@codeo-engineering/licenserail-embedded 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.
- package/LICENSE +21 -0
- package/README.md +53 -2
- package/dist/cjs/client.js +113 -0
- package/dist/cjs/encoding.js +95 -0
- package/dist/cjs/evaluate.js +47 -0
- package/dist/cjs/fingerprint.js +50 -0
- package/dist/cjs/index.js +41 -0
- package/dist/cjs/p256.js +117 -0
- package/dist/cjs/package.json +1 -0
- package/dist/cjs/protocol.js +101 -0
- package/dist/cjs/sha256.js +60 -0
- package/dist/cjs/token.js +63 -0
- package/dist/esm/client.d.ts +60 -0
- package/dist/esm/client.js +110 -0
- package/dist/esm/encoding.d.ts +8 -0
- package/dist/esm/encoding.js +89 -0
- package/dist/esm/evaluate.d.ts +21 -0
- package/dist/esm/evaluate.js +41 -0
- package/dist/esm/fingerprint.d.ts +18 -0
- package/dist/esm/fingerprint.js +43 -0
- package/dist/esm/index.d.ts +8 -0
- package/dist/esm/index.js +10 -0
- package/dist/esm/p256.d.ts +8 -0
- package/dist/esm/p256.js +113 -0
- package/dist/esm/protocol.d.ts +71 -0
- package/dist/esm/protocol.js +92 -0
- package/dist/esm/sha256.d.ts +2 -0
- package/dist/esm/sha256.js +57 -0
- package/dist/esm/token.d.ts +46 -0
- package/dist/esm/token.js +58 -0
- package/package.json +29 -4
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.sha256 = sha256;
|
|
4
|
+
// SHA-256 (FIPS 180-4) in plain JavaScript, for hosts without crypto.subtle or node:crypto.
|
|
5
|
+
const K = [
|
|
6
|
+
0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be,
|
|
7
|
+
0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa,
|
|
8
|
+
0x5cb0a9dc, 0x76f988da, 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, 0x27b70a85,
|
|
9
|
+
0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3,
|
|
10
|
+
0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f,
|
|
11
|
+
0x682e6ff3, 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2,
|
|
12
|
+
];
|
|
13
|
+
const rotr = (x, n) => (x >>> n) | (x << (32 - n));
|
|
14
|
+
function sha256(bytes) {
|
|
15
|
+
const m = Array.prototype.slice.call(bytes);
|
|
16
|
+
const bitLength = bytes.length * 8;
|
|
17
|
+
m.push(0x80);
|
|
18
|
+
while (m.length % 64 !== 56)
|
|
19
|
+
m.push(0);
|
|
20
|
+
const hi = Math.floor(bitLength / 0x100000000), lo = bitLength >>> 0;
|
|
21
|
+
m.push(hi >>> 24, (hi >>> 16) & 255, (hi >>> 8) & 255, hi & 255, lo >>> 24, (lo >>> 16) & 255, (lo >>> 8) & 255, lo & 255);
|
|
22
|
+
const h = [0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19];
|
|
23
|
+
const w = new Array(64);
|
|
24
|
+
for (let off = 0; off < m.length; off += 64) {
|
|
25
|
+
for (let t = 0; t < 64; t++) {
|
|
26
|
+
if (t < 16)
|
|
27
|
+
w[t] = (m[off + 4 * t] << 24) | (m[off + 4 * t + 1] << 16) | (m[off + 4 * t + 2] << 8) | m[off + 4 * t + 3];
|
|
28
|
+
else {
|
|
29
|
+
const s0 = rotr(w[t - 15], 7) ^ rotr(w[t - 15], 18) ^ (w[t - 15] >>> 3);
|
|
30
|
+
const s1 = rotr(w[t - 2], 17) ^ rotr(w[t - 2], 19) ^ (w[t - 2] >>> 10);
|
|
31
|
+
w[t] = (w[t - 16] + s0 + w[t - 7] + s1) | 0;
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
let [a, b, c, d, e, f, g, k] = h;
|
|
35
|
+
for (let t = 0; t < 64; t++) {
|
|
36
|
+
const t1 = (k + (rotr(e, 6) ^ rotr(e, 11) ^ rotr(e, 25)) + ((e & f) ^ (~e & g)) + K[t] + w[t]) | 0;
|
|
37
|
+
const t2 = ((rotr(a, 2) ^ rotr(a, 13) ^ rotr(a, 22)) + ((a & b) ^ (a & c) ^ (b & c))) | 0;
|
|
38
|
+
k = g;
|
|
39
|
+
g = f;
|
|
40
|
+
f = e;
|
|
41
|
+
e = (d + t1) | 0;
|
|
42
|
+
d = c;
|
|
43
|
+
c = b;
|
|
44
|
+
b = a;
|
|
45
|
+
a = (t1 + t2) | 0;
|
|
46
|
+
}
|
|
47
|
+
h[0] = (h[0] + a) | 0;
|
|
48
|
+
h[1] = (h[1] + b) | 0;
|
|
49
|
+
h[2] = (h[2] + c) | 0;
|
|
50
|
+
h[3] = (h[3] + d) | 0;
|
|
51
|
+
h[4] = (h[4] + e) | 0;
|
|
52
|
+
h[5] = (h[5] + f) | 0;
|
|
53
|
+
h[6] = (h[6] + g) | 0;
|
|
54
|
+
h[7] = (h[7] + k) | 0;
|
|
55
|
+
}
|
|
56
|
+
const out = [];
|
|
57
|
+
for (let i = 0; i < 8; i++)
|
|
58
|
+
out.push(h[i] >>> 24, (h[i] >>> 16) & 255, (h[i] >>> 8) & 255, h[i] & 255);
|
|
59
|
+
return out;
|
|
60
|
+
}
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.verifyToken = verifyToken;
|
|
4
|
+
exports.verifyTokenAsync = verifyTokenAsync;
|
|
5
|
+
exports.decodeTokenUnverified = decodeTokenUnverified;
|
|
6
|
+
const encoding_js_1 = require("./encoding");
|
|
7
|
+
const p256_js_1 = require("./p256");
|
|
8
|
+
function split(token) {
|
|
9
|
+
if (!token || typeof token !== 'string')
|
|
10
|
+
return null;
|
|
11
|
+
const parts = token.trim().split('.');
|
|
12
|
+
if (parts.length !== 2 || !parts[0] || !parts[1])
|
|
13
|
+
return null;
|
|
14
|
+
const signature = (0, encoding_js_1.base64Decode)(parts[1]);
|
|
15
|
+
const body = (0, encoding_js_1.base64Decode)(parts[0]);
|
|
16
|
+
if (!signature || signature.length !== 64 || !body)
|
|
17
|
+
return null;
|
|
18
|
+
try {
|
|
19
|
+
const payload = JSON.parse((0, encoding_js_1.utf8Decode)(body));
|
|
20
|
+
if (!payload || typeof payload !== 'object' || !payload.fingerprint)
|
|
21
|
+
return null;
|
|
22
|
+
// The signature covers the ASCII bytes of the base64url payload as it appears in the token.
|
|
23
|
+
return { signed: (0, encoding_js_1.utf8Encode)(parts[0]), signature, payload };
|
|
24
|
+
}
|
|
25
|
+
catch {
|
|
26
|
+
return null;
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
/**
|
|
30
|
+
* Verifies a token with the environment's public key (PEM) using the bundled P-256 code, synchronously.
|
|
31
|
+
* Returns the payload, or null when the token is malformed or the signature doesn't match.
|
|
32
|
+
*/
|
|
33
|
+
function verifyToken(token, publicKeyPem) {
|
|
34
|
+
const parts = split(token);
|
|
35
|
+
return parts && (0, p256_js_1.verifyP256)(publicKeyPem, parts.signed, parts.signature) ? parts.payload : null;
|
|
36
|
+
}
|
|
37
|
+
function subtle() {
|
|
38
|
+
const c = globalThis.crypto;
|
|
39
|
+
return c && c.subtle && typeof c.subtle.verify === 'function' ? c.subtle : null;
|
|
40
|
+
}
|
|
41
|
+
/** Like {@link verifyToken}, but uses WebCrypto (`crypto.subtle`) when the host has it. */
|
|
42
|
+
async function verifyTokenAsync(token, publicKeyPem) {
|
|
43
|
+
const s = subtle();
|
|
44
|
+
if (!s || typeof Uint8Array === 'undefined')
|
|
45
|
+
return verifyToken(token, publicKeyPem);
|
|
46
|
+
const parts = split(token);
|
|
47
|
+
const key = (0, p256_js_1.parsePublicKey)(publicKeyPem);
|
|
48
|
+
if (!parts || !key)
|
|
49
|
+
return null;
|
|
50
|
+
try {
|
|
51
|
+
const der = (0, encoding_js_1.base64Decode)(publicKeyPem.replace(/-----(BEGIN|END) PUBLIC KEY-----/g, ''));
|
|
52
|
+
const cryptoKey = await s.importKey('spki', new Uint8Array(der).buffer, { name: 'ECDSA', namedCurve: 'P-256' }, false, ['verify']);
|
|
53
|
+
const ok = await s.verify({ name: 'ECDSA', hash: 'SHA-256' }, cryptoKey, new Uint8Array(parts.signature).buffer, new Uint8Array(parts.signed).buffer);
|
|
54
|
+
return ok ? parts.payload : null;
|
|
55
|
+
}
|
|
56
|
+
catch {
|
|
57
|
+
return verifyToken(token, publicKeyPem);
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
/** Reads a token's payload WITHOUT checking the signature (for display only; never trust it). */
|
|
61
|
+
function decodeTokenUnverified(token) {
|
|
62
|
+
return split(token)?.payload ?? null;
|
|
63
|
+
}
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
import { type LicenseStatus, type LicenseSummary } from './evaluate.js';
|
|
2
|
+
import { type HttpRequestDescription } from './protocol.js';
|
|
3
|
+
import { type Fingerprint, type LicensePayload } from './token.js';
|
|
4
|
+
/** Key-value storage for the token and the last-run time (e.g. chrome.storage, localStorage, a settings store). */
|
|
5
|
+
export interface LicenseStorage {
|
|
6
|
+
get(key: string): Promise<string | null> | string | null;
|
|
7
|
+
set(key: string, value: string): Promise<void> | void;
|
|
8
|
+
remove(key: string): Promise<void> | void;
|
|
9
|
+
}
|
|
10
|
+
/** Sends a request description; returns the status (0 on network failure) and the body text. */
|
|
11
|
+
export type Transport = (request: HttpRequestDescription) => Promise<{
|
|
12
|
+
status: number;
|
|
13
|
+
body: string;
|
|
14
|
+
}>;
|
|
15
|
+
export interface ClientOptions {
|
|
16
|
+
apiUrl: string;
|
|
17
|
+
/** The environment's public key (PEM) from the dashboard. Not a secret. */
|
|
18
|
+
publicKeyPem: string;
|
|
19
|
+
product: string;
|
|
20
|
+
/** The device or installation (see installationFingerprint). */
|
|
21
|
+
fingerprint: Fingerprint;
|
|
22
|
+
storage: LicenseStorage;
|
|
23
|
+
transport?: Transport;
|
|
24
|
+
machineName?: string;
|
|
25
|
+
appVersion?: string;
|
|
26
|
+
/** The host's current number of users, if the license is priced per host user. */
|
|
27
|
+
hostUsers?: () => number | undefined;
|
|
28
|
+
now?: () => Date;
|
|
29
|
+
/** Request timeout in milliseconds for the built-in transport (default 10 s). */
|
|
30
|
+
timeoutMs?: number;
|
|
31
|
+
/** Storage key prefix (default "licenserail:"). */
|
|
32
|
+
prefix?: string;
|
|
33
|
+
}
|
|
34
|
+
export interface LicenseState {
|
|
35
|
+
status: LicenseStatus;
|
|
36
|
+
payload: LicensePayload | null;
|
|
37
|
+
summary: LicenseSummary | null;
|
|
38
|
+
}
|
|
39
|
+
export type ActionResult = {
|
|
40
|
+
ok: true;
|
|
41
|
+
state: LicenseState;
|
|
42
|
+
} | {
|
|
43
|
+
ok: false;
|
|
44
|
+
code: string;
|
|
45
|
+
message: string;
|
|
46
|
+
state: LicenseState;
|
|
47
|
+
};
|
|
48
|
+
export declare function createLicenseClient(o: ClientOptions): {
|
|
49
|
+
/** The current license, checked offline. */
|
|
50
|
+
state: () => Promise<LicenseState>;
|
|
51
|
+
/** Activates a license key on this device or installation. */
|
|
52
|
+
activate(licenseKey: string, floating?: boolean): Promise<ActionResult>;
|
|
53
|
+
/** Starts (or gets back) this device's or installation's keyless trial. */
|
|
54
|
+
startTrial(keyId: string): Promise<ActionResult>;
|
|
55
|
+
/** Refreshes when the token asks for it (or always with force); keeps the token on network errors. */
|
|
56
|
+
refresh(force?: boolean): Promise<ActionResult>;
|
|
57
|
+
/** Releases the license on this device or installation and removes it locally. */
|
|
58
|
+
deactivate(): Promise<ActionResult>;
|
|
59
|
+
};
|
|
60
|
+
export type LicenseClient = ReturnType<typeof createLicenseClient>;
|
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
import { evaluate, summarize } from './evaluate.js';
|
|
2
|
+
import { fingerprintMatches } from './fingerprint.js';
|
|
3
|
+
import { activateRequest, deactivateRequest, readResponse, refreshDueAt, refreshRequest, trialRequest } from './protocol.js';
|
|
4
|
+
import { verifyTokenAsync } from './token.js';
|
|
5
|
+
const fetchTransport = (timeoutMs) => async (r) => {
|
|
6
|
+
const host = globalThis;
|
|
7
|
+
if (!host.fetch)
|
|
8
|
+
return { status: 0, body: '' };
|
|
9
|
+
// Hosts without timers or AbortController rely on their own request timeout.
|
|
10
|
+
const controller = host.AbortController && host.setTimeout ? new host.AbortController() : null;
|
|
11
|
+
const timer = controller ? host.setTimeout(() => controller.abort(), timeoutMs) : null;
|
|
12
|
+
try {
|
|
13
|
+
const res = await host.fetch(r.url, { method: r.method, headers: r.headers, body: r.body, ...(controller ? { signal: controller.signal } : {}) });
|
|
14
|
+
return { status: res.status, body: await res.text() };
|
|
15
|
+
}
|
|
16
|
+
catch {
|
|
17
|
+
return { status: 0, body: '' };
|
|
18
|
+
}
|
|
19
|
+
finally {
|
|
20
|
+
if (timer !== null)
|
|
21
|
+
host.clearTimeout?.(timer);
|
|
22
|
+
}
|
|
23
|
+
};
|
|
24
|
+
export function createLicenseClient(o) {
|
|
25
|
+
const send = o.transport ?? fetchTransport(o.timeoutMs ?? 10000);
|
|
26
|
+
const now = () => (o.now ? o.now() : new Date());
|
|
27
|
+
const key = (k) => (o.prefix ?? 'licenserail:') + k;
|
|
28
|
+
const target = { apiUrl: o.apiUrl, product: o.product, fingerprint: o.fingerprint };
|
|
29
|
+
async function load() {
|
|
30
|
+
const token = await o.storage.get(key('token'));
|
|
31
|
+
const seen = await o.storage.get(key('lastSeen'));
|
|
32
|
+
return { token, lastSeen: seen ? new Date(Number(seen)) : null };
|
|
33
|
+
}
|
|
34
|
+
async function state() {
|
|
35
|
+
const { token, lastSeen } = await load();
|
|
36
|
+
if (!token)
|
|
37
|
+
return { status: 'Missing', payload: null, summary: null };
|
|
38
|
+
const payload = await verifyTokenAsync(token, o.publicKeyPem);
|
|
39
|
+
const status = evaluate(payload, o.product, o.fingerprint, now(), lastSeen);
|
|
40
|
+
if (status === 'Valid')
|
|
41
|
+
await o.storage.set(key('lastSeen'), String(now().getTime()));
|
|
42
|
+
return { status, payload, summary: payload ? summarize(payload, o.hostUsers?.()) : null };
|
|
43
|
+
}
|
|
44
|
+
/** Set when a license for this device or installation would never match it again: activating would only use up a seat. */
|
|
45
|
+
async function unidentified() {
|
|
46
|
+
if (fingerprintMatches(o.fingerprint, o.fingerprint))
|
|
47
|
+
return null;
|
|
48
|
+
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() };
|
|
49
|
+
}
|
|
50
|
+
async function accept(response) {
|
|
51
|
+
const r = readResponse(response.status, response.body);
|
|
52
|
+
if (r.ok && r.token) {
|
|
53
|
+
const payload = await verifyTokenAsync(r.token, o.publicKeyPem);
|
|
54
|
+
if (!payload)
|
|
55
|
+
return { ok: false, code: 'invalid_token', message: 'The license server returned a token that does not verify.', state: await state() };
|
|
56
|
+
await o.storage.set(key('token'), r.token);
|
|
57
|
+
await o.storage.set(key('lastSeen'), String(now().getTime()));
|
|
58
|
+
return { ok: true, state: await state() };
|
|
59
|
+
}
|
|
60
|
+
if (!r.ok) {
|
|
61
|
+
if (r.revokesLocalLicense)
|
|
62
|
+
await o.storage.remove(key('token'));
|
|
63
|
+
return { ok: false, code: r.code, message: r.message, state: await state() };
|
|
64
|
+
}
|
|
65
|
+
return { ok: true, state: await state() };
|
|
66
|
+
}
|
|
67
|
+
return {
|
|
68
|
+
/** The current license, checked offline. */
|
|
69
|
+
state,
|
|
70
|
+
/** Activates a license key on this device or installation. */
|
|
71
|
+
async activate(licenseKey, floating = false) {
|
|
72
|
+
return (await unidentified()) ?? accept(await send(activateRequest({
|
|
73
|
+
...target, licenseKey, machineName: o.machineName, appVersion: o.appVersion, hostUsers: o.hostUsers?.(), floating,
|
|
74
|
+
})));
|
|
75
|
+
},
|
|
76
|
+
/** Starts (or gets back) this device's or installation's keyless trial. */
|
|
77
|
+
async startTrial(keyId) {
|
|
78
|
+
return (await unidentified()) ?? accept(await send(trialRequest({ ...target, keyId, machineName: o.machineName, appVersion: o.appVersion, hostUsers: o.hostUsers?.() })));
|
|
79
|
+
},
|
|
80
|
+
/** Refreshes when the token asks for it (or always with force); keeps the token on network errors. */
|
|
81
|
+
async refresh(force = false) {
|
|
82
|
+
const { token } = await load();
|
|
83
|
+
const current = await state();
|
|
84
|
+
if (!token || !current.payload)
|
|
85
|
+
return { ok: false, code: 'no_license', message: 'No license to refresh.', state: current };
|
|
86
|
+
const due = refreshDueAt(current.payload);
|
|
87
|
+
if (!force && (!due || due.getTime() > now().getTime()))
|
|
88
|
+
return { ok: true, state: current };
|
|
89
|
+
return accept(await send(refreshRequest({
|
|
90
|
+
...target, token, appVersion: o.appVersion, hostUsers: o.hostUsers?.(), floating: current.payload.floating === true,
|
|
91
|
+
})));
|
|
92
|
+
},
|
|
93
|
+
/** Releases the license on this device or installation and removes it locally. */
|
|
94
|
+
async deactivate() {
|
|
95
|
+
const { token } = await load();
|
|
96
|
+
const current = await state();
|
|
97
|
+
if (!token || !current.payload || current.payload.trial) {
|
|
98
|
+
await o.storage.remove(key('token'));
|
|
99
|
+
return { ok: true, state: await state() };
|
|
100
|
+
}
|
|
101
|
+
const res = await send(deactivateRequest({ ...target, token, floating: current.payload.floating === true }));
|
|
102
|
+
const r = readResponse(res.status, res.body);
|
|
103
|
+
if (r.ok || r.revokesLocalLicense) {
|
|
104
|
+
await o.storage.remove(key('token'));
|
|
105
|
+
return { ok: true, state: await state() };
|
|
106
|
+
}
|
|
107
|
+
return { ok: false, code: r.code, message: r.message, state: current };
|
|
108
|
+
},
|
|
109
|
+
};
|
|
110
|
+
}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
export type Bytes = number[];
|
|
2
|
+
/** UTF-8 bytes of a string (surrogate pairs combined). */
|
|
3
|
+
export declare function utf8Encode(text: string): Bytes;
|
|
4
|
+
/** Decodes UTF-8; invalid sequences become U+FFFD. */
|
|
5
|
+
export declare function utf8Decode(bytes: ArrayLike<number>): string;
|
|
6
|
+
/** Decodes base64 or base64url (padding and whitespace ignored). Returns null on any other character. */
|
|
7
|
+
export declare function base64Decode(text: string): Bytes | null;
|
|
8
|
+
export declare function hex(bytes: ArrayLike<number>): string;
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
// Byte helpers that work without TextEncoder, TextDecoder, atob or Buffer (sandboxed hosts such as YouTrack apps lack them).
|
|
2
|
+
/** UTF-8 bytes of a string (surrogate pairs combined). */
|
|
3
|
+
export function utf8Encode(text) {
|
|
4
|
+
const out = [];
|
|
5
|
+
for (let i = 0; i < text.length; i++) {
|
|
6
|
+
let c = text.charCodeAt(i);
|
|
7
|
+
if (c >= 0xd800 && c < 0xdc00 && i + 1 < text.length) {
|
|
8
|
+
const d = text.charCodeAt(i + 1);
|
|
9
|
+
if (d >= 0xdc00 && d < 0xe000) {
|
|
10
|
+
c = 0x10000 + ((c - 0xd800) << 10) + (d - 0xdc00);
|
|
11
|
+
i++;
|
|
12
|
+
}
|
|
13
|
+
}
|
|
14
|
+
if (c < 0x80)
|
|
15
|
+
out.push(c);
|
|
16
|
+
else if (c < 0x800)
|
|
17
|
+
out.push(0xc0 | (c >> 6), 0x80 | (c & 63));
|
|
18
|
+
else if (c < 0x10000)
|
|
19
|
+
out.push(0xe0 | (c >> 12), 0x80 | ((c >> 6) & 63), 0x80 | (c & 63));
|
|
20
|
+
else
|
|
21
|
+
out.push(0xf0 | (c >> 18), 0x80 | ((c >> 12) & 63), 0x80 | ((c >> 6) & 63), 0x80 | (c & 63));
|
|
22
|
+
}
|
|
23
|
+
return out;
|
|
24
|
+
}
|
|
25
|
+
/** Decodes UTF-8; invalid sequences become U+FFFD. */
|
|
26
|
+
export function utf8Decode(bytes) {
|
|
27
|
+
let out = '';
|
|
28
|
+
for (let i = 0; i < bytes.length;) {
|
|
29
|
+
const b = bytes[i];
|
|
30
|
+
let cp = 0xfffd, len = 1;
|
|
31
|
+
if (b < 0x80) {
|
|
32
|
+
cp = b;
|
|
33
|
+
}
|
|
34
|
+
else if (b >= 0xc2 && b < 0xe0 && cont(bytes, i + 1)) {
|
|
35
|
+
cp = ((b & 31) << 6) | (bytes[i + 1] & 63);
|
|
36
|
+
len = 2;
|
|
37
|
+
}
|
|
38
|
+
else if (b >= 0xe0 && b < 0xf0 && cont(bytes, i + 1) && cont(bytes, i + 2)) {
|
|
39
|
+
const v = ((b & 15) << 12) | ((bytes[i + 1] & 63) << 6) | (bytes[i + 2] & 63);
|
|
40
|
+
if (v >= 0x800 && (v < 0xd800 || v > 0xdfff)) {
|
|
41
|
+
cp = v;
|
|
42
|
+
len = 3;
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
else if (b >= 0xf0 && b < 0xf5 && cont(bytes, i + 1) && cont(bytes, i + 2) && cont(bytes, i + 3)) {
|
|
46
|
+
const v = ((b & 7) << 18) | ((bytes[i + 1] & 63) << 12) | ((bytes[i + 2] & 63) << 6) | (bytes[i + 3] & 63);
|
|
47
|
+
if (v >= 0x10000 && v <= 0x10ffff) {
|
|
48
|
+
cp = v;
|
|
49
|
+
len = 4;
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
if (cp > 0xffff) {
|
|
53
|
+
cp -= 0x10000;
|
|
54
|
+
out += String.fromCharCode(0xd800 + (cp >> 10), 0xdc00 + (cp & 1023));
|
|
55
|
+
}
|
|
56
|
+
else
|
|
57
|
+
out += String.fromCharCode(cp);
|
|
58
|
+
i += len;
|
|
59
|
+
}
|
|
60
|
+
return out;
|
|
61
|
+
}
|
|
62
|
+
function cont(bytes, i) {
|
|
63
|
+
return i < bytes.length && (bytes[i] & 0xc0) === 0x80;
|
|
64
|
+
}
|
|
65
|
+
const B64 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
|
|
66
|
+
/** Decodes base64 or base64url (padding and whitespace ignored). Returns null on any other character. */
|
|
67
|
+
export function base64Decode(text) {
|
|
68
|
+
const s = text.replace(/[\s=]/g, '').replace(/-/g, '+').replace(/_/g, '/');
|
|
69
|
+
const out = [];
|
|
70
|
+
let acc = 0, bits = 0;
|
|
71
|
+
for (let i = 0; i < s.length; i++) {
|
|
72
|
+
const v = B64.indexOf(s.charAt(i));
|
|
73
|
+
if (v < 0)
|
|
74
|
+
return null;
|
|
75
|
+
acc = ((acc << 6) | v) & 0xffffff;
|
|
76
|
+
bits += 6;
|
|
77
|
+
if (bits >= 8) {
|
|
78
|
+
bits -= 8;
|
|
79
|
+
out.push((acc >> bits) & 255);
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
return out;
|
|
83
|
+
}
|
|
84
|
+
export function hex(bytes) {
|
|
85
|
+
let out = '';
|
|
86
|
+
for (let i = 0; i < bytes.length; i++)
|
|
87
|
+
out += (bytes[i] < 16 ? '0' : '') + bytes[i].toString(16);
|
|
88
|
+
return out;
|
|
89
|
+
}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import type { Fingerprint, LicensePayload } from './token.js';
|
|
2
|
+
export type LicenseStatus = 'Valid' | 'Missing' | 'InvalidSignature' | 'WrongProduct' | 'WrongMachine' | 'Expired' | 'OfflineTooLong' | 'ClockTampered' | 'Unverified' | 'Suspended';
|
|
3
|
+
/**
|
|
4
|
+
* The offline check, identical in every SDK (shared test vectors). `lastSeen` is the last time the app ran with this license;
|
|
5
|
+
* without one the license is Unverified until the next online check.
|
|
6
|
+
*/
|
|
7
|
+
export declare function evaluate(payload: LicensePayload | null, product: string, machine: Fingerprint, now: Date, lastSeen: Date | null): LicenseStatus;
|
|
8
|
+
/** What an app needs to show and gate features, read from a verified payload. */
|
|
9
|
+
export interface LicenseSummary {
|
|
10
|
+
isTrial: boolean;
|
|
11
|
+
isTest: boolean;
|
|
12
|
+
expiresAt: Date | null;
|
|
13
|
+
entitlements: string[];
|
|
14
|
+
metadata: Record<string, unknown>;
|
|
15
|
+
maxHostUsers: number | null;
|
|
16
|
+
hostUserPolicy: string | null;
|
|
17
|
+
/** True when the server flagged the host user limit (policy "warn"), or `hostUsers` is above the limit. */
|
|
18
|
+
hostUsersOverLimit: boolean;
|
|
19
|
+
}
|
|
20
|
+
export declare function summarize(payload: LicensePayload, hostUsers?: number | null): LicenseSummary;
|
|
21
|
+
export declare const hasFeature: (payload: LicensePayload, code: string) => boolean;
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import { fingerprintMatches } from './fingerprint.js';
|
|
2
|
+
const CLOCK_TOLERANCE_MS = 10 * 60 * 1000;
|
|
3
|
+
const ISSUED_AT_TOLERANCE_MS = 24 * 60 * 60 * 1000;
|
|
4
|
+
/**
|
|
5
|
+
* The offline check, identical in every SDK (shared test vectors). `lastSeen` is the last time the app ran with this license;
|
|
6
|
+
* without one the license is Unverified until the next online check.
|
|
7
|
+
*/
|
|
8
|
+
export function evaluate(payload, product, machine, now, lastSeen) {
|
|
9
|
+
if (!payload)
|
|
10
|
+
return 'InvalidSignature';
|
|
11
|
+
if (payload.product.toLowerCase() !== product.toLowerCase())
|
|
12
|
+
return 'WrongProduct';
|
|
13
|
+
if (!fingerprintMatches(payload.fingerprint, machine))
|
|
14
|
+
return 'WrongMachine';
|
|
15
|
+
if (payload.suspended)
|
|
16
|
+
return 'Suspended';
|
|
17
|
+
if (!lastSeen)
|
|
18
|
+
return 'Unverified';
|
|
19
|
+
const t = now.getTime();
|
|
20
|
+
if (t + ISSUED_AT_TOLERANCE_MS < Date.parse(payload.issuedAt) || t + CLOCK_TOLERANCE_MS < lastSeen.getTime())
|
|
21
|
+
return 'ClockTampered';
|
|
22
|
+
if (payload.expiresAt && t >= Date.parse(payload.expiresAt))
|
|
23
|
+
return 'Expired';
|
|
24
|
+
if (t >= Date.parse(payload.offlineUntil))
|
|
25
|
+
return 'OfflineTooLong';
|
|
26
|
+
return 'Valid';
|
|
27
|
+
}
|
|
28
|
+
export function summarize(payload, hostUsers) {
|
|
29
|
+
const max = typeof payload.maxHostUsers === 'number' ? payload.maxHostUsers : null;
|
|
30
|
+
return {
|
|
31
|
+
isTrial: payload.trial === true || payload.kind === 'trial',
|
|
32
|
+
isTest: payload.test === true,
|
|
33
|
+
expiresAt: payload.expiresAt ? new Date(payload.expiresAt) : null,
|
|
34
|
+
entitlements: payload.entitlements ?? [],
|
|
35
|
+
metadata: payload.metadata ?? {},
|
|
36
|
+
maxHostUsers: max,
|
|
37
|
+
hostUserPolicy: max === null ? null : (payload.hostUserPolicy ?? 'block'),
|
|
38
|
+
hostUsersOverLimit: payload.hostUsersExceeded === true || (max !== null && typeof hostUsers === 'number' && hostUsers > max),
|
|
39
|
+
};
|
|
40
|
+
}
|
|
41
|
+
export const hasFeature = (payload, code) => (payload.entitlements ?? []).indexOf(code) >= 0;
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import type { Fingerprint } from './token.js';
|
|
2
|
+
export declare const UNAVAILABLE = "none";
|
|
3
|
+
/** Host platforms whose installations are licensed like devices (the server's list; extended as adapters ship). */
|
|
4
|
+
export declare const HOST_PLATFORMS: readonly string[];
|
|
5
|
+
export type ComponentPart = 'machine' | 'disk' | 'host' | 'board' | 'installation';
|
|
6
|
+
/**
|
|
7
|
+
* lowercase_hex(SHA256(vendor:product:part:UPPER(TRIM(raw)))); missing or blank raw is "none". The vendor is the organization
|
|
8
|
+
* id (ten_...), so the same device or installation hashes differently for every vendor and product.
|
|
9
|
+
*/
|
|
10
|
+
export declare function hashComponent(vendor: string, product: string, part: ComponentPart, raw: string | null | undefined): string;
|
|
11
|
+
/** The fingerprint of an installation inside a host platform (e.g. a YouTrack instance's uuid). */
|
|
12
|
+
export declare function installationFingerprint(vendor: string, product: string, platform: string, installationId: string): Fingerprint;
|
|
13
|
+
export declare const isHostInstallation: (f: Fingerprint) => boolean;
|
|
14
|
+
/**
|
|
15
|
+
* Whether `presented` is the device or installation `registered` was issued for (call on the registered fingerprint).
|
|
16
|
+
* Installations: same platform and exactly the same id. Computers: board id + one other part, or two of three without a board id.
|
|
17
|
+
*/
|
|
18
|
+
export declare function fingerprintMatches(registered: Fingerprint, presented: Fingerprint): boolean;
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
import { hex, utf8Encode } from './encoding.js';
|
|
2
|
+
import { sha256 } from './sha256.js';
|
|
3
|
+
export const UNAVAILABLE = 'none';
|
|
4
|
+
/** Host platforms whose installations are licensed like devices (the server's list; extended as adapters ship). */
|
|
5
|
+
export const HOST_PLATFORMS = ['youtrack'];
|
|
6
|
+
/**
|
|
7
|
+
* lowercase_hex(SHA256(vendor:product:part:UPPER(TRIM(raw)))); missing or blank raw is "none". The vendor is the organization
|
|
8
|
+
* id (ten_...), so the same device or installation hashes differently for every vendor and product.
|
|
9
|
+
*/
|
|
10
|
+
export function hashComponent(vendor, product, part, raw) {
|
|
11
|
+
if (raw == null || raw.trim() === '')
|
|
12
|
+
return UNAVAILABLE;
|
|
13
|
+
return hex(sha256(utf8Encode(`${vendor}:${product}:${part}:${raw.trim().toUpperCase()}`)));
|
|
14
|
+
}
|
|
15
|
+
/** The fingerprint of an installation inside a host platform (e.g. a YouTrack instance's uuid). */
|
|
16
|
+
export function installationFingerprint(vendor, product, platform, installationId) {
|
|
17
|
+
return {
|
|
18
|
+
machineId: hashComponent(vendor, product, 'installation', installationId),
|
|
19
|
+
diskId: UNAVAILABLE, hostName: UNAVAILABLE, boardId: UNAVAILABLE,
|
|
20
|
+
os: platform.toLowerCase(),
|
|
21
|
+
};
|
|
22
|
+
}
|
|
23
|
+
export const isHostInstallation = (f) => !!f.os && HOST_PLATFORMS.indexOf(f.os.toLowerCase()) >= 0;
|
|
24
|
+
const available = (v) => !!v && v !== UNAVAILABLE;
|
|
25
|
+
const same = (a, b) => available(a) && a === b;
|
|
26
|
+
/**
|
|
27
|
+
* Whether `presented` is the device or installation `registered` was issued for (call on the registered fingerprint).
|
|
28
|
+
* Installations: same platform and exactly the same id. Computers: board id + one other part, or two of three without a board id.
|
|
29
|
+
*/
|
|
30
|
+
export function fingerprintMatches(registered, presented) {
|
|
31
|
+
if (isHostInstallation(registered) || isHostInstallation(presented))
|
|
32
|
+
return (registered.os ?? '').toLowerCase() === (presented.os ?? '').toLowerCase() && same(registered.machineId, presented.machineId);
|
|
33
|
+
if (registered.os && presented.os && registered.os.toLowerCase() !== presented.os.toLowerCase())
|
|
34
|
+
return false;
|
|
35
|
+
let matches = 0;
|
|
36
|
+
if (same(registered.machineId, presented.machineId))
|
|
37
|
+
matches++;
|
|
38
|
+
if (same(registered.diskId, presented.diskId))
|
|
39
|
+
matches++;
|
|
40
|
+
if (same(registered.hostName, presented.hostName))
|
|
41
|
+
matches++;
|
|
42
|
+
return available(registered.boardId) ? same(registered.boardId, presented.boardId) && matches >= 1 : matches >= 2;
|
|
43
|
+
}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
export { utf8Encode, utf8Decode, base64Decode, hex } from './encoding.js';
|
|
2
|
+
export { sha256 } from './sha256.js';
|
|
3
|
+
export { verifyP256, parsePublicKey } from './p256.js';
|
|
4
|
+
export { verifyToken, verifyTokenAsync, decodeTokenUnverified, type Fingerprint, type LicensePayload } from './token.js';
|
|
5
|
+
export { hashComponent, installationFingerprint, fingerprintMatches, isHostInstallation, HOST_PLATFORMS, UNAVAILABLE, type ComponentPart } from './fingerprint.js';
|
|
6
|
+
export { evaluate, summarize, hasFeature, type LicenseStatus, type LicenseSummary } from './evaluate.js';
|
|
7
|
+
export { activateRequest, refreshRequest, deactivateRequest, trialRequest, readResponse, refreshDueAt, REVOKING_CODES, INSTALLATION_HEADER, type HttpRequestDescription, type ActivateOptions, type RefreshOptions, type TrialOptions, type ClientResponse, type Target, } from './protocol.js';
|
|
8
|
+
export { createLicenseClient, type ClientOptions, type LicenseStorage, type Transport, type LicenseState, type ActionResult, type LicenseClient } from './client.js';
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
// licenserail-embedded: the LicenseRail client core for apps that run inside a host platform (YouTrack apps, browser
|
|
2
|
+
// extensions, web apps, workers). No dependencies and no Node APIs; needs ES2020 (BigInt).
|
|
3
|
+
export { utf8Encode, utf8Decode, base64Decode, hex } from './encoding.js';
|
|
4
|
+
export { sha256 } from './sha256.js';
|
|
5
|
+
export { verifyP256, parsePublicKey } from './p256.js';
|
|
6
|
+
export { verifyToken, verifyTokenAsync, decodeTokenUnverified } from './token.js';
|
|
7
|
+
export { hashComponent, installationFingerprint, fingerprintMatches, isHostInstallation, HOST_PLATFORMS, UNAVAILABLE } from './fingerprint.js';
|
|
8
|
+
export { evaluate, summarize, hasFeature } from './evaluate.js';
|
|
9
|
+
export { activateRequest, refreshRequest, deactivateRequest, trialRequest, readResponse, refreshDueAt, REVOKING_CODES, INSTALLATION_HEADER, } from './protocol.js';
|
|
10
|
+
export { createLicenseClient } from './client.js';
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import { type Bytes } from './encoding.js';
|
|
2
|
+
/** The public point of a PEM (SPKI) P-256 key, or null if it is anything else. */
|
|
3
|
+
export declare function parsePublicKey(pem: string): {
|
|
4
|
+
x: Bytes;
|
|
5
|
+
y: Bytes;
|
|
6
|
+
} | null;
|
|
7
|
+
/** Verifies an IEEE P1363 (r || s, 64 bytes) ECDSA P-256 SHA-256 signature over `data`. */
|
|
8
|
+
export declare function verifyP256(publicKeyPem: string, data: ArrayLike<number>, signature: ArrayLike<number>): boolean;
|