-
Notifications
You must be signed in to change notification settings - Fork 7
/
psicash.cpp
1460 lines (1221 loc) · 51.6 KB
/
psicash.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (c) 2018, Psiphon Inc.
* All rights reserved.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include <map>
#include <iostream>
#include <sstream>
#include <chrono>
#include <thread>
#include <algorithm>
#include "psicash.hpp"
#include "userdata.hpp"
#include "datetime.hpp"
#include "error.hpp"
#include "url.hpp"
#include "base64.hpp"
#include "utils.hpp"
#include "http_status_codes.h"
#include "vendor/nlohmann/json.hpp"
using json = nlohmann::json;
using namespace std;
using namespace nonstd;
using namespace psicash;
using namespace error;
namespace psicash {
const char* const kTransactionIDZero = "";
namespace prod {
static constexpr const char* kAPIServerScheme = "https";
static constexpr const char* kAPIServerHostname = "api.psi.cash";
static constexpr int kAPIServerPort = 443;
}
namespace dev {
#define LOCAL_TEST 0
#if LOCAL_TEST
static constexpr const char* kAPIServerScheme = "http";
static constexpr const char* kAPIServerHostname = "localhost";
static constexpr int kAPIServerPort = 51337;
#else
static constexpr const char* kAPIServerScheme = "https";
static constexpr const char* kAPIServerHostname = "api.dev.psi.cash";
static constexpr int kAPIServerPort = 443;
#endif
}
static constexpr const char* kAPIServerVersion = "v1";
static constexpr const char* kLandingPageParamKey = "psicash";
static constexpr const char* kMethodGET = "GET";
static constexpr const char* kMethodPOST = "POST";
//
// PsiCash class implementation
//
// Definitions of static member variables
constexpr int HTTPResult::CRITICAL_ERROR;
constexpr int HTTPResult::RECOVERABLE_ERROR;
PsiCash::PsiCash()
: test_(false),
initialized_(false),
server_port_(0),
user_data_(std::make_unique<UserData>()),
make_http_request_fn_(nullptr) {
}
PsiCash::~PsiCash() {
}
Error PsiCash::Init(const string& user_agent, const string& file_store_root,
MakeHTTPRequestFn make_http_request_fn, bool force_reset,
bool test) {
test_ = test;
if (test) {
server_scheme_ = dev::kAPIServerScheme;
server_hostname_ = dev::kAPIServerHostname;
server_port_ = dev::kAPIServerPort;
} else {
server_scheme_ = prod::kAPIServerScheme;
server_hostname_ = prod::kAPIServerHostname;
server_port_ = prod::kAPIServerPort;
}
if (user_agent.empty()) {
return MakeCriticalError("user_agent is required");
}
user_agent_ = user_agent;
if (file_store_root.empty()) {
return MakeCriticalError("file_store_root is required");
}
if (force_reset) {
user_data_->Clear(file_store_root, test);
}
// May still be null.
make_http_request_fn_ = std::move(make_http_request_fn);
if (auto err = user_data_->Init(file_store_root, test)) {
return PassError(err);
}
initialized_ = true;
return error::nullerr;
}
#define MUST_BE_INITIALIZED if (!Initialized()) { return MakeCriticalError("PsiCash is uninitialized"); }
bool PsiCash::Initialized() const {
return initialized_;
}
Error PsiCash::ResetUser() {
return PassError(user_data_->DeleteUserData(/*is_logged_out_account=*/false));
}
Error PsiCash::MigrateTrackerTokens(const map<string, string>& tokens) {
MUST_BE_INITIALIZED;
AuthTokens auth_tokens;
for (const auto& it : tokens) {
auth_tokens[it.first].id = it.second;
// leave expiry null
}
UserData::Transaction transaction(*user_data_);
// Ignoring return values while writing is paused.
// Blow away any user state, as the newly migrated tokens are overwriting it.
(void)ResetUser();
(void)user_data_->SetAuthTokens(auth_tokens, /*is_account=*/false, /*account_username=*/"");
if (auto err = transaction.Commit()) {
return WrapError(err, "user data write failed");
}
return nullerr;
}
void PsiCash::SetHTTPRequestFn(MakeHTTPRequestFn make_http_request_fn) {
make_http_request_fn_ = std::move(make_http_request_fn);
}
Error PsiCash::SetRequestMetadataItems(const std::map<std::string, std::string>& items) {
MUST_BE_INITIALIZED;
UserData::Transaction transaction(*user_data_);
for (const auto& it : items) {
// Errors won't manifest until we commit
(void)user_data_->SetRequestMetadataItem(it.first, it.second);
}
if (auto err = transaction.Commit()) {
return WrapError(err, "user data write failed");
}
return nullerr;
}
Error PsiCash::SetLocale(const string& locale) {
MUST_BE_INITIALIZED;
return PassError(user_data_->SetLocale(locale));
}
//
// Stored info accessors
//
bool PsiCash::HasTokens() const {
MUST_BE_INITIALIZED;
// Trackers and Accounts both require the same token types (for now).
// (Accounts will also have the "logout" type, but it isn't strictly needed for sane operation.)
vector<string> required_token_types = {kEarnerTokenType, kSpenderTokenType, kIndicatorTokenType};
auto auth_tokens = user_data_->GetAuthTokens();
for (const auto& it : auth_tokens) {
auto found = std::find(required_token_types.begin(), required_token_types.end(), it.first);
if (found != required_token_types.end()) {
required_token_types.erase(found);
}
}
return required_token_types.empty();
}
/// If the user has no tokens, most actions are disallowed. (This can include being in
/// the is-logged-out-account state.)
#define TOKENS_REQUIRED if (!HasTokens()) { return MakeCriticalError("user has insufficient tokens"); }
bool PsiCash::IsAccount() const {
if (user_data_->GetIsLoggedOutAccount()) {
return true;
}
return user_data_->GetIsAccount();
}
nonstd::optional<std::string> PsiCash::AccountUsername() const {
if (user_data_->GetIsLoggedOutAccount() || !user_data_->GetIsAccount()) {
return nullopt;
}
return user_data_->GetAccountUsername();
}
int64_t PsiCash::Balance() const {
return user_data_->GetBalance();
}
PurchasePrices PsiCash::GetPurchasePrices() const {
return user_data_->GetPurchasePrices();
}
Purchases PsiCash::GetPurchases() const {
return user_data_->GetPurchases();
}
static bool IsExpired(const Purchase& p) {
// Note that "expired" is decided using local time.
auto local_now = datetime::DateTime::Now();
return (p.local_time_expiry && *p.local_time_expiry < local_now);
}
Purchases PsiCash::ActivePurchases() const {
Purchases res;
for (const auto& p : user_data_->GetPurchases()) {
if (!IsExpired(p)) {
res.push_back(p);
}
}
return res;
}
Authorizations PsiCash::GetAuthorizations(bool activeOnly/*=false*/) const {
Authorizations res;
for (const auto& p : user_data_->GetPurchases()) {
if (p.authorization && (!activeOnly || !IsExpired(p))) {
res.push_back(*p.authorization);
}
}
return res;
}
Purchases PsiCash::GetPurchasesByAuthorizationID(std::vector<std::string> authorization_ids) const {
auto purchases = user_data_->GetPurchases();
auto new_end = std::remove_if(purchases.begin(), purchases.end(), [&authorization_ids](const Purchase& p){
return !p.authorization
|| std::find(authorization_ids.begin(), authorization_ids.end(), p.authorization->id) == authorization_ids.end();
});
purchases.erase(new_end, purchases.end());
return purchases;
}
optional<Purchase> PsiCash::NextExpiringPurchase() const {
optional<Purchase> next;
for (const auto& p : user_data_->GetPurchases()) {
// We're using server time, since we're not comparing to local now (because we're
// not checking to see if the purchase is expired -- just which expires next).
if (!p.server_time_expiry) {
continue;
}
if (!next) {
// We haven't yet set a next.
next = p;
continue;
}
if (p.server_time_expiry < next->server_time_expiry) {
next = p;
}
}
return next;
}
Result<Purchases> PsiCash::ExpirePurchases() {
auto all_purchases = GetPurchases();
Purchases expired_purchases, valid_purchases;
for (const auto& p : all_purchases) {
if (IsExpired(p)) {
expired_purchases.push_back(p);
} else {
valid_purchases.push_back(p);
}
}
auto err = user_data_->SetPurchases(valid_purchases);
if (err) {
return WrapError(err, "SetPurchases failed");
}
return expired_purchases;
}
error::Result<Purchases> PsiCash::RemovePurchases(const vector<TransactionID>& ids) {
auto all_purchases = GetPurchases();
Purchases remaining_purchases, removed_purchases;
for (const auto& p : all_purchases) {
bool match = false;
for (const auto& id : ids) {
if (p.id == id) {
match = true;
break;
}
}
if (match) {
removed_purchases.push_back(p);
}
else {
remaining_purchases.push_back(p);
}
}
auto err = user_data_->SetPurchases(remaining_purchases);
if (err) {
return WrapError(err, "SetPurchases failed");
}
return removed_purchases;
}
/// Adds a params package to the URL which includes the user's earner token (if there is one).
/// @param query_param_only If true, the params will only be added to the query parameters
/// part of the URL, rather than first attempting to add it to the hash/fragment.
Result<string> PsiCash::AddEarnerTokenToURL(const string& url_string, bool query_param_only) const {
URL url;
auto err = url.Parse(url_string);
if (err) {
return WrapError(err, "url.Parse failed");
}
auto url_package_res = GetUserMetadataURLPackage({kEarnerTokenType}, false);
if (!url_package_res) {
return WrapError(url_package_res.error(), "GetUserMetadataURLPackage failed");
}
// Our preference is to put the our data into the URL's fragment/hash/anchor,
// because we'd prefer the data not be sent to the server nor included in the referrer
// header to third-party page resources.
// But if there already is a fragment value then we'll put our data into the query parameters.
// (Because altering the fragment is more likely to have negative consequences
// for the page than adding a query parameter that will be ignored.)
if (!query_param_only && url.fragment_.empty()) {
// When setting in the fragment, we use "#!psicash=etc". The ! prevents the
// fragment from accidentally functioning as a jump-to anchor on a landing page
// (where we don't control element IDs, etc.).
url.fragment_ = "!"s + kLandingPageParamKey + "=" + *url_package_res;
} else {
if (!url.query_.empty()) {
url.query_ += "&";
}
url.query_ += kLandingPageParamKey + "="s + *url_package_res;
}
return url.ToString();
}
Result<string> PsiCash::ModifyLandingPage(const string& url_string) const {
// All of our landing pages are arrived at via the redirector service we run. We want
// to send our token package to the redirector, so that it can decide if and how to
// include it in the final site URL. So we have to send it via a query parameter.
return AddEarnerTokenToURL(url_string, true);
}
Result<string> PsiCash::GetBuyPsiURL() const {
TOKENS_REQUIRED;
return AddEarnerTokenToURL(test_ ? "https://dev-psicash.myshopify.com/" : "https://buy.psi.cash/", false);
}
std::string PsiCash::GetUserSiteURL(UserSiteURLType url_type, bool webview) const {
URL url;
url.scheme_host_path_ = test_ ? "https://dev-my.psi.cash" : "https://my.psi.cash";
switch (url_type) {
case UserSiteURLType::AccountSignup:
url.scheme_host_path_ += "/signup";
break;
case UserSiteURLType::ForgotAccount:
url.scheme_host_path_ += "/forgot";
break;
case UserSiteURLType::AccountManagement:
default:
// Just the root domain
break;
}
url.query_ = "utm_source=" + URL::Encode(user_agent_, false);
url.query_ += "&locale=" + URL::Encode(user_data_->GetLocale(), false);
if (!user_data_->GetAccountUsername().empty()) {
auto encoded_username = URL::Encode(user_data_->GetAccountUsername(), false);
// IE has a URL limit of 2083 characters, so if the username is too long (or encodes
// to too long), then we're going to omit this parameter). It is better to omit the
// username than to pre-fill an incorrect username or have broken UTF-8 characters.
if (encoded_username.length() < 2000) {
url.query_ += "&username=" + encoded_username;
}
}
if (webview) {
url.query_ += "&webview=true";
}
auto metadata_package_res = GetUserMetadataURLPackage({}, false);
if (metadata_package_res) {
url.fragment_ = "!psicash=" + *metadata_package_res;
}
return url.ToString();
}
/// Creates the metadata+tokens package should be added to URLs where, for example,
/// earning is desired (landing pages) or user info should be passed onto the server
/// even if there is no earning (user management site).
Result<string> PsiCash::GetUserMetadataURLPackage(
const vector<string>& token_types, bool error_if_token_missing) const {
json psicash_data;
psicash_data["v"] = 1;
if (test_) {
psicash_data["dev"] = 1;
psicash_data["debug"] = 1;
}
psicash_data["timestamp"] = datetime::DateTime::Now().ToISO8601();
// Get the metadata (sponsor ID, etc.)
psicash_data["metadata"] = GetRequestMetadata(0);
// Get tokens to include, if indicated
if (!token_types.empty()) {
auto auth_tokens = user_data_->GetAuthTokens();
for (const auto& tt : token_types) {
if (auth_tokens.count(tt) == 0 && error_if_token_missing) {
// Missing token for this type
return MakeCriticalError(utils::Stringer("token type missing: ", tt));
}
}
auto tokens_string = CommaDelimitTokens(token_types);
if (tokens_string.empty()) {
psicash_data["tokens"] = nullptr;
} else {
psicash_data["tokens"] = tokens_string;
}
}
string json_data;
try {
json_data = psicash_data.dump(-1, ' ', // disable indent
true); // ensure ASCII
}
catch (json::exception& e) {
return MakeCriticalError(
utils::Stringer("json dump failed: ", e.what(), "; id:", e.id));
}
// Base64-encode the JSON
auto encoded_json = URL::Encode(base64::TrimPadding(base64::B64Encode(json_data)), false);
return encoded_json;
}
Result<string> PsiCash::GetRewardedActivityData() const {
TOKENS_REQUIRED;
return GetUserMetadataURLPackage({kEarnerTokenType}, true);
}
json PsiCash::GetDiagnosticInfo(bool lite) const {
// NOTE: Do not put personal identifiers in this package.
// TODO: This is still enough info to uniquely identify the user (combined with the
// PsiCash DB). So maybe avoiding direct PII does not achieve anything, and we should
// instead either include less data or make sure our retention of this data is
// aggregated and/or short.
json j = json::object();
j["test"] = test_;
j["hasInstanceID"] = user_data_->HasInstanceID();
j["isLoggedOutAccount"] = user_data_->GetIsLoggedOutAccount();
j["validTokenTypes"] = user_data_->ValidTokenTypes();
j["isAccount"] = IsAccount();
j["balance"] = Balance();
j["serverTimeDiff"] = user_data_->GetServerTimeDiff().count(); // in milliseconds
// Include a sanitized version of the purchases
j["purchases"] = json::array();
for (const auto& p : GetPurchases()) {
j["purchases"].push_back({{"class", p.transaction_class},
{"distinguisher", p.distinguisher}});
}
// The purchase prices are about 800 bytes of the 1000 bytes in a typical diangnostic
// dump, and they're generally not useful.
if (!lite) {
j["purchasePrices"] = GetPurchasePrices();
}
return j;
}
//
// API Server Requests
//
// Simple helper to determine if a given HTTP response code should be considered a "server error".
inline bool IsServerError(int code) {
return code >= 500 && code <= 599;
}
// Creates the metadata JSON that should be included with requests.
// This method MUST be called rather than calling UserData::GetRequestMetadata directly.
// If `attempt` is 0 it will be omitted from the metadata object.
json PsiCash::GetRequestMetadata(int attempt) const {
auto req_metadata = user_data_->GetRequestMetadata();
// UserData stores only the explicitly set metadata. We have more fields to add at this level.
req_metadata["v"] = 1;
req_metadata["user_agent"] = user_agent_;
if (attempt > 0) {
req_metadata["attempt"] = attempt;
}
return req_metadata;
}
// Makes an HTTP request (with possible retries).
// HTTPResult.error will always be empty on a non-error return.
Result<HTTPResult> PsiCash::MakeHTTPRequestWithRetry(
const std::string& method, const std::string& path, bool include_auth_tokens,
const std::vector<std::pair<std::string, std::string>>& query_params,
const optional<json>& body)
{
MUST_BE_INITIALIZED;
if (!make_http_request_fn_) {
throw std::runtime_error("make_http_request_fn_ must be set before requests are attempted");
}
string body_string;
if (body) {
try {
body_string = body->dump(-1, ' ', true);
}
catch (json::exception& e) {
return MakeCriticalError(
utils::Stringer("body json dump failed: ", e.what(), "; id:", e.id));
}
}
const int max_attempts = 3;
HTTPResult http_result;
for (int i = 0; i < max_attempts; i++) {
if (i > 0) {
// Not the first attempt; wait before retrying
this_thread::sleep_for(chrono::seconds(i));
}
auto req_params = BuildRequestParams(
method, path, include_auth_tokens, query_params, i + 1, {}, body_string);
if (!req_params) {
return WrapError(req_params.error(), "BuildRequestParams failed");
}
http_result = make_http_request_fn_(*req_params);
// Error state sanity check
if (http_result.code < 0 && http_result.error.empty()) {
return MakeCriticalError("HTTP result code is negative but no error message provided");
}
// We just got a fresh server timestamp (Date header), so set the server time diff
auto date_header = utils::FindHeaderValue(http_result.headers, "Date");
if (!date_header.empty()) {
datetime::DateTime server_datetime;
if (server_datetime.FromRFC7231(date_header)) {
// We don't care about the return value at this point.
(void)user_data_->SetServerTimeDiff(server_datetime);
}
// else: we're not going to raise the error
}
// Store/update any cookies we received, to send in the next request.
// We're not going to cause a general error if the cookies fail to save but
// everything else is successful.
(void)user_data_->SetCookies(utils::GetCookies(http_result.headers));
if (http_result.code < 0) {
// Something happened that prevented the request from nominally succeeding.
// If the native code indicates that this is a "recoverable error" (such as
// the network interruption error we see on iOS sometimes), then we will retry.
if (http_result.code == HTTPResult::RECOVERABLE_ERROR) {
continue;
}
// Unrecoverable error; don't retry.
return MakeCriticalError("Request resulted in critical error: "s + http_result.error);
}
if (IsServerError(http_result.code)) {
// Server error; retry
continue;
}
// We got a response of less than 500. We'll consider that success at this point.
return http_result;
}
// We exceeded our retry limit.
if (http_result.code < 0) {
// A critical error would have returned above, so this is a non-critical error
return MakeNoncriticalError("Request resulted in noncritical error: "s + http_result.error);
}
// Return the last result (which is a 5xx server error)
return http_result;
}
// Build the request parameters JSON appropriate for passing to make_http_request_fn_.
Result<HTTPParams> PsiCash::BuildRequestParams(
const std::string& method, const std::string& path, bool include_auth_tokens,
const std::vector<std::pair<std::string, std::string>>& query_params, int attempt,
const std::map<std::string, std::string>& additional_headers,
const std::string& body) const {
HTTPParams params;
params.scheme = server_scheme_;
params.hostname = server_hostname_;
params.port = server_port_;
params.method = method;
params.path = "/"s + kAPIServerVersion + path;
params.query = query_params;
params.headers = additional_headers;
params.headers["Accept"] = "application/json";
params.headers["User-Agent"] = user_agent_;
params.headers["Cookie"] = user_data_->GetCookies();
if (include_auth_tokens) {
params.headers["X-PsiCash-Auth"] = CommaDelimitTokens({});
}
auto metadata = GetRequestMetadata(attempt);
try {
params.headers["X-PsiCash-Metadata"] = metadata.dump(-1, ' ', true);
}
catch (json::exception& e) {
return MakeCriticalError(
utils::Stringer("metadata json dump failed: ", e.what(), "; id:", e.id));
}
params.body = body;
if (!body.empty()) {
params.headers["Content-Type"] = "application/json; charset=utf-8";
}
return params;
}
/// Returns our auth tokens in comma-delimited format. If types is `{}`, all tokens will
/// be included; otherwise only tokens of the types specified will be included.
std::string PsiCash::CommaDelimitTokens(const std::vector<std::string>& types) const {
vector<string> tokens;
for (const auto& at : user_data_->GetAuthTokens()) {
if (types.empty() || std::find(types.begin(), types.end(), at.first) != types.end()) {
tokens.push_back(at.second.id);
}
}
return utils::Join(tokens, ",");
}
// Get new tracker tokens from the server. This effectively gives us a new identity.
Result<Status> PsiCash::NewTracker() {
MUST_BE_INITIALIZED;
auto result = MakeHTTPRequestWithRetry(
kMethodPOST,
"/tracker",
false,
{{"instanceID", user_data_->GetInstanceID()}},
nullopt // body
);
if (!result) {
return WrapError(result.error(), "MakeHTTPRequestWithRetry failed");
}
if (result->code == kHTTPStatusOK) {
if (result->body.empty()) {
return MakeCriticalError(
utils::Stringer("result has no body; code: ", result->code));
}
AuthTokens auth_tokens;
try {
auto j = json::parse(result->body);
auth_tokens = j.get<AuthTokens>();
}
catch (json::exception& e) {
return MakeCriticalError(
utils::Stringer("json parse failed: ", e.what(), "; id:", e.id));
}
// Sanity check
if (auth_tokens.size() < 3) {
return MakeCriticalError(
utils::Stringer("bad number of tokens received: ", auth_tokens.size()));
}
// Set our new data in a single write.
UserData::Transaction transaction(*user_data_);
(void)user_data_->SetIsLoggedOutAccount(false);
(void)user_data_->SetAuthTokens(auth_tokens, /*is_account=*/false, /*account_username=*/"");
(void)user_data_->SetBalance(0);
if (auto err = transaction.Commit()) {
return WrapError(err, "user data write failed");
}
return Status::Success;
} else if (IsServerError(result->code)) {
return Status::ServerError;
}
return MakeCriticalError(utils::Stringer(
"request returned unexpected result code: ", result->code, "; ",
result->body, "; ", json(result->headers).dump()));
}
Result<PsiCash::RefreshStateResponse> PsiCash::RefreshState(bool local_only, const std::vector<std::string>& purchase_classes) {
if (local_only) {
// Our "local only" refresh involves checking tokens for expiry and potentially
// shifting into a logged-out state.
// This call is offline, but we might be currently connected, so the reconnect_required
// considerations still apply.
bool reconnect_required = false;
auto local_now = datetime::DateTime::Now();
for (const auto& it : user_data_->GetAuthTokens()) {
if (it.second.server_time_expiry
&& user_data_->ServerTimeToLocal(*it.second.server_time_expiry) < local_now) {
// If any tokens are expired, we consider ourselves to not have a proper set
// If we're transitioning to a logged out state and there are active
// authorizations (applied to the current tunnel), then we need to
// reconnect to remove them.
// TODO: this line/logic is duplicated below; consider a helper to encapsulate
reconnect_required = !GetAuthorizations(true).empty();
if (auto err = user_data_->DeleteUserData(IsAccount())) {
return WrapError(err, "DeleteUserData failed");
}
break;
}
}
return PsiCash::RefreshStateResponse{ Status::Success, reconnect_required };
}
return RefreshState(purchase_classes, true);
}
// RefreshState helper that makes recursive calls (to allow for NewTracker and then
// RefreshState requests).
Result<PsiCash::RefreshStateResponse> PsiCash::RefreshState(
const std::vector<std::string>& purchase_classes, bool allow_recursion) {
/*
Logic flow overview:
1. If there are no tokens:
a. If isAccount then return. The user needs to log in immediately.
b. If !isAccount then call NewTracker to get new tracker tokens.
2. Make the RefreshClientState request.
3. If isAccount then return. (Even if there are no valid tokens.)
4. If there are valid (tracker) tokens then return.
5. If there are no valid tokens call NewTracker. Call RefreshClientState again.
6. If there are still no valid tokens, then things are horribly wrong. Return error.
*/
MUST_BE_INITIALIZED;
auto auth_tokens = user_data_->GetAuthTokens();
if (auth_tokens.empty()) {
// No tokens.
if (IsAccount()) {
// This is a logged-in or logged-out account. We can't just get a new tracker.
// The app will have to force a login for the user to do anything.
return PsiCash::RefreshStateResponse{ Status::Success, false };
}
if (!allow_recursion) {
// We have already recursed and can't do it again. This is an error condition.
// This is impossible-ish. It requires us to start out with no tokens, make a NewTracker
// call that appears to succeed, but then _still_ have no tokens.
return MakeCriticalError("failed to obtain valid tracker tokens (a)");
}
// Get new tracker tokens. (Which is effectively getting a new identity.)
auto new_tracker_result = NewTracker();
if (!new_tracker_result) {
return WrapError(new_tracker_result.error(), "NewTracker failed");
}
if (*new_tracker_result != Status::Success) {
return PsiCash::RefreshStateResponse{ *new_tracker_result, false };
}
// Note: NewTracker calls SetAuthTokens and SetBalance.
// Recursive RefreshState call now that we have tokens.
return RefreshState(purchase_classes, false);
}
// We have tokens. Make the RefreshClientState request.
vector<pair<string, string>> query_items;
for (const auto& purchase_class : purchase_classes) {
query_items.emplace_back("class", purchase_class);
}
// If LastTransactionID is empty, we'll get all transactions.
query_items.emplace_back("lastTransactionID", user_data_->GetLastTransactionID());
auto result = MakeHTTPRequestWithRetry(
kMethodGET,
"/refresh-state",
true,
query_items,
nullopt // body
);
if (!result) {
return WrapError(result.error(), "MakeHTTPRequestWithRetry failed");
}
if (result->code == kHTTPStatusOK) {
if (result->body.empty()) {
return MakeCriticalError(
utils::Stringer("result has no body; code: ", result->code));
}
bool reconnect_required = false;
try {
// We're going to be setting a bunch of UserData values, so let's wait until we're done
// to write them all to disk.
UserData::Transaction transaction(*user_data_);
auto j = json::parse(result->body);
auto valid_token_types = j["TokensValid"].get<map<string, bool>>();
(void)user_data_->CullAuthTokens(valid_token_types);
// If any of our tokens were valid, then the IsAccount value from the
// server is authoritative. Otherwise we'll respect our existing value.
bool any_valid_token = false;
for (const auto& vtt : valid_token_types) {
if (vtt.second) {
any_valid_token = true;
break;
}
}
if (any_valid_token && j["IsAccount"].is_boolean()) {
// If we have moved from being an account to not being an account,
// something is very wrong.
auto prev_is_account = IsAccount();
auto is_account = j["IsAccount"].get<bool>();
if (prev_is_account && !is_account) {
return MakeCriticalError("invalid is-account state");
}
(void)user_data_->SetIsAccount(is_account);
}
if (j["AccountUsername"].is_string()) {
(void)user_data_->SetAccountUsername(j["AccountUsername"].get<string>());
}
if (j["Balance"].is_number_integer()) {
(void)user_data_->SetBalance(j["Balance"].get<int64_t>());
}
// We only try to use the PurchasePrices if we supplied purchase classes to the request
if (!purchase_classes.empty() && j["PurchasePrices"].is_array()) {
PurchasePrices purchase_prices;
// The from_json for the PurchasePrice struct is for our internal (datastore and library API)
// representation of PurchasePrice. We won't assume that the representation used by the
// server is the same (nor that it won't change independent of our representation).
for (const auto& pp : j["PurchasePrices"]) {
auto transaction_class = pp["Class"].get<string>();
purchase_prices.push_back(PurchasePrice{
transaction_class,
pp["Distinguisher"].get<string>(),
pp["Price"].get<int64_t>()
});
}
(void)user_data_->SetPurchasePrices(purchase_prices);
}
if (j["Purchases"].is_array()) {
for (const auto& p : j["Purchases"]) {
auto purchase_res = PurchaseFromJSON(p);
if (!purchase_res) {
return WrapError(purchase_res.error(), "failed to deserialize purchases");
}
// Authorizations are applied to tunnel connections, which requires a reconnect
reconnect_required = reconnect_required || purchase_res->authorization;
(void)user_data_->AddPurchase(*purchase_res);
}
}
// If the account tokens just expired, then we need to go into a logged-out state.
if (IsAccount() && !HasTokens()) {
// If we're transitioning to a logged out state and there are active
// authorizations (applied to the current tunnel), then we need to
// reconnect to remove them.
reconnect_required = reconnect_required || !GetAuthorizations(true).empty();
(void)user_data_->DeleteUserData(true);
}
if (auto err = transaction.Commit()) {
return WrapError(err, "UserData write failed");
}
}
catch (json::exception& e) {
return MakeCriticalError(
utils::Stringer("json parse failed: ", e.what(), "; id:", e.id));
}
if (IsAccount()) {
// For accounts there's nothing else we can do, regardless of the state of token validity.
return PsiCash::RefreshStateResponse{ Status::Success, reconnect_required };
}
if (HasTokens()) {
// We have a good tracker state.
return PsiCash::RefreshStateResponse{ Status::Success, reconnect_required };
}
// We started out with tracker tokens, but they're all invalid.
// Note that this shouldn't happen -- we "know" that Tracker tokens don't
// expire -- but we'll still try to recover if we haven't already recursed.
if (!allow_recursion) {
return MakeCriticalError("failed to obtain valid tracker tokens (b)");
}
return RefreshState(purchase_classes, true);
}
else if (result->code == kHTTPStatusUnauthorized) {
// This can only happen if the tokens we sent didn't all belong to same user.
// This really should never happen. We're not checking the return value, as there
// isn't a sane response to a failure at this point.
(void)user_data_->Clear();
return PsiCash::RefreshStateResponse{ Status::InvalidTokens, false };
}
else if (IsServerError(result->code)) {
return PsiCash::RefreshStateResponse{ Status::ServerError, false };
}
return MakeCriticalError(utils::Stringer(
"request returned unexpected result code: ", result->code, "; ",
result->body, "; ", json(result->headers).dump()));
}
Result<PsiCash::NewExpiringPurchaseResponse> PsiCash::NewExpiringPurchase(
const string& transaction_class,
const string& distinguisher,
const int64_t expected_price) {
TOKENS_REQUIRED;