@codeo-engineering/licenserail 0.0.0-stage → 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/LICENSE +21 -0
- package/README.md +68 -2
- package/dist/client.d.ts +192 -0
- package/dist/client.js +451 -0
- package/dist/core.d.ts +147 -0
- package/dist/core.js +225 -0
- package/dist/fingerprint.d.ts +3 -0
- package/dist/fingerprint.js +73 -0
- package/dist/index.d.ts +5 -0
- package/dist/index.js +5 -0
- package/dist/management.d.ts +73 -0
- package/dist/management.js +66 -0
- package/dist/vm.d.ts +53 -0
- package/dist/vm.js +184 -0
- package/package.json +22 -4
package/dist/client.js
ADDED
|
@@ -0,0 +1,451 @@
|
|
|
1
|
+
import { mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
|
|
2
|
+
import { homedir, hostname, platform } from 'node:os';
|
|
3
|
+
import { join } from 'node:path';
|
|
4
|
+
import { decodeRunHistory, encodeRunHistory, ERROR_CODES, evaluate, fingerprintMatches, importPublicKey, REVOKING_CODES, verifyToken, } from './core.js';
|
|
5
|
+
import { collectFingerprint } from './fingerprint.js';
|
|
6
|
+
import { detectVirtualMachine, isVirtualMachine as detectVirtualMachineSync } from './vm.js';
|
|
7
|
+
const notIdentified = {
|
|
8
|
+
success: false, errorCode: 'device_not_identified', message: "This device can't be identified, so a license can't be activated on it.",
|
|
9
|
+
};
|
|
10
|
+
const offline = (message = 'Could not connect to the license server.') => ({ success: false, errorCode: ERROR_CODES.network, message });
|
|
11
|
+
/** Read-only view of the current license. */
|
|
12
|
+
export class License {
|
|
13
|
+
payload;
|
|
14
|
+
constructor(payload) {
|
|
15
|
+
this.payload = payload;
|
|
16
|
+
}
|
|
17
|
+
get key() { return this.payload.licenseKey; }
|
|
18
|
+
get customer() { return this.payload.customer; }
|
|
19
|
+
get kind() { return this.payload.kind; }
|
|
20
|
+
/**
|
|
21
|
+
* What the offline check enforces: the end of grace when the license has grace days; null when perpetual or when the expiration
|
|
22
|
+
* strategy keeps the license working after expiry. Show licenseExpiresAt to the user instead.
|
|
23
|
+
*/
|
|
24
|
+
get expiresAt() { return this.payload.expiresAt ? new Date(this.payload.expiresAt) : null; }
|
|
25
|
+
/** The license's own expiry, for showing to the user (null = perpetual); never enforced. */
|
|
26
|
+
get licenseExpiresAt() { return this.payload.licenseExpiresAt ? new Date(this.payload.licenseExpiresAt) : null; }
|
|
27
|
+
get offlineUntil() { return new Date(this.payload.offlineUntil); }
|
|
28
|
+
get isTest() { return this.payload.test === true; }
|
|
29
|
+
get isFloating() { return this.payload.floating === true; }
|
|
30
|
+
get features() { return this.payload.entitlements ?? []; }
|
|
31
|
+
get metadata() { return this.payload.metadata ?? {}; }
|
|
32
|
+
hasFeature(code) { return this.features.includes(code); }
|
|
33
|
+
/**
|
|
34
|
+
* A keyless trial (startTrial()): the token says `trial: true`. A keyed license of kind "trial" is an ordinary license (see
|
|
35
|
+
* `kind`): it refreshes and deactivates on the server.
|
|
36
|
+
*/
|
|
37
|
+
get isTrial() { return this.payload.trial === true; }
|
|
38
|
+
/** Device matching applied offline: 'default', 'strict' or 'loose'. */
|
|
39
|
+
get matching() { return this.payload.matching ?? 'default'; }
|
|
40
|
+
/** The newest app version this license may run; null = any. */
|
|
41
|
+
get maxAppVersion() { return this.payload.maxAppVersion ?? null; }
|
|
42
|
+
/** The license has expired but keeps working (expiration strategy maintain or allow); show a renewal notice. */
|
|
43
|
+
get isExpired() { return this.payload.expired === true; }
|
|
44
|
+
/** The license expired and works until graceUntil (grace period). */
|
|
45
|
+
get isInGrace() { return !!this.payload.graceUntil; }
|
|
46
|
+
get graceUntil() { return this.payload.graceUntil ? new Date(this.payload.graceUntil) : null; }
|
|
47
|
+
/** Floating: the seat is borrowed for offline use until this time. */
|
|
48
|
+
get borrowedUntil() { return this.payload.borrowedUntil ? new Date(this.payload.borrowedUntil) : null; }
|
|
49
|
+
get isBorrowed() { return !!this.payload.borrowedUntil; }
|
|
50
|
+
/** Use counting: the license's limit, and the uses when the token was issued. */
|
|
51
|
+
get maxUses() { return this.payload.maxUses ?? null; }
|
|
52
|
+
get uses() { return this.payload.uses ?? null; }
|
|
53
|
+
/** More devices are active than the license's seats (overdraft). */
|
|
54
|
+
get isOverage() { return this.payload.overage === true; }
|
|
55
|
+
}
|
|
56
|
+
const messages = {
|
|
57
|
+
Valid: 'The license is valid.',
|
|
58
|
+
Missing: 'No license is activated on this device.',
|
|
59
|
+
InvalidSignature: 'The license file is invalid. Activate it again.',
|
|
60
|
+
WrongProduct: 'The license is for another product.',
|
|
61
|
+
WrongMachine: 'The license belongs to another device.',
|
|
62
|
+
Expired: 'The license has expired.',
|
|
63
|
+
OfflineTooLong: 'Connect to the internet to verify the license.',
|
|
64
|
+
ClockTampered: "The device's clock looks wrong. Correct it and connect to the internet.",
|
|
65
|
+
Unverified: 'Connect to the internet to verify the license.',
|
|
66
|
+
Suspended: 'The license has been suspended.',
|
|
67
|
+
AppVersionNotAllowed: 'This version of the app is newer than the license covers. Contact your software vendor to upgrade.',
|
|
68
|
+
};
|
|
69
|
+
/**
|
|
70
|
+
* The licensing client for a vendor's app: offline verification on every start, online refresh when due, activation,
|
|
71
|
+
* deactivation, keyless trials, floating leases (with borrowing) and use counting. Never put an API key in client code; this
|
|
72
|
+
* class needs only the public key.
|
|
73
|
+
*/
|
|
74
|
+
export class LicenseClient {
|
|
75
|
+
options;
|
|
76
|
+
key;
|
|
77
|
+
dir;
|
|
78
|
+
fp = null;
|
|
79
|
+
heartbeat = null;
|
|
80
|
+
warnedTest = false;
|
|
81
|
+
/** The last message from the server (e.g. why a license was removed). */
|
|
82
|
+
lastServerMessage = null;
|
|
83
|
+
constructor(options) {
|
|
84
|
+
if (!options.serverUrl || !options.vendor || !options.product || !options.publicKeyPem)
|
|
85
|
+
throw new Error('serverUrl, vendor, product and publicKeyPem are required.');
|
|
86
|
+
this.options = { timeoutMs: 10_000, ...options, serverUrl: options.serverUrl.replace(/\/+$/, '') };
|
|
87
|
+
this.key = importPublicKey(options.publicKeyPem);
|
|
88
|
+
this.dir = options.storageDir ?? defaultStorageDir(options.product);
|
|
89
|
+
}
|
|
90
|
+
now() { return this.options.now?.() ?? new Date(); }
|
|
91
|
+
/** The device clock (UTC, ISO 8601) sent as `clientTime`; the server refuses requests whose clock is too far off. */
|
|
92
|
+
clientTime() { return this.now().toISOString(); }
|
|
93
|
+
fingerprint() { return (this.fp ??= this.options.fingerprint?.() ?? collectFingerprint(this.options.vendor, this.options.product)); }
|
|
94
|
+
/** Whether a license for this device would match it again; if not, activating would only use up a seat. */
|
|
95
|
+
identified() { return fingerprintMatches(this.fingerprint(), this.fingerprint()); }
|
|
96
|
+
get tokenPath() { return join(this.dir, 'license.lic'); }
|
|
97
|
+
get historyPath() { return join(this.dir, 'license.seen'); }
|
|
98
|
+
/**
|
|
99
|
+
* What requests carry as `virtualMachine`: null (not sent) when detection is off (and no answer is set) or couldn't tell. The
|
|
100
|
+
* probe runs once per process without blocking (a child process with a 5-second limit); requests await the cached result.
|
|
101
|
+
*/
|
|
102
|
+
async virtualMachineField() {
|
|
103
|
+
const o = this.options.virtualMachine;
|
|
104
|
+
if (typeof o === 'boolean')
|
|
105
|
+
return o;
|
|
106
|
+
try {
|
|
107
|
+
if (typeof o === 'function')
|
|
108
|
+
return (await o()) ?? null;
|
|
109
|
+
return this.options.detectVirtualMachine === false ? null : await detectVirtualMachine();
|
|
110
|
+
}
|
|
111
|
+
catch {
|
|
112
|
+
return null;
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
/**
|
|
116
|
+
* Starts virtual machine detection in the background and returns at once, so the first activate, checkout or trial doesn't
|
|
117
|
+
* wait for it. Optional: without it the probe starts at the first activate, checkout or trial (which then waits for it, at
|
|
118
|
+
* most the 5-second probe limit). It never runs at app start or in the constructor. Runs once per process; does nothing when
|
|
119
|
+
* detection is off or the `virtualMachine` option gives the answer.
|
|
120
|
+
*/
|
|
121
|
+
warmUpVirtualMachineDetection() {
|
|
122
|
+
if (this.options.virtualMachine !== undefined || this.options.detectVirtualMachine === false)
|
|
123
|
+
return;
|
|
124
|
+
void detectVirtualMachine().catch(() => null);
|
|
125
|
+
}
|
|
126
|
+
/**
|
|
127
|
+
* Whether the app runs in a virtual machine or container (best effort): the `virtualMachine` option if set, otherwise
|
|
128
|
+
* detected (false when detection is off or failed). Sent with activations, floating checkouts and trials.
|
|
129
|
+
*/
|
|
130
|
+
async isVirtualMachineAsync() { return (await this.virtualMachineField()) === true; }
|
|
131
|
+
/**
|
|
132
|
+
* Synchronous form of isVirtualMachineAsync(). Never starts a second probe: returns the cached result once detection has
|
|
133
|
+
* finished, and false while the asynchronous probe is still running. Blocks only before the first detection has started (up
|
|
134
|
+
* to 5 seconds, once per process). A custom detector that returns a promise counts as false here.
|
|
135
|
+
* @deprecated Use isVirtualMachineAsync().
|
|
136
|
+
*/
|
|
137
|
+
isVirtualMachine() {
|
|
138
|
+
const o = this.options.virtualMachine;
|
|
139
|
+
if (typeof o === 'boolean')
|
|
140
|
+
return o;
|
|
141
|
+
if (typeof o === 'function') {
|
|
142
|
+
const v = o();
|
|
143
|
+
return v === true;
|
|
144
|
+
}
|
|
145
|
+
return this.options.detectVirtualMachine === false ? false : detectVirtualMachineSync();
|
|
146
|
+
}
|
|
147
|
+
/** The current license after the last check, or null. */
|
|
148
|
+
get license() {
|
|
149
|
+
const p = this.readPayload();
|
|
150
|
+
return p ? new License(p) : null;
|
|
151
|
+
}
|
|
152
|
+
/** Offline evaluation only (no network). */
|
|
153
|
+
evaluateLocal() {
|
|
154
|
+
const token = this.read(this.tokenPath);
|
|
155
|
+
if (!token)
|
|
156
|
+
return { status: 'Missing', valid: false, license: null };
|
|
157
|
+
const payload = verifyToken(token, this.key);
|
|
158
|
+
const lastSeen = decodeRunHistory(this.read(this.historyPath), this.options.vendor, this.options.product, this.fingerprint());
|
|
159
|
+
const now = this.now();
|
|
160
|
+
const status = evaluate(payload, this.options.product, this.fingerprint(), now, lastSeen, this.options.appVersion);
|
|
161
|
+
if ((status === 'Valid' || status === 'Expired' || status === 'OfflineTooLong') && (!lastSeen || now > lastSeen))
|
|
162
|
+
this.write(this.historyPath, encodeRunHistory(now, this.options.vendor, this.options.product, this.fingerprint()));
|
|
163
|
+
if (payload?.test && !this.warnedTest) {
|
|
164
|
+
this.warnedTest = true;
|
|
165
|
+
console.warn('[licenserail] Test license: not for production use.');
|
|
166
|
+
}
|
|
167
|
+
return { status, valid: status === 'Valid', license: payload ? new License(payload) : null };
|
|
168
|
+
}
|
|
169
|
+
/** Call on startup: evaluates offline and refreshes online when due or when only the server can clear the state. */
|
|
170
|
+
async check() {
|
|
171
|
+
let result = this.evaluateLocal();
|
|
172
|
+
if (result.license?.payload.trial === true)
|
|
173
|
+
return result; // trials are never refreshed; startTrial() asks again
|
|
174
|
+
const due = result.valid && (this.options.refreshOnStartup || this.now() >= new Date(result.license.payload.refreshAfter));
|
|
175
|
+
if (due || ['Expired', 'Suspended', 'OfflineTooLong', 'ClockTampered', 'Unverified', 'AppVersionNotAllowed'].includes(result.status)) {
|
|
176
|
+
try {
|
|
177
|
+
await this.refresh(result.status === 'ClockTampered' ? ['clock_rollback'] : result.status === 'Unverified' ? ['history_missing'] : undefined);
|
|
178
|
+
}
|
|
179
|
+
catch {
|
|
180
|
+
// offline: the local result stands until offlineUntil
|
|
181
|
+
}
|
|
182
|
+
result = this.evaluateLocal();
|
|
183
|
+
}
|
|
184
|
+
return result;
|
|
185
|
+
}
|
|
186
|
+
async activationBody(licenseKey, machineName) {
|
|
187
|
+
const virtualMachine = await this.virtualMachineField();
|
|
188
|
+
return {
|
|
189
|
+
licenseKey: licenseKey.trim(), product: this.options.product, fingerprint: this.fingerprint(),
|
|
190
|
+
machineName: machineName ?? this.options.machineName ?? hostname(), appVersion: this.options.appVersion ?? null,
|
|
191
|
+
virtualMachine, clientTime: this.clientTime(),
|
|
192
|
+
};
|
|
193
|
+
}
|
|
194
|
+
/** Activates `licenseKey` on this device (or checks out a floating lease if the license is floating). */
|
|
195
|
+
async activate(licenseKey, machineName) {
|
|
196
|
+
if (!licenseKey?.trim())
|
|
197
|
+
return { success: false, errorCode: 'bad_request', message: 'Enter the license key.' };
|
|
198
|
+
if (!this.identified())
|
|
199
|
+
return notIdentified;
|
|
200
|
+
const body = await this.activationBody(licenseKey, machineName);
|
|
201
|
+
let r = await this.post('/api/client/v2/activate', body).catch(() => null);
|
|
202
|
+
if (r && !r.ok && r.error?.code === 'bad_request' && /floating/i.test(r.error.message))
|
|
203
|
+
r = await this.post('/api/client/v2/floating/checkout', body).catch(() => null);
|
|
204
|
+
if (!r)
|
|
205
|
+
return offline();
|
|
206
|
+
if (!r.ok)
|
|
207
|
+
return { success: false, errorCode: r.error?.code, message: r.error?.message ?? `Server error (${r.status}).` };
|
|
208
|
+
if (!this.saveIfValid(r.token))
|
|
209
|
+
return { success: false, errorCode: 'invalid_token', message: 'The server returned an invalid license.' };
|
|
210
|
+
const result = this.evaluateLocal();
|
|
211
|
+
if (result.license?.isFloating)
|
|
212
|
+
this.startHeartbeat();
|
|
213
|
+
return result.valid ? { success: true, message: 'The license has been activated.' } : { success: false, errorCode: result.status, message: messages[result.status] };
|
|
214
|
+
}
|
|
215
|
+
/** Checks out a floating seat and keeps it alive with heartbeats until release(). */
|
|
216
|
+
async checkout(licenseKey) {
|
|
217
|
+
if (!this.identified())
|
|
218
|
+
return notIdentified;
|
|
219
|
+
const r = await this.post('/api/client/v2/floating/checkout', await this.activationBody(licenseKey)).catch(() => null);
|
|
220
|
+
if (!r)
|
|
221
|
+
return offline();
|
|
222
|
+
if (!r.ok)
|
|
223
|
+
return { success: false, errorCode: r.error?.code, message: r.error?.message ?? `Server error (${r.status}).` };
|
|
224
|
+
this.saveIfValid(r.token);
|
|
225
|
+
this.startHeartbeat();
|
|
226
|
+
return { success: true, message: 'Floating license checked out.' };
|
|
227
|
+
}
|
|
228
|
+
/**
|
|
229
|
+
* Starts this device's keyless trial, or gets the running one back (the server keeps one trial per device and product). Needs
|
|
230
|
+
* the `keyId` option. The trial token is stored and checked like a license (kind "trial"); it is never refreshed.
|
|
231
|
+
*/
|
|
232
|
+
async startTrial() {
|
|
233
|
+
if (!this.options.keyId)
|
|
234
|
+
return { success: false, errorCode: 'bad_request', message: "Set keyId (the environment's signing key id) to start trials." };
|
|
235
|
+
if (!this.identified())
|
|
236
|
+
return { ...notIdentified, message: "This device can't be identified, so a trial can't start on it." };
|
|
237
|
+
const virtualMachine = await this.virtualMachineField();
|
|
238
|
+
const r = await this.post('/api/client/v2/trial', {
|
|
239
|
+
keyId: this.options.keyId, product: this.options.product, fingerprint: this.fingerprint(),
|
|
240
|
+
machineName: this.options.machineName ?? hostname(), appVersion: this.options.appVersion ?? null,
|
|
241
|
+
virtualMachine, clientTime: this.clientTime(),
|
|
242
|
+
}).catch(() => null);
|
|
243
|
+
if (!r)
|
|
244
|
+
return offline();
|
|
245
|
+
if (!r.ok)
|
|
246
|
+
return { success: false, errorCode: r.error?.code, message: r.error?.message ?? `Server error (${r.status}).` };
|
|
247
|
+
if (!this.saveIfValid(r.token))
|
|
248
|
+
return { success: false, errorCode: 'invalid_token', message: 'The server returned an invalid license.' };
|
|
249
|
+
const result = this.evaluateLocal();
|
|
250
|
+
return result.valid ? { success: true, message: 'The trial has started.' } : { success: false, errorCode: result.status, message: messages[result.status] };
|
|
251
|
+
}
|
|
252
|
+
/**
|
|
253
|
+
* Floating: keeps this device's seat for offline use for `hours` (up to the license's limit). Return it early with
|
|
254
|
+
* returnBorrow() (the same as release()). Refused without a request with `no_license` when there is no license and
|
|
255
|
+
* `borrow_not_allowed` when it isn't a checked-out floating license; a keyless trial gets `bad_request` (it is never sent to the
|
|
256
|
+
* server). The license file is removed only on a revoking code or lease_expired; other refusals keep it.
|
|
257
|
+
*/
|
|
258
|
+
async borrow(hours) {
|
|
259
|
+
if (!Number.isInteger(hours) || hours < 1)
|
|
260
|
+
return { success: false, errorCode: 'bad_request', message: 'Borrow for a whole number of hours (at least 1).' };
|
|
261
|
+
const token = this.read(this.tokenPath);
|
|
262
|
+
if (!token)
|
|
263
|
+
return { success: false, errorCode: ERROR_CODES.noLicense, message: 'There is no license on this device.' };
|
|
264
|
+
const payload = verifyToken(token, this.key);
|
|
265
|
+
if (payload?.trial === true)
|
|
266
|
+
return { success: false, errorCode: 'bad_request', message: "A trial can't be borrowed." };
|
|
267
|
+
if (payload?.floating !== true)
|
|
268
|
+
return { success: false, errorCode: ERROR_CODES.borrowNotAllowed, message: 'Only a checked-out floating license can be borrowed.' };
|
|
269
|
+
const r = await this.post('/api/client/v2/floating/borrow', {
|
|
270
|
+
token, fingerprint: this.fingerprint(), hours, appVersion: this.options.appVersion ?? null, clientTime: this.clientTime(),
|
|
271
|
+
}).catch(() => null);
|
|
272
|
+
if (!r)
|
|
273
|
+
return offline('Borrowing a license needs an internet connection.');
|
|
274
|
+
if (!r.ok) {
|
|
275
|
+
if (removesLicense(r)) {
|
|
276
|
+
this.stopHeartbeat();
|
|
277
|
+
this.clear();
|
|
278
|
+
this.lastServerMessage = r.error.message;
|
|
279
|
+
}
|
|
280
|
+
return { success: false, errorCode: r.error?.code, message: r.error?.message ?? `Server error (${r.status}).` };
|
|
281
|
+
}
|
|
282
|
+
if (!this.saveIfValid(r.token))
|
|
283
|
+
return { success: false, errorCode: 'invalid_token', message: 'The server returned an invalid license.' };
|
|
284
|
+
const result = this.evaluateLocal();
|
|
285
|
+
return result.valid
|
|
286
|
+
? { success: true, message: `The license is borrowed until ${result.license?.borrowedUntil?.toISOString() ?? '?'}.` }
|
|
287
|
+
: { success: false, errorCode: result.status, message: messages[result.status] };
|
|
288
|
+
}
|
|
289
|
+
/**
|
|
290
|
+
* Licenses with a use limit: consumes `count` uses on the server; refused with use_limit_reached when they are used up. A count
|
|
291
|
+
* below 1 is refused with `bad_request` and no license with `no_license`, both without a request; so is a keyless trial
|
|
292
|
+
* (`bad_request`: it is never sent to the server). The license file is removed only on a revoking code or lease_expired; any
|
|
293
|
+
* other refusal keeps it.
|
|
294
|
+
*/
|
|
295
|
+
async consume(count = 1) {
|
|
296
|
+
if (!Number.isInteger(count) || count < 1)
|
|
297
|
+
return { success: false, errorCode: 'bad_request', message: 'Consume a whole number of uses (at least 1).' };
|
|
298
|
+
const token = this.read(this.tokenPath);
|
|
299
|
+
if (!token)
|
|
300
|
+
return { success: false, errorCode: ERROR_CODES.noLicense, message: 'There is no license on this device.' };
|
|
301
|
+
if (verifyToken(token, this.key)?.trial === true)
|
|
302
|
+
return { success: false, errorCode: 'bad_request', message: 'A trial has no uses to consume.' };
|
|
303
|
+
const r = await this.post('/api/client/v2/use', { token, fingerprint: this.fingerprint(), count }).catch(() => null);
|
|
304
|
+
if (!r)
|
|
305
|
+
return { success: false, errorCode: ERROR_CODES.network, message: 'Could not connect to the license server.' };
|
|
306
|
+
if (!r.ok) {
|
|
307
|
+
if (removesLicense(r)) {
|
|
308
|
+
this.stopHeartbeat();
|
|
309
|
+
this.clear();
|
|
310
|
+
this.lastServerMessage = r.error.message;
|
|
311
|
+
}
|
|
312
|
+
return { success: false, errorCode: r.error?.code, message: r.error?.message ?? `Server error (${r.status}).` };
|
|
313
|
+
}
|
|
314
|
+
const uses = typeof r.json?.uses === 'number' ? r.json.uses : undefined;
|
|
315
|
+
const maxUses = typeof r.json?.maxUses === 'number' ? r.json.maxUses : undefined;
|
|
316
|
+
return { success: true, uses, maxUses, message: `${uses} of ${maxUses} uses.` };
|
|
317
|
+
}
|
|
318
|
+
/** Releases a floating seat (also returns a borrowed seat early). */
|
|
319
|
+
async release() {
|
|
320
|
+
this.stopHeartbeat();
|
|
321
|
+
return this.deactivate();
|
|
322
|
+
}
|
|
323
|
+
/**
|
|
324
|
+
* Returns a borrowed floating seat early (releases the seat of a floating license). On a node-locked license or a keyless trial
|
|
325
|
+
* it returns `borrow_not_allowed` without a request, so it can never use up a deactivation. Without a license it succeeds.
|
|
326
|
+
*/
|
|
327
|
+
async returnBorrow() {
|
|
328
|
+
const token = this.read(this.tokenPath);
|
|
329
|
+
if (!token)
|
|
330
|
+
return { success: true, message: 'There is no license on this device.' };
|
|
331
|
+
const payload = verifyToken(token, this.key);
|
|
332
|
+
if (payload?.floating !== true || payload.trial === true)
|
|
333
|
+
return { success: false, errorCode: ERROR_CODES.borrowNotAllowed, message: 'Only a floating license can be borrowed and returned.' };
|
|
334
|
+
return this.release();
|
|
335
|
+
}
|
|
336
|
+
/** Removes the license from this device and frees its seat on the server. */
|
|
337
|
+
async deactivate() {
|
|
338
|
+
this.stopHeartbeat();
|
|
339
|
+
const token = this.read(this.tokenPath);
|
|
340
|
+
if (!token)
|
|
341
|
+
return { success: true, message: 'There is no license on this device.' };
|
|
342
|
+
const payload = verifyToken(token, this.key);
|
|
343
|
+
if (payload?.trial === true) {
|
|
344
|
+
this.clear(); // a trial has no seat to free
|
|
345
|
+
return { success: true, message: 'The license has been removed from this device.' };
|
|
346
|
+
}
|
|
347
|
+
const floating = payload?.floating === true;
|
|
348
|
+
const r = await this.post(floating ? '/api/client/v2/floating/release' : '/api/client/v2/deactivate', { token, fingerprint: this.fingerprint() }).catch(() => null);
|
|
349
|
+
if (!r)
|
|
350
|
+
return offline('Removing the license needs an internet connection.');
|
|
351
|
+
if (!r.ok && !(r.error && REVOKING_CODES.has(r.error.code)))
|
|
352
|
+
return { success: false, errorCode: r.error?.code, message: r.error?.message ?? `Server error (${r.status}).` };
|
|
353
|
+
this.clear();
|
|
354
|
+
return r.ok || r.error?.code !== 'wrong_machine'
|
|
355
|
+
? { success: true, message: 'The license has been removed from this device.' }
|
|
356
|
+
: { success: false, errorCode: 'wrong_machine', message: r.error.message };
|
|
357
|
+
}
|
|
358
|
+
/** Asks the server for a fresh token now (floating licenses: a heartbeat). A keyless trial is never sent: it stays as it is. */
|
|
359
|
+
async refresh(anomalies) {
|
|
360
|
+
const token = this.read(this.tokenPath);
|
|
361
|
+
if (!token)
|
|
362
|
+
return;
|
|
363
|
+
const payload = verifyToken(token, this.key);
|
|
364
|
+
if (payload?.trial === true)
|
|
365
|
+
return;
|
|
366
|
+
const floating = payload?.floating === true;
|
|
367
|
+
const r = await this.post(floating ? '/api/client/v2/floating/heartbeat' : '/api/client/v2/refresh', { token, fingerprint: this.fingerprint(), appVersion: this.options.appVersion ?? null, anomalies: anomalies ?? null, clientTime: this.clientTime() });
|
|
368
|
+
if (r.ok)
|
|
369
|
+
this.saveIfValid(r.token);
|
|
370
|
+
else if (removesLicense(r)) {
|
|
371
|
+
this.clear();
|
|
372
|
+
this.lastServerMessage = r.error.message;
|
|
373
|
+
}
|
|
374
|
+
else if (r.error) {
|
|
375
|
+
this.lastServerMessage = r.error.message; // e.g. clock_offset or app_version_not_allowed: the license stays
|
|
376
|
+
}
|
|
377
|
+
}
|
|
378
|
+
/** A user-facing sentence for a status. */
|
|
379
|
+
message(status) {
|
|
380
|
+
return status === 'Missing' && this.lastServerMessage ? this.lastServerMessage : messages[status];
|
|
381
|
+
}
|
|
382
|
+
startHeartbeat() {
|
|
383
|
+
this.stopHeartbeat();
|
|
384
|
+
const payload = this.readPayload();
|
|
385
|
+
if (!payload?.floating)
|
|
386
|
+
return;
|
|
387
|
+
const half = Math.max(30_000, (Date.parse(payload.offlineUntil) - Date.parse(payload.issuedAt)) / 2);
|
|
388
|
+
this.heartbeat = setInterval(() => void this.refresh().catch(() => undefined), half);
|
|
389
|
+
this.heartbeat.unref?.();
|
|
390
|
+
}
|
|
391
|
+
stopHeartbeat() {
|
|
392
|
+
if (this.heartbeat)
|
|
393
|
+
clearInterval(this.heartbeat);
|
|
394
|
+
this.heartbeat = null;
|
|
395
|
+
}
|
|
396
|
+
async post(path, body) {
|
|
397
|
+
const controller = new AbortController();
|
|
398
|
+
const timer = setTimeout(() => controller.abort(), this.options.timeoutMs);
|
|
399
|
+
try {
|
|
400
|
+
const res = await (this.options.fetch ?? fetch)(this.options.serverUrl + path, {
|
|
401
|
+
method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body), signal: controller.signal,
|
|
402
|
+
});
|
|
403
|
+
const text = await res.text();
|
|
404
|
+
const json = text ? JSON.parse(text) : {};
|
|
405
|
+
return res.ok ? { ok: true, status: res.status, token: json.token, json } : { ok: false, status: res.status, error: json.code ? json : undefined };
|
|
406
|
+
}
|
|
407
|
+
finally {
|
|
408
|
+
clearTimeout(timer);
|
|
409
|
+
}
|
|
410
|
+
}
|
|
411
|
+
saveIfValid(token) {
|
|
412
|
+
const payload = verifyToken(token, this.key);
|
|
413
|
+
if (!payload || payload.product.toLowerCase() !== this.options.product.toLowerCase())
|
|
414
|
+
return false;
|
|
415
|
+
this.write(this.tokenPath, token);
|
|
416
|
+
this.write(this.historyPath, encodeRunHistory(this.now(), this.options.vendor, this.options.product, this.fingerprint()));
|
|
417
|
+
return true;
|
|
418
|
+
}
|
|
419
|
+
readPayload() {
|
|
420
|
+
const token = this.read(this.tokenPath);
|
|
421
|
+
return token ? verifyToken(token, this.key) : null;
|
|
422
|
+
}
|
|
423
|
+
clear() {
|
|
424
|
+
for (const p of [this.tokenPath])
|
|
425
|
+
rmSync(p, { force: true });
|
|
426
|
+
}
|
|
427
|
+
read(path) {
|
|
428
|
+
try {
|
|
429
|
+
return readFileSync(path, 'utf8').trim() || null;
|
|
430
|
+
}
|
|
431
|
+
catch {
|
|
432
|
+
return null;
|
|
433
|
+
}
|
|
434
|
+
}
|
|
435
|
+
write(path, value) {
|
|
436
|
+
mkdirSync(this.dir, { recursive: true });
|
|
437
|
+
writeFileSync(path, value, 'utf8');
|
|
438
|
+
}
|
|
439
|
+
}
|
|
440
|
+
/** The one rule (refresh, consume, borrow) for removing the local license: a revoking code or lease_expired. */
|
|
441
|
+
function removesLicense(r) {
|
|
442
|
+
return !!r.error && (REVOKING_CODES.has(r.error.code) || r.error.code === 'lease_expired');
|
|
443
|
+
}
|
|
444
|
+
function defaultStorageDir(product) {
|
|
445
|
+
const base = platform() === 'win32'
|
|
446
|
+
? process.env.LOCALAPPDATA ?? join(homedir(), 'AppData', 'Local')
|
|
447
|
+
: platform() === 'darwin'
|
|
448
|
+
? join(homedir(), 'Library', 'Application Support')
|
|
449
|
+
: process.env.XDG_DATA_HOME ?? join(homedir(), '.local', 'share');
|
|
450
|
+
return join(base, 'licenserail', product);
|
|
451
|
+
}
|
package/dist/core.d.ts
ADDED
|
@@ -0,0 +1,147 @@
|
|
|
1
|
+
import { type KeyObject } from 'node:crypto';
|
|
2
|
+
/** Hashed device components; raw hardware values never leave the device. */
|
|
3
|
+
export interface Fingerprint {
|
|
4
|
+
machineId: string;
|
|
5
|
+
diskId: string;
|
|
6
|
+
hostName: string;
|
|
7
|
+
boardId: string;
|
|
8
|
+
/** windows, macos, linux, android or ios. */
|
|
9
|
+
os?: string | null;
|
|
10
|
+
}
|
|
11
|
+
/** Device matching: 'default' (board id + one other, or 2 of 3), 'strict' (every registered part) or 'loose' (any one part). */
|
|
12
|
+
export type MatchingStrategy = 'default' | 'strict' | 'loose';
|
|
13
|
+
/** The signed license content (token payload). v2 fields are optional. */
|
|
14
|
+
export interface LicensePayload {
|
|
15
|
+
licenseId: string;
|
|
16
|
+
activationId: string;
|
|
17
|
+
licenseKey: string;
|
|
18
|
+
product: string;
|
|
19
|
+
customer: string;
|
|
20
|
+
kind: 'full' | 'trial' | string;
|
|
21
|
+
expiresAt: string | null;
|
|
22
|
+
issuedAt: string;
|
|
23
|
+
refreshAfter: string;
|
|
24
|
+
offlineUntil: string;
|
|
25
|
+
fingerprint: Fingerprint;
|
|
26
|
+
suspended: boolean;
|
|
27
|
+
environmentId?: string;
|
|
28
|
+
test?: boolean;
|
|
29
|
+
entitlements?: string[];
|
|
30
|
+
metadata?: Record<string, unknown>;
|
|
31
|
+
floating?: boolean;
|
|
32
|
+
leaseExpiresAt?: string;
|
|
33
|
+
/** Device matching applied offline: 'strict' or 'loose'; absent = default. */
|
|
34
|
+
matching?: MatchingStrategy | string;
|
|
35
|
+
/** The newest app version this license may run; absent = any. */
|
|
36
|
+
maxAppVersion?: string;
|
|
37
|
+
/** The license has expired but its strategy keeps it working (maintain or allow); expiresAt is then absent. */
|
|
38
|
+
expired?: boolean;
|
|
39
|
+
/** The license expired and works until this time (grace); expiresAt is the same moment. */
|
|
40
|
+
graceUntil?: string;
|
|
41
|
+
/** Floating: the seat is borrowed for offline use until this time. */
|
|
42
|
+
borrowedUntil?: string;
|
|
43
|
+
/** Use counting: the license's limit, and the uses when the token was issued. */
|
|
44
|
+
maxUses?: number;
|
|
45
|
+
uses?: number;
|
|
46
|
+
/** More devices are active than the license's seats (overdraft). */
|
|
47
|
+
overage?: boolean;
|
|
48
|
+
/** The license's own expiry, for display (absent/null = perpetual); never enforced (the offline check uses expiresAt). */
|
|
49
|
+
licenseExpiresAt?: string | null;
|
|
50
|
+
/** A keyless trial: valid until expiresAt, never refreshed. */
|
|
51
|
+
trial?: boolean;
|
|
52
|
+
}
|
|
53
|
+
export type LicenseStatus = 'Valid' | 'Missing' | 'InvalidSignature' | 'WrongProduct' | 'WrongMachine' | 'Expired' | 'OfflineTooLong' | 'ClockTampered' | 'Unverified' | 'Suspended'
|
|
54
|
+
/** The app is newer than the license's maxAppVersion. */
|
|
55
|
+
| 'AppVersionNotAllowed';
|
|
56
|
+
export declare const UNAVAILABLE = "none";
|
|
57
|
+
/** The clock going back slightly during NTP sync is normal. */
|
|
58
|
+
export declare const CLOCK_TOLERANCE_MS: number;
|
|
59
|
+
/** The device clock may lag the server; a token "from the future" by less than this is accepted. */
|
|
60
|
+
export declare const ISSUED_AT_TOLERANCE_MS: number;
|
|
61
|
+
/** Error codes on which the local license is deleted; on any other error (network, 402…) it is kept. */
|
|
62
|
+
export declare const REVOKING_CODES: Set<string>;
|
|
63
|
+
/** The `code` values the client API returns (`ActivationResult.errorCode`, `UseResult.errorCode`). */
|
|
64
|
+
export declare const ERROR_CODES: {
|
|
65
|
+
readonly badRequest: "bad_request";
|
|
66
|
+
/** Returned by the SDK without a request: there is no license on this device (borrow, consume). */
|
|
67
|
+
readonly noLicense: "no_license";
|
|
68
|
+
readonly network: "network";
|
|
69
|
+
readonly licenseNotFound: "license_not_found";
|
|
70
|
+
readonly wrongProduct: "wrong_product";
|
|
71
|
+
readonly licenseSuspended: "license_suspended";
|
|
72
|
+
readonly licenseExpired: "license_expired";
|
|
73
|
+
readonly licenseRevoked: "license_revoked";
|
|
74
|
+
readonly licenseInUse: "license_in_use";
|
|
75
|
+
readonly activationRevoked: "activation_revoked";
|
|
76
|
+
readonly wrongMachine: "wrong_machine";
|
|
77
|
+
readonly invalidToken: "invalid_token";
|
|
78
|
+
readonly seatLimitReached: "seat_limit_reached";
|
|
79
|
+
readonly leaseExpired: "lease_expired";
|
|
80
|
+
readonly tenantSuspended: "tenant_suspended";
|
|
81
|
+
readonly insufficientBalance: "insufficient_balance";
|
|
82
|
+
readonly rateLimited: "rate_limited";
|
|
83
|
+
readonly deviceNotIdentified: "device_not_identified";
|
|
84
|
+
readonly trialUnavailable: "trial_unavailable";
|
|
85
|
+
readonly trialEnded: "trial_ended";
|
|
86
|
+
/** The vendor blocked the address the request came from. */
|
|
87
|
+
readonly ipBlocked: "ip_blocked";
|
|
88
|
+
/** This device used up the license's lifetime deactivations; only the vendor can free the seat. */
|
|
89
|
+
readonly deactivationLimitReached: "deactivation_limit_reached";
|
|
90
|
+
/** The vendor banned this device from the license. */
|
|
91
|
+
readonly deviceBanned: "device_banned";
|
|
92
|
+
/** Too many failed activations: new devices are locked until the vendor unlocks the license. */
|
|
93
|
+
readonly licenseLocked: "license_locked";
|
|
94
|
+
/** The device clock is too far from the server's. */
|
|
95
|
+
readonly clockOffset: "clock_offset";
|
|
96
|
+
/** The app version is older than the product's minimum or newer than the license's maximum. */
|
|
97
|
+
readonly appVersionNotAllowed: "app_version_not_allowed";
|
|
98
|
+
/** The license can't be used from this country or network. */
|
|
99
|
+
readonly locationNotAllowed: "location_not_allowed";
|
|
100
|
+
/** Borrowing is off for the license, or more hours were asked than it allows. */
|
|
101
|
+
readonly borrowNotAllowed: "borrow_not_allowed";
|
|
102
|
+
/** A seat was just released by another device and can't be taken yet. */
|
|
103
|
+
readonly seatCoolingDown: "seat_cooling_down";
|
|
104
|
+
/** All uses of the license are used up. */
|
|
105
|
+
readonly useLimitReached: "use_limit_reached";
|
|
106
|
+
/** The product doesn't allow new activations or trials on virtual machines. */
|
|
107
|
+
readonly virtualMachineNotAllowed: "virtual_machine_not_allowed";
|
|
108
|
+
};
|
|
109
|
+
export type ErrorCode = (typeof ERROR_CODES)[keyof typeof ERROR_CODES];
|
|
110
|
+
export declare function importPublicKey(pem: string): KeyObject;
|
|
111
|
+
/**
|
|
112
|
+
* Verifies `base64url(json).base64url(signature)` (ECDSA P-256 / SHA-256, IEEE P1363 r||s) over the ASCII bytes of the encoded
|
|
113
|
+
* body and returns the payload, or null if the signature or format is invalid.
|
|
114
|
+
*/
|
|
115
|
+
export declare function verifyToken(token: string, publicKey: KeyObject | string): LicensePayload | null;
|
|
116
|
+
/**
|
|
117
|
+
* component = hex(SHA256(vendor + ":" + product + ":" + part + ":" + upper(trim(raw)))); blank → "none".
|
|
118
|
+
* `vendor` is the organization ID from the dashboard (ten_...); it never changes, so device identities stay stable.
|
|
119
|
+
*/
|
|
120
|
+
export declare function hashComponent(vendor: string, product: string, part: 'machine' | 'disk' | 'host' | 'board', raw: string | null | undefined): string;
|
|
121
|
+
/** Host platforms whose installations are licensed like devices (an app inside YouTrack, not a computer). */
|
|
122
|
+
export declare const HOST_PLATFORMS: readonly string[];
|
|
123
|
+
/**
|
|
124
|
+
* Whether `presented` is the device `registered` was issued for (call on the registered fingerprint). `strategy` is the token's
|
|
125
|
+
* `matching` field: default (board id + one other part, or 2 of 3 without a board id), 'strict' (every part the registered device
|
|
126
|
+
* has) or 'loose' (any one part). When both sides name an operating system it must be the same; host installations always
|
|
127
|
+
* match exactly (same platform and id).
|
|
128
|
+
*/
|
|
129
|
+
export declare function fingerprintMatches(registered: Fingerprint, presented: Fingerprint, strategy?: MatchingStrategy | string | null): boolean;
|
|
130
|
+
/** A version the server compares: after trimming whitespace, 1 to 50 characters and the first is an ASCII digit. */
|
|
131
|
+
export declare function isVersion(v: string | null | undefined): v is string;
|
|
132
|
+
/**
|
|
133
|
+
* "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
|
|
134
|
+
* (-beta, +build) is ignored; a part above 2147483647 counts as 0. Same as the server (test-vectors/versions.json).
|
|
135
|
+
*/
|
|
136
|
+
export declare function compareVersions(a: string, b: string): number;
|
|
137
|
+
/** Whether `appVersion` may run under a license limited to `maxAppVersion` (unknown or missing versions aren't refused). */
|
|
138
|
+
export declare function appVersionAllowed(maxAppVersion: string | null | undefined, appVersion: string | null | undefined): boolean;
|
|
139
|
+
/**
|
|
140
|
+
* Offline check, identical in every SDK (see the shared test vectors). `appVersion` (optional) is checked against the token's
|
|
141
|
+
* `maxAppVersion`. Grace (`graceUntil`) and expired-but-kept licenses (`expired: true`) need nothing extra: the server sets
|
|
142
|
+
* `expiresAt` to the end of grace, or leaves it out.
|
|
143
|
+
*/
|
|
144
|
+
export declare function evaluate(payload: LicensePayload | null, product: string, machine: Fingerprint, now: Date, lastSeen: Date | null, appVersion?: string | null): LicenseStatus;
|
|
145
|
+
/** Tamper-evident "last run" record: `{epochMs}.{hmac}` keyed to the product and device. */
|
|
146
|
+
export declare function encodeRunHistory(at: Date, vendor: string, product: string, machine: Fingerprint): string;
|
|
147
|
+
export declare function decodeRunHistory(value: string | null | undefined, vendor: string, product: string, machine: Fingerprint): Date | null;
|