@licenseseat/js 0.3.0 → 0.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,2339 @@
1
+ var LicenseSeat = (() => {
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/index.js
21
+ var src_exports = {};
22
+ __export(src_exports, {
23
+ APIError: () => APIError,
24
+ ConfigurationError: () => ConfigurationError,
25
+ CryptoError: () => CryptoError,
26
+ LicenseCache: () => LicenseCache,
27
+ LicenseError: () => LicenseError,
28
+ LicenseSeatSDK: () => LicenseSeatSDK,
29
+ base64UrlDecode: () => base64UrlDecode,
30
+ canonicalJsonStringify: () => canonicalJsonStringify,
31
+ configure: () => configure,
32
+ constantTimeEqual: () => constantTimeEqual,
33
+ default: () => src_default,
34
+ generateDeviceId: () => generateDeviceId,
35
+ getCsrfToken: () => getCsrfToken,
36
+ getSharedInstance: () => getSharedInstance,
37
+ parseActiveEntitlements: () => parseActiveEntitlements,
38
+ resetSharedInstance: () => resetSharedInstance
39
+ });
40
+
41
+ // node_modules/@noble/ed25519/index.js
42
+ var ed25519_exports = {};
43
+ __export(ed25519_exports, {
44
+ CURVE: () => ed25519_CURVE,
45
+ ExtendedPoint: () => Point,
46
+ Point: () => Point,
47
+ etc: () => etc,
48
+ getPublicKey: () => getPublicKey,
49
+ getPublicKeyAsync: () => getPublicKeyAsync,
50
+ sign: () => sign,
51
+ signAsync: () => signAsync,
52
+ utils: () => utils,
53
+ verify: () => verify,
54
+ verifyAsync: () => verifyAsync
55
+ });
56
+ var ed25519_CURVE = {
57
+ p: 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffedn,
58
+ n: 0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3edn,
59
+ h: 8n,
60
+ a: 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffecn,
61
+ d: 0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3n,
62
+ Gx: 0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51an,
63
+ Gy: 0x6666666666666666666666666666666666666666666666666666666666666658n
64
+ };
65
+ var { p: P, n: N, Gx, Gy, a: _a, d: _d } = ed25519_CURVE;
66
+ var h = 8n;
67
+ var L = 32;
68
+ var L2 = 64;
69
+ var err = (m = "") => {
70
+ throw new Error(m);
71
+ };
72
+ var isBig = (n) => typeof n === "bigint";
73
+ var isStr = (s) => typeof s === "string";
74
+ var isBytes = (a) => a instanceof Uint8Array || ArrayBuffer.isView(a) && a.constructor.name === "Uint8Array";
75
+ var abytes = (a, l) => !isBytes(a) || typeof l === "number" && l > 0 && a.length !== l ? err("Uint8Array expected") : a;
76
+ var u8n = (len) => new Uint8Array(len);
77
+ var u8fr = (buf) => Uint8Array.from(buf);
78
+ var padh = (n, pad) => n.toString(16).padStart(pad, "0");
79
+ var bytesToHex = (b) => Array.from(abytes(b)).map((e) => padh(e, 2)).join("");
80
+ var C = { _0: 48, _9: 57, A: 65, F: 70, a: 97, f: 102 };
81
+ var _ch = (ch) => {
82
+ if (ch >= C._0 && ch <= C._9)
83
+ return ch - C._0;
84
+ if (ch >= C.A && ch <= C.F)
85
+ return ch - (C.A - 10);
86
+ if (ch >= C.a && ch <= C.f)
87
+ return ch - (C.a - 10);
88
+ return;
89
+ };
90
+ var hexToBytes = (hex) => {
91
+ const e = "hex invalid";
92
+ if (!isStr(hex))
93
+ return err(e);
94
+ const hl = hex.length;
95
+ const al = hl / 2;
96
+ if (hl % 2)
97
+ return err(e);
98
+ const array = u8n(al);
99
+ for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {
100
+ const n1 = _ch(hex.charCodeAt(hi));
101
+ const n2 = _ch(hex.charCodeAt(hi + 1));
102
+ if (n1 === void 0 || n2 === void 0)
103
+ return err(e);
104
+ array[ai] = n1 * 16 + n2;
105
+ }
106
+ return array;
107
+ };
108
+ var toU8 = (a, len) => abytes(isStr(a) ? hexToBytes(a) : u8fr(abytes(a)), len);
109
+ var cr = () => globalThis?.crypto;
110
+ var subtle = () => cr()?.subtle ?? err("crypto.subtle must be defined");
111
+ var concatBytes = (...arrs) => {
112
+ const r = u8n(arrs.reduce((sum, a) => sum + abytes(a).length, 0));
113
+ let pad = 0;
114
+ arrs.forEach((a) => {
115
+ r.set(a, pad);
116
+ pad += a.length;
117
+ });
118
+ return r;
119
+ };
120
+ var randomBytes = (len = L) => {
121
+ const c = cr();
122
+ return c.getRandomValues(u8n(len));
123
+ };
124
+ var big = BigInt;
125
+ var arange = (n, min, max, msg = "bad number: out of range") => isBig(n) && min <= n && n < max ? n : err(msg);
126
+ var M = (a, b = P) => {
127
+ const r = a % b;
128
+ return r >= 0n ? r : b + r;
129
+ };
130
+ var modN = (a) => M(a, N);
131
+ var invert = (num, md) => {
132
+ if (num === 0n || md <= 0n)
133
+ err("no inverse n=" + num + " mod=" + md);
134
+ let a = M(num, md), b = md, x = 0n, y = 1n, u = 1n, v = 0n;
135
+ while (a !== 0n) {
136
+ const q = b / a, r = b % a;
137
+ const m = x - u * q, n = y - v * q;
138
+ b = a, a = r, x = u, y = v, u = m, v = n;
139
+ }
140
+ return b === 1n ? M(x, md) : err("no inverse");
141
+ };
142
+ var callHash = (name) => {
143
+ const fn = etc[name];
144
+ if (typeof fn !== "function")
145
+ err("hashes." + name + " not set");
146
+ return fn;
147
+ };
148
+ var apoint = (p) => p instanceof Point ? p : err("Point expected");
149
+ var B256 = 2n ** 256n;
150
+ var Point = class _Point {
151
+ static BASE;
152
+ static ZERO;
153
+ ex;
154
+ ey;
155
+ ez;
156
+ et;
157
+ constructor(ex, ey, ez, et) {
158
+ const max = B256;
159
+ this.ex = arange(ex, 0n, max);
160
+ this.ey = arange(ey, 0n, max);
161
+ this.ez = arange(ez, 1n, max);
162
+ this.et = arange(et, 0n, max);
163
+ Object.freeze(this);
164
+ }
165
+ static fromAffine(p) {
166
+ return new _Point(p.x, p.y, 1n, M(p.x * p.y));
167
+ }
168
+ /** RFC8032 5.1.3: Uint8Array to Point. */
169
+ static fromBytes(hex, zip215 = false) {
170
+ const d = _d;
171
+ const normed = u8fr(abytes(hex, L));
172
+ const lastByte = hex[31];
173
+ normed[31] = lastByte & ~128;
174
+ const y = bytesToNumLE(normed);
175
+ const max = zip215 ? B256 : P;
176
+ arange(y, 0n, max);
177
+ const y2 = M(y * y);
178
+ const u = M(y2 - 1n);
179
+ const v = M(d * y2 + 1n);
180
+ let { isValid, value: x } = uvRatio(u, v);
181
+ if (!isValid)
182
+ err("bad point: y not sqrt");
183
+ const isXOdd = (x & 1n) === 1n;
184
+ const isLastByteOdd = (lastByte & 128) !== 0;
185
+ if (!zip215 && x === 0n && isLastByteOdd)
186
+ err("bad point: x==0, isLastByteOdd");
187
+ if (isLastByteOdd !== isXOdd)
188
+ x = M(-x);
189
+ return new _Point(x, y, 1n, M(x * y));
190
+ }
191
+ /** Checks if the point is valid and on-curve. */
192
+ assertValidity() {
193
+ const a = _a;
194
+ const d = _d;
195
+ const p = this;
196
+ if (p.is0())
197
+ throw new Error("bad point: ZERO");
198
+ const { ex: X, ey: Y, ez: Z, et: T } = p;
199
+ const X2 = M(X * X);
200
+ const Y2 = M(Y * Y);
201
+ const Z2 = M(Z * Z);
202
+ const Z4 = M(Z2 * Z2);
203
+ const aX2 = M(X2 * a);
204
+ const left = M(Z2 * M(aX2 + Y2));
205
+ const right = M(Z4 + M(d * M(X2 * Y2)));
206
+ if (left !== right)
207
+ throw new Error("bad point: equation left != right (1)");
208
+ const XY = M(X * Y);
209
+ const ZT = M(Z * T);
210
+ if (XY !== ZT)
211
+ throw new Error("bad point: equation left != right (2)");
212
+ return this;
213
+ }
214
+ /** Equality check: compare points P&Q. */
215
+ equals(other) {
216
+ const { ex: X1, ey: Y1, ez: Z1 } = this;
217
+ const { ex: X2, ey: Y2, ez: Z2 } = apoint(other);
218
+ const X1Z2 = M(X1 * Z2);
219
+ const X2Z1 = M(X2 * Z1);
220
+ const Y1Z2 = M(Y1 * Z2);
221
+ const Y2Z1 = M(Y2 * Z1);
222
+ return X1Z2 === X2Z1 && Y1Z2 === Y2Z1;
223
+ }
224
+ is0() {
225
+ return this.equals(I);
226
+ }
227
+ /** Flip point over y coordinate. */
228
+ negate() {
229
+ return new _Point(M(-this.ex), this.ey, this.ez, M(-this.et));
230
+ }
231
+ /** Point doubling. Complete formula. Cost: `4M + 4S + 1*a + 6add + 1*2`. */
232
+ double() {
233
+ const { ex: X1, ey: Y1, ez: Z1 } = this;
234
+ const a = _a;
235
+ const A = M(X1 * X1);
236
+ const B = M(Y1 * Y1);
237
+ const C2 = M(2n * M(Z1 * Z1));
238
+ const D = M(a * A);
239
+ const x1y1 = X1 + Y1;
240
+ const E = M(M(x1y1 * x1y1) - A - B);
241
+ const G2 = D + B;
242
+ const F = G2 - C2;
243
+ const H = D - B;
244
+ const X3 = M(E * F);
245
+ const Y3 = M(G2 * H);
246
+ const T3 = M(E * H);
247
+ const Z3 = M(F * G2);
248
+ return new _Point(X3, Y3, Z3, T3);
249
+ }
250
+ /** Point addition. Complete formula. Cost: `8M + 1*k + 8add + 1*2`. */
251
+ add(other) {
252
+ const { ex: X1, ey: Y1, ez: Z1, et: T1 } = this;
253
+ const { ex: X2, ey: Y2, ez: Z2, et: T2 } = apoint(other);
254
+ const a = _a;
255
+ const d = _d;
256
+ const A = M(X1 * X2);
257
+ const B = M(Y1 * Y2);
258
+ const C2 = M(T1 * d * T2);
259
+ const D = M(Z1 * Z2);
260
+ const E = M((X1 + Y1) * (X2 + Y2) - A - B);
261
+ const F = M(D - C2);
262
+ const G2 = M(D + C2);
263
+ const H = M(B - a * A);
264
+ const X3 = M(E * F);
265
+ const Y3 = M(G2 * H);
266
+ const T3 = M(E * H);
267
+ const Z3 = M(F * G2);
268
+ return new _Point(X3, Y3, Z3, T3);
269
+ }
270
+ /**
271
+ * Point-by-scalar multiplication. Scalar must be in range 1 <= n < CURVE.n.
272
+ * Uses {@link wNAF} for base point.
273
+ * Uses fake point to mitigate side-channel leakage.
274
+ * @param n scalar by which point is multiplied
275
+ * @param safe safe mode guards against timing attacks; unsafe mode is faster
276
+ */
277
+ multiply(n, safe = true) {
278
+ if (!safe && (n === 0n || this.is0()))
279
+ return I;
280
+ arange(n, 1n, N);
281
+ if (n === 1n)
282
+ return this;
283
+ if (this.equals(G))
284
+ return wNAF(n).p;
285
+ let p = I;
286
+ let f = G;
287
+ for (let d = this; n > 0n; d = d.double(), n >>= 1n) {
288
+ if (n & 1n)
289
+ p = p.add(d);
290
+ else if (safe)
291
+ f = f.add(d);
292
+ }
293
+ return p;
294
+ }
295
+ /** Convert point to 2d xy affine point. (X, Y, Z) ∋ (x=X/Z, y=Y/Z) */
296
+ toAffine() {
297
+ const { ex: x, ey: y, ez: z } = this;
298
+ if (this.equals(I))
299
+ return { x: 0n, y: 1n };
300
+ const iz = invert(z, P);
301
+ if (M(z * iz) !== 1n)
302
+ err("invalid inverse");
303
+ return { x: M(x * iz), y: M(y * iz) };
304
+ }
305
+ toBytes() {
306
+ const { x, y } = this.assertValidity().toAffine();
307
+ const b = numTo32bLE(y);
308
+ b[31] |= x & 1n ? 128 : 0;
309
+ return b;
310
+ }
311
+ toHex() {
312
+ return bytesToHex(this.toBytes());
313
+ }
314
+ // encode to hex string
315
+ clearCofactor() {
316
+ return this.multiply(big(h), false);
317
+ }
318
+ isSmallOrder() {
319
+ return this.clearCofactor().is0();
320
+ }
321
+ isTorsionFree() {
322
+ let p = this.multiply(N / 2n, false).double();
323
+ if (N % 2n)
324
+ p = p.add(this);
325
+ return p.is0();
326
+ }
327
+ static fromHex(hex, zip215) {
328
+ return _Point.fromBytes(toU8(hex), zip215);
329
+ }
330
+ get x() {
331
+ return this.toAffine().x;
332
+ }
333
+ get y() {
334
+ return this.toAffine().y;
335
+ }
336
+ toRawBytes() {
337
+ return this.toBytes();
338
+ }
339
+ };
340
+ var G = new Point(Gx, Gy, 1n, M(Gx * Gy));
341
+ var I = new Point(0n, 1n, 1n, 0n);
342
+ Point.BASE = G;
343
+ Point.ZERO = I;
344
+ var numTo32bLE = (num) => hexToBytes(padh(arange(num, 0n, B256), L2)).reverse();
345
+ var bytesToNumLE = (b) => big("0x" + bytesToHex(u8fr(abytes(b)).reverse()));
346
+ var pow2 = (x, power) => {
347
+ let r = x;
348
+ while (power-- > 0n) {
349
+ r *= r;
350
+ r %= P;
351
+ }
352
+ return r;
353
+ };
354
+ var pow_2_252_3 = (x) => {
355
+ const x2 = x * x % P;
356
+ const b2 = x2 * x % P;
357
+ const b4 = pow2(b2, 2n) * b2 % P;
358
+ const b5 = pow2(b4, 1n) * x % P;
359
+ const b10 = pow2(b5, 5n) * b5 % P;
360
+ const b20 = pow2(b10, 10n) * b10 % P;
361
+ const b40 = pow2(b20, 20n) * b20 % P;
362
+ const b80 = pow2(b40, 40n) * b40 % P;
363
+ const b160 = pow2(b80, 80n) * b80 % P;
364
+ const b240 = pow2(b160, 80n) * b80 % P;
365
+ const b250 = pow2(b240, 10n) * b10 % P;
366
+ const pow_p_5_8 = pow2(b250, 2n) * x % P;
367
+ return { pow_p_5_8, b2 };
368
+ };
369
+ var RM1 = 0x2b8324804fc1df0b2b4d00993dfbd7a72f431806ad2fe478c4ee1b274a0ea0b0n;
370
+ var uvRatio = (u, v) => {
371
+ const v3 = M(v * v * v);
372
+ const v7 = M(v3 * v3 * v);
373
+ const pow = pow_2_252_3(u * v7).pow_p_5_8;
374
+ let x = M(u * v3 * pow);
375
+ const vx2 = M(v * x * x);
376
+ const root1 = x;
377
+ const root2 = M(x * RM1);
378
+ const useRoot1 = vx2 === u;
379
+ const useRoot2 = vx2 === M(-u);
380
+ const noRoot = vx2 === M(-u * RM1);
381
+ if (useRoot1)
382
+ x = root1;
383
+ if (useRoot2 || noRoot)
384
+ x = root2;
385
+ if ((M(x) & 1n) === 1n)
386
+ x = M(-x);
387
+ return { isValid: useRoot1 || useRoot2, value: x };
388
+ };
389
+ var modL_LE = (hash) => modN(bytesToNumLE(hash));
390
+ var sha512a = (...m) => etc.sha512Async(...m);
391
+ var sha512s = (...m) => callHash("sha512Sync")(...m);
392
+ var hash2extK = (hashed) => {
393
+ const head = hashed.slice(0, L);
394
+ head[0] &= 248;
395
+ head[31] &= 127;
396
+ head[31] |= 64;
397
+ const prefix = hashed.slice(L, L2);
398
+ const scalar = modL_LE(head);
399
+ const point = G.multiply(scalar);
400
+ const pointBytes = point.toBytes();
401
+ return { head, prefix, scalar, point, pointBytes };
402
+ };
403
+ var getExtendedPublicKeyAsync = (priv) => sha512a(toU8(priv, L)).then(hash2extK);
404
+ var getExtendedPublicKey = (priv) => hash2extK(sha512s(toU8(priv, L)));
405
+ var getPublicKeyAsync = (priv) => getExtendedPublicKeyAsync(priv).then((p) => p.pointBytes);
406
+ var getPublicKey = (priv) => getExtendedPublicKey(priv).pointBytes;
407
+ var hashFinishA = (res) => sha512a(res.hashable).then(res.finish);
408
+ var hashFinishS = (res) => res.finish(sha512s(res.hashable));
409
+ var _sign = (e, rBytes, msg) => {
410
+ const { pointBytes: P2, scalar: s } = e;
411
+ const r = modL_LE(rBytes);
412
+ const R = G.multiply(r).toBytes();
413
+ const hashable = concatBytes(R, P2, msg);
414
+ const finish = (hashed) => {
415
+ const S = modN(r + modL_LE(hashed) * s);
416
+ return abytes(concatBytes(R, numTo32bLE(S)), L2);
417
+ };
418
+ return { hashable, finish };
419
+ };
420
+ var signAsync = async (msg, privKey) => {
421
+ const m = toU8(msg);
422
+ const e = await getExtendedPublicKeyAsync(privKey);
423
+ const rBytes = await sha512a(e.prefix, m);
424
+ return hashFinishA(_sign(e, rBytes, m));
425
+ };
426
+ var sign = (msg, privKey) => {
427
+ const m = toU8(msg);
428
+ const e = getExtendedPublicKey(privKey);
429
+ const rBytes = sha512s(e.prefix, m);
430
+ return hashFinishS(_sign(e, rBytes, m));
431
+ };
432
+ var veriOpts = { zip215: true };
433
+ var _verify = (sig, msg, pub, opts = veriOpts) => {
434
+ sig = toU8(sig, L2);
435
+ msg = toU8(msg);
436
+ pub = toU8(pub, L);
437
+ const { zip215 } = opts;
438
+ let A;
439
+ let R;
440
+ let s;
441
+ let SB;
442
+ let hashable = Uint8Array.of();
443
+ try {
444
+ A = Point.fromHex(pub, zip215);
445
+ R = Point.fromHex(sig.slice(0, L), zip215);
446
+ s = bytesToNumLE(sig.slice(L, L2));
447
+ SB = G.multiply(s, false);
448
+ hashable = concatBytes(R.toBytes(), A.toBytes(), msg);
449
+ } catch (error) {
450
+ }
451
+ const finish = (hashed) => {
452
+ if (SB == null)
453
+ return false;
454
+ if (!zip215 && A.isSmallOrder())
455
+ return false;
456
+ const k = modL_LE(hashed);
457
+ const RkA = R.add(A.multiply(k, false));
458
+ return RkA.add(SB.negate()).clearCofactor().is0();
459
+ };
460
+ return { hashable, finish };
461
+ };
462
+ var verifyAsync = async (s, m, p, opts = veriOpts) => hashFinishA(_verify(s, m, p, opts));
463
+ var verify = (s, m, p, opts = veriOpts) => hashFinishS(_verify(s, m, p, opts));
464
+ var etc = {
465
+ sha512Async: async (...messages) => {
466
+ const s = subtle();
467
+ const m = concatBytes(...messages);
468
+ return u8n(await s.digest("SHA-512", m.buffer));
469
+ },
470
+ sha512Sync: void 0,
471
+ bytesToHex,
472
+ hexToBytes,
473
+ concatBytes,
474
+ mod: M,
475
+ invert,
476
+ randomBytes
477
+ };
478
+ var utils = {
479
+ getExtendedPublicKeyAsync,
480
+ getExtendedPublicKey,
481
+ randomPrivateKey: () => randomBytes(L),
482
+ precompute: (w = 8, p = G) => {
483
+ p.multiply(3n);
484
+ w;
485
+ return p;
486
+ }
487
+ // no-op
488
+ };
489
+ var W = 8;
490
+ var scalarBits = 256;
491
+ var pwindows = Math.ceil(scalarBits / W) + 1;
492
+ var pwindowSize = 2 ** (W - 1);
493
+ var precompute = () => {
494
+ const points = [];
495
+ let p = G;
496
+ let b = p;
497
+ for (let w = 0; w < pwindows; w++) {
498
+ b = p;
499
+ points.push(b);
500
+ for (let i = 1; i < pwindowSize; i++) {
501
+ b = b.add(p);
502
+ points.push(b);
503
+ }
504
+ p = b.double();
505
+ }
506
+ return points;
507
+ };
508
+ var Gpows = void 0;
509
+ var ctneg = (cnd, p) => {
510
+ const n = p.negate();
511
+ return cnd ? n : p;
512
+ };
513
+ var wNAF = (n) => {
514
+ const comp = Gpows || (Gpows = precompute());
515
+ let p = I;
516
+ let f = G;
517
+ const pow_2_w = 2 ** W;
518
+ const maxNum = pow_2_w;
519
+ const mask = big(pow_2_w - 1);
520
+ const shiftBy = big(W);
521
+ for (let w = 0; w < pwindows; w++) {
522
+ let wbits = Number(n & mask);
523
+ n >>= shiftBy;
524
+ if (wbits > pwindowSize) {
525
+ wbits -= maxNum;
526
+ n += 1n;
527
+ }
528
+ const off = w * pwindowSize;
529
+ const offF = off;
530
+ const offP = off + Math.abs(wbits) - 1;
531
+ const isEven = w % 2 !== 0;
532
+ const isNeg = wbits < 0;
533
+ if (wbits === 0) {
534
+ f = f.add(ctneg(isEven, comp[offF]));
535
+ } else {
536
+ p = p.add(ctneg(isNeg, comp[offP]));
537
+ }
538
+ }
539
+ return { p, f };
540
+ };
541
+
542
+ // node_modules/@noble/hashes/esm/utils.js
543
+ function isBytes2(a) {
544
+ return a instanceof Uint8Array || ArrayBuffer.isView(a) && a.constructor.name === "Uint8Array";
545
+ }
546
+ function abytes2(b, ...lengths) {
547
+ if (!isBytes2(b))
548
+ throw new Error("Uint8Array expected");
549
+ if (lengths.length > 0 && !lengths.includes(b.length))
550
+ throw new Error("Uint8Array expected of length " + lengths + ", got length=" + b.length);
551
+ }
552
+ function aexists(instance, checkFinished = true) {
553
+ if (instance.destroyed)
554
+ throw new Error("Hash instance has been destroyed");
555
+ if (checkFinished && instance.finished)
556
+ throw new Error("Hash#digest() has already been called");
557
+ }
558
+ function aoutput(out, instance) {
559
+ abytes2(out);
560
+ const min = instance.outputLen;
561
+ if (out.length < min) {
562
+ throw new Error("digestInto() expects output buffer of length at least " + min);
563
+ }
564
+ }
565
+ function clean(...arrays) {
566
+ for (let i = 0; i < arrays.length; i++) {
567
+ arrays[i].fill(0);
568
+ }
569
+ }
570
+ function createView(arr) {
571
+ return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);
572
+ }
573
+ function utf8ToBytes(str2) {
574
+ if (typeof str2 !== "string")
575
+ throw new Error("string expected");
576
+ return new Uint8Array(new TextEncoder().encode(str2));
577
+ }
578
+ function toBytes(data) {
579
+ if (typeof data === "string")
580
+ data = utf8ToBytes(data);
581
+ abytes2(data);
582
+ return data;
583
+ }
584
+ var Hash = class {
585
+ };
586
+ function createHasher(hashCons) {
587
+ const hashC = (msg) => hashCons().update(toBytes(msg)).digest();
588
+ const tmp = hashCons();
589
+ hashC.outputLen = tmp.outputLen;
590
+ hashC.blockLen = tmp.blockLen;
591
+ hashC.create = () => hashCons();
592
+ return hashC;
593
+ }
594
+
595
+ // node_modules/@noble/hashes/esm/_md.js
596
+ function setBigUint64(view, byteOffset, value, isLE) {
597
+ if (typeof view.setBigUint64 === "function")
598
+ return view.setBigUint64(byteOffset, value, isLE);
599
+ const _32n2 = BigInt(32);
600
+ const _u32_max = BigInt(4294967295);
601
+ const wh = Number(value >> _32n2 & _u32_max);
602
+ const wl = Number(value & _u32_max);
603
+ const h2 = isLE ? 4 : 0;
604
+ const l = isLE ? 0 : 4;
605
+ view.setUint32(byteOffset + h2, wh, isLE);
606
+ view.setUint32(byteOffset + l, wl, isLE);
607
+ }
608
+ var HashMD = class extends Hash {
609
+ constructor(blockLen, outputLen, padOffset, isLE) {
610
+ super();
611
+ this.finished = false;
612
+ this.length = 0;
613
+ this.pos = 0;
614
+ this.destroyed = false;
615
+ this.blockLen = blockLen;
616
+ this.outputLen = outputLen;
617
+ this.padOffset = padOffset;
618
+ this.isLE = isLE;
619
+ this.buffer = new Uint8Array(blockLen);
620
+ this.view = createView(this.buffer);
621
+ }
622
+ update(data) {
623
+ aexists(this);
624
+ data = toBytes(data);
625
+ abytes2(data);
626
+ const { view, buffer, blockLen } = this;
627
+ const len = data.length;
628
+ for (let pos = 0; pos < len; ) {
629
+ const take = Math.min(blockLen - this.pos, len - pos);
630
+ if (take === blockLen) {
631
+ const dataView = createView(data);
632
+ for (; blockLen <= len - pos; pos += blockLen)
633
+ this.process(dataView, pos);
634
+ continue;
635
+ }
636
+ buffer.set(data.subarray(pos, pos + take), this.pos);
637
+ this.pos += take;
638
+ pos += take;
639
+ if (this.pos === blockLen) {
640
+ this.process(view, 0);
641
+ this.pos = 0;
642
+ }
643
+ }
644
+ this.length += data.length;
645
+ this.roundClean();
646
+ return this;
647
+ }
648
+ digestInto(out) {
649
+ aexists(this);
650
+ aoutput(out, this);
651
+ this.finished = true;
652
+ const { buffer, view, blockLen, isLE } = this;
653
+ let { pos } = this;
654
+ buffer[pos++] = 128;
655
+ clean(this.buffer.subarray(pos));
656
+ if (this.padOffset > blockLen - pos) {
657
+ this.process(view, 0);
658
+ pos = 0;
659
+ }
660
+ for (let i = pos; i < blockLen; i++)
661
+ buffer[i] = 0;
662
+ setBigUint64(view, blockLen - 8, BigInt(this.length * 8), isLE);
663
+ this.process(view, 0);
664
+ const oview = createView(out);
665
+ const len = this.outputLen;
666
+ if (len % 4)
667
+ throw new Error("_sha2: outputLen should be aligned to 32bit");
668
+ const outLen = len / 4;
669
+ const state = this.get();
670
+ if (outLen > state.length)
671
+ throw new Error("_sha2: outputLen bigger than state");
672
+ for (let i = 0; i < outLen; i++)
673
+ oview.setUint32(4 * i, state[i], isLE);
674
+ }
675
+ digest() {
676
+ const { buffer, outputLen } = this;
677
+ this.digestInto(buffer);
678
+ const res = buffer.slice(0, outputLen);
679
+ this.destroy();
680
+ return res;
681
+ }
682
+ _cloneInto(to) {
683
+ to || (to = new this.constructor());
684
+ to.set(...this.get());
685
+ const { blockLen, buffer, length, finished, destroyed, pos } = this;
686
+ to.destroyed = destroyed;
687
+ to.finished = finished;
688
+ to.length = length;
689
+ to.pos = pos;
690
+ if (length % blockLen)
691
+ to.buffer.set(buffer);
692
+ return to;
693
+ }
694
+ clone() {
695
+ return this._cloneInto();
696
+ }
697
+ };
698
+ var SHA512_IV = /* @__PURE__ */ Uint32Array.from([
699
+ 1779033703,
700
+ 4089235720,
701
+ 3144134277,
702
+ 2227873595,
703
+ 1013904242,
704
+ 4271175723,
705
+ 2773480762,
706
+ 1595750129,
707
+ 1359893119,
708
+ 2917565137,
709
+ 2600822924,
710
+ 725511199,
711
+ 528734635,
712
+ 4215389547,
713
+ 1541459225,
714
+ 327033209
715
+ ]);
716
+
717
+ // node_modules/@noble/hashes/esm/_u64.js
718
+ var U32_MASK64 = /* @__PURE__ */ BigInt(2 ** 32 - 1);
719
+ var _32n = /* @__PURE__ */ BigInt(32);
720
+ function fromBig(n, le = false) {
721
+ if (le)
722
+ return { h: Number(n & U32_MASK64), l: Number(n >> _32n & U32_MASK64) };
723
+ return { h: Number(n >> _32n & U32_MASK64) | 0, l: Number(n & U32_MASK64) | 0 };
724
+ }
725
+ function split(lst, le = false) {
726
+ const len = lst.length;
727
+ let Ah = new Uint32Array(len);
728
+ let Al = new Uint32Array(len);
729
+ for (let i = 0; i < len; i++) {
730
+ const { h: h2, l } = fromBig(lst[i], le);
731
+ [Ah[i], Al[i]] = [h2, l];
732
+ }
733
+ return [Ah, Al];
734
+ }
735
+ var shrSH = (h2, _l, s) => h2 >>> s;
736
+ var shrSL = (h2, l, s) => h2 << 32 - s | l >>> s;
737
+ var rotrSH = (h2, l, s) => h2 >>> s | l << 32 - s;
738
+ var rotrSL = (h2, l, s) => h2 << 32 - s | l >>> s;
739
+ var rotrBH = (h2, l, s) => h2 << 64 - s | l >>> s - 32;
740
+ var rotrBL = (h2, l, s) => h2 >>> s - 32 | l << 64 - s;
741
+ function add(Ah, Al, Bh, Bl) {
742
+ const l = (Al >>> 0) + (Bl >>> 0);
743
+ return { h: Ah + Bh + (l / 2 ** 32 | 0) | 0, l: l | 0 };
744
+ }
745
+ var add3L = (Al, Bl, Cl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0);
746
+ var add3H = (low, Ah, Bh, Ch) => Ah + Bh + Ch + (low / 2 ** 32 | 0) | 0;
747
+ var add4L = (Al, Bl, Cl, Dl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0);
748
+ var add4H = (low, Ah, Bh, Ch, Dh) => Ah + Bh + Ch + Dh + (low / 2 ** 32 | 0) | 0;
749
+ var add5L = (Al, Bl, Cl, Dl, El) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0) + (El >>> 0);
750
+ var add5H = (low, Ah, Bh, Ch, Dh, Eh) => Ah + Bh + Ch + Dh + Eh + (low / 2 ** 32 | 0) | 0;
751
+
752
+ // node_modules/@noble/hashes/esm/sha2.js
753
+ var K512 = /* @__PURE__ */ (() => split([
754
+ "0x428a2f98d728ae22",
755
+ "0x7137449123ef65cd",
756
+ "0xb5c0fbcfec4d3b2f",
757
+ "0xe9b5dba58189dbbc",
758
+ "0x3956c25bf348b538",
759
+ "0x59f111f1b605d019",
760
+ "0x923f82a4af194f9b",
761
+ "0xab1c5ed5da6d8118",
762
+ "0xd807aa98a3030242",
763
+ "0x12835b0145706fbe",
764
+ "0x243185be4ee4b28c",
765
+ "0x550c7dc3d5ffb4e2",
766
+ "0x72be5d74f27b896f",
767
+ "0x80deb1fe3b1696b1",
768
+ "0x9bdc06a725c71235",
769
+ "0xc19bf174cf692694",
770
+ "0xe49b69c19ef14ad2",
771
+ "0xefbe4786384f25e3",
772
+ "0x0fc19dc68b8cd5b5",
773
+ "0x240ca1cc77ac9c65",
774
+ "0x2de92c6f592b0275",
775
+ "0x4a7484aa6ea6e483",
776
+ "0x5cb0a9dcbd41fbd4",
777
+ "0x76f988da831153b5",
778
+ "0x983e5152ee66dfab",
779
+ "0xa831c66d2db43210",
780
+ "0xb00327c898fb213f",
781
+ "0xbf597fc7beef0ee4",
782
+ "0xc6e00bf33da88fc2",
783
+ "0xd5a79147930aa725",
784
+ "0x06ca6351e003826f",
785
+ "0x142929670a0e6e70",
786
+ "0x27b70a8546d22ffc",
787
+ "0x2e1b21385c26c926",
788
+ "0x4d2c6dfc5ac42aed",
789
+ "0x53380d139d95b3df",
790
+ "0x650a73548baf63de",
791
+ "0x766a0abb3c77b2a8",
792
+ "0x81c2c92e47edaee6",
793
+ "0x92722c851482353b",
794
+ "0xa2bfe8a14cf10364",
795
+ "0xa81a664bbc423001",
796
+ "0xc24b8b70d0f89791",
797
+ "0xc76c51a30654be30",
798
+ "0xd192e819d6ef5218",
799
+ "0xd69906245565a910",
800
+ "0xf40e35855771202a",
801
+ "0x106aa07032bbd1b8",
802
+ "0x19a4c116b8d2d0c8",
803
+ "0x1e376c085141ab53",
804
+ "0x2748774cdf8eeb99",
805
+ "0x34b0bcb5e19b48a8",
806
+ "0x391c0cb3c5c95a63",
807
+ "0x4ed8aa4ae3418acb",
808
+ "0x5b9cca4f7763e373",
809
+ "0x682e6ff3d6b2b8a3",
810
+ "0x748f82ee5defb2fc",
811
+ "0x78a5636f43172f60",
812
+ "0x84c87814a1f0ab72",
813
+ "0x8cc702081a6439ec",
814
+ "0x90befffa23631e28",
815
+ "0xa4506cebde82bde9",
816
+ "0xbef9a3f7b2c67915",
817
+ "0xc67178f2e372532b",
818
+ "0xca273eceea26619c",
819
+ "0xd186b8c721c0c207",
820
+ "0xeada7dd6cde0eb1e",
821
+ "0xf57d4f7fee6ed178",
822
+ "0x06f067aa72176fba",
823
+ "0x0a637dc5a2c898a6",
824
+ "0x113f9804bef90dae",
825
+ "0x1b710b35131c471b",
826
+ "0x28db77f523047d84",
827
+ "0x32caab7b40c72493",
828
+ "0x3c9ebe0a15c9bebc",
829
+ "0x431d67c49c100d4c",
830
+ "0x4cc5d4becb3e42b6",
831
+ "0x597f299cfc657e2a",
832
+ "0x5fcb6fab3ad6faec",
833
+ "0x6c44198c4a475817"
834
+ ].map((n) => BigInt(n))))();
835
+ var SHA512_Kh = /* @__PURE__ */ (() => K512[0])();
836
+ var SHA512_Kl = /* @__PURE__ */ (() => K512[1])();
837
+ var SHA512_W_H = /* @__PURE__ */ new Uint32Array(80);
838
+ var SHA512_W_L = /* @__PURE__ */ new Uint32Array(80);
839
+ var SHA512 = class extends HashMD {
840
+ constructor(outputLen = 64) {
841
+ super(128, outputLen, 16, false);
842
+ this.Ah = SHA512_IV[0] | 0;
843
+ this.Al = SHA512_IV[1] | 0;
844
+ this.Bh = SHA512_IV[2] | 0;
845
+ this.Bl = SHA512_IV[3] | 0;
846
+ this.Ch = SHA512_IV[4] | 0;
847
+ this.Cl = SHA512_IV[5] | 0;
848
+ this.Dh = SHA512_IV[6] | 0;
849
+ this.Dl = SHA512_IV[7] | 0;
850
+ this.Eh = SHA512_IV[8] | 0;
851
+ this.El = SHA512_IV[9] | 0;
852
+ this.Fh = SHA512_IV[10] | 0;
853
+ this.Fl = SHA512_IV[11] | 0;
854
+ this.Gh = SHA512_IV[12] | 0;
855
+ this.Gl = SHA512_IV[13] | 0;
856
+ this.Hh = SHA512_IV[14] | 0;
857
+ this.Hl = SHA512_IV[15] | 0;
858
+ }
859
+ // prettier-ignore
860
+ get() {
861
+ const { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;
862
+ return [Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl];
863
+ }
864
+ // prettier-ignore
865
+ set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl) {
866
+ this.Ah = Ah | 0;
867
+ this.Al = Al | 0;
868
+ this.Bh = Bh | 0;
869
+ this.Bl = Bl | 0;
870
+ this.Ch = Ch | 0;
871
+ this.Cl = Cl | 0;
872
+ this.Dh = Dh | 0;
873
+ this.Dl = Dl | 0;
874
+ this.Eh = Eh | 0;
875
+ this.El = El | 0;
876
+ this.Fh = Fh | 0;
877
+ this.Fl = Fl | 0;
878
+ this.Gh = Gh | 0;
879
+ this.Gl = Gl | 0;
880
+ this.Hh = Hh | 0;
881
+ this.Hl = Hl | 0;
882
+ }
883
+ process(view, offset) {
884
+ for (let i = 0; i < 16; i++, offset += 4) {
885
+ SHA512_W_H[i] = view.getUint32(offset);
886
+ SHA512_W_L[i] = view.getUint32(offset += 4);
887
+ }
888
+ for (let i = 16; i < 80; i++) {
889
+ const W15h = SHA512_W_H[i - 15] | 0;
890
+ const W15l = SHA512_W_L[i - 15] | 0;
891
+ const s0h = rotrSH(W15h, W15l, 1) ^ rotrSH(W15h, W15l, 8) ^ shrSH(W15h, W15l, 7);
892
+ const s0l = rotrSL(W15h, W15l, 1) ^ rotrSL(W15h, W15l, 8) ^ shrSL(W15h, W15l, 7);
893
+ const W2h = SHA512_W_H[i - 2] | 0;
894
+ const W2l = SHA512_W_L[i - 2] | 0;
895
+ const s1h = rotrSH(W2h, W2l, 19) ^ rotrBH(W2h, W2l, 61) ^ shrSH(W2h, W2l, 6);
896
+ const s1l = rotrSL(W2h, W2l, 19) ^ rotrBL(W2h, W2l, 61) ^ shrSL(W2h, W2l, 6);
897
+ const SUMl = add4L(s0l, s1l, SHA512_W_L[i - 7], SHA512_W_L[i - 16]);
898
+ const SUMh = add4H(SUMl, s0h, s1h, SHA512_W_H[i - 7], SHA512_W_H[i - 16]);
899
+ SHA512_W_H[i] = SUMh | 0;
900
+ SHA512_W_L[i] = SUMl | 0;
901
+ }
902
+ let { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;
903
+ for (let i = 0; i < 80; i++) {
904
+ const sigma1h = rotrSH(Eh, El, 14) ^ rotrSH(Eh, El, 18) ^ rotrBH(Eh, El, 41);
905
+ const sigma1l = rotrSL(Eh, El, 14) ^ rotrSL(Eh, El, 18) ^ rotrBL(Eh, El, 41);
906
+ const CHIh = Eh & Fh ^ ~Eh & Gh;
907
+ const CHIl = El & Fl ^ ~El & Gl;
908
+ const T1ll = add5L(Hl, sigma1l, CHIl, SHA512_Kl[i], SHA512_W_L[i]);
909
+ const T1h = add5H(T1ll, Hh, sigma1h, CHIh, SHA512_Kh[i], SHA512_W_H[i]);
910
+ const T1l = T1ll | 0;
911
+ const sigma0h = rotrSH(Ah, Al, 28) ^ rotrBH(Ah, Al, 34) ^ rotrBH(Ah, Al, 39);
912
+ const sigma0l = rotrSL(Ah, Al, 28) ^ rotrBL(Ah, Al, 34) ^ rotrBL(Ah, Al, 39);
913
+ const MAJh = Ah & Bh ^ Ah & Ch ^ Bh & Ch;
914
+ const MAJl = Al & Bl ^ Al & Cl ^ Bl & Cl;
915
+ Hh = Gh | 0;
916
+ Hl = Gl | 0;
917
+ Gh = Fh | 0;
918
+ Gl = Fl | 0;
919
+ Fh = Eh | 0;
920
+ Fl = El | 0;
921
+ ({ h: Eh, l: El } = add(Dh | 0, Dl | 0, T1h | 0, T1l | 0));
922
+ Dh = Ch | 0;
923
+ Dl = Cl | 0;
924
+ Ch = Bh | 0;
925
+ Cl = Bl | 0;
926
+ Bh = Ah | 0;
927
+ Bl = Al | 0;
928
+ const All = add3L(T1l, sigma0l, MAJl);
929
+ Ah = add3H(All, T1h, sigma0h, MAJh);
930
+ Al = All | 0;
931
+ }
932
+ ({ h: Ah, l: Al } = add(this.Ah | 0, this.Al | 0, Ah | 0, Al | 0));
933
+ ({ h: Bh, l: Bl } = add(this.Bh | 0, this.Bl | 0, Bh | 0, Bl | 0));
934
+ ({ h: Ch, l: Cl } = add(this.Ch | 0, this.Cl | 0, Ch | 0, Cl | 0));
935
+ ({ h: Dh, l: Dl } = add(this.Dh | 0, this.Dl | 0, Dh | 0, Dl | 0));
936
+ ({ h: Eh, l: El } = add(this.Eh | 0, this.El | 0, Eh | 0, El | 0));
937
+ ({ h: Fh, l: Fl } = add(this.Fh | 0, this.Fl | 0, Fh | 0, Fl | 0));
938
+ ({ h: Gh, l: Gl } = add(this.Gh | 0, this.Gl | 0, Gh | 0, Gl | 0));
939
+ ({ h: Hh, l: Hl } = add(this.Hh | 0, this.Hl | 0, Hh | 0, Hl | 0));
940
+ this.set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl);
941
+ }
942
+ roundClean() {
943
+ clean(SHA512_W_H, SHA512_W_L);
944
+ }
945
+ destroy() {
946
+ clean(this.buffer);
947
+ this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
948
+ }
949
+ };
950
+ var sha512 = /* @__PURE__ */ createHasher(() => new SHA512());
951
+
952
+ // node_modules/@noble/hashes/esm/sha512.js
953
+ var sha5122 = sha512;
954
+
955
+ // src/cache.js
956
+ var LicenseCache = class {
957
+ /**
958
+ * Create a LicenseCache instance
959
+ * @param {string} [prefix="licenseseat_"] - Prefix for all localStorage keys
960
+ */
961
+ constructor(prefix = "licenseseat_") {
962
+ this.prefix = prefix;
963
+ this.publicKeyCacheKey = this.prefix + "public_keys";
964
+ }
965
+ /**
966
+ * Get the cached license data
967
+ * @returns {import('./types.js').CachedLicense|null} Cached license or null if not found
968
+ */
969
+ getLicense() {
970
+ try {
971
+ const data = localStorage.getItem(this.prefix + "license");
972
+ return data ? JSON.parse(data) : null;
973
+ } catch (e) {
974
+ console.error("Failed to read license cache:", e);
975
+ return null;
976
+ }
977
+ }
978
+ /**
979
+ * Store license data in cache
980
+ * @param {import('./types.js').CachedLicense} data - License data to cache
981
+ * @returns {void}
982
+ */
983
+ setLicense(data) {
984
+ try {
985
+ localStorage.setItem(this.prefix + "license", JSON.stringify(data));
986
+ } catch (e) {
987
+ console.error("Failed to cache license:", e);
988
+ }
989
+ }
990
+ /**
991
+ * Update the validation data for the cached license
992
+ * @param {import('./types.js').ValidationResult} validationData - Validation result to store
993
+ * @returns {void}
994
+ */
995
+ updateValidation(validationData) {
996
+ const license = this.getLicense();
997
+ if (license) {
998
+ license.validation = validationData;
999
+ license.last_validated = (/* @__PURE__ */ new Date()).toISOString();
1000
+ this.setLicense(license);
1001
+ }
1002
+ }
1003
+ /**
1004
+ * Get the device ID from the cached license
1005
+ * @returns {string|null} Device ID or null if not found
1006
+ */
1007
+ getDeviceId() {
1008
+ const license = this.getLicense();
1009
+ return license ? license.device_id : null;
1010
+ }
1011
+ /**
1012
+ * Clear the cached license data
1013
+ * @returns {void}
1014
+ */
1015
+ clearLicense() {
1016
+ localStorage.removeItem(this.prefix + "license");
1017
+ }
1018
+ /**
1019
+ * Get the cached offline token
1020
+ * @returns {import('./types.js').OfflineToken|null} Offline token or null if not found
1021
+ */
1022
+ getOfflineToken() {
1023
+ try {
1024
+ const data = localStorage.getItem(this.prefix + "offline_token");
1025
+ return data ? JSON.parse(data) : null;
1026
+ } catch (e) {
1027
+ console.error("Failed to read offline token cache:", e);
1028
+ return null;
1029
+ }
1030
+ }
1031
+ /**
1032
+ * Store offline token data in cache
1033
+ * @param {import('./types.js').OfflineToken} data - Offline token to cache
1034
+ * @returns {void}
1035
+ */
1036
+ setOfflineToken(data) {
1037
+ try {
1038
+ localStorage.setItem(
1039
+ this.prefix + "offline_token",
1040
+ JSON.stringify(data)
1041
+ );
1042
+ } catch (e) {
1043
+ console.error("Failed to cache offline token:", e);
1044
+ }
1045
+ }
1046
+ /**
1047
+ * Clear the cached offline token
1048
+ * @returns {void}
1049
+ */
1050
+ clearOfflineToken() {
1051
+ localStorage.removeItem(this.prefix + "offline_token");
1052
+ }
1053
+ /**
1054
+ * Get a cached public key by key ID
1055
+ * @param {string} keyId - The key ID to look up
1056
+ * @returns {string|null} Base64-encoded public key or null if not found
1057
+ */
1058
+ getPublicKey(keyId) {
1059
+ try {
1060
+ const cache = JSON.parse(
1061
+ localStorage.getItem(this.publicKeyCacheKey) || "{}"
1062
+ );
1063
+ return cache[keyId] || null;
1064
+ } catch (e) {
1065
+ console.error("Failed to read public key cache:", e);
1066
+ return null;
1067
+ }
1068
+ }
1069
+ /**
1070
+ * Store a public key in cache
1071
+ * @param {string} keyId - The key ID
1072
+ * @param {string} publicKeyB64 - Base64-encoded public key
1073
+ * @returns {void}
1074
+ */
1075
+ setPublicKey(keyId, publicKeyB64) {
1076
+ try {
1077
+ const cache = JSON.parse(
1078
+ localStorage.getItem(this.publicKeyCacheKey) || "{}"
1079
+ );
1080
+ cache[keyId] = publicKeyB64;
1081
+ localStorage.setItem(this.publicKeyCacheKey, JSON.stringify(cache));
1082
+ } catch (e) {
1083
+ console.error("Failed to cache public key:", e);
1084
+ }
1085
+ }
1086
+ /**
1087
+ * Clear all LicenseSeat SDK data for this prefix
1088
+ * @returns {void}
1089
+ */
1090
+ clear() {
1091
+ Object.keys(localStorage).forEach((key) => {
1092
+ if (key.startsWith(this.prefix)) {
1093
+ localStorage.removeItem(key);
1094
+ }
1095
+ });
1096
+ }
1097
+ /**
1098
+ * Get the last seen timestamp (for clock tamper detection)
1099
+ * @returns {number|null} Unix timestamp in milliseconds or null if not set
1100
+ */
1101
+ getLastSeenTimestamp() {
1102
+ const v = localStorage.getItem(this.prefix + "last_seen_ts");
1103
+ return v ? parseInt(v, 10) : null;
1104
+ }
1105
+ /**
1106
+ * Store the last seen timestamp
1107
+ * @param {number} ts - Unix timestamp in milliseconds
1108
+ * @returns {void}
1109
+ */
1110
+ setLastSeenTimestamp(ts) {
1111
+ try {
1112
+ localStorage.setItem(this.prefix + "last_seen_ts", String(ts));
1113
+ } catch (e) {
1114
+ }
1115
+ }
1116
+ };
1117
+
1118
+ // src/errors.js
1119
+ var APIError = class extends Error {
1120
+ /**
1121
+ * Create an APIError
1122
+ * @param {string} message - Error message
1123
+ * @param {number} status - HTTP status code (0 for network failures)
1124
+ * @param {import('./types.js').APIErrorData} [data] - Additional error data from the API response
1125
+ */
1126
+ constructor(message, status, data) {
1127
+ super(message);
1128
+ this.name = "APIError";
1129
+ this.status = status;
1130
+ this.data = data;
1131
+ }
1132
+ };
1133
+ var ConfigurationError = class extends Error {
1134
+ /**
1135
+ * Create a ConfigurationError
1136
+ * @param {string} message - Error message
1137
+ */
1138
+ constructor(message) {
1139
+ super(message);
1140
+ this.name = "ConfigurationError";
1141
+ }
1142
+ };
1143
+ var LicenseError = class extends Error {
1144
+ /**
1145
+ * Create a LicenseError
1146
+ * @param {string} message - Error message
1147
+ * @param {string} [code] - Machine-readable error code
1148
+ */
1149
+ constructor(message, code) {
1150
+ super(message);
1151
+ this.name = "LicenseError";
1152
+ this.code = code;
1153
+ }
1154
+ };
1155
+ var CryptoError = class extends Error {
1156
+ /**
1157
+ * Create a CryptoError
1158
+ * @param {string} message - Error message
1159
+ */
1160
+ constructor(message) {
1161
+ super(message);
1162
+ this.name = "CryptoError";
1163
+ }
1164
+ };
1165
+
1166
+ // node_modules/canonical-json/stringify.js
1167
+ var gap = "";
1168
+ var indent = "";
1169
+ var rep;
1170
+ var cmp;
1171
+ var escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g;
1172
+ var meta = { "\b": "\\b", " ": "\\t", "\n": "\\n", "\f": "\\f", "\r": "\\r", '"': '\\"', "\\": "\\\\" };
1173
+ function quote(str2) {
1174
+ escapable.lastIndex = 0;
1175
+ return escapable.test(str2) ? '"' + str2.replace(escapable, (a) => meta[a] || "\\u" + ("0000" + a.charCodeAt(0).toString(16)).slice(-4)) + '"' : '"' + str2 + '"';
1176
+ }
1177
+ function str(key, holder) {
1178
+ let value = holder[key];
1179
+ if (value && typeof value === "object" && typeof value.toJSON === "function") {
1180
+ value = value.toJSON(key);
1181
+ }
1182
+ if (typeof rep === "function") {
1183
+ value = rep.call(holder, key, value);
1184
+ }
1185
+ switch (typeof value) {
1186
+ case "string":
1187
+ return quote(value);
1188
+ case "number":
1189
+ return isFinite(value) ? String(value) : "null";
1190
+ case "boolean":
1191
+ case "undefined":
1192
+ case "object":
1193
+ if (value === null)
1194
+ return "null";
1195
+ const mind = gap;
1196
+ gap += indent;
1197
+ const partial = [];
1198
+ if (Array.isArray(value)) {
1199
+ for (let i = 0; i < value.length; i++)
1200
+ partial[i] = str(i, value) || "null";
1201
+ } else {
1202
+ const keys = Object.keys(value).sort(cmp);
1203
+ for (const k of keys) {
1204
+ if (Object.prototype.hasOwnProperty.call(value, k)) {
1205
+ const v2 = str(k, value);
1206
+ if (v2)
1207
+ partial.push(quote(k) + (gap ? ": " : ":") + v2);
1208
+ }
1209
+ }
1210
+ }
1211
+ let v;
1212
+ if (Array.isArray(value)) {
1213
+ v = partial.length === 0 ? "[]" : gap ? "[\n" + gap + partial.join(",\n" + gap) + "\n" + mind + "]" : "[" + partial.join(",") + "]";
1214
+ } else {
1215
+ v = partial.length === 0 ? "{}" : gap ? "{\n" + gap + partial.join(",\n" + gap) + "\n" + mind + "}" : "{" + partial.join(",") + "}";
1216
+ }
1217
+ gap = mind;
1218
+ return v;
1219
+ default:
1220
+ return String(value);
1221
+ }
1222
+ }
1223
+ function stringify(value, replacer, space, keyCompare) {
1224
+ gap = "";
1225
+ indent = "";
1226
+ rep = replacer;
1227
+ cmp = typeof keyCompare === "function" ? keyCompare : void 0;
1228
+ if (typeof space === "number") {
1229
+ indent = " ".repeat(space);
1230
+ } else if (typeof space === "string") {
1231
+ indent = space;
1232
+ }
1233
+ return str("", { "": value });
1234
+ }
1235
+
1236
+ // node_modules/canonical-json/index.js
1237
+ var canonical_json_default = stringify;
1238
+
1239
+ // src/utils.js
1240
+ function parseActiveEntitlements(payload = {}) {
1241
+ const raw = payload.entitlements || payload.active_entitlements || [];
1242
+ return raw.map((e) => ({
1243
+ key: e.key,
1244
+ expires_at: e.expires_at ?? null,
1245
+ metadata: e.metadata ?? null
1246
+ }));
1247
+ }
1248
+ function constantTimeEqual(a = "", b = "") {
1249
+ if (a.length !== b.length)
1250
+ return false;
1251
+ let res = 0;
1252
+ for (let i = 0; i < a.length; i++) {
1253
+ res |= a.charCodeAt(i) ^ b.charCodeAt(i);
1254
+ }
1255
+ return res === 0;
1256
+ }
1257
+ function canonicalJsonStringify(obj) {
1258
+ const stringify2 = typeof canonical_json_default === "function" ? canonical_json_default : canonical_json_default && typeof canonical_json_default === "object" ? (
1259
+ /** @type {any} */
1260
+ canonical_json_default.stringify
1261
+ ) : void 0;
1262
+ if (!stringify2 || typeof stringify2 !== "function") {
1263
+ console.warn(
1264
+ "[LicenseSeat SDK] canonical-json library not loaded correctly. Falling back to basic JSON.stringify. Signature verification might be unreliable if server uses different canonicalization."
1265
+ );
1266
+ try {
1267
+ const sortedObj = {};
1268
+ Object.keys(obj).sort().forEach((key) => {
1269
+ sortedObj[key] = obj[key];
1270
+ });
1271
+ return JSON.stringify(sortedObj);
1272
+ } catch (e) {
1273
+ return JSON.stringify(obj);
1274
+ }
1275
+ }
1276
+ return stringify2(obj);
1277
+ }
1278
+ function base64UrlDecode(base64UrlString) {
1279
+ let base64 = base64UrlString.replace(/-/g, "+").replace(/_/g, "/");
1280
+ while (base64.length % 4) {
1281
+ base64 += "=";
1282
+ }
1283
+ let raw;
1284
+ if (typeof atob === "function") {
1285
+ raw = atob(base64);
1286
+ } else if (typeof Buffer !== "undefined") {
1287
+ raw = Buffer.from(base64, "base64").toString("binary");
1288
+ } else {
1289
+ throw new Error("No base64 decoder available (neither atob nor Buffer found)");
1290
+ }
1291
+ const outputArray = new Uint8Array(raw.length);
1292
+ for (let i = 0; i < raw.length; ++i) {
1293
+ outputArray[i] = raw.charCodeAt(i);
1294
+ }
1295
+ return outputArray;
1296
+ }
1297
+ function hashCode(str2) {
1298
+ let hash = 0;
1299
+ for (let i = 0; i < str2.length; i++) {
1300
+ const char = str2.charCodeAt(i);
1301
+ hash = (hash << 5) - hash + char;
1302
+ hash = hash & hash;
1303
+ }
1304
+ return Math.abs(hash).toString(36);
1305
+ }
1306
+ function getCanvasFingerprint() {
1307
+ try {
1308
+ const canvas = document.createElement("canvas");
1309
+ const ctx = canvas.getContext("2d");
1310
+ ctx.textBaseline = "top";
1311
+ ctx.font = "14px Arial";
1312
+ ctx.fillText("LicenseSeat SDK", 2, 2);
1313
+ return canvas.toDataURL().slice(-50);
1314
+ } catch (e) {
1315
+ return "no-canvas";
1316
+ }
1317
+ }
1318
+ function generateDeviceId() {
1319
+ if (typeof window === "undefined" || typeof navigator === "undefined") {
1320
+ const os = typeof process !== "undefined" ? process.platform : "unknown";
1321
+ const arch = typeof process !== "undefined" ? process.arch : "unknown";
1322
+ return `node-${hashCode(os + "|" + arch)}`;
1323
+ }
1324
+ const nav = window.navigator;
1325
+ const screen = window.screen;
1326
+ const data = [
1327
+ nav.userAgent,
1328
+ nav.language,
1329
+ screen.colorDepth,
1330
+ screen.width + "x" + screen.height,
1331
+ (/* @__PURE__ */ new Date()).getTimezoneOffset(),
1332
+ nav.hardwareConcurrency,
1333
+ getCanvasFingerprint()
1334
+ ].join("|");
1335
+ return `web-${hashCode(data)}`;
1336
+ }
1337
+ function sleep(ms) {
1338
+ return new Promise((resolve) => setTimeout(resolve, ms));
1339
+ }
1340
+ function getCsrfToken() {
1341
+ const token = document.querySelector('meta[name="csrf-token"]');
1342
+ return token ? token.content : "";
1343
+ }
1344
+
1345
+ // src/LicenseSeat.js
1346
+ var DEFAULT_CONFIG = {
1347
+ apiBaseUrl: "https://licenseseat.com/api/v1",
1348
+ productSlug: null,
1349
+ // Required: Product slug for API calls (e.g., "my-app")
1350
+ storagePrefix: "licenseseat_",
1351
+ autoValidateInterval: 36e5,
1352
+ // 1 hour
1353
+ networkRecheckInterval: 3e4,
1354
+ // 30 seconds
1355
+ maxRetries: 3,
1356
+ retryDelay: 1e3,
1357
+ apiKey: null,
1358
+ debug: false,
1359
+ offlineLicenseRefreshInterval: 1e3 * 60 * 60 * 72,
1360
+ // 72 hours
1361
+ offlineFallbackEnabled: false,
1362
+ // default false (strict mode, matches Swift SDK)
1363
+ maxOfflineDays: 0,
1364
+ // 0 = disabled
1365
+ maxClockSkewMs: 5 * 60 * 1e3,
1366
+ // 5 minutes
1367
+ autoInitialize: true
1368
+ };
1369
+ var LicenseSeatSDK = class {
1370
+ /**
1371
+ * Create a new LicenseSeat SDK instance
1372
+ * @param {import('./types.js').LicenseSeatConfig} [config={}] - Configuration options
1373
+ */
1374
+ constructor(config = {}) {
1375
+ this.config = {
1376
+ ...DEFAULT_CONFIG,
1377
+ ...config
1378
+ };
1379
+ this.eventListeners = {};
1380
+ this.validationTimer = null;
1381
+ this.cache = new LicenseCache(this.config.storagePrefix);
1382
+ this.online = true;
1383
+ this.currentAutoLicenseKey = null;
1384
+ this.connectivityTimer = null;
1385
+ this.offlineRefreshTimer = null;
1386
+ this.lastOfflineValidation = null;
1387
+ this.syncingOfflineAssets = false;
1388
+ this.destroyed = false;
1389
+ if (ed25519_exports && etc && sha5122) {
1390
+ etc.sha512Sync = (...m) => sha5122(etc.concatBytes(...m));
1391
+ } else {
1392
+ console.error(
1393
+ "[LicenseSeat SDK] Noble-ed25519 or Noble-hashes not loaded correctly. Sync crypto methods may fail."
1394
+ );
1395
+ }
1396
+ if (this.config.autoInitialize) {
1397
+ this.initialize();
1398
+ }
1399
+ }
1400
+ /**
1401
+ * Initialize the SDK
1402
+ * Loads cached license and starts auto-validation if configured.
1403
+ * Called automatically unless autoInitialize is set to false.
1404
+ * @returns {void}
1405
+ */
1406
+ initialize() {
1407
+ this.log("LicenseSeat SDK initialized", this.config);
1408
+ const cachedLicense = this.cache.getLicense();
1409
+ if (cachedLicense) {
1410
+ this.emit("license:loaded", cachedLicense);
1411
+ if (this.config.offlineFallbackEnabled) {
1412
+ this.quickVerifyCachedOfflineLocal().then((offlineResult) => {
1413
+ if (offlineResult) {
1414
+ this.cache.updateValidation(offlineResult);
1415
+ if (offlineResult.valid) {
1416
+ this.emit("validation:offline-success", offlineResult);
1417
+ } else {
1418
+ this.emit("validation:offline-failed", offlineResult);
1419
+ }
1420
+ this.lastOfflineValidation = offlineResult;
1421
+ }
1422
+ }).catch(() => {
1423
+ });
1424
+ }
1425
+ if (this.config.apiKey) {
1426
+ this.startAutoValidation(cachedLicense.license_key);
1427
+ this.validateLicense(cachedLicense.license_key).catch((err2) => {
1428
+ this.log("Background validation failed:", err2);
1429
+ if (err2 instanceof APIError && (err2.status === 401 || err2.status === 501)) {
1430
+ this.log(
1431
+ "Authentication issue during validation, using cached license data"
1432
+ );
1433
+ this.emit("validation:auth-failed", {
1434
+ licenseKey: cachedLicense.license_key,
1435
+ error: err2,
1436
+ cached: true
1437
+ });
1438
+ }
1439
+ });
1440
+ }
1441
+ }
1442
+ }
1443
+ /**
1444
+ * Activate a license
1445
+ * @param {string} licenseKey - The license key to activate
1446
+ * @param {import('./types.js').ActivationOptions} [options={}] - Activation options
1447
+ * @returns {Promise<import('./types.js').CachedLicense>} Activation result with cached license data
1448
+ * @throws {ConfigurationError} When productSlug is not configured
1449
+ * @throws {APIError} When the API request fails
1450
+ */
1451
+ async activate(licenseKey, options = {}) {
1452
+ if (!this.config.productSlug) {
1453
+ throw new ConfigurationError("productSlug is required for activation");
1454
+ }
1455
+ const deviceId = options.deviceId || generateDeviceId();
1456
+ const payload = {
1457
+ device_id: deviceId,
1458
+ metadata: options.metadata || {}
1459
+ };
1460
+ if (options.deviceName) {
1461
+ payload.device_name = options.deviceName;
1462
+ }
1463
+ try {
1464
+ this.emit("activation:start", { licenseKey, deviceId });
1465
+ const response = await this.apiCall(
1466
+ `/products/${this.config.productSlug}/licenses/${encodeURIComponent(licenseKey)}/activate`,
1467
+ {
1468
+ method: "POST",
1469
+ body: payload
1470
+ }
1471
+ );
1472
+ const licenseData = {
1473
+ license_key: licenseKey,
1474
+ device_id: deviceId,
1475
+ activation: response,
1476
+ activated_at: (/* @__PURE__ */ new Date()).toISOString(),
1477
+ last_validated: (/* @__PURE__ */ new Date()).toISOString()
1478
+ };
1479
+ this.cache.setLicense(licenseData);
1480
+ this.cache.updateValidation({ valid: true, optimistic: true });
1481
+ this.startAutoValidation(licenseKey);
1482
+ this.syncOfflineAssets();
1483
+ this.scheduleOfflineRefresh();
1484
+ this.emit("activation:success", licenseData);
1485
+ return licenseData;
1486
+ } catch (error) {
1487
+ this.emit("activation:error", { licenseKey, error });
1488
+ throw error;
1489
+ }
1490
+ }
1491
+ /**
1492
+ * Deactivate the current license
1493
+ * @returns {Promise<Object>} Deactivation result from the API
1494
+ * @throws {ConfigurationError} When productSlug is not configured
1495
+ * @throws {LicenseError} When no active license is found
1496
+ * @throws {APIError} When the API request fails
1497
+ */
1498
+ async deactivate() {
1499
+ if (!this.config.productSlug) {
1500
+ throw new ConfigurationError("productSlug is required for deactivation");
1501
+ }
1502
+ const cachedLicense = this.cache.getLicense();
1503
+ if (!cachedLicense) {
1504
+ throw new LicenseError("No active license found", "no_license");
1505
+ }
1506
+ try {
1507
+ this.emit("deactivation:start", cachedLicense);
1508
+ const response = await this.apiCall(
1509
+ `/products/${this.config.productSlug}/licenses/${encodeURIComponent(cachedLicense.license_key)}/deactivate`,
1510
+ {
1511
+ method: "POST",
1512
+ body: {
1513
+ device_id: cachedLicense.device_id
1514
+ }
1515
+ }
1516
+ );
1517
+ this.cache.clearLicense();
1518
+ this.cache.clearOfflineToken();
1519
+ this.stopAutoValidation();
1520
+ this.emit("deactivation:success", response);
1521
+ return response;
1522
+ } catch (error) {
1523
+ this.emit("deactivation:error", { error, license: cachedLicense });
1524
+ throw error;
1525
+ }
1526
+ }
1527
+ /**
1528
+ * Validate a license
1529
+ * @param {string} licenseKey - License key to validate
1530
+ * @param {import('./types.js').ValidationOptions} [options={}] - Validation options
1531
+ * @returns {Promise<import('./types.js').ValidationResult>} Validation result
1532
+ * @throws {ConfigurationError} When productSlug is not configured
1533
+ * @throws {APIError} When the API request fails and offline fallback is not available
1534
+ */
1535
+ async validateLicense(licenseKey, options = {}) {
1536
+ if (!this.config.productSlug) {
1537
+ throw new ConfigurationError("productSlug is required for validation");
1538
+ }
1539
+ try {
1540
+ this.emit("validation:start", { licenseKey });
1541
+ const rawResponse = await this.apiCall(
1542
+ `/products/${this.config.productSlug}/licenses/${encodeURIComponent(licenseKey)}/validate`,
1543
+ {
1544
+ method: "POST",
1545
+ body: {
1546
+ device_id: options.deviceId || this.cache.getDeviceId()
1547
+ }
1548
+ }
1549
+ );
1550
+ const response = {
1551
+ valid: rawResponse.valid,
1552
+ code: rawResponse.code,
1553
+ message: rawResponse.message,
1554
+ warnings: rawResponse.warnings,
1555
+ license: rawResponse.license,
1556
+ activation: rawResponse.activation,
1557
+ // Extract entitlements from license for easy access
1558
+ active_entitlements: rawResponse.license?.active_entitlements || []
1559
+ };
1560
+ const cachedLicense = this.cache.getLicense();
1561
+ if ((!response.active_entitlements || response.active_entitlements.length === 0) && cachedLicense?.validation?.active_entitlements?.length) {
1562
+ response.active_entitlements = cachedLicense.validation.active_entitlements;
1563
+ }
1564
+ if (cachedLicense && cachedLicense.license_key === licenseKey) {
1565
+ this.cache.updateValidation(response);
1566
+ }
1567
+ if (response.valid) {
1568
+ this.emit("validation:success", response);
1569
+ this.cache.setLastSeenTimestamp(Date.now());
1570
+ } else {
1571
+ this.emit("validation:failed", response);
1572
+ this.stopAutoValidation();
1573
+ this.currentAutoLicenseKey = null;
1574
+ }
1575
+ this.cache.setLastSeenTimestamp(Date.now());
1576
+ return response;
1577
+ } catch (error) {
1578
+ this.emit("validation:error", { licenseKey, error });
1579
+ const isNetworkFailure = error instanceof TypeError && error.message.includes("fetch") || error instanceof APIError && [0, 408].includes(error.status);
1580
+ if (this.config.offlineFallbackEnabled && isNetworkFailure) {
1581
+ const offlineResult = await this.verifyCachedOffline();
1582
+ const cachedLicense = this.cache.getLicense();
1583
+ if (cachedLicense && cachedLicense.license_key === licenseKey) {
1584
+ this.cache.updateValidation(offlineResult);
1585
+ }
1586
+ if (offlineResult.valid) {
1587
+ this.emit("validation:offline-success", offlineResult);
1588
+ return offlineResult;
1589
+ } else {
1590
+ this.emit("validation:offline-failed", offlineResult);
1591
+ this.stopAutoValidation();
1592
+ this.currentAutoLicenseKey = null;
1593
+ }
1594
+ }
1595
+ if (error instanceof APIError && error.data) {
1596
+ const cachedLicense = this.cache.getLicense();
1597
+ if (cachedLicense && cachedLicense.license_key === licenseKey) {
1598
+ const errorCode = error.data.error?.code || error.data.code;
1599
+ const errorMessage = error.data.error?.message || error.data.message;
1600
+ this.cache.updateValidation({
1601
+ valid: false,
1602
+ code: errorCode,
1603
+ message: errorMessage
1604
+ });
1605
+ }
1606
+ if (![0, 408, 429].includes(error.status)) {
1607
+ this.stopAutoValidation();
1608
+ this.currentAutoLicenseKey = null;
1609
+ }
1610
+ }
1611
+ throw error;
1612
+ }
1613
+ }
1614
+ /**
1615
+ * Check if a specific entitlement is active (detailed version)
1616
+ * @param {string} entitlementKey - The entitlement key to check
1617
+ * @returns {import('./types.js').EntitlementCheckResult} Entitlement status with details
1618
+ */
1619
+ checkEntitlement(entitlementKey) {
1620
+ const license = this.cache.getLicense();
1621
+ if (!license || !license.validation) {
1622
+ return { active: false, reason: "no_license" };
1623
+ }
1624
+ const entitlements = license.validation.active_entitlements || [];
1625
+ const entitlement = entitlements.find((e) => e.key === entitlementKey);
1626
+ if (!entitlement) {
1627
+ return { active: false, reason: "not_found" };
1628
+ }
1629
+ if (entitlement.expires_at) {
1630
+ const expiresAt = new Date(entitlement.expires_at);
1631
+ const now = /* @__PURE__ */ new Date();
1632
+ if (expiresAt < now) {
1633
+ return {
1634
+ active: false,
1635
+ reason: "expired",
1636
+ expires_at: entitlement.expires_at
1637
+ };
1638
+ }
1639
+ }
1640
+ return { active: true, entitlement };
1641
+ }
1642
+ /**
1643
+ * Check if a specific entitlement is active (simple boolean version)
1644
+ * This is a convenience method that returns a simple boolean.
1645
+ * Use checkEntitlement() for detailed status information.
1646
+ * @param {string} entitlementKey - The entitlement key to check
1647
+ * @returns {boolean} True if the entitlement is active, false otherwise
1648
+ */
1649
+ hasEntitlement(entitlementKey) {
1650
+ return this.checkEntitlement(entitlementKey).active;
1651
+ }
1652
+ /**
1653
+ * Get offline token data from the server
1654
+ * @param {Object} [options={}] - Options for offline token generation
1655
+ * @param {string} [options.deviceId] - Device ID to bind the token to (required for hardware_locked mode)
1656
+ * @param {number} [options.ttlDays] - Token lifetime in days (default: 30, max: 90)
1657
+ * @returns {Promise<import('./types.js').OfflineToken>} Offline token data
1658
+ * @throws {ConfigurationError} When productSlug is not configured
1659
+ * @throws {LicenseError} When no active license is found
1660
+ * @throws {APIError} When the API request fails
1661
+ */
1662
+ async getOfflineToken(options = {}) {
1663
+ if (!this.config.productSlug) {
1664
+ throw new ConfigurationError("productSlug is required for offline token");
1665
+ }
1666
+ const license = this.cache.getLicense();
1667
+ if (!license || !license.license_key) {
1668
+ const errorMsg = "No active license key found in cache to fetch offline token.";
1669
+ this.emit("sdk:error", { message: errorMsg });
1670
+ throw new LicenseError(errorMsg, "no_license");
1671
+ }
1672
+ try {
1673
+ this.emit("offlineToken:fetching", { licenseKey: license.license_key });
1674
+ const body = {};
1675
+ if (options.deviceId) {
1676
+ body.device_id = options.deviceId;
1677
+ }
1678
+ if (options.ttlDays) {
1679
+ body.ttl_days = options.ttlDays;
1680
+ }
1681
+ const path = `/products/${this.config.productSlug}/licenses/${encodeURIComponent(license.license_key)}/offline-token`;
1682
+ const response = await this.apiCall(path, {
1683
+ method: "POST",
1684
+ body: Object.keys(body).length > 0 ? body : void 0
1685
+ });
1686
+ this.emit("offlineToken:fetched", {
1687
+ licenseKey: license.license_key,
1688
+ data: response
1689
+ });
1690
+ return response;
1691
+ } catch (error) {
1692
+ this.log(
1693
+ `Failed to get offline token for ${license.license_key}:`,
1694
+ error
1695
+ );
1696
+ this.emit("offlineToken:fetchError", {
1697
+ licenseKey: license.license_key,
1698
+ error
1699
+ });
1700
+ throw error;
1701
+ }
1702
+ }
1703
+ /**
1704
+ * Fetch a signing key from the server by key ID
1705
+ * @param {string} keyId - The Key ID (kid) for which to fetch the signing key
1706
+ * @returns {Promise<import('./types.js').SigningKey>} Signing key data
1707
+ * @throws {Error} When keyId is not provided or the key is not found
1708
+ */
1709
+ async getSigningKey(keyId) {
1710
+ if (!keyId) {
1711
+ throw new Error("Key ID is required to fetch a signing key.");
1712
+ }
1713
+ try {
1714
+ this.log(`Fetching signing key for kid: ${keyId}`);
1715
+ const response = await this.apiCall(`/signing-keys/${encodeURIComponent(keyId)}`, {
1716
+ method: "GET"
1717
+ });
1718
+ if (response && response.public_key) {
1719
+ this.log(`Successfully fetched signing key for kid: ${keyId}`);
1720
+ return response;
1721
+ } else {
1722
+ throw new Error(
1723
+ `Signing key not found or invalid response for kid: ${keyId}`
1724
+ );
1725
+ }
1726
+ } catch (error) {
1727
+ this.log(`Failed to fetch signing key for kid ${keyId}:`, error);
1728
+ throw error;
1729
+ }
1730
+ }
1731
+ /**
1732
+ * Verify a signed offline token client-side using Ed25519
1733
+ * @param {import('./types.js').OfflineToken} offlineTokenData - The offline token data
1734
+ * @param {string} publicKeyB64 - Base64-encoded public Ed25519 key
1735
+ * @returns {Promise<boolean>} True if verification is successful
1736
+ * @throws {CryptoError} When crypto library is not available
1737
+ * @throws {Error} When inputs are invalid
1738
+ */
1739
+ async verifyOfflineToken(offlineTokenData, publicKeyB64) {
1740
+ this.log("Attempting to verify offline token client-side.");
1741
+ if (!offlineTokenData || !offlineTokenData.canonical || !offlineTokenData.signature) {
1742
+ throw new Error("Invalid offline token object provided. Expected format: { token, signature, canonical }");
1743
+ }
1744
+ if (!publicKeyB64) {
1745
+ throw new Error("Public key (Base64 encoded) is required.");
1746
+ }
1747
+ if (!ed25519_exports || !verify || !etc.sha512Sync) {
1748
+ const err2 = new CryptoError(
1749
+ "noble-ed25519 crypto library not available/configured for offline verification."
1750
+ );
1751
+ this.emit("sdk:error", { message: err2.message });
1752
+ throw err2;
1753
+ }
1754
+ try {
1755
+ const messageBytes = new TextEncoder().encode(offlineTokenData.canonical);
1756
+ const signatureBytes = base64UrlDecode(offlineTokenData.signature.value);
1757
+ const publicKeyBytes = base64UrlDecode(publicKeyB64);
1758
+ const isValid = verify(signatureBytes, messageBytes, publicKeyBytes);
1759
+ if (isValid) {
1760
+ this.log("Offline token signature VERIFIED successfully client-side.");
1761
+ this.emit("offlineToken:verified", { token: offlineTokenData.token });
1762
+ } else {
1763
+ this.log("Offline token signature INVALID client-side.");
1764
+ this.emit("offlineToken:verificationFailed", { token: offlineTokenData.token });
1765
+ }
1766
+ return isValid;
1767
+ } catch (error) {
1768
+ this.log("Client-side offline token verification error:", error);
1769
+ this.emit("sdk:error", {
1770
+ message: "Client-side verification failed.",
1771
+ error
1772
+ });
1773
+ throw error;
1774
+ }
1775
+ }
1776
+ /**
1777
+ * Get current license status
1778
+ * @returns {import('./types.js').LicenseStatus} Current license status
1779
+ */
1780
+ getStatus() {
1781
+ const license = this.cache.getLicense();
1782
+ if (!license) {
1783
+ return { status: "inactive", message: "No license activated" };
1784
+ }
1785
+ const validation = license.validation;
1786
+ if (!validation) {
1787
+ return { status: "pending", message: "License pending validation" };
1788
+ }
1789
+ if (!validation.valid) {
1790
+ if (validation.offline) {
1791
+ return {
1792
+ status: "offline-invalid",
1793
+ message: validation.code || "License invalid (offline)"
1794
+ };
1795
+ }
1796
+ return {
1797
+ status: "invalid",
1798
+ message: validation.message || validation.code || "License invalid"
1799
+ };
1800
+ }
1801
+ if (validation.offline) {
1802
+ return {
1803
+ status: "offline-valid",
1804
+ license: license.license_key,
1805
+ device: license.device_id,
1806
+ activated_at: license.activated_at,
1807
+ last_validated: license.last_validated,
1808
+ entitlements: validation.active_entitlements || []
1809
+ };
1810
+ }
1811
+ return {
1812
+ status: "active",
1813
+ license: license.license_key,
1814
+ device: license.device_id,
1815
+ activated_at: license.activated_at,
1816
+ last_validated: license.last_validated,
1817
+ entitlements: validation.active_entitlements || []
1818
+ };
1819
+ }
1820
+ /**
1821
+ * Test API connectivity
1822
+ * Makes a request to the health endpoint to verify connectivity.
1823
+ * Note: To fully verify API key validity, attempt an actual operation like activate() or validateLicense().
1824
+ * @returns {Promise<{authenticated: boolean, healthy: boolean, api_version: string}>}
1825
+ * @throws {ConfigurationError} If API key is not configured
1826
+ * @throws {APIError} If the health check fails
1827
+ */
1828
+ async testAuth() {
1829
+ if (!this.config.apiKey) {
1830
+ const err2 = new ConfigurationError("API key is required for auth test");
1831
+ this.emit("auth_test:error", { error: err2 });
1832
+ throw err2;
1833
+ }
1834
+ try {
1835
+ this.emit("auth_test:start");
1836
+ const response = await this.apiCall("/health", { method: "GET" });
1837
+ const result = {
1838
+ authenticated: true,
1839
+ // API key was included in request
1840
+ healthy: response.status === "healthy",
1841
+ api_version: response.api_version
1842
+ };
1843
+ this.emit("auth_test:success", result);
1844
+ return result;
1845
+ } catch (error) {
1846
+ this.emit("auth_test:error", { error });
1847
+ throw error;
1848
+ }
1849
+ }
1850
+ /**
1851
+ * Clear all data and reset SDK state
1852
+ * @returns {void}
1853
+ */
1854
+ reset() {
1855
+ this.stopAutoValidation();
1856
+ this.stopConnectivityPolling();
1857
+ if (this.offlineRefreshTimer) {
1858
+ clearInterval(this.offlineRefreshTimer);
1859
+ this.offlineRefreshTimer = null;
1860
+ }
1861
+ this.cache.clear();
1862
+ this.lastOfflineValidation = null;
1863
+ this.currentAutoLicenseKey = null;
1864
+ this.emit("sdk:reset");
1865
+ }
1866
+ /**
1867
+ * Destroy the SDK instance and release all resources
1868
+ * Call this when you no longer need the SDK to prevent memory leaks.
1869
+ * After calling destroy(), the SDK instance should not be used.
1870
+ * @returns {void}
1871
+ */
1872
+ destroy() {
1873
+ this.destroyed = true;
1874
+ this.stopAutoValidation();
1875
+ this.stopConnectivityPolling();
1876
+ if (this.offlineRefreshTimer) {
1877
+ clearInterval(this.offlineRefreshTimer);
1878
+ this.offlineRefreshTimer = null;
1879
+ }
1880
+ this.eventListeners = {};
1881
+ this.cache.clear();
1882
+ this.lastOfflineValidation = null;
1883
+ this.currentAutoLicenseKey = null;
1884
+ this.emit("sdk:destroyed");
1885
+ }
1886
+ // ============================================================
1887
+ // Event Handling
1888
+ // ============================================================
1889
+ /**
1890
+ * Subscribe to an event
1891
+ * @param {string} event - Event name
1892
+ * @param {import('./types.js').EventCallback} callback - Event handler
1893
+ * @returns {import('./types.js').EventUnsubscribe} Unsubscribe function
1894
+ */
1895
+ on(event, callback) {
1896
+ if (!this.eventListeners[event]) {
1897
+ this.eventListeners[event] = [];
1898
+ }
1899
+ this.eventListeners[event].push(callback);
1900
+ return () => this.off(event, callback);
1901
+ }
1902
+ /**
1903
+ * Unsubscribe from an event
1904
+ * @param {string} event - Event name
1905
+ * @param {import('./types.js').EventCallback} callback - Event handler to remove
1906
+ * @returns {void}
1907
+ */
1908
+ off(event, callback) {
1909
+ if (this.eventListeners[event]) {
1910
+ this.eventListeners[event] = this.eventListeners[event].filter(
1911
+ (cb) => cb !== callback
1912
+ );
1913
+ }
1914
+ }
1915
+ /**
1916
+ * Emit an event
1917
+ * @param {string} event - Event name
1918
+ * @param {*} data - Event data
1919
+ * @returns {void}
1920
+ * @private
1921
+ */
1922
+ emit(event, data) {
1923
+ this.log(`Event: ${event}`, data);
1924
+ if (this.eventListeners[event]) {
1925
+ this.eventListeners[event].forEach((callback) => {
1926
+ try {
1927
+ callback(data);
1928
+ } catch (error) {
1929
+ console.error(`Error in event listener for ${event}:`, error);
1930
+ }
1931
+ });
1932
+ }
1933
+ }
1934
+ // ============================================================
1935
+ // Auto-Validation & Connectivity
1936
+ // ============================================================
1937
+ /**
1938
+ * Start automatic license validation
1939
+ * @param {string} licenseKey - License key to validate
1940
+ * @returns {void}
1941
+ * @private
1942
+ */
1943
+ startAutoValidation(licenseKey) {
1944
+ this.stopAutoValidation();
1945
+ this.currentAutoLicenseKey = licenseKey;
1946
+ const validationInterval = this.config.autoValidateInterval;
1947
+ const performAndReschedule = () => {
1948
+ this.validateLicense(licenseKey).catch((err2) => {
1949
+ this.log("Auto-validation failed:", err2);
1950
+ this.emit("validation:auto-failed", { licenseKey, error: err2 });
1951
+ });
1952
+ this.emit("autovalidation:cycle", {
1953
+ nextRunAt: new Date(Date.now() + validationInterval)
1954
+ });
1955
+ };
1956
+ this.validationTimer = setInterval(performAndReschedule, validationInterval);
1957
+ this.emit("autovalidation:cycle", {
1958
+ nextRunAt: new Date(Date.now() + validationInterval)
1959
+ });
1960
+ }
1961
+ /**
1962
+ * Stop automatic validation
1963
+ * @returns {void}
1964
+ * @private
1965
+ */
1966
+ stopAutoValidation() {
1967
+ if (this.validationTimer) {
1968
+ clearInterval(this.validationTimer);
1969
+ this.validationTimer = null;
1970
+ this.emit("autovalidation:stopped");
1971
+ }
1972
+ }
1973
+ /**
1974
+ * Start connectivity polling (when offline)
1975
+ * @returns {void}
1976
+ * @private
1977
+ */
1978
+ startConnectivityPolling() {
1979
+ if (this.connectivityTimer)
1980
+ return;
1981
+ const healthCheck = async () => {
1982
+ try {
1983
+ await fetch(`${this.config.apiBaseUrl}/health`, {
1984
+ method: "GET",
1985
+ credentials: "omit"
1986
+ });
1987
+ if (!this.online) {
1988
+ this.online = true;
1989
+ this.emit("network:online");
1990
+ if (this.currentAutoLicenseKey && !this.validationTimer) {
1991
+ this.startAutoValidation(this.currentAutoLicenseKey);
1992
+ }
1993
+ this.syncOfflineAssets();
1994
+ }
1995
+ this.stopConnectivityPolling();
1996
+ } catch (err2) {
1997
+ }
1998
+ };
1999
+ this.connectivityTimer = setInterval(
2000
+ healthCheck,
2001
+ this.config.networkRecheckInterval
2002
+ );
2003
+ }
2004
+ /**
2005
+ * Stop connectivity polling
2006
+ * @returns {void}
2007
+ * @private
2008
+ */
2009
+ stopConnectivityPolling() {
2010
+ if (this.connectivityTimer) {
2011
+ clearInterval(this.connectivityTimer);
2012
+ this.connectivityTimer = null;
2013
+ }
2014
+ }
2015
+ // ============================================================
2016
+ // Offline License Management
2017
+ // ============================================================
2018
+ /**
2019
+ * Fetch and cache offline token and signing key
2020
+ * Uses a lock to prevent concurrent calls from causing race conditions
2021
+ * @returns {Promise<void>}
2022
+ * @private
2023
+ */
2024
+ async syncOfflineAssets() {
2025
+ if (this.syncingOfflineAssets || this.destroyed) {
2026
+ this.log("Skipping syncOfflineAssets: already syncing or destroyed");
2027
+ return;
2028
+ }
2029
+ this.syncingOfflineAssets = true;
2030
+ try {
2031
+ const offline = await this.getOfflineToken();
2032
+ this.cache.setOfflineToken(offline);
2033
+ const kid = offline.signature?.key_id || offline.token?.kid;
2034
+ if (kid) {
2035
+ const existingKey = this.cache.getPublicKey(kid);
2036
+ if (!existingKey) {
2037
+ const signingKey = await this.getSigningKey(kid);
2038
+ this.cache.setPublicKey(kid, signingKey.public_key);
2039
+ }
2040
+ }
2041
+ this.emit("offlineToken:ready", {
2042
+ kid,
2043
+ exp: offline.token?.exp
2044
+ });
2045
+ const res = await this.quickVerifyCachedOfflineLocal();
2046
+ if (res) {
2047
+ this.cache.updateValidation(res);
2048
+ this.emit(
2049
+ res.valid ? "validation:offline-success" : "validation:offline-failed",
2050
+ res
2051
+ );
2052
+ }
2053
+ } catch (err2) {
2054
+ this.log("Failed to sync offline assets:", err2);
2055
+ } finally {
2056
+ this.syncingOfflineAssets = false;
2057
+ }
2058
+ }
2059
+ /**
2060
+ * Schedule periodic offline license refresh
2061
+ * @returns {void}
2062
+ * @private
2063
+ */
2064
+ scheduleOfflineRefresh() {
2065
+ if (this.offlineRefreshTimer)
2066
+ clearInterval(this.offlineRefreshTimer);
2067
+ this.offlineRefreshTimer = setInterval(
2068
+ () => this.syncOfflineAssets(),
2069
+ this.config.offlineLicenseRefreshInterval
2070
+ );
2071
+ }
2072
+ /**
2073
+ * Verify cached offline token
2074
+ * @returns {Promise<import('./types.js').ValidationResult>}
2075
+ * @private
2076
+ */
2077
+ async verifyCachedOffline() {
2078
+ const signed = this.cache.getOfflineToken();
2079
+ if (!signed) {
2080
+ return { valid: false, offline: true, code: "no_offline_token" };
2081
+ }
2082
+ const kid = signed.signature?.key_id || signed.token?.kid;
2083
+ let pub = kid ? this.cache.getPublicKey(kid) : null;
2084
+ if (!pub) {
2085
+ try {
2086
+ const signingKey = await this.getSigningKey(kid);
2087
+ pub = signingKey.public_key;
2088
+ this.cache.setPublicKey(kid, pub);
2089
+ } catch (e) {
2090
+ return { valid: false, offline: true, code: "no_public_key" };
2091
+ }
2092
+ }
2093
+ try {
2094
+ const ok = await this.verifyOfflineToken(signed, pub);
2095
+ if (!ok) {
2096
+ return { valid: false, offline: true, code: "signature_invalid" };
2097
+ }
2098
+ const token = signed.token;
2099
+ const cached = this.cache.getLicense();
2100
+ if (!cached || !constantTimeEqual(token.license_key || "", cached.license_key || "")) {
2101
+ return { valid: false, offline: true, code: "license_mismatch" };
2102
+ }
2103
+ const now = Date.now();
2104
+ const expAt = token.exp ? token.exp * 1e3 : null;
2105
+ if (expAt && expAt < now) {
2106
+ return { valid: false, offline: true, code: "expired" };
2107
+ }
2108
+ if (!expAt && this.config.maxOfflineDays > 0) {
2109
+ const pivot = cached.last_validated || cached.activated_at;
2110
+ if (pivot) {
2111
+ const ageMs = now - new Date(pivot).getTime();
2112
+ if (ageMs > this.config.maxOfflineDays * 24 * 60 * 60 * 1e3) {
2113
+ return {
2114
+ valid: false,
2115
+ offline: true,
2116
+ code: "grace_period_expired"
2117
+ };
2118
+ }
2119
+ }
2120
+ }
2121
+ const lastSeen = this.cache.getLastSeenTimestamp();
2122
+ if (lastSeen && now + this.config.maxClockSkewMs < lastSeen) {
2123
+ return { valid: false, offline: true, code: "clock_tamper" };
2124
+ }
2125
+ this.cache.setLastSeenTimestamp(now);
2126
+ const active = parseActiveEntitlements(token);
2127
+ return {
2128
+ valid: true,
2129
+ offline: true,
2130
+ ...active.length ? { active_entitlements: active } : {}
2131
+ };
2132
+ } catch (e) {
2133
+ return { valid: false, offline: true, code: "verification_error" };
2134
+ }
2135
+ }
2136
+ /**
2137
+ * Quick offline verification using only local data (no network)
2138
+ * Performs signature verification plus basic validity checks (expiry, license key match)
2139
+ * @returns {Promise<import('./types.js').ValidationResult|null>}
2140
+ * @private
2141
+ */
2142
+ async quickVerifyCachedOfflineLocal() {
2143
+ const signed = this.cache.getOfflineToken();
2144
+ if (!signed)
2145
+ return null;
2146
+ const kid = signed.signature?.key_id || signed.token?.kid;
2147
+ const pub = kid ? this.cache.getPublicKey(kid) : null;
2148
+ if (!pub)
2149
+ return null;
2150
+ try {
2151
+ const ok = await this.verifyOfflineToken(signed, pub);
2152
+ if (!ok) {
2153
+ return { valid: false, offline: true, code: "signature_invalid" };
2154
+ }
2155
+ const token = signed.token;
2156
+ const cached = this.cache.getLicense();
2157
+ if (!cached || !constantTimeEqual(token.license_key || "", cached.license_key || "")) {
2158
+ return { valid: false, offline: true, code: "license_mismatch" };
2159
+ }
2160
+ const now = Date.now();
2161
+ const expAt = token.exp ? token.exp * 1e3 : null;
2162
+ if (expAt && expAt < now) {
2163
+ return { valid: false, offline: true, code: "expired" };
2164
+ }
2165
+ const lastSeen = this.cache.getLastSeenTimestamp();
2166
+ if (lastSeen && now + this.config.maxClockSkewMs < lastSeen) {
2167
+ return { valid: false, offline: true, code: "clock_tamper" };
2168
+ }
2169
+ const active = parseActiveEntitlements(token);
2170
+ return {
2171
+ valid: true,
2172
+ offline: true,
2173
+ ...active.length ? { active_entitlements: active } : {}
2174
+ };
2175
+ } catch (_) {
2176
+ return { valid: false, offline: true, code: "verification_error" };
2177
+ }
2178
+ }
2179
+ // ============================================================
2180
+ // API Communication
2181
+ // ============================================================
2182
+ /**
2183
+ * Make an API call with retry logic
2184
+ * @param {string} endpoint - API endpoint (will be appended to apiBaseUrl)
2185
+ * @param {Object} [options={}] - Fetch options
2186
+ * @param {string} [options.method="GET"] - HTTP method
2187
+ * @param {Object} [options.body] - Request body (will be JSON-stringified)
2188
+ * @param {Object} [options.headers] - Additional headers
2189
+ * @returns {Promise<Object>} API response data
2190
+ * @throws {APIError} When the request fails after all retries
2191
+ * @private
2192
+ */
2193
+ async apiCall(endpoint, options = {}) {
2194
+ const url = `${this.config.apiBaseUrl}${endpoint}`;
2195
+ let lastError;
2196
+ const headers = {
2197
+ "Content-Type": "application/json",
2198
+ Accept: "application/json",
2199
+ ...options.headers
2200
+ };
2201
+ if (this.config.apiKey) {
2202
+ headers["Authorization"] = `Bearer ${this.config.apiKey}`;
2203
+ } else {
2204
+ this.log(
2205
+ "[Warning] No API key configured for LicenseSeat SDK. Authenticated endpoints will fail."
2206
+ );
2207
+ }
2208
+ for (let attempt = 0; attempt <= this.config.maxRetries; attempt++) {
2209
+ try {
2210
+ const response = await fetch(url, {
2211
+ method: options.method || "GET",
2212
+ headers,
2213
+ body: options.body ? JSON.stringify(options.body) : void 0,
2214
+ credentials: "omit"
2215
+ });
2216
+ const data = await response.json();
2217
+ if (!response.ok) {
2218
+ const errorObj = data.error;
2219
+ let errorMessage = "Request failed";
2220
+ if (typeof errorObj === "object" && errorObj !== null) {
2221
+ errorMessage = errorObj.message || "Request failed";
2222
+ } else if (typeof errorObj === "string") {
2223
+ errorMessage = errorObj;
2224
+ }
2225
+ throw new APIError(errorMessage, response.status, data);
2226
+ }
2227
+ if (!this.online) {
2228
+ this.online = true;
2229
+ this.emit("network:online");
2230
+ }
2231
+ this.stopConnectivityPolling();
2232
+ if (!this.validationTimer && this.currentAutoLicenseKey) {
2233
+ this.startAutoValidation(this.currentAutoLicenseKey);
2234
+ }
2235
+ return data;
2236
+ } catch (error) {
2237
+ const networkFailure = error instanceof TypeError && error.message.includes("fetch") || error instanceof APIError && error.status === 0;
2238
+ if (networkFailure && this.online) {
2239
+ this.online = false;
2240
+ this.emit("network:offline", { error });
2241
+ this.stopAutoValidation();
2242
+ this.startConnectivityPolling();
2243
+ }
2244
+ lastError = error;
2245
+ const shouldRetry = attempt < this.config.maxRetries && this.shouldRetryError(error);
2246
+ if (shouldRetry) {
2247
+ const delay = this.config.retryDelay * Math.pow(2, attempt);
2248
+ this.log(
2249
+ `Retry attempt ${attempt + 1} after ${delay}ms for error:`,
2250
+ error.message
2251
+ );
2252
+ await sleep(delay);
2253
+ } else {
2254
+ throw error;
2255
+ }
2256
+ }
2257
+ }
2258
+ throw lastError;
2259
+ }
2260
+ /**
2261
+ * Determine if an error should be retried
2262
+ * @param {Error} error - The error to check
2263
+ * @returns {boolean} True if the error should trigger a retry
2264
+ * @private
2265
+ */
2266
+ shouldRetryError(error) {
2267
+ if (error instanceof TypeError && error.message.includes("fetch")) {
2268
+ return true;
2269
+ }
2270
+ if (error instanceof APIError) {
2271
+ const status = error.status;
2272
+ if (status >= 502 && status < 600) {
2273
+ return true;
2274
+ }
2275
+ if (status === 0 || status === 408 || status === 429) {
2276
+ return true;
2277
+ }
2278
+ return false;
2279
+ }
2280
+ return false;
2281
+ }
2282
+ // ============================================================
2283
+ // Utilities
2284
+ // ============================================================
2285
+ /**
2286
+ * Get CSRF token from meta tag
2287
+ * @returns {string} CSRF token or empty string
2288
+ */
2289
+ getCsrfToken() {
2290
+ return getCsrfToken();
2291
+ }
2292
+ /**
2293
+ * Log a message (if debug mode is enabled)
2294
+ * @param {...*} args - Arguments to log
2295
+ * @returns {void}
2296
+ * @private
2297
+ */
2298
+ log(...args) {
2299
+ if (this.config.debug) {
2300
+ console.log("[LicenseSeat SDK]", ...args);
2301
+ }
2302
+ }
2303
+ };
2304
+ var sharedInstance = null;
2305
+ function getSharedInstance(config) {
2306
+ if (!sharedInstance) {
2307
+ sharedInstance = new LicenseSeatSDK(config);
2308
+ }
2309
+ return sharedInstance;
2310
+ }
2311
+ function configure(config, force = false) {
2312
+ if (sharedInstance && !force) {
2313
+ console.warn(
2314
+ "[LicenseSeat SDK] Already configured. Call configure with force=true to reconfigure."
2315
+ );
2316
+ return sharedInstance;
2317
+ }
2318
+ sharedInstance = new LicenseSeatSDK(config);
2319
+ return sharedInstance;
2320
+ }
2321
+ function resetSharedInstance() {
2322
+ if (sharedInstance) {
2323
+ sharedInstance.reset();
2324
+ sharedInstance = null;
2325
+ }
2326
+ }
2327
+
2328
+ // src/index.js
2329
+ var src_default = LicenseSeatSDK;
2330
+ return __toCommonJS(src_exports);
2331
+ })();
2332
+ /*! Bundled license information:
2333
+
2334
+ @noble/ed25519/index.js:
2335
+ (*! noble-ed25519 - MIT License (c) 2019 Paul Miller (paulmillr.com) *)
2336
+
2337
+ @noble/hashes/esm/utils.js:
2338
+ (*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) *)
2339
+ */