@carchalabs/seal-electron 0.0.0-stage → 0.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +35 -2
- package/dist/fingerprint.d.ts +33 -0
- package/dist/fingerprint.js +97 -0
- package/dist/fingerprint.js.map +1 -0
- package/dist/index.d.ts +166 -0
- package/dist/index.js +524 -0
- package/dist/index.js.map +1 -0
- package/package.json +24 -4
- package/src/fingerprint.ts +103 -0
- package/src/index.ts +623 -0
package/src/index.ts
ADDED
|
@@ -0,0 +1,623 @@
|
|
|
1
|
+
import { KeyObject } from 'node:crypto';
|
|
2
|
+
import { existsSync, readFileSync } from 'node:fs';
|
|
3
|
+
import { mkdir, readFile, rm, writeFile } from 'node:fs/promises';
|
|
4
|
+
import { createRequire } from 'node:module';
|
|
5
|
+
import { hostname, platform } from 'node:os';
|
|
6
|
+
import { dirname, join, resolve } from 'node:path';
|
|
7
|
+
import { compileFunction } from 'node:vm';
|
|
8
|
+
import { decodeLease, decryptFeature, hashFingerprint, keySet, LeaseClaims, LeaseFailure, LeaseVerifyOptions, LeaseVerifyResult, verifyLease } from '@carchalabs/seal-core';
|
|
9
|
+
import { MachineIdUnavailableError, readMachineId } from './fingerprint';
|
|
10
|
+
|
|
11
|
+
export { MachineIdUnavailableError, readMachineId };
|
|
12
|
+
|
|
13
|
+
/** This SDK's version, sent to the server so vendors can see (and require) which SDK each device runs. */
|
|
14
|
+
// eslint-disable-next-line @typescript-eslint/no-require-imports
|
|
15
|
+
export const SDK_VERSION: string = require('../package.json').version;
|
|
16
|
+
|
|
17
|
+
export type LicenseStatus = 'valid' | 'grace' | 'invalid' | 'unlicensed' | 'clock_suspect';
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* Something the server asks the app to act on: sdk_update_recommended (update the Carcha Seal SDK in the app) or
|
|
21
|
+
* app_update_recommended (the vendor's minimum app version), each with minimum and requiredFrom.
|
|
22
|
+
*/
|
|
23
|
+
export interface LicenseNotice {
|
|
24
|
+
code: string;
|
|
25
|
+
minimum?: string;
|
|
26
|
+
/** ISO date from which an older SDK is refused; null when the update is only recommended. */
|
|
27
|
+
requiredFrom?: string | null;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export interface LicenseState {
|
|
31
|
+
status: LicenseStatus;
|
|
32
|
+
offline: boolean;
|
|
33
|
+
storageProtected: boolean;
|
|
34
|
+
reason?: string;
|
|
35
|
+
message?: string;
|
|
36
|
+
customer?: string;
|
|
37
|
+
features: string[];
|
|
38
|
+
expiresAt: string | null;
|
|
39
|
+
maintenanceUntil?: string | null;
|
|
40
|
+
revalidateBy?: string;
|
|
41
|
+
keyHint?: string;
|
|
42
|
+
/** From the last successful check-in; kept while offline. The app decides how to show them. */
|
|
43
|
+
notices?: LicenseNotice[];
|
|
44
|
+
/** True when the license came from an offline license file (activateOffline); renew it with a new file. */
|
|
45
|
+
offlineActivated?: boolean;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/** Hashed hardware components (see @carchalabs/seal-hwid); the server matches a device by them. */
|
|
49
|
+
export interface HardwareReport {
|
|
50
|
+
components: { kind: string; hash: string }[];
|
|
51
|
+
/** True when the device runs as a virtual machine. */
|
|
52
|
+
vm: boolean;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
export interface SecureStore {
|
|
56
|
+
encrypt(plain: string): Buffer | Promise<Buffer>;
|
|
57
|
+
decrypt(cipher: Buffer): string | Promise<string>;
|
|
58
|
+
isProtected?(): boolean;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
export interface SealOptions {
|
|
62
|
+
serverUrl: string;
|
|
63
|
+
product: string;
|
|
64
|
+
publicKey: string | string[];
|
|
65
|
+
storageDir: string;
|
|
66
|
+
appVersion?: string;
|
|
67
|
+
graceDays?: number;
|
|
68
|
+
secureStore?: SecureStore;
|
|
69
|
+
requestTimeoutMs?: number;
|
|
70
|
+
fetchImpl?: typeof fetch;
|
|
71
|
+
machineId?: () => Promise<string>;
|
|
72
|
+
/** Use hostname + CPU + MAC when the OS machine id cannot be read (default false; see readMachineId). */
|
|
73
|
+
allowFallbackFingerprint?: boolean;
|
|
74
|
+
/**
|
|
75
|
+
* Hardware components sent with each request, so the device keeps its seat after a new disk, network
|
|
76
|
+
* card or OS install. Default: read with @carchalabs/seal-hwid when it is installed; nothing is
|
|
77
|
+
* sent when it is not (or cannot load on this platform). false: never send them. A function: your own.
|
|
78
|
+
*/
|
|
79
|
+
hardware?: false | (() => HardwareReport | null | Promise<HardwareReport | null>);
|
|
80
|
+
now?: () => number;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
interface Stored {
|
|
84
|
+
licenseKey: string;
|
|
85
|
+
/** Signed lease. Absent after the server refused this device: nothing is left to verify offline. */
|
|
86
|
+
token?: string;
|
|
87
|
+
lastSeen?: number;
|
|
88
|
+
/** The server's last definitive refusal, kept so an offline check reports it instead of an old lease. */
|
|
89
|
+
refused?: { code: string; message: string; at: number };
|
|
90
|
+
notices?: LicenseNotice[];
|
|
91
|
+
/** Activated from an offline license file: check() never calls the server; a new file renews it. */
|
|
92
|
+
offline?: boolean;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
type Leased = Stored & { token: string };
|
|
96
|
+
|
|
97
|
+
/** File formats of offline activation, shared with the license server. */
|
|
98
|
+
const OFFLINE_REQUEST_FORMAT = 'licensekit-offline-request';
|
|
99
|
+
const OFFLINE_LICENSE_FORMAT = 'licensekit-offline-license';
|
|
100
|
+
const OFFLINE_DEACTIVATION_FORMAT = 'licensekit-offline-deactivation';
|
|
101
|
+
|
|
102
|
+
const DEFINITIVE = new Set(['invalid_key', 'not_activated', 'license_suspended', 'license_revoked', 'license_expired', 'sdk_update_required', 'app_update_required', 'vm_not_allowed']);
|
|
103
|
+
/** The native hardware module. A non-literal require: bundlers leave it to Node, which must load the .node file from disk. */
|
|
104
|
+
const HWID_PACKAGE = '@carchalabs/seal-hwid';
|
|
105
|
+
/** The native module's lease verifier (@carchalabs/seal-hwid 0.2+): its keys are compiled in. */
|
|
106
|
+
interface NativeLease {
|
|
107
|
+
verifyLease(token: string, check: { product: string; fingerprintHash: string; now: number; graceSeconds?: number }): { ok: boolean; reason?: string };
|
|
108
|
+
leaseKeyIds(): string[];
|
|
109
|
+
/** This machine's X25519 public key from its hardware (base64url), or null. */
|
|
110
|
+
devicePublicKey?(key: string): string | null;
|
|
111
|
+
/** @carchalabs/seal-hwid 0.2+ with feature keys. */
|
|
112
|
+
decryptFeature?(
|
|
113
|
+
token: string,
|
|
114
|
+
check: { product: string; fingerprintHash: string; now: number; graceSeconds?: number },
|
|
115
|
+
licenseKey: string,
|
|
116
|
+
feature: string,
|
|
117
|
+
data: Buffer,
|
|
118
|
+
): { ok: boolean; data?: Buffer; reason?: string };
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/** Loads the native module once per process; null when it is not installed or has no build for this platform. */
|
|
122
|
+
let hwidModule: any;
|
|
123
|
+
function loadHwid(): any {
|
|
124
|
+
if (hwidModule === undefined) {
|
|
125
|
+
try {
|
|
126
|
+
// eslint-disable-next-line @typescript-eslint/no-require-imports
|
|
127
|
+
hwidModule = require(HWID_PACKAGE);
|
|
128
|
+
} catch {
|
|
129
|
+
hwidModule = null;
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
return hwidModule;
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
/** The server accepts at most this many components. */
|
|
136
|
+
const MAX_COMPONENTS = 32;
|
|
137
|
+
/** The license itself is gone: forget the key too. The other refusals can be undone on the server (resume, renew,
|
|
138
|
+
* re-activate), so the key is kept and the next successful online check restores the license on its own. */
|
|
139
|
+
const FORGET_KEY = new Set(['invalid_key', 'license_revoked']);
|
|
140
|
+
const CLOCK_TOLERANCE_SECONDS = 24 * 3600;
|
|
141
|
+
const DEFAULT_GRACE_DAYS = 7;
|
|
142
|
+
const CLOCK_MESSAGE = 'The date and time on this computer look wrong. Correct them, then connect to the internet.';
|
|
143
|
+
|
|
144
|
+
export class LicenseError extends Error {
|
|
145
|
+
constructor(
|
|
146
|
+
public readonly code: string,
|
|
147
|
+
message: string,
|
|
148
|
+
public readonly status?: number,
|
|
149
|
+
) {
|
|
150
|
+
super(message);
|
|
151
|
+
this.name = 'LicenseError';
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
const REASON_TEXT: Record<LeaseFailure, string> = {
|
|
156
|
+
malformed: 'The saved license is damaged. Please activate again.',
|
|
157
|
+
bad_signature: 'The saved license was modified. Please activate again.',
|
|
158
|
+
unsupported_algorithm: 'Please update the app.',
|
|
159
|
+
wrong_type: 'Please update the app.',
|
|
160
|
+
unknown_key: 'Please update the app.',
|
|
161
|
+
wrong_issuer: 'This license was issued by a different license server.',
|
|
162
|
+
not_yet_valid: CLOCK_MESSAGE,
|
|
163
|
+
wrong_product: 'This license is for a different product.',
|
|
164
|
+
wrong_device: 'This license is activated on another device.',
|
|
165
|
+
expired: 'Your license has expired.',
|
|
166
|
+
revalidation_required: 'Connect to the internet to confirm your license.',
|
|
167
|
+
};
|
|
168
|
+
|
|
169
|
+
const toIso = (seconds: number) => new Date(seconds * 1000).toISOString();
|
|
170
|
+
|
|
171
|
+
function noticesFrom(response: any): { notices?: LicenseNotice[] } {
|
|
172
|
+
const list = Array.isArray(response?.notices) ? response.notices.filter((n: any) => n && typeof n.code === 'string') : [];
|
|
173
|
+
return list.length ? { notices: list } : {};
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
export class Seal {
|
|
177
|
+
private readonly file: string;
|
|
178
|
+
private readonly keys: Map<string, KeyObject>;
|
|
179
|
+
private fingerprintCache?: string;
|
|
180
|
+
private hardwareCache?: Promise<HardwareReport | null>;
|
|
181
|
+
/** The native lease verifier, when it trusts every key this app was given (undefined = not looked up yet). */
|
|
182
|
+
private nativeLease?: NativeLease | null;
|
|
183
|
+
private deviceKeyCache?: string | null;
|
|
184
|
+
|
|
185
|
+
constructor(private readonly opts: SealOptions) {
|
|
186
|
+
this.file = join(opts.storageDir, 'license.dat');
|
|
187
|
+
this.keys = keySet(Array.isArray(opts.publicKey) ? opts.publicKey : [opts.publicKey]);
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
private get fetch() {
|
|
191
|
+
return this.opts.fetchImpl ?? fetch;
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
private nowSec() {
|
|
195
|
+
return Math.floor((this.opts.now?.() ?? Date.now()) / 1000);
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
private get storageProtected(): boolean {
|
|
199
|
+
const store = this.opts.secureStore;
|
|
200
|
+
return store !== undefined && (store.isProtected?.() ?? true);
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
async fingerprint(): Promise<string> {
|
|
204
|
+
if (!this.fingerprintCache) {
|
|
205
|
+
let raw: string;
|
|
206
|
+
try {
|
|
207
|
+
raw = await (this.opts.machineId ?? (() => readMachineId({ allowFallback: this.opts.allowFallbackFingerprint })))();
|
|
208
|
+
} catch (e) {
|
|
209
|
+
if (e instanceof MachineIdUnavailableError) throw new LicenseError(e.code, e.message);
|
|
210
|
+
throw e;
|
|
211
|
+
}
|
|
212
|
+
this.fingerprintCache = hashFingerprint(raw, this.opts.product);
|
|
213
|
+
}
|
|
214
|
+
return this.fingerprintCache;
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
/** Read once per instance: hardware does not change while the app runs. Never throws. */
|
|
218
|
+
private hardware(): Promise<{ components?: HardwareReport['components']; vm?: boolean }> {
|
|
219
|
+
this.hardwareCache ??= (async () => {
|
|
220
|
+
const source = this.opts.hardware;
|
|
221
|
+
if (source === false) return null;
|
|
222
|
+
try {
|
|
223
|
+
if (source) return await source();
|
|
224
|
+
const hwid = loadHwid();
|
|
225
|
+
if (!hwid) return null;
|
|
226
|
+
const { components, vm } = hwid.collect(`licensekit:${this.opts.product}`);
|
|
227
|
+
return { components, vm };
|
|
228
|
+
} catch {
|
|
229
|
+
return null; // not installed, or no module for this platform: send nothing, as before
|
|
230
|
+
}
|
|
231
|
+
})();
|
|
232
|
+
return this.hardwareCache.then((report) =>
|
|
233
|
+
report && report.components.length ? { components: report.components.slice(0, MAX_COMPONENTS), vm: report.vm === true } : {},
|
|
234
|
+
);
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
private async load(): Promise<Stored | null> {
|
|
238
|
+
try {
|
|
239
|
+
const buf = await readFile(this.file);
|
|
240
|
+
const text = this.opts.secureStore ? await this.opts.secureStore.decrypt(buf) : buf.toString('utf8');
|
|
241
|
+
return JSON.parse(text);
|
|
242
|
+
} catch {
|
|
243
|
+
return null;
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
private async save(stored: Stored) {
|
|
248
|
+
await mkdir(this.opts.storageDir, { recursive: true });
|
|
249
|
+
const text = JSON.stringify(stored);
|
|
250
|
+
await writeFile(this.file, this.opts.secureStore ? await this.opts.secureStore.encrypt(text) : text, { mode: 0o600 });
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
private async clear() {
|
|
254
|
+
await rm(this.file, { force: true });
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
private async post(path: string, body: Record<string, unknown>): Promise<any> {
|
|
258
|
+
let res: Response;
|
|
259
|
+
try {
|
|
260
|
+
res = await this.fetch(this.opts.serverUrl.replace(/\/+$/, '') + path, {
|
|
261
|
+
method: 'POST',
|
|
262
|
+
headers: { 'Content-Type': 'application/json' },
|
|
263
|
+
body: JSON.stringify(body),
|
|
264
|
+
signal: AbortSignal.timeout(this.opts.requestTimeoutMs ?? 8000),
|
|
265
|
+
});
|
|
266
|
+
} catch {
|
|
267
|
+
throw new LicenseError('network', 'Could not reach the license server.');
|
|
268
|
+
}
|
|
269
|
+
const json: any = await res.json().catch(() => ({}));
|
|
270
|
+
if (!res.ok) throw new LicenseError(json.error ?? 'server_error', json.message ?? `License server error (${res.status})`, res.status);
|
|
271
|
+
return json;
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
private emptyState(status: LicenseStatus, offline: boolean, extra: Partial<LicenseState> = {}): LicenseState {
|
|
275
|
+
return { status, offline, storageProtected: this.storageProtected, features: [], expiresAt: null, ...extra };
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
/**
|
|
279
|
+
* The device's public key, sent with activation and check-ins so the server wraps feature keys for
|
|
280
|
+
* this machine only. Only when the native module verifies for this app (it then also decrypts, with
|
|
281
|
+
* the matching secret it derives itself) and hardware is not turned off. Never throws.
|
|
282
|
+
*/
|
|
283
|
+
private deviceKey(): { devicePublicKey?: string } {
|
|
284
|
+
if (this.deviceKeyCache === undefined) {
|
|
285
|
+
let key: string | null = null;
|
|
286
|
+
try {
|
|
287
|
+
const native = this.opts.hardware === false ? null : this.native();
|
|
288
|
+
if (native && typeof native.devicePublicKey === 'function' && typeof native.decryptFeature === 'function') {
|
|
289
|
+
key = native.devicePublicKey(`licensekit:${this.opts.product}`);
|
|
290
|
+
}
|
|
291
|
+
} catch {
|
|
292
|
+
key = null;
|
|
293
|
+
}
|
|
294
|
+
this.deviceKeyCache = key;
|
|
295
|
+
}
|
|
296
|
+
return this.deviceKeyCache ? { devicePublicKey: this.deviceKeyCache } : {};
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
/**
|
|
300
|
+
* The native verifier, used only when its compiled-in keys include every key this app was given:
|
|
301
|
+
* an app that trusts other keys (a self-hosted server) is checked by the JavaScript verifier alone.
|
|
302
|
+
*/
|
|
303
|
+
private native(): NativeLease | null {
|
|
304
|
+
if (this.nativeLease === undefined) {
|
|
305
|
+
const hwid = loadHwid();
|
|
306
|
+
let native: NativeLease | null = null;
|
|
307
|
+
if (hwid && typeof hwid.verifyLease === 'function' && typeof hwid.leaseKeyIds === 'function') {
|
|
308
|
+
const trusted = new Set<string>(hwid.leaseKeyIds());
|
|
309
|
+
if ([...this.keys.keys()].every((kid) => trusted.has(kid))) native = hwid;
|
|
310
|
+
}
|
|
311
|
+
this.nativeLease = native;
|
|
312
|
+
}
|
|
313
|
+
return this.nativeLease;
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
/**
|
|
317
|
+
* Verifies a lease twice, in JavaScript and in the native module, when the native verifier applies.
|
|
318
|
+
* Both follow the same rules, so a different answer means one of them was tampered with: the lease
|
|
319
|
+
* is then treated as modified.
|
|
320
|
+
*/
|
|
321
|
+
private verify(token: string, options: LeaseVerifyOptions): LeaseVerifyResult {
|
|
322
|
+
const result = verifyLease(token, options);
|
|
323
|
+
const native = this.native();
|
|
324
|
+
if (!native) return result;
|
|
325
|
+
const check = native.verifyLease(token, {
|
|
326
|
+
product: options.product,
|
|
327
|
+
fingerprintHash: options.fingerprintHash,
|
|
328
|
+
now: options.now ?? Math.floor(Date.now() / 1000),
|
|
329
|
+
...(options.graceSeconds !== undefined ? { graceSeconds: options.graceSeconds } : {}),
|
|
330
|
+
});
|
|
331
|
+
const agree = check.ok === result.ok && (result.ok || check.reason === result.reason);
|
|
332
|
+
return agree ? result : { ok: false, reason: 'bad_signature' };
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
private stateFromLease(stored: Leased, offline: boolean): LicenseState {
|
|
336
|
+
const fingerprintHash = this.fingerprintCache!;
|
|
337
|
+
const now = this.nowSec();
|
|
338
|
+
const keyHint = `${stored.licenseKey.slice(0, 7)}…${stored.licenseKey.slice(-4)}`;
|
|
339
|
+
if (offline && stored.lastSeen !== undefined && now < stored.lastSeen - CLOCK_TOLERANCE_SECONDS) {
|
|
340
|
+
return this.emptyState('clock_suspect', offline, { reason: 'clock_rollback', message: CLOCK_MESSAGE, keyHint });
|
|
341
|
+
}
|
|
342
|
+
const verifyOptions = { keys: this.keys, product: this.opts.product, fingerprintHash, now };
|
|
343
|
+
const strict = this.verify(stored.token, verifyOptions);
|
|
344
|
+
const fromClaims = (claims: LeaseClaims) => ({
|
|
345
|
+
customer: claims.cus,
|
|
346
|
+
features: claims.feat,
|
|
347
|
+
expiresAt: claims.exp === undefined ? null : toIso(claims.exp),
|
|
348
|
+
maintenanceUntil: claims.mnt === undefined ? null : toIso(claims.mnt),
|
|
349
|
+
storageProtected: this.storageProtected,
|
|
350
|
+
keyHint,
|
|
351
|
+
...(stored.notices ? { notices: stored.notices } : {}),
|
|
352
|
+
...(stored.offline ? { offlineActivated: true } : {}),
|
|
353
|
+
});
|
|
354
|
+
if (strict.ok) {
|
|
355
|
+
return { status: 'valid', offline, ...fromClaims(strict.claims), revalidateBy: toIso(strict.claims.rev) };
|
|
356
|
+
}
|
|
357
|
+
if (strict.reason === 'not_yet_valid') {
|
|
358
|
+
return this.emptyState('clock_suspect', offline, { reason: 'lease_from_future', message: CLOCK_MESSAGE, keyHint });
|
|
359
|
+
}
|
|
360
|
+
if (strict.reason === 'revalidation_required' && strict.claims) {
|
|
361
|
+
const grace = strict.claims.grc ?? (this.opts.graceDays ?? DEFAULT_GRACE_DAYS) * 86400;
|
|
362
|
+
const lenient = this.verify(stored.token, { ...verifyOptions, graceSeconds: grace });
|
|
363
|
+
if (lenient.ok) {
|
|
364
|
+
return {
|
|
365
|
+
status: 'grace',
|
|
366
|
+
offline,
|
|
367
|
+
reason: 'offline_grace',
|
|
368
|
+
message: stored.offline
|
|
369
|
+
? 'This offline license is past its renewal date. Load a new offline license file soon to keep using the app.'
|
|
370
|
+
: 'Working offline. Connect to the internet soon to keep using the app.',
|
|
371
|
+
...fromClaims(lenient.claims),
|
|
372
|
+
revalidateBy: toIso(Math.min(lenient.claims.rev + grace, lenient.claims.exp ?? Infinity)),
|
|
373
|
+
};
|
|
374
|
+
}
|
|
375
|
+
}
|
|
376
|
+
return this.emptyState('invalid', offline, { reason: strict.reason, message: REASON_TEXT[strict.reason], keyHint });
|
|
377
|
+
}
|
|
378
|
+
|
|
379
|
+
async activate(licenseKey: string, machineName = hostname()): Promise<LicenseState> {
|
|
380
|
+
const fingerprint = await this.fingerprint();
|
|
381
|
+
const key = licenseKey.trim().toUpperCase();
|
|
382
|
+
const response = await this.post('/v1/activate', {
|
|
383
|
+
licenseKey: key,
|
|
384
|
+
product: this.opts.product,
|
|
385
|
+
fingerprint,
|
|
386
|
+
machineName: machineName.slice(0, 80),
|
|
387
|
+
platform: platform(),
|
|
388
|
+
appVersion: this.opts.appVersion,
|
|
389
|
+
sdkVersion: SDK_VERSION,
|
|
390
|
+
...(await this.hardware()),
|
|
391
|
+
...this.deviceKey(),
|
|
392
|
+
});
|
|
393
|
+
const stored: Leased = { licenseKey: key, token: response.token, lastSeen: this.nowSec(), ...noticesFrom(response) };
|
|
394
|
+
const state = this.stateFromLease(stored, false);
|
|
395
|
+
if (state.status !== 'valid') throw new LicenseError(state.status === 'clock_suspect' ? 'clock_suspect' : state.reason ?? 'invalid', state.message ?? 'Server returned an unusable license');
|
|
396
|
+
await this.save(stored);
|
|
397
|
+
return state;
|
|
398
|
+
}
|
|
399
|
+
|
|
400
|
+
async check(): Promise<LicenseState> {
|
|
401
|
+
try {
|
|
402
|
+
await this.fingerprint();
|
|
403
|
+
} catch (e) {
|
|
404
|
+
// Nothing is changed on disk: the next check tries to read the id again.
|
|
405
|
+
if (e instanceof LicenseError && e.code === 'machine_id_unavailable') return this.emptyState('invalid', false, { reason: e.code, message: e.message });
|
|
406
|
+
throw e;
|
|
407
|
+
}
|
|
408
|
+
const stored = await this.load();
|
|
409
|
+
if (!stored) return this.emptyState('unlicensed', false);
|
|
410
|
+
if (stored.offline && stored.token) {
|
|
411
|
+
// Activated from an offline license file: the machine is not expected to reach the server.
|
|
412
|
+
const state = this.stateFromLease({ ...stored, token: stored.token }, true);
|
|
413
|
+
if (state.status === 'valid' || state.status === 'grace') {
|
|
414
|
+
await this.save({ ...stored, lastSeen: Math.max(stored.lastSeen ?? 0, this.nowSec()) });
|
|
415
|
+
}
|
|
416
|
+
return state;
|
|
417
|
+
}
|
|
418
|
+
try {
|
|
419
|
+
const response = await this.post('/v1/validate', {
|
|
420
|
+
licenseKey: stored.licenseKey,
|
|
421
|
+
product: this.opts.product,
|
|
422
|
+
fingerprint: this.fingerprintCache,
|
|
423
|
+
appVersion: this.opts.appVersion,
|
|
424
|
+
sdkVersion: SDK_VERSION,
|
|
425
|
+
...(await this.hardware()),
|
|
426
|
+
...this.deviceKey(),
|
|
427
|
+
});
|
|
428
|
+
const fresh: Leased = { licenseKey: stored.licenseKey, token: response.token, lastSeen: this.nowSec(), ...noticesFrom(response) };
|
|
429
|
+
await this.save(fresh);
|
|
430
|
+
return this.stateFromLease(fresh, false);
|
|
431
|
+
} catch (e) {
|
|
432
|
+
const keyHint = `${stored.licenseKey.slice(0, 7)}…${stored.licenseKey.slice(-4)}`;
|
|
433
|
+
if (e instanceof LicenseError && DEFINITIVE.has(e.code)) {
|
|
434
|
+
// Persist the refusal: drop the signed lease so going offline cannot bring the license back.
|
|
435
|
+
if (FORGET_KEY.has(e.code)) await this.clear();
|
|
436
|
+
else await this.save({ licenseKey: stored.licenseKey, lastSeen: stored.lastSeen, refused: { code: e.code, message: e.message, at: this.nowSec() } });
|
|
437
|
+
return this.emptyState('invalid', false, { reason: e.code, message: e.message, keyHint });
|
|
438
|
+
}
|
|
439
|
+
if (!stored.token) {
|
|
440
|
+
const refused = stored.refused ?? { code: 'not_activated', message: 'This device is not activated for this license' };
|
|
441
|
+
return this.emptyState('invalid', true, { reason: refused.code, message: refused.message, keyHint });
|
|
442
|
+
}
|
|
443
|
+
const state = this.stateFromLease({ ...stored, token: stored.token }, true);
|
|
444
|
+
if (state.status === 'valid' || state.status === 'grace') {
|
|
445
|
+
await this.save({ ...stored, lastSeen: Math.max(stored.lastSeen ?? 0, this.nowSec()) });
|
|
446
|
+
}
|
|
447
|
+
return state;
|
|
448
|
+
}
|
|
449
|
+
}
|
|
450
|
+
|
|
451
|
+
/**
|
|
452
|
+
* Decrypts data you encrypted for a feature (encryptForFeature in @carchalabs/seal-core, with the
|
|
453
|
+
* feature's content key from the console). Works offline: it uses the saved lease, which must be valid
|
|
454
|
+
* (or in its offline grace period), grant the feature and carry its key, and the saved license key.
|
|
455
|
+
* The native module does the work when it trusts this app's keys, so the content key never reaches
|
|
456
|
+
* JavaScript; without it the JavaScript implementation is used. Throws a LicenseError:
|
|
457
|
+
* `unlicensed`, a lease failure reason, `clock_suspect`, `feature_not_licensed` or `decrypt_failed`.
|
|
458
|
+
*/
|
|
459
|
+
async decrypt(feature: string, data: Uint8Array): Promise<Buffer> {
|
|
460
|
+
return (await this.opener(feature))(data);
|
|
461
|
+
}
|
|
462
|
+
|
|
463
|
+
/**
|
|
464
|
+
* Envelope: loads a CommonJS module you encrypted for a feature (seal-encrypt, one file or a
|
|
465
|
+
* folder) and returns its exports, like require(). The code is decrypted with the lease's feature key
|
|
466
|
+
* (see decrypt) and compiled from memory; it never exists as a plain file. Relative requires inside
|
|
467
|
+
* it load encrypted neighbours (`./x` finds `x.lke`, `x.js.lke` or `x/index.js.lke`), anything else
|
|
468
|
+
* goes to Node as usual. Loaded once per process, like require(). Throws the same LicenseErrors as
|
|
469
|
+
* decrypt. A licensed user can still read the code from memory: this keeps an app with the license
|
|
470
|
+
* check removed from having the feature, it does not hide the code from its licensed users.
|
|
471
|
+
*/
|
|
472
|
+
async requireEncrypted(feature: string, file: string): Promise<any> {
|
|
473
|
+
const open = await this.opener(feature);
|
|
474
|
+
return this.loadEncrypted(resolve(file), feature, open);
|
|
475
|
+
}
|
|
476
|
+
|
|
477
|
+
private readonly encryptedModules = new Map<string, { exports: any; filename: string; id: string; loaded: boolean }>();
|
|
478
|
+
|
|
479
|
+
private loadEncrypted(file: string, feature: string, open: (data: Uint8Array) => Buffer): any {
|
|
480
|
+
const cacheKey = `${feature}\0${file}`;
|
|
481
|
+
const cached = this.encryptedModules.get(cacheKey);
|
|
482
|
+
if (cached) return cached.exports;
|
|
483
|
+
const source = open(readFileSync(file)).toString('utf8');
|
|
484
|
+
const filename = file.replace(/\.lke$/, '');
|
|
485
|
+
const mod = { exports: {} as any, filename, id: filename, loaded: false };
|
|
486
|
+
// Registered before it runs, so a require cycle gets the partial exports, as in Node.
|
|
487
|
+
this.encryptedModules.set(cacheKey, mod);
|
|
488
|
+
const nodeRequire = createRequire(filename);
|
|
489
|
+
const localRequire = ((request: string) => {
|
|
490
|
+
if (request.startsWith('./') || request.startsWith('../')) {
|
|
491
|
+
const base = resolve(dirname(filename), request);
|
|
492
|
+
const encrypted = [`${base}.lke`, `${base}.js.lke`, join(base, 'index.js.lke')].find((candidate) => existsSync(candidate));
|
|
493
|
+
if (encrypted) return this.loadEncrypted(encrypted, feature, open);
|
|
494
|
+
}
|
|
495
|
+
return nodeRequire(request);
|
|
496
|
+
}) as NodeJS.Require;
|
|
497
|
+
Object.assign(localRequire, { resolve: nodeRequire.resolve, cache: nodeRequire.cache, main: nodeRequire.main, extensions: nodeRequire.extensions });
|
|
498
|
+
try {
|
|
499
|
+
const run = compileFunction(source, ['exports', 'require', 'module', '__filename', '__dirname'], { filename });
|
|
500
|
+
run.call(mod.exports, mod.exports, localRequire, mod, filename, dirname(filename));
|
|
501
|
+
} catch (e) {
|
|
502
|
+
this.encryptedModules.delete(cacheKey);
|
|
503
|
+
throw e;
|
|
504
|
+
}
|
|
505
|
+
mod.loaded = true;
|
|
506
|
+
return mod.exports;
|
|
507
|
+
}
|
|
508
|
+
|
|
509
|
+
/**
|
|
510
|
+
* Checks the saved lease once for a feature and returns a synchronous decrypter bound to it: decrypt
|
|
511
|
+
* uses it once, requireEncrypted for a module and the encrypted modules it requires.
|
|
512
|
+
*/
|
|
513
|
+
private async opener(feature: string): Promise<(data: Uint8Array) => Buffer> {
|
|
514
|
+
const fingerprintHash = await this.fingerprint();
|
|
515
|
+
const stored = await this.load();
|
|
516
|
+
if (!stored?.token) throw new LicenseError('unlicensed', 'This device has no license.');
|
|
517
|
+
const leased: Leased = { ...stored, token: stored.token };
|
|
518
|
+
const state = this.stateFromLease(leased, true);
|
|
519
|
+
if (state.status !== 'valid' && state.status !== 'grace') {
|
|
520
|
+
throw new LicenseError(state.status === 'clock_suspect' ? 'clock_suspect' : (state.reason ?? 'invalid'), state.message ?? 'The license is not valid.');
|
|
521
|
+
}
|
|
522
|
+
const claims = decodeLease(leased.token)?.claims;
|
|
523
|
+
const graceSeconds = state.status === 'grace' ? (claims?.grc ?? (this.opts.graceDays ?? DEFAULT_GRACE_DAYS) * 86400) : 0;
|
|
524
|
+
const check = { product: this.opts.product, fingerprintHash, now: this.nowSec(), ...(graceSeconds ? { graceSeconds } : {}) };
|
|
525
|
+
const native = this.native();
|
|
526
|
+
return (data: Uint8Array) => {
|
|
527
|
+
const result: { ok: boolean; data?: Buffer; reason?: string } =
|
|
528
|
+
native && typeof native.decryptFeature === 'function'
|
|
529
|
+
? native.decryptFeature(leased.token, check, leased.licenseKey, feature, Buffer.from(data))
|
|
530
|
+
: decryptFeature(leased.token, { keys: this.keys, ...check }, leased.licenseKey, feature, Buffer.from(data));
|
|
531
|
+
if (result.ok && result.data) return Buffer.from(result.data);
|
|
532
|
+
if (result.reason === 'not_licensed') throw new LicenseError('feature_not_licensed', `This license does not include "${feature}".`);
|
|
533
|
+
if (result.reason === 'decrypt_failed') throw new LicenseError('decrypt_failed', 'The data could not be decrypted with this license.');
|
|
534
|
+
throw new LicenseError(result.reason ?? 'invalid', REASON_TEXT[result.reason as LeaseFailure] ?? 'The license is not valid.');
|
|
535
|
+
};
|
|
536
|
+
}
|
|
537
|
+
|
|
538
|
+
/**
|
|
539
|
+
* Offline activation, step 1 on a machine that cannot reach the server: the request file (JSON text)
|
|
540
|
+
* the user takes to a connected device. The license server turns it into a license file at
|
|
541
|
+
* POST /v1/offline/activate (or its offline activation page). It holds what activate() would send:
|
|
542
|
+
* the license key, this device's fingerprint and hashed hardware parts, never raw serial numbers.
|
|
543
|
+
*/
|
|
544
|
+
async offlineRequest(licenseKey: string, machineName = hostname()): Promise<string> {
|
|
545
|
+
const fingerprint = await this.fingerprint();
|
|
546
|
+
const activation = {
|
|
547
|
+
licenseKey: licenseKey.trim().toUpperCase(),
|
|
548
|
+
product: this.opts.product,
|
|
549
|
+
fingerprint,
|
|
550
|
+
machineName: machineName.slice(0, 80),
|
|
551
|
+
platform: platform(),
|
|
552
|
+
appVersion: this.opts.appVersion,
|
|
553
|
+
sdkVersion: SDK_VERSION,
|
|
554
|
+
...(await this.hardware()),
|
|
555
|
+
...this.deviceKey(),
|
|
556
|
+
};
|
|
557
|
+
return JSON.stringify({ format: OFFLINE_REQUEST_FORMAT, version: 1, activation }, null, 2);
|
|
558
|
+
}
|
|
559
|
+
|
|
560
|
+
/**
|
|
561
|
+
* Offline activation, step 2: loads the license file the server issued for this machine's request.
|
|
562
|
+
* It is verified like an online lease (signature, product, this device) and then saved; from then on
|
|
563
|
+
* check() works without the server until the lease's renewal date plus the offline grace. Throws a
|
|
564
|
+
* LicenseError: `invalid_file`, `wrong_product`, or a lease failure reason such as `wrong_device`.
|
|
565
|
+
*/
|
|
566
|
+
async activateOffline(licenseFile: string): Promise<LicenseState> {
|
|
567
|
+
await this.fingerprint();
|
|
568
|
+
let file: any;
|
|
569
|
+
try {
|
|
570
|
+
file = JSON.parse(licenseFile);
|
|
571
|
+
} catch {
|
|
572
|
+
throw new LicenseError('invalid_file', 'This is not a Carcha Seal offline license file.');
|
|
573
|
+
}
|
|
574
|
+
if (!file || file.format !== OFFLINE_LICENSE_FORMAT || file.version !== 1 || typeof file.token !== 'string' || typeof file.licenseKey !== 'string') {
|
|
575
|
+
throw new LicenseError('invalid_file', 'This is not a Carcha Seal offline license file.');
|
|
576
|
+
}
|
|
577
|
+
if (file.product !== this.opts.product) throw new LicenseError('wrong_product', 'This offline license file is for another product.');
|
|
578
|
+
const stored: Leased = { licenseKey: file.licenseKey.trim().toUpperCase(), token: file.token, lastSeen: this.nowSec(), offline: true };
|
|
579
|
+
const state = this.stateFromLease(stored, true);
|
|
580
|
+
if (state.status !== 'valid') {
|
|
581
|
+
throw new LicenseError(state.status === 'clock_suspect' ? 'clock_suspect' : state.reason ?? 'invalid', state.message ?? 'This offline license file cannot be used on this computer.');
|
|
582
|
+
}
|
|
583
|
+
await this.save(stored);
|
|
584
|
+
return state;
|
|
585
|
+
}
|
|
586
|
+
|
|
587
|
+
/**
|
|
588
|
+
* Gives an offline machine's seat back: removes the license from this device and returns the
|
|
589
|
+
* deactivation file (JSON text) for the vendor, who frees the seat by uploading it in the console.
|
|
590
|
+
* Throws `unlicensed` when there is no license to remove.
|
|
591
|
+
*/
|
|
592
|
+
async deactivateOffline(): Promise<string> {
|
|
593
|
+
const stored = await this.load();
|
|
594
|
+
if (!stored?.token) throw new LicenseError('unlicensed', 'This device has no license.');
|
|
595
|
+
await this.clear();
|
|
596
|
+
return JSON.stringify({ format: OFFLINE_DEACTIVATION_FORMAT, version: 1, product: this.opts.product, token: stored.token }, null, 2);
|
|
597
|
+
}
|
|
598
|
+
|
|
599
|
+
async deactivate(): Promise<void> {
|
|
600
|
+
const stored = await this.load();
|
|
601
|
+
if (!stored) return;
|
|
602
|
+
try {
|
|
603
|
+
await this.post('/v1/deactivate', {
|
|
604
|
+
licenseKey: stored.licenseKey,
|
|
605
|
+
product: this.opts.product,
|
|
606
|
+
fingerprint: await this.fingerprint(),
|
|
607
|
+
...(await this.hardware()),
|
|
608
|
+
});
|
|
609
|
+
} catch (e) {
|
|
610
|
+
if (!(e instanceof LicenseError && (e.code === 'not_activated' || e.code === 'invalid_key'))) throw e;
|
|
611
|
+
}
|
|
612
|
+
await this.clear();
|
|
613
|
+
}
|
|
614
|
+
|
|
615
|
+
static hasFeature(state: LicenseState, feature: string): boolean {
|
|
616
|
+
return (state.status === 'valid' || state.status === 'grace') && state.features.includes(feature);
|
|
617
|
+
}
|
|
618
|
+
}
|
|
619
|
+
|
|
620
|
+
/** The SDK class under its earlier name (LicenseKit). Same class; use Seal in new code. */
|
|
621
|
+
export { Seal as LicenseKit };
|
|
622
|
+
/** @deprecated The options under the class's earlier name; use SealOptions. */
|
|
623
|
+
export type LicenseKitOptions = SealOptions;
|