@codeo-engineering/licenserail-youtrack 0.0.0-stage → 0.1.0

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,657 @@
1
+ // licenserail-embedded (MIT, Codeo Solutions Limited), bundled for YouTrack apps. Do not edit; update with licenserail-youtrack.
2
+ "use strict";
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
7
+ var __export = (target, all) => {
8
+ for (var name in all)
9
+ __defProp(target, name, { get: all[name], enumerable: true });
10
+ };
11
+ var __copyProps = (to, from, except, desc) => {
12
+ if (from && typeof from === "object" || typeof from === "function") {
13
+ for (let key of __getOwnPropNames(from))
14
+ if (!__hasOwnProp.call(to, key) && key !== except)
15
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
16
+ }
17
+ return to;
18
+ };
19
+ var __toCommonJS = (mod2) => __copyProps(__defProp({}, "__esModule", { value: true }), mod2);
20
+
21
+ // ../embedded/src/index.ts
22
+ var index_exports = {};
23
+ __export(index_exports, {
24
+ HOST_PLATFORMS: () => HOST_PLATFORMS,
25
+ INSTALLATION_HEADER: () => INSTALLATION_HEADER,
26
+ REVOKING_CODES: () => REVOKING_CODES,
27
+ UNAVAILABLE: () => UNAVAILABLE,
28
+ activateRequest: () => activateRequest,
29
+ base64Decode: () => base64Decode,
30
+ createLicenseClient: () => createLicenseClient,
31
+ deactivateRequest: () => deactivateRequest,
32
+ decodeTokenUnverified: () => decodeTokenUnverified,
33
+ evaluate: () => evaluate,
34
+ fingerprintMatches: () => fingerprintMatches,
35
+ hasFeature: () => hasFeature,
36
+ hashComponent: () => hashComponent,
37
+ hex: () => hex,
38
+ installationFingerprint: () => installationFingerprint,
39
+ isHostInstallation: () => isHostInstallation,
40
+ parsePublicKey: () => parsePublicKey,
41
+ readResponse: () => readResponse,
42
+ refreshDueAt: () => refreshDueAt,
43
+ refreshRequest: () => refreshRequest,
44
+ sha256: () => sha256,
45
+ summarize: () => summarize,
46
+ trialRequest: () => trialRequest,
47
+ utf8Decode: () => utf8Decode,
48
+ utf8Encode: () => utf8Encode,
49
+ verifyP256: () => verifyP256,
50
+ verifyToken: () => verifyToken,
51
+ verifyTokenAsync: () => verifyTokenAsync
52
+ });
53
+ module.exports = __toCommonJS(index_exports);
54
+
55
+ // ../embedded/src/encoding.ts
56
+ function utf8Encode(text) {
57
+ const out = [];
58
+ for (let i = 0; i < text.length; i++) {
59
+ let c = text.charCodeAt(i);
60
+ if (c >= 55296 && c < 56320 && i + 1 < text.length) {
61
+ const d = text.charCodeAt(i + 1);
62
+ if (d >= 56320 && d < 57344) {
63
+ c = 65536 + (c - 55296 << 10) + (d - 56320);
64
+ i++;
65
+ }
66
+ }
67
+ if (c < 128) out.push(c);
68
+ else if (c < 2048) out.push(192 | c >> 6, 128 | c & 63);
69
+ else if (c < 65536) out.push(224 | c >> 12, 128 | c >> 6 & 63, 128 | c & 63);
70
+ else out.push(240 | c >> 18, 128 | c >> 12 & 63, 128 | c >> 6 & 63, 128 | c & 63);
71
+ }
72
+ return out;
73
+ }
74
+ function utf8Decode(bytes) {
75
+ let out = "";
76
+ for (let i = 0; i < bytes.length; ) {
77
+ const b = bytes[i];
78
+ let cp = 65533, len = 1;
79
+ if (b < 128) {
80
+ cp = b;
81
+ } else if (b >= 194 && b < 224 && cont(bytes, i + 1)) {
82
+ cp = (b & 31) << 6 | bytes[i + 1] & 63;
83
+ len = 2;
84
+ } else if (b >= 224 && b < 240 && cont(bytes, i + 1) && cont(bytes, i + 2)) {
85
+ const v = (b & 15) << 12 | (bytes[i + 1] & 63) << 6 | bytes[i + 2] & 63;
86
+ if (v >= 2048 && (v < 55296 || v > 57343)) {
87
+ cp = v;
88
+ len = 3;
89
+ }
90
+ } else if (b >= 240 && b < 245 && cont(bytes, i + 1) && cont(bytes, i + 2) && cont(bytes, i + 3)) {
91
+ const v = (b & 7) << 18 | (bytes[i + 1] & 63) << 12 | (bytes[i + 2] & 63) << 6 | bytes[i + 3] & 63;
92
+ if (v >= 65536 && v <= 1114111) {
93
+ cp = v;
94
+ len = 4;
95
+ }
96
+ }
97
+ if (cp > 65535) {
98
+ cp -= 65536;
99
+ out += String.fromCharCode(55296 + (cp >> 10), 56320 + (cp & 1023));
100
+ } else out += String.fromCharCode(cp);
101
+ i += len;
102
+ }
103
+ return out;
104
+ }
105
+ function cont(bytes, i) {
106
+ return i < bytes.length && (bytes[i] & 192) === 128;
107
+ }
108
+ var B64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
109
+ function base64Decode(text) {
110
+ const s = text.replace(/[\s=]/g, "").replace(/-/g, "+").replace(/_/g, "/");
111
+ const out = [];
112
+ let acc = 0, bits = 0;
113
+ for (let i = 0; i < s.length; i++) {
114
+ const v = B64.indexOf(s.charAt(i));
115
+ if (v < 0) return null;
116
+ acc = (acc << 6 | v) & 16777215;
117
+ bits += 6;
118
+ if (bits >= 8) {
119
+ bits -= 8;
120
+ out.push(acc >> bits & 255);
121
+ }
122
+ }
123
+ return out;
124
+ }
125
+ function hex(bytes) {
126
+ let out = "";
127
+ for (let i = 0; i < bytes.length; i++) out += (bytes[i] < 16 ? "0" : "") + bytes[i].toString(16);
128
+ return out;
129
+ }
130
+
131
+ // ../embedded/src/sha256.ts
132
+ var K = [
133
+ 1116352408,
134
+ 1899447441,
135
+ 3049323471,
136
+ 3921009573,
137
+ 961987163,
138
+ 1508970993,
139
+ 2453635748,
140
+ 2870763221,
141
+ 3624381080,
142
+ 310598401,
143
+ 607225278,
144
+ 1426881987,
145
+ 1925078388,
146
+ 2162078206,
147
+ 2614888103,
148
+ 3248222580,
149
+ 3835390401,
150
+ 4022224774,
151
+ 264347078,
152
+ 604807628,
153
+ 770255983,
154
+ 1249150122,
155
+ 1555081692,
156
+ 1996064986,
157
+ 2554220882,
158
+ 2821834349,
159
+ 2952996808,
160
+ 3210313671,
161
+ 3336571891,
162
+ 3584528711,
163
+ 113926993,
164
+ 338241895,
165
+ 666307205,
166
+ 773529912,
167
+ 1294757372,
168
+ 1396182291,
169
+ 1695183700,
170
+ 1986661051,
171
+ 2177026350,
172
+ 2456956037,
173
+ 2730485921,
174
+ 2820302411,
175
+ 3259730800,
176
+ 3345764771,
177
+ 3516065817,
178
+ 3600352804,
179
+ 4094571909,
180
+ 275423344,
181
+ 430227734,
182
+ 506948616,
183
+ 659060556,
184
+ 883997877,
185
+ 958139571,
186
+ 1322822218,
187
+ 1537002063,
188
+ 1747873779,
189
+ 1955562222,
190
+ 2024104815,
191
+ 2227730452,
192
+ 2361852424,
193
+ 2428436474,
194
+ 2756734187,
195
+ 3204031479,
196
+ 3329325298
197
+ ];
198
+ var rotr = (x, n) => x >>> n | x << 32 - n;
199
+ function sha256(bytes) {
200
+ const m = Array.prototype.slice.call(bytes);
201
+ const bitLength = bytes.length * 8;
202
+ m.push(128);
203
+ while (m.length % 64 !== 56) m.push(0);
204
+ const hi = Math.floor(bitLength / 4294967296), lo = bitLength >>> 0;
205
+ m.push(hi >>> 24, hi >>> 16 & 255, hi >>> 8 & 255, hi & 255, lo >>> 24, lo >>> 16 & 255, lo >>> 8 & 255, lo & 255);
206
+ const h = [1779033703, 3144134277, 1013904242, 2773480762, 1359893119, 2600822924, 528734635, 1541459225];
207
+ const w = new Array(64);
208
+ for (let off = 0; off < m.length; off += 64) {
209
+ for (let t = 0; t < 64; t++) {
210
+ if (t < 16) w[t] = m[off + 4 * t] << 24 | m[off + 4 * t + 1] << 16 | m[off + 4 * t + 2] << 8 | m[off + 4 * t + 3];
211
+ else {
212
+ const s0 = rotr(w[t - 15], 7) ^ rotr(w[t - 15], 18) ^ w[t - 15] >>> 3;
213
+ const s1 = rotr(w[t - 2], 17) ^ rotr(w[t - 2], 19) ^ w[t - 2] >>> 10;
214
+ w[t] = w[t - 16] + s0 + w[t - 7] + s1 | 0;
215
+ }
216
+ }
217
+ let [a, b, c, d, e, f, g, k] = h;
218
+ for (let t = 0; t < 64; t++) {
219
+ const t1 = k + (rotr(e, 6) ^ rotr(e, 11) ^ rotr(e, 25)) + (e & f ^ ~e & g) + K[t] + w[t] | 0;
220
+ const t2 = (rotr(a, 2) ^ rotr(a, 13) ^ rotr(a, 22)) + (a & b ^ a & c ^ b & c) | 0;
221
+ k = g;
222
+ g = f;
223
+ f = e;
224
+ e = d + t1 | 0;
225
+ d = c;
226
+ c = b;
227
+ b = a;
228
+ a = t1 + t2 | 0;
229
+ }
230
+ h[0] = h[0] + a | 0;
231
+ h[1] = h[1] + b | 0;
232
+ h[2] = h[2] + c | 0;
233
+ h[3] = h[3] + d | 0;
234
+ h[4] = h[4] + e | 0;
235
+ h[5] = h[5] + f | 0;
236
+ h[6] = h[6] + g | 0;
237
+ h[7] = h[7] + k | 0;
238
+ }
239
+ const out = [];
240
+ for (let i = 0; i < 8; i++) out.push(h[i] >>> 24, h[i] >>> 16 & 255, h[i] >>> 8 & 255, h[i] & 255);
241
+ return out;
242
+ }
243
+
244
+ // ../embedded/src/p256.ts
245
+ var P = 0xffffffff00000001000000000000000000000000ffffffffffffffffffffffffn;
246
+ var N = 0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551n;
247
+ var B = 0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604bn;
248
+ var G = {
249
+ x: 0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296n,
250
+ y: 0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5n,
251
+ z: 1n
252
+ };
253
+ var INFINITY = { x: 0n, y: 1n, z: 0n };
254
+ function toInt(bytes) {
255
+ let r = 0n;
256
+ for (let i = 0; i < bytes.length; i++) r = r << 8n | BigInt(bytes[i]);
257
+ return r;
258
+ }
259
+ function mod(a, m) {
260
+ const r = a % m;
261
+ return r < 0n ? r + m : r;
262
+ }
263
+ function pow(a, e, m) {
264
+ let r = 1n;
265
+ a = mod(a, m);
266
+ while (e > 0n) {
267
+ if (e & 1n) r = r * a % m;
268
+ a = a * a % m;
269
+ e >>= 1n;
270
+ }
271
+ return r;
272
+ }
273
+ var invert = (a, m) => pow(a, m - 2n, m);
274
+ function double(p) {
275
+ if (p.z === 0n || p.y === 0n) return INFINITY;
276
+ const delta = p.z * p.z % P, gamma = p.y * p.y % P, beta = p.x * gamma % P;
277
+ const alpha = 3n * mod(p.x - delta, P) * (p.x + delta) % P;
278
+ const x = mod(alpha * alpha - 8n * beta, P);
279
+ const z = mod((p.y + p.z) * (p.y + p.z) - gamma - delta, P);
280
+ const y = mod(alpha * (4n * beta - x) - 8n * gamma * gamma, P);
281
+ return { x, y, z };
282
+ }
283
+ function add(p, q) {
284
+ if (p.z === 0n) return q;
285
+ if (q.z === 0n) return p;
286
+ const z1z1 = p.z * p.z % P, z2z2 = q.z * q.z % P;
287
+ const u1 = p.x * z2z2 % P, u2 = q.x * z1z1 % P;
288
+ const s1 = p.y * q.z % P * z2z2 % P, s2 = q.y * p.z % P * z1z1 % P;
289
+ const h = mod(u2 - u1, P), r = mod(s2 - s1, P);
290
+ if (h === 0n) return r === 0n ? double(p) : INFINITY;
291
+ const hh = h * h % P, hhh = hh * h % P, v = u1 * hh % P;
292
+ const x = mod(r * r - hhh - 2n * v, P);
293
+ const y = mod(r * (v - x) - s1 * hhh, P);
294
+ return { x, y, z: p.z * q.z % P * h % P };
295
+ }
296
+ function mulAdd(u1, u2, q) {
297
+ const gq = add(G, q);
298
+ let r = INFINITY;
299
+ for (let i = 255; i >= 0; i--) {
300
+ r = double(r);
301
+ const b1 = u1 >> BigInt(i) & 1n, b2 = u2 >> BigInt(i) & 1n;
302
+ if (b1 && b2) r = add(r, gq);
303
+ else if (b1) r = add(r, G);
304
+ else if (b2) r = add(r, q);
305
+ }
306
+ return r;
307
+ }
308
+ var SPKI_HEADER = [
309
+ 48,
310
+ 89,
311
+ 48,
312
+ 19,
313
+ 6,
314
+ 7,
315
+ 42,
316
+ 134,
317
+ 72,
318
+ 206,
319
+ 61,
320
+ 2,
321
+ 1,
322
+ 6,
323
+ 8,
324
+ 42,
325
+ 134,
326
+ 72,
327
+ 206,
328
+ 61,
329
+ 3,
330
+ 1,
331
+ 7,
332
+ 3,
333
+ 66,
334
+ 0
335
+ ];
336
+ function parsePublicKey(pem) {
337
+ const der = base64Decode(pem.replace(/-----(BEGIN|END) PUBLIC KEY-----/g, ""));
338
+ if (!der || der.length !== 91 || der[26] !== 4) return null;
339
+ for (let i = 0; i < SPKI_HEADER.length; i++) if (der[i] !== SPKI_HEADER[i]) return null;
340
+ return { x: der.slice(27, 59), y: der.slice(59, 91) };
341
+ }
342
+ function verifyP256(publicKeyPem, data, signature) {
343
+ const key = parsePublicKey(publicKeyPem);
344
+ if (!key || signature.length !== 64) return false;
345
+ const qx = toInt(key.x), qy = toInt(key.y);
346
+ if (qx >= P || qy >= P || mod(qy * qy - (qx * qx * qx - 3n * qx + B), P) !== 0n) return false;
347
+ const sig = Array.prototype.slice.call(signature);
348
+ const r = toInt(sig.slice(0, 32)), s = toInt(sig.slice(32, 64));
349
+ if (r < 1n || r >= N || s < 1n || s >= N) return false;
350
+ const e = toInt(sha256(data));
351
+ const w = invert(s, N);
352
+ const point = mulAdd(e * w % N, r * w % N, { x: qx, y: qy, z: 1n });
353
+ if (point.z === 0n) return false;
354
+ const zi = invert(point.z, P);
355
+ const x = point.x * zi % P * zi % P;
356
+ return x % N === r;
357
+ }
358
+
359
+ // ../embedded/src/token.ts
360
+ function split(token) {
361
+ if (!token || typeof token !== "string") return null;
362
+ const parts = token.trim().split(".");
363
+ if (parts.length !== 2 || !parts[0] || !parts[1]) return null;
364
+ const signature = base64Decode(parts[1]);
365
+ const body = base64Decode(parts[0]);
366
+ if (!signature || signature.length !== 64 || !body) return null;
367
+ try {
368
+ const payload = JSON.parse(utf8Decode(body));
369
+ if (!payload || typeof payload !== "object" || !payload.fingerprint) return null;
370
+ return { signed: utf8Encode(parts[0]), signature, payload };
371
+ } catch {
372
+ return null;
373
+ }
374
+ }
375
+ function verifyToken(token, publicKeyPem) {
376
+ const parts = split(token);
377
+ return parts && verifyP256(publicKeyPem, parts.signed, parts.signature) ? parts.payload : null;
378
+ }
379
+ function subtle() {
380
+ const c = globalThis.crypto;
381
+ return c && c.subtle && typeof c.subtle.verify === "function" ? c.subtle : null;
382
+ }
383
+ async function verifyTokenAsync(token, publicKeyPem) {
384
+ const s = subtle();
385
+ if (!s || typeof Uint8Array === "undefined") return verifyToken(token, publicKeyPem);
386
+ const parts = split(token);
387
+ const key = parsePublicKey(publicKeyPem);
388
+ if (!parts || !key) return null;
389
+ try {
390
+ const der = base64Decode(publicKeyPem.replace(/-----(BEGIN|END) PUBLIC KEY-----/g, ""));
391
+ const cryptoKey = await s.importKey("spki", new Uint8Array(der).buffer, { name: "ECDSA", namedCurve: "P-256" }, false, ["verify"]);
392
+ const ok = await s.verify({ name: "ECDSA", hash: "SHA-256" }, cryptoKey, new Uint8Array(parts.signature).buffer, new Uint8Array(parts.signed).buffer);
393
+ return ok ? parts.payload : null;
394
+ } catch {
395
+ return verifyToken(token, publicKeyPem);
396
+ }
397
+ }
398
+ function decodeTokenUnverified(token) {
399
+ return split(token)?.payload ?? null;
400
+ }
401
+
402
+ // ../embedded/src/fingerprint.ts
403
+ var UNAVAILABLE = "none";
404
+ var HOST_PLATFORMS = ["youtrack"];
405
+ function hashComponent(vendor, product, part, raw) {
406
+ if (raw == null || raw.trim() === "") return UNAVAILABLE;
407
+ return hex(sha256(utf8Encode(`${vendor}:${product}:${part}:${raw.trim().toUpperCase()}`)));
408
+ }
409
+ function installationFingerprint(vendor, product, platform, installationId) {
410
+ return {
411
+ machineId: hashComponent(vendor, product, "installation", installationId),
412
+ diskId: UNAVAILABLE,
413
+ hostName: UNAVAILABLE,
414
+ boardId: UNAVAILABLE,
415
+ os: platform.toLowerCase()
416
+ };
417
+ }
418
+ var isHostInstallation = (f) => !!f.os && HOST_PLATFORMS.indexOf(f.os.toLowerCase()) >= 0;
419
+ var available = (v) => !!v && v !== UNAVAILABLE;
420
+ var same = (a, b) => available(a) && a === b;
421
+ function fingerprintMatches(registered, presented) {
422
+ if (isHostInstallation(registered) || isHostInstallation(presented))
423
+ return (registered.os ?? "").toLowerCase() === (presented.os ?? "").toLowerCase() && same(registered.machineId, presented.machineId);
424
+ if (registered.os && presented.os && registered.os.toLowerCase() !== presented.os.toLowerCase()) return false;
425
+ let matches = 0;
426
+ if (same(registered.machineId, presented.machineId)) matches++;
427
+ if (same(registered.diskId, presented.diskId)) matches++;
428
+ if (same(registered.hostName, presented.hostName)) matches++;
429
+ return available(registered.boardId) ? same(registered.boardId, presented.boardId) && matches >= 1 : matches >= 2;
430
+ }
431
+
432
+ // ../embedded/src/evaluate.ts
433
+ var CLOCK_TOLERANCE_MS = 10 * 60 * 1e3;
434
+ var ISSUED_AT_TOLERANCE_MS = 24 * 60 * 60 * 1e3;
435
+ function evaluate(payload, product, machine, now, lastSeen) {
436
+ if (!payload) return "InvalidSignature";
437
+ if (payload.product.toLowerCase() !== product.toLowerCase()) return "WrongProduct";
438
+ if (!fingerprintMatches(payload.fingerprint, machine)) return "WrongMachine";
439
+ if (payload.suspended) return "Suspended";
440
+ if (!lastSeen) return "Unverified";
441
+ const t = now.getTime();
442
+ if (t + ISSUED_AT_TOLERANCE_MS < Date.parse(payload.issuedAt) || t + CLOCK_TOLERANCE_MS < lastSeen.getTime()) return "ClockTampered";
443
+ if (payload.expiresAt && t >= Date.parse(payload.expiresAt)) return "Expired";
444
+ if (t >= Date.parse(payload.offlineUntil)) return "OfflineTooLong";
445
+ return "Valid";
446
+ }
447
+ function summarize(payload, hostUsers) {
448
+ const max = typeof payload.maxHostUsers === "number" ? payload.maxHostUsers : null;
449
+ return {
450
+ isTrial: payload.trial === true || payload.kind === "trial",
451
+ isTest: payload.test === true,
452
+ expiresAt: payload.expiresAt ? new Date(payload.expiresAt) : null,
453
+ entitlements: payload.entitlements ?? [],
454
+ metadata: payload.metadata ?? {},
455
+ maxHostUsers: max,
456
+ hostUserPolicy: max === null ? null : payload.hostUserPolicy ?? "block",
457
+ hostUsersOverLimit: payload.hostUsersExceeded === true || max !== null && typeof hostUsers === "number" && hostUsers > max
458
+ };
459
+ }
460
+ var hasFeature = (payload, code) => (payload.entitlements ?? []).indexOf(code) >= 0;
461
+
462
+ // ../embedded/src/protocol.ts
463
+ var INSTALLATION_HEADER = "LicenseRail-Installation";
464
+ function url(apiUrl, path) {
465
+ return apiUrl.replace(/\/+$/, "") + "/api/client/v2" + path;
466
+ }
467
+ function headers(fingerprint) {
468
+ const h = { "Content-Type": "application/json" };
469
+ if (fingerprint.os) h[INSTALLATION_HEADER] = `${fingerprint.os}:${fingerprint.machineId}`.slice(0, 128);
470
+ return h;
471
+ }
472
+ function clean(o) {
473
+ const out = {};
474
+ for (const k of Object.keys(o)) if (o[k] !== void 0 && o[k] !== null) out[k] = o[k];
475
+ return out;
476
+ }
477
+ function activateRequest(o) {
478
+ const h = headers(o.fingerprint);
479
+ const inHeader = o.keyInHeader !== false;
480
+ if (o.licenseKey && inHeader) h.Authorization = `Bearer ${o.licenseKey}`;
481
+ return {
482
+ method: "POST",
483
+ url: url(o.apiUrl, o.floating ? "/floating/checkout" : "/activate"),
484
+ headers: h,
485
+ body: JSON.stringify(clean({
486
+ product: o.product,
487
+ fingerprint: o.fingerprint,
488
+ licenseKey: inHeader ? void 0 : o.licenseKey,
489
+ machineName: o.machineName,
490
+ appVersion: o.appVersion,
491
+ hostUsers: o.hostUsers
492
+ }))
493
+ };
494
+ }
495
+ function refreshRequest(o) {
496
+ return {
497
+ method: "POST",
498
+ url: url(o.apiUrl, o.floating ? "/floating/heartbeat" : "/refresh"),
499
+ headers: headers(o.fingerprint),
500
+ // appVersion is a required field of the refresh request (null allowed).
501
+ body: JSON.stringify({ ...clean({ token: o.token, fingerprint: o.fingerprint, anomalies: o.anomalies, hostUsers: o.hostUsers }), appVersion: o.appVersion ?? null })
502
+ };
503
+ }
504
+ function deactivateRequest(o) {
505
+ return {
506
+ method: "POST",
507
+ url: url(o.apiUrl, o.floating ? "/floating/release" : "/deactivate"),
508
+ headers: headers(o.fingerprint),
509
+ body: JSON.stringify({ token: o.token, fingerprint: o.fingerprint })
510
+ };
511
+ }
512
+ function trialRequest(o) {
513
+ return {
514
+ method: "POST",
515
+ url: url(o.apiUrl, "/trial"),
516
+ headers: headers(o.fingerprint),
517
+ body: JSON.stringify(clean({ keyId: o.keyId, product: o.product, fingerprint: o.fingerprint, machineName: o.machineName, appVersion: o.appVersion, hostUsers: o.hostUsers }))
518
+ };
519
+ }
520
+ var REVOKING_CODES = [
521
+ "license_not_found",
522
+ "license_suspended",
523
+ "license_expired",
524
+ "activation_revoked",
525
+ "wrong_machine",
526
+ "invalid_token",
527
+ "license_revoked"
528
+ ];
529
+ function readResponse(status, bodyText) {
530
+ let body = null;
531
+ try {
532
+ body = bodyText ? JSON.parse(bodyText) : null;
533
+ } catch {
534
+ body = null;
535
+ }
536
+ if (status >= 200 && status < 300) {
537
+ if (status === 204) return { ok: true, token: null };
538
+ if (body && typeof body.token === "string") return { ok: true, token: body.token };
539
+ }
540
+ const code = body && typeof body.code === "string" ? body.code : status === 0 ? "network_error" : `http_${status}`;
541
+ const message = body && typeof body.message === "string" ? body.message : status === 0 ? "The license server could not be reached." : "Unexpected response from the license server.";
542
+ return {
543
+ ok: false,
544
+ code,
545
+ message,
546
+ revokesLocalLicense: REVOKING_CODES.indexOf(code) >= 0,
547
+ retryLater: status === 0 || status === 429 || status === 402 || status >= 500
548
+ };
549
+ }
550
+ function refreshDueAt(payload) {
551
+ if (payload.trial === true) return null;
552
+ return new Date(payload.refreshAfter);
553
+ }
554
+
555
+ // ../embedded/src/client.ts
556
+ var fetchTransport = (timeoutMs) => async (r) => {
557
+ const host = globalThis;
558
+ if (!host.fetch) return { status: 0, body: "" };
559
+ const controller = host.AbortController && host.setTimeout ? new host.AbortController() : null;
560
+ const timer = controller ? host.setTimeout(() => controller.abort(), timeoutMs) : null;
561
+ try {
562
+ const res = await host.fetch(r.url, { method: r.method, headers: r.headers, body: r.body, ...controller ? { signal: controller.signal } : {} });
563
+ return { status: res.status, body: await res.text() };
564
+ } catch {
565
+ return { status: 0, body: "" };
566
+ } finally {
567
+ if (timer !== null) host.clearTimeout?.(timer);
568
+ }
569
+ };
570
+ function createLicenseClient(o) {
571
+ const send = o.transport ?? fetchTransport(o.timeoutMs ?? 1e4);
572
+ const now = () => o.now ? o.now() : /* @__PURE__ */ new Date();
573
+ const key = (k) => (o.prefix ?? "licenserail:") + k;
574
+ const target = { apiUrl: o.apiUrl, product: o.product, fingerprint: o.fingerprint };
575
+ async function load() {
576
+ const token = await o.storage.get(key("token"));
577
+ const seen = await o.storage.get(key("lastSeen"));
578
+ return { token, lastSeen: seen ? new Date(Number(seen)) : null };
579
+ }
580
+ async function state() {
581
+ const { token, lastSeen } = await load();
582
+ if (!token) return { status: "Missing", payload: null, summary: null };
583
+ const payload = await verifyTokenAsync(token, o.publicKeyPem);
584
+ const status = evaluate(payload, o.product, o.fingerprint, now(), lastSeen);
585
+ if (status === "Valid") await o.storage.set(key("lastSeen"), String(now().getTime()));
586
+ return { status, payload, summary: payload ? summarize(payload, o.hostUsers?.()) : null };
587
+ }
588
+ async function unidentified() {
589
+ if (fingerprintMatches(o.fingerprint, o.fingerprint)) return null;
590
+ return { ok: false, code: "device_not_identified", message: "This device can't be identified, so a license can't be activated on it.", state: await state() };
591
+ }
592
+ async function accept(response) {
593
+ const r = readResponse(response.status, response.body);
594
+ if (r.ok && r.token) {
595
+ const payload = await verifyTokenAsync(r.token, o.publicKeyPem);
596
+ if (!payload) return { ok: false, code: "invalid_token", message: "The license server returned a token that does not verify.", state: await state() };
597
+ await o.storage.set(key("token"), r.token);
598
+ await o.storage.set(key("lastSeen"), String(now().getTime()));
599
+ return { ok: true, state: await state() };
600
+ }
601
+ if (!r.ok) {
602
+ if (r.revokesLocalLicense) await o.storage.remove(key("token"));
603
+ return { ok: false, code: r.code, message: r.message, state: await state() };
604
+ }
605
+ return { ok: true, state: await state() };
606
+ }
607
+ return {
608
+ /** The current license, checked offline. */
609
+ state,
610
+ /** Activates a license key on this device or installation. */
611
+ async activate(licenseKey, floating = false) {
612
+ return await unidentified() ?? accept(await send(activateRequest({
613
+ ...target,
614
+ licenseKey,
615
+ machineName: o.machineName,
616
+ appVersion: o.appVersion,
617
+ hostUsers: o.hostUsers?.(),
618
+ floating
619
+ })));
620
+ },
621
+ /** Starts (or gets back) this device's or installation's keyless trial. */
622
+ async startTrial(keyId) {
623
+ return await unidentified() ?? accept(await send(trialRequest({ ...target, keyId, machineName: o.machineName, appVersion: o.appVersion, hostUsers: o.hostUsers?.() })));
624
+ },
625
+ /** Refreshes when the token asks for it (or always with force); keeps the token on network errors. */
626
+ async refresh(force = false) {
627
+ const { token } = await load();
628
+ const current = await state();
629
+ if (!token || !current.payload) return { ok: false, code: "no_license", message: "No license to refresh.", state: current };
630
+ const due = refreshDueAt(current.payload);
631
+ if (!force && (!due || due.getTime() > now().getTime())) return { ok: true, state: current };
632
+ return accept(await send(refreshRequest({
633
+ ...target,
634
+ token,
635
+ appVersion: o.appVersion,
636
+ hostUsers: o.hostUsers?.(),
637
+ floating: current.payload.floating === true
638
+ })));
639
+ },
640
+ /** Releases the license on this device or installation and removes it locally. */
641
+ async deactivate() {
642
+ const { token } = await load();
643
+ const current = await state();
644
+ if (!token || !current.payload || current.payload.trial) {
645
+ await o.storage.remove(key("token"));
646
+ return { ok: true, state: await state() };
647
+ }
648
+ const res = await send(deactivateRequest({ ...target, token, floating: current.payload.floating === true }));
649
+ const r = readResponse(res.status, res.body);
650
+ if (r.ok || r.revokesLocalLicense) {
651
+ await o.storage.remove(key("token"));
652
+ return { ok: true, state: await state() };
653
+ }
654
+ return { ok: false, code: r.code, message: r.message, state: current };
655
+ }
656
+ };
657
+ }