@codeo-engineering/licenserail 0.0.0-stage → 0.1.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +68 -2
- package/dist/client.d.ts +192 -0
- package/dist/client.js +451 -0
- package/dist/core.d.ts +147 -0
- package/dist/core.js +225 -0
- package/dist/fingerprint.d.ts +3 -0
- package/dist/fingerprint.js +73 -0
- package/dist/index.d.ts +5 -0
- package/dist/index.js +5 -0
- package/dist/management.d.ts +73 -0
- package/dist/management.js +66 -0
- package/dist/vm.d.ts +53 -0
- package/dist/vm.js +184 -0
- package/package.json +22 -4
package/dist/core.js
ADDED
|
@@ -0,0 +1,225 @@
|
|
|
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
|
+
/** The `code` values the client API returns (`ActivationResult.errorCode`, `UseResult.errorCode`). */
|
|
12
|
+
export const ERROR_CODES = {
|
|
13
|
+
badRequest: 'bad_request',
|
|
14
|
+
/** Returned by the SDK without a request: there is no license on this device (borrow, consume). */
|
|
15
|
+
noLicense: 'no_license',
|
|
16
|
+
network: 'network',
|
|
17
|
+
licenseNotFound: 'license_not_found',
|
|
18
|
+
wrongProduct: 'wrong_product',
|
|
19
|
+
licenseSuspended: 'license_suspended',
|
|
20
|
+
licenseExpired: 'license_expired',
|
|
21
|
+
licenseRevoked: 'license_revoked',
|
|
22
|
+
licenseInUse: 'license_in_use',
|
|
23
|
+
activationRevoked: 'activation_revoked',
|
|
24
|
+
wrongMachine: 'wrong_machine',
|
|
25
|
+
invalidToken: 'invalid_token',
|
|
26
|
+
seatLimitReached: 'seat_limit_reached',
|
|
27
|
+
leaseExpired: 'lease_expired',
|
|
28
|
+
tenantSuspended: 'tenant_suspended',
|
|
29
|
+
insufficientBalance: 'insufficient_balance',
|
|
30
|
+
rateLimited: 'rate_limited',
|
|
31
|
+
deviceNotIdentified: 'device_not_identified',
|
|
32
|
+
trialUnavailable: 'trial_unavailable',
|
|
33
|
+
trialEnded: 'trial_ended',
|
|
34
|
+
/** The vendor blocked the address the request came from. */
|
|
35
|
+
ipBlocked: 'ip_blocked',
|
|
36
|
+
/** This device used up the license's lifetime deactivations; only the vendor can free the seat. */
|
|
37
|
+
deactivationLimitReached: 'deactivation_limit_reached',
|
|
38
|
+
/** The vendor banned this device from the license. */
|
|
39
|
+
deviceBanned: 'device_banned',
|
|
40
|
+
/** Too many failed activations: new devices are locked until the vendor unlocks the license. */
|
|
41
|
+
licenseLocked: 'license_locked',
|
|
42
|
+
/** The device clock is too far from the server's. */
|
|
43
|
+
clockOffset: 'clock_offset',
|
|
44
|
+
/** The app version is older than the product's minimum or newer than the license's maximum. */
|
|
45
|
+
appVersionNotAllowed: 'app_version_not_allowed',
|
|
46
|
+
/** The license can't be used from this country or network. */
|
|
47
|
+
locationNotAllowed: 'location_not_allowed',
|
|
48
|
+
/** Borrowing is off for the license, or more hours were asked than it allows. */
|
|
49
|
+
borrowNotAllowed: 'borrow_not_allowed',
|
|
50
|
+
/** A seat was just released by another device and can't be taken yet. */
|
|
51
|
+
seatCoolingDown: 'seat_cooling_down',
|
|
52
|
+
/** All uses of the license are used up. */
|
|
53
|
+
useLimitReached: 'use_limit_reached',
|
|
54
|
+
/** The product doesn't allow new activations or trials on virtual machines. */
|
|
55
|
+
virtualMachineNotAllowed: 'virtual_machine_not_allowed',
|
|
56
|
+
};
|
|
57
|
+
function fromBase64Url(text) {
|
|
58
|
+
if (!/^[A-Za-z0-9_-]*$/.test(text) || text.length % 4 === 1)
|
|
59
|
+
throw new Error('invalid base64url');
|
|
60
|
+
return Buffer.from(text, 'base64url');
|
|
61
|
+
}
|
|
62
|
+
export function importPublicKey(pem) {
|
|
63
|
+
return createPublicKey({ key: pem, format: 'pem' });
|
|
64
|
+
}
|
|
65
|
+
/**
|
|
66
|
+
* Verifies `base64url(json).base64url(signature)` (ECDSA P-256 / SHA-256, IEEE P1363 r||s) over the ASCII bytes of the encoded
|
|
67
|
+
* body and returns the payload, or null if the signature or format is invalid.
|
|
68
|
+
*/
|
|
69
|
+
export function verifyToken(token, publicKey) {
|
|
70
|
+
if (!token || typeof token !== 'string')
|
|
71
|
+
return null;
|
|
72
|
+
const parts = token.trim().split('.');
|
|
73
|
+
if (parts.length !== 2)
|
|
74
|
+
return null;
|
|
75
|
+
try {
|
|
76
|
+
const key = typeof publicKey === 'string' ? importPublicKey(publicKey) : publicKey;
|
|
77
|
+
const signature = fromBase64Url(parts[1]);
|
|
78
|
+
if (signature.length !== 64)
|
|
79
|
+
return null;
|
|
80
|
+
const ok = cryptoVerify('sha256', Buffer.from(parts[0], 'ascii'), { key, dsaEncoding: 'ieee-p1363' }, signature);
|
|
81
|
+
if (!ok)
|
|
82
|
+
return null;
|
|
83
|
+
const payload = JSON.parse(fromBase64Url(parts[0]).toString('utf8'));
|
|
84
|
+
return payload && typeof payload === 'object' && payload.fingerprint ? payload : null;
|
|
85
|
+
}
|
|
86
|
+
catch {
|
|
87
|
+
return null;
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
/**
|
|
91
|
+
* component = hex(SHA256(vendor + ":" + product + ":" + part + ":" + upper(trim(raw)))); blank → "none".
|
|
92
|
+
* `vendor` is the organization ID from the dashboard (ten_...); it never changes, so device identities stay stable.
|
|
93
|
+
*/
|
|
94
|
+
export function hashComponent(vendor, product, part, raw) {
|
|
95
|
+
if (raw == null || raw.trim() === '')
|
|
96
|
+
return UNAVAILABLE;
|
|
97
|
+
return createHash('sha256').update(`${vendor}:${product}:${part}:${raw.trim().toUpperCase()}`, 'utf8').digest('hex');
|
|
98
|
+
}
|
|
99
|
+
/** Host platforms whose installations are licensed like devices (an app inside YouTrack, not a computer). */
|
|
100
|
+
export const HOST_PLATFORMS = ['youtrack'];
|
|
101
|
+
const available = (v) => !!v && v !== UNAVAILABLE;
|
|
102
|
+
const same = (a, b) => available(a) && a === b;
|
|
103
|
+
const isHostInstallation = (f) => !!f.os && HOST_PLATFORMS.includes(f.os.toLowerCase());
|
|
104
|
+
/**
|
|
105
|
+
* Whether `presented` is the device `registered` was issued for (call on the registered fingerprint). `strategy` is the token's
|
|
106
|
+
* `matching` field: default (board id + one other part, or 2 of 3 without a board id), 'strict' (every part the registered device
|
|
107
|
+
* has) or 'loose' (any one part). When both sides name an operating system it must be the same; host installations always
|
|
108
|
+
* match exactly (same platform and id).
|
|
109
|
+
*/
|
|
110
|
+
export function fingerprintMatches(registered, presented, strategy) {
|
|
111
|
+
if (isHostInstallation(registered) || isHostInstallation(presented))
|
|
112
|
+
return (registered.os ?? '').toLowerCase() === (presented.os ?? '').toLowerCase() && same(registered.machineId, presented.machineId);
|
|
113
|
+
if (registered.os && presented.os && registered.os.toLowerCase() !== presented.os.toLowerCase())
|
|
114
|
+
return false;
|
|
115
|
+
if (strategy === 'strict' || strategy === 'loose') {
|
|
116
|
+
const parts = [
|
|
117
|
+
[registered.machineId, presented.machineId], [registered.diskId, presented.diskId],
|
|
118
|
+
[registered.hostName, presented.hostName], [registered.boardId, presented.boardId],
|
|
119
|
+
];
|
|
120
|
+
const mine = parts.filter(([r]) => available(r));
|
|
121
|
+
return strategy === 'strict' ? mine.length > 0 && mine.every(([r, p]) => same(r, p)) : mine.some(([r, p]) => same(r, p));
|
|
122
|
+
}
|
|
123
|
+
let matches = 0;
|
|
124
|
+
if (same(registered.machineId, presented.machineId))
|
|
125
|
+
matches++;
|
|
126
|
+
if (same(registered.diskId, presented.diskId))
|
|
127
|
+
matches++;
|
|
128
|
+
if (same(registered.hostName, presented.hostName))
|
|
129
|
+
matches++;
|
|
130
|
+
return available(registered.boardId) ? same(registered.boardId, presented.boardId) && matches >= 1 : matches >= 2;
|
|
131
|
+
}
|
|
132
|
+
/**
|
|
133
|
+
* Whitespace as .NET's char.IsWhiteSpace sees it (the server trims with it): U+0009-U+000D, U+0085 and the Unicode Zs, Zl and Zp
|
|
134
|
+
* characters. Not String.prototype.trim(): that also strips U+FEFF, which .NET keeps.
|
|
135
|
+
*/
|
|
136
|
+
const DOTNET_WHITESPACE = '\u0009-\u000D\u0020\u0085\u00A0\u1680\u2000-\u200A\u2028\u2029\u202F\u205F\u3000';
|
|
137
|
+
const EDGE_WHITESPACE = new RegExp(`^[${DOTNET_WHITESPACE}]+|[${DOTNET_WHITESPACE}]+$`, 'g');
|
|
138
|
+
/** Trims the .NET whitespace set from both ends, like the server's string.Trim(). */
|
|
139
|
+
function trimVersion(v) {
|
|
140
|
+
return v.replace(EDGE_WHITESPACE, '');
|
|
141
|
+
}
|
|
142
|
+
const INT32_MAX = 2147483647;
|
|
143
|
+
/** A part is a run of ASCII digits; the server parses it as a signed 32-bit integer, so one above 2147483647 counts as 0. */
|
|
144
|
+
function versionPart(p) {
|
|
145
|
+
const digits = p.replace(/^0+(?=[0-9])/, '');
|
|
146
|
+
if (digits.length > 10)
|
|
147
|
+
return 0;
|
|
148
|
+
const n = Number(digits);
|
|
149
|
+
return n > INT32_MAX ? 0 : n;
|
|
150
|
+
}
|
|
151
|
+
function versionParts(v) {
|
|
152
|
+
const core = /^[0-9.]*/.exec(trimVersion(v).replace(/^[vV]+/, ''))[0];
|
|
153
|
+
return core.split('.').filter((p) => p !== '').map(versionPart);
|
|
154
|
+
}
|
|
155
|
+
/** A version the server compares: after trimming whitespace, 1 to 50 characters and the first is an ASCII digit. */
|
|
156
|
+
export function isVersion(v) {
|
|
157
|
+
if (typeof v !== 'string')
|
|
158
|
+
return false;
|
|
159
|
+
const t = trimVersion(v); // the limit counts UTF-16 code units, like .NET's string.Length
|
|
160
|
+
return t.length > 0 && t.length <= 50 && /^[0-9]/.test(t);
|
|
161
|
+
}
|
|
162
|
+
/**
|
|
163
|
+
* "1.10.2" > "1.9"; a leading v/V is ignored; missing parts are 0; anything after the leading run of ASCII digits and dots
|
|
164
|
+
* (-beta, +build) is ignored; a part above 2147483647 counts as 0. Same as the server (test-vectors/versions.json).
|
|
165
|
+
*/
|
|
166
|
+
export function compareVersions(a, b) {
|
|
167
|
+
const x = versionParts(a);
|
|
168
|
+
const y = versionParts(b);
|
|
169
|
+
for (let i = 0; i < Math.max(x.length, y.length); i++) {
|
|
170
|
+
const d = (x[i] ?? 0) - (y[i] ?? 0);
|
|
171
|
+
if (d !== 0)
|
|
172
|
+
return d < 0 ? -1 : 1;
|
|
173
|
+
}
|
|
174
|
+
return 0;
|
|
175
|
+
}
|
|
176
|
+
/** Whether `appVersion` may run under a license limited to `maxAppVersion` (unknown or missing versions aren't refused). */
|
|
177
|
+
export function appVersionAllowed(maxAppVersion, appVersion) {
|
|
178
|
+
return !isVersion(maxAppVersion) || !isVersion(appVersion) || compareVersions(appVersion, maxAppVersion) <= 0;
|
|
179
|
+
}
|
|
180
|
+
/**
|
|
181
|
+
* Offline check, identical in every SDK (see the shared test vectors). `appVersion` (optional) is checked against the token's
|
|
182
|
+
* `maxAppVersion`. Grace (`graceUntil`) and expired-but-kept licenses (`expired: true`) need nothing extra: the server sets
|
|
183
|
+
* `expiresAt` to the end of grace, or leaves it out.
|
|
184
|
+
*/
|
|
185
|
+
export function evaluate(payload, product, machine, now, lastSeen, appVersion) {
|
|
186
|
+
if (!payload)
|
|
187
|
+
return 'InvalidSignature';
|
|
188
|
+
if (payload.product.toLowerCase() !== product.toLowerCase())
|
|
189
|
+
return 'WrongProduct';
|
|
190
|
+
if (!fingerprintMatches(payload.fingerprint, machine, payload.matching))
|
|
191
|
+
return 'WrongMachine';
|
|
192
|
+
if (payload.suspended)
|
|
193
|
+
return 'Suspended';
|
|
194
|
+
if (!appVersionAllowed(payload.maxAppVersion, appVersion))
|
|
195
|
+
return 'AppVersionNotAllowed';
|
|
196
|
+
if (!lastSeen)
|
|
197
|
+
return 'Unverified';
|
|
198
|
+
const t = now.getTime();
|
|
199
|
+
if (t + ISSUED_AT_TOLERANCE_MS < Date.parse(payload.issuedAt) || t + CLOCK_TOLERANCE_MS < lastSeen.getTime())
|
|
200
|
+
return 'ClockTampered';
|
|
201
|
+
if (payload.expiresAt && t >= Date.parse(payload.expiresAt))
|
|
202
|
+
return 'Expired';
|
|
203
|
+
if (t >= Date.parse(payload.offlineUntil))
|
|
204
|
+
return 'OfflineTooLong';
|
|
205
|
+
return 'Valid';
|
|
206
|
+
}
|
|
207
|
+
/** Tamper-evident "last run" record: `{epochMs}.{hmac}` keyed to the product and device. */
|
|
208
|
+
export function encodeRunHistory(at, vendor, product, machine) {
|
|
209
|
+
const ms = String(at.getTime());
|
|
210
|
+
return `${ms}.${historyMac(ms, vendor, product, machine)}`;
|
|
211
|
+
}
|
|
212
|
+
export function decodeRunHistory(value, vendor, product, machine) {
|
|
213
|
+
const parts = value?.trim().split('.');
|
|
214
|
+
if (!parts || parts.length !== 2 || !/^\d{1,15}$/.test(parts[0]))
|
|
215
|
+
return null;
|
|
216
|
+
const expected = Buffer.from(historyMac(parts[0], vendor, product, machine));
|
|
217
|
+
const actual = Buffer.from(parts[1]);
|
|
218
|
+
if (expected.length !== actual.length || !timingSafeEqual(expected, actual))
|
|
219
|
+
return null;
|
|
220
|
+
return new Date(Number(parts[0]));
|
|
221
|
+
}
|
|
222
|
+
function historyMac(ms, vendor, product, machine) {
|
|
223
|
+
const key = createHash('sha256').update(`${vendor}:run-history:${product}:${machine.machineId}:${machine.boardId}`).digest();
|
|
224
|
+
return createHmac('sha256', key).update(ms).digest('hex').slice(0, 32).toUpperCase();
|
|
225
|
+
}
|
|
@@ -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,5 @@
|
|
|
1
|
+
export * from './core.js';
|
|
2
|
+
export { collectFingerprint } from './fingerprint.js';
|
|
3
|
+
export { detectVirtualMachine, isVirtualMachine, isVirtualHardware, cpuInfoHasHypervisor, cgroupIsContainer, sysctlSaysVirtual, isWsl, linuxIsVirtual, parseWindowsComputerSystem, VM_PROBE_TIMEOUT_MS, type LinuxProbe, } from './vm.js';
|
|
4
|
+
export { License, LicenseClient, type ActivationResult, type CheckResult, type LicenseClientOptions, type UseResult } from './client.js';
|
|
5
|
+
export { ApiRequestError, ManagementClient, verifyWebhook, type ManagementOptions } from './management.js';
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
export * from './core.js';
|
|
2
|
+
export { collectFingerprint } from './fingerprint.js';
|
|
3
|
+
export { detectVirtualMachine, isVirtualMachine, isVirtualHardware, cpuInfoHasHypervisor, cgroupIsContainer, sysctlSaysVirtual, isWsl, linuxIsVirtual, parseWindowsComputerSystem, VM_PROBE_TIMEOUT_MS, } from './vm.js';
|
|
4
|
+
export { License, LicenseClient } from './client.js';
|
|
5
|
+
export { ApiRequestError, ManagementClient, verifyWebhook } from './management.js';
|
|
@@ -0,0 +1,73 @@
|
|
|
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
|
+
/**
|
|
52
|
+
* Starts a trial for an email address you verified: one per person and product ("+tags", Gmail dots and case are the same
|
|
53
|
+
* person; throwaway mail services are refused unless allowDisposable). Returns the trial license; send its key to the user.
|
|
54
|
+
*/
|
|
55
|
+
createEmailTrial: (body: {
|
|
56
|
+
productId: string;
|
|
57
|
+
email: string;
|
|
58
|
+
name?: string;
|
|
59
|
+
days?: number;
|
|
60
|
+
maxActivations?: number;
|
|
61
|
+
features?: string[];
|
|
62
|
+
allowDisposable?: boolean;
|
|
63
|
+
}) => Promise<any>;
|
|
64
|
+
/** Whether an email address already had a trial of the product. */
|
|
65
|
+
checkEmailTrial: (productId: string, email: string) => Promise<any>;
|
|
66
|
+
updateLicense: (id: string, patch: Record<string, unknown>) => Promise<any>;
|
|
67
|
+
suspendLicense: (id: string) => Promise<any>;
|
|
68
|
+
resumeLicense: (id: string) => Promise<any>;
|
|
69
|
+
revokeLicense: (id: string, approvalId?: string) => Promise<any>;
|
|
70
|
+
listEvents: (type?: string) => Promise<any>;
|
|
71
|
+
}
|
|
72
|
+
/** Verifies a Standard Webhooks signature (webhook-id, webhook-timestamp, webhook-signature) with the endpoint secret. */
|
|
73
|
+
export declare function verifyWebhook(secret: string, headers: Record<string, string | undefined>, body: string, toleranceSeconds?: number): Promise<boolean>;
|
|
@@ -0,0 +1,66 @@
|
|
|
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
|
+
/**
|
|
40
|
+
* Starts a trial for an email address you verified: one per person and product ("+tags", Gmail dots and case are the same
|
|
41
|
+
* person; throwaway mail services are refused unless allowDisposable). Returns the trial license; send its key to the user.
|
|
42
|
+
*/
|
|
43
|
+
createEmailTrial = (body) => this.request('POST', '/trials/email', body);
|
|
44
|
+
/** Whether an email address already had a trial of the product. */
|
|
45
|
+
checkEmailTrial = (productId, email) => this.request('GET', `/trials/email?productId=${encodeURIComponent(productId)}&email=${encodeURIComponent(email)}`);
|
|
46
|
+
updateLicense = (id, patch) => this.request('PATCH', `/licenses/${id}`, patch);
|
|
47
|
+
suspendLicense = (id) => this.request('POST', `/licenses/${id}/suspend`);
|
|
48
|
+
resumeLicense = (id) => this.request('POST', `/licenses/${id}/resume`);
|
|
49
|
+
revokeLicense = (id, approvalId) => this.request('POST', `/licenses/${id}/revoke`, undefined, approvalId ? { 'Approval-Id': approvalId } : {});
|
|
50
|
+
listEvents = (type) => this.request('GET', `/events${type ? `?type=${encodeURIComponent(type)}` : ''}`);
|
|
51
|
+
}
|
|
52
|
+
/** Verifies a Standard Webhooks signature (webhook-id, webhook-timestamp, webhook-signature) with the endpoint secret. */
|
|
53
|
+
export async function verifyWebhook(secret, headers, body, toleranceSeconds = 300) {
|
|
54
|
+
const { createHmac, timingSafeEqual } = await import('node:crypto');
|
|
55
|
+
const id = headers['webhook-id'], ts = headers['webhook-timestamp'], sig = headers['webhook-signature'];
|
|
56
|
+
if (!id || !ts || !sig)
|
|
57
|
+
return false;
|
|
58
|
+
if (Math.abs(Date.now() / 1000 - Number(ts)) > toleranceSeconds)
|
|
59
|
+
return false;
|
|
60
|
+
const key = Buffer.from(secret.startsWith('whsec_') ? secret.slice(6) : secret, 'base64');
|
|
61
|
+
const expected = Buffer.from(createHmac('sha256', key).update(`${id}.${ts}.${body}`).digest('base64'));
|
|
62
|
+
return sig.split(' ').some((s) => {
|
|
63
|
+
const v = Buffer.from(s.startsWith('v1,') ? s.slice(3) : '');
|
|
64
|
+
return v.length === expected.length && timingSafeEqual(v, expected);
|
|
65
|
+
});
|
|
66
|
+
}
|
package/dist/vm.d.ts
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
/** How long the probe (PowerShell on Windows, sysctl on macOS) may run before it is killed. */
|
|
2
|
+
export declare const VM_PROBE_TIMEOUT_MS = 5000;
|
|
3
|
+
/**
|
|
4
|
+
* Whether a system manufacturer and model (Windows Win32_ComputerSystem; Linux /sys/class/dmi/id sys_vendor and product_name)
|
|
5
|
+
* name a hypervisor: VMware, VirtualBox, innotek, QEMU, KVM, Xen, HVM domU, Parallels, Bochs or bhyve as whole words
|
|
6
|
+
* (case-insensitive), or "Virtual Machine" made by "Microsoft Corporation" (a Hyper-V guest). Cloud vendor names are not on the
|
|
7
|
+
* list: they also sell bare metal.
|
|
8
|
+
*/
|
|
9
|
+
export declare function isVirtualHardware(manufacturer: string | null | undefined, model: string | null | undefined): boolean;
|
|
10
|
+
/**
|
|
11
|
+
* The Windows probe's output (Win32_ComputerSystem Manufacturer, then Model, one per line); null when there is no output (the
|
|
12
|
+
* probe failed). Windows hosts with Hyper-V or VBS enabled report their real maker and model, so they don't match.
|
|
13
|
+
*/
|
|
14
|
+
export declare function parseWindowsComputerSystem(output: string | null | undefined): boolean | null;
|
|
15
|
+
/** Whether /proc/sys/kernel/osrelease is a WSL kernel (contains "microsoft" or "WSL"). WSL is not a virtual machine. */
|
|
16
|
+
export declare function isWsl(osrelease: string | null | undefined): boolean;
|
|
17
|
+
/** Whether /proc/cpuinfo lists the "hypervisor" CPU flag. */
|
|
18
|
+
export declare function cpuInfoHasHypervisor(cpuinfo: string | null | undefined): boolean;
|
|
19
|
+
/** Whether /proc/1/cgroup shows a container runtime (docker, kubepods, containerd or lxc). */
|
|
20
|
+
export declare function cgroupIsContainer(cgroup: string | null | undefined): boolean;
|
|
21
|
+
/** macOS `sysctl -n kern.hv_vmm_present`: "1" in a virtual machine. */
|
|
22
|
+
export declare function sysctlSaysVirtual(output: string | null | undefined): boolean;
|
|
23
|
+
/** The Linux files the rule reads; `containerFile`: /.dockerenv or /run/.containerenv exists. */
|
|
24
|
+
export interface LinuxProbe {
|
|
25
|
+
osrelease?: string | null;
|
|
26
|
+
sysVendor?: string | null;
|
|
27
|
+
productName?: string | null;
|
|
28
|
+
cpuinfo?: string | null;
|
|
29
|
+
containerFile?: boolean;
|
|
30
|
+
cgroup?: string | null;
|
|
31
|
+
}
|
|
32
|
+
/**
|
|
33
|
+
* The Linux rule: false under WSL; otherwise true when the DMI vendor or product names a hypervisor, the CPU has the
|
|
34
|
+
* `hypervisor` flag, or the process runs in a container.
|
|
35
|
+
*/
|
|
36
|
+
export declare function linuxIsVirtual(p: LinuxProbe): boolean;
|
|
37
|
+
/**
|
|
38
|
+
* Whether this process runs in a virtual machine or a container: detected once per process without blocking (the probe runs
|
|
39
|
+
* as a child process with a 5-second limit and no window). null when it couldn't be detected (error or timeout). Nothing runs at
|
|
40
|
+
* import time: the probe starts on the first call (the client calls it at the first activate, checkout or trial, or from
|
|
41
|
+
* warmUpVirtualMachineDetection()).
|
|
42
|
+
*/
|
|
43
|
+
export declare function detectVirtualMachine(): Promise<boolean | null>;
|
|
44
|
+
/**
|
|
45
|
+
* Synchronous form of detectVirtualMachine() (false when not detected). It never starts a second probe: once detection has
|
|
46
|
+
* finished it returns the cached result; while the asynchronous probe is still running it returns false at once (the answer
|
|
47
|
+
* isn't known yet; await detectVirtualMachine() for it). Only before the first detection has started does it run the probe
|
|
48
|
+
* itself and block the event loop until it ends (up to 5 seconds, once per process); that result is then cached for both forms.
|
|
49
|
+
* @deprecated Use detectVirtualMachine().
|
|
50
|
+
*/
|
|
51
|
+
export declare function isVirtualMachine(): boolean;
|
|
52
|
+
/** Whether detection has started in this process (for tests: the probe never starts at import or client construction). */
|
|
53
|
+
export declare function virtualMachineDetectionStarted(): boolean;
|