@codeo-engineering/licenserail 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +26 -2
- package/dist/client.d.ts +97 -0
- package/dist/client.js +248 -0
- package/dist/core.d.ts +57 -0
- package/dist/core.js +107 -0
- package/dist/fingerprint.d.ts +3 -0
- package/dist/fingerprint.js +73 -0
- package/dist/index.d.ts +4 -0
- package/dist/index.js +4 -0
- package/dist/management.d.ts +58 -0
- package/dist/management.js +59 -0
- package/package.json +22 -4
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Codeo Solutions Limited
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,27 @@
|
|
|
1
|
-
#
|
|
1
|
+
# LicenseRail (TypeScript / Node / Electron)
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Client SDK for [LicenseRail](https://licenserail.com) licensing. MIT.
|
|
4
|
+
|
|
5
|
+
```sh
|
|
6
|
+
npm install @codeo-engineering/licenserail
|
|
7
|
+
```
|
|
8
|
+
|
|
9
|
+
```ts
|
|
10
|
+
import { LicenseClient } from '@codeo-engineering/licenserail'
|
|
11
|
+
|
|
12
|
+
const client = new LicenseClient({ serverUrl: 'https://api.licenserail.com', vendor: 'ten_6f1a7e2c3b4d4e5f8a9b0c1d2e3f4a5b', product: 'my-app', publicKeyPem, appVersion: '1.0.0' })
|
|
13
|
+
const result = await client.check() // offline check, refreshed online when due
|
|
14
|
+
if (!result.valid) console.log((await client.activate(licenseKey)).message)
|
|
15
|
+
const canExport = client.license?.hasFeature('export')
|
|
16
|
+
// await client.deactivate() frees the seat
|
|
17
|
+
```
|
|
18
|
+
|
|
19
|
+
- `check()` on every start: offline verification; online refresh when the token is due, or when only the server can clear the
|
|
20
|
+
state (expired, suspended, offline too long, clock problems).
|
|
21
|
+
- `activate(key)` on the license screen; floating licenses are checked out and kept alive automatically where the platform allows.
|
|
22
|
+
- `deactivate()` frees the seat (needs internet).
|
|
23
|
+
- On `license_not_found`, `license_suspended`, `license_revoked`, `license_expired`, `activation_revoked`, `wrong_machine` and
|
|
24
|
+
`invalid_token` the local license is removed; other errors (network, `402`) keep it.
|
|
25
|
+
- Get the public key with `licenserail public-key --pem` or `licenserail init typescript`.
|
|
26
|
+
|
|
27
|
+
Source: [licenserail-sdks](https://github.com/codeo-engineering/licenserail-sdks) (`typescript/`). Tests (shared vectors in `../test-vectors`): `npm test`.
|
package/dist/client.d.ts
ADDED
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
import { type Fingerprint, type LicensePayload, type LicenseStatus } from './core.js';
|
|
2
|
+
export interface LicenseClientOptions {
|
|
3
|
+
/** Base URL of the licensing service, e.g. https://api.licenserail.com */
|
|
4
|
+
serverUrl: string;
|
|
5
|
+
/** The product code from the dashboard. */
|
|
6
|
+
product: string;
|
|
7
|
+
/** Your organization ID from the dashboard (ten_...; part of every device identity). */
|
|
8
|
+
vendor: string;
|
|
9
|
+
/** The environment's public key (PEM); verifies license files offline. */
|
|
10
|
+
publicKeyPem: string;
|
|
11
|
+
/** Where the license file and run history live; default: a per-user folder. */
|
|
12
|
+
storageDir?: string;
|
|
13
|
+
appVersion?: string;
|
|
14
|
+
/** Refresh online on every check() (default false: only when the token says it is due). */
|
|
15
|
+
refreshOnStartup?: boolean;
|
|
16
|
+
/** Request timeout in milliseconds (default 10 s). */
|
|
17
|
+
timeoutMs?: number;
|
|
18
|
+
/** Overrides device fingerprinting (tests, custom hardware ids). */
|
|
19
|
+
fingerprint?: () => Fingerprint;
|
|
20
|
+
/** Overrides the clock (tests). */
|
|
21
|
+
now?: () => Date;
|
|
22
|
+
/** Overrides fetch (tests, proxies). */
|
|
23
|
+
fetch?: typeof fetch;
|
|
24
|
+
machineName?: string;
|
|
25
|
+
}
|
|
26
|
+
export interface ActivationResult {
|
|
27
|
+
success: boolean;
|
|
28
|
+
errorCode?: string;
|
|
29
|
+
message: string;
|
|
30
|
+
}
|
|
31
|
+
export interface CheckResult {
|
|
32
|
+
status: LicenseStatus;
|
|
33
|
+
valid: boolean;
|
|
34
|
+
license: License | null;
|
|
35
|
+
}
|
|
36
|
+
/** Read-only view of the current license. */
|
|
37
|
+
export declare class License {
|
|
38
|
+
readonly payload: LicensePayload;
|
|
39
|
+
constructor(payload: LicensePayload);
|
|
40
|
+
get key(): string;
|
|
41
|
+
get customer(): string;
|
|
42
|
+
get kind(): string;
|
|
43
|
+
get expiresAt(): Date | null;
|
|
44
|
+
get offlineUntil(): Date;
|
|
45
|
+
get isTest(): boolean;
|
|
46
|
+
get isFloating(): boolean;
|
|
47
|
+
get features(): string[];
|
|
48
|
+
get metadata(): Record<string, unknown>;
|
|
49
|
+
hasFeature(code: string): boolean;
|
|
50
|
+
}
|
|
51
|
+
/**
|
|
52
|
+
* The licensing client for a vendor's app: offline verification on every start, online refresh when due, activation,
|
|
53
|
+
* deactivation and floating leases. Never put an API key in client code; this class needs only the public key.
|
|
54
|
+
*/
|
|
55
|
+
export declare class LicenseClient {
|
|
56
|
+
private readonly options;
|
|
57
|
+
private readonly key;
|
|
58
|
+
private readonly dir;
|
|
59
|
+
private fp;
|
|
60
|
+
private heartbeat;
|
|
61
|
+
private warnedTest;
|
|
62
|
+
/** The last message from the server (e.g. why a license was removed). */
|
|
63
|
+
lastServerMessage: string | null;
|
|
64
|
+
constructor(options: LicenseClientOptions);
|
|
65
|
+
private now;
|
|
66
|
+
private fingerprint;
|
|
67
|
+
/** Whether a license for this device would match it again; if not, activating would only use up a seat. */
|
|
68
|
+
private identified;
|
|
69
|
+
private get tokenPath();
|
|
70
|
+
private get historyPath();
|
|
71
|
+
/** The current license after the last check, or null. */
|
|
72
|
+
get license(): License | null;
|
|
73
|
+
/** Offline evaluation only (no network). */
|
|
74
|
+
evaluateLocal(): CheckResult;
|
|
75
|
+
/** Call on startup: evaluates offline and refreshes online when due or when only the server can clear the state. */
|
|
76
|
+
check(): Promise<CheckResult>;
|
|
77
|
+
/** Activates `licenseKey` on this device (or checks out a floating lease if the license is floating). */
|
|
78
|
+
activate(licenseKey: string, machineName?: string): Promise<ActivationResult>;
|
|
79
|
+
/** Checks out a floating seat and keeps it alive with heartbeats until release(). */
|
|
80
|
+
checkout(licenseKey: string): Promise<ActivationResult>;
|
|
81
|
+
/** Releases a floating seat. */
|
|
82
|
+
release(): Promise<ActivationResult>;
|
|
83
|
+
/** Removes the license from this device and frees its seat on the server. */
|
|
84
|
+
deactivate(): Promise<ActivationResult>;
|
|
85
|
+
/** Asks the server for a fresh token now (floating licenses: a heartbeat). */
|
|
86
|
+
refresh(anomalies?: string[]): Promise<void>;
|
|
87
|
+
/** A user-facing sentence for a status. */
|
|
88
|
+
message(status: LicenseStatus): string;
|
|
89
|
+
private startHeartbeat;
|
|
90
|
+
private stopHeartbeat;
|
|
91
|
+
private post;
|
|
92
|
+
private saveIfValid;
|
|
93
|
+
private readPayload;
|
|
94
|
+
private clear;
|
|
95
|
+
private read;
|
|
96
|
+
private write;
|
|
97
|
+
}
|
package/dist/client.js
ADDED
|
@@ -0,0 +1,248 @@
|
|
|
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, evaluate, fingerprintMatches, importPublicKey, REVOKING_CODES, verifyToken, } from './core.js';
|
|
5
|
+
import { collectFingerprint } from './fingerprint.js';
|
|
6
|
+
const notIdentified = {
|
|
7
|
+
success: false, errorCode: 'device_not_identified', message: "This device can't be identified, so a license can't be activated on it.",
|
|
8
|
+
};
|
|
9
|
+
/** Read-only view of the current license. */
|
|
10
|
+
export class License {
|
|
11
|
+
payload;
|
|
12
|
+
constructor(payload) {
|
|
13
|
+
this.payload = payload;
|
|
14
|
+
}
|
|
15
|
+
get key() { return this.payload.licenseKey; }
|
|
16
|
+
get customer() { return this.payload.customer; }
|
|
17
|
+
get kind() { return this.payload.kind; }
|
|
18
|
+
get expiresAt() { return this.payload.expiresAt ? new Date(this.payload.expiresAt) : null; }
|
|
19
|
+
get offlineUntil() { return new Date(this.payload.offlineUntil); }
|
|
20
|
+
get isTest() { return this.payload.test === true; }
|
|
21
|
+
get isFloating() { return this.payload.floating === true; }
|
|
22
|
+
get features() { return this.payload.entitlements ?? []; }
|
|
23
|
+
get metadata() { return this.payload.metadata ?? {}; }
|
|
24
|
+
hasFeature(code) { return this.features.includes(code); }
|
|
25
|
+
}
|
|
26
|
+
const messages = {
|
|
27
|
+
Valid: 'The license is valid.',
|
|
28
|
+
Missing: 'No license is activated on this device.',
|
|
29
|
+
InvalidSignature: 'The license file is invalid. Activate it again.',
|
|
30
|
+
WrongProduct: 'The license is for another product.',
|
|
31
|
+
WrongMachine: 'The license belongs to another device.',
|
|
32
|
+
Expired: 'The license has expired.',
|
|
33
|
+
OfflineTooLong: 'Connect to the internet to verify the license.',
|
|
34
|
+
ClockTampered: "The device's clock looks wrong. Correct it and connect to the internet.",
|
|
35
|
+
Unverified: 'Connect to the internet to verify the license.',
|
|
36
|
+
Suspended: 'The license has been suspended.',
|
|
37
|
+
};
|
|
38
|
+
/**
|
|
39
|
+
* The licensing client for a vendor's app: offline verification on every start, online refresh when due, activation,
|
|
40
|
+
* deactivation and floating leases. Never put an API key in client code; this class needs only the public key.
|
|
41
|
+
*/
|
|
42
|
+
export class LicenseClient {
|
|
43
|
+
options;
|
|
44
|
+
key;
|
|
45
|
+
dir;
|
|
46
|
+
fp = null;
|
|
47
|
+
heartbeat = null;
|
|
48
|
+
warnedTest = false;
|
|
49
|
+
/** The last message from the server (e.g. why a license was removed). */
|
|
50
|
+
lastServerMessage = null;
|
|
51
|
+
constructor(options) {
|
|
52
|
+
if (!options.serverUrl || !options.vendor || !options.product || !options.publicKeyPem)
|
|
53
|
+
throw new Error('serverUrl, vendor, product and publicKeyPem are required.');
|
|
54
|
+
this.options = { timeoutMs: 10_000, ...options, serverUrl: options.serverUrl.replace(/\/+$/, '') };
|
|
55
|
+
this.key = importPublicKey(options.publicKeyPem);
|
|
56
|
+
this.dir = options.storageDir ?? defaultStorageDir(options.product);
|
|
57
|
+
}
|
|
58
|
+
now() { return this.options.now?.() ?? new Date(); }
|
|
59
|
+
fingerprint() { return (this.fp ??= this.options.fingerprint?.() ?? collectFingerprint(this.options.vendor, this.options.product)); }
|
|
60
|
+
/** Whether a license for this device would match it again; if not, activating would only use up a seat. */
|
|
61
|
+
identified() { return fingerprintMatches(this.fingerprint(), this.fingerprint()); }
|
|
62
|
+
get tokenPath() { return join(this.dir, 'license.lic'); }
|
|
63
|
+
get historyPath() { return join(this.dir, 'license.seen'); }
|
|
64
|
+
/** The current license after the last check, or null. */
|
|
65
|
+
get license() {
|
|
66
|
+
const p = this.readPayload();
|
|
67
|
+
return p ? new License(p) : null;
|
|
68
|
+
}
|
|
69
|
+
/** Offline evaluation only (no network). */
|
|
70
|
+
evaluateLocal() {
|
|
71
|
+
const token = this.read(this.tokenPath);
|
|
72
|
+
if (!token)
|
|
73
|
+
return { status: 'Missing', valid: false, license: null };
|
|
74
|
+
const payload = verifyToken(token, this.key);
|
|
75
|
+
const lastSeen = decodeRunHistory(this.read(this.historyPath), this.options.vendor, this.options.product, this.fingerprint());
|
|
76
|
+
const now = this.now();
|
|
77
|
+
const status = evaluate(payload, this.options.product, this.fingerprint(), now, lastSeen);
|
|
78
|
+
if ((status === 'Valid' || status === 'Expired' || status === 'OfflineTooLong') && (!lastSeen || now > lastSeen))
|
|
79
|
+
this.write(this.historyPath, encodeRunHistory(now, this.options.vendor, this.options.product, this.fingerprint()));
|
|
80
|
+
if (payload?.test && !this.warnedTest) {
|
|
81
|
+
this.warnedTest = true;
|
|
82
|
+
console.warn('[licenserail] Test license: not for production use.');
|
|
83
|
+
}
|
|
84
|
+
return { status, valid: status === 'Valid', license: payload ? new License(payload) : null };
|
|
85
|
+
}
|
|
86
|
+
/** Call on startup: evaluates offline and refreshes online when due or when only the server can clear the state. */
|
|
87
|
+
async check() {
|
|
88
|
+
let result = this.evaluateLocal();
|
|
89
|
+
const due = result.valid && (this.options.refreshOnStartup || this.now() >= new Date(result.license.payload.refreshAfter));
|
|
90
|
+
if (due || ['Expired', 'Suspended', 'OfflineTooLong', 'ClockTampered', 'Unverified'].includes(result.status)) {
|
|
91
|
+
try {
|
|
92
|
+
await this.refresh(result.status === 'ClockTampered' ? ['clock_rollback'] : result.status === 'Unverified' ? ['history_missing'] : undefined);
|
|
93
|
+
}
|
|
94
|
+
catch {
|
|
95
|
+
// offline: the local result stands until offlineUntil
|
|
96
|
+
}
|
|
97
|
+
result = this.evaluateLocal();
|
|
98
|
+
}
|
|
99
|
+
return result;
|
|
100
|
+
}
|
|
101
|
+
/** Activates `licenseKey` on this device (or checks out a floating lease if the license is floating). */
|
|
102
|
+
async activate(licenseKey, machineName) {
|
|
103
|
+
if (!licenseKey?.trim())
|
|
104
|
+
return { success: false, errorCode: 'bad_request', message: 'Enter the license key.' };
|
|
105
|
+
if (!this.identified())
|
|
106
|
+
return notIdentified;
|
|
107
|
+
const body = {
|
|
108
|
+
licenseKey: licenseKey.trim(), product: this.options.product, fingerprint: this.fingerprint(),
|
|
109
|
+
machineName: machineName ?? this.options.machineName ?? hostname(), appVersion: this.options.appVersion ?? null,
|
|
110
|
+
};
|
|
111
|
+
let r = await this.post('/api/client/v2/activate', body).catch(() => null);
|
|
112
|
+
if (r && !r.ok && r.error?.code === 'bad_request' && /floating/i.test(r.error.message))
|
|
113
|
+
r = await this.post('/api/client/v2/floating/checkout', body).catch(() => null);
|
|
114
|
+
if (!r)
|
|
115
|
+
return { success: false, errorCode: 'network', message: 'Could not connect to the license server.' };
|
|
116
|
+
if (!r.ok)
|
|
117
|
+
return { success: false, errorCode: r.error?.code, message: r.error?.message ?? `Server error (${r.status}).` };
|
|
118
|
+
if (!this.saveIfValid(r.token))
|
|
119
|
+
return { success: false, errorCode: 'invalid_token', message: 'The server returned an invalid license.' };
|
|
120
|
+
const result = this.evaluateLocal();
|
|
121
|
+
if (result.license?.isFloating)
|
|
122
|
+
this.startHeartbeat();
|
|
123
|
+
return result.valid ? { success: true, message: 'The license has been activated.' } : { success: false, errorCode: result.status, message: messages[result.status] };
|
|
124
|
+
}
|
|
125
|
+
/** Checks out a floating seat and keeps it alive with heartbeats until release(). */
|
|
126
|
+
async checkout(licenseKey) {
|
|
127
|
+
if (!this.identified())
|
|
128
|
+
return notIdentified;
|
|
129
|
+
const body = { licenseKey: licenseKey.trim(), product: this.options.product, fingerprint: this.fingerprint(), machineName: this.options.machineName ?? hostname(), appVersion: this.options.appVersion ?? null };
|
|
130
|
+
const r = await this.post('/api/client/v2/floating/checkout', body).catch(() => null);
|
|
131
|
+
if (!r)
|
|
132
|
+
return { success: false, errorCode: 'network', message: 'Could not connect to the license server.' };
|
|
133
|
+
if (!r.ok)
|
|
134
|
+
return { success: false, errorCode: r.error?.code, message: r.error?.message ?? `Server error (${r.status}).` };
|
|
135
|
+
this.saveIfValid(r.token);
|
|
136
|
+
this.startHeartbeat();
|
|
137
|
+
return { success: true, message: 'Floating license checked out.' };
|
|
138
|
+
}
|
|
139
|
+
/** Releases a floating seat. */
|
|
140
|
+
async release() {
|
|
141
|
+
this.stopHeartbeat();
|
|
142
|
+
return this.deactivate();
|
|
143
|
+
}
|
|
144
|
+
/** Removes the license from this device and frees its seat on the server. */
|
|
145
|
+
async deactivate() {
|
|
146
|
+
this.stopHeartbeat();
|
|
147
|
+
const token = this.read(this.tokenPath);
|
|
148
|
+
if (!token)
|
|
149
|
+
return { success: true, message: 'There is no license on this device.' };
|
|
150
|
+
const floating = verifyToken(token, this.key)?.floating === true;
|
|
151
|
+
const r = await this.post(floating ? '/api/client/v2/floating/release' : '/api/client/v2/deactivate', { token, fingerprint: this.fingerprint() }).catch(() => null);
|
|
152
|
+
if (!r)
|
|
153
|
+
return { success: false, errorCode: 'network', message: 'Removing the license needs an internet connection.' };
|
|
154
|
+
if (!r.ok && !(r.error && REVOKING_CODES.has(r.error.code)))
|
|
155
|
+
return { success: false, errorCode: r.error?.code, message: r.error?.message ?? `Server error (${r.status}).` };
|
|
156
|
+
this.clear();
|
|
157
|
+
return r.ok || r.error?.code !== 'wrong_machine'
|
|
158
|
+
? { success: true, message: 'The license has been removed from this device.' }
|
|
159
|
+
: { success: false, errorCode: 'wrong_machine', message: r.error.message };
|
|
160
|
+
}
|
|
161
|
+
/** Asks the server for a fresh token now (floating licenses: a heartbeat). */
|
|
162
|
+
async refresh(anomalies) {
|
|
163
|
+
const token = this.read(this.tokenPath);
|
|
164
|
+
if (!token)
|
|
165
|
+
return;
|
|
166
|
+
const floating = verifyToken(token, this.key)?.floating === true;
|
|
167
|
+
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 });
|
|
168
|
+
if (r.ok)
|
|
169
|
+
this.saveIfValid(r.token);
|
|
170
|
+
else if (r.error && REVOKING_CODES.has(r.error.code)) {
|
|
171
|
+
this.clear();
|
|
172
|
+
this.lastServerMessage = r.error.message;
|
|
173
|
+
}
|
|
174
|
+
else if (r.error?.code === 'lease_expired') {
|
|
175
|
+
this.clear();
|
|
176
|
+
this.lastServerMessage = r.error.message;
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
/** A user-facing sentence for a status. */
|
|
180
|
+
message(status) {
|
|
181
|
+
return status === 'Missing' && this.lastServerMessage ? this.lastServerMessage : messages[status];
|
|
182
|
+
}
|
|
183
|
+
startHeartbeat() {
|
|
184
|
+
this.stopHeartbeat();
|
|
185
|
+
const payload = this.readPayload();
|
|
186
|
+
if (!payload?.floating)
|
|
187
|
+
return;
|
|
188
|
+
const half = Math.max(30_000, (Date.parse(payload.offlineUntil) - Date.parse(payload.issuedAt)) / 2);
|
|
189
|
+
this.heartbeat = setInterval(() => void this.refresh().catch(() => undefined), half);
|
|
190
|
+
this.heartbeat.unref?.();
|
|
191
|
+
}
|
|
192
|
+
stopHeartbeat() {
|
|
193
|
+
if (this.heartbeat)
|
|
194
|
+
clearInterval(this.heartbeat);
|
|
195
|
+
this.heartbeat = null;
|
|
196
|
+
}
|
|
197
|
+
async post(path, body) {
|
|
198
|
+
const controller = new AbortController();
|
|
199
|
+
const timer = setTimeout(() => controller.abort(), this.options.timeoutMs);
|
|
200
|
+
try {
|
|
201
|
+
const res = await (this.options.fetch ?? fetch)(this.options.serverUrl + path, {
|
|
202
|
+
method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body), signal: controller.signal,
|
|
203
|
+
});
|
|
204
|
+
const text = await res.text();
|
|
205
|
+
const json = text ? JSON.parse(text) : {};
|
|
206
|
+
return res.ok ? { ok: true, status: res.status, token: json.token } : { ok: false, status: res.status, error: json.code ? json : undefined };
|
|
207
|
+
}
|
|
208
|
+
finally {
|
|
209
|
+
clearTimeout(timer);
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
saveIfValid(token) {
|
|
213
|
+
const payload = verifyToken(token, this.key);
|
|
214
|
+
if (!payload || payload.product.toLowerCase() !== this.options.product.toLowerCase())
|
|
215
|
+
return false;
|
|
216
|
+
this.write(this.tokenPath, token);
|
|
217
|
+
this.write(this.historyPath, encodeRunHistory(this.now(), this.options.vendor, this.options.product, this.fingerprint()));
|
|
218
|
+
return true;
|
|
219
|
+
}
|
|
220
|
+
readPayload() {
|
|
221
|
+
const token = this.read(this.tokenPath);
|
|
222
|
+
return token ? verifyToken(token, this.key) : null;
|
|
223
|
+
}
|
|
224
|
+
clear() {
|
|
225
|
+
for (const p of [this.tokenPath])
|
|
226
|
+
rmSync(p, { force: true });
|
|
227
|
+
}
|
|
228
|
+
read(path) {
|
|
229
|
+
try {
|
|
230
|
+
return readFileSync(path, 'utf8').trim() || null;
|
|
231
|
+
}
|
|
232
|
+
catch {
|
|
233
|
+
return null;
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
write(path, value) {
|
|
237
|
+
mkdirSync(this.dir, { recursive: true });
|
|
238
|
+
writeFileSync(path, value, 'utf8');
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
function defaultStorageDir(product) {
|
|
242
|
+
const base = platform() === 'win32'
|
|
243
|
+
? process.env.LOCALAPPDATA ?? join(homedir(), 'AppData', 'Local')
|
|
244
|
+
: platform() === 'darwin'
|
|
245
|
+
? join(homedir(), 'Library', 'Application Support')
|
|
246
|
+
: process.env.XDG_DATA_HOME ?? join(homedir(), '.local', 'share');
|
|
247
|
+
return join(base, 'licenserail', product);
|
|
248
|
+
}
|
package/dist/core.d.ts
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
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
|
+
/** The signed license content (token payload). v2 fields are optional. */
|
|
12
|
+
export interface LicensePayload {
|
|
13
|
+
licenseId: string;
|
|
14
|
+
activationId: string;
|
|
15
|
+
licenseKey: string;
|
|
16
|
+
product: string;
|
|
17
|
+
customer: string;
|
|
18
|
+
kind: 'full' | 'trial' | string;
|
|
19
|
+
expiresAt: string | null;
|
|
20
|
+
issuedAt: string;
|
|
21
|
+
refreshAfter: string;
|
|
22
|
+
offlineUntil: string;
|
|
23
|
+
fingerprint: Fingerprint;
|
|
24
|
+
suspended: boolean;
|
|
25
|
+
environmentId?: string;
|
|
26
|
+
test?: boolean;
|
|
27
|
+
entitlements?: string[];
|
|
28
|
+
metadata?: Record<string, unknown>;
|
|
29
|
+
floating?: boolean;
|
|
30
|
+
leaseExpiresAt?: string;
|
|
31
|
+
}
|
|
32
|
+
export type LicenseStatus = 'Valid' | 'Missing' | 'InvalidSignature' | 'WrongProduct' | 'WrongMachine' | 'Expired' | 'OfflineTooLong' | 'ClockTampered' | 'Unverified' | 'Suspended';
|
|
33
|
+
export declare const UNAVAILABLE = "none";
|
|
34
|
+
/** The clock going back slightly during NTP sync is normal. */
|
|
35
|
+
export declare const CLOCK_TOLERANCE_MS: number;
|
|
36
|
+
/** The device clock may lag the server; a token "from the future" by less than this is accepted. */
|
|
37
|
+
export declare const ISSUED_AT_TOLERANCE_MS: number;
|
|
38
|
+
/** Error codes on which the local license is deleted; on any other error (network, 402…) it is kept. */
|
|
39
|
+
export declare const REVOKING_CODES: Set<string>;
|
|
40
|
+
export declare function importPublicKey(pem: string): KeyObject;
|
|
41
|
+
/**
|
|
42
|
+
* Verifies `base64url(json).base64url(signature)` (ECDSA P-256 / SHA-256, IEEE P1363 r||s) over the ASCII bytes of the encoded
|
|
43
|
+
* body and returns the payload, or null if the signature or format is invalid.
|
|
44
|
+
*/
|
|
45
|
+
export declare function verifyToken(token: string, publicKey: KeyObject | string): LicensePayload | null;
|
|
46
|
+
/**
|
|
47
|
+
* component = hex(SHA256(vendor + ":" + product + ":" + part + ":" + upper(trim(raw)))); blank → "none".
|
|
48
|
+
* `vendor` is the organization ID from the dashboard (ten_...); it never changes, so device identities stay stable.
|
|
49
|
+
*/
|
|
50
|
+
export declare function hashComponent(vendor: string, product: string, part: 'machine' | 'disk' | 'host' | 'board', raw: string | null | undefined): string;
|
|
51
|
+
/** Whether `presented` is the device `registered` was issued for (call on the registered fingerprint). */
|
|
52
|
+
export declare function fingerprintMatches(registered: Fingerprint, presented: Fingerprint): boolean;
|
|
53
|
+
/** Offline check, identical in every SDK (see the shared test vectors). */
|
|
54
|
+
export declare function evaluate(payload: LicensePayload | null, product: string, machine: Fingerprint, now: Date, lastSeen: Date | null): LicenseStatus;
|
|
55
|
+
/** Tamper-evident "last run" record: `{epochMs}.{hmac}` keyed to the product and device. */
|
|
56
|
+
export declare function encodeRunHistory(at: Date, vendor: string, product: string, machine: Fingerprint): string;
|
|
57
|
+
export declare function decodeRunHistory(value: string | null | undefined, vendor: string, product: string, machine: Fingerprint): Date | null;
|
package/dist/core.js
ADDED
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
import { createHash, createHmac, createPublicKey, timingSafeEqual, verify as cryptoVerify } from 'node:crypto';
|
|
2
|
+
export const UNAVAILABLE = 'none';
|
|
3
|
+
/** The clock going back slightly during NTP sync is normal. */
|
|
4
|
+
export const CLOCK_TOLERANCE_MS = 10 * 60 * 1000;
|
|
5
|
+
/** The device clock may lag the server; a token "from the future" by less than this is accepted. */
|
|
6
|
+
export const ISSUED_AT_TOLERANCE_MS = 24 * 60 * 60 * 1000;
|
|
7
|
+
/** Error codes on which the local license is deleted; on any other error (network, 402…) it is kept. */
|
|
8
|
+
export const REVOKING_CODES = new Set([
|
|
9
|
+
'license_not_found', 'license_suspended', 'license_expired', 'activation_revoked', 'wrong_machine', 'invalid_token', 'license_revoked',
|
|
10
|
+
]);
|
|
11
|
+
function fromBase64Url(text) {
|
|
12
|
+
if (!/^[A-Za-z0-9_-]*$/.test(text) || text.length % 4 === 1)
|
|
13
|
+
throw new Error('invalid base64url');
|
|
14
|
+
return Buffer.from(text, 'base64url');
|
|
15
|
+
}
|
|
16
|
+
export function importPublicKey(pem) {
|
|
17
|
+
return createPublicKey({ key: pem, format: 'pem' });
|
|
18
|
+
}
|
|
19
|
+
/**
|
|
20
|
+
* Verifies `base64url(json).base64url(signature)` (ECDSA P-256 / SHA-256, IEEE P1363 r||s) over the ASCII bytes of the encoded
|
|
21
|
+
* body and returns the payload, or null if the signature or format is invalid.
|
|
22
|
+
*/
|
|
23
|
+
export function verifyToken(token, publicKey) {
|
|
24
|
+
if (!token || typeof token !== 'string')
|
|
25
|
+
return null;
|
|
26
|
+
const parts = token.trim().split('.');
|
|
27
|
+
if (parts.length !== 2)
|
|
28
|
+
return null;
|
|
29
|
+
try {
|
|
30
|
+
const key = typeof publicKey === 'string' ? importPublicKey(publicKey) : publicKey;
|
|
31
|
+
const signature = fromBase64Url(parts[1]);
|
|
32
|
+
if (signature.length !== 64)
|
|
33
|
+
return null;
|
|
34
|
+
const ok = cryptoVerify('sha256', Buffer.from(parts[0], 'ascii'), { key, dsaEncoding: 'ieee-p1363' }, signature);
|
|
35
|
+
if (!ok)
|
|
36
|
+
return null;
|
|
37
|
+
const payload = JSON.parse(fromBase64Url(parts[0]).toString('utf8'));
|
|
38
|
+
return payload && typeof payload === 'object' && payload.fingerprint ? payload : null;
|
|
39
|
+
}
|
|
40
|
+
catch {
|
|
41
|
+
return null;
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
/**
|
|
45
|
+
* component = hex(SHA256(vendor + ":" + product + ":" + part + ":" + upper(trim(raw)))); blank → "none".
|
|
46
|
+
* `vendor` is the organization ID from the dashboard (ten_...); it never changes, so device identities stay stable.
|
|
47
|
+
*/
|
|
48
|
+
export function hashComponent(vendor, product, part, raw) {
|
|
49
|
+
if (raw == null || raw.trim() === '')
|
|
50
|
+
return UNAVAILABLE;
|
|
51
|
+
return createHash('sha256').update(`${vendor}:${product}:${part}:${raw.trim().toUpperCase()}`, 'utf8').digest('hex');
|
|
52
|
+
}
|
|
53
|
+
const available = (v) => !!v && v !== UNAVAILABLE;
|
|
54
|
+
const same = (a, b) => available(a) && a === b;
|
|
55
|
+
/** Whether `presented` is the device `registered` was issued for (call on the registered fingerprint). */
|
|
56
|
+
export function fingerprintMatches(registered, presented) {
|
|
57
|
+
if (registered.os && presented.os && registered.os.toLowerCase() !== presented.os.toLowerCase())
|
|
58
|
+
return false;
|
|
59
|
+
let matches = 0;
|
|
60
|
+
if (same(registered.machineId, presented.machineId))
|
|
61
|
+
matches++;
|
|
62
|
+
if (same(registered.diskId, presented.diskId))
|
|
63
|
+
matches++;
|
|
64
|
+
if (same(registered.hostName, presented.hostName))
|
|
65
|
+
matches++;
|
|
66
|
+
return available(registered.boardId) ? same(registered.boardId, presented.boardId) && matches >= 1 : matches >= 2;
|
|
67
|
+
}
|
|
68
|
+
/** Offline check, identical in every SDK (see the shared test vectors). */
|
|
69
|
+
export function evaluate(payload, product, machine, now, lastSeen) {
|
|
70
|
+
if (!payload)
|
|
71
|
+
return 'InvalidSignature';
|
|
72
|
+
if (payload.product.toLowerCase() !== product.toLowerCase())
|
|
73
|
+
return 'WrongProduct';
|
|
74
|
+
if (!fingerprintMatches(payload.fingerprint, machine))
|
|
75
|
+
return 'WrongMachine';
|
|
76
|
+
if (payload.suspended)
|
|
77
|
+
return 'Suspended';
|
|
78
|
+
if (!lastSeen)
|
|
79
|
+
return 'Unverified';
|
|
80
|
+
const t = now.getTime();
|
|
81
|
+
if (t + ISSUED_AT_TOLERANCE_MS < Date.parse(payload.issuedAt) || t + CLOCK_TOLERANCE_MS < lastSeen.getTime())
|
|
82
|
+
return 'ClockTampered';
|
|
83
|
+
if (payload.expiresAt && t >= Date.parse(payload.expiresAt))
|
|
84
|
+
return 'Expired';
|
|
85
|
+
if (t >= Date.parse(payload.offlineUntil))
|
|
86
|
+
return 'OfflineTooLong';
|
|
87
|
+
return 'Valid';
|
|
88
|
+
}
|
|
89
|
+
/** Tamper-evident "last run" record: `{epochMs}.{hmac}` keyed to the product and device. */
|
|
90
|
+
export function encodeRunHistory(at, vendor, product, machine) {
|
|
91
|
+
const ms = String(at.getTime());
|
|
92
|
+
return `${ms}.${historyMac(ms, vendor, product, machine)}`;
|
|
93
|
+
}
|
|
94
|
+
export function decodeRunHistory(value, vendor, product, machine) {
|
|
95
|
+
const parts = value?.trim().split('.');
|
|
96
|
+
if (!parts || parts.length !== 2 || !/^\d{1,15}$/.test(parts[0]))
|
|
97
|
+
return null;
|
|
98
|
+
const expected = Buffer.from(historyMac(parts[0], vendor, product, machine));
|
|
99
|
+
const actual = Buffer.from(parts[1]);
|
|
100
|
+
if (expected.length !== actual.length || !timingSafeEqual(expected, actual))
|
|
101
|
+
return null;
|
|
102
|
+
return new Date(Number(parts[0]));
|
|
103
|
+
}
|
|
104
|
+
function historyMac(ms, vendor, product, machine) {
|
|
105
|
+
const key = createHash('sha256').update(`${vendor}:run-history:${product}:${machine.machineId}:${machine.boardId}`).digest();
|
|
106
|
+
return createHmac('sha256', key).update(ms).digest('hex').slice(0, 32).toUpperCase();
|
|
107
|
+
}
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
import { execFileSync } from 'node:child_process';
|
|
2
|
+
import { existsSync, readFileSync } from 'node:fs';
|
|
3
|
+
import { hostname, platform } from 'node:os';
|
|
4
|
+
import { hashComponent } from './core.js';
|
|
5
|
+
function run(cmd, args) {
|
|
6
|
+
try {
|
|
7
|
+
return execFileSync(cmd, args, { encoding: 'utf8', timeout: 5000, windowsHide: true, stdio: ['ignore', 'pipe', 'ignore'] });
|
|
8
|
+
}
|
|
9
|
+
catch {
|
|
10
|
+
return null;
|
|
11
|
+
}
|
|
12
|
+
}
|
|
13
|
+
function readFirst(...paths) {
|
|
14
|
+
for (const p of paths) {
|
|
15
|
+
try {
|
|
16
|
+
if (existsSync(p)) {
|
|
17
|
+
const v = readFileSync(p, 'utf8').trim();
|
|
18
|
+
if (v)
|
|
19
|
+
return v;
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
catch {
|
|
23
|
+
// not readable (often root-only)
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
return null;
|
|
27
|
+
}
|
|
28
|
+
/** SMBIOS placeholders some vendors ship instead of a real UUID. */
|
|
29
|
+
const placeholder = (v) => !v || /^[0F-]+$/i.test(v.replace(/-/g, '')) || /^(03000200-0400-0500-0006-000700080009|FFFFFFFF-FFFF-FFFF-FFFF-FFFFFFFFFFFF)$/i.test(v);
|
|
30
|
+
function windows() {
|
|
31
|
+
const reg = run('reg', ['query', 'HKLM\\SOFTWARE\\Microsoft\\Cryptography', '/v', 'MachineGuid', '/reg:64']);
|
|
32
|
+
const machine = reg?.match(/MachineGuid\s+REG_SZ\s+(\S+)/i)?.[1] ?? null;
|
|
33
|
+
const vol = run('cmd', ['/c', 'vol', process.env.SystemDrive ?? 'C:']);
|
|
34
|
+
const serial = vol?.match(/([0-9A-F]{4})-([0-9A-F]{4})/i);
|
|
35
|
+
const disk = serial ? `${serial[1]}${serial[2]}`.toUpperCase() : null;
|
|
36
|
+
const uuidOut = run('powershell', ['-NoProfile', '-Command', '(Get-CimInstance Win32_ComputerSystemProduct).UUID'])?.trim() ?? null;
|
|
37
|
+
return [machine, disk, hostname(), placeholder(uuidOut) ? null : uuidOut];
|
|
38
|
+
}
|
|
39
|
+
function macos() {
|
|
40
|
+
const io = run('ioreg', ['-rd1', '-c', 'IOPlatformExpertDevice']) ?? '';
|
|
41
|
+
const platformUuid = io.match(/"IOPlatformUUID"\s*=\s*"([^"]+)"/)?.[1] ?? null;
|
|
42
|
+
const serial = io.match(/"IOPlatformSerialNumber"\s*=\s*"([^"]+)"/)?.[1] ?? null;
|
|
43
|
+
const diskInfo = run('diskutil', ['info', '/']) ?? '';
|
|
44
|
+
const volume = diskInfo.match(/Volume UUID:\s*([0-9A-F-]+)/i)?.[1] ?? null;
|
|
45
|
+
const host = run('scutil', ['--get', 'LocalHostName'])?.trim() || hostname();
|
|
46
|
+
// machine = hardware serial (independent of the board UUID, so 2 signals remain), board = IOPlatformUUID.
|
|
47
|
+
return [serial, volume, host, platformUuid];
|
|
48
|
+
}
|
|
49
|
+
function linux() {
|
|
50
|
+
const machine = readFirst('/etc/machine-id', '/var/lib/dbus/machine-id');
|
|
51
|
+
let disk = null;
|
|
52
|
+
const mounts = readFirst('/proc/self/mountinfo');
|
|
53
|
+
const root = mounts?.split('\n').map((l) => l.split(' ')).find((f) => f[4] === '/');
|
|
54
|
+
const device = root ? root[root.indexOf('-') + 2] : null;
|
|
55
|
+
if (device) {
|
|
56
|
+
const out = run('blkid', ['-s', 'UUID', '-o', 'value', device])?.trim();
|
|
57
|
+
disk = out || null;
|
|
58
|
+
}
|
|
59
|
+
const board = readFirst('/sys/class/dmi/id/product_uuid');
|
|
60
|
+
return [machine, disk, hostname(), placeholder(board) ? null : board];
|
|
61
|
+
}
|
|
62
|
+
/** Collects and hashes the device fingerprint for `vendor` (organization ID) and `product` (Windows, macOS, Linux). */
|
|
63
|
+
export function collectFingerprint(vendor, product) {
|
|
64
|
+
const os = platform() === 'win32' ? 'windows' : platform() === 'darwin' ? 'macos' : 'linux';
|
|
65
|
+
const [m, d, h, b] = os === 'windows' ? windows() : os === 'macos' ? macos() : linux();
|
|
66
|
+
return {
|
|
67
|
+
machineId: hashComponent(vendor, product, 'machine', m),
|
|
68
|
+
diskId: hashComponent(vendor, product, 'disk', d),
|
|
69
|
+
hostName: hashComponent(vendor, product, 'host', h),
|
|
70
|
+
boardId: hashComponent(vendor, product, 'board', b),
|
|
71
|
+
os,
|
|
72
|
+
};
|
|
73
|
+
}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
export * from './core.js';
|
|
2
|
+
export { collectFingerprint } from './fingerprint.js';
|
|
3
|
+
export { License, LicenseClient, type ActivationResult, type CheckResult, type LicenseClientOptions } from './client.js';
|
|
4
|
+
export { ApiRequestError, ManagementClient, verifyWebhook, type ManagementOptions } from './management.js';
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Server-side client for the management API (/api/v2). Needs a secret API key: never ship it in an app.
|
|
3
|
+
* Every operation of /openapi.json is reachable through `request`; the common ones have typed helpers.
|
|
4
|
+
*/
|
|
5
|
+
export interface ManagementOptions {
|
|
6
|
+
apiKey: string;
|
|
7
|
+
baseUrl?: string;
|
|
8
|
+
/** For access tokens (not API keys): "test" (default) or "live". */
|
|
9
|
+
environment?: 'test' | 'live';
|
|
10
|
+
fetch?: typeof fetch;
|
|
11
|
+
}
|
|
12
|
+
export declare class ApiRequestError extends Error {
|
|
13
|
+
readonly status: number;
|
|
14
|
+
readonly code: string;
|
|
15
|
+
readonly body: unknown;
|
|
16
|
+
constructor(status: number, code: string, message: string, body: unknown);
|
|
17
|
+
}
|
|
18
|
+
export declare class ManagementClient {
|
|
19
|
+
private readonly options;
|
|
20
|
+
private readonly base;
|
|
21
|
+
constructor(options: ManagementOptions);
|
|
22
|
+
request<T = any>(method: string, path: string, body?: unknown, headers?: Record<string, string>): Promise<T>;
|
|
23
|
+
createProduct: (body: {
|
|
24
|
+
code: string;
|
|
25
|
+
name: string;
|
|
26
|
+
offlineGraceDays?: number;
|
|
27
|
+
metadata?: Record<string, unknown>;
|
|
28
|
+
}) => Promise<any>;
|
|
29
|
+
listProducts: () => Promise<any>;
|
|
30
|
+
createCustomer: (body: {
|
|
31
|
+
name: string;
|
|
32
|
+
email?: string;
|
|
33
|
+
contactName?: string;
|
|
34
|
+
metadata?: Record<string, unknown>;
|
|
35
|
+
}) => Promise<any>;
|
|
36
|
+
createLicenses: (body: {
|
|
37
|
+
productId: string;
|
|
38
|
+
customerId: string;
|
|
39
|
+
kind?: "full" | "trial";
|
|
40
|
+
expiresAt?: string | null;
|
|
41
|
+
maxActivations?: number;
|
|
42
|
+
isFloating?: boolean;
|
|
43
|
+
leaseMinutes?: number;
|
|
44
|
+
features?: string[];
|
|
45
|
+
metadata?: Record<string, unknown>;
|
|
46
|
+
quantity?: number;
|
|
47
|
+
licensee?: string;
|
|
48
|
+
notes?: string;
|
|
49
|
+
}) => Promise<any>;
|
|
50
|
+
getLicense: (id: string) => Promise<any>;
|
|
51
|
+
updateLicense: (id: string, patch: Record<string, unknown>) => Promise<any>;
|
|
52
|
+
suspendLicense: (id: string) => Promise<any>;
|
|
53
|
+
resumeLicense: (id: string) => Promise<any>;
|
|
54
|
+
revokeLicense: (id: string, approvalId?: string) => Promise<any>;
|
|
55
|
+
listEvents: (type?: string) => Promise<any>;
|
|
56
|
+
}
|
|
57
|
+
/** Verifies a Standard Webhooks signature (webhook-id, webhook-timestamp, webhook-signature) with the endpoint secret. */
|
|
58
|
+
export declare function verifyWebhook(secret: string, headers: Record<string, string | undefined>, body: string, toleranceSeconds?: number): Promise<boolean>;
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
export class ApiRequestError extends Error {
|
|
2
|
+
status;
|
|
3
|
+
code;
|
|
4
|
+
body;
|
|
5
|
+
constructor(status, code, message, body) {
|
|
6
|
+
super(message);
|
|
7
|
+
this.status = status;
|
|
8
|
+
this.code = code;
|
|
9
|
+
this.body = body;
|
|
10
|
+
}
|
|
11
|
+
}
|
|
12
|
+
export class ManagementClient {
|
|
13
|
+
options;
|
|
14
|
+
base;
|
|
15
|
+
constructor(options) {
|
|
16
|
+
this.options = options;
|
|
17
|
+
this.base = (options.baseUrl ?? 'https://api.licenserail.com').replace(/\/+$/, '');
|
|
18
|
+
}
|
|
19
|
+
async request(method, path, body, headers = {}) {
|
|
20
|
+
const h = { Authorization: `Bearer ${this.options.apiKey}`, ...headers };
|
|
21
|
+
if (this.options.environment)
|
|
22
|
+
h['X-Environment'] = this.options.environment;
|
|
23
|
+
if (body !== undefined)
|
|
24
|
+
h['Content-Type'] = 'application/json';
|
|
25
|
+
if (method !== 'GET' && !h['Idempotency-Key'])
|
|
26
|
+
h['Idempotency-Key'] = crypto.randomUUID();
|
|
27
|
+
const res = await (this.options.fetch ?? fetch)(`${this.base}/api/v2${path}`, { method, headers: h, body: body === undefined ? undefined : JSON.stringify(body) });
|
|
28
|
+
const text = await res.text();
|
|
29
|
+
const json = text ? JSON.parse(text) : undefined;
|
|
30
|
+
if (!res.ok)
|
|
31
|
+
throw new ApiRequestError(res.status, json?.error?.code ?? 'error', json?.error?.message ?? `HTTP ${res.status}`, json);
|
|
32
|
+
return json;
|
|
33
|
+
}
|
|
34
|
+
createProduct = (body) => this.request('POST', '/products', body);
|
|
35
|
+
listProducts = () => this.request('GET', '/products');
|
|
36
|
+
createCustomer = (body) => this.request('POST', '/customers', body);
|
|
37
|
+
createLicenses = (body) => this.request('POST', '/licenses', body);
|
|
38
|
+
getLicense = (id) => this.request('GET', `/licenses/${id}`);
|
|
39
|
+
updateLicense = (id, patch) => this.request('PATCH', `/licenses/${id}`, patch);
|
|
40
|
+
suspendLicense = (id) => this.request('POST', `/licenses/${id}/suspend`);
|
|
41
|
+
resumeLicense = (id) => this.request('POST', `/licenses/${id}/resume`);
|
|
42
|
+
revokeLicense = (id, approvalId) => this.request('POST', `/licenses/${id}/revoke`, undefined, approvalId ? { 'Approval-Id': approvalId } : {});
|
|
43
|
+
listEvents = (type) => this.request('GET', `/events${type ? `?type=${encodeURIComponent(type)}` : ''}`);
|
|
44
|
+
}
|
|
45
|
+
/** Verifies a Standard Webhooks signature (webhook-id, webhook-timestamp, webhook-signature) with the endpoint secret. */
|
|
46
|
+
export async function verifyWebhook(secret, headers, body, toleranceSeconds = 300) {
|
|
47
|
+
const { createHmac, timingSafeEqual } = await import('node:crypto');
|
|
48
|
+
const id = headers['webhook-id'], ts = headers['webhook-timestamp'], sig = headers['webhook-signature'];
|
|
49
|
+
if (!id || !ts || !sig)
|
|
50
|
+
return false;
|
|
51
|
+
if (Math.abs(Date.now() / 1000 - Number(ts)) > toleranceSeconds)
|
|
52
|
+
return false;
|
|
53
|
+
const key = Buffer.from(secret.startsWith('whsec_') ? secret.slice(6) : secret, 'base64');
|
|
54
|
+
const expected = Buffer.from(createHmac('sha256', key).update(`${id}.${ts}.${body}`).digest('base64'));
|
|
55
|
+
return sig.split(' ').some((s) => {
|
|
56
|
+
const v = Buffer.from(s.startsWith('v1,') ? s.slice(3) : '');
|
|
57
|
+
return v.length === expected.length && timingSafeEqual(v, expected);
|
|
58
|
+
});
|
|
59
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,24 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@codeo-engineering/licenserail",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
}
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "LicenseRail client SDK: offline license verification, activation, refresh, floating leases and the management API.",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"publishConfig": { "access": "public" },
|
|
7
|
+
"author": "Codeo Solutions Limited",
|
|
8
|
+
"homepage": "https://licenserail.com",
|
|
9
|
+
"repository": { "type": "git", "url": "git+https://github.com/codeo-engineering/licenserail-sdks.git", "directory": "typescript" },
|
|
10
|
+
"type": "module",
|
|
11
|
+
"main": "dist/index.js",
|
|
12
|
+
"types": "dist/index.d.ts",
|
|
13
|
+
"exports": { ".": { "types": "./dist/index.d.ts", "default": "./dist/index.js" } },
|
|
14
|
+
"files": ["dist"],
|
|
15
|
+
"engines": { "node": ">=18" },
|
|
16
|
+
"scripts": {
|
|
17
|
+
"build": "tsc -p tsconfig.json",
|
|
18
|
+
"test": "npm run build && node --test test/"
|
|
19
|
+
},
|
|
20
|
+
"devDependencies": {
|
|
21
|
+
"@types/node": "^20.11.0",
|
|
22
|
+
"typescript": "^5.6.0"
|
|
23
|
+
}
|
|
24
|
+
}
|