-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathauthforge_sdk.cpp
More file actions
1435 lines (1322 loc) · 41.8 KB
/
authforge_sdk.cpp
File metadata and controls
1435 lines (1322 loc) · 41.8 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 <chrono>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <ctime>
#include <iomanip>
#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")
#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
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;
}
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;
}
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<std::string *>(userdata);
out->append(ptr, bytes);
return bytes;
}
void EnsureCurlInit() {
static std::once_flag initFlag;
std::call_once(initFlag, []() {
const CURLcode rc = curl_global_init(CURL_GLOBAL_DEFAULT);
if (rc != CURLE_OK) {
throw std::runtime_error("url_error: curl_global_init_failed");
}
});
}
} // namespace
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;
}
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),
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)
: appId_(std::move(appId)),
appSecret_(std::move(appSecret)),
publicKeys_(std::move(publicKeys)),
heartbeatMode_(ToLower(std::move(heartbeatMode))),
heartbeatInterval_(heartbeatInterval),
apiBaseUrl_(std::move(apiBaseUrl)),
onFailure_(std::move(onFailure)),
requestTimeout_(requestTimeout),
ttlSeconds_(ttlSeconds > 0 ? ttlSeconds : 0),
heartbeatStarted_(false) {
if (appId_.empty()) {
throw std::invalid_argument("app_id must be a non-empty string");
}
if (appSecret_.empty()) {
throw std::invalid_argument("app_secret must be a non-empty string");
}
// 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");
}
std::transform(heartbeatMode_.begin(), heartbeatMode_.end(), heartbeatMode_.begin(),
[](unsigned char c) { return static_cast<char>(std::toupper(c)); });
if (heartbeatMode_ != "LOCAL" && heartbeatMode_ != "SERVER") {
throw std::invalid_argument("heartbeat_mode must be LOCAL or SERVER");
}
if (heartbeatInterval_ <= 0) {
throw std::invalid_argument("heartbeat_interval must be > 0");
}
while (!apiBaseUrl_.empty() && apiBaseUrl_.back() == '/') {
apiBaseUrl_.pop_back();
}
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);
hwid_ = trimmedOverride.empty() ? GetHwid() : trimmedOverride;
}
bool AuthForgeClient::Login(const std::string &licenseKey) {
if (licenseKey.empty()) {
throw std::invalid_argument("license_key must be a non-empty string");
}
try {
ValidateAndStore(licenseKey);
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;
}
try {
const std::string nonce = GenerateNonceHex32();
std::string body = BuildJsonBody({
{"appId", appId_},
{"appSecret", appSecret_},
{"licenseKey", licenseKey},
{"hwid", hwid_},
{"nonce", nonce},
});
if (ttlSeconds_ > 0 && body.size() >= 2 && body.back() == '}') {
body.pop_back();
body += ",\"ttlSeconds\":" + std::to_string(ttlSeconds_) + "}";
}
std::string usedNonce = nonce;
const std::string response = PostJson("/auth/validate", body, &usedNonce);
ApplySignedResponse(response, usedNonce, std::nullopt, SigningContext::Validate, false, &result);
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) {
try {
std::string resolvedSessionToken;
std::string resolvedLicenseKey;
std::string hwid;
{
std::lock_guard<std::mutex> guard(lock_);
resolvedSessionToken = Trim(sessionToken.empty() ? sessionToken_ : sessionToken);
resolvedLicenseKey = Trim(licenseKey.empty() ? licenseKey_ : licenseKey);
hwid = hwid_;
}
auto appendFlags = [](std::string body,
bool revoke,
bool includeRevoke,
bool hwidFlag,
bool ipFlag) {
if (body.size() < 2 || body.back() != '}') {
return body;
}
body.pop_back();
if (includeRevoke) {
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},
});
body = appendFlags(body, revokeLicense, true, blacklistHwid, blacklistIp);
response = PostJson("/auth/selfban", body);
} else {
if (resolvedLicenseKey.empty()) {
throw std::runtime_error("missing_license_key");
}
std::string body = BuildJsonBody({
{"appId", appId_},
{"appSecret", appSecret_},
{"licenseKey", resolvedLicenseKey},
{"hwid", hwid},
{"nonce", GenerateNonceHex32()},
});
// Pre-session self-ban cannot revoke licenses.
body = appendFlags(body, false, true, blacklistHwid, blacklistIp);
response = PostJson("/auth/selfban", body);
}
JsonValue status;
ExtractJsonValue(response, "status", status);
if (!IsSuccessStatus(status)) {
throw std::runtime_error(ExtractServerError(response));
}
return true;
} catch (const std::exception &exc) {
Fail("selfban_failed", &exc);
return false;
} catch (...) {
Fail("selfban_failed", nullptr);
return false;
}
}
void AuthForgeClient::StartHeartbeatOnce() {
std::lock_guard<std::mutex> guard(lock_);
if (heartbeatStarted_) {
return;
}
heartbeatStop_ = false;
heartbeatStarted_ = true;
std::thread([this]() { HeartbeatLoop(); }).detach();
}
void AuthForgeClient::HeartbeatLoop() noexcept {
while (true) {
std::this_thread::sleep_for(std::chrono::seconds(heartbeatInterval_));
{
std::lock_guard<std::mutex> guard(lock_);
if (heartbeatStop_) {
break;
}
}
try {
if (heartbeatMode_ == "SERVER") {
ServerHeartbeat();
} else {
LocalHeartbeat();
}
} catch (const std::exception &exc) {
Fail("heartbeat_failed", &exc);
break;
} catch (...) {
Fail("heartbeat_failed", nullptr);
break;
}
}
}
void AuthForgeClient::ServerHeartbeat() {
std::string sessionToken;
std::string hwid;
{
std::lock_guard<std::mutex> guard(lock_);
sessionToken = sessionToken_;
hwid = hwid_;
}
if (sessionToken.empty()) {
throw std::runtime_error("missing_session_token");
}
const std::string nonce = GenerateNonceHex32();
const std::string body = BuildJsonBody({
{"appId", appId_},
{"sessionToken", sessionToken},
{"nonce", nonce},
{"hwid", hwid},
});
std::string usedNonce = nonce;
const std::string response = PostJson("/auth/heartbeat", body, &usedNonce);
ApplySignedResponse(response, usedNonce, std::nullopt, SigningContext::Heartbeat);
}
void AuthForgeClient::LocalHeartbeat() {
std::string rawPayloadB64;
std::string signature;
std::optional<long long> expiresIn;
{
std::lock_guard<std::mutex> guard(lock_);
rawPayloadB64 = rawPayloadB64_;
signature = signature_;
expiresIn = sessionExpiresIn_;
}
if (rawPayloadB64.empty() || signature.empty()) {
throw std::runtime_error("missing_local_verification_state");
}
VerifySignature(rawPayloadB64, signature);
if (!expiresIn.has_value()) {
throw std::runtime_error("missing_session_expiry");
}
const long long now = static_cast<long long>(std::time(nullptr));
if (now < *expiresIn) {
return;
}
throw std::runtime_error("session_expired");
}
void AuthForgeClient::ValidateAndStore(const std::string &licenseKey) {
const std::string nonce = GenerateNonceHex32();
std::string body = BuildJsonBody({
{"appId", appId_},
{"appSecret", appSecret_},
{"licenseKey", licenseKey},
{"hwid", hwid_},
{"nonce", nonce},
});
// BuildJsonBody always emits string values; splice ttlSeconds in as a raw
// integer when the caller requested a custom session lifetime.
if (ttlSeconds_ > 0 && body.size() >= 2 && body.back() == '}') {
body.pop_back();
body += ",\"ttlSeconds\":" + std::to_string(ttlSeconds_) + "}";
}
std::string usedNonce = nonce;
const std::string response = PostJson("/auth/validate", body, &usedNonce);
ApplySignedResponse(response, usedNonce, licenseKey, SigningContext::Validate);
}
void AuthForgeClient::ApplySignedResponse(
const std::string &responseJson,
const std::string &expectedNonce,
const std::optional<std::string> &licenseKey,
SigningContext context,
bool persistToSession,
ValidateLicenseResult *validateOnlyOut) {
JsonValue status;
ExtractJsonValue(responseJson, "status", status);
if (!IsSuccessStatus(status)) {
throw std::runtime_error(ExtractServerError(responseJson));
}
const std::optional<std::string> rawPayloadOpt = ExtractJsonString(responseJson, "payload");
if (!rawPayloadOpt.has_value()) {
throw std::runtime_error("missing_payload");
}
if (rawPayloadOpt->empty()) {
throw std::runtime_error("empty_payload");
}
const std::optional<std::string> signatureOpt = ExtractJsonString(responseJson, "signature");
if (!signatureOpt.has_value()) {
throw std::runtime_error("missing_signature");
}
if (signatureOpt->empty()) {
throw std::runtime_error("empty_signature");
}
const std::string rawPayloadB64 = *rawPayloadOpt;
const std::string signature = *signatureOpt;
std::vector<unsigned char> payloadBytes;
try {
payloadBytes = DecodeBase64Any(rawPayloadB64);
} catch (...) {
throw std::runtime_error("invalid_payload_json");
}
std::string payloadJson(payloadBytes.begin(), payloadBytes.end());
const std::string payloadTrimmed = Trim(payloadJson);
if (payloadTrimmed.empty() || payloadTrimmed.front() != '{' || payloadTrimmed.back() != '}') {
throw std::runtime_error("payload_not_json_object");
}
payloadJson = payloadTrimmed;
JsonValue nonceValue;
if (!ExtractJsonValue(payloadJson, "nonce", nonceValue)) {
nonceValue.value.clear();
nonceValue.isString = true;
nonceValue.exists = true;
}
std::string receivedNonce = Trim(nonceValue.value);
if (receivedNonce != expectedNonce) {
throw std::runtime_error("nonce_mismatch");
}
(void)context;
VerifySignature(rawPayloadB64, signature);
const std::optional<std::string> sessionTokenOpt = ExtractJsonString(payloadJson, "sessionToken");
const std::string sessionToken = sessionTokenOpt.has_value() ? Trim(*sessionTokenOpt) : "";
if (sessionToken.empty()) {
throw std::runtime_error("missing_sessionToken");
}
std::optional<long long> expiresIn = ExtractExpiresInFromSessionToken(sessionToken);
if (!expiresIn.has_value()) {
expiresIn = ExtractJsonInt(payloadJson, "expiresIn");
}
if (!expiresIn.has_value()) {
throw std::runtime_error("missing_expiresIn");
}
if (validateOnlyOut != nullptr) {
validateOnlyOut->valid = true;
validateOnlyOut->errorCode.clear();
validateOnlyOut->sessionToken = sessionToken;
validateOnlyOut->expiresIn = *expiresIn;
validateOnlyOut->sessionDataJson = payloadJson;
validateOnlyOut->keyId.clear();
if (const std::optional<std::string> keyIdOpt = ExtractJsonString(responseJson, "keyId"); keyIdOpt.has_value()) {
validateOnlyOut->keyId = *keyIdOpt;
}
validateOnlyOut->appVariablesJson.clear();
if (const std::optional<std::string> appVars = ExtractTopLevelObject(payloadJson, "appVariables"); appVars.has_value()) {
validateOnlyOut->appVariablesJson = *appVars;
}
validateOnlyOut->licenseVariablesJson.clear();
if (const std::optional<std::string> licenseVars = ExtractTopLevelObject(payloadJson, "licenseVariables"); licenseVars.has_value()) {
validateOnlyOut->licenseVariablesJson = *licenseVars;
}
validateOnlyOut->sessionExpiresAt.reset();
if (const std::optional<std::string> sea = ExtractJsonString(payloadJson, "sessionExpiresAt"); sea.has_value() && !sea->empty()) {
validateOnlyOut->sessionExpiresAt = *sea;
}
validateOnlyOut->licenseExpirationKnown = false;
validateOnlyOut->licenseExpiresAt.clear();
JsonValue le;
if (ExtractJsonValue(payloadJson, "licenseExpiresAt", le) && le.exists) {
validateOnlyOut->licenseExpirationKnown = true;
if (le.isString) {
validateOnlyOut->licenseExpiresAt = le.value;
}
}
validateOnlyOut->maxHwidSlots.reset();
if (const std::optional<long long> mh = ExtractJsonInt(payloadJson, "maxHwidSlots"); mh.has_value()) {
validateOnlyOut->maxHwidSlots = static_cast<int>(*mh);
}
validateOnlyOut->hwidCount.reset();
if (const std::optional<long long> hc = ExtractJsonInt(payloadJson, "hwidCount"); hc.has_value()) {
validateOnlyOut->hwidCount = static_cast<int>(*hc);
}
validateOnlyOut->licenseLabel.reset();
if (const std::optional<std::string> ll = ExtractJsonString(payloadJson, "licenseLabel"); ll.has_value() && !ll->empty()) {
validateOnlyOut->licenseLabel = *ll;
}
}
if (!persistToSession) {
return;
}
{
std::lock_guard<std::mutex> guard(lock_);
if (licenseKey.has_value()) {
licenseKey_ = *licenseKey;
}
sessionToken_ = sessionToken;
sessionExpiresIn_ = *expiresIn;
lastNonce_ = expectedNonce;
rawPayloadB64_ = rawPayloadB64;
signature_ = signature;
keyId_.clear();
if (const std::optional<std::string> keyId = ExtractJsonString(responseJson, "keyId"); keyId.has_value()) {
keyId_ = *keyId;
}
sessionDataJson_ = payloadJson;
appVariablesJson_.clear();
if (const std::optional<std::string> appVars = ExtractTopLevelObject(payloadJson, "appVariables"); appVars.has_value()) {
appVariablesJson_ = *appVars;
}
licenseVariablesJson_.clear();
if (const std::optional<std::string> licenseVars = ExtractTopLevelObject(payloadJson, "licenseVariables"); licenseVars.has_value()) {
licenseVariablesJson_ = *licenseVars;
}
authenticated_ = true;
}
}
std::string AuthForgeClient::PostJson(const std::string &path, const std::string &bodyJson, std::string *usedNonce) const {
EnsureCurlInit();
const std::string url = apiBaseUrl_ + path;
std::array<int, 2> rateRetryDelays = {2, 5};
std::string mutableBody = bodyJson;
std::string currentNonce = ExtractNonceFromBody(mutableBody).value_or("");
bool networkRetried = false;
int rateAttempt = 0;
while (true) {
CURL *curl = curl_easy_init();
if (curl == nullptr) {
throw std::runtime_error("url_error: curl_easy_init_failed");
}
std::string responseBody;
struct curl_slist *headers = nullptr;
headers = curl_slist_append(headers, "Content-Type: application/json");
curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
curl_easy_setopt(curl, CURLOPT_POST, 1L);
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, mutableBody.c_str());
curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, static_cast<long>(mutableBody.size()));
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
curl_easy_setopt(curl, CURLOPT_TIMEOUT, static_cast<long>(requestTimeout_));
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, CurlWriteCallback);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &responseBody);
const CURLcode rc = curl_easy_perform(curl);
long code = 0;
curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &code);
curl_slist_free_all(headers);
curl_easy_cleanup(curl);
if (rc != CURLE_OK) {
if (!networkRetried) {
networkRetried = true;
std::this_thread::sleep_for(std::chrono::seconds(2));
continue;
}
throw std::runtime_error(std::string("url_error: ") + curl_easy_strerror(rc));
}
const std::string trimmed = Trim(responseBody);
if (trimmed.empty()) {
throw std::runtime_error("invalid_json_response");
}
if (trimmed.front() != '{' || trimmed.back() != '}') {
throw std::runtime_error("response_not_json_object");
}
const bool isRateLimited = (code == 429) || (ExtractServerError(trimmed) == "rate_limited");
if (isRateLimited && rateAttempt < static_cast<int>(rateRetryDelays.size())) {
std::this_thread::sleep_for(std::chrono::seconds(rateRetryDelays[rateAttempt]));
currentNonce = GenerateNonceHex32();
mutableBody = RefreshNonceInBody(mutableBody, currentNonce);
++rateAttempt;
continue;
}
if (code >= 400) {
throw std::runtime_error("http_error_" + std::to_string(code) + ": " + trimmed);
}
if (usedNonce != nullptr) {
*usedNonce = currentNonce;
}
return trimmed;
}
}
std::string AuthForgeClient::ExtractServerError(const std::string &responseJson) const {
JsonValue errorValue;
if (ExtractJsonValue(responseJson, "error", errorValue) && errorValue.exists) {
const std::string candidate = ToLower(Trim(errorValue.value));
if (knownServerErrors_.find(candidate) != knownServerErrors_.end()) {
return candidate;
}
}
JsonValue statusValue;
if (ExtractJsonValue(responseJson, "status", statusValue) && statusValue.exists) {
const std::string candidate = ToLower(Trim(statusValue.value));
if (knownServerErrors_.find(candidate) != knownServerErrors_.end()) {
return candidate;
}
}
return "unknown_error";
}
void AuthForgeClient::Fail(const std::string &reason, const std::exception *exc) const noexcept {
if (onFailure_) {
try {
onFailure_(reason, exc);
return;
} catch (...) {
}
}
std::exit(1);
}
void AuthForgeClient::Logout() {
std::lock_guard<std::mutex> guard(lock_);
heartbeatStop_ = true;
heartbeatStarted_ = false;
licenseKey_.clear();
sessionToken_.clear();
sessionExpiresIn_ = std::nullopt;
lastNonce_.clear();
rawPayloadB64_.clear();
signature_.clear();
keyId_.clear();
sessionDataJson_.clear();
appVariablesJson_.clear();
licenseVariablesJson_.clear();
authenticated_ = false;
}
bool AuthForgeClient::IsAuthenticated() const {
std::lock_guard<std::mutex> guard(lock_);
return authenticated_ && !sessionToken_.empty();
}
std::optional<std::string> AuthForgeClient::GetSessionDataJson() const {
std::lock_guard<std::mutex> guard(lock_);
if (sessionDataJson_.empty()) {
return std::nullopt;
}
return sessionDataJson_;
}
std::optional<std::string> AuthForgeClient::GetAppVariablesJson() const {
std::lock_guard<std::mutex> guard(lock_);
if (appVariablesJson_.empty()) {
return std::nullopt;
}
return appVariablesJson_;
}
std::optional<std::string> AuthForgeClient::GetLicenseVariablesJson() const {
std::lock_guard<std::mutex> guard(lock_);
if (licenseVariablesJson_.empty()) {
return std::nullopt;
}
return licenseVariablesJson_;
}
std::string AuthForgeClient::GetHwid() const {
const std::string mac = SafeMacAddress();
const std::string cpu = SafeCpuInfo();
const std::string disk = SafeDiskSerial();
const std::string material = "mac:" + mac + "|cpu:" + cpu + "|disk:" + disk;
return Sha256Hex(material);
}
std::string AuthForgeClient::SafeMacAddress() const {
try {
#ifdef _WIN32
ULONG size = 0;
if (GetAdaptersAddresses(AF_UNSPEC, GAA_FLAG_SKIP_ANYCAST | GAA_FLAG_SKIP_MULTICAST | GAA_FLAG_SKIP_DNS_SERVER, nullptr, nullptr, &size) != ERROR_BUFFER_OVERFLOW) {
return "mac-unavailable";
}
std::vector<unsigned char> buffer(size);
auto *addresses = reinterpret_cast<IP_ADAPTER_ADDRESSES *>(buffer.data());
const ULONG result = GetAdaptersAddresses(AF_UNSPEC, GAA_FLAG_SKIP_ANYCAST | GAA_FLAG_SKIP_MULTICAST | GAA_FLAG_SKIP_DNS_SERVER, nullptr, addresses, &size);
if (result != NO_ERROR) {
return "mac-unavailable";
}
for (IP_ADAPTER_ADDRESSES *entry = addresses; entry != nullptr; entry = entry->Next) {
if (entry->PhysicalAddressLength == 0) {
continue;
}
std::ostringstream oss;
for (ULONG i = 0; i < entry->PhysicalAddressLength; ++i) {
oss << std::hex << std::nouppercase;
oss.width(2);
oss.fill('0');
oss << static_cast<int>(entry->PhysicalAddress[i]);
}
const std::string mac = oss.str();
if (!mac.empty()) {
return mac;
}
}
return "mac-unavailable";
#elif defined(__linux__)
namespace fs = std::filesystem;
const fs::path netPath("/sys/class/net");
if (!fs::exists(netPath)) {
return "mac-unavailable";
}
for (const auto &entry : fs::directory_iterator(netPath)) {
const fs::path addressPath = entry.path() / "address";
if (!fs::exists(addressPath)) {
continue;
}
std::ifstream file(addressPath);
std::string mac;
std::getline(file, mac);
mac = ToLower(Trim(mac));
mac.erase(std::remove(mac.begin(), mac.end(), ':'), mac.end());
if (!mac.empty() && mac != "000000000000") {
return mac;
}
}
return "mac-unavailable";
#elif defined(__APPLE__)
struct ifaddrs *ifaddr = nullptr;
if (getifaddrs(&ifaddr) != 0 || ifaddr == nullptr) {
return "mac-unavailable";
}
std::string mac = "mac-unavailable";
for (struct ifaddrs *ifa = ifaddr; ifa != nullptr; ifa = ifa->ifa_next) {
if (ifa->ifa_addr == nullptr || (ifa->ifa_flags & IFF_LOOPBACK) != 0) {
continue;
}
if (ifa->ifa_addr->sa_family != AF_LINK) {
continue;
}
auto *sdl = reinterpret_cast<sockaddr_dl *>(ifa->ifa_addr);
const unsigned char *base = reinterpret_cast<const unsigned char *>(LLADDR(sdl));
if (sdl->sdl_alen <= 0) {
continue;
}
std::ostringstream oss;
for (int i = 0; i < sdl->sdl_alen; ++i) {
oss << std::hex << std::nouppercase;
oss.width(2);
oss.fill('0');
oss << static_cast<int>(base[i]);
}
mac = oss.str();
if (!mac.empty()) {
break;
}
}
freeifaddrs(ifaddr);
return mac;
#else
return "mac-unavailable";
#endif
} catch (...) {
return "mac-unavailable";
}
}
std::string AuthForgeClient::SafeCpuInfo() const {
try {
#ifdef _WIN32
int cpuInfo[4] = {0, 0, 0, 0};
__cpuid(cpuInfo, 0);
char vendor[13] = {};
std::memcpy(vendor + 0, &cpuInfo[1], 4);
std::memcpy(vendor + 4, &cpuInfo[3], 4);
std::memcpy(vendor + 8, &cpuInfo[2], 4);
SYSTEM_INFO sysInfo;
GetSystemInfo(&sysInfo);
std::ostringstream oss;
oss << vendor << "-" << static_cast<unsigned long>(sysInfo.dwProcessorType);
return oss.str();
#elif defined(__linux__)
std::ifstream cpuFile("/proc/cpuinfo");
if (!cpuFile.is_open()) {
return "cpu-unavailable";
}
std::string line;
while (std::getline(cpuFile, line)) {
if (line.rfind("model name", 0) == 0 || line.rfind("Hardware", 0) == 0 || line.rfind("Processor", 0) == 0) {
const std::size_t pos = line.find(':');
if (pos != std::string::npos) {
return Trim(line.substr(pos + 1));
}
}
}
cpuFile.clear();
cpuFile.seekg(0, std::ios::beg);
std::ostringstream all;
all << cpuFile.rdbuf();
const std::string compact = JoinAndCompactWhitespace(all.str());
return compact.empty() ? "cpu-unavailable" : compact.substr(0, std::min<std::size_t>(compact.size(), 256));
#elif defined(__APPLE__)
std::array<char, 256> buffer{};
std::size_t size = buffer.size();
if (sysctlbyname("machdep.cpu.brand_string", buffer.data(), &size, nullptr, 0) == 0 && size > 1) {
return std::string(buffer.data());
}
size = buffer.size();
if (sysctlbyname("hw.model", buffer.data(), &size, nullptr, 0) == 0 && size > 1) {
return std::string(buffer.data());
}
return "cpu-unavailable";
#else
return "cpu-unavailable";
#endif
} catch (...) {
return "cpu-unavailable";
}
}
std::string AuthForgeClient::SafeDiskSerial() const {
try {
#ifdef _WIN32
return RunCommand("wmic diskdrive get serialnumber");
#elif defined(__linux__)
return RunCommand("lsblk -ndo SERIAL");
#elif defined(__APPLE__)
return RunCommand("system_profiler SPStorageDataType");
#else
return "disk-unavailable";
#endif
} catch (...) {
return "disk-unavailable";
}
}
std::string AuthForgeClient::RunCommand(const std::string &command) const {
#ifdef _WIN32
const std::string wrapped = command + " 2>NUL";
FILE *pipe = _popen(wrapped.c_str(), "r");