-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathauthforge.mjs
More file actions
1331 lines (1223 loc) · 43.2 KB
/
Copy pathauthforge.mjs
File metadata and controls
1331 lines (1223 loc) · 43.2 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
import { createHash, createPublicKey, randomBytes, verify } from "node:crypto";
import { readFileSync, writeFileSync } from "node:fs";
import https from "node:https";
import os from "node:os";
import { clearInterval as clearIntervalTimer, setInterval as setIntervalTimer } from "node:timers";
const DEFAULT_API_BASE_URL = "https://auth.authforge.cc";
const RATE_LIMIT_RETRY_DELAYS = [2, 5];
const NETWORK_RETRY_DELAY = 2;
const KNOWN_SERVER_ERRORS = new Set([
"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",
"system_error",
]);
const SUCCESS_STATUSES = new Set(["ok", "success", "valid", "true", "1"]);
function sleepSeconds(seconds) {
return new Promise((resolve) => {
setTimeout(resolve, seconds * 1000);
});
}
function cloneObject(value) {
if (value && typeof value === "object" && !Array.isArray(value)) {
return { ...value };
}
return null;
}
function toBase64Url(rawBase64) {
return rawBase64.replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/g, "");
}
function createEd25519PublicKey(rawBase64) {
return createPublicKey({
key: {
crv: "Ed25519",
kty: "OKP",
x: toBase64Url(rawBase64),
},
format: "jwk",
});
}
/**
* Normalize the public-key argument into a non-empty array of base64 strings.
*
* Accepts:
* - "abc..." (single key — historical contract)
* - ["abc...", "def..."] (key set — current first, previous(es) after)
* - "abc...,def..." (legacy comma-separated for env-var convenience)
*
* Returns the trimmed list of keys. Throws if no usable key is present so
* the constructor can surface "publicKey must be a non-empty string" errors
* unchanged.
*/
function normalizePublicKeyList(input) {
const out = [];
const push = (value) => {
if (typeof value !== "string") return;
const trimmed = value.trim();
if (trimmed) out.push(trimmed);
};
if (Array.isArray(input)) {
for (const entry of input) push(entry);
} else if (typeof input === "string") {
if (input.includes(",")) {
for (const entry of input.split(",")) push(entry);
} else {
push(input);
}
}
return out;
}
/**
* Verify a payload signature against one or more trusted Ed25519 public keys.
*
* Accepting a list lets a deployment publish a new public key while clients
* are still pinned to the previous one — the SDK trusts both during the
* rotation window and falls back automatically when the server-side key
* changes. Returns `true` on the first match.
*/
export function verifyPayloadSignatureEd25519(payloadBase64, signatureBase64, publicKeyOrKeys) {
const keys = normalizePublicKeyList(publicKeyOrKeys);
if (keys.length === 0) return false;
for (const key of keys) {
try {
const isValid = verify(
null,
Buffer.from(payloadBase64, "utf8"),
createEd25519PublicKey(key),
Buffer.from(signatureBase64, "base64"),
);
if (isValid) return true;
} catch {
// Malformed key — try the next one rather than failing the whole set.
}
}
return false;
}
// ---------------------------------------------------------------------------
// Offline license files (`.authforge`)
//
// A cloud-minted, Ed25519-signed document for machines that never phone home.
// This is a SEPARATE mode from the grace period: the grace period continues a
// signed session after one online activation, while an offline file is
// verified locally with only the app public key and the machine HWID. Nothing
// here performs network I/O or starts online check-ins.
// ---------------------------------------------------------------------------
const OFFLINE_LICENSE_FILE_VERSION = 1;
const OFFLINE_BEGIN_LICENSE = "-----BEGIN AUTHFORGE LICENSE-----";
const OFFLINE_END_LICENSE = "-----END AUTHFORGE LICENSE-----";
const OFFLINE_BEGIN_SIGNATURE = "-----BEGIN AUTHFORGE SIGNATURE-----";
const OFFLINE_END_SIGNATURE = "-----END AUTHFORGE SIGNATURE-----";
const OFFLINE_BASE64_RE = /^[A-Za-z0-9+/]+={0,2}$/;
const ARMOR_LINE_WIDTH = 64;
// Activation requests (`.authforge-request`): unsigned transport for a HWID so
// the operator can mint a bound `.authforge` file without the customer pasting
// a raw string. Distinct markers from BEGIN AUTHFORGE LICENSE. Not signed;
// the Checksum header is the only integrity check. Keep SDK_TAG in sync with
// package.json version.
const ACTIVATION_REQUEST_VERSION = 1;
const ACTIVATION_REQUEST_TYP = "authforge-activation-request";
const BEGIN_ACTIVATION_REQUEST = "-----BEGIN AUTHFORGE ACTIVATION REQUEST-----";
const END_ACTIVATION_REQUEST = "-----END AUTHFORGE ACTIVATION REQUEST-----";
const SDK_TAG = "node/1.3.1";
const MAX_REQUEST_HWID = 256;
const MAX_REQUEST_MACHINE_NAME = 128;
const MAX_REQUEST_OS = 64;
const MAX_REQUEST_SDK = 64;
const MAX_REQUEST_LICENSE_KEY = 64;
function clipRequestField(value, max) {
if (typeof value !== "string" || value.length === 0) return "";
return value.length <= max ? value : value.slice(0, max);
}
function jsonEscapeRequest(value) {
let out = "";
for (let i = 0; i < value.length; i++) {
const code = value.charCodeAt(i);
const ch = value[i];
switch (ch) {
case "\\":
out += "\\\\";
break;
case '"':
out += '\\"';
break;
case "\b":
out += "\\b";
break;
case "\f":
out += "\\f";
break;
case "\n":
out += "\\n";
break;
case "\r":
out += "\\r";
break;
case "\t":
out += "\\t";
break;
default:
if (code < 0x20) {
out += `\\u00${code.toString(16).padStart(2, "0")}`;
} else {
out += ch;
}
}
}
return `"${out}"`;
}
function wrapArmor64(value) {
const lines = [];
for (let i = 0; i < value.length; i += ARMOR_LINE_WIDTH) {
lines.push(value.slice(i, i + ARMOR_LINE_WIDTH));
}
return lines.join("\n");
}
function canonicalActivationRequestJson({ appId, hwid, createdAt, machineName, os: osName, sdk, licenseKey }) {
const parts = [
`"v":${ACTIVATION_REQUEST_VERSION}`,
`"typ":${jsonEscapeRequest(ACTIVATION_REQUEST_TYP)}`,
`"appId":${jsonEscapeRequest(appId)}`,
`"hwid":${jsonEscapeRequest(clipRequestField(hwid, MAX_REQUEST_HWID))}`,
`"createdAt":${jsonEscapeRequest(createdAt)}`,
];
if (machineName) parts.push(`"machineName":${jsonEscapeRequest(clipRequestField(machineName, MAX_REQUEST_MACHINE_NAME))}`);
if (osName) parts.push(`"os":${jsonEscapeRequest(clipRequestField(osName, MAX_REQUEST_OS))}`);
if (sdk) parts.push(`"sdk":${jsonEscapeRequest(clipRequestField(sdk, MAX_REQUEST_SDK))}`);
if (licenseKey) parts.push(`"licenseKey":${jsonEscapeRequest(clipRequestField(licenseKey, MAX_REQUEST_LICENSE_KEY))}`);
return `{${parts.join(",")}}`;
}
function detectOsLabel() {
switch (process.platform) {
case "win32":
return clipRequestField(`Windows ${os.release()}`, MAX_REQUEST_OS);
case "darwin":
return clipRequestField(`macOS ${os.release()}`, MAX_REQUEST_OS);
default:
return clipRequestField(`${os.type()} ${os.release()}`, MAX_REQUEST_OS);
}
}
/**
* Build armored `.authforge-request` text from explicit fields. Exported so
* the vector generator and tests share one encoder with the client.
*/
export function formatActivationRequest({
appId,
hwid,
createdAt,
machineName,
os: osName,
sdk,
licenseKey,
}) {
const json = canonicalActivationRequestJson({
appId,
hwid,
createdAt,
machineName,
os: osName,
sdk,
licenseKey,
});
const payloadBase64 = Buffer.from(json, "utf8").toString("base64");
const checksum = createHash("sha256").update(payloadBase64, "utf8").digest("hex").slice(0, 16);
const clean = (value) => String(value).replace(/[\r\n]+/g, " ").trim();
return [
BEGIN_ACTIVATION_REQUEST,
`Version: ${ACTIVATION_REQUEST_VERSION}`,
`App-Id: ${clean(appId)}`,
`Checksum: ${checksum}`,
"",
wrapArmor64(payloadBase64),
END_ACTIVATION_REQUEST,
"",
].join("\n");
}
export const offlineLicenseErrors = [
"bad_armor",
"bad_signature",
"unsupported_version",
"malformed_payload",
"wrong_app",
"expired",
"hwid_mismatch",
];
/**
* Parse armored `.authforge` text into `{ headers, payloadBase64, signatureBase64 }`
* or `null` when the armor is malformed. Tolerates CRLF, a UTF-8 BOM, any
* re-wrapping of the base64 body and text before/after the armor.
* `payloadBase64` is exactly the string the signature covers.
*/
export function parseLicenseFile(text) {
if (typeof text !== "string") return null;
const lines = text.replace(/^\uFEFF/, "").replace(/\r\n?/g, "\n").split("\n");
const beginIdx = lines.findIndex((l) => l.trim() === OFFLINE_BEGIN_LICENSE);
if (beginIdx === -1) return null;
const endIdx = lines.findIndex((l, i) => i > beginIdx && l.trim() === OFFLINE_END_LICENSE);
if (endIdx === -1) return null;
const sigBeginIdx = lines.findIndex((l, i) => i > endIdx && l.trim() === OFFLINE_BEGIN_SIGNATURE);
if (sigBeginIdx === -1) return null;
const sigEndIdx = lines.findIndex((l, i) => i > sigBeginIdx && l.trim() === OFFLINE_END_SIGNATURE);
if (sigEndIdx === -1) return null;
const block = lines.slice(beginIdx + 1, endIdx);
const blankIdx = block.findIndex((l) => l.trim() === "");
if (blankIdx === -1) return null;
const headers = {};
for (const raw of block.slice(0, blankIdx)) {
const line = raw.trim();
const colon = line.indexOf(":");
if (colon <= 0) return null;
headers[line.slice(0, colon).trim()] = line.slice(colon + 1).trim();
}
const payloadBase64 = block.slice(blankIdx + 1).join("").replace(/\s+/g, "");
const signatureBase64 = lines.slice(sigBeginIdx + 1, sigEndIdx).join("").replace(/\s+/g, "");
if (!payloadBase64 || !OFFLINE_BASE64_RE.test(payloadBase64)) return null;
if (!signatureBase64 || !OFFLINE_BASE64_RE.test(signatureBase64)) return null;
return { headers, payloadBase64, signatureBase64 };
}
function isPlainObject(value) {
return Boolean(value) && typeof value === "object" && !Array.isArray(value);
}
function isStringArray(value) {
return Array.isArray(value) && value.length > 0 && value.every((v) => typeof v === "string" && v.length > 0);
}
function validateOfflinePayloadShape(payload) {
if (payload.typ !== "authforge-license") return false;
for (const field of ["appId", "licenseKey", "jti", "kid", "issuedAt"]) {
if (typeof payload[field] !== "string" || payload[field].length === 0) return false;
}
if (payload.expiresAt !== null && (typeof payload.expiresAt !== "string" || payload.expiresAt.length === 0)) {
return false;
}
if (!isPlainObject(payload.hwid)) return false;
if (payload.hwid.mode === "bound") {
if (!isStringArray(payload.hwid.hwids)) return false;
} else if (payload.hwid.mode !== "any") {
return false;
}
return true;
}
/**
* Verify an offline `.authforge` license file with NO network access.
*
* Check order (fixed across every SDK): bad_armor -> bad_signature ->
* unsupported_version -> malformed_payload -> wrong_app -> expired ->
* hwid_mismatch. The signature is checked before the payload JSON is
* decoded so a forged file never reaches the parser.
*
* @param {object} params
* @param {string} params.file Armored file text.
* @param {string} params.appId Your app id; must match the payload.
* @param {string|readonly string[]} params.publicKey Trusted public key(s).
* @param {string|null} [params.hwid] Local HWID (required for bound files).
* @param {Date|number} [params.now] Clock override (tests).
* @returns {{ok: true, license: object, payloadBase64: string, signatureBase64: string} | {ok: false, error: string}}
*/
export function verifyLicenseFile({ file, appId, publicKey, hwid = null, now = undefined }) {
const parsed = parseLicenseFile(file);
if (!parsed) return { ok: false, error: "bad_armor" };
if (!verifyPayloadSignatureEd25519(parsed.payloadBase64, parsed.signatureBase64, publicKey)) {
return { ok: false, error: "bad_signature" };
}
let payload;
try {
payload = JSON.parse(Buffer.from(parsed.payloadBase64, "base64").toString("utf8"));
} catch {
return { ok: false, error: "malformed_payload" };
}
if (!isPlainObject(payload)) return { ok: false, error: "malformed_payload" };
if (payload.v !== OFFLINE_LICENSE_FILE_VERSION) return { ok: false, error: "unsupported_version" };
if (!validateOfflinePayloadShape(payload)) return { ok: false, error: "malformed_payload" };
if (payload.appId !== appId) return { ok: false, error: "wrong_app" };
const nowMs = now instanceof Date ? now.getTime() : typeof now === "number" ? now : Date.now();
if (payload.expiresAt !== null) {
const exp = new Date(payload.expiresAt).getTime();
if (!Number.isFinite(exp) || exp <= nowMs) return { ok: false, error: "expired" };
}
if (payload.hwid.mode === "bound") {
const local = typeof hwid === "string" ? hwid.trim() : "";
if (!local || !payload.hwid.hwids.includes(local)) return { ok: false, error: "hwid_mismatch" };
}
return {
ok: true,
license: {
appId: payload.appId,
licenseKey: payload.licenseKey,
jti: payload.jti,
keyId: payload.kid,
issuedAt: payload.issuedAt,
expiresAt: payload.expiresAt,
hwidPolicy: payload.hwid.mode === "bound" ? { mode: "bound", hwids: [...payload.hwid.hwids] } : { mode: "any" },
...(typeof payload.label === "string" ? { label: payload.label } : {}),
...(Object.hasOwn(payload, "licenseExpiresAt") ? { licenseExpiresAt: payload.licenseExpiresAt ?? null } : {}),
licenseVariables: cloneObject(payload.licenseVariables),
appVariables: cloneObject(payload.appVariables),
payload: { ...payload },
},
payloadBase64: parsed.payloadBase64,
signatureBase64: parsed.signatureBase64,
};
}
function postJson(urlText, body, timeoutSeconds) {
const payload = JSON.stringify(body);
const url = new URL(urlText);
const options = {
method: "POST",
protocol: url.protocol,
hostname: url.hostname,
port: url.port || undefined,
path: `${url.pathname}${url.search}`,
headers: {
"Content-Type": "application/json",
"Content-Length": Buffer.byteLength(payload),
},
timeout: timeoutSeconds * 1000,
};
return new Promise((resolve, reject) => {
const request = https.request(options, (response) => {
const chunks = [];
response.on("data", (chunk) => chunks.push(chunk));
response.on("end", () => {
const raw = Buffer.concat(chunks).toString("utf8");
resolve({ statusCode: response.statusCode ?? 0, raw });
});
});
request.on("timeout", () => {
request.destroy(new Error("timeout"));
});
request.on("error", (error) => {
reject(error);
});
request.write(payload);
request.end();
});
}
export class AuthForgeClient {
constructor(
appId,
appSecret,
publicKey,
heartbeatMode,
heartbeatInterval = 900,
apiBaseUrl = DEFAULT_API_BASE_URL,
onFailure = null,
requestTimeout = 15,
ttlSeconds = null,
hwidOverride = null,
) {
let onlineHeartbeat = false;
if (appId && typeof appId === "object" && !Array.isArray(appId)) {
const options = appId;
appId = options.appId;
appSecret = options.appSecret;
publicKey = options.publicKey;
heartbeatMode = options.heartbeatMode;
onlineHeartbeat = options.onlineHeartbeat ?? false;
heartbeatInterval = options.heartbeatInterval ?? 900;
apiBaseUrl = options.apiBaseUrl ?? DEFAULT_API_BASE_URL;
onFailure = options.onFailure ?? null;
requestTimeout = options.requestTimeout ?? 15;
ttlSeconds = options.ttlSeconds ?? null;
hwidOverride = options.hwidOverride ?? null;
}
if (!appId || typeof appId !== "string") {
throw new Error("appId must be a non-empty string");
}
// Empty/omitted is valid for offline-only clients (loginFromFile).
// Online APIs (login, validateLicense, selfBan) still require a secret.
if (appSecret == null || appSecret === undefined) {
appSecret = "";
} else if (typeof appSecret !== "string") {
throw new Error("appSecret must be a string or omitted");
}
const publicKeyList = normalizePublicKeyList(publicKey);
if (publicKeyList.length === 0) {
throw new Error("publicKey must be a non-empty string or array of strings");
}
// `heartbeatMode` is a deprecated shim. The product policy is:
// grace period by default (no network after activate/validate until the
// session TTL expires), or opt-in online check-ins via `onlineHeartbeat`.
let mode = null;
if (heartbeatMode !== null && heartbeatMode !== undefined && String(heartbeatMode) !== "") {
mode = String(heartbeatMode).toUpperCase();
if (mode !== "LOCAL" && mode !== "SERVER") {
throw new Error("heartbeatMode must be LOCAL or SERVER");
}
process.emitWarning(
"heartbeatMode is deprecated: use onlineHeartbeat: true for online check-ins; the default is the grace period behavior",
"DeprecationWarning",
);
}
if (heartbeatInterval < 10) {
throw new Error("heartbeatInterval must be >= 10");
}
this.appId = appId;
this.appSecret = appSecret;
// `publicKey` is the historical name; we now hold the full list to
// support key rotation, but expose `.publicKey` as the first (primary)
// entry for callers that read it directly.
this.publicKeys = publicKeyList;
this.publicKey = publicKeyList[0];
// Effective policy: online check-ins when opted in explicitly or via the
// legacy "SERVER" mode; otherwise the grace period behavior.
this.onlineHeartbeat = Boolean(onlineHeartbeat) || mode === "SERVER";
// Back-compat alias for callers that still read `heartbeatMode`.
this.heartbeatMode = this.onlineHeartbeat ? "SERVER" : "LOCAL";
this.heartbeatInterval = Number.parseInt(String(heartbeatInterval), 10);
this.apiBaseUrl = String(apiBaseUrl).replace(/\/+$/, "");
this.onFailure = typeof onFailure === "function" ? onFailure : null;
this.requestTimeout = requestTimeout;
// Requested grace period duration in seconds (equals the session TTL).
// Server default is 24h; the server clamps requests to 1h..7d.
const parsedTtl = Number.parseInt(String(ttlSeconds ?? ""), 10);
this.ttlSeconds = Number.isFinite(parsedTtl) && parsedTtl > 0 ? parsedTtl : null;
this._heartbeatTimer = null;
this._heartbeatStarted = false;
this._licenseKey = null;
this._sessionToken = null;
// "online" after login()/validate, "offline" after loginFromFile(), null
// when logged out. Drives isAuthenticated(), selfBan() and the heartbeat
// guard so the two modes can never be confused for each other.
this._sessionKind = null;
this._sessionExpiresIn = null;
this._lastNonce = null;
this._rawPayloadB64 = null;
this._signature = null;
this._keyId = null;
this._sessionData = null;
this._appVariables = null;
this._licenseVariables = null;
this._authenticated = false;
this._offlineLicense = null;
this._hwid = this._resolveHwid(hwidOverride);
}
/** `"online"`, `"offline"` or `null` when not authenticated. */
getSessionKind() {
return this._sessionKind;
}
/**
* The HWID this client sends to AuthForge (or `hwidOverride` if set).
* Customers on air-gapped machines report this value to the operator so an
* offline `.authforge` file can be bound to it.
*/
getHwid() {
return this._hwid;
}
/**
* Build an activation request (`.authforge-request`) for this machine.
* No network, no session, no app secret. The HWID is the same value
* `login()` / `loginFromFile()` use. `machineName` is omitted unless
* `includeMachineName` is true (hostnames are often a person's name).
*
* @param {{ includeMachineName?: boolean, machineName?: string, os?: string, omitOs?: boolean, sdk?: string, omitSdk?: boolean, licenseKey?: string, createdAt?: string }} [options]
*/
createActivationRequest(options = {}) {
const createdAt = options.createdAt ?? new Date().toISOString();
const machineName = options.includeMachineName
? options.machineName || os.hostname()
: undefined;
const osName = options.omitOs ? undefined : (options.os ?? detectOsLabel());
const sdk = options.omitSdk ? undefined : (options.sdk ?? SDK_TAG);
const licenseKey =
options.licenseKey !== undefined ? options.licenseKey : this._licenseKey || undefined;
return formatActivationRequest({
appId: this.appId,
hwid: this._hwid,
createdAt,
machineName,
os: osName,
sdk,
licenseKey,
});
}
/**
* Write an activation request to `path` (UTF-8). Same options as
* {@link createActivationRequest}.
*/
writeActivationRequest(filePath, options = {}) {
writeFileSync(filePath, this.createActivationRequest(options), "utf8");
}
/**
* Authorize from a cloud-minted offline license file (`.authforge`) with NO
* network access. Accepts a filesystem path or the armored text itself.
*
* On success the client is authenticated (`isAuthenticated()`,
* `getSessionData()`, `getAppVariables()`, `getLicenseVariables()` work) and
* `getOfflineLicense()` describes the file. No grace-period timer and no
* online check-ins are started - the file's own `expiresAt` is the only
* clock. Online `login()` is untouched.
*
* Returns `true`/`false`; failures are reported through `onFailure` with
* reason `offline_login_failed` (never `process.exit`, unlike `login()`
* without a callback - an unreadable file should not kill an air-gapped
* process without a chance to show the user why).
*/
loginFromFile(pathOrText) {
let text;
try {
text = this._readLicenseFileInput(pathOrText);
} catch (error) {
this._failSoft("offline_login_failed", error);
return false;
}
const result = verifyLicenseFile({
file: text,
appId: this.appId,
publicKey: this.publicKeys,
hwid: this._hwid,
});
if (!result.ok) {
this._failSoft("offline_login_failed", new Error(result.error));
return false;
}
this._applyOfflineLicense(result);
return true;
}
/**
* Verify a `.authforge` file with this client's app id, public key(s) and
* HWID, without touching session state. Pure; never throws for bad input.
*/
verifyLicenseFile(pathOrText, options = {}) {
let text;
try {
text = this._readLicenseFileInput(pathOrText);
} catch (error) {
return { ok: false, error: `read_error: ${error instanceof Error ? error.message : String(error)}` };
}
return verifyLicenseFile({
file: text,
appId: this.appId,
publicKey: this.publicKeys,
hwid: this._hwid,
now: options.now,
});
}
/** Details of the offline file the client authenticated with, or `null`. */
getOfflineLicense() {
return this._offlineLicense ? { ...this._offlineLicense } : null;
}
_readLicenseFileInput(pathOrText) {
if (typeof pathOrText !== "string" || pathOrText.length === 0) {
throw new Error("license file must be a path or the armored text");
}
if (pathOrText.includes(OFFLINE_BEGIN_LICENSE)) {
return pathOrText;
}
return readFileSync(pathOrText, "utf8");
}
_applyOfflineLicense(result) {
// Stop any online session first so the two modes never overlap.
this.logout();
const { license } = result;
this._licenseKey = license.licenseKey;
// Offline files carry no server session token. The explicit session kind
// (not a token sentinel) is what makes isAuthenticated() true and keeps
// selfBan()/heartbeats from ever contacting the server for this session.
this._sessionToken = null;
this._sessionKind = "offline";
this._sessionExpiresIn = license.expiresAt ? Math.floor(new Date(license.expiresAt).getTime() / 1000) : null;
this._rawPayloadB64 = result.payloadBase64;
this._signature = result.signatureBase64;
this._keyId = license.keyId;
this._sessionData = { ...license.payload };
this._appVariables = license.appVariables;
this._licenseVariables = license.licenseVariables;
this._offlineLicense = {
licenseKey: license.licenseKey,
jti: license.jti,
keyId: license.keyId,
issuedAt: license.issuedAt,
expiresAt: license.expiresAt,
hwidPolicy: license.hwidPolicy,
...(license.label !== undefined ? { label: license.label } : {}),
...(license.licenseExpiresAt !== undefined ? { licenseExpiresAt: license.licenseExpiresAt } : {}),
};
this._authenticated = true;
}
_failSoft(reason, error) {
if (this.onFailure) {
try {
this.onFailure(reason, error);
} catch {
// Caller's callback threw; nothing else to do offline.
}
}
}
_requireAppSecret() {
if (!this.appSecret) {
throw new Error(
"appSecret is required for online APIs; omit it only when using loginFromFile",
);
}
}
async login(licenseKey) {
if (!licenseKey || typeof licenseKey !== "string") {
throw new Error("licenseKey must be a non-empty string");
}
this._requireAppSecret();
try {
await this._validateAndStore(licenseKey);
this._startHeartbeatOnce();
return true;
} catch (error) {
this._fail("login_failed", error);
return false;
}
}
async selfBan(options = {}) {
if (options !== null && typeof options !== "object") {
throw new Error("options must be an object");
}
const opts = options ?? {};
const blacklistHwid = opts.blacklistHwid !== false;
const blacklistIp = opts.blacklistIp !== false;
const requestedRevoke = opts.revokeLicense !== false;
const sessionTokenOption =
typeof opts.sessionToken === "string" && opts.sessionToken.trim()
? opts.sessionToken.trim()
: null;
const licenseKeyOption =
typeof opts.licenseKey === "string" && opts.licenseKey.trim()
? opts.licenseKey.trim()
: null;
// An offline session has no server session and must never phone home on
// its own. Callers who pass an explicit licenseKey/sessionToken are
// asking about a *different* credential and still get the normal paths.
if (this._sessionKind === "offline" && !sessionTokenOption && !licenseKeyOption) {
throw new Error("offline_session");
}
const sessionToken = sessionTokenOption || this._sessionToken;
if (sessionToken) {
const body = {
appId: this.appId,
sessionToken,
hwid: this._hwid,
revokeLicense: requestedRevoke,
blacklistHwid,
blacklistIp,
};
const responseObject = await this._postJson("/auth/selfban", body);
if (!this._isSuccessStatus(responseObject?.status)) {
throw new Error(this._extractServerError(responseObject));
}
return responseObject;
}
const licenseKey = licenseKeyOption || this._licenseKey;
if (!licenseKey) {
throw new Error("missing_license_key");
}
this._requireAppSecret();
const body = {
appId: this.appId,
appSecret: this.appSecret,
licenseKey,
hwid: this._hwid,
nonce: this._generateNonce(),
revokeLicense: false,
blacklistHwid,
blacklistIp,
};
const responseObject = await this._postJson("/auth/selfban", body);
if (!this._isSuccessStatus(responseObject?.status)) {
throw new Error(this._extractServerError(responseObject));
}
return responseObject;
}
logout() {
if (this._heartbeatTimer !== null) {
clearIntervalTimer(this._heartbeatTimer);
}
this._heartbeatTimer = null;
this._heartbeatStarted = false;
this._licenseKey = null;
this._sessionToken = null;
this._sessionKind = null;
this._sessionExpiresIn = null;
this._lastNonce = null;
this._rawPayloadB64 = null;
this._signature = null;
this._keyId = null;
this._sessionData = null;
this._appVariables = null;
this._licenseVariables = null;
this._authenticated = false;
this._offlineLicense = null;
}
isAuthenticated() {
if (!this._authenticated) {
return false;
}
switch (this._sessionKind) {
case "online":
return Boolean(this._sessionToken);
case "offline":
return true;
case null:
return false;
default:
return false;
}
}
getSessionData() {
return this._sessionData ? { ...this._sessionData } : null;
}
getAppVariables() {
return this._appVariables ? { ...this._appVariables } : null;
}
getLicenseVariables() {
return this._licenseVariables ? { ...this._licenseVariables } : null;
}
_startHeartbeatOnce() {
// Offline sessions have no grace period and no online check-ins: the
// file's own expiresAt is the only clock. Never start a timer for them.
if (this._heartbeatStarted || this._sessionKind === "offline") {
return;
}
this._heartbeatStarted = true;
this._heartbeatTimer = setIntervalTimer(() => {
this._heartbeatTick().catch(() => {
// _heartbeatTick handles failures and interval clearing.
});
}, this.heartbeatInterval * 1000);
}
async _heartbeatTick() {
if (this._sessionKind === "offline") {
return;
}
try {
if (this.onlineHeartbeat) {
await this._serverHeartbeat();
} else {
this._gracePeriodCheck();
}
} catch (error) {
this._fail("heartbeat_failed", error);
if (this._heartbeatTimer !== null) {
clearIntervalTimer(this._heartbeatTimer);
}
this._heartbeatTimer = null;
this._heartbeatStarted = false;
}
}
async _serverHeartbeat() {
const sessionToken = this._sessionToken;
if (!sessionToken) {
throw new Error("missing_session_token");
}
const body = {
appId: this.appId,
sessionToken,
nonce: this._generateNonce(),
hwid: this._hwid,
};
const responseObject = await this._postJson("/auth/heartbeat", body);
const expectedNonce = String(body.nonce ?? "").trim();
this._applySignedResponse(responseObject, expectedNonce, null, "heartbeat");
}
/**
* Grace period check: without any network call, re-verify the signed
* session obtained from activate/validate and fail once the session TTL
* (the grace period) has expired.
*/
_gracePeriodCheck() {
const rawPayloadB64 = this._rawPayloadB64;
const signature = this._signature;
const expiresIn = this._sessionExpiresIn;
if (!rawPayloadB64 || !signature) {
throw new Error("missing_local_verification_state");
}
this._verifySignature(rawPayloadB64, signature);
if (expiresIn === null) {
throw new Error("missing_session_expiry");
}
const now = Math.floor(Date.now() / 1000);
if (now >= Number.parseInt(String(expiresIn), 10)) {
throw new Error("session_expired");
}
}
async _validateAndStore(licenseKey) {
const body = {
appId: this.appId,
appSecret: this.appSecret,
licenseKey,
hwid: this._hwid,
nonce: this._generateNonce(),
};
if (this.ttlSeconds !== null) {
body.ttlSeconds = this.ttlSeconds;
}
const responseObject = await this._postJson("/auth/validate", body);
const expectedNonce = String(body.nonce ?? "").trim();
this._applySignedResponse(responseObject, expectedNonce, licenseKey, "validate");
}
/**
* Validates a license with the same request and Ed25519 verification as login,
* without mutating session state or starting heartbeats.
*/
async validateLicense(licenseKey) {
if (!licenseKey || typeof licenseKey !== "string") {
throw new Error("licenseKey must be a non-empty string");
}
this._requireAppSecret();
try {
const body = {
appId: this.appId,
appSecret: this.appSecret,
licenseKey,
hwid: this._hwid,
nonce: this._generateNonce(),
};
if (this.ttlSeconds !== null) {
body.ttlSeconds = this.ttlSeconds;
}
const responseObject = await this._postJson("/auth/validate", body, { skipFailureHook: true });
const expectedNonce = String(body.nonce ?? "").trim();
const parsed = this._parseValidateSuccess(responseObject, expectedNonce);
return {
valid: true,
sessionToken: parsed.sessionToken,
expiresIn: parsed.expiresIn,
sessionData: parsed.sessionData,
appVariables: parsed.appVariables,
licenseVariables: parsed.licenseVariables,
keyId: parsed.keyId,
...(parsed.sessionExpiresAt !== undefined ? { sessionExpiresAt: parsed.sessionExpiresAt } : {}),
...(parsed.licenseExpiresAt !== undefined ? { licenseExpiresAt: parsed.licenseExpiresAt } : {}),
...(parsed.maxHwidSlots !== undefined ? { maxHwidSlots: parsed.maxHwidSlots } : {}),
...(parsed.hwidCount !== undefined ? { hwidCount: parsed.hwidCount } : {}),
...(parsed.licenseLabel !== undefined ? { licenseLabel: parsed.licenseLabel } : {}),
};
} catch (error) {
const err = error instanceof Error ? error : new Error(String(error));
return { valid: false, code: err.message, error: err };
}
}
_parseValidateSuccess(responseObject, expectedNonce) {
if (!this._isSuccessStatus(responseObject?.status)) {
throw new Error(this._extractServerError(responseObject));
}
const rawPayloadB64 = this._requireStr(responseObject, "payload");
const signature = this._requireStr(responseObject, "signature");
const payloadObject = this._decodePayloadJson(rawPayloadB64);
const receivedNonce = String(payloadObject.nonce ?? "").trim();
if (receivedNonce !== expectedNonce) {
throw new Error("nonce_mismatch");
}
this._verifySignature(rawPayloadB64, signature);
const sessionToken = String(payloadObject.sessionToken ?? "").trim();
if (!sessionToken) {
throw new Error("missing_sessionToken");
}
const expiresFromToken = this._extractExpiresInFromSessionToken(sessionToken);