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