@codeo-engineering/licenserail-embedded 0.1.0 → 0.1.6
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/README.md +34 -6
- package/dist/cjs/client.js +86 -21
- package/dist/cjs/evaluate.js +69 -4
- package/dist/cjs/fingerprint.js +14 -2
- package/dist/cjs/index.js +7 -1
- package/dist/cjs/protocol.js +55 -8
- package/dist/esm/client.d.ts +37 -5
- package/dist/esm/client.js +87 -22
- package/dist/esm/evaluate.d.ts +36 -3
- package/dist/esm/evaluate.js +66 -4
- package/dist/esm/fingerprint.d.ts +4 -2
- package/dist/esm/fingerprint.js +14 -2
- package/dist/esm/index.d.ts +3 -3
- package/dist/esm/index.js +3 -3
- package/dist/esm/protocol.d.ts +55 -0
- package/dist/esm/protocol.js +52 -8
- package/dist/esm/token.d.ts +17 -0
- package/package.json +2 -2
package/README.md
CHANGED
|
@@ -9,7 +9,7 @@ No dependencies and no Node APIs: it needs ES2020 (BigInt) and nothing else, so
|
|
|
9
9
|
- Installation identity: `installationFingerprint(vendor, product, platform, installationId)` licenses one installation of
|
|
10
10
|
the host (for example a YouTrack instance) instead of a computer.
|
|
11
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.
|
|
12
|
+
floating leases (with borrowing), use counting and keyless trials — no I/O of their own, so callback-style hosts can send them.
|
|
13
13
|
- `createLicenseClient(...)`: a ready client for hosts that can await `fetch`.
|
|
14
14
|
|
|
15
15
|
For YouTrack apps use [`@codeo-engineering/licenserail-youtrack`](../youtrack), which wires this core into app settings, storage, async HTTP
|
|
@@ -29,26 +29,54 @@ const client = createLicenseClient({
|
|
|
29
29
|
appVersion: '1.2.0',
|
|
30
30
|
})
|
|
31
31
|
|
|
32
|
-
await client.startTrial(KEY_ID
|
|
32
|
+
await client.startTrial(KEY_ID, { instanceId: installationId, baseUrls: ['https://acme.youtrack.cloud'] })
|
|
33
|
+
// keyless trial, once per installation; the server confirms the
|
|
34
|
+
// instance at its address, so it must be reachable from the internet
|
|
33
35
|
await client.activate(licenseKey) // a license key
|
|
34
36
|
const { status, summary } = await client.state() // offline check: 'Valid', 'Expired', 'OfflineTooLong', ...
|
|
35
37
|
await client.refresh() // when the token asks for it; keeps the license on network errors
|
|
36
38
|
await client.deactivate() // release this installation
|
|
39
|
+
await client.consume(1) // use-limited license: { ok, uses, maxUses } or { ok: false, code }
|
|
40
|
+
await client.borrow(24) // floating: keep the seat offline for 24 hours; returnBorrow() gives it back
|
|
37
41
|
```
|
|
38
42
|
|
|
39
|
-
`summary` has `isTrial
|
|
40
|
-
|
|
43
|
+
`summary` has `isTrial` (keyless trials only: the token says `trial: true`; a keyed license of kind `trial` is an ordinary
|
|
44
|
+
license that refreshes and deactivates), `expiresAt` (what the offline check enforces: the end of grace, or null when the
|
|
45
|
+
expiration strategy keeps the license working), `licenseExpiresAt` (the license's own expiry for display, null = perpetual;
|
|
46
|
+
never enforced), `entitlements`, `metadata`, `maxHostUsers`, `hostUserPolicy`,
|
|
47
|
+
`hostUsersOverLimit`, `expired` (expired, but its expiration strategy keeps it working), `inGrace` / `graceUntil`,
|
|
48
|
+
`maxAppVersion`, `maxUses` / `uses`, `borrowedUntil`, `overage` and `matching`. Pass `hostUsers: () => count` when the license
|
|
49
|
+
is priced per host user. `state()` checks `appVersion` against the license's `maxAppVersion` (status `AppVersionNotAllowed`;
|
|
50
|
+
`refresh()` then asks the server at once instead of waiting for `refreshAfter`, so an app updated before the license expires
|
|
51
|
+
gets a new cap; a keyless trial is not refreshed) and applies the token's `matching` (installations always match exactly). Every request carries the device clock as
|
|
52
|
+
`clientTime`; the server refuses requests when it is far off (`clock_offset`). `consume(count)` and `borrow(hours)` refuse a
|
|
53
|
+
count or hours below 1 (`bad_request`) and a missing license (`no_license`) without a request; `borrow` also refuses a license
|
|
54
|
+
that isn't a checked-out floating one (`borrow_not_allowed`). Refresh, consume and borrow remove the local license only on a
|
|
55
|
+
revoking code or `lease_expired`; any other refusal keeps it. A keyless trial (`trial: true`) is never sent to the server:
|
|
56
|
+
`refresh()` (even with `force`) returns it as it is, `consume()` and `borrow()` return `bad_request`. `returnBorrow()`
|
|
57
|
+
releases the seat of a floating license; on a node-locked license or a keyless trial it returns `borrow_not_allowed` without a
|
|
58
|
+
request, so it never uses up a deactivation.
|
|
41
59
|
|
|
42
60
|
## Core functions (any host)
|
|
43
61
|
|
|
44
62
|
| Function | Purpose |
|
|
45
63
|
|---|---|
|
|
46
64
|
| `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 |
|
|
65
|
+
| `evaluate(payload, product, fingerprint, now, lastSeen, appVersion?)` | Offline status, identical in every LicenseRail SDK (token `matching`, `maxAppVersion`) |
|
|
66
|
+
| `fingerprintMatches(registered, presented, strategy?)`, `compareVersions(a, b)`, `isVersion(v)` | Device matching (`default`, `strict`, `loose`) and the server's version rules (`test-vectors/versions.json`) |
|
|
48
67
|
| `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 |
|
|
68
|
+
| `activateRequest`, `refreshRequest`, `deactivateRequest`, `trialRequest`, `borrowRequest`, `consumeRequest` | `{method, url, headers, body}` to send; `clientTime` defaults to now (`null`, an invalid Date or a string that isn't a date leaves it out) |
|
|
50
69
|
| `readResponse(status, body)` | Token, or an error with `revokesLocalLicense` / `retryLater` |
|
|
70
|
+
| `readUseResponse(status, body)` | The answer to `consumeRequest`: `{ ok: true, uses, maxUses }` or the same error shape |
|
|
51
71
|
| `refreshDueAt(payload)` | When to refresh (null for trials) |
|
|
52
72
|
|
|
73
|
+
## Changes
|
|
74
|
+
|
|
75
|
+
- 2026-12-01: additions only, existing calls keep working. New: the `AppVersionNotAllowed` status (an added member of
|
|
76
|
+
`LicenseStatus`: a `Record<LicenseStatus, ...>` or an exhaustive `switch` needs an entry for it), `borrowRequest`,
|
|
77
|
+
`consumeRequest`, `readUseResponse`, and `borrow()`, `returnBorrow()` and `consume()` on the client. Changed behaviour:
|
|
78
|
+
`summary.isTrial` is true only for keyless trials (`trial: true`), an invalid `clientTime` is left out instead of throwing,
|
|
79
|
+
and versions with a 10-digit part up to 2147483647 compare like the server.
|
|
80
|
+
|
|
53
81
|
Build: `npm run build` writes ES modules to `dist/esm` and CommonJS (for `require()`, e.g. YouTrack apps) to `dist/cjs`.
|
|
54
82
|
Tests: `npm test` (shared vectors, Wycheproof, a sandbox without web/Node globals, the client).
|
package/dist/cjs/client.js
CHANGED
|
@@ -24,6 +24,8 @@ const fetchTransport = (timeoutMs) => async (r) => {
|
|
|
24
24
|
host.clearTimeout?.(timer);
|
|
25
25
|
}
|
|
26
26
|
};
|
|
27
|
+
/** The one rule (refresh, consume, borrow) for removing the local license: a revoking code or lease_expired. */
|
|
28
|
+
const removesLicense = (code, revoking) => revoking || code === 'lease_expired';
|
|
27
29
|
function createLicenseClient(o) {
|
|
28
30
|
const send = o.transport ?? fetchTransport(o.timeoutMs ?? 10000);
|
|
29
31
|
const now = () => (o.now ? o.now() : new Date());
|
|
@@ -39,7 +41,7 @@ function createLicenseClient(o) {
|
|
|
39
41
|
if (!token)
|
|
40
42
|
return { status: 'Missing', payload: null, summary: null };
|
|
41
43
|
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);
|
|
44
|
+
const status = (0, evaluate_js_1.evaluate)(payload, o.product, o.fingerprint, now(), lastSeen, o.appVersion);
|
|
43
45
|
if (status === 'Valid')
|
|
44
46
|
await o.storage.set(key('lastSeen'), String(now().getTime()));
|
|
45
47
|
return { status, payload, summary: payload ? (0, evaluate_js_1.summarize)(payload, o.hostUsers?.()) : null };
|
|
@@ -61,53 +63,116 @@ function createLicenseClient(o) {
|
|
|
61
63
|
return { ok: true, state: await state() };
|
|
62
64
|
}
|
|
63
65
|
if (!r.ok) {
|
|
64
|
-
if (r.revokesLocalLicense)
|
|
66
|
+
if (removesLicense(r.code, r.revokesLocalLicense))
|
|
65
67
|
await o.storage.remove(key('token'));
|
|
66
68
|
return { ok: false, code: r.code, message: r.message, state: await state() };
|
|
67
69
|
}
|
|
68
70
|
return { ok: true, state: await state() };
|
|
69
71
|
}
|
|
72
|
+
async function deactivate() {
|
|
73
|
+
const { token } = await load();
|
|
74
|
+
const current = await state();
|
|
75
|
+
if (!token || !current.payload || current.payload.trial === true) {
|
|
76
|
+
await o.storage.remove(key('token'));
|
|
77
|
+
return { ok: true, state: await state() };
|
|
78
|
+
}
|
|
79
|
+
const res = await send((0, protocol_js_1.deactivateRequest)({ ...target, token, floating: current.payload.floating === true }));
|
|
80
|
+
const r = (0, protocol_js_1.readResponse)(res.status, res.body);
|
|
81
|
+
if (r.ok || r.revokesLocalLicense) {
|
|
82
|
+
await o.storage.remove(key('token'));
|
|
83
|
+
return { ok: true, state: await state() };
|
|
84
|
+
}
|
|
85
|
+
return { ok: false, code: r.code, message: r.message, state: current };
|
|
86
|
+
}
|
|
70
87
|
return {
|
|
71
88
|
/** The current license, checked offline. */
|
|
72
89
|
state,
|
|
73
90
|
/** Activates a license key on this device or installation. */
|
|
74
91
|
async activate(licenseKey, floating = false) {
|
|
75
92
|
return (await unidentified()) ?? accept(await send((0, protocol_js_1.activateRequest)({
|
|
76
|
-
...target, licenseKey, machineName: o.machineName, appVersion: o.appVersion, hostUsers: o.hostUsers?.(), floating,
|
|
93
|
+
...target, licenseKey, machineName: o.machineName, appVersion: o.appVersion, hostUsers: o.hostUsers?.(), floating, clientTime: now(),
|
|
77
94
|
})));
|
|
78
95
|
},
|
|
79
|
-
/** Starts (or gets back) this device's or installation's keyless trial. */
|
|
80
|
-
async startTrial(keyId) {
|
|
81
|
-
return (await unidentified()) ?? accept(await send((0, protocol_js_1.trialRequest)({
|
|
96
|
+
/** Starts (or gets back) this device's or installation's keyless trial; apps inside a host pass the installation. */
|
|
97
|
+
async startTrial(keyId, host) {
|
|
98
|
+
return (await unidentified()) ?? accept(await send((0, protocol_js_1.trialRequest)({
|
|
99
|
+
...target, keyId, machineName: o.machineName, appVersion: o.appVersion, hostUsers: o.hostUsers?.(), host, clientTime: now(),
|
|
100
|
+
})));
|
|
82
101
|
},
|
|
83
|
-
/** Refreshes when the token asks for it (or always with force); keeps the token on network errors.
|
|
102
|
+
/** Refreshes when the token asks for it (or always with force); keeps the token on network errors. A keyless trial is never
|
|
103
|
+
* sent to the server, even with force: it is returned as it is. When the offline check refuses the app version
|
|
104
|
+
* (AppVersionNotAllowed: the app was updated past the token's maxAppVersion), it refreshes at once, so an app updated before
|
|
105
|
+
* the license expires gets a new cap without waiting for refreshAfter. */
|
|
84
106
|
async refresh(force = false) {
|
|
85
107
|
const { token } = await load();
|
|
86
108
|
const current = await state();
|
|
87
109
|
if (!token || !current.payload)
|
|
88
110
|
return { ok: false, code: 'no_license', message: 'No license to refresh.', state: current };
|
|
111
|
+
if (current.payload.trial === true)
|
|
112
|
+
return { ok: true, state: current };
|
|
89
113
|
const due = (0, protocol_js_1.refreshDueAt)(current.payload);
|
|
90
|
-
|
|
114
|
+
const versionRefused = current.status === 'AppVersionNotAllowed';
|
|
115
|
+
if (!force && !versionRefused && (!due || due.getTime() > now().getTime()))
|
|
91
116
|
return { ok: true, state: current };
|
|
92
117
|
return accept(await send((0, protocol_js_1.refreshRequest)({
|
|
93
|
-
...target, token, appVersion: o.appVersion, hostUsers: o.hostUsers?.(), floating: current.payload.floating === true,
|
|
118
|
+
...target, token, appVersion: o.appVersion, hostUsers: o.hostUsers?.(), floating: current.payload.floating === true, clientTime: now(),
|
|
94
119
|
})));
|
|
95
120
|
},
|
|
96
|
-
/**
|
|
97
|
-
|
|
121
|
+
/**
|
|
122
|
+
* Floating: keeps the checked-out seat for offline use for `hours` (up to the license's limit). Refused without a request
|
|
123
|
+
* with `no_license` when there is no license and `borrow_not_allowed` when it isn't a checked-out floating license; a keyless
|
|
124
|
+
* trial gets `bad_request` (it is never sent to the server). The license is removed only on a revoking code or lease_expired;
|
|
125
|
+
* other refusals keep it.
|
|
126
|
+
*/
|
|
127
|
+
async borrow(hours) {
|
|
98
128
|
const { token } = await load();
|
|
99
129
|
const current = await state();
|
|
100
|
-
if (
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
if (
|
|
130
|
+
if (typeof hours !== 'number' || !Number.isInteger(hours) || hours < 1)
|
|
131
|
+
return { ok: false, code: 'bad_request', message: 'Borrow for a whole number of hours (at least 1).', state: current };
|
|
132
|
+
if (!token)
|
|
133
|
+
return { ok: false, code: 'no_license', message: 'There is no license on this device.', state: current };
|
|
134
|
+
if (current.payload?.trial === true)
|
|
135
|
+
return { ok: false, code: 'bad_request', message: "A trial can't be borrowed.", state: current };
|
|
136
|
+
if (current.payload?.floating !== true)
|
|
137
|
+
return { ok: false, code: 'borrow_not_allowed', message: 'Only a checked-out floating license can be borrowed.', state: current };
|
|
138
|
+
return accept(await send((0, protocol_js_1.borrowRequest)({ ...target, token, hours, appVersion: o.appVersion, clientTime: now() })));
|
|
139
|
+
},
|
|
140
|
+
/**
|
|
141
|
+
* Returns a borrowed floating seat early (releases the seat of a floating license). On a node-locked license or a keyless
|
|
142
|
+
* trial it returns `borrow_not_allowed` without a request, so it can never use up a deactivation. Without a license it
|
|
143
|
+
* succeeds.
|
|
144
|
+
*/
|
|
145
|
+
async returnBorrow() {
|
|
146
|
+
const { token } = await load();
|
|
147
|
+
const current = await state();
|
|
148
|
+
if (!token)
|
|
149
|
+
return { ok: true, state: current };
|
|
150
|
+
if (current.payload?.floating !== true || current.payload.trial === true)
|
|
151
|
+
return { ok: false, code: 'borrow_not_allowed', message: 'Only a floating license can be borrowed and returned.', state: current };
|
|
152
|
+
return deactivate();
|
|
153
|
+
},
|
|
154
|
+
/**
|
|
155
|
+
* Licenses with a use limit: consumes `count` uses on the server (use_limit_reached when they are used up). A count below 1
|
|
156
|
+
* is refused with `bad_request` and no license with `no_license`, both without a request; so is a keyless trial (`bad_request`:
|
|
157
|
+
* it is never sent to the server). The license is removed only on a revoking code or lease_expired; any other refusal keeps it.
|
|
158
|
+
*/
|
|
159
|
+
async consume(count = 1) {
|
|
160
|
+
if (typeof count !== 'number' || !Number.isInteger(count) || count < 1)
|
|
161
|
+
return { ok: false, code: 'bad_request', message: 'Consume a whole number of uses (at least 1).' };
|
|
162
|
+
const { token } = await load();
|
|
163
|
+
if (!token)
|
|
164
|
+
return { ok: false, code: 'no_license', message: 'There is no license on this device.' };
|
|
165
|
+
if ((await (0, token_js_1.verifyTokenAsync)(token, o.publicKeyPem))?.trial === true)
|
|
166
|
+
return { ok: false, code: 'bad_request', message: 'A trial has no uses to consume.' };
|
|
167
|
+
const res = await send((0, protocol_js_1.consumeRequest)({ ...target, token, count }));
|
|
168
|
+
const r = (0, protocol_js_1.readUseResponse)(res.status, res.body);
|
|
169
|
+
if (r.ok)
|
|
170
|
+
return r;
|
|
171
|
+
if (removesLicense(r.code, r.revokesLocalLicense))
|
|
107
172
|
await o.storage.remove(key('token'));
|
|
108
|
-
|
|
109
|
-
}
|
|
110
|
-
return { ok: false, code: r.code, message: r.message, state: current };
|
|
173
|
+
return { ok: false, code: r.code, message: r.message };
|
|
111
174
|
},
|
|
175
|
+
/** Releases the license on this device or installation and removes it locally. */
|
|
176
|
+
deactivate,
|
|
112
177
|
};
|
|
113
178
|
}
|
package/dist/cjs/evaluate.js
CHANGED
|
@@ -1,24 +1,79 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
3
|
exports.hasFeature = void 0;
|
|
4
|
+
exports.isVersion = isVersion;
|
|
5
|
+
exports.compareVersions = compareVersions;
|
|
6
|
+
exports.appVersionAllowed = appVersionAllowed;
|
|
4
7
|
exports.evaluate = evaluate;
|
|
5
8
|
exports.summarize = summarize;
|
|
6
9
|
const fingerprint_js_1 = require("./fingerprint");
|
|
7
10
|
const CLOCK_TOLERANCE_MS = 10 * 60 * 1000;
|
|
8
11
|
const ISSUED_AT_TOLERANCE_MS = 24 * 60 * 60 * 1000;
|
|
12
|
+
/**
|
|
13
|
+
* Whitespace as .NET's char.IsWhiteSpace sees it (the server trims with it): U+0009-U+000D, U+0085 and the Unicode Zs, Zl and Zp
|
|
14
|
+
* characters. Not String.prototype.trim(): that also strips U+FEFF, which .NET keeps.
|
|
15
|
+
*/
|
|
16
|
+
const DOTNET_WHITESPACE = '\u0009-\u000D\u0020\u0085\u00A0\u1680\u2000-\u200A\u2028\u2029\u202F\u205F\u3000';
|
|
17
|
+
const EDGE_WHITESPACE = new RegExp(`^[${DOTNET_WHITESPACE}]+|[${DOTNET_WHITESPACE}]+$`, 'g');
|
|
18
|
+
/** Trims the .NET whitespace set from both ends, like the server's string.Trim(). */
|
|
19
|
+
function trimVersion(v) {
|
|
20
|
+
return v.replace(EDGE_WHITESPACE, '');
|
|
21
|
+
}
|
|
22
|
+
const INT32_MAX = 2147483647;
|
|
23
|
+
/** A part is a run of ASCII digits; the server parses it as a signed 32-bit integer, so one above 2147483647 counts as 0. */
|
|
24
|
+
function versionPart(p) {
|
|
25
|
+
const digits = p.replace(/^0+(?=[0-9])/, '');
|
|
26
|
+
if (digits.length > 10)
|
|
27
|
+
return 0;
|
|
28
|
+
const n = Number(digits);
|
|
29
|
+
return n > INT32_MAX ? 0 : n;
|
|
30
|
+
}
|
|
31
|
+
function versionParts(v) {
|
|
32
|
+
const core = /^[0-9.]*/.exec(trimVersion(v).replace(/^[vV]+/, ''))[0];
|
|
33
|
+
return core.split('.').filter((p) => p !== '').map(versionPart);
|
|
34
|
+
}
|
|
35
|
+
/** A version the server compares: after trimming whitespace, 1 to 50 characters and the first is an ASCII digit. */
|
|
36
|
+
function isVersion(v) {
|
|
37
|
+
if (typeof v !== 'string')
|
|
38
|
+
return false;
|
|
39
|
+
const t = trimVersion(v); // the limit counts UTF-16 code units, like .NET's string.Length
|
|
40
|
+
return t.length > 0 && t.length <= 50 && /^[0-9]/.test(t);
|
|
41
|
+
}
|
|
42
|
+
/**
|
|
43
|
+
* "1.10.2" > "1.9"; a leading v/V is ignored; missing parts are 0; anything after the leading run of ASCII digits and dots
|
|
44
|
+
* (-beta, +build) is ignored; a part above 2147483647 counts as 0. Same as the server (test-vectors/versions.json).
|
|
45
|
+
*/
|
|
46
|
+
function compareVersions(a, b) {
|
|
47
|
+
const x = versionParts(a);
|
|
48
|
+
const y = versionParts(b);
|
|
49
|
+
for (let i = 0; i < Math.max(x.length, y.length); i++) {
|
|
50
|
+
const d = (i < x.length ? x[i] : 0) - (i < y.length ? y[i] : 0);
|
|
51
|
+
if (d !== 0)
|
|
52
|
+
return d < 0 ? -1 : 1;
|
|
53
|
+
}
|
|
54
|
+
return 0;
|
|
55
|
+
}
|
|
56
|
+
/** Whether `appVersion` may run under a license limited to `maxAppVersion` (unknown or missing versions aren't refused). */
|
|
57
|
+
function appVersionAllowed(maxAppVersion, appVersion) {
|
|
58
|
+
return !isVersion(maxAppVersion) || !isVersion(appVersion) || compareVersions(appVersion, maxAppVersion) <= 0;
|
|
59
|
+
}
|
|
9
60
|
/**
|
|
10
61
|
* 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.
|
|
62
|
+
* without one the license is Unverified until the next online check. `appVersion` (optional) is checked against the token's
|
|
63
|
+
* `maxAppVersion`; the token's `matching` is applied to the device. Grace (`graceUntil`) and expired-but-kept licenses
|
|
64
|
+
* (`expired: true`) need nothing extra: the server sets `expiresAt` to the end of grace, or leaves it out.
|
|
12
65
|
*/
|
|
13
|
-
function evaluate(payload, product, machine, now, lastSeen) {
|
|
66
|
+
function evaluate(payload, product, machine, now, lastSeen, appVersion) {
|
|
14
67
|
if (!payload)
|
|
15
68
|
return 'InvalidSignature';
|
|
16
69
|
if (payload.product.toLowerCase() !== product.toLowerCase())
|
|
17
70
|
return 'WrongProduct';
|
|
18
|
-
if (!(0, fingerprint_js_1.fingerprintMatches)(payload.fingerprint, machine))
|
|
71
|
+
if (!(0, fingerprint_js_1.fingerprintMatches)(payload.fingerprint, machine, payload.matching))
|
|
19
72
|
return 'WrongMachine';
|
|
20
73
|
if (payload.suspended)
|
|
21
74
|
return 'Suspended';
|
|
75
|
+
if (!appVersionAllowed(payload.maxAppVersion, appVersion))
|
|
76
|
+
return 'AppVersionNotAllowed';
|
|
22
77
|
if (!lastSeen)
|
|
23
78
|
return 'Unverified';
|
|
24
79
|
const t = now.getTime();
|
|
@@ -33,14 +88,24 @@ function evaluate(payload, product, machine, now, lastSeen) {
|
|
|
33
88
|
function summarize(payload, hostUsers) {
|
|
34
89
|
const max = typeof payload.maxHostUsers === 'number' ? payload.maxHostUsers : null;
|
|
35
90
|
return {
|
|
36
|
-
isTrial: payload.trial === true
|
|
91
|
+
isTrial: payload.trial === true,
|
|
37
92
|
isTest: payload.test === true,
|
|
38
93
|
expiresAt: payload.expiresAt ? new Date(payload.expiresAt) : null,
|
|
94
|
+
licenseExpiresAt: payload.licenseExpiresAt ? new Date(payload.licenseExpiresAt) : null,
|
|
39
95
|
entitlements: payload.entitlements ?? [],
|
|
40
96
|
metadata: payload.metadata ?? {},
|
|
41
97
|
maxHostUsers: max,
|
|
42
98
|
hostUserPolicy: max === null ? null : (payload.hostUserPolicy ?? 'block'),
|
|
43
99
|
hostUsersOverLimit: payload.hostUsersExceeded === true || (max !== null && typeof hostUsers === 'number' && hostUsers > max),
|
|
100
|
+
matching: typeof payload.matching === 'string' ? payload.matching : 'default',
|
|
101
|
+
maxAppVersion: typeof payload.maxAppVersion === 'string' ? payload.maxAppVersion : null,
|
|
102
|
+
expired: payload.expired === true,
|
|
103
|
+
inGrace: !!payload.graceUntil,
|
|
104
|
+
graceUntil: payload.graceUntil ? new Date(payload.graceUntil) : null,
|
|
105
|
+
borrowedUntil: payload.borrowedUntil ? new Date(payload.borrowedUntil) : null,
|
|
106
|
+
maxUses: typeof payload.maxUses === 'number' ? payload.maxUses : null,
|
|
107
|
+
uses: typeof payload.uses === 'number' ? payload.uses : null,
|
|
108
|
+
overage: payload.overage === true,
|
|
44
109
|
};
|
|
45
110
|
}
|
|
46
111
|
const hasFeature = (payload, code) => (payload.entitlements ?? []).indexOf(code) >= 0;
|
package/dist/cjs/fingerprint.js
CHANGED
|
@@ -32,13 +32,25 @@ const available = (v) => !!v && v !== exports.UNAVAILABLE;
|
|
|
32
32
|
const same = (a, b) => available(a) && a === b;
|
|
33
33
|
/**
|
|
34
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:
|
|
35
|
+
* Installations: same platform and exactly the same id, whatever the strategy. Computers: `strategy` is the token's `matching`
|
|
36
|
+
* field; default: board id + one other part, or two of three without a board id; 'strict': every part the registered device
|
|
37
|
+
* has; 'loose': any one part. When both sides name an operating system it must be the same.
|
|
36
38
|
*/
|
|
37
|
-
function fingerprintMatches(registered, presented) {
|
|
39
|
+
function fingerprintMatches(registered, presented, strategy) {
|
|
38
40
|
if ((0, exports.isHostInstallation)(registered) || (0, exports.isHostInstallation)(presented))
|
|
39
41
|
return (registered.os ?? '').toLowerCase() === (presented.os ?? '').toLowerCase() && same(registered.machineId, presented.machineId);
|
|
40
42
|
if (registered.os && presented.os && registered.os.toLowerCase() !== presented.os.toLowerCase())
|
|
41
43
|
return false;
|
|
44
|
+
if (strategy === 'strict' || strategy === 'loose') {
|
|
45
|
+
const parts = [
|
|
46
|
+
[registered.machineId, presented.machineId], [registered.diskId, presented.diskId],
|
|
47
|
+
[registered.hostName, presented.hostName], [registered.boardId, presented.boardId],
|
|
48
|
+
];
|
|
49
|
+
const mine = parts.filter((p) => available(p[0]));
|
|
50
|
+
if (strategy === 'strict')
|
|
51
|
+
return mine.length > 0 && mine.every((p) => same(p[0], p[1]));
|
|
52
|
+
return mine.some((p) => same(p[0], p[1]));
|
|
53
|
+
}
|
|
42
54
|
let matches = 0;
|
|
43
55
|
if (same(registered.machineId, presented.machineId))
|
|
44
56
|
matches++;
|
package/dist/cjs/index.js
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
// licenserail-embedded: the LicenseRail client core for apps that run inside a host platform (YouTrack apps, browser
|
|
3
3
|
// extensions, web apps, workers). No dependencies and no Node APIs; needs ES2020 (BigInt).
|
|
4
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;
|
|
5
|
+
exports.createLicenseClient = exports.INSTALLATION_HEADER = exports.REVOKING_CODES = exports.refreshDueAt = exports.readUseResponse = exports.readResponse = exports.consumeRequest = exports.borrowRequest = exports.trialRequest = exports.deactivateRequest = exports.refreshRequest = exports.activateRequest = exports.appVersionAllowed = exports.isVersion = exports.compareVersions = 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
6
|
var encoding_js_1 = require("./encoding");
|
|
7
7
|
Object.defineProperty(exports, "utf8Encode", { enumerable: true, get: function () { return encoding_js_1.utf8Encode; } });
|
|
8
8
|
Object.defineProperty(exports, "utf8Decode", { enumerable: true, get: function () { return encoding_js_1.utf8Decode; } });
|
|
@@ -28,12 +28,18 @@ var evaluate_js_1 = require("./evaluate");
|
|
|
28
28
|
Object.defineProperty(exports, "evaluate", { enumerable: true, get: function () { return evaluate_js_1.evaluate; } });
|
|
29
29
|
Object.defineProperty(exports, "summarize", { enumerable: true, get: function () { return evaluate_js_1.summarize; } });
|
|
30
30
|
Object.defineProperty(exports, "hasFeature", { enumerable: true, get: function () { return evaluate_js_1.hasFeature; } });
|
|
31
|
+
Object.defineProperty(exports, "compareVersions", { enumerable: true, get: function () { return evaluate_js_1.compareVersions; } });
|
|
32
|
+
Object.defineProperty(exports, "isVersion", { enumerable: true, get: function () { return evaluate_js_1.isVersion; } });
|
|
33
|
+
Object.defineProperty(exports, "appVersionAllowed", { enumerable: true, get: function () { return evaluate_js_1.appVersionAllowed; } });
|
|
31
34
|
var protocol_js_1 = require("./protocol");
|
|
32
35
|
Object.defineProperty(exports, "activateRequest", { enumerable: true, get: function () { return protocol_js_1.activateRequest; } });
|
|
33
36
|
Object.defineProperty(exports, "refreshRequest", { enumerable: true, get: function () { return protocol_js_1.refreshRequest; } });
|
|
34
37
|
Object.defineProperty(exports, "deactivateRequest", { enumerable: true, get: function () { return protocol_js_1.deactivateRequest; } });
|
|
35
38
|
Object.defineProperty(exports, "trialRequest", { enumerable: true, get: function () { return protocol_js_1.trialRequest; } });
|
|
39
|
+
Object.defineProperty(exports, "borrowRequest", { enumerable: true, get: function () { return protocol_js_1.borrowRequest; } });
|
|
40
|
+
Object.defineProperty(exports, "consumeRequest", { enumerable: true, get: function () { return protocol_js_1.consumeRequest; } });
|
|
36
41
|
Object.defineProperty(exports, "readResponse", { enumerable: true, get: function () { return protocol_js_1.readResponse; } });
|
|
42
|
+
Object.defineProperty(exports, "readUseResponse", { enumerable: true, get: function () { return protocol_js_1.readUseResponse; } });
|
|
37
43
|
Object.defineProperty(exports, "refreshDueAt", { enumerable: true, get: function () { return protocol_js_1.refreshDueAt; } });
|
|
38
44
|
Object.defineProperty(exports, "REVOKING_CODES", { enumerable: true, get: function () { return protocol_js_1.REVOKING_CODES; } });
|
|
39
45
|
Object.defineProperty(exports, "INSTALLATION_HEADER", { enumerable: true, get: function () { return protocol_js_1.INSTALLATION_HEADER; } });
|
package/dist/cjs/protocol.js
CHANGED
|
@@ -4,8 +4,11 @@ exports.REVOKING_CODES = exports.INSTALLATION_HEADER = void 0;
|
|
|
4
4
|
exports.activateRequest = activateRequest;
|
|
5
5
|
exports.refreshRequest = refreshRequest;
|
|
6
6
|
exports.deactivateRequest = deactivateRequest;
|
|
7
|
+
exports.borrowRequest = borrowRequest;
|
|
8
|
+
exports.consumeRequest = consumeRequest;
|
|
7
9
|
exports.trialRequest = trialRequest;
|
|
8
10
|
exports.readResponse = readResponse;
|
|
11
|
+
exports.readUseResponse = readUseResponse;
|
|
9
12
|
exports.refreshDueAt = refreshDueAt;
|
|
10
13
|
/** Header that makes the server rate-limit per installation instead of per IP (apps inside a host share its IPs). */
|
|
11
14
|
exports.INSTALLATION_HEADER = 'LicenseRail-Installation';
|
|
@@ -18,6 +21,14 @@ function headers(fingerprint) {
|
|
|
18
21
|
h[exports.INSTALLATION_HEADER] = `${fingerprint.os}:${fingerprint.machineId}`.slice(0, 128);
|
|
19
22
|
return h;
|
|
20
23
|
}
|
|
24
|
+
function clientTime(t) {
|
|
25
|
+
if (t === null)
|
|
26
|
+
return undefined;
|
|
27
|
+
if (typeof t === 'string')
|
|
28
|
+
return isNaN(Date.parse(t)) ? undefined : t;
|
|
29
|
+
const d = t instanceof Date ? t : t === undefined ? new Date() : null;
|
|
30
|
+
return d && !isNaN(d.getTime()) ? d.toISOString() : undefined;
|
|
31
|
+
}
|
|
21
32
|
function clean(o) {
|
|
22
33
|
const out = {};
|
|
23
34
|
for (const k of Object.keys(o))
|
|
@@ -36,7 +47,7 @@ function activateRequest(o) {
|
|
|
36
47
|
headers: h,
|
|
37
48
|
body: JSON.stringify(clean({
|
|
38
49
|
product: o.product, fingerprint: o.fingerprint, licenseKey: inHeader ? undefined : o.licenseKey,
|
|
39
|
-
machineName: o.machineName, appVersion: o.appVersion, hostUsers: o.hostUsers,
|
|
50
|
+
machineName: o.machineName, appVersion: o.appVersion, hostUsers: o.hostUsers, clientTime: clientTime(o.clientTime),
|
|
40
51
|
})),
|
|
41
52
|
};
|
|
42
53
|
}
|
|
@@ -46,7 +57,7 @@ function refreshRequest(o) {
|
|
|
46
57
|
url: url(o.apiUrl, o.floating ? '/floating/heartbeat' : '/refresh'),
|
|
47
58
|
headers: headers(o.fingerprint),
|
|
48
59
|
// 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 }),
|
|
60
|
+
body: JSON.stringify({ ...clean({ token: o.token, fingerprint: o.fingerprint, anomalies: o.anomalies, hostUsers: o.hostUsers, clientTime: clientTime(o.clientTime) }), appVersion: o.appVersion ?? null }),
|
|
50
61
|
};
|
|
51
62
|
}
|
|
52
63
|
function deactivateRequest(o) {
|
|
@@ -57,27 +68,53 @@ function deactivateRequest(o) {
|
|
|
57
68
|
body: JSON.stringify({ token: o.token, fingerprint: o.fingerprint }),
|
|
58
69
|
};
|
|
59
70
|
}
|
|
71
|
+
/**
|
|
72
|
+
* Floating: keeps the checked-out seat for offline use for `hours`. The answer is a token (readResponse). Return the seat early
|
|
73
|
+
* with deactivateRequest({ ..., floating: true }).
|
|
74
|
+
*/
|
|
75
|
+
function borrowRequest(o) {
|
|
76
|
+
return {
|
|
77
|
+
method: 'POST',
|
|
78
|
+
url: url(o.apiUrl, '/floating/borrow'),
|
|
79
|
+
headers: headers(o.fingerprint),
|
|
80
|
+
body: JSON.stringify({ ...clean({ token: o.token, fingerprint: o.fingerprint, hours: o.hours, clientTime: clientTime(o.clientTime) }), appVersion: o.appVersion ?? null }),
|
|
81
|
+
};
|
|
82
|
+
}
|
|
83
|
+
/** Licenses with a use limit: consumes `count` uses. Read the answer with readUseResponse. */
|
|
84
|
+
function consumeRequest(o) {
|
|
85
|
+
return {
|
|
86
|
+
method: 'POST',
|
|
87
|
+
url: url(o.apiUrl, '/use'),
|
|
88
|
+
headers: headers(o.fingerprint),
|
|
89
|
+
body: JSON.stringify({ token: o.token, fingerprint: o.fingerprint, count: o.count }),
|
|
90
|
+
};
|
|
91
|
+
}
|
|
60
92
|
function trialRequest(o) {
|
|
61
93
|
return {
|
|
62
94
|
method: 'POST',
|
|
63
95
|
url: url(o.apiUrl, '/trial'),
|
|
64
96
|
headers: headers(o.fingerprint),
|
|
65
|
-
body: JSON.stringify(clean({
|
|
97
|
+
body: JSON.stringify(clean({
|
|
98
|
+
keyId: o.keyId, product: o.product, fingerprint: o.fingerprint, machineName: o.machineName, appVersion: o.appVersion, hostUsers: o.hostUsers,
|
|
99
|
+
host: o.host, clientTime: clientTime(o.clientTime),
|
|
100
|
+
})),
|
|
66
101
|
};
|
|
67
102
|
}
|
|
68
103
|
/** Codes on which the local license must be removed; on all others (network errors, 402, 429, 5xx) the app keeps it. */
|
|
69
104
|
exports.REVOKING_CODES = [
|
|
70
105
|
'license_not_found', 'license_suspended', 'license_expired', 'activation_revoked', 'wrong_machine', 'invalid_token', 'license_revoked',
|
|
71
106
|
];
|
|
72
|
-
|
|
73
|
-
function readResponse(status, bodyText) {
|
|
74
|
-
let body = null;
|
|
107
|
+
function parseBody(bodyText) {
|
|
75
108
|
try {
|
|
76
|
-
|
|
109
|
+
return bodyText ? JSON.parse(bodyText) : null;
|
|
77
110
|
}
|
|
78
111
|
catch {
|
|
79
|
-
|
|
112
|
+
return null;
|
|
80
113
|
}
|
|
114
|
+
}
|
|
115
|
+
/** Reads a client API response. `status` 0 means the request failed before any response (network error, timeout). */
|
|
116
|
+
function readResponse(status, bodyText) {
|
|
117
|
+
const body = parseBody(bodyText);
|
|
81
118
|
if (status >= 200 && status < 300) {
|
|
82
119
|
if (status === 204)
|
|
83
120
|
return { ok: true, token: null };
|
|
@@ -85,6 +122,16 @@ function readResponse(status, bodyText) {
|
|
|
85
122
|
if (body && typeof body.token === 'string')
|
|
86
123
|
return { ok: true, token: body.token };
|
|
87
124
|
}
|
|
125
|
+
return errorResponse(status, body);
|
|
126
|
+
}
|
|
127
|
+
/** Reads the answer to consumeRequest: the license's use counter after the use, or an error (use_limit_reached when used up). */
|
|
128
|
+
function readUseResponse(status, bodyText) {
|
|
129
|
+
const body = parseBody(bodyText);
|
|
130
|
+
if (status >= 200 && status < 300 && body && (typeof body.uses === 'number' || typeof body.maxUses === 'number'))
|
|
131
|
+
return { ok: true, uses: typeof body.uses === 'number' ? body.uses : null, maxUses: typeof body.maxUses === 'number' ? body.maxUses : null };
|
|
132
|
+
return errorResponse(status, body);
|
|
133
|
+
}
|
|
134
|
+
function errorResponse(status, body) {
|
|
88
135
|
const code = body && typeof body.code === 'string' ? body.code : status === 0 ? 'network_error' : `http_${status}`;
|
|
89
136
|
const message = body && typeof body.message === 'string' ? body.message : status === 0 ? 'The license server could not be reached.' : 'Unexpected response from the license server.';
|
|
90
137
|
return {
|
package/dist/esm/client.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { type LicenseStatus, type LicenseSummary } from './evaluate.js';
|
|
2
|
-
import { type HttpRequestDescription } from './protocol.js';
|
|
2
|
+
import { type HttpRequestDescription, type TrialHost } from './protocol.js';
|
|
3
3
|
import { type Fingerprint, type LicensePayload } from './token.js';
|
|
4
4
|
/** Key-value storage for the token and the last-run time (e.g. chrome.storage, localStorage, a settings store). */
|
|
5
5
|
export interface LicenseStorage {
|
|
@@ -45,16 +45,48 @@ export type ActionResult = {
|
|
|
45
45
|
message: string;
|
|
46
46
|
state: LicenseState;
|
|
47
47
|
};
|
|
48
|
+
/** Result of consume(): the license's use counter after the use, or why it was refused. */
|
|
49
|
+
export type ConsumeResult = {
|
|
50
|
+
ok: true;
|
|
51
|
+
uses: number | null;
|
|
52
|
+
maxUses: number | null;
|
|
53
|
+
} | {
|
|
54
|
+
ok: false;
|
|
55
|
+
code: string;
|
|
56
|
+
message: string;
|
|
57
|
+
};
|
|
48
58
|
export declare function createLicenseClient(o: ClientOptions): {
|
|
49
59
|
/** The current license, checked offline. */
|
|
50
60
|
state: () => Promise<LicenseState>;
|
|
51
61
|
/** Activates a license key on this device or installation. */
|
|
52
62
|
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.
|
|
63
|
+
/** Starts (or gets back) this device's or installation's keyless trial; apps inside a host pass the installation. */
|
|
64
|
+
startTrial(keyId: string, host?: TrialHost): Promise<ActionResult>;
|
|
65
|
+
/** Refreshes when the token asks for it (or always with force); keeps the token on network errors. A keyless trial is never
|
|
66
|
+
* sent to the server, even with force: it is returned as it is. When the offline check refuses the app version
|
|
67
|
+
* (AppVersionNotAllowed: the app was updated past the token's maxAppVersion), it refreshes at once, so an app updated before
|
|
68
|
+
* the license expires gets a new cap without waiting for refreshAfter. */
|
|
56
69
|
refresh(force?: boolean): Promise<ActionResult>;
|
|
70
|
+
/**
|
|
71
|
+
* Floating: keeps the checked-out seat for offline use for `hours` (up to the license's limit). Refused without a request
|
|
72
|
+
* with `no_license` when there is no license and `borrow_not_allowed` when it isn't a checked-out floating license; a keyless
|
|
73
|
+
* trial gets `bad_request` (it is never sent to the server). The license is removed only on a revoking code or lease_expired;
|
|
74
|
+
* other refusals keep it.
|
|
75
|
+
*/
|
|
76
|
+
borrow(hours: number): Promise<ActionResult>;
|
|
77
|
+
/**
|
|
78
|
+
* Returns a borrowed floating seat early (releases the seat of a floating license). On a node-locked license or a keyless
|
|
79
|
+
* trial it returns `borrow_not_allowed` without a request, so it can never use up a deactivation. Without a license it
|
|
80
|
+
* succeeds.
|
|
81
|
+
*/
|
|
82
|
+
returnBorrow(): Promise<ActionResult>;
|
|
83
|
+
/**
|
|
84
|
+
* Licenses with a use limit: consumes `count` uses on the server (use_limit_reached when they are used up). A count below 1
|
|
85
|
+
* is refused with `bad_request` and no license with `no_license`, both without a request; so is a keyless trial (`bad_request`:
|
|
86
|
+
* it is never sent to the server). The license is removed only on a revoking code or lease_expired; any other refusal keeps it.
|
|
87
|
+
*/
|
|
88
|
+
consume(count?: number): Promise<ConsumeResult>;
|
|
57
89
|
/** Releases the license on this device or installation and removes it locally. */
|
|
58
|
-
deactivate()
|
|
90
|
+
deactivate: () => Promise<ActionResult>;
|
|
59
91
|
};
|
|
60
92
|
export type LicenseClient = ReturnType<typeof createLicenseClient>;
|
package/dist/esm/client.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { evaluate, summarize } from './evaluate.js';
|
|
2
2
|
import { fingerprintMatches } from './fingerprint.js';
|
|
3
|
-
import { activateRequest, deactivateRequest, readResponse, refreshDueAt, refreshRequest, trialRequest } from './protocol.js';
|
|
3
|
+
import { activateRequest, borrowRequest, consumeRequest, deactivateRequest, readResponse, readUseResponse, refreshDueAt, refreshRequest, trialRequest, } from './protocol.js';
|
|
4
4
|
import { verifyTokenAsync } from './token.js';
|
|
5
5
|
const fetchTransport = (timeoutMs) => async (r) => {
|
|
6
6
|
const host = globalThis;
|
|
@@ -21,6 +21,8 @@ const fetchTransport = (timeoutMs) => async (r) => {
|
|
|
21
21
|
host.clearTimeout?.(timer);
|
|
22
22
|
}
|
|
23
23
|
};
|
|
24
|
+
/** The one rule (refresh, consume, borrow) for removing the local license: a revoking code or lease_expired. */
|
|
25
|
+
const removesLicense = (code, revoking) => revoking || code === 'lease_expired';
|
|
24
26
|
export function createLicenseClient(o) {
|
|
25
27
|
const send = o.transport ?? fetchTransport(o.timeoutMs ?? 10000);
|
|
26
28
|
const now = () => (o.now ? o.now() : new Date());
|
|
@@ -36,7 +38,7 @@ export function createLicenseClient(o) {
|
|
|
36
38
|
if (!token)
|
|
37
39
|
return { status: 'Missing', payload: null, summary: null };
|
|
38
40
|
const payload = await verifyTokenAsync(token, o.publicKeyPem);
|
|
39
|
-
const status = evaluate(payload, o.product, o.fingerprint, now(), lastSeen);
|
|
41
|
+
const status = evaluate(payload, o.product, o.fingerprint, now(), lastSeen, o.appVersion);
|
|
40
42
|
if (status === 'Valid')
|
|
41
43
|
await o.storage.set(key('lastSeen'), String(now().getTime()));
|
|
42
44
|
return { status, payload, summary: payload ? summarize(payload, o.hostUsers?.()) : null };
|
|
@@ -58,53 +60,116 @@ export function createLicenseClient(o) {
|
|
|
58
60
|
return { ok: true, state: await state() };
|
|
59
61
|
}
|
|
60
62
|
if (!r.ok) {
|
|
61
|
-
if (r.revokesLocalLicense)
|
|
63
|
+
if (removesLicense(r.code, r.revokesLocalLicense))
|
|
62
64
|
await o.storage.remove(key('token'));
|
|
63
65
|
return { ok: false, code: r.code, message: r.message, state: await state() };
|
|
64
66
|
}
|
|
65
67
|
return { ok: true, state: await state() };
|
|
66
68
|
}
|
|
69
|
+
async function deactivate() {
|
|
70
|
+
const { token } = await load();
|
|
71
|
+
const current = await state();
|
|
72
|
+
if (!token || !current.payload || current.payload.trial === true) {
|
|
73
|
+
await o.storage.remove(key('token'));
|
|
74
|
+
return { ok: true, state: await state() };
|
|
75
|
+
}
|
|
76
|
+
const res = await send(deactivateRequest({ ...target, token, floating: current.payload.floating === true }));
|
|
77
|
+
const r = readResponse(res.status, res.body);
|
|
78
|
+
if (r.ok || r.revokesLocalLicense) {
|
|
79
|
+
await o.storage.remove(key('token'));
|
|
80
|
+
return { ok: true, state: await state() };
|
|
81
|
+
}
|
|
82
|
+
return { ok: false, code: r.code, message: r.message, state: current };
|
|
83
|
+
}
|
|
67
84
|
return {
|
|
68
85
|
/** The current license, checked offline. */
|
|
69
86
|
state,
|
|
70
87
|
/** Activates a license key on this device or installation. */
|
|
71
88
|
async activate(licenseKey, floating = false) {
|
|
72
89
|
return (await unidentified()) ?? accept(await send(activateRequest({
|
|
73
|
-
...target, licenseKey, machineName: o.machineName, appVersion: o.appVersion, hostUsers: o.hostUsers?.(), floating,
|
|
90
|
+
...target, licenseKey, machineName: o.machineName, appVersion: o.appVersion, hostUsers: o.hostUsers?.(), floating, clientTime: now(),
|
|
74
91
|
})));
|
|
75
92
|
},
|
|
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({
|
|
93
|
+
/** Starts (or gets back) this device's or installation's keyless trial; apps inside a host pass the installation. */
|
|
94
|
+
async startTrial(keyId, host) {
|
|
95
|
+
return (await unidentified()) ?? accept(await send(trialRequest({
|
|
96
|
+
...target, keyId, machineName: o.machineName, appVersion: o.appVersion, hostUsers: o.hostUsers?.(), host, clientTime: now(),
|
|
97
|
+
})));
|
|
79
98
|
},
|
|
80
|
-
/** Refreshes when the token asks for it (or always with force); keeps the token on network errors.
|
|
99
|
+
/** Refreshes when the token asks for it (or always with force); keeps the token on network errors. A keyless trial is never
|
|
100
|
+
* sent to the server, even with force: it is returned as it is. When the offline check refuses the app version
|
|
101
|
+
* (AppVersionNotAllowed: the app was updated past the token's maxAppVersion), it refreshes at once, so an app updated before
|
|
102
|
+
* the license expires gets a new cap without waiting for refreshAfter. */
|
|
81
103
|
async refresh(force = false) {
|
|
82
104
|
const { token } = await load();
|
|
83
105
|
const current = await state();
|
|
84
106
|
if (!token || !current.payload)
|
|
85
107
|
return { ok: false, code: 'no_license', message: 'No license to refresh.', state: current };
|
|
108
|
+
if (current.payload.trial === true)
|
|
109
|
+
return { ok: true, state: current };
|
|
86
110
|
const due = refreshDueAt(current.payload);
|
|
87
|
-
|
|
111
|
+
const versionRefused = current.status === 'AppVersionNotAllowed';
|
|
112
|
+
if (!force && !versionRefused && (!due || due.getTime() > now().getTime()))
|
|
88
113
|
return { ok: true, state: current };
|
|
89
114
|
return accept(await send(refreshRequest({
|
|
90
|
-
...target, token, appVersion: o.appVersion, hostUsers: o.hostUsers?.(), floating: current.payload.floating === true,
|
|
115
|
+
...target, token, appVersion: o.appVersion, hostUsers: o.hostUsers?.(), floating: current.payload.floating === true, clientTime: now(),
|
|
91
116
|
})));
|
|
92
117
|
},
|
|
93
|
-
/**
|
|
94
|
-
|
|
118
|
+
/**
|
|
119
|
+
* Floating: keeps the checked-out seat for offline use for `hours` (up to the license's limit). Refused without a request
|
|
120
|
+
* with `no_license` when there is no license and `borrow_not_allowed` when it isn't a checked-out floating license; a keyless
|
|
121
|
+
* trial gets `bad_request` (it is never sent to the server). The license is removed only on a revoking code or lease_expired;
|
|
122
|
+
* other refusals keep it.
|
|
123
|
+
*/
|
|
124
|
+
async borrow(hours) {
|
|
95
125
|
const { token } = await load();
|
|
96
126
|
const current = await state();
|
|
97
|
-
if (
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
if (
|
|
127
|
+
if (typeof hours !== 'number' || !Number.isInteger(hours) || hours < 1)
|
|
128
|
+
return { ok: false, code: 'bad_request', message: 'Borrow for a whole number of hours (at least 1).', state: current };
|
|
129
|
+
if (!token)
|
|
130
|
+
return { ok: false, code: 'no_license', message: 'There is no license on this device.', state: current };
|
|
131
|
+
if (current.payload?.trial === true)
|
|
132
|
+
return { ok: false, code: 'bad_request', message: "A trial can't be borrowed.", state: current };
|
|
133
|
+
if (current.payload?.floating !== true)
|
|
134
|
+
return { ok: false, code: 'borrow_not_allowed', message: 'Only a checked-out floating license can be borrowed.', state: current };
|
|
135
|
+
return accept(await send(borrowRequest({ ...target, token, hours, appVersion: o.appVersion, clientTime: now() })));
|
|
136
|
+
},
|
|
137
|
+
/**
|
|
138
|
+
* Returns a borrowed floating seat early (releases the seat of a floating license). On a node-locked license or a keyless
|
|
139
|
+
* trial it returns `borrow_not_allowed` without a request, so it can never use up a deactivation. Without a license it
|
|
140
|
+
* succeeds.
|
|
141
|
+
*/
|
|
142
|
+
async returnBorrow() {
|
|
143
|
+
const { token } = await load();
|
|
144
|
+
const current = await state();
|
|
145
|
+
if (!token)
|
|
146
|
+
return { ok: true, state: current };
|
|
147
|
+
if (current.payload?.floating !== true || current.payload.trial === true)
|
|
148
|
+
return { ok: false, code: 'borrow_not_allowed', message: 'Only a floating license can be borrowed and returned.', state: current };
|
|
149
|
+
return deactivate();
|
|
150
|
+
},
|
|
151
|
+
/**
|
|
152
|
+
* Licenses with a use limit: consumes `count` uses on the server (use_limit_reached when they are used up). A count below 1
|
|
153
|
+
* is refused with `bad_request` and no license with `no_license`, both without a request; so is a keyless trial (`bad_request`:
|
|
154
|
+
* it is never sent to the server). The license is removed only on a revoking code or lease_expired; any other refusal keeps it.
|
|
155
|
+
*/
|
|
156
|
+
async consume(count = 1) {
|
|
157
|
+
if (typeof count !== 'number' || !Number.isInteger(count) || count < 1)
|
|
158
|
+
return { ok: false, code: 'bad_request', message: 'Consume a whole number of uses (at least 1).' };
|
|
159
|
+
const { token } = await load();
|
|
160
|
+
if (!token)
|
|
161
|
+
return { ok: false, code: 'no_license', message: 'There is no license on this device.' };
|
|
162
|
+
if ((await verifyTokenAsync(token, o.publicKeyPem))?.trial === true)
|
|
163
|
+
return { ok: false, code: 'bad_request', message: 'A trial has no uses to consume.' };
|
|
164
|
+
const res = await send(consumeRequest({ ...target, token, count }));
|
|
165
|
+
const r = readUseResponse(res.status, res.body);
|
|
166
|
+
if (r.ok)
|
|
167
|
+
return r;
|
|
168
|
+
if (removesLicense(r.code, r.revokesLocalLicense))
|
|
104
169
|
await o.storage.remove(key('token'));
|
|
105
|
-
|
|
106
|
-
}
|
|
107
|
-
return { ok: false, code: r.code, message: r.message, state: current };
|
|
170
|
+
return { ok: false, code: r.code, message: r.message };
|
|
108
171
|
},
|
|
172
|
+
/** Releases the license on this device or installation and removes it locally. */
|
|
173
|
+
deactivate,
|
|
109
174
|
};
|
|
110
175
|
}
|
package/dist/esm/evaluate.d.ts
CHANGED
|
@@ -1,21 +1,54 @@
|
|
|
1
1
|
import type { Fingerprint, LicensePayload } from './token.js';
|
|
2
|
-
export type LicenseStatus = 'Valid' | 'Missing' | 'InvalidSignature' | 'WrongProduct' | 'WrongMachine' | 'Expired' | 'OfflineTooLong' | 'ClockTampered' | 'Unverified' | 'Suspended'
|
|
2
|
+
export type LicenseStatus = 'Valid' | 'Missing' | 'InvalidSignature' | 'WrongProduct' | 'WrongMachine' | 'Expired' | 'OfflineTooLong' | 'ClockTampered' | 'Unverified' | 'Suspended'
|
|
3
|
+
/** The app is newer than the license's maxAppVersion. */
|
|
4
|
+
| 'AppVersionNotAllowed';
|
|
5
|
+
/** A version the server compares: after trimming whitespace, 1 to 50 characters and the first is an ASCII digit. */
|
|
6
|
+
export declare function isVersion(v: string | null | undefined): v is string;
|
|
7
|
+
/**
|
|
8
|
+
* "1.10.2" > "1.9"; a leading v/V is ignored; missing parts are 0; anything after the leading run of ASCII digits and dots
|
|
9
|
+
* (-beta, +build) is ignored; a part above 2147483647 counts as 0. Same as the server (test-vectors/versions.json).
|
|
10
|
+
*/
|
|
11
|
+
export declare function compareVersions(a: string, b: string): number;
|
|
12
|
+
/** Whether `appVersion` may run under a license limited to `maxAppVersion` (unknown or missing versions aren't refused). */
|
|
13
|
+
export declare function appVersionAllowed(maxAppVersion: string | null | undefined, appVersion: string | null | undefined): boolean;
|
|
3
14
|
/**
|
|
4
15
|
* 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.
|
|
16
|
+
* without one the license is Unverified until the next online check. `appVersion` (optional) is checked against the token's
|
|
17
|
+
* `maxAppVersion`; the token's `matching` is applied to the device. Grace (`graceUntil`) and expired-but-kept licenses
|
|
18
|
+
* (`expired: true`) need nothing extra: the server sets `expiresAt` to the end of grace, or leaves it out.
|
|
6
19
|
*/
|
|
7
|
-
export declare function evaluate(payload: LicensePayload | null, product: string, machine: Fingerprint, now: Date, lastSeen: Date | null): LicenseStatus;
|
|
20
|
+
export declare function evaluate(payload: LicensePayload | null, product: string, machine: Fingerprint, now: Date, lastSeen: Date | null, appVersion?: string | null): LicenseStatus;
|
|
8
21
|
/** What an app needs to show and gate features, read from a verified payload. */
|
|
9
22
|
export interface LicenseSummary {
|
|
23
|
+
/** A keyless trial: the token says `trial: true`. A keyed license of kind "trial" is an ordinary license. */
|
|
10
24
|
isTrial: boolean;
|
|
11
25
|
isTest: boolean;
|
|
26
|
+
/** What the offline check enforces (end of grace; null when perpetual or when the strategy keeps the license working). */
|
|
12
27
|
expiresAt: Date | null;
|
|
28
|
+
/** The license's own expiry, for showing to the user (null = perpetual); never enforced. */
|
|
29
|
+
licenseExpiresAt: Date | null;
|
|
13
30
|
entitlements: string[];
|
|
14
31
|
metadata: Record<string, unknown>;
|
|
15
32
|
maxHostUsers: number | null;
|
|
16
33
|
hostUserPolicy: string | null;
|
|
17
34
|
/** True when the server flagged the host user limit (policy "warn"), or `hostUsers` is above the limit. */
|
|
18
35
|
hostUsersOverLimit: boolean;
|
|
36
|
+
/** Device matching applied offline: 'default', 'strict' or 'loose'. */
|
|
37
|
+
matching: string;
|
|
38
|
+
/** The newest app version this license may run; null = any. */
|
|
39
|
+
maxAppVersion: string | null;
|
|
40
|
+
/** The license has expired but keeps working (expiration strategy maintain or allow): show a renewal notice. */
|
|
41
|
+
expired: boolean;
|
|
42
|
+
/** The license expired and works until graceUntil (grace period). */
|
|
43
|
+
inGrace: boolean;
|
|
44
|
+
graceUntil: Date | null;
|
|
45
|
+
/** Floating: the seat is borrowed for offline use until this time. */
|
|
46
|
+
borrowedUntil: Date | null;
|
|
47
|
+
/** Use counting: the license's limit, and the uses when the token was issued. */
|
|
48
|
+
maxUses: number | null;
|
|
49
|
+
uses: number | null;
|
|
50
|
+
/** More devices or installations are active than the license's seats (overdraft). */
|
|
51
|
+
overage: boolean;
|
|
19
52
|
}
|
|
20
53
|
export declare function summarize(payload: LicensePayload, hostUsers?: number | null): LicenseSummary;
|
|
21
54
|
export declare const hasFeature: (payload: LicensePayload, code: string) => boolean;
|
package/dist/esm/evaluate.js
CHANGED
|
@@ -1,19 +1,71 @@
|
|
|
1
1
|
import { fingerprintMatches } from './fingerprint.js';
|
|
2
2
|
const CLOCK_TOLERANCE_MS = 10 * 60 * 1000;
|
|
3
3
|
const ISSUED_AT_TOLERANCE_MS = 24 * 60 * 60 * 1000;
|
|
4
|
+
/**
|
|
5
|
+
* Whitespace as .NET's char.IsWhiteSpace sees it (the server trims with it): U+0009-U+000D, U+0085 and the Unicode Zs, Zl and Zp
|
|
6
|
+
* characters. Not String.prototype.trim(): that also strips U+FEFF, which .NET keeps.
|
|
7
|
+
*/
|
|
8
|
+
const DOTNET_WHITESPACE = '\u0009-\u000D\u0020\u0085\u00A0\u1680\u2000-\u200A\u2028\u2029\u202F\u205F\u3000';
|
|
9
|
+
const EDGE_WHITESPACE = new RegExp(`^[${DOTNET_WHITESPACE}]+|[${DOTNET_WHITESPACE}]+$`, 'g');
|
|
10
|
+
/** Trims the .NET whitespace set from both ends, like the server's string.Trim(). */
|
|
11
|
+
function trimVersion(v) {
|
|
12
|
+
return v.replace(EDGE_WHITESPACE, '');
|
|
13
|
+
}
|
|
14
|
+
const INT32_MAX = 2147483647;
|
|
15
|
+
/** A part is a run of ASCII digits; the server parses it as a signed 32-bit integer, so one above 2147483647 counts as 0. */
|
|
16
|
+
function versionPart(p) {
|
|
17
|
+
const digits = p.replace(/^0+(?=[0-9])/, '');
|
|
18
|
+
if (digits.length > 10)
|
|
19
|
+
return 0;
|
|
20
|
+
const n = Number(digits);
|
|
21
|
+
return n > INT32_MAX ? 0 : n;
|
|
22
|
+
}
|
|
23
|
+
function versionParts(v) {
|
|
24
|
+
const core = /^[0-9.]*/.exec(trimVersion(v).replace(/^[vV]+/, ''))[0];
|
|
25
|
+
return core.split('.').filter((p) => p !== '').map(versionPart);
|
|
26
|
+
}
|
|
27
|
+
/** A version the server compares: after trimming whitespace, 1 to 50 characters and the first is an ASCII digit. */
|
|
28
|
+
export function isVersion(v) {
|
|
29
|
+
if (typeof v !== 'string')
|
|
30
|
+
return false;
|
|
31
|
+
const t = trimVersion(v); // the limit counts UTF-16 code units, like .NET's string.Length
|
|
32
|
+
return t.length > 0 && t.length <= 50 && /^[0-9]/.test(t);
|
|
33
|
+
}
|
|
34
|
+
/**
|
|
35
|
+
* "1.10.2" > "1.9"; a leading v/V is ignored; missing parts are 0; anything after the leading run of ASCII digits and dots
|
|
36
|
+
* (-beta, +build) is ignored; a part above 2147483647 counts as 0. Same as the server (test-vectors/versions.json).
|
|
37
|
+
*/
|
|
38
|
+
export function compareVersions(a, b) {
|
|
39
|
+
const x = versionParts(a);
|
|
40
|
+
const y = versionParts(b);
|
|
41
|
+
for (let i = 0; i < Math.max(x.length, y.length); i++) {
|
|
42
|
+
const d = (i < x.length ? x[i] : 0) - (i < y.length ? y[i] : 0);
|
|
43
|
+
if (d !== 0)
|
|
44
|
+
return d < 0 ? -1 : 1;
|
|
45
|
+
}
|
|
46
|
+
return 0;
|
|
47
|
+
}
|
|
48
|
+
/** Whether `appVersion` may run under a license limited to `maxAppVersion` (unknown or missing versions aren't refused). */
|
|
49
|
+
export function appVersionAllowed(maxAppVersion, appVersion) {
|
|
50
|
+
return !isVersion(maxAppVersion) || !isVersion(appVersion) || compareVersions(appVersion, maxAppVersion) <= 0;
|
|
51
|
+
}
|
|
4
52
|
/**
|
|
5
53
|
* 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.
|
|
54
|
+
* without one the license is Unverified until the next online check. `appVersion` (optional) is checked against the token's
|
|
55
|
+
* `maxAppVersion`; the token's `matching` is applied to the device. Grace (`graceUntil`) and expired-but-kept licenses
|
|
56
|
+
* (`expired: true`) need nothing extra: the server sets `expiresAt` to the end of grace, or leaves it out.
|
|
7
57
|
*/
|
|
8
|
-
export function evaluate(payload, product, machine, now, lastSeen) {
|
|
58
|
+
export function evaluate(payload, product, machine, now, lastSeen, appVersion) {
|
|
9
59
|
if (!payload)
|
|
10
60
|
return 'InvalidSignature';
|
|
11
61
|
if (payload.product.toLowerCase() !== product.toLowerCase())
|
|
12
62
|
return 'WrongProduct';
|
|
13
|
-
if (!fingerprintMatches(payload.fingerprint, machine))
|
|
63
|
+
if (!fingerprintMatches(payload.fingerprint, machine, payload.matching))
|
|
14
64
|
return 'WrongMachine';
|
|
15
65
|
if (payload.suspended)
|
|
16
66
|
return 'Suspended';
|
|
67
|
+
if (!appVersionAllowed(payload.maxAppVersion, appVersion))
|
|
68
|
+
return 'AppVersionNotAllowed';
|
|
17
69
|
if (!lastSeen)
|
|
18
70
|
return 'Unverified';
|
|
19
71
|
const t = now.getTime();
|
|
@@ -28,14 +80,24 @@ export function evaluate(payload, product, machine, now, lastSeen) {
|
|
|
28
80
|
export function summarize(payload, hostUsers) {
|
|
29
81
|
const max = typeof payload.maxHostUsers === 'number' ? payload.maxHostUsers : null;
|
|
30
82
|
return {
|
|
31
|
-
isTrial: payload.trial === true
|
|
83
|
+
isTrial: payload.trial === true,
|
|
32
84
|
isTest: payload.test === true,
|
|
33
85
|
expiresAt: payload.expiresAt ? new Date(payload.expiresAt) : null,
|
|
86
|
+
licenseExpiresAt: payload.licenseExpiresAt ? new Date(payload.licenseExpiresAt) : null,
|
|
34
87
|
entitlements: payload.entitlements ?? [],
|
|
35
88
|
metadata: payload.metadata ?? {},
|
|
36
89
|
maxHostUsers: max,
|
|
37
90
|
hostUserPolicy: max === null ? null : (payload.hostUserPolicy ?? 'block'),
|
|
38
91
|
hostUsersOverLimit: payload.hostUsersExceeded === true || (max !== null && typeof hostUsers === 'number' && hostUsers > max),
|
|
92
|
+
matching: typeof payload.matching === 'string' ? payload.matching : 'default',
|
|
93
|
+
maxAppVersion: typeof payload.maxAppVersion === 'string' ? payload.maxAppVersion : null,
|
|
94
|
+
expired: payload.expired === true,
|
|
95
|
+
inGrace: !!payload.graceUntil,
|
|
96
|
+
graceUntil: payload.graceUntil ? new Date(payload.graceUntil) : null,
|
|
97
|
+
borrowedUntil: payload.borrowedUntil ? new Date(payload.borrowedUntil) : null,
|
|
98
|
+
maxUses: typeof payload.maxUses === 'number' ? payload.maxUses : null,
|
|
99
|
+
uses: typeof payload.uses === 'number' ? payload.uses : null,
|
|
100
|
+
overage: payload.overage === true,
|
|
39
101
|
};
|
|
40
102
|
}
|
|
41
103
|
export const hasFeature = (payload, code) => (payload.entitlements ?? []).indexOf(code) >= 0;
|
|
@@ -13,6 +13,8 @@ export declare function installationFingerprint(vendor: string, product: string,
|
|
|
13
13
|
export declare const isHostInstallation: (f: Fingerprint) => boolean;
|
|
14
14
|
/**
|
|
15
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:
|
|
16
|
+
* Installations: same platform and exactly the same id, whatever the strategy. Computers: `strategy` is the token's `matching`
|
|
17
|
+
* field; default: board id + one other part, or two of three without a board id; 'strict': every part the registered device
|
|
18
|
+
* has; 'loose': any one part. When both sides name an operating system it must be the same.
|
|
17
19
|
*/
|
|
18
|
-
export declare function fingerprintMatches(registered: Fingerprint, presented: Fingerprint): boolean;
|
|
20
|
+
export declare function fingerprintMatches(registered: Fingerprint, presented: Fingerprint, strategy?: string | null): boolean;
|
package/dist/esm/fingerprint.js
CHANGED
|
@@ -25,13 +25,25 @@ const available = (v) => !!v && v !== UNAVAILABLE;
|
|
|
25
25
|
const same = (a, b) => available(a) && a === b;
|
|
26
26
|
/**
|
|
27
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:
|
|
28
|
+
* Installations: same platform and exactly the same id, whatever the strategy. Computers: `strategy` is the token's `matching`
|
|
29
|
+
* field; default: board id + one other part, or two of three without a board id; 'strict': every part the registered device
|
|
30
|
+
* has; 'loose': any one part. When both sides name an operating system it must be the same.
|
|
29
31
|
*/
|
|
30
|
-
export function fingerprintMatches(registered, presented) {
|
|
32
|
+
export function fingerprintMatches(registered, presented, strategy) {
|
|
31
33
|
if (isHostInstallation(registered) || isHostInstallation(presented))
|
|
32
34
|
return (registered.os ?? '').toLowerCase() === (presented.os ?? '').toLowerCase() && same(registered.machineId, presented.machineId);
|
|
33
35
|
if (registered.os && presented.os && registered.os.toLowerCase() !== presented.os.toLowerCase())
|
|
34
36
|
return false;
|
|
37
|
+
if (strategy === 'strict' || strategy === 'loose') {
|
|
38
|
+
const parts = [
|
|
39
|
+
[registered.machineId, presented.machineId], [registered.diskId, presented.diskId],
|
|
40
|
+
[registered.hostName, presented.hostName], [registered.boardId, presented.boardId],
|
|
41
|
+
];
|
|
42
|
+
const mine = parts.filter((p) => available(p[0]));
|
|
43
|
+
if (strategy === 'strict')
|
|
44
|
+
return mine.length > 0 && mine.every((p) => same(p[0], p[1]));
|
|
45
|
+
return mine.some((p) => same(p[0], p[1]));
|
|
46
|
+
}
|
|
35
47
|
let matches = 0;
|
|
36
48
|
if (same(registered.machineId, presented.machineId))
|
|
37
49
|
matches++;
|
package/dist/esm/index.d.ts
CHANGED
|
@@ -3,6 +3,6 @@ export { sha256 } from './sha256.js';
|
|
|
3
3
|
export { verifyP256, parsePublicKey } from './p256.js';
|
|
4
4
|
export { verifyToken, verifyTokenAsync, decodeTokenUnverified, type Fingerprint, type LicensePayload } from './token.js';
|
|
5
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';
|
|
6
|
+
export { evaluate, summarize, hasFeature, compareVersions, isVersion, appVersionAllowed, type LicenseStatus, type LicenseSummary } from './evaluate.js';
|
|
7
|
+
export { activateRequest, refreshRequest, deactivateRequest, trialRequest, borrowRequest, consumeRequest, readResponse, readUseResponse, refreshDueAt, REVOKING_CODES, INSTALLATION_HEADER, type HttpRequestDescription, type ActivateOptions, type RefreshOptions, type TrialOptions, type BorrowOptions, type ConsumeOptions, type ClientResponse, type UseResponse, type Target, type ClientTime, } from './protocol.js';
|
|
8
|
+
export { createLicenseClient, type ClientOptions, type LicenseStorage, type Transport, type LicenseState, type ActionResult, type ConsumeResult, type LicenseClient, } from './client.js';
|
package/dist/esm/index.js
CHANGED
|
@@ -5,6 +5,6 @@ export { sha256 } from './sha256.js';
|
|
|
5
5
|
export { verifyP256, parsePublicKey } from './p256.js';
|
|
6
6
|
export { verifyToken, verifyTokenAsync, decodeTokenUnverified } from './token.js';
|
|
7
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';
|
|
8
|
+
export { evaluate, summarize, hasFeature, compareVersions, isVersion, appVersionAllowed } from './evaluate.js';
|
|
9
|
+
export { activateRequest, refreshRequest, deactivateRequest, trialRequest, borrowRequest, consumeRequest, readResponse, readUseResponse, refreshDueAt, REVOKING_CODES, INSTALLATION_HEADER, } from './protocol.js';
|
|
10
|
+
export { createLicenseClient, } from './client.js';
|
package/dist/esm/protocol.d.ts
CHANGED
|
@@ -14,6 +14,11 @@ export interface Target {
|
|
|
14
14
|
}
|
|
15
15
|
/** Header that makes the server rate-limit per installation instead of per IP (apps inside a host share its IPs). */
|
|
16
16
|
export declare const INSTALLATION_HEADER = "LicenseRail-Installation";
|
|
17
|
+
/**
|
|
18
|
+
* The device clock sent as `clientTime` (UTC, ISO 8601); the server refuses requests whose clock is too far from its own.
|
|
19
|
+
* Undefined means now; null leaves it out, and so does an invalid Date or a string that isn't a date.
|
|
20
|
+
*/
|
|
21
|
+
export type ClientTime = Date | string | null | undefined;
|
|
17
22
|
export interface ActivateOptions extends Target {
|
|
18
23
|
/**
|
|
19
24
|
* The license key. Omit it when the host adds `Authorization: Bearer <key>` itself (YouTrack: the key is a secret setting
|
|
@@ -28,6 +33,8 @@ export interface ActivateOptions extends Target {
|
|
|
28
33
|
hostUsers?: number;
|
|
29
34
|
/** Floating license: check out a lease instead of activating. */
|
|
30
35
|
floating?: boolean;
|
|
36
|
+
/** Default: now. */
|
|
37
|
+
clientTime?: ClientTime;
|
|
31
38
|
}
|
|
32
39
|
export declare function activateRequest(o: ActivateOptions): HttpRequestDescription;
|
|
33
40
|
export interface RefreshOptions extends Target {
|
|
@@ -36,18 +43,53 @@ export interface RefreshOptions extends Target {
|
|
|
36
43
|
hostUsers?: number;
|
|
37
44
|
anomalies?: string[];
|
|
38
45
|
floating?: boolean;
|
|
46
|
+
/** Default: now. */
|
|
47
|
+
clientTime?: ClientTime;
|
|
39
48
|
}
|
|
40
49
|
export declare function refreshRequest(o: RefreshOptions): HttpRequestDescription;
|
|
41
50
|
export declare function deactivateRequest(o: Target & {
|
|
42
51
|
token: string;
|
|
43
52
|
floating?: boolean;
|
|
44
53
|
}): HttpRequestDescription;
|
|
54
|
+
export interface BorrowOptions extends Target {
|
|
55
|
+
/** The checked-out floating token. */
|
|
56
|
+
token: string;
|
|
57
|
+
/** Whole hours to keep the seat offline (up to the license's maxBorrowHours). */
|
|
58
|
+
hours: number;
|
|
59
|
+
appVersion?: string;
|
|
60
|
+
/** Default: now. */
|
|
61
|
+
clientTime?: ClientTime;
|
|
62
|
+
}
|
|
63
|
+
/**
|
|
64
|
+
* Floating: keeps the checked-out seat for offline use for `hours`. The answer is a token (readResponse). Return the seat early
|
|
65
|
+
* with deactivateRequest({ ..., floating: true }).
|
|
66
|
+
*/
|
|
67
|
+
export declare function borrowRequest(o: BorrowOptions): HttpRequestDescription;
|
|
68
|
+
export interface ConsumeOptions extends Target {
|
|
69
|
+
token: string;
|
|
70
|
+
/** Uses to consume (a whole number, at least 1). */
|
|
71
|
+
count: number;
|
|
72
|
+
}
|
|
73
|
+
/** Licenses with a use limit: consumes `count` uses. Read the answer with readUseResponse. */
|
|
74
|
+
export declare function consumeRequest(o: ConsumeOptions): HttpRequestDescription;
|
|
75
|
+
/**
|
|
76
|
+
* The host installation a trial is for. The server asks it for its id before a trial starts (YouTrack: the uuid that
|
|
77
|
+
* /api/config returns at baseUrls), so it must be reachable from the internet; otherwise the vendor gives a trial key.
|
|
78
|
+
*/
|
|
79
|
+
export interface TrialHost {
|
|
80
|
+
instanceId: string;
|
|
81
|
+
baseUrls?: string[];
|
|
82
|
+
}
|
|
45
83
|
export interface TrialOptions extends Target {
|
|
46
84
|
/** The environment's signing key id (public; shown with the public key in the dashboard). */
|
|
47
85
|
keyId: string;
|
|
86
|
+
/** Required for apps inside a host (fingerprint made with installationFingerprint from the same instance id). */
|
|
87
|
+
host?: TrialHost;
|
|
48
88
|
machineName?: string;
|
|
49
89
|
appVersion?: string;
|
|
50
90
|
hostUsers?: number;
|
|
91
|
+
/** Default: now. */
|
|
92
|
+
clientTime?: ClientTime;
|
|
51
93
|
}
|
|
52
94
|
export declare function trialRequest(o: TrialOptions): HttpRequestDescription;
|
|
53
95
|
/** Codes on which the local license must be removed; on all others (network errors, 402, 429, 5xx) the app keeps it. */
|
|
@@ -67,5 +109,18 @@ export type ClientResponse = {
|
|
|
67
109
|
};
|
|
68
110
|
/** Reads a client API response. `status` 0 means the request failed before any response (network error, timeout). */
|
|
69
111
|
export declare function readResponse(status: number, bodyText: string | null | undefined): ClientResponse;
|
|
112
|
+
export type UseResponse = {
|
|
113
|
+
ok: true;
|
|
114
|
+
uses: number | null;
|
|
115
|
+
maxUses: number | null;
|
|
116
|
+
} | {
|
|
117
|
+
ok: false;
|
|
118
|
+
code: string;
|
|
119
|
+
message: string;
|
|
120
|
+
revokesLocalLicense: boolean;
|
|
121
|
+
retryLater: boolean;
|
|
122
|
+
};
|
|
123
|
+
/** Reads the answer to consumeRequest: the license's use counter after the use, or an error (use_limit_reached when used up). */
|
|
124
|
+
export declare function readUseResponse(status: number, bodyText: string | null | undefined): UseResponse;
|
|
70
125
|
/** When the token wants to be refreshed (null for trials, which are never refreshed). */
|
|
71
126
|
export declare function refreshDueAt(payload: LicensePayload): Date | null;
|
package/dist/esm/protocol.js
CHANGED
|
@@ -9,6 +9,14 @@ function headers(fingerprint) {
|
|
|
9
9
|
h[INSTALLATION_HEADER] = `${fingerprint.os}:${fingerprint.machineId}`.slice(0, 128);
|
|
10
10
|
return h;
|
|
11
11
|
}
|
|
12
|
+
function clientTime(t) {
|
|
13
|
+
if (t === null)
|
|
14
|
+
return undefined;
|
|
15
|
+
if (typeof t === 'string')
|
|
16
|
+
return isNaN(Date.parse(t)) ? undefined : t;
|
|
17
|
+
const d = t instanceof Date ? t : t === undefined ? new Date() : null;
|
|
18
|
+
return d && !isNaN(d.getTime()) ? d.toISOString() : undefined;
|
|
19
|
+
}
|
|
12
20
|
function clean(o) {
|
|
13
21
|
const out = {};
|
|
14
22
|
for (const k of Object.keys(o))
|
|
@@ -27,7 +35,7 @@ export function activateRequest(o) {
|
|
|
27
35
|
headers: h,
|
|
28
36
|
body: JSON.stringify(clean({
|
|
29
37
|
product: o.product, fingerprint: o.fingerprint, licenseKey: inHeader ? undefined : o.licenseKey,
|
|
30
|
-
machineName: o.machineName, appVersion: o.appVersion, hostUsers: o.hostUsers,
|
|
38
|
+
machineName: o.machineName, appVersion: o.appVersion, hostUsers: o.hostUsers, clientTime: clientTime(o.clientTime),
|
|
31
39
|
})),
|
|
32
40
|
};
|
|
33
41
|
}
|
|
@@ -37,7 +45,7 @@ export function refreshRequest(o) {
|
|
|
37
45
|
url: url(o.apiUrl, o.floating ? '/floating/heartbeat' : '/refresh'),
|
|
38
46
|
headers: headers(o.fingerprint),
|
|
39
47
|
// appVersion is a required field of the refresh request (null allowed).
|
|
40
|
-
body: JSON.stringify({ ...clean({ token: o.token, fingerprint: o.fingerprint, anomalies: o.anomalies, hostUsers: o.hostUsers }), appVersion: o.appVersion ?? null }),
|
|
48
|
+
body: JSON.stringify({ ...clean({ token: o.token, fingerprint: o.fingerprint, anomalies: o.anomalies, hostUsers: o.hostUsers, clientTime: clientTime(o.clientTime) }), appVersion: o.appVersion ?? null }),
|
|
41
49
|
};
|
|
42
50
|
}
|
|
43
51
|
export function deactivateRequest(o) {
|
|
@@ -48,27 +56,53 @@ export function deactivateRequest(o) {
|
|
|
48
56
|
body: JSON.stringify({ token: o.token, fingerprint: o.fingerprint }),
|
|
49
57
|
};
|
|
50
58
|
}
|
|
59
|
+
/**
|
|
60
|
+
* Floating: keeps the checked-out seat for offline use for `hours`. The answer is a token (readResponse). Return the seat early
|
|
61
|
+
* with deactivateRequest({ ..., floating: true }).
|
|
62
|
+
*/
|
|
63
|
+
export function borrowRequest(o) {
|
|
64
|
+
return {
|
|
65
|
+
method: 'POST',
|
|
66
|
+
url: url(o.apiUrl, '/floating/borrow'),
|
|
67
|
+
headers: headers(o.fingerprint),
|
|
68
|
+
body: JSON.stringify({ ...clean({ token: o.token, fingerprint: o.fingerprint, hours: o.hours, clientTime: clientTime(o.clientTime) }), appVersion: o.appVersion ?? null }),
|
|
69
|
+
};
|
|
70
|
+
}
|
|
71
|
+
/** Licenses with a use limit: consumes `count` uses. Read the answer with readUseResponse. */
|
|
72
|
+
export function consumeRequest(o) {
|
|
73
|
+
return {
|
|
74
|
+
method: 'POST',
|
|
75
|
+
url: url(o.apiUrl, '/use'),
|
|
76
|
+
headers: headers(o.fingerprint),
|
|
77
|
+
body: JSON.stringify({ token: o.token, fingerprint: o.fingerprint, count: o.count }),
|
|
78
|
+
};
|
|
79
|
+
}
|
|
51
80
|
export function trialRequest(o) {
|
|
52
81
|
return {
|
|
53
82
|
method: 'POST',
|
|
54
83
|
url: url(o.apiUrl, '/trial'),
|
|
55
84
|
headers: headers(o.fingerprint),
|
|
56
|
-
body: JSON.stringify(clean({
|
|
85
|
+
body: JSON.stringify(clean({
|
|
86
|
+
keyId: o.keyId, product: o.product, fingerprint: o.fingerprint, machineName: o.machineName, appVersion: o.appVersion, hostUsers: o.hostUsers,
|
|
87
|
+
host: o.host, clientTime: clientTime(o.clientTime),
|
|
88
|
+
})),
|
|
57
89
|
};
|
|
58
90
|
}
|
|
59
91
|
/** Codes on which the local license must be removed; on all others (network errors, 402, 429, 5xx) the app keeps it. */
|
|
60
92
|
export const REVOKING_CODES = [
|
|
61
93
|
'license_not_found', 'license_suspended', 'license_expired', 'activation_revoked', 'wrong_machine', 'invalid_token', 'license_revoked',
|
|
62
94
|
];
|
|
63
|
-
|
|
64
|
-
export function readResponse(status, bodyText) {
|
|
65
|
-
let body = null;
|
|
95
|
+
function parseBody(bodyText) {
|
|
66
96
|
try {
|
|
67
|
-
|
|
97
|
+
return bodyText ? JSON.parse(bodyText) : null;
|
|
68
98
|
}
|
|
69
99
|
catch {
|
|
70
|
-
|
|
100
|
+
return null;
|
|
71
101
|
}
|
|
102
|
+
}
|
|
103
|
+
/** Reads a client API response. `status` 0 means the request failed before any response (network error, timeout). */
|
|
104
|
+
export function readResponse(status, bodyText) {
|
|
105
|
+
const body = parseBody(bodyText);
|
|
72
106
|
if (status >= 200 && status < 300) {
|
|
73
107
|
if (status === 204)
|
|
74
108
|
return { ok: true, token: null };
|
|
@@ -76,6 +110,16 @@ export function readResponse(status, bodyText) {
|
|
|
76
110
|
if (body && typeof body.token === 'string')
|
|
77
111
|
return { ok: true, token: body.token };
|
|
78
112
|
}
|
|
113
|
+
return errorResponse(status, body);
|
|
114
|
+
}
|
|
115
|
+
/** Reads the answer to consumeRequest: the license's use counter after the use, or an error (use_limit_reached when used up). */
|
|
116
|
+
export function readUseResponse(status, bodyText) {
|
|
117
|
+
const body = parseBody(bodyText);
|
|
118
|
+
if (status >= 200 && status < 300 && body && (typeof body.uses === 'number' || typeof body.maxUses === 'number'))
|
|
119
|
+
return { ok: true, uses: typeof body.uses === 'number' ? body.uses : null, maxUses: typeof body.maxUses === 'number' ? body.maxUses : null };
|
|
120
|
+
return errorResponse(status, body);
|
|
121
|
+
}
|
|
122
|
+
function errorResponse(status, body) {
|
|
79
123
|
const code = body && typeof body.code === 'string' ? body.code : status === 0 ? 'network_error' : `http_${status}`;
|
|
80
124
|
const message = body && typeof body.message === 'string' ? body.message : status === 0 ? 'The license server could not be reached.' : 'Unexpected response from the license server.';
|
|
81
125
|
return {
|
package/dist/esm/token.d.ts
CHANGED
|
@@ -26,6 +26,8 @@ export interface LicensePayload {
|
|
|
26
26
|
metadata?: Record<string, unknown>;
|
|
27
27
|
floating?: boolean;
|
|
28
28
|
leaseExpiresAt?: string;
|
|
29
|
+
/** The license's own expiry, for display (absent/null = perpetual); never enforced (the offline check uses `expiresAt`). */
|
|
30
|
+
licenseExpiresAt?: string | null;
|
|
29
31
|
/** A keyless trial: valid until `expiresAt`, never refreshed. */
|
|
30
32
|
trial?: boolean;
|
|
31
33
|
/** Apps inside a host: the most users the host may have and what happens above it. */
|
|
@@ -33,6 +35,21 @@ export interface LicensePayload {
|
|
|
33
35
|
hostUserPolicy?: 'block' | 'warn' | 'report' | string;
|
|
34
36
|
/** The server saw more host users than allowed and the policy is "warn": show a warning. */
|
|
35
37
|
hostUsersExceeded?: boolean;
|
|
38
|
+
/** Device matching applied offline: 'strict' or 'loose'; absent = default. Installations always match exactly. */
|
|
39
|
+
matching?: string;
|
|
40
|
+
/** The newest app version this license may run; absent = any. */
|
|
41
|
+
maxAppVersion?: string;
|
|
42
|
+
/** The license has expired but its strategy keeps it working (maintain or allow); expiresAt is then absent. */
|
|
43
|
+
expired?: boolean;
|
|
44
|
+
/** The license expired and works until this time (grace); expiresAt is the same moment. */
|
|
45
|
+
graceUntil?: string;
|
|
46
|
+
/** Floating: the seat is borrowed for offline use until this time. */
|
|
47
|
+
borrowedUntil?: string;
|
|
48
|
+
/** Use counting: the license's limit, and the uses when the token was issued. */
|
|
49
|
+
maxUses?: number;
|
|
50
|
+
uses?: number;
|
|
51
|
+
/** More devices are active than the license's seats (overdraft). */
|
|
52
|
+
overage?: boolean;
|
|
36
53
|
[field: string]: unknown;
|
|
37
54
|
}
|
|
38
55
|
/**
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@codeo-engineering/licenserail-embedded",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.6",
|
|
4
4
|
"description": "LicenseRail client core for apps inside a host platform (YouTrack apps, browser extensions, web apps): offline ES256 verification without WebCrypto, installation identity, activation, trials. No dependencies.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"publishConfig": { "access": "public" },
|
|
@@ -22,7 +22,7 @@
|
|
|
22
22
|
"sideEffects": false,
|
|
23
23
|
"scripts": {
|
|
24
24
|
"build": "tsc -p tsconfig.json && tsc -p tsconfig.cjs.json && node scripts/cjs-package.mjs",
|
|
25
|
-
"test": "npm run build && node --test
|
|
25
|
+
"test": "npm run build && node --test"
|
|
26
26
|
},
|
|
27
27
|
"devDependencies": {
|
|
28
28
|
"@types/node": "^20.11.0",
|