Repository navigation
Expand file tree
/
Copy pathauthforge_sdk.cpp
More file actions
2931 lines (2747 loc) · 93 KB
/
Copy pathauthforge_sdk.cpp
File metadata and controls
2931 lines (2747 loc) · 93 KB
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
#include "authforge_sdk.h"
#include <algorithm>
#include <array>
#include <cctype>
#include <cerrno>
#include <chrono>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <ctime>
#include <iomanip>
#include <iostream>
#include <sstream>
#include <stdexcept>
#include <thread>
#include <utility>
#include <curl/curl.h>
#include <openssl/crypto.h>
#include <openssl/sha.h>
#include <sodium.h>
#ifdef _WIN32
#include <iphlpapi.h>
#include <intrin.h>
#include <winsock2.h>
#include <windows.h>
#pragma comment(lib, "iphlpapi.lib")
#pragma comment(lib, "ws2_32.lib")
#pragma comment(lib, "advapi32.lib")
#endif
#if defined(__linux__) || defined(__APPLE__)
#include <ifaddrs.h>
#include <net/if.h>
#include <sys/types.h>
#endif
#if defined(__linux__)
#include <filesystem>
#include <fstream>
#endif
#if defined(__APPLE__)
#include <net/if_dl.h>
#include <sys/sysctl.h>
#endif
#if defined(__linux__) || defined(__APPLE__)
#include <fcntl.h>
#include <poll.h>
#include <signal.h>
#include <spawn.h>
#include <sys/wait.h>
#include <unistd.h>
extern char **environ;
#endif
#ifdef _WIN32
#ifndef RRF_SUBKEY_WOW6464KEY
#define RRF_SUBKEY_WOW6464KEY 0x00010000
#endif
#endif
namespace authforge {
namespace {
std::string JoinAndCompactWhitespace(const std::string &input) {
std::string out;
out.reserve(input.size());
bool inSpace = false;
for (unsigned char ch : input) {
if (std::isspace(ch) != 0) {
inSpace = true;
continue;
}
if (inSpace && !out.empty()) {
out.push_back(' ');
}
inSpace = false;
out.push_back(static_cast<char>(ch));
}
return out;
}
bool StartsWithNoCase(const std::string &value, const std::string &lowerPrefix) {
if (value.size() < lowerPrefix.size()) {
return false;
}
for (std::size_t i = 0; i < lowerPrefix.size(); ++i) {
if (std::tolower(static_cast<unsigned char>(value[i])) != lowerPrefix[i]) {
return false;
}
}
return true;
}
// An http:// URL (any case) to this machine: host 127.0.0.1, [::1] or
// localhost, with or without a port. User info is refused, so that no URL
// parser can read another host out of it.
bool IsLoopbackHttpUrl(const std::string &url) {
const std::string scheme = "http://";
if (!StartsWithNoCase(url, scheme)) {
return false;
}
const std::size_t authorityEnd = url.find_first_of("/?#", scheme.size());
const std::string authority = url.substr(
scheme.size(), authorityEnd == std::string::npos ? std::string::npos : authorityEnd - scheme.size());
if (authority.find('@') != std::string::npos) {
return false;
}
std::string host;
if (!authority.empty() && authority.front() == '[') {
const std::size_t close = authority.find(']');
if (close == std::string::npos || (close + 1 < authority.size() && authority[close + 1] != ':')) {
return false;
}
host = authority.substr(1, close - 1);
} else {
host = authority.substr(0, authority.find(':'));
}
for (char &ch : host) {
ch = static_cast<char>(std::tolower(static_cast<unsigned char>(ch)));
}
return host == "127.0.0.1" || host == "::1" || host == "localhost";
}
std::optional<std::string> ExtractTopLevelObject(const std::string &json, const std::string &key) {
const std::string needle = "\"" + key + "\"";
const std::size_t keyPos = json.find(needle);
if (keyPos == std::string::npos) {
return std::nullopt;
}
std::size_t pos = json.find(':', keyPos + needle.size());
if (pos == std::string::npos) {
return std::nullopt;
}
++pos;
while (pos < json.size() && std::isspace(static_cast<unsigned char>(json[pos])) != 0) {
++pos;
}
if (pos >= json.size() || json[pos] != '{') {
return std::nullopt;
}
std::size_t end = pos;
int depth = 0;
bool inString = false;
bool escaping = false;
for (; end < json.size(); ++end) {
const char c = json[end];
if (inString) {
if (escaping) {
escaping = false;
} else if (c == '\\') {
escaping = true;
} else if (c == '"') {
inString = false;
}
continue;
}
if (c == '"') {
inString = true;
continue;
}
if (c == '{') {
++depth;
continue;
}
if (c == '}') {
--depth;
if (depth == 0) {
return json.substr(pos, (end - pos) + 1);
}
}
}
return std::nullopt;
}
bool IsJsonWhitespace(char c) {
return c == ' ' || c == '\t' || c == '\n' || c == '\r';
}
void SkipJsonWhitespace(const std::string &json, std::size_t &pos) {
while (pos < json.size() && IsJsonWhitespace(json[pos])) {
++pos;
}
}
bool ReadJsonHex4(const std::string &json, std::size_t pos, unsigned int &out) {
if (pos > json.size() || json.size() - pos < 4) {
return false;
}
unsigned int value = 0;
for (std::size_t i = 0; i < 4; ++i) {
const char c = json[pos + i];
value <<= 4;
if (c >= '0' && c <= '9') {
value |= static_cast<unsigned int>(c - '0');
} else if (c >= 'a' && c <= 'f') {
value |= static_cast<unsigned int>(c - 'a' + 10);
} else if (c >= 'A' && c <= 'F') {
value |= static_cast<unsigned int>(c - 'A' + 10);
} else {
return false;
}
}
out = value;
return true;
}
void AppendUtf8(std::string &out, unsigned int codepoint) {
if (codepoint < 0x80) {
out.push_back(static_cast<char>(codepoint));
} else if (codepoint < 0x800) {
out.push_back(static_cast<char>(0xC0 | (codepoint >> 6)));
out.push_back(static_cast<char>(0x80 | (codepoint & 0x3F)));
} else if (codepoint < 0x10000) {
out.push_back(static_cast<char>(0xE0 | (codepoint >> 12)));
out.push_back(static_cast<char>(0x80 | ((codepoint >> 6) & 0x3F)));
out.push_back(static_cast<char>(0x80 | (codepoint & 0x3F)));
} else {
out.push_back(static_cast<char>(0xF0 | (codepoint >> 18)));
out.push_back(static_cast<char>(0x80 | ((codepoint >> 12) & 0x3F)));
out.push_back(static_cast<char>(0x80 | ((codepoint >> 6) & 0x3F)));
out.push_back(static_cast<char>(0x80 | (codepoint & 0x3F)));
}
}
// Reads the JSON string whose opening quote is at json[pos] and leaves pos
// after the closing quote. Escapes are decoded to UTF-8 so the result can be
// compared byte for byte with a value this client sent. A surrogate that is
// not part of a pair is rejected: it has no UTF-8 form.
bool ReadJsonString(const std::string &json, std::size_t &pos, std::string &out) {
out.clear();
if (pos >= json.size() || json[pos] != '"') {
return false;
}
++pos;
while (pos < json.size()) {
const char c = json[pos++];
if (c == '"') {
return true;
}
if (c != '\\') {
out.push_back(c);
continue;
}
if (pos >= json.size()) {
return false;
}
const char esc = json[pos++];
switch (esc) {
case '"':
out.push_back('"');
break;
case '\\':
out.push_back('\\');
break;
case '/':
out.push_back('/');
break;
case 'b':
out.push_back('\b');
break;
case 'f':
out.push_back('\f');
break;
case 'n':
out.push_back('\n');
break;
case 'r':
out.push_back('\r');
break;
case 't':
out.push_back('\t');
break;
case 'u': {
unsigned int codepoint = 0;
if (!ReadJsonHex4(json, pos, codepoint)) {
return false;
}
pos += 4;
if (codepoint >= 0xD800 && codepoint <= 0xDBFF) {
unsigned int low = 0;
if (json.compare(pos, 2, "\\u") != 0 || !ReadJsonHex4(json, pos + 2, low) || low < 0xDC00 || low > 0xDFFF) {
return false;
}
pos += 6;
codepoint = 0x10000 + ((codepoint - 0xD800) << 10) + (low - 0xDC00);
} else if (codepoint >= 0xDC00 && codepoint <= 0xDFFF) {
return false;
}
AppendUtf8(out, codepoint);
break;
}
default:
return false;
}
}
return false;
}
// Steps over the JSON string whose opening quote is at json[pos] without
// decoding it.
bool SkipJsonString(const std::string &json, std::size_t &pos) {
if (pos >= json.size() || json[pos] != '"') {
return false;
}
++pos;
while (pos < json.size()) {
const char c = json[pos++];
if (c == '"') {
return true;
}
if (c == '\\') {
if (pos >= json.size()) {
return false;
}
++pos;
}
}
return false;
}
// Steps over one JSON value of any type starting at json[pos].
bool SkipJsonValue(const std::string &json, std::size_t &pos) {
if (pos >= json.size()) {
return false;
}
if (json[pos] == '"') {
return SkipJsonString(json, pos);
}
if (json[pos] == '{' || json[pos] == '[') {
std::size_t depth = 0;
while (pos < json.size()) {
const char c = json[pos];
if (c == '"') {
if (!SkipJsonString(json, pos)) {
return false;
}
continue;
}
++pos;
if (c == '{' || c == '[') {
++depth;
} else if (c == '}' || c == ']') {
--depth;
if (depth == 0) {
return true;
}
}
}
return false;
}
const std::size_t start = pos;
while (pos < json.size() && json[pos] != ',' && json[pos] != '}' && json[pos] != ']' &&
!IsJsonWhitespace(json[pos])) {
++pos;
}
return pos > start;
}
enum class JsonMemberState { Absent, NotString, String, Malformed };
// Looks up `key` among the direct members of a JSON object. A string value is
// decoded into `out`; any other value is left in `out` as its JSON text.
// Unlike a text search this never matches a key of a nested object (a
// license variable may legitimately be called "hwid").
JsonMemberState ReadTopLevelJsonMember(const std::string &json, const std::string &key, std::string &out) {
out.clear();
std::size_t pos = 0;
SkipJsonWhitespace(json, pos);
if (pos >= json.size() || json[pos] != '{') {
return JsonMemberState::Malformed;
}
++pos;
SkipJsonWhitespace(json, pos);
if (pos < json.size() && json[pos] == '}') {
return JsonMemberState::Absent;
}
std::string name;
while (true) {
SkipJsonWhitespace(json, pos);
if (!ReadJsonString(json, pos, name)) {
return JsonMemberState::Malformed;
}
SkipJsonWhitespace(json, pos);
if (pos >= json.size() || json[pos] != ':') {
return JsonMemberState::Malformed;
}
++pos;
SkipJsonWhitespace(json, pos);
if (name == key) {
if (pos < json.size() && json[pos] == '"') {
return ReadJsonString(json, pos, out) ? JsonMemberState::String : JsonMemberState::Malformed;
}
const std::size_t start = pos;
if (!SkipJsonValue(json, pos)) {
return JsonMemberState::Malformed;
}
out = json.substr(start, pos - start);
return JsonMemberState::NotString;
}
if (!SkipJsonValue(json, pos)) {
return JsonMemberState::Malformed;
}
SkipJsonWhitespace(json, pos);
if (pos >= json.size()) {
return JsonMemberState::Malformed;
}
if (json[pos] == '}') {
return JsonMemberState::Absent;
}
if (json[pos] != ',') {
return JsonMemberState::Malformed;
}
++pos;
}
}
// True unless the signed payload names a different value for `key` than the
// one this client sent. A payload without the member (older servers) passes;
// one that cannot be read does not, so a value this reader cannot decode can
// never stand in for a match.
bool SignedMemberMatches(const std::string &payloadJson, const std::string &key, const std::string &sent) {
std::string value;
switch (ReadTopLevelJsonMember(payloadJson, key, value)) {
case JsonMemberState::Absent:
case JsonMemberState::NotString:
return true;
case JsonMemberState::String:
return value == sent;
case JsonMemberState::Malformed:
return false;
}
return false;
}
// A JSON number of seconds; std::nullopt for anything else.
std::optional<long long> ParseJsonSeconds(const std::string &text) {
if (text.empty() || !(text[0] == '-' || (text[0] >= '0' && text[0] <= '9'))) {
return std::nullopt;
}
char *end = nullptr;
const double value = std::strtod(text.c_str(), &end);
if (end != text.c_str() + text.size() || !(value > -1e15 && value < 1e15)) {
return std::nullopt;
}
return static_cast<long long>(std::floor(value));
}
// Seconds a signed session lasts: from the signed `timestamp` (an ISO 8601
// time or Unix seconds; `wallNow` when absent or unusable) to `end` (the
// session expiry), lowered to the signed licenseExpiresAt when it is an ISO
// 8601 time. Measured from the server's own two times, so a local clock that
// is off by a constant amount does not change it.
long long SignedSessionLifetime(const std::string &payloadJson, long long end, long long wallNow) {
std::string value;
if (ReadTopLevelJsonMember(payloadJson, "licenseExpiresAt", value) == JsonMemberState::String) {
if (const std::optional<long long> ms = ParseIso8601Ms(value); ms.has_value()) {
end = (std::min)(end, *ms / 1000);
}
}
long long issued = wallNow;
switch (ReadTopLevelJsonMember(payloadJson, "timestamp", value)) {
case JsonMemberState::String:
if (const std::optional<long long> ms = ParseIso8601Ms(value); ms.has_value()) {
issued = *ms / 1000;
}
break;
case JsonMemberState::NotString:
if (const std::optional<long long> seconds = ParseJsonSeconds(value); seconds.has_value()) {
issued = *seconds;
}
break;
default:
break;
}
return end - issued;
}
// Tells the API which SDK and version made the request.
constexpr const char *kSdkIdentificationHeader = "X-AuthForge-SDK: authforge-cpp/" AUTHFORGE_SDK_VERSION;
// No AuthForge answer comes near this; a larger one is not read.
constexpr std::size_t kMaxResponseBytes = 1024 * 1024;
struct CurlBody {
std::string data;
bool tooLarge = false;
};
size_t CurlWriteCallback(char *ptr, size_t size, size_t nmemb, void *userdata) {
if (userdata == nullptr) {
return 0;
}
const size_t bytes = size * nmemb;
auto *out = static_cast<CurlBody *>(userdata);
if (bytes > kMaxResponseBytes - out->data.size()) {
out->tooLarge = true;
return 0; // ends the transfer with CURLE_WRITE_ERROR
}
out->data.append(ptr, bytes);
return bytes;
}
// The stop flag of the background check whose own requests run on this
// thread: setting it (Logout(), a new Login(), the destructor) ends their
// retry delay and aborts their transfer, so nothing waits for them. Null on
// every other thread, and inside onFailure: a Login() there runs to the end.
thread_local const std::atomic<bool> *tlsAbortWhen = nullptr;
class AbortScope {
public:
explicit AbortScope(const std::atomic<bool> *flag) noexcept : previous_(tlsAbortWhen) { tlsAbortWhen = flag; }
~AbortScope() { tlsAbortWhen = previous_; }
AbortScope(const AbortScope &) = delete;
AbortScope &operator=(const AbortScope &) = delete;
private:
const std::atomic<bool> *previous_;
};
bool Stopping() noexcept { return tlsAbortWhen != nullptr && tlsAbortWhen->load(); }
int CurlAbortWhenStopped(void *clientp, curl_off_t, curl_off_t, curl_off_t, curl_off_t) {
const auto *stop = static_cast<const std::atomic<bool> *>(clientp);
return stop != nullptr && stop->load() ? 1 : 0;
}
bool EnsureCurlInit() {
static const bool initialized = curl_global_init(CURL_GLOBAL_DEFAULT) == CURLE_OK;
return initialized;
}
// Server codes are snake_case tokens: ^[a-z][a-z0-9_]{0,63}$.
bool IsErrorCodeToken(const std::string &code) {
if (code.empty() || code.size() > 64 || code.front() < 'a' || code.front() > 'z') {
return false;
}
return std::all_of(code.begin(), code.end(), [](char c) {
return (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') || c == '_';
});
}
constexpr std::array<int, 2> kRateLimitRetryDelays = {2, 5};
constexpr int kNetworkRetryDelay = 2;
// The stop flag of the background check thread this code runs on; null on
// every other thread.
thread_local const std::atomic<bool> *tlsHeartbeatStop = nullptr;
// The exit SetExitOnFailure(true) asks for. std::exit runs static
// destructors, which main() may still be using when the exit comes from the
// background thread; quick_exit skips them (macOS has no quick_exit).
void ExitForFailure(int code) {
if (tlsHeartbeatStop != nullptr) {
#if defined(__APPLE__)
std::_Exit(code);
#else
std::quick_exit(code);
#endif
}
std::exit(code);
}
} // namespace
bool IsTransientErrorCode(const std::string &code) {
static const std::unordered_set<std::string> kDefinitiveErrorCodes = {
"revoked",
"expired",
"hwid_mismatch",
"blocked",
"session_expired",
"malformed_request",
"app_disabled",
"invalid_app",
"offline_activation_disabled",
"offline_activation_requires_perpetual",
"offline_activation_requires_seats",
"offline_activation_limit_reached",
"signature_mismatch",
"offline_file_rejected",
};
return kDefinitiveErrorCodes.find(code) == kDefinitiveErrorCodes.end();
}
std::string RefreshNonceInBody(const std::string &bodyJson, const std::string &newNonce) {
const std::string marker = "\"nonce\":\"";
const std::size_t start = bodyJson.find(marker);
if (start == std::string::npos) {
return bodyJson;
}
const std::size_t valueStart = start + marker.size();
const std::size_t valueEnd = bodyJson.find('"', valueStart);
if (valueEnd == std::string::npos) {
return bodyJson;
}
std::string refreshed = bodyJson;
refreshed.replace(valueStart, valueEnd - valueStart, newNonce);
return refreshed;
}
std::optional<std::string> ExtractNonceFromBody(const std::string &bodyJson) {
const std::string marker = "\"nonce\":\"";
const std::size_t start = bodyJson.find(marker);
if (start == std::string::npos) {
return std::nullopt;
}
const std::size_t valueStart = start + marker.size();
const std::size_t valueEnd = bodyJson.find('"', valueStart);
if (valueEnd == std::string::npos) {
return std::nullopt;
}
return bodyJson.substr(valueStart, valueEnd - valueStart);
}
std::vector<std::string> AuthForgeClient::SplitCommaTrustList(const std::string &value) {
// Honour the same comma-separated convention the other SDKs use. Lets
// operators ship a rotation set through `AUTHFORGE_PUBLIC_KEY` without
// touching call sites that still pass a single string.
std::vector<std::string> out;
std::string current;
for (const char ch : value) {
if (ch == ',') {
const std::string trimmed = Trim(current);
if (!trimmed.empty()) {
out.push_back(trimmed);
}
current.clear();
} else {
current.push_back(ch);
}
}
const std::string trimmed = Trim(current);
if (!trimmed.empty()) {
out.push_back(trimmed);
}
return out;
}
namespace {
// Maps the legacy heartbeatMode strings onto the OnlineHeartbeat policy while
// preserving the exact legacy validation: anything other than LOCAL or SERVER
// (case-insensitive) throws std::invalid_argument. LOCAL is the default grace
// period behavior (OnlineHeartbeat::Off); SERVER enables online check-ins
// (OnlineHeartbeat::On).
OnlineHeartbeat ParseLegacyHeartbeatMode(std::string heartbeatMode) {
std::transform(heartbeatMode.begin(), heartbeatMode.end(), heartbeatMode.begin(),
[](unsigned char c) { return static_cast<char>(std::toupper(c)); });
if (heartbeatMode == "SERVER") {
return OnlineHeartbeat::On;
}
if (heartbeatMode == "LOCAL") {
return OnlineHeartbeat::Off;
}
throw std::invalid_argument("heartbeat_mode must be LOCAL or SERVER");
}
} // namespace
AuthForgeClient::AuthForgeClient(
std::string appId,
std::string appSecret,
std::string publicKey,
OnlineHeartbeat onlineHeartbeat,
int heartbeatInterval,
std::string apiBaseUrl,
std::function<void(const std::string &, const std::exception *)> onFailure,
int requestTimeout,
int ttlSeconds,
std::string hwidOverride)
: AuthForgeClient(
std::move(appId),
std::move(appSecret),
SplitCommaTrustList(publicKey),
onlineHeartbeat,
heartbeatInterval,
std::move(apiBaseUrl),
std::move(onFailure),
requestTimeout,
ttlSeconds,
std::move(hwidOverride)) {}
AuthForgeClient::AuthForgeClient(
std::string appId,
std::string appSecret,
std::string publicKey,
std::string heartbeatMode,
int heartbeatInterval,
std::string apiBaseUrl,
std::function<void(const std::string &, const std::exception *)> onFailure,
int requestTimeout,
int ttlSeconds,
std::string hwidOverride)
: AuthForgeClient(
std::move(appId),
std::move(appSecret),
SplitCommaTrustList(publicKey),
ParseLegacyHeartbeatMode(std::move(heartbeatMode)),
heartbeatInterval,
std::move(apiBaseUrl),
std::move(onFailure),
requestTimeout,
ttlSeconds,
std::move(hwidOverride)) {}
AuthForgeClient::AuthForgeClient(
std::string appId,
std::string appSecret,
std::vector<std::string> publicKeys,
std::string heartbeatMode,
int heartbeatInterval,
std::string apiBaseUrl,
std::function<void(const std::string &, const std::exception *)> onFailure,
int requestTimeout,
int ttlSeconds,
std::string hwidOverride)
: AuthForgeClient(
std::move(appId),
std::move(appSecret),
std::move(publicKeys),
ParseLegacyHeartbeatMode(std::move(heartbeatMode)),
heartbeatInterval,
std::move(apiBaseUrl),
std::move(onFailure),
requestTimeout,
ttlSeconds,
std::move(hwidOverride)) {}
AuthForgeClient::AuthForgeClient(
std::string appId,
std::string appSecret,
std::vector<std::string> publicKeys,
OnlineHeartbeat onlineHeartbeat,
int heartbeatInterval,
std::string apiBaseUrl,
std::function<void(const std::string &, const std::exception *)> onFailure,
int requestTimeout,
int ttlSeconds,
std::string hwidOverride)
: appId_(std::move(appId)),
appSecret_(std::move(appSecret)),
publicKeys_(std::move(publicKeys)),
onlineHeartbeat_(onlineHeartbeat == OnlineHeartbeat::On),
heartbeatInterval_(heartbeatInterval),
apiBaseUrl_(std::move(apiBaseUrl)),
onFailure_(std::move(onFailure)),
requestTimeout_(requestTimeout),
ttlSeconds_(ttlSeconds > 0 ? ttlSeconds : 0),
transport_(CurlPost),
sleep_([this](std::chrono::seconds delay) {
// A background check's retry delay ends as soon as the check is
// stopped; any other caller sleeps the whole delay.
const std::atomic<bool> *stop = tlsAbortWhen;
if (stop == nullptr) {
std::this_thread::sleep_for(delay);
return;
}
std::unique_lock<std::mutex> guard(lock_);
heartbeatCv_.wait_for(guard, delay, [stop]() { return stop->load(); });
}),
nonce_(GenerateNonceHex32),
exit_(ExitForFailure),
wallClock_([]() { return static_cast<long long>(std::time(nullptr)); }),
monoClock_([]() {
return static_cast<long long>(
std::chrono::duration_cast<std::chrono::seconds>(std::chrono::steady_clock::now().time_since_epoch())
.count());
}),
heartbeatStarted_(false) {
if (appId_.empty()) {
throw std::invalid_argument("app_id must be a non-empty string");
}
// Empty appSecret is valid for offline-only clients (LoginFromFile).
// Online APIs (Login, ValidateLicense, SelfBan) still require a secret.
// Drop blanks/duplicates while preserving caller order: the first slot is
// treated as the *current* key by tools/diagnostics.
std::vector<std::string> deduped;
for (auto &key : publicKeys_) {
const std::string trimmed = Trim(key);
if (trimmed.empty()) continue;
if (std::find(deduped.begin(), deduped.end(), trimmed) != deduped.end()) continue;
deduped.push_back(trimmed);
}
publicKeys_ = std::move(deduped);
if (publicKeys_.empty()) {
throw std::invalid_argument("public_key must be a non-empty string");
}
if (heartbeatInterval_ < 10) {
throw std::invalid_argument("heartbeat_interval must be >= 10");
}
while (!apiBaseUrl_.empty() && apiBaseUrl_.back() == '/') {
apiBaseUrl_.pop_back();
}
// Over plain HTTP anyone on the path reads the app secret and license key;
// it is only for a server on this machine (a test server, a local proxy).
if (StartsWithNoCase(apiBaseUrl_, "http://") && !IsLoopbackHttpUrl(apiBaseUrl_)) {
throw std::invalid_argument("api_base_url must use https:// (http:// only for 127.0.0.1, ::1 or localhost)");
}
if (sodium_init() < 0) {
throw std::runtime_error("sodium_init_failed");
}
verifyPublicKeysBytes_.reserve(publicKeys_.size());
for (const auto &key : publicKeys_) {
auto decoded = DecodeBase64Any(key);
if (decoded.size() != crypto_sign_PUBLICKEYBYTES) {
throw std::invalid_argument("public_key must be 32 bytes (base64 Ed25519 raw key)");
}
verifyPublicKeysBytes_.push_back(std::move(decoded));
}
const std::string trimmedOverride = Trim(hwidOverride);
if (!trimmedOverride.empty()) {
hwid_ = trimmedOverride;
hwidSource_ = "override";
} else {
std::string reason;
if (const std::optional<std::string> machineId = ReadOsMachineId(reason); machineId.has_value()) {
hwid_ = HwidFromMachineId(appId_, *machineId);
hwidSource_ = "machine-id";
} else {
// The fallback is a different identity for the same machine: say so.
std::cerr << "AuthForge: could not read the OS machine id (" << reason
<< "); using the legacy fingerprint as the HWID\n";
hwid_ = HwidFromMachineId(appId_, "legacy:" + ComputeLegacyFingerprint());
hwidSource_ = "legacy";
}
}
// The server clamps the session TTL to 1h..7d (24h when not requested). A
// background check at least half a TTL apart can miss the whole refresh
// window; a warning instead of an error keeps existing apps starting.
const int ttl = ttlSeconds_ > 0 ? std::clamp(ttlSeconds_, 3600, 604800) : 86400;
if (2LL * heartbeatInterval_ >= ttl) {
std::cerr << "AuthForge: heartbeatInterval " << heartbeatInterval_ << "s is at least half the session TTL " << ttl
<< "s; sessions may lapse between background checks\n";
}
}
void AuthForgeClient::SetAutoRenew(bool enabled) noexcept {
autoRenew_ = enabled;
}
void AuthForgeClient::SetExitOnFailure(bool enabled) noexcept {
exitOnFailure_ = enabled;
}
std::optional<AuthForgeFailure> AuthForgeClient::GetLastFailure() const {
std::lock_guard<std::mutex> guard(lock_);
return lastFailure_;
}
AuthForgeClient::~AuthForgeClient() {
// Loop because onFailure (running on the thread being joined) may call
// Login() and start a replacement thread.
while (true) {
std::thread thread;
{
std::lock_guard<std::mutex> guard(lock_);
++sessionGeneration_;
if (heartbeatControl_) {
heartbeatControl_->stop = true;
}
thread = std::move(heartbeatThread_);
}
heartbeatCv_.notify_all();
if (!thread.joinable()) {
return;
}
if (thread.get_id() == std::this_thread::get_id()) {
thread.detach();
return;
}
thread.join();
}
}
bool AuthForgeClient::Login(const std::string &licenseKey) {
if (licenseKey.empty()) {
throw std::invalid_argument("license_key must be a non-empty string");
}
if (appSecret_.empty()) {
throw std::invalid_argument(
"app_secret is required for online APIs; omit it only when using LoginFromFile");
}
try {
ValidateAndStore(licenseKey);
{
std::lock_guard<std::mutex> guard(lock_);
lastFailure_.reset();
}
StartHeartbeatOnce();
return true;
} catch (const std::exception &exc) {
Fail("login_failed", &exc);
return false;
} catch (...) {
Fail("login_failed", nullptr);
return false;
}
}
ValidateLicenseResult AuthForgeClient::ValidateLicense(const std::string &licenseKey) {
ValidateLicenseResult result;
if (licenseKey.empty()) {
result.valid = false;
result.errorCode = "missing_license_key";
return result;
}
if (appSecret_.empty()) {
result.valid = false;
result.errorCode =
"app_secret is required for online APIs; omit it only when using LoginFromFile";
return result;
}
try {
const std::string nonce = nonce_();
std::string usedNonce = nonce;
const std::string response = PostJson("/auth/validate", BuildValidateBody(licenseKey, nonce), &usedNonce);
// The key is passed so the response can be checked against it; nothing is
// stored because persistToSession is false.
ApplySignedResponse(response, usedNonce, licenseKey, SigningContext::Validate, false, &result);
return result;
} catch (const AuthForgeError &exc) {
// A response bound to another device or license explains itself in the
// message; errorCode stays the bare code so callers can match on it.
result.valid = false;
result.errorCode = exc.code() == "signature_mismatch" ? exc.code() : std::string(exc.what());
return result;
} catch (const std::exception &exc) {
result.valid = false;
result.errorCode = exc.what();
return result;
} catch (...) {
result.valid = false;
result.errorCode = "unknown_error";
return result;
}
}
bool AuthForgeClient::SelfBan(
const std::string &licenseKey,
const std::string &sessionToken,
bool revokeLicense,
bool blacklistHwid,
bool blacklistIp) {
std::string resolvedSessionToken;
std::string resolvedLicenseKey;
SessionKind kind;
{
std::lock_guard<std::mutex> guard(lock_);
kind = sessionKind_;
resolvedSessionToken = Trim(sessionToken.empty() ? sessionToken_ : sessionToken);
resolvedLicenseKey = Trim(licenseKey.empty() ? licenseKey_ : licenseKey);
}
// An offline session has no server session to revoke and no license key
// the server should hear about: fail locally, no HTTP.
if (kind == SessionKind::Offline && Trim(sessionToken).empty() && Trim(licenseKey).empty()) {
throw std::invalid_argument("offline_session");
}
auto appendFlags = [](std::string body, bool revoke, bool hwidFlag, bool ipFlag) {
if (body.size() < 2 || body.back() != '}') {
return body;
}
body.pop_back();
body += ",\"revokeLicense\":";
body += revoke ? "true" : "false";
body += ",\"blacklistHwid\":";
body += hwidFlag ? "true" : "false";
body += ",\"blacklistIp\":";
body += ipFlag ? "true" : "false";
body.push_back('}');
return body;
};
std::string response;
if (!resolvedSessionToken.empty()) {
std::string body = BuildJsonBody({
{"appId", appId_},
{"sessionToken", resolvedSessionToken},
{"hwid", hwid_},
});
response = PostJson("/auth/selfban", appendFlags(body, revokeLicense, blacklistHwid, blacklistIp));
} else {
if (resolvedLicenseKey.empty()) {
throw std::invalid_argument("missing_license_key");