-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAuthForgeClient.cs
More file actions
1265 lines (1147 loc) · 44.8 KB
/
AuthForgeClient.cs
File metadata and controls
1265 lines (1147 loc) · 44.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
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Net.Http;
using System.Net.NetworkInformation;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
using System.Text;
using System.Text.Encodings.Web;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.Crypto.Signers;
namespace AuthForge
{
public sealed class AuthForgeClient
{
private const string DefaultApiBaseUrl = "https://auth.authforge.cc";
private static readonly JsonSerializerOptions CompactJsonOptions = new JsonSerializerOptions
{
Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping,
};
private readonly object _lock = new object();
private readonly HttpClient _httpClient;
private readonly HashSet<string> _knownServerErrors = new HashSet<string>(StringComparer.Ordinal)
{
"invalid_app",
"invalid_key",
"expired",
"revoked",
"hwid_mismatch",
"no_credits",
"app_burn_cap_reached",
"blocked",
"rate_limited",
"replay_detected",
"app_disabled",
"session_expired",
"revoke_requires_session",
"bad_request",
"malformed_request",
"server_error",
"system_error",
};
private Thread? _heartbeatThread;
private bool _heartbeatStarted;
private bool _heartbeatStop;
private string? _licenseKey;
private string? _sessionToken;
private long? _sessionExpiresIn;
private string? _lastNonce;
private string? _rawPayloadB64;
private string? _signature;
private string? _keyId;
private Dictionary<string, object?>? _sessionData;
private Dictionary<string, object?>? _appVariables;
private Dictionary<string, object?>? _licenseVariables;
private bool _authenticated;
private readonly string _hwid;
public string AppId { get; }
public string AppSecret { get; }
public string PublicKey { get; }
/// <summary>
/// Full trust list of Ed25519 public keys. Always contains at least
/// one entry; the first is the primary (current) key, additional
/// entries are previous keys still trusted during a rotation window.
/// </summary>
public IReadOnlyList<string> PublicKeys { get; }
public string HeartbeatMode { get; }
public int HeartbeatInterval { get; }
public string ApiBaseUrl { get; }
public Action<string, Exception?>? OnFailure { get; }
public int RequestTimeout { get; }
/// <summary>
/// Requested session token lifetime (seconds) sent to /auth/validate.
/// <c>null</c> (or <= 0) means "let the server pick its default" (24h today).
/// The server clamps to [3600, 604800]; out-of-range values are silently clamped.
/// Heartbeats refresh the token while preserving the requested lifetime.
/// </summary>
public int? TtlSeconds { get; }
private readonly IReadOnlyList<Ed25519PublicKeyParameters> _verifyPublicKeys;
/// <summary>
/// Single-key constructor for backward compatibility. Forwards to the
/// rotation-aware overload with a single-entry trust list.
/// </summary>
public AuthForgeClient(
string appId,
string appSecret,
string publicKey,
string heartbeatMode,
int heartbeatInterval = 900,
string apiBaseUrl = DefaultApiBaseUrl,
Action<string, Exception?>? onFailure = null,
int requestTimeout = 15,
int? ttlSeconds = null,
string? hwidOverride = null)
: this(
appId,
appSecret,
NormalizePublicKeys(publicKey),
heartbeatMode,
heartbeatInterval,
apiBaseUrl,
onFailure,
requestTimeout,
ttlSeconds,
hwidOverride)
{
}
/// <summary>
/// Rotation-aware constructor. Pass the current public key first,
/// followed by any previous keys you want to remain trusted during a
/// cutover. Verification accepts a signature that matches *any* key.
/// </summary>
public AuthForgeClient(
string appId,
string appSecret,
IEnumerable<string> publicKeys,
string heartbeatMode,
int heartbeatInterval = 900,
string apiBaseUrl = DefaultApiBaseUrl,
Action<string, Exception?>? onFailure = null,
int requestTimeout = 15,
int? ttlSeconds = null,
string? hwidOverride = null)
{
if (string.IsNullOrEmpty(appId))
{
throw new ArgumentException("app_id must be a non-empty string", nameof(appId));
}
if (string.IsNullOrEmpty(appSecret))
{
throw new ArgumentException("app_secret must be a non-empty string", nameof(appSecret));
}
var keyList = (publicKeys ?? Array.Empty<string>())
.Where(k => !string.IsNullOrWhiteSpace(k))
.Select(k => k.Trim())
.Distinct(StringComparer.Ordinal)
.ToList();
if (keyList.Count == 0)
{
throw new ArgumentException(
"publicKeys must contain at least one non-empty base64 string",
nameof(publicKeys));
}
var mode = (heartbeatMode ?? string.Empty).ToUpperInvariant();
if (mode != "LOCAL" && mode != "SERVER")
{
throw new ArgumentException("heartbeat_mode must be LOCAL or SERVER", nameof(heartbeatMode));
}
if (heartbeatInterval < 10)
{
throw new ArgumentException("heartbeat_interval must be >= 10", nameof(heartbeatInterval));
}
AppId = appId;
AppSecret = appSecret;
PublicKeys = keyList;
PublicKey = keyList[0];
HeartbeatMode = mode;
HeartbeatInterval = heartbeatInterval;
ApiBaseUrl = (apiBaseUrl ?? string.Empty).TrimEnd('/');
OnFailure = onFailure;
RequestTimeout = requestTimeout;
TtlSeconds = ttlSeconds.HasValue && ttlSeconds.Value > 0 ? ttlSeconds : null;
_httpClient = new HttpClient
{
Timeout = TimeSpan.FromSeconds(RequestTimeout),
};
var verifyKeys = new List<Ed25519PublicKeyParameters>(keyList.Count);
foreach (var key in keyList)
{
byte[] publicKeyBytes;
try
{
publicKeyBytes = Convert.FromBase64String(key);
}
catch (FormatException ex)
{
throw new ArgumentException("public_key must be valid base64", nameof(publicKeys), ex);
}
if (publicKeyBytes.Length != 32)
{
throw new ArgumentException(
"public_key must be 32 bytes (base64 Ed25519 raw key)",
nameof(publicKeys));
}
verifyKeys.Add(new Ed25519PublicKeyParameters(publicKeyBytes, 0));
}
_verifyPublicKeys = verifyKeys;
_hwid = ResolveHwid(hwidOverride);
}
/// <summary>
/// Splits the historical single-string <c>publicKey</c> argument into
/// the canonical list form. A comma separator is honoured so callers
/// can plumb a trust list through environment variables.
/// </summary>
private static IEnumerable<string> NormalizePublicKeys(string publicKey)
{
if (string.IsNullOrWhiteSpace(publicKey))
{
return Array.Empty<string>();
}
return publicKey.Contains(',')
? publicKey.Split(',')
: new[] { publicKey };
}
public bool Login(string licenseKey)
{
if (string.IsNullOrEmpty(licenseKey))
{
throw new ArgumentException("license_key must be a non-empty string", nameof(licenseKey));
}
try
{
ValidateAndStore(licenseKey);
StartHeartbeatOnce();
return true;
}
catch (Exception ex)
{
Fail("login_failed", ex);
return false;
}
}
/// <summary>
/// Performs the same <c>/auth/validate</c> request and Ed25519 verification as <see cref="Login"/>,
/// without updating client session state or starting the heartbeat thread.
/// </summary>
public ValidateLicenseResult ValidateLicense(string licenseKey)
{
if (string.IsNullOrEmpty(licenseKey))
{
throw new ArgumentException("license_key must be a non-empty string", nameof(licenseKey));
}
try
{
var body = new Dictionary<string, object?>
{
["appId"] = AppId,
["appSecret"] = AppSecret,
["licenseKey"] = licenseKey,
["hwid"] = _hwid,
["nonce"] = GenerateNonce(),
};
if (TtlSeconds.HasValue)
{
body["ttlSeconds"] = TtlSeconds.Value;
}
var responseObj = PostJson("/auth/validate", body, skipFailureOnNetwork: true);
var expectedNonce = body.TryGetValue("nonce", out var usedNonce) ? (usedNonce?.ToString() ?? string.Empty) : string.Empty;
var parsed = ParseSignedValidateResponse(responseObj, expectedNonce);
var sessionData = ConvertToObjectMap(parsed.PayloadJson);
var appVars = parsed.PayloadJson.TryGetValue("appVariables", out var appVarsElement)
? ConvertJsonElementObject(appVarsElement)
: null;
var licenseVars = parsed.PayloadJson.TryGetValue("licenseVariables", out var licenseVarsElement)
? ConvertJsonElementObject(licenseVarsElement)
: null;
return new ValidateLicenseResult
{
Valid = true,
SessionToken = parsed.SessionToken,
ExpiresIn = parsed.ExpiresIn,
SessionData = new Dictionary<string, object?>(sessionData, StringComparer.Ordinal),
AppVariables = appVars is null ? null : new Dictionary<string, object?>(appVars, StringComparer.Ordinal),
LicenseVariables = licenseVars is null ? null : new Dictionary<string, object?>(licenseVars, StringComparer.Ordinal),
KeyId = parsed.KeyId,
SessionExpiresAt = parsed.SessionExpiresAt,
LicenseExpirationPresent = parsed.LicenseExpirationPresent,
LicenseExpiresAt = parsed.LicenseExpiresAt,
MaxHwidSlots = parsed.MaxHwidSlots,
HwidCount = parsed.HwidCount,
LicenseLabel = parsed.LicenseLabel,
};
}
catch (Exception ex)
{
return new ValidateLicenseResult
{
Valid = false,
ErrorCode = ex.Message,
Error = ex,
};
}
}
public Dictionary<string, object?> SelfBan(
string? licenseKey = null,
string? sessionToken = null,
bool revokeLicense = true,
bool blacklistHwid = true,
bool blacklistIp = true)
{
string? currentSessionToken;
string? currentLicenseKey;
string hwid;
lock (_lock)
{
currentSessionToken = _sessionToken;
currentLicenseKey = _licenseKey;
hwid = _hwid;
}
var resolvedSessionToken = string.IsNullOrWhiteSpace(sessionToken)
? currentSessionToken
: sessionToken.Trim();
if (!string.IsNullOrWhiteSpace(resolvedSessionToken))
{
var sessionBody = new Dictionary<string, object?>
{
["appId"] = AppId,
["sessionToken"] = resolvedSessionToken,
["hwid"] = hwid,
["revokeLicense"] = revokeLicense,
["blacklistHwid"] = blacklistHwid,
["blacklistIp"] = blacklistIp,
};
var responseObj = PostJson("/auth/selfban", sessionBody);
responseObj.TryGetValue("status", out var statusElement);
if (!IsSuccessStatus(statusElement))
{
throw new ArgumentException(ExtractServerError(responseObj));
}
return ConvertToObjectMap(responseObj);
}
var resolvedLicenseKey = string.IsNullOrWhiteSpace(licenseKey)
? currentLicenseKey
: licenseKey.Trim();
if (string.IsNullOrWhiteSpace(resolvedLicenseKey))
{
throw new ArgumentException("missing_license_key");
}
var preSessionBody = new Dictionary<string, object?>
{
["appId"] = AppId,
["appSecret"] = AppSecret,
["licenseKey"] = resolvedLicenseKey,
["hwid"] = hwid,
["nonce"] = GenerateNonce(),
// Pre-session self-ban cannot revoke licenses.
["revokeLicense"] = false,
["blacklistHwid"] = blacklistHwid,
["blacklistIp"] = blacklistIp,
};
var preSessionResponse = PostJson("/auth/selfban", preSessionBody);
preSessionResponse.TryGetValue("status", out var preSessionStatus);
if (!IsSuccessStatus(preSessionStatus))
{
throw new ArgumentException(ExtractServerError(preSessionResponse));
}
return ConvertToObjectMap(preSessionResponse);
}
private void StartHeartbeatOnce()
{
lock (_lock)
{
if (_heartbeatStarted)
{
return;
}
_heartbeatStop = false;
_heartbeatStarted = true;
_heartbeatThread = new Thread(HeartbeatLoop)
{
Name = "AuthForgeHeartbeat",
IsBackground = true,
};
_heartbeatThread.Start();
}
}
private void HeartbeatLoop()
{
while (true)
{
Thread.Sleep(TimeSpan.FromSeconds(HeartbeatInterval));
lock (_lock)
{
if (_heartbeatStop)
{
break;
}
}
try
{
if (HeartbeatMode == "SERVER")
{
ServerHeartbeat();
}
else
{
LocalHeartbeat();
}
}
catch (Exception ex)
{
Fail("heartbeat_failed", ex);
break;
}
}
}
private void ServerHeartbeat()
{
string? sessionToken;
string hwid;
lock (_lock)
{
sessionToken = _sessionToken;
hwid = _hwid;
}
if (string.IsNullOrEmpty(sessionToken))
{
throw new InvalidOperationException("missing_session_token");
}
var body = new Dictionary<string, object?>
{
["appId"] = AppId,
["sessionToken"] = sessionToken,
["nonce"] = GenerateNonce(),
["hwid"] = hwid,
};
var responseObj = PostJson("/auth/heartbeat", body);
var expectedNonce = body.TryGetValue("nonce", out var usedNonce) ? (usedNonce?.ToString() ?? string.Empty) : string.Empty;
ApplySignedResponse(responseObj, expectedNonce, null, "heartbeat");
}
private void LocalHeartbeat()
{
string? rawPayloadB64;
string? signature;
long? expiresIn;
lock (_lock)
{
rawPayloadB64 = _rawPayloadB64;
signature = _signature;
expiresIn = _sessionExpiresIn;
}
if (string.IsNullOrEmpty(rawPayloadB64) || string.IsNullOrEmpty(signature))
{
throw new InvalidOperationException("missing_local_verification_state");
}
VerifySignature(rawPayloadB64, signature);
if (expiresIn is null)
{
throw new InvalidOperationException("missing_session_expiry");
}
var now = DateTimeOffset.UtcNow.ToUnixTimeSeconds();
if (now < expiresIn.Value)
{
return;
}
throw new InvalidOperationException("session_expired");
}
private void ValidateAndStore(string licenseKey)
{
var body = new Dictionary<string, object?>
{
["appId"] = AppId,
["appSecret"] = AppSecret,
["licenseKey"] = licenseKey,
["hwid"] = _hwid,
["nonce"] = GenerateNonce(),
};
if (TtlSeconds.HasValue)
{
body["ttlSeconds"] = TtlSeconds.Value;
}
var responseObj = PostJson("/auth/validate", body);
var expectedNonce = body.TryGetValue("nonce", out var usedNonce) ? (usedNonce?.ToString() ?? string.Empty) : string.Empty;
ApplySignedResponse(responseObj, expectedNonce, licenseKey, "validate");
}
private sealed class ParsedValidateSession
{
public string SessionToken { get; set; } = string.Empty;
public long ExpiresIn { get; set; }
public string RawPayloadB64 { get; set; } = string.Empty;
public string Signature { get; set; } = string.Empty;
public string? KeyId { get; set; }
public string? SessionExpiresAt { get; set; }
public bool LicenseExpirationPresent { get; set; }
public string? LicenseExpiresAt { get; set; }
public int? MaxHwidSlots { get; set; }
public int? HwidCount { get; set; }
public string? LicenseLabel { get; set; }
public Dictionary<string, JsonElement> PayloadJson { get; set; } = new(StringComparer.Ordinal);
}
private ParsedValidateSession ParseSignedValidateResponse(
Dictionary<string, JsonElement> responseObj,
string expectedNonce)
{
responseObj.TryGetValue("status", out var statusElement);
if (!IsSuccessStatus(statusElement))
{
throw new ArgumentException(ExtractServerError(responseObj));
}
var rawPayloadB64 = RequireStr(responseObj, "payload");
var signature = RequireStr(responseObj, "signature");
var payloadJson = DecodePayloadJson(rawPayloadB64);
var receivedNonce = payloadJson.TryGetValue("nonce", out var nonceElement)
? (nonceElement.ToString() ?? string.Empty).Trim()
: string.Empty;
if (!string.Equals(receivedNonce, expectedNonce, StringComparison.Ordinal))
{
throw new ArgumentException("nonce_mismatch");
}
VerifySignature(rawPayloadB64, signature);
var sessionToken = payloadJson.TryGetValue("sessionToken", out var sessionTokenElement)
? (sessionTokenElement.ToString() ?? string.Empty).Trim()
: string.Empty;
if (string.IsNullOrEmpty(sessionToken))
{
throw new ArgumentException("missing_sessionToken");
}
var expiresFromToken = ExtractExpiresInFromSessionToken(sessionToken);
long? expiresFromPayload = null;
if (payloadJson.TryGetValue("expiresIn", out var expiresElement) && expiresElement.ValueKind != JsonValueKind.Null)
{
expiresFromPayload = ConvertToInt64(expiresElement);
}
var expiresIn = expiresFromToken ?? expiresFromPayload;
if (expiresIn is null)
{
throw new ArgumentException("missing_expiresIn");
}
string? sessionExpiresAt = null;
if (payloadJson.TryGetValue("sessionExpiresAt", out var sea) && sea.ValueKind == JsonValueKind.String)
{
sessionExpiresAt = sea.GetString();
}
var licenseExpirationPresent = payloadJson.TryGetValue("licenseExpiresAt", out var lee);
string? licenseExpiresAt = null;
if (licenseExpirationPresent)
{
licenseExpiresAt = lee.ValueKind == JsonValueKind.Null ? null : lee.GetString();
}
int? maxHwidSlots = null;
if (payloadJson.TryGetValue("maxHwidSlots", out var mh) && mh.ValueKind != JsonValueKind.Null)
{
maxHwidSlots = ConvertToInt32Nullable(mh);
}
int? hwidCount = null;
if (payloadJson.TryGetValue("hwidCount", out var hc) && hc.ValueKind != JsonValueKind.Null)
{
hwidCount = ConvertToInt32Nullable(hc);
}
string? licenseLabel = null;
if (payloadJson.TryGetValue("licenseLabel", out var ll) && ll.ValueKind == JsonValueKind.String)
{
licenseLabel = ll.GetString();
}
return new ParsedValidateSession
{
SessionToken = sessionToken,
ExpiresIn = expiresIn.Value,
RawPayloadB64 = rawPayloadB64,
Signature = signature,
KeyId = responseObj.TryGetValue("keyId", out var keyIdElement) ? keyIdElement.ToString() : null,
SessionExpiresAt = sessionExpiresAt,
LicenseExpirationPresent = licenseExpirationPresent,
LicenseExpiresAt = licenseExpiresAt,
MaxHwidSlots = maxHwidSlots,
HwidCount = hwidCount,
LicenseLabel = licenseLabel,
PayloadJson = payloadJson,
};
}
private void ApplySignedResponse(
Dictionary<string, JsonElement> responseObj,
string expectedNonce,
string? licenseKey,
string context)
{
var parsed = ParseSignedValidateResponse(responseObj, expectedNonce);
_ = context;
lock (_lock)
{
if (licenseKey is not null)
{
_licenseKey = licenseKey;
}
_sessionToken = parsed.SessionToken;
_sessionExpiresIn = parsed.ExpiresIn;
_lastNonce = expectedNonce;
_rawPayloadB64 = parsed.RawPayloadB64;
_signature = parsed.Signature;
_keyId = parsed.KeyId;
_sessionData = ConvertToObjectMap(parsed.PayloadJson);
_appVariables = parsed.PayloadJson.TryGetValue("appVariables", out var appVarsElement)
? ConvertJsonElementObject(appVarsElement)
: null;
_licenseVariables = parsed.PayloadJson.TryGetValue("licenseVariables", out var licenseVarsElement)
? ConvertJsonElementObject(licenseVarsElement)
: null;
_authenticated = true;
}
}
private Dictionary<string, JsonElement> PostJson(string path, Dictionary<string, object?> data, bool skipFailureOnNetwork = false)
{
var url = $"{ApiBaseUrl}{path}";
var body = new Dictionary<string, object?>(data, StringComparer.Ordinal);
var rateRetryDelays = new[] { 2, 5 };
var networkRetried = false;
var rateAttempt = 0;
while (true)
{
if (rateAttempt > 0 && body.ContainsKey("nonce"))
{
body["nonce"] = GenerateNonce();
data["nonce"] = body["nonce"];
}
var payloadBytes = JsonSerializer.SerializeToUtf8Bytes(body, CompactJsonOptions);
using var request = new HttpRequestMessage(HttpMethod.Post, url)
{
Content = new ByteArrayContent(payloadBytes),
};
request.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");
try
{
using var response = _httpClient.SendAsync(request).GetAwaiter().GetResult();
var statusCode = (int)response.StatusCode;
var rawResponse = response.Content.ReadAsStringAsync().GetAwaiter().GetResult();
Dictionary<string, JsonElement> parsed;
try
{
parsed = ParseResponseObject(rawResponse);
}
catch
{
if (statusCode >= 400)
{
throw new InvalidOperationException($"http_error_{statusCode}");
}
throw;
}
var isRateLimited = statusCode == 429 || ExtractServerError(parsed) == "rate_limited";
if (isRateLimited && rateAttempt < rateRetryDelays.Length)
{
Thread.Sleep(TimeSpan.FromSeconds(rateRetryDelays[rateAttempt]));
rateAttempt++;
continue;
}
return parsed;
}
catch (HttpRequestException ex)
{
if (!networkRetried)
{
networkRetried = true;
Thread.Sleep(TimeSpan.FromSeconds(2));
continue;
}
if (!skipFailureOnNetwork)
{
Fail("network_error", ex);
}
throw new InvalidOperationException($"url_error: {ex.Message}", ex);
}
catch (TaskCanceledException ex)
{
if (!networkRetried)
{
networkRetried = true;
Thread.Sleep(TimeSpan.FromSeconds(2));
continue;
}
if (!skipFailureOnNetwork)
{
Fail("network_error", ex);
}
throw new InvalidOperationException($"url_error: {ex.Message}", ex);
}
}
}
private static Dictionary<string, JsonElement> ParseResponseObject(string rawResponse)
{
JsonDocument document;
try
{
document = JsonDocument.Parse(rawResponse);
}
catch (JsonException ex)
{
throw new ArgumentException("invalid_json_response", ex);
}
using (document)
{
if (document.RootElement.ValueKind != JsonValueKind.Object)
{
throw new ArgumentException("response_not_json_object");
}
var result = new Dictionary<string, JsonElement>(StringComparer.Ordinal);
foreach (var property in document.RootElement.EnumerateObject())
{
result[property.Name] = property.Value.Clone();
}
return result;
}
}
private string GetHwid()
{
var mac = SafeMacAddress();
var cpu = SafeCpuInfo();
var disk = SafeDiskSerial();
var material = $"mac:{mac}|cpu:{cpu}|disk:{disk}";
byte[] hash;
using (var sha256 = SHA256.Create())
{
hash = sha256.ComputeHash(Encoding.UTF8.GetBytes(material));
}
return ToHexLower(hash);
}
private string ResolveHwid(string? hwidOverride)
{
var trimmed = (hwidOverride ?? string.Empty).Trim();
return trimmed.Length > 0 ? trimmed : GetHwid();
}
private string SafeMacAddress()
{
try
{
foreach (var networkInterface in NetworkInterface.GetAllNetworkInterfaces())
{
var bytes = networkInterface.GetPhysicalAddress().GetAddressBytes();
if (bytes.Length > 0)
{
return BitConverter.ToString(bytes).Replace("-", string.Empty).ToLowerInvariant();
}
}
return "mac-unavailable";
}
catch
{
return "mac-unavailable";
}
}
private string SafeCpuInfo()
{
try
{
var value = $"{Environment.ProcessorCount}-{RuntimeInformation.ProcessArchitecture}";
return string.IsNullOrWhiteSpace(value) ? "cpu-unavailable" : value;
}
catch
{
return "cpu-unavailable";
}
}
private string SafeDiskSerial()
{
var system = RuntimeInformation.OSDescription.ToLowerInvariant();
try
{
if (system.Contains("windows", StringComparison.Ordinal))
{
return RunCommand("wmic", "diskdrive get serialnumber");
}
if (system.Contains("linux", StringComparison.Ordinal))
{
var outText = RunCommand("lsblk", "-ndo SERIAL");
if (!string.IsNullOrWhiteSpace(outText))
{
return outText;
}
return RunCommand("udevadm", "info --query=property --name=sda");
}
if (system.Contains("darwin", StringComparison.Ordinal) || RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
{
return RunCommand("system_profiler", "SPStorageDataType");
}
}
catch
{
return "disk-unavailable";
}
return "disk-unavailable";
}
private static string RunCommand(string fileName, string arguments)
{
try
{
var startInfo = new ProcessStartInfo
{
FileName = fileName,
Arguments = arguments,
RedirectStandardOutput = true,
RedirectStandardError = true,
UseShellExecute = false,
CreateNoWindow = true,
};
using var process = Process.Start(startInfo);
if (process is null)
{
return "unavailable";
}
if (!process.WaitForExit(2000))
{
try
{
process.Kill();
}
catch
{
// Ignore kill failures and return unavailable.
}
return "unavailable";
}
var output = process.StandardOutput.ReadToEnd();
var cleaned = string.Join(" ", (output ?? string.Empty).Split((char[]?)null, StringSplitOptions.RemoveEmptyEntries));
return string.IsNullOrEmpty(cleaned) ? "empty" : (cleaned.Length > 256 ? cleaned.Substring(0, 256) : cleaned);
}
catch
{
return "unavailable";
}
}
private static Dictionary<string, JsonElement> DecodePayloadJson(string payloadB64)
{
var payloadBytes = DecodeBase64Any(payloadB64);
JsonDocument doc;
try
{
doc = JsonDocument.Parse(payloadBytes);
}
catch (Exception ex)
{
throw new ArgumentException("invalid_payload_json", ex);
}
using (doc)
{
if (doc.RootElement.ValueKind != JsonValueKind.Object)
{
throw new ArgumentException("payload_not_json_object");
}
var result = new Dictionary<string, JsonElement>(StringComparer.Ordinal);
foreach (var property in doc.RootElement.EnumerateObject())
{
result[property.Name] = property.Value.Clone();
}
return result;
}
}
private static byte[] DecodeBase64Any(string value)
{
var padded = AddBase64Padding(value);
try
{
return Convert.FromBase64String(padded);
}
catch
{
var normalized = padded.Replace('-', '+').Replace('_', '/');
return Convert.FromBase64String(normalized);
}
}
private static JsonDocument? TryDecodeSessionTokenBody(string sessionToken)
{
var parts = sessionToken.Split('.');
if (parts.Length < 2)
{
return null;
}
var padded = AddBase64Padding(parts[0]);
try
{
var normalized = padded.Replace('-', '+').Replace('_', '/');
var decoded = Convert.FromBase64String(normalized);
var doc = JsonDocument.Parse(decoded);
if (doc.RootElement.ValueKind != JsonValueKind.Object)
{
doc.Dispose();
return null;
}
return doc;
}
catch
{
return null;
}
}
private static long? ExtractExpiresInFromSessionToken(string sessionToken)
{
using var doc = TryDecodeSessionTokenBody(sessionToken);
if (doc is null)
{
return null;
}
if (!doc.RootElement.TryGetProperty("exp", out var expiresInElement))
{
return null;
}
try
{
return ConvertToInt64(expiresInElement);
}
catch
{
return null;
}
}
private static string AddBase64Padding(string text)
{
var remainder = text.Length % 4;
if (remainder == 0)
{
return text;
}
return text + new string('=', 4 - remainder);
}
private void VerifySignature(string rawPayloadB64, string signature)
{
byte[] signatureBytes;
try
{