@codeo-engineering/licenserail-embedded 0.0.0-stage → 0.1.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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Codeo Solutions Limited
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,54 @@
1
- # Temporary Holding Version
1
+ # @codeo-engineering/licenserail-embedded
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ The LicenseRail client core for apps that run **inside a host platform**. The server accepts the platform `youtrack` today.
4
+ No dependencies and no Node APIs: it needs ES2020 (BigInt) and nothing else, so it also runs where `TextEncoder`,
5
+ `atob` and `crypto.subtle` are missing (YouTrack app backends).
6
+
7
+ - Offline verification of LicenseRail tokens (ECDSA P-256, IEEE P1363) with a bundled verifier, or WebCrypto when the host has it.
8
+ The bundled verifier passes all 262 Project Wycheproof P1363 cases.
9
+ - Installation identity: `installationFingerprint(vendor, product, platform, installationId)` licenses one installation of
10
+ the host (for example a YouTrack instance) instead of a computer.
11
+ - Request builders and response reading for activation (key in `Authorization: Bearer` or the body), refresh, deactivation,
12
+ floating leases and keyless trials — no I/O of their own, so callback-style hosts can send them.
13
+ - `createLicenseClient(...)`: a ready client for hosts that can await `fetch`.
14
+
15
+ For YouTrack apps use [`@codeo-engineering/licenserail-youtrack`](../youtrack), which wires this core into app settings, storage, async HTTP
16
+ and an admin page.
17
+
18
+ ## Ready client (hosts with fetch)
19
+
20
+ ```js
21
+ import { createLicenseClient, installationFingerprint } from '@codeo-engineering/licenserail-embedded'
22
+
23
+ const client = createLicenseClient({
24
+ apiUrl: 'https://api.licenserail.com',
25
+ publicKeyPem: PUBLIC_KEY_PEM, // from the dashboard; not a secret
26
+ product: 'my-app',
27
+ fingerprint: installationFingerprint(VENDOR_ID, 'my-app', 'youtrack', installationId),
28
+ storage: { get: (k) => localStorage.getItem(k), set: (k, v) => localStorage.setItem(k, v), remove: (k) => localStorage.removeItem(k) },
29
+ appVersion: '1.2.0',
30
+ })
31
+
32
+ await client.startTrial(KEY_ID) // keyless trial (once per installation)
33
+ await client.activate(licenseKey) // a license key
34
+ const { status, summary } = await client.state() // offline check: 'Valid', 'Expired', 'OfflineTooLong', ...
35
+ await client.refresh() // when the token asks for it; keeps the license on network errors
36
+ await client.deactivate() // release this installation
37
+ ```
38
+
39
+ `summary` has `isTrial`, `expiresAt`, `entitlements`, `metadata`, `maxHostUsers`, `hostUserPolicy` and
40
+ `hostUsersOverLimit`. Pass `hostUsers: () => count` when the license is priced per host user.
41
+
42
+ ## Core functions (any host)
43
+
44
+ | Function | Purpose |
45
+ |---|---|
46
+ | `verifyToken(token, pem)` / `verifyTokenAsync(token, pem)` | Signature check; returns the payload or null |
47
+ | `evaluate(payload, product, fingerprint, now, lastSeen)` | Offline status, identical in every LicenseRail SDK |
48
+ | `summarize(payload, hostUsers?)`, `hasFeature(payload, code)` | What to show and which features to unlock |
49
+ | `activateRequest`, `refreshRequest`, `deactivateRequest`, `trialRequest` | `{method, url, headers, body}` to send |
50
+ | `readResponse(status, body)` | Token, or an error with `revokesLocalLicense` / `retryLater` |
51
+ | `refreshDueAt(payload)` | When to refresh (null for trials) |
52
+
53
+ Build: `npm run build` writes ES modules to `dist/esm` and CommonJS (for `require()`, e.g. YouTrack apps) to `dist/cjs`.
54
+ Tests: `npm test` (shared vectors, Wycheproof, a sandbox without web/Node globals, the client).
@@ -0,0 +1,115 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.createLicenseClient = createLicenseClient;
4
+ const evaluate_js_1 = require("./evaluate");
5
+ const fingerprint_js_1 = require("./fingerprint");
6
+ const protocol_js_1 = require("./protocol");
7
+ const token_js_1 = require("./token");
8
+ const fetchTransport = (timeoutMs) => async (r) => {
9
+ const host = globalThis;
10
+ if (!host.fetch)
11
+ return { status: 0, body: '' };
12
+ // Hosts without timers or AbortController rely on their own request timeout.
13
+ const controller = host.AbortController && host.setTimeout ? new host.AbortController() : null;
14
+ const timer = controller ? host.setTimeout(() => controller.abort(), timeoutMs) : null;
15
+ try {
16
+ const res = await host.fetch(r.url, { method: r.method, headers: r.headers, body: r.body, ...(controller ? { signal: controller.signal } : {}) });
17
+ return { status: res.status, body: await res.text() };
18
+ }
19
+ catch {
20
+ return { status: 0, body: '' };
21
+ }
22
+ finally {
23
+ if (timer !== null)
24
+ host.clearTimeout?.(timer);
25
+ }
26
+ };
27
+ function createLicenseClient(o) {
28
+ const send = o.transport ?? fetchTransport(o.timeoutMs ?? 10000);
29
+ const now = () => (o.now ? o.now() : new Date());
30
+ const key = (k) => (o.prefix ?? 'licenserail:') + k;
31
+ const target = { apiUrl: o.apiUrl, product: o.product, fingerprint: o.fingerprint };
32
+ async function load() {
33
+ const token = await o.storage.get(key('token'));
34
+ const seen = await o.storage.get(key('lastSeen'));
35
+ return { token, lastSeen: seen ? new Date(Number(seen)) : null };
36
+ }
37
+ async function state() {
38
+ const { token, lastSeen } = await load();
39
+ if (!token)
40
+ return { status: 'Missing', payload: null, summary: null };
41
+ const payload = await (0, token_js_1.verifyTokenAsync)(token, o.publicKeyPem);
42
+ const status = (0, evaluate_js_1.evaluate)(payload, o.product, o.fingerprint, now(), lastSeen);
43
+ if (status === 'Valid')
44
+ await o.storage.set(key('lastSeen'), String(now().getTime()));
45
+ return { status, payload, summary: payload ? (0, evaluate_js_1.summarize)(payload, o.hostUsers?.()) : null };
46
+ }
47
+ /** Set when a license for this device or installation would never match it again: activating would only use up a seat. */
48
+ async function unidentified() {
49
+ if ((0, fingerprint_js_1.fingerprintMatches)(o.fingerprint, o.fingerprint))
50
+ return null;
51
+ 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() };
52
+ }
53
+ async function accept(response) {
54
+ const r = (0, protocol_js_1.readResponse)(response.status, response.body);
55
+ if (r.ok && r.token) {
56
+ const payload = await (0, token_js_1.verifyTokenAsync)(r.token, o.publicKeyPem);
57
+ if (!payload)
58
+ return { ok: false, code: 'invalid_token', message: 'The license server returned a token that does not verify.', state: await state() };
59
+ await o.storage.set(key('token'), r.token);
60
+ await o.storage.set(key('lastSeen'), String(now().getTime()));
61
+ return { ok: true, state: await state() };
62
+ }
63
+ if (!r.ok) {
64
+ if (r.revokesLocalLicense)
65
+ await o.storage.remove(key('token'));
66
+ return { ok: false, code: r.code, message: r.message, state: await state() };
67
+ }
68
+ return { ok: true, state: await state() };
69
+ }
70
+ return {
71
+ /** The current license, checked offline. */
72
+ state,
73
+ /** Activates a license key on this device or installation. */
74
+ async activate(licenseKey, floating = false) {
75
+ return (await unidentified()) ?? accept(await send((0, protocol_js_1.activateRequest)({
76
+ ...target, licenseKey, machineName: o.machineName, appVersion: o.appVersion, hostUsers: o.hostUsers?.(), floating,
77
+ })));
78
+ },
79
+ /** Starts (or gets back) this device's or installation's keyless trial; apps inside a host pass the installation. */
80
+ async startTrial(keyId, host) {
81
+ return (await unidentified()) ?? accept(await send((0, protocol_js_1.trialRequest)({
82
+ ...target, keyId, machineName: o.machineName, appVersion: o.appVersion, hostUsers: o.hostUsers?.(), host,
83
+ })));
84
+ },
85
+ /** Refreshes when the token asks for it (or always with force); keeps the token on network errors. */
86
+ async refresh(force = false) {
87
+ const { token } = await load();
88
+ const current = await state();
89
+ if (!token || !current.payload)
90
+ return { ok: false, code: 'no_license', message: 'No license to refresh.', state: current };
91
+ const due = (0, protocol_js_1.refreshDueAt)(current.payload);
92
+ if (!force && (!due || due.getTime() > now().getTime()))
93
+ return { ok: true, state: current };
94
+ return accept(await send((0, protocol_js_1.refreshRequest)({
95
+ ...target, token, appVersion: o.appVersion, hostUsers: o.hostUsers?.(), floating: current.payload.floating === true,
96
+ })));
97
+ },
98
+ /** Releases the license on this device or installation and removes it locally. */
99
+ async deactivate() {
100
+ const { token } = await load();
101
+ const current = await state();
102
+ if (!token || !current.payload || current.payload.trial) {
103
+ await o.storage.remove(key('token'));
104
+ return { ok: true, state: await state() };
105
+ }
106
+ const res = await send((0, protocol_js_1.deactivateRequest)({ ...target, token, floating: current.payload.floating === true }));
107
+ const r = (0, protocol_js_1.readResponse)(res.status, res.body);
108
+ if (r.ok || r.revokesLocalLicense) {
109
+ await o.storage.remove(key('token'));
110
+ return { ok: true, state: await state() };
111
+ }
112
+ return { ok: false, code: r.code, message: r.message, state: current };
113
+ },
114
+ };
115
+ }
@@ -0,0 +1,95 @@
1
+ "use strict";
2
+ // Byte helpers that work without TextEncoder, TextDecoder, atob or Buffer (sandboxed hosts such as YouTrack apps lack them).
3
+ Object.defineProperty(exports, "__esModule", { value: true });
4
+ exports.utf8Encode = utf8Encode;
5
+ exports.utf8Decode = utf8Decode;
6
+ exports.base64Decode = base64Decode;
7
+ exports.hex = hex;
8
+ /** UTF-8 bytes of a string (surrogate pairs combined). */
9
+ function utf8Encode(text) {
10
+ const out = [];
11
+ for (let i = 0; i < text.length; i++) {
12
+ let c = text.charCodeAt(i);
13
+ if (c >= 0xd800 && c < 0xdc00 && i + 1 < text.length) {
14
+ const d = text.charCodeAt(i + 1);
15
+ if (d >= 0xdc00 && d < 0xe000) {
16
+ c = 0x10000 + ((c - 0xd800) << 10) + (d - 0xdc00);
17
+ i++;
18
+ }
19
+ }
20
+ if (c < 0x80)
21
+ out.push(c);
22
+ else if (c < 0x800)
23
+ out.push(0xc0 | (c >> 6), 0x80 | (c & 63));
24
+ else if (c < 0x10000)
25
+ out.push(0xe0 | (c >> 12), 0x80 | ((c >> 6) & 63), 0x80 | (c & 63));
26
+ else
27
+ out.push(0xf0 | (c >> 18), 0x80 | ((c >> 12) & 63), 0x80 | ((c >> 6) & 63), 0x80 | (c & 63));
28
+ }
29
+ return out;
30
+ }
31
+ /** Decodes UTF-8; invalid sequences become U+FFFD. */
32
+ function utf8Decode(bytes) {
33
+ let out = '';
34
+ for (let i = 0; i < bytes.length;) {
35
+ const b = bytes[i];
36
+ let cp = 0xfffd, len = 1;
37
+ if (b < 0x80) {
38
+ cp = b;
39
+ }
40
+ else if (b >= 0xc2 && b < 0xe0 && cont(bytes, i + 1)) {
41
+ cp = ((b & 31) << 6) | (bytes[i + 1] & 63);
42
+ len = 2;
43
+ }
44
+ else if (b >= 0xe0 && b < 0xf0 && cont(bytes, i + 1) && cont(bytes, i + 2)) {
45
+ const v = ((b & 15) << 12) | ((bytes[i + 1] & 63) << 6) | (bytes[i + 2] & 63);
46
+ if (v >= 0x800 && (v < 0xd800 || v > 0xdfff)) {
47
+ cp = v;
48
+ len = 3;
49
+ }
50
+ }
51
+ else if (b >= 0xf0 && b < 0xf5 && cont(bytes, i + 1) && cont(bytes, i + 2) && cont(bytes, i + 3)) {
52
+ const v = ((b & 7) << 18) | ((bytes[i + 1] & 63) << 12) | ((bytes[i + 2] & 63) << 6) | (bytes[i + 3] & 63);
53
+ if (v >= 0x10000 && v <= 0x10ffff) {
54
+ cp = v;
55
+ len = 4;
56
+ }
57
+ }
58
+ if (cp > 0xffff) {
59
+ cp -= 0x10000;
60
+ out += String.fromCharCode(0xd800 + (cp >> 10), 0xdc00 + (cp & 1023));
61
+ }
62
+ else
63
+ out += String.fromCharCode(cp);
64
+ i += len;
65
+ }
66
+ return out;
67
+ }
68
+ function cont(bytes, i) {
69
+ return i < bytes.length && (bytes[i] & 0xc0) === 0x80;
70
+ }
71
+ const B64 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
72
+ /** Decodes base64 or base64url (padding and whitespace ignored). Returns null on any other character. */
73
+ function base64Decode(text) {
74
+ const s = text.replace(/[\s=]/g, '').replace(/-/g, '+').replace(/_/g, '/');
75
+ const out = [];
76
+ let acc = 0, bits = 0;
77
+ for (let i = 0; i < s.length; i++) {
78
+ const v = B64.indexOf(s.charAt(i));
79
+ if (v < 0)
80
+ return null;
81
+ acc = ((acc << 6) | v) & 0xffffff;
82
+ bits += 6;
83
+ if (bits >= 8) {
84
+ bits -= 8;
85
+ out.push((acc >> bits) & 255);
86
+ }
87
+ }
88
+ return out;
89
+ }
90
+ function hex(bytes) {
91
+ let out = '';
92
+ for (let i = 0; i < bytes.length; i++)
93
+ out += (bytes[i] < 16 ? '0' : '') + bytes[i].toString(16);
94
+ return out;
95
+ }
@@ -0,0 +1,47 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.hasFeature = void 0;
4
+ exports.evaluate = evaluate;
5
+ exports.summarize = summarize;
6
+ const fingerprint_js_1 = require("./fingerprint");
7
+ const CLOCK_TOLERANCE_MS = 10 * 60 * 1000;
8
+ const ISSUED_AT_TOLERANCE_MS = 24 * 60 * 60 * 1000;
9
+ /**
10
+ * The offline check, identical in every SDK (shared test vectors). `lastSeen` is the last time the app ran with this license;
11
+ * without one the license is Unverified until the next online check.
12
+ */
13
+ function evaluate(payload, product, machine, now, lastSeen) {
14
+ if (!payload)
15
+ return 'InvalidSignature';
16
+ if (payload.product.toLowerCase() !== product.toLowerCase())
17
+ return 'WrongProduct';
18
+ if (!(0, fingerprint_js_1.fingerprintMatches)(payload.fingerprint, machine))
19
+ return 'WrongMachine';
20
+ if (payload.suspended)
21
+ return 'Suspended';
22
+ if (!lastSeen)
23
+ return 'Unverified';
24
+ const t = now.getTime();
25
+ if (t + ISSUED_AT_TOLERANCE_MS < Date.parse(payload.issuedAt) || t + CLOCK_TOLERANCE_MS < lastSeen.getTime())
26
+ return 'ClockTampered';
27
+ if (payload.expiresAt && t >= Date.parse(payload.expiresAt))
28
+ return 'Expired';
29
+ if (t >= Date.parse(payload.offlineUntil))
30
+ return 'OfflineTooLong';
31
+ return 'Valid';
32
+ }
33
+ function summarize(payload, hostUsers) {
34
+ const max = typeof payload.maxHostUsers === 'number' ? payload.maxHostUsers : null;
35
+ return {
36
+ isTrial: payload.trial === true || payload.kind === 'trial',
37
+ isTest: payload.test === true,
38
+ expiresAt: payload.expiresAt ? new Date(payload.expiresAt) : null,
39
+ entitlements: payload.entitlements ?? [],
40
+ metadata: payload.metadata ?? {},
41
+ maxHostUsers: max,
42
+ hostUserPolicy: max === null ? null : (payload.hostUserPolicy ?? 'block'),
43
+ hostUsersOverLimit: payload.hostUsersExceeded === true || (max !== null && typeof hostUsers === 'number' && hostUsers > max),
44
+ };
45
+ }
46
+ const hasFeature = (payload, code) => (payload.entitlements ?? []).indexOf(code) >= 0;
47
+ exports.hasFeature = hasFeature;
@@ -0,0 +1,50 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.isHostInstallation = exports.HOST_PLATFORMS = exports.UNAVAILABLE = void 0;
4
+ exports.hashComponent = hashComponent;
5
+ exports.installationFingerprint = installationFingerprint;
6
+ exports.fingerprintMatches = fingerprintMatches;
7
+ const encoding_js_1 = require("./encoding");
8
+ const sha256_js_1 = require("./sha256");
9
+ exports.UNAVAILABLE = 'none';
10
+ /** Host platforms whose installations are licensed like devices (the server's list; extended as adapters ship). */
11
+ exports.HOST_PLATFORMS = ['youtrack'];
12
+ /**
13
+ * lowercase_hex(SHA256(vendor:product:part:UPPER(TRIM(raw)))); missing or blank raw is "none". The vendor is the organization
14
+ * id (ten_...), so the same device or installation hashes differently for every vendor and product.
15
+ */
16
+ function hashComponent(vendor, product, part, raw) {
17
+ if (raw == null || raw.trim() === '')
18
+ return exports.UNAVAILABLE;
19
+ return (0, encoding_js_1.hex)((0, sha256_js_1.sha256)((0, encoding_js_1.utf8Encode)(`${vendor}:${product}:${part}:${raw.trim().toUpperCase()}`)));
20
+ }
21
+ /** The fingerprint of an installation inside a host platform (e.g. a YouTrack instance's uuid). */
22
+ function installationFingerprint(vendor, product, platform, installationId) {
23
+ return {
24
+ machineId: hashComponent(vendor, product, 'installation', installationId),
25
+ diskId: exports.UNAVAILABLE, hostName: exports.UNAVAILABLE, boardId: exports.UNAVAILABLE,
26
+ os: platform.toLowerCase(),
27
+ };
28
+ }
29
+ const isHostInstallation = (f) => !!f.os && exports.HOST_PLATFORMS.indexOf(f.os.toLowerCase()) >= 0;
30
+ exports.isHostInstallation = isHostInstallation;
31
+ const available = (v) => !!v && v !== exports.UNAVAILABLE;
32
+ const same = (a, b) => available(a) && a === b;
33
+ /**
34
+ * Whether `presented` is the device or installation `registered` was issued for (call on the registered fingerprint).
35
+ * Installations: same platform and exactly the same id. Computers: board id + one other part, or two of three without a board id.
36
+ */
37
+ function fingerprintMatches(registered, presented) {
38
+ if ((0, exports.isHostInstallation)(registered) || (0, exports.isHostInstallation)(presented))
39
+ return (registered.os ?? '').toLowerCase() === (presented.os ?? '').toLowerCase() && same(registered.machineId, presented.machineId);
40
+ if (registered.os && presented.os && registered.os.toLowerCase() !== presented.os.toLowerCase())
41
+ return false;
42
+ let matches = 0;
43
+ if (same(registered.machineId, presented.machineId))
44
+ matches++;
45
+ if (same(registered.diskId, presented.diskId))
46
+ matches++;
47
+ if (same(registered.hostName, presented.hostName))
48
+ matches++;
49
+ return available(registered.boardId) ? same(registered.boardId, presented.boardId) && matches >= 1 : matches >= 2;
50
+ }
@@ -0,0 +1,41 @@
1
+ "use strict";
2
+ // licenserail-embedded: the LicenseRail client core for apps that run inside a host platform (YouTrack apps, browser
3
+ // extensions, web apps, workers). No dependencies and no Node APIs; needs ES2020 (BigInt).
4
+ Object.defineProperty(exports, "__esModule", { value: true });
5
+ exports.createLicenseClient = exports.INSTALLATION_HEADER = exports.REVOKING_CODES = exports.refreshDueAt = exports.readResponse = exports.trialRequest = exports.deactivateRequest = exports.refreshRequest = exports.activateRequest = exports.hasFeature = exports.summarize = exports.evaluate = exports.UNAVAILABLE = exports.HOST_PLATFORMS = exports.isHostInstallation = exports.fingerprintMatches = exports.installationFingerprint = exports.hashComponent = exports.decodeTokenUnverified = exports.verifyTokenAsync = exports.verifyToken = exports.parsePublicKey = exports.verifyP256 = exports.sha256 = exports.hex = exports.base64Decode = exports.utf8Decode = exports.utf8Encode = void 0;
6
+ var encoding_js_1 = require("./encoding");
7
+ Object.defineProperty(exports, "utf8Encode", { enumerable: true, get: function () { return encoding_js_1.utf8Encode; } });
8
+ Object.defineProperty(exports, "utf8Decode", { enumerable: true, get: function () { return encoding_js_1.utf8Decode; } });
9
+ Object.defineProperty(exports, "base64Decode", { enumerable: true, get: function () { return encoding_js_1.base64Decode; } });
10
+ Object.defineProperty(exports, "hex", { enumerable: true, get: function () { return encoding_js_1.hex; } });
11
+ var sha256_js_1 = require("./sha256");
12
+ Object.defineProperty(exports, "sha256", { enumerable: true, get: function () { return sha256_js_1.sha256; } });
13
+ var p256_js_1 = require("./p256");
14
+ Object.defineProperty(exports, "verifyP256", { enumerable: true, get: function () { return p256_js_1.verifyP256; } });
15
+ Object.defineProperty(exports, "parsePublicKey", { enumerable: true, get: function () { return p256_js_1.parsePublicKey; } });
16
+ var token_js_1 = require("./token");
17
+ Object.defineProperty(exports, "verifyToken", { enumerable: true, get: function () { return token_js_1.verifyToken; } });
18
+ Object.defineProperty(exports, "verifyTokenAsync", { enumerable: true, get: function () { return token_js_1.verifyTokenAsync; } });
19
+ Object.defineProperty(exports, "decodeTokenUnverified", { enumerable: true, get: function () { return token_js_1.decodeTokenUnverified; } });
20
+ var fingerprint_js_1 = require("./fingerprint");
21
+ Object.defineProperty(exports, "hashComponent", { enumerable: true, get: function () { return fingerprint_js_1.hashComponent; } });
22
+ Object.defineProperty(exports, "installationFingerprint", { enumerable: true, get: function () { return fingerprint_js_1.installationFingerprint; } });
23
+ Object.defineProperty(exports, "fingerprintMatches", { enumerable: true, get: function () { return fingerprint_js_1.fingerprintMatches; } });
24
+ Object.defineProperty(exports, "isHostInstallation", { enumerable: true, get: function () { return fingerprint_js_1.isHostInstallation; } });
25
+ Object.defineProperty(exports, "HOST_PLATFORMS", { enumerable: true, get: function () { return fingerprint_js_1.HOST_PLATFORMS; } });
26
+ Object.defineProperty(exports, "UNAVAILABLE", { enumerable: true, get: function () { return fingerprint_js_1.UNAVAILABLE; } });
27
+ var evaluate_js_1 = require("./evaluate");
28
+ Object.defineProperty(exports, "evaluate", { enumerable: true, get: function () { return evaluate_js_1.evaluate; } });
29
+ Object.defineProperty(exports, "summarize", { enumerable: true, get: function () { return evaluate_js_1.summarize; } });
30
+ Object.defineProperty(exports, "hasFeature", { enumerable: true, get: function () { return evaluate_js_1.hasFeature; } });
31
+ var protocol_js_1 = require("./protocol");
32
+ Object.defineProperty(exports, "activateRequest", { enumerable: true, get: function () { return protocol_js_1.activateRequest; } });
33
+ Object.defineProperty(exports, "refreshRequest", { enumerable: true, get: function () { return protocol_js_1.refreshRequest; } });
34
+ Object.defineProperty(exports, "deactivateRequest", { enumerable: true, get: function () { return protocol_js_1.deactivateRequest; } });
35
+ Object.defineProperty(exports, "trialRequest", { enumerable: true, get: function () { return protocol_js_1.trialRequest; } });
36
+ Object.defineProperty(exports, "readResponse", { enumerable: true, get: function () { return protocol_js_1.readResponse; } });
37
+ Object.defineProperty(exports, "refreshDueAt", { enumerable: true, get: function () { return protocol_js_1.refreshDueAt; } });
38
+ Object.defineProperty(exports, "REVOKING_CODES", { enumerable: true, get: function () { return protocol_js_1.REVOKING_CODES; } });
39
+ Object.defineProperty(exports, "INSTALLATION_HEADER", { enumerable: true, get: function () { return protocol_js_1.INSTALLATION_HEADER; } });
40
+ var client_js_1 = require("./client");
41
+ Object.defineProperty(exports, "createLicenseClient", { enumerable: true, get: function () { return client_js_1.createLicenseClient; } });
@@ -0,0 +1,117 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.parsePublicKey = parsePublicKey;
4
+ exports.verifyP256 = verifyP256;
5
+ const encoding_js_1 = require("./encoding");
6
+ const sha256_js_1 = require("./sha256");
7
+ // ECDSA P-256 / SHA-256 signature verification with BigInt (ES2020), for hosts without crypto.subtle.
8
+ // Verify-only: no secret data is involved, so constant-time arithmetic is not needed. Checked against the Wycheproof
9
+ // ecdsa_secp256r1_sha256_p1363 vectors (test/wycheproof.test.mjs).
10
+ const P = 0xffffffff00000001000000000000000000000000ffffffffffffffffffffffffn;
11
+ const N = 0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551n;
12
+ const B = 0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604bn;
13
+ const G = {
14
+ x: 0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296n,
15
+ y: 0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5n,
16
+ z: 1n,
17
+ };
18
+ const INFINITY = { x: 0n, y: 1n, z: 0n };
19
+ function toInt(bytes) {
20
+ let r = 0n;
21
+ for (let i = 0; i < bytes.length; i++)
22
+ r = (r << 8n) | BigInt(bytes[i]);
23
+ return r;
24
+ }
25
+ function mod(a, m) {
26
+ const r = a % m;
27
+ return r < 0n ? r + m : r;
28
+ }
29
+ function pow(a, e, m) {
30
+ let r = 1n;
31
+ a = mod(a, m);
32
+ while (e > 0n) {
33
+ if (e & 1n)
34
+ r = (r * a) % m;
35
+ a = (a * a) % m;
36
+ e >>= 1n;
37
+ }
38
+ return r;
39
+ }
40
+ const invert = (a, m) => pow(a, m - 2n, m); // m is prime
41
+ // Curve a = -3.
42
+ function double(p) {
43
+ if (p.z === 0n || p.y === 0n)
44
+ return INFINITY;
45
+ const delta = (p.z * p.z) % P, gamma = (p.y * p.y) % P, beta = (p.x * gamma) % P;
46
+ const alpha = (3n * mod(p.x - delta, P) * (p.x + delta)) % P;
47
+ const x = mod(alpha * alpha - 8n * beta, P);
48
+ const z = mod((p.y + p.z) * (p.y + p.z) - gamma - delta, P);
49
+ const y = mod(alpha * (4n * beta - x) - 8n * gamma * gamma, P);
50
+ return { x, y, z };
51
+ }
52
+ function add(p, q) {
53
+ if (p.z === 0n)
54
+ return q;
55
+ if (q.z === 0n)
56
+ return p;
57
+ const z1z1 = (p.z * p.z) % P, z2z2 = (q.z * q.z) % P;
58
+ const u1 = (p.x * z2z2) % P, u2 = (q.x * z1z1) % P;
59
+ const s1 = (((p.y * q.z) % P) * z2z2) % P, s2 = (((q.y * p.z) % P) * z1z1) % P;
60
+ const h = mod(u2 - u1, P), r = mod(s2 - s1, P);
61
+ if (h === 0n)
62
+ return r === 0n ? double(p) : INFINITY;
63
+ const hh = (h * h) % P, hhh = (hh * h) % P, v = (u1 * hh) % P;
64
+ const x = mod(r * r - hhh - 2n * v, P);
65
+ const y = mod(r * (v - x) - s1 * hhh, P);
66
+ return { x, y, z: (((p.z * q.z) % P) * h) % P };
67
+ }
68
+ /** u1·G + u2·Q in one pass (Shamir's trick). */
69
+ function mulAdd(u1, u2, q) {
70
+ const gq = add(G, q);
71
+ let r = INFINITY;
72
+ for (let i = 255; i >= 0; i--) {
73
+ r = double(r);
74
+ const b1 = (u1 >> BigInt(i)) & 1n, b2 = (u2 >> BigInt(i)) & 1n;
75
+ if (b1 && b2)
76
+ r = add(r, gq);
77
+ else if (b1)
78
+ r = add(r, G);
79
+ else if (b2)
80
+ r = add(r, q);
81
+ }
82
+ return r;
83
+ }
84
+ // An uncompressed P-256 SubjectPublicKeyInfo is always 91 bytes: this fixed header, 0x04, X (32), Y (32).
85
+ const SPKI_HEADER = [0x30, 0x59, 0x30, 0x13, 0x06, 0x07, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x02, 0x01, 0x06, 0x08, 0x2a, 0x86, 0x48, 0xce, 0x3d,
86
+ 0x03, 0x01, 0x07, 0x03, 0x42, 0x00];
87
+ /** The public point of a PEM (SPKI) P-256 key, or null if it is anything else. */
88
+ function parsePublicKey(pem) {
89
+ const der = (0, encoding_js_1.base64Decode)(pem.replace(/-----(BEGIN|END) PUBLIC KEY-----/g, ''));
90
+ if (!der || der.length !== 91 || der[26] !== 0x04)
91
+ return null;
92
+ for (let i = 0; i < SPKI_HEADER.length; i++)
93
+ if (der[i] !== SPKI_HEADER[i])
94
+ return null;
95
+ return { x: der.slice(27, 59), y: der.slice(59, 91) };
96
+ }
97
+ /** Verifies an IEEE P1363 (r || s, 64 bytes) ECDSA P-256 SHA-256 signature over `data`. */
98
+ function verifyP256(publicKeyPem, data, signature) {
99
+ const key = parsePublicKey(publicKeyPem);
100
+ if (!key || signature.length !== 64)
101
+ return false;
102
+ const qx = toInt(key.x), qy = toInt(key.y);
103
+ if (qx >= P || qy >= P || mod(qy * qy - (qx * qx * qx - 3n * qx + B), P) !== 0n)
104
+ return false; // on the curve
105
+ const sig = Array.prototype.slice.call(signature);
106
+ const r = toInt(sig.slice(0, 32)), s = toInt(sig.slice(32, 64));
107
+ if (r < 1n || r >= N || s < 1n || s >= N)
108
+ return false;
109
+ const e = toInt((0, sha256_js_1.sha256)(data)); // a 256-bit hash needs no truncation for P-256
110
+ const w = invert(s, N);
111
+ const point = mulAdd((e * w) % N, (r * w) % N, { x: qx, y: qy, z: 1n });
112
+ if (point.z === 0n)
113
+ return false;
114
+ const zi = invert(point.z, P);
115
+ const x = (((point.x * zi) % P) * zi) % P;
116
+ return x % N === r;
117
+ }
@@ -0,0 +1 @@
1
+ {"type":"commonjs"}
@@ -0,0 +1,104 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.REVOKING_CODES = exports.INSTALLATION_HEADER = void 0;
4
+ exports.activateRequest = activateRequest;
5
+ exports.refreshRequest = refreshRequest;
6
+ exports.deactivateRequest = deactivateRequest;
7
+ exports.trialRequest = trialRequest;
8
+ exports.readResponse = readResponse;
9
+ exports.refreshDueAt = refreshDueAt;
10
+ /** Header that makes the server rate-limit per installation instead of per IP (apps inside a host share its IPs). */
11
+ exports.INSTALLATION_HEADER = 'LicenseRail-Installation';
12
+ function url(apiUrl, path) {
13
+ return apiUrl.replace(/\/+$/, '') + '/api/client/v2' + path;
14
+ }
15
+ function headers(fingerprint) {
16
+ const h = { 'Content-Type': 'application/json' };
17
+ if (fingerprint.os)
18
+ h[exports.INSTALLATION_HEADER] = `${fingerprint.os}:${fingerprint.machineId}`.slice(0, 128);
19
+ return h;
20
+ }
21
+ function clean(o) {
22
+ const out = {};
23
+ for (const k of Object.keys(o))
24
+ if (o[k] !== undefined && o[k] !== null)
25
+ out[k] = o[k];
26
+ return out;
27
+ }
28
+ function activateRequest(o) {
29
+ const h = headers(o.fingerprint);
30
+ const inHeader = o.keyInHeader !== false;
31
+ if (o.licenseKey && inHeader)
32
+ h.Authorization = `Bearer ${o.licenseKey}`;
33
+ return {
34
+ method: 'POST',
35
+ url: url(o.apiUrl, o.floating ? '/floating/checkout' : '/activate'),
36
+ headers: h,
37
+ body: JSON.stringify(clean({
38
+ product: o.product, fingerprint: o.fingerprint, licenseKey: inHeader ? undefined : o.licenseKey,
39
+ machineName: o.machineName, appVersion: o.appVersion, hostUsers: o.hostUsers,
40
+ })),
41
+ };
42
+ }
43
+ function refreshRequest(o) {
44
+ return {
45
+ method: 'POST',
46
+ url: url(o.apiUrl, o.floating ? '/floating/heartbeat' : '/refresh'),
47
+ headers: headers(o.fingerprint),
48
+ // appVersion is a required field of the refresh request (null allowed).
49
+ body: JSON.stringify({ ...clean({ token: o.token, fingerprint: o.fingerprint, anomalies: o.anomalies, hostUsers: o.hostUsers }), appVersion: o.appVersion ?? null }),
50
+ };
51
+ }
52
+ function deactivateRequest(o) {
53
+ return {
54
+ method: 'POST',
55
+ url: url(o.apiUrl, o.floating ? '/floating/release' : '/deactivate'),
56
+ headers: headers(o.fingerprint),
57
+ body: JSON.stringify({ token: o.token, fingerprint: o.fingerprint }),
58
+ };
59
+ }
60
+ function trialRequest(o) {
61
+ return {
62
+ method: 'POST',
63
+ url: url(o.apiUrl, '/trial'),
64
+ headers: headers(o.fingerprint),
65
+ body: JSON.stringify(clean({
66
+ keyId: o.keyId, product: o.product, fingerprint: o.fingerprint, machineName: o.machineName, appVersion: o.appVersion, hostUsers: o.hostUsers,
67
+ host: o.host,
68
+ })),
69
+ };
70
+ }
71
+ /** Codes on which the local license must be removed; on all others (network errors, 402, 429, 5xx) the app keeps it. */
72
+ exports.REVOKING_CODES = [
73
+ 'license_not_found', 'license_suspended', 'license_expired', 'activation_revoked', 'wrong_machine', 'invalid_token', 'license_revoked',
74
+ ];
75
+ /** Reads a client API response. `status` 0 means the request failed before any response (network error, timeout). */
76
+ function readResponse(status, bodyText) {
77
+ let body = null;
78
+ try {
79
+ body = bodyText ? JSON.parse(bodyText) : null;
80
+ }
81
+ catch {
82
+ body = null;
83
+ }
84
+ if (status >= 200 && status < 300) {
85
+ if (status === 204)
86
+ return { ok: true, token: null };
87
+ // Anything else without a token isn't our server's answer (a captive portal, a proxy): an error, so nothing is removed.
88
+ if (body && typeof body.token === 'string')
89
+ return { ok: true, token: body.token };
90
+ }
91
+ const code = body && typeof body.code === 'string' ? body.code : status === 0 ? 'network_error' : `http_${status}`;
92
+ const message = body && typeof body.message === 'string' ? body.message : status === 0 ? 'The license server could not be reached.' : 'Unexpected response from the license server.';
93
+ return {
94
+ ok: false, code, message,
95
+ revokesLocalLicense: exports.REVOKING_CODES.indexOf(code) >= 0,
96
+ retryLater: status === 0 || status === 429 || status === 402 || status >= 500,
97
+ };
98
+ }
99
+ /** When the token wants to be refreshed (null for trials, which are never refreshed). */
100
+ function refreshDueAt(payload) {
101
+ if (payload.trial === true)
102
+ return null;
103
+ return new Date(payload.refreshAfter);
104
+ }