@codeo-engineering/licenserail 0.1.0 → 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/README.md CHANGED
@@ -9,7 +9,7 @@ npm install @codeo-engineering/licenserail
9
9
  ```ts
10
10
  import { LicenseClient } from '@codeo-engineering/licenserail'
11
11
 
12
- const client = new LicenseClient({ serverUrl: 'https://api.licenserail.com', vendor: 'ten_6f1a7e2c3b4d4e5f8a9b0c1d2e3f4a5b', product: 'my-app', publicKeyPem, appVersion: '1.0.0' })
12
+ const client = new LicenseClient({ serverUrl: 'https://api.licenserail.com', vendor: 'ten_6f1a7e2c3b4d4e5f8a9b0c1d2e3f4a5b', product: 'my-app', publicKeyPem, appVersion: '1.0.0', keyId })
13
13
  const result = await client.check() // offline check, refreshed online when due
14
14
  if (!result.valid) console.log((await client.activate(licenseKey)).message)
15
15
  const canExport = client.license?.hasFeature('export')
@@ -20,8 +20,50 @@ const canExport = client.license?.hasFeature('export')
20
20
  state (expired, suspended, offline too long, clock problems).
21
21
  - `activate(key)` on the license screen; floating licenses are checked out and kept alive automatically where the platform allows.
22
22
  - `deactivate()` frees the seat (needs internet).
23
+ - `startTrial()` starts this device's keyless trial (needs the `keyId` option, the environment's public signing key id) or gets
24
+ the running one back. The trial token is stored and checked like a license (`license.isTrial`, true only when the token says
25
+ `trial: true`); it is never refreshed. A keyed license of kind `trial` is an ordinary license: it refreshes and deactivates.
26
+ - `borrow(hours)` keeps a checked-out floating seat for offline use (up to the license's limit). Without a license it returns
27
+ `no_license`, for a license that isn't a checked-out floating one `borrow_not_allowed`, both without a request.
28
+ - `returnBorrow()` releases the seat of a floating license early. On a node-locked license or a keyless trial it returns
29
+ `borrow_not_allowed` without a request, so it never uses up a deactivation.
30
+ - `consume(count = 1)` counts uses of a license with a use limit: `{ success, uses, maxUses }`, or `errorCode: 'use_limit_reached'`.
31
+ A count below 1 gives `bad_request` and no license `no_license`, without a request. Refresh, borrow and consume remove the
32
+ local license only on the revoking codes below or `lease_expired`; any other refusal keeps it.
33
+ - Keyless trials (`trial: true`) are never sent to the server: `refresh()` leaves the trial as it is, and `consume()` /
34
+ `borrow()` return `bad_request` without a request.
35
+ - `isVirtualMachineAsync()` (and the exported `detectVirtualMachine()`): best-effort VM/container detection without admin
36
+ rights, with the same narrow rules in every LicenseRail SDK: hypervisor names (VMware, VirtualBox, QEMU, KVM, Xen, Parallels,
37
+ ..., and a Microsoft "Virtual Machine") in Win32_ComputerSystem or Linux DMI, the Linux `hypervisor` CPU flag, containers,
38
+ macOS `kern.hv_vmm_present`. Cloud vendor names, Hyper-V/VBS hosts and WSL are not virtual. The probe never blocks: it runs
39
+ once per process as a hidden child process, is killed after 5 seconds (then `virtualMachine` is not sent), and requests await
40
+ the cached answer. Sent with activations, floating checkouts and trials; override with
41
+ `virtualMachine: true | false | () => boolean | Promise<boolean>`, or `detectVirtualMachine: false` to not send it. The
42
+ synchronous `isVirtualMachine()` still works but blocks until the probe ends the first time. The probe never runs at import
43
+ or in the constructor: it starts at the first activate, checkout or trial (which waits for it, at most 5 seconds), or earlier
44
+ in the background when you call `client.warmUpVirtualMachineDetection()` (returns at once; once per process).
45
+ - Every request carries the device clock (`clientTime`); the server answers `clock_offset` when it is far off.
46
+ - Offline checks apply the token's `matching` (`default`, `strict`, `loose`) and `maxAppVersion` (status
47
+ `AppVersionNotAllowed` when `appVersion` is newer; versions compare like the server, `test-vectors/versions.json`). `license` also shows `isExpired` (expired, but its strategy keeps it
48
+ working), `isInGrace` / `graceUntil`, `borrowedUntil`, `maxUses` / `uses`, `isOverage` and `matching`.
49
+ - `license.licenseExpiresAt` is the license's own expiry (null = perpetual), for showing to the user; it is never enforced.
50
+ `expiresAt` is what the offline check enforces: the end of grace, or null when the expiration strategy keeps the license
51
+ working after expiry.
52
+ - `ERROR_CODES` lists the server's codes, including `deactivation_limit_reached`, `device_banned`, `license_locked`,
53
+ `clock_offset`, `app_version_not_allowed`, `location_not_allowed`, `borrow_not_allowed`, `seat_cooling_down`,
54
+ `use_limit_reached`, `virtual_machine_not_allowed` and `ip_blocked`; `errorCode` and the server's `message` come back as is.
23
55
  - On `license_not_found`, `license_suspended`, `license_revoked`, `license_expired`, `activation_revoked`, `wrong_machine` and
24
56
  `invalid_token` the local license is removed; other errors (network, `402`) keep it.
25
57
  - Get the public key with `licenserail public-key --pem` or `licenserail init typescript`.
26
58
 
59
+ ## Changes
60
+
61
+ - 2026-12-01: additions only, existing calls keep working. New: the `AppVersionNotAllowed` status (an added member of
62
+ `LicenseStatus`: a `Record<LicenseStatus, ...>` or an exhaustive `switch` needs an entry for it), `ERROR_CODES.noLicense`,
63
+ `returnBorrow()`, `isVirtualMachineAsync()`, `detectVirtualMachine()`, `isWsl()`, `linuxIsVirtual()`,
64
+ `parseWindowsComputerSystem()`. Changed behaviour: `license.isTrial` is true only for keyless trials (`trial: true`), borrow
65
+ and consume without a license return `no_license`, consume removes the license on a revoking code, VM detection no longer
66
+ blocks the event loop, cloud vendor names no longer count as virtual machines, WSL is not virtual, and versions with a
67
+ 10-digit part up to 2147483647 compare like the server.
68
+
27
69
  Source: [licenserail-sdks](https://github.com/codeo-engineering/licenserail-sdks) (`typescript/`). Tests (shared vectors in `../test-vectors`): `npm test`.
package/dist/client.d.ts CHANGED
@@ -8,8 +8,11 @@ export interface LicenseClientOptions {
8
8
  vendor: string;
9
9
  /** The environment's public key (PEM); verifies license files offline. */
10
10
  publicKeyPem: string;
11
+ /** The environment's signing key id (public, shown with the public key); needed only for startTrial(). */
12
+ keyId?: string;
11
13
  /** Where the license file and run history live; default: a per-user folder. */
12
14
  storageDir?: string;
15
+ /** The app's version: sent to the server and checked offline against the license's maxAppVersion. */
13
16
  appVersion?: string;
14
17
  /** Refresh online on every check() (default false: only when the token says it is due). */
15
18
  refreshOnStartup?: boolean;
@@ -22,12 +25,24 @@ export interface LicenseClientOptions {
22
25
  /** Overrides fetch (tests, proxies). */
23
26
  fetch?: typeof fetch;
24
27
  machineName?: string;
28
+ /** Overrides virtual machine detection: a fixed answer, or your own detector (it may return a promise; null = not detected). */
29
+ virtualMachine?: boolean | (() => boolean | null | Promise<boolean | null>);
30
+ /** Detect virtual machines and containers and send the result (default true). false: `virtualMachine` is not sent. */
31
+ detectVirtualMachine?: boolean;
25
32
  }
26
33
  export interface ActivationResult {
27
34
  success: boolean;
28
35
  errorCode?: string;
29
36
  message: string;
30
37
  }
38
+ /** Result of consume(): the license's use counter after the use, or why it was refused. */
39
+ export interface UseResult {
40
+ success: boolean;
41
+ uses?: number;
42
+ maxUses?: number;
43
+ errorCode?: string;
44
+ message: string;
45
+ }
31
46
  export interface CheckResult {
32
47
  status: LicenseStatus;
33
48
  valid: boolean;
@@ -40,17 +55,46 @@ export declare class License {
40
55
  get key(): string;
41
56
  get customer(): string;
42
57
  get kind(): string;
58
+ /**
59
+ * What the offline check enforces: the end of grace when the license has grace days; null when perpetual or when the expiration
60
+ * strategy keeps the license working after expiry. Show licenseExpiresAt to the user instead.
61
+ */
43
62
  get expiresAt(): Date | null;
63
+ /** The license's own expiry, for showing to the user (null = perpetual); never enforced. */
64
+ get licenseExpiresAt(): Date | null;
44
65
  get offlineUntil(): Date;
45
66
  get isTest(): boolean;
46
67
  get isFloating(): boolean;
47
68
  get features(): string[];
48
69
  get metadata(): Record<string, unknown>;
49
70
  hasFeature(code: string): boolean;
71
+ /**
72
+ * A keyless trial (startTrial()): the token says `trial: true`. A keyed license of kind "trial" is an ordinary license (see
73
+ * `kind`): it refreshes and deactivates on the server.
74
+ */
75
+ get isTrial(): boolean;
76
+ /** Device matching applied offline: 'default', 'strict' or 'loose'. */
77
+ get matching(): string;
78
+ /** The newest app version this license may run; null = any. */
79
+ get maxAppVersion(): string | null;
80
+ /** The license has expired but keeps working (expiration strategy maintain or allow); show a renewal notice. */
81
+ get isExpired(): boolean;
82
+ /** The license expired and works until graceUntil (grace period). */
83
+ get isInGrace(): boolean;
84
+ get graceUntil(): Date | null;
85
+ /** Floating: the seat is borrowed for offline use until this time. */
86
+ get borrowedUntil(): Date | null;
87
+ get isBorrowed(): boolean;
88
+ /** Use counting: the license's limit, and the uses when the token was issued. */
89
+ get maxUses(): number | null;
90
+ get uses(): number | null;
91
+ /** More devices are active than the license's seats (overdraft). */
92
+ get isOverage(): boolean;
50
93
  }
51
94
  /**
52
95
  * 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.
96
+ * deactivation, keyless trials, floating leases (with borrowing) and use counting. Never put an API key in client code; this
97
+ * class needs only the public key.
54
98
  */
55
99
  export declare class LicenseClient {
56
100
  private readonly options;
@@ -63,26 +107,77 @@ export declare class LicenseClient {
63
107
  lastServerMessage: string | null;
64
108
  constructor(options: LicenseClientOptions);
65
109
  private now;
110
+ /** The device clock (UTC, ISO 8601) sent as `clientTime`; the server refuses requests whose clock is too far off. */
111
+ private clientTime;
66
112
  private fingerprint;
67
113
  /** Whether a license for this device would match it again; if not, activating would only use up a seat. */
68
114
  private identified;
69
115
  private get tokenPath();
70
116
  private get historyPath();
117
+ /**
118
+ * What requests carry as `virtualMachine`: null (not sent) when detection is off (and no answer is set) or couldn't tell. The
119
+ * probe runs once per process without blocking (a child process with a 5-second limit); requests await the cached result.
120
+ */
121
+ private virtualMachineField;
122
+ /**
123
+ * Starts virtual machine detection in the background and returns at once, so the first activate, checkout or trial doesn't
124
+ * wait for it. Optional: without it the probe starts at the first activate, checkout or trial (which then waits for it, at
125
+ * most the 5-second probe limit). It never runs at app start or in the constructor. Runs once per process; does nothing when
126
+ * detection is off or the `virtualMachine` option gives the answer.
127
+ */
128
+ warmUpVirtualMachineDetection(): void;
129
+ /**
130
+ * Whether the app runs in a virtual machine or container (best effort): the `virtualMachine` option if set, otherwise
131
+ * detected (false when detection is off or failed). Sent with activations, floating checkouts and trials.
132
+ */
133
+ isVirtualMachineAsync(): Promise<boolean>;
134
+ /**
135
+ * Synchronous form of isVirtualMachineAsync(). Never starts a second probe: returns the cached result once detection has
136
+ * finished, and false while the asynchronous probe is still running. Blocks only before the first detection has started (up
137
+ * to 5 seconds, once per process). A custom detector that returns a promise counts as false here.
138
+ * @deprecated Use isVirtualMachineAsync().
139
+ */
140
+ isVirtualMachine(): boolean;
71
141
  /** The current license after the last check, or null. */
72
142
  get license(): License | null;
73
143
  /** Offline evaluation only (no network). */
74
144
  evaluateLocal(): CheckResult;
75
145
  /** Call on startup: evaluates offline and refreshes online when due or when only the server can clear the state. */
76
146
  check(): Promise<CheckResult>;
147
+ private activationBody;
77
148
  /** Activates `licenseKey` on this device (or checks out a floating lease if the license is floating). */
78
149
  activate(licenseKey: string, machineName?: string): Promise<ActivationResult>;
79
150
  /** Checks out a floating seat and keeps it alive with heartbeats until release(). */
80
151
  checkout(licenseKey: string): Promise<ActivationResult>;
81
- /** Releases a floating seat. */
152
+ /**
153
+ * Starts this device's keyless trial, or gets the running one back (the server keeps one trial per device and product). Needs
154
+ * the `keyId` option. The trial token is stored and checked like a license (kind "trial"); it is never refreshed.
155
+ */
156
+ startTrial(): Promise<ActivationResult>;
157
+ /**
158
+ * Floating: keeps this device's seat for offline use for `hours` (up to the license's limit). Return it early with
159
+ * returnBorrow() (the same as release()). Refused without a request with `no_license` when there is no license and
160
+ * `borrow_not_allowed` when it isn't a checked-out floating license; a keyless trial gets `bad_request` (it is never sent to the
161
+ * server). The license file is removed only on a revoking code or lease_expired; other refusals keep it.
162
+ */
163
+ borrow(hours: number): Promise<ActivationResult>;
164
+ /**
165
+ * Licenses with a use limit: consumes `count` uses on the server; refused with use_limit_reached when they are used up. A count
166
+ * below 1 is refused with `bad_request` and no license with `no_license`, both without a request; so is a keyless trial
167
+ * (`bad_request`: it is never sent to the server). The license file is removed only on a revoking code or lease_expired; any
168
+ * other refusal keeps it.
169
+ */
170
+ consume(count?: number): Promise<UseResult>;
171
+ /** Releases a floating seat (also returns a borrowed seat early). */
82
172
  release(): Promise<ActivationResult>;
173
+ /**
174
+ * Returns a borrowed floating seat early (releases the seat of a floating license). On a node-locked license or a keyless trial
175
+ * it returns `borrow_not_allowed` without a request, so it can never use up a deactivation. Without a license it succeeds.
176
+ */
177
+ returnBorrow(): Promise<ActivationResult>;
83
178
  /** Removes the license from this device and frees its seat on the server. */
84
179
  deactivate(): Promise<ActivationResult>;
85
- /** Asks the server for a fresh token now (floating licenses: a heartbeat). */
180
+ /** Asks the server for a fresh token now (floating licenses: a heartbeat). A keyless trial is never sent: it stays as it is. */
86
181
  refresh(anomalies?: string[]): Promise<void>;
87
182
  /** A user-facing sentence for a status. */
88
183
  message(status: LicenseStatus): string;
package/dist/client.js CHANGED
@@ -1,11 +1,13 @@
1
1
  import { mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
2
2
  import { homedir, hostname, platform } from 'node:os';
3
3
  import { join } from 'node:path';
4
- import { decodeRunHistory, encodeRunHistory, evaluate, fingerprintMatches, importPublicKey, REVOKING_CODES, verifyToken, } from './core.js';
4
+ import { decodeRunHistory, encodeRunHistory, ERROR_CODES, evaluate, fingerprintMatches, importPublicKey, REVOKING_CODES, verifyToken, } from './core.js';
5
5
  import { collectFingerprint } from './fingerprint.js';
6
+ import { detectVirtualMachine, isVirtualMachine as detectVirtualMachineSync } from './vm.js';
6
7
  const notIdentified = {
7
8
  success: false, errorCode: 'device_not_identified', message: "This device can't be identified, so a license can't be activated on it.",
8
9
  };
10
+ const offline = (message = 'Could not connect to the license server.') => ({ success: false, errorCode: ERROR_CODES.network, message });
9
11
  /** Read-only view of the current license. */
10
12
  export class License {
11
13
  payload;
@@ -15,13 +17,41 @@ export class License {
15
17
  get key() { return this.payload.licenseKey; }
16
18
  get customer() { return this.payload.customer; }
17
19
  get kind() { return this.payload.kind; }
20
+ /**
21
+ * What the offline check enforces: the end of grace when the license has grace days; null when perpetual or when the expiration
22
+ * strategy keeps the license working after expiry. Show licenseExpiresAt to the user instead.
23
+ */
18
24
  get expiresAt() { return this.payload.expiresAt ? new Date(this.payload.expiresAt) : null; }
25
+ /** The license's own expiry, for showing to the user (null = perpetual); never enforced. */
26
+ get licenseExpiresAt() { return this.payload.licenseExpiresAt ? new Date(this.payload.licenseExpiresAt) : null; }
19
27
  get offlineUntil() { return new Date(this.payload.offlineUntil); }
20
28
  get isTest() { return this.payload.test === true; }
21
29
  get isFloating() { return this.payload.floating === true; }
22
30
  get features() { return this.payload.entitlements ?? []; }
23
31
  get metadata() { return this.payload.metadata ?? {}; }
24
32
  hasFeature(code) { return this.features.includes(code); }
33
+ /**
34
+ * A keyless trial (startTrial()): the token says `trial: true`. A keyed license of kind "trial" is an ordinary license (see
35
+ * `kind`): it refreshes and deactivates on the server.
36
+ */
37
+ get isTrial() { return this.payload.trial === true; }
38
+ /** Device matching applied offline: 'default', 'strict' or 'loose'. */
39
+ get matching() { return this.payload.matching ?? 'default'; }
40
+ /** The newest app version this license may run; null = any. */
41
+ get maxAppVersion() { return this.payload.maxAppVersion ?? null; }
42
+ /** The license has expired but keeps working (expiration strategy maintain or allow); show a renewal notice. */
43
+ get isExpired() { return this.payload.expired === true; }
44
+ /** The license expired and works until graceUntil (grace period). */
45
+ get isInGrace() { return !!this.payload.graceUntil; }
46
+ get graceUntil() { return this.payload.graceUntil ? new Date(this.payload.graceUntil) : null; }
47
+ /** Floating: the seat is borrowed for offline use until this time. */
48
+ get borrowedUntil() { return this.payload.borrowedUntil ? new Date(this.payload.borrowedUntil) : null; }
49
+ get isBorrowed() { return !!this.payload.borrowedUntil; }
50
+ /** Use counting: the license's limit, and the uses when the token was issued. */
51
+ get maxUses() { return this.payload.maxUses ?? null; }
52
+ get uses() { return this.payload.uses ?? null; }
53
+ /** More devices are active than the license's seats (overdraft). */
54
+ get isOverage() { return this.payload.overage === true; }
25
55
  }
26
56
  const messages = {
27
57
  Valid: 'The license is valid.',
@@ -34,10 +64,12 @@ const messages = {
34
64
  ClockTampered: "The device's clock looks wrong. Correct it and connect to the internet.",
35
65
  Unverified: 'Connect to the internet to verify the license.',
36
66
  Suspended: 'The license has been suspended.',
67
+ AppVersionNotAllowed: 'This version of the app is newer than the license covers. Contact your software vendor to upgrade.',
37
68
  };
38
69
  /**
39
70
  * 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.
71
+ * deactivation, keyless trials, floating leases (with borrowing) and use counting. Never put an API key in client code; this
72
+ * class needs only the public key.
41
73
  */
42
74
  export class LicenseClient {
43
75
  options;
@@ -56,11 +88,62 @@ export class LicenseClient {
56
88
  this.dir = options.storageDir ?? defaultStorageDir(options.product);
57
89
  }
58
90
  now() { return this.options.now?.() ?? new Date(); }
91
+ /** The device clock (UTC, ISO 8601) sent as `clientTime`; the server refuses requests whose clock is too far off. */
92
+ clientTime() { return this.now().toISOString(); }
59
93
  fingerprint() { return (this.fp ??= this.options.fingerprint?.() ?? collectFingerprint(this.options.vendor, this.options.product)); }
60
94
  /** Whether a license for this device would match it again; if not, activating would only use up a seat. */
61
95
  identified() { return fingerprintMatches(this.fingerprint(), this.fingerprint()); }
62
96
  get tokenPath() { return join(this.dir, 'license.lic'); }
63
97
  get historyPath() { return join(this.dir, 'license.seen'); }
98
+ /**
99
+ * What requests carry as `virtualMachine`: null (not sent) when detection is off (and no answer is set) or couldn't tell. The
100
+ * probe runs once per process without blocking (a child process with a 5-second limit); requests await the cached result.
101
+ */
102
+ async virtualMachineField() {
103
+ const o = this.options.virtualMachine;
104
+ if (typeof o === 'boolean')
105
+ return o;
106
+ try {
107
+ if (typeof o === 'function')
108
+ return (await o()) ?? null;
109
+ return this.options.detectVirtualMachine === false ? null : await detectVirtualMachine();
110
+ }
111
+ catch {
112
+ return null;
113
+ }
114
+ }
115
+ /**
116
+ * Starts virtual machine detection in the background and returns at once, so the first activate, checkout or trial doesn't
117
+ * wait for it. Optional: without it the probe starts at the first activate, checkout or trial (which then waits for it, at
118
+ * most the 5-second probe limit). It never runs at app start or in the constructor. Runs once per process; does nothing when
119
+ * detection is off or the `virtualMachine` option gives the answer.
120
+ */
121
+ warmUpVirtualMachineDetection() {
122
+ if (this.options.virtualMachine !== undefined || this.options.detectVirtualMachine === false)
123
+ return;
124
+ void detectVirtualMachine().catch(() => null);
125
+ }
126
+ /**
127
+ * Whether the app runs in a virtual machine or container (best effort): the `virtualMachine` option if set, otherwise
128
+ * detected (false when detection is off or failed). Sent with activations, floating checkouts and trials.
129
+ */
130
+ async isVirtualMachineAsync() { return (await this.virtualMachineField()) === true; }
131
+ /**
132
+ * Synchronous form of isVirtualMachineAsync(). Never starts a second probe: returns the cached result once detection has
133
+ * finished, and false while the asynchronous probe is still running. Blocks only before the first detection has started (up
134
+ * to 5 seconds, once per process). A custom detector that returns a promise counts as false here.
135
+ * @deprecated Use isVirtualMachineAsync().
136
+ */
137
+ isVirtualMachine() {
138
+ const o = this.options.virtualMachine;
139
+ if (typeof o === 'boolean')
140
+ return o;
141
+ if (typeof o === 'function') {
142
+ const v = o();
143
+ return v === true;
144
+ }
145
+ return this.options.detectVirtualMachine === false ? false : detectVirtualMachineSync();
146
+ }
64
147
  /** The current license after the last check, or null. */
65
148
  get license() {
66
149
  const p = this.readPayload();
@@ -74,7 +157,7 @@ export class LicenseClient {
74
157
  const payload = verifyToken(token, this.key);
75
158
  const lastSeen = decodeRunHistory(this.read(this.historyPath), this.options.vendor, this.options.product, this.fingerprint());
76
159
  const now = this.now();
77
- const status = evaluate(payload, this.options.product, this.fingerprint(), now, lastSeen);
160
+ const status = evaluate(payload, this.options.product, this.fingerprint(), now, lastSeen, this.options.appVersion);
78
161
  if ((status === 'Valid' || status === 'Expired' || status === 'OfflineTooLong') && (!lastSeen || now > lastSeen))
79
162
  this.write(this.historyPath, encodeRunHistory(now, this.options.vendor, this.options.product, this.fingerprint()));
80
163
  if (payload?.test && !this.warnedTest) {
@@ -86,8 +169,10 @@ export class LicenseClient {
86
169
  /** Call on startup: evaluates offline and refreshes online when due or when only the server can clear the state. */
87
170
  async check() {
88
171
  let result = this.evaluateLocal();
172
+ if (result.license?.payload.trial === true)
173
+ return result; // trials are never refreshed; startTrial() asks again
89
174
  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)) {
175
+ if (due || ['Expired', 'Suspended', 'OfflineTooLong', 'ClockTampered', 'Unverified', 'AppVersionNotAllowed'].includes(result.status)) {
91
176
  try {
92
177
  await this.refresh(result.status === 'ClockTampered' ? ['clock_rollback'] : result.status === 'Unverified' ? ['history_missing'] : undefined);
93
178
  }
@@ -98,21 +183,26 @@ export class LicenseClient {
98
183
  }
99
184
  return result;
100
185
  }
186
+ async activationBody(licenseKey, machineName) {
187
+ const virtualMachine = await this.virtualMachineField();
188
+ return {
189
+ licenseKey: licenseKey.trim(), product: this.options.product, fingerprint: this.fingerprint(),
190
+ machineName: machineName ?? this.options.machineName ?? hostname(), appVersion: this.options.appVersion ?? null,
191
+ virtualMachine, clientTime: this.clientTime(),
192
+ };
193
+ }
101
194
  /** Activates `licenseKey` on this device (or checks out a floating lease if the license is floating). */
102
195
  async activate(licenseKey, machineName) {
103
196
  if (!licenseKey?.trim())
104
197
  return { success: false, errorCode: 'bad_request', message: 'Enter the license key.' };
105
198
  if (!this.identified())
106
199
  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
- };
200
+ const body = await this.activationBody(licenseKey, machineName);
111
201
  let r = await this.post('/api/client/v2/activate', body).catch(() => null);
112
202
  if (r && !r.ok && r.error?.code === 'bad_request' && /floating/i.test(r.error.message))
113
203
  r = await this.post('/api/client/v2/floating/checkout', body).catch(() => null);
114
204
  if (!r)
115
- return { success: false, errorCode: 'network', message: 'Could not connect to the license server.' };
205
+ return offline();
116
206
  if (!r.ok)
117
207
  return { success: false, errorCode: r.error?.code, message: r.error?.message ?? `Server error (${r.status}).` };
118
208
  if (!this.saveIfValid(r.token))
@@ -126,31 +216,138 @@ export class LicenseClient {
126
216
  async checkout(licenseKey) {
127
217
  if (!this.identified())
128
218
  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);
219
+ const r = await this.post('/api/client/v2/floating/checkout', await this.activationBody(licenseKey)).catch(() => null);
131
220
  if (!r)
132
- return { success: false, errorCode: 'network', message: 'Could not connect to the license server.' };
221
+ return offline();
133
222
  if (!r.ok)
134
223
  return { success: false, errorCode: r.error?.code, message: r.error?.message ?? `Server error (${r.status}).` };
135
224
  this.saveIfValid(r.token);
136
225
  this.startHeartbeat();
137
226
  return { success: true, message: 'Floating license checked out.' };
138
227
  }
139
- /** Releases a floating seat. */
228
+ /**
229
+ * Starts this device's keyless trial, or gets the running one back (the server keeps one trial per device and product). Needs
230
+ * the `keyId` option. The trial token is stored and checked like a license (kind "trial"); it is never refreshed.
231
+ */
232
+ async startTrial() {
233
+ if (!this.options.keyId)
234
+ return { success: false, errorCode: 'bad_request', message: "Set keyId (the environment's signing key id) to start trials." };
235
+ if (!this.identified())
236
+ return { ...notIdentified, message: "This device can't be identified, so a trial can't start on it." };
237
+ const virtualMachine = await this.virtualMachineField();
238
+ const r = await this.post('/api/client/v2/trial', {
239
+ keyId: this.options.keyId, product: this.options.product, fingerprint: this.fingerprint(),
240
+ machineName: this.options.machineName ?? hostname(), appVersion: this.options.appVersion ?? null,
241
+ virtualMachine, clientTime: this.clientTime(),
242
+ }).catch(() => null);
243
+ if (!r)
244
+ return offline();
245
+ if (!r.ok)
246
+ return { success: false, errorCode: r.error?.code, message: r.error?.message ?? `Server error (${r.status}).` };
247
+ if (!this.saveIfValid(r.token))
248
+ return { success: false, errorCode: 'invalid_token', message: 'The server returned an invalid license.' };
249
+ const result = this.evaluateLocal();
250
+ return result.valid ? { success: true, message: 'The trial has started.' } : { success: false, errorCode: result.status, message: messages[result.status] };
251
+ }
252
+ /**
253
+ * Floating: keeps this device's seat for offline use for `hours` (up to the license's limit). Return it early with
254
+ * returnBorrow() (the same as release()). Refused without a request with `no_license` when there is no license and
255
+ * `borrow_not_allowed` when it isn't a checked-out floating license; a keyless trial gets `bad_request` (it is never sent to the
256
+ * server). The license file is removed only on a revoking code or lease_expired; other refusals keep it.
257
+ */
258
+ async borrow(hours) {
259
+ if (!Number.isInteger(hours) || hours < 1)
260
+ return { success: false, errorCode: 'bad_request', message: 'Borrow for a whole number of hours (at least 1).' };
261
+ const token = this.read(this.tokenPath);
262
+ if (!token)
263
+ return { success: false, errorCode: ERROR_CODES.noLicense, message: 'There is no license on this device.' };
264
+ const payload = verifyToken(token, this.key);
265
+ if (payload?.trial === true)
266
+ return { success: false, errorCode: 'bad_request', message: "A trial can't be borrowed." };
267
+ if (payload?.floating !== true)
268
+ return { success: false, errorCode: ERROR_CODES.borrowNotAllowed, message: 'Only a checked-out floating license can be borrowed.' };
269
+ const r = await this.post('/api/client/v2/floating/borrow', {
270
+ token, fingerprint: this.fingerprint(), hours, appVersion: this.options.appVersion ?? null, clientTime: this.clientTime(),
271
+ }).catch(() => null);
272
+ if (!r)
273
+ return offline('Borrowing a license needs an internet connection.');
274
+ if (!r.ok) {
275
+ if (removesLicense(r)) {
276
+ this.stopHeartbeat();
277
+ this.clear();
278
+ this.lastServerMessage = r.error.message;
279
+ }
280
+ return { success: false, errorCode: r.error?.code, message: r.error?.message ?? `Server error (${r.status}).` };
281
+ }
282
+ if (!this.saveIfValid(r.token))
283
+ return { success: false, errorCode: 'invalid_token', message: 'The server returned an invalid license.' };
284
+ const result = this.evaluateLocal();
285
+ return result.valid
286
+ ? { success: true, message: `The license is borrowed until ${result.license?.borrowedUntil?.toISOString() ?? '?'}.` }
287
+ : { success: false, errorCode: result.status, message: messages[result.status] };
288
+ }
289
+ /**
290
+ * Licenses with a use limit: consumes `count` uses on the server; refused with use_limit_reached when they are used up. A count
291
+ * below 1 is refused with `bad_request` and no license with `no_license`, both without a request; so is a keyless trial
292
+ * (`bad_request`: it is never sent to the server). The license file is removed only on a revoking code or lease_expired; any
293
+ * other refusal keeps it.
294
+ */
295
+ async consume(count = 1) {
296
+ if (!Number.isInteger(count) || count < 1)
297
+ return { success: false, errorCode: 'bad_request', message: 'Consume a whole number of uses (at least 1).' };
298
+ const token = this.read(this.tokenPath);
299
+ if (!token)
300
+ return { success: false, errorCode: ERROR_CODES.noLicense, message: 'There is no license on this device.' };
301
+ if (verifyToken(token, this.key)?.trial === true)
302
+ return { success: false, errorCode: 'bad_request', message: 'A trial has no uses to consume.' };
303
+ const r = await this.post('/api/client/v2/use', { token, fingerprint: this.fingerprint(), count }).catch(() => null);
304
+ if (!r)
305
+ return { success: false, errorCode: ERROR_CODES.network, message: 'Could not connect to the license server.' };
306
+ if (!r.ok) {
307
+ if (removesLicense(r)) {
308
+ this.stopHeartbeat();
309
+ this.clear();
310
+ this.lastServerMessage = r.error.message;
311
+ }
312
+ return { success: false, errorCode: r.error?.code, message: r.error?.message ?? `Server error (${r.status}).` };
313
+ }
314
+ const uses = typeof r.json?.uses === 'number' ? r.json.uses : undefined;
315
+ const maxUses = typeof r.json?.maxUses === 'number' ? r.json.maxUses : undefined;
316
+ return { success: true, uses, maxUses, message: `${uses} of ${maxUses} uses.` };
317
+ }
318
+ /** Releases a floating seat (also returns a borrowed seat early). */
140
319
  async release() {
141
320
  this.stopHeartbeat();
142
321
  return this.deactivate();
143
322
  }
323
+ /**
324
+ * Returns a borrowed floating seat early (releases the seat of a floating license). On a node-locked license or a keyless trial
325
+ * it returns `borrow_not_allowed` without a request, so it can never use up a deactivation. Without a license it succeeds.
326
+ */
327
+ async returnBorrow() {
328
+ const token = this.read(this.tokenPath);
329
+ if (!token)
330
+ return { success: true, message: 'There is no license on this device.' };
331
+ const payload = verifyToken(token, this.key);
332
+ if (payload?.floating !== true || payload.trial === true)
333
+ return { success: false, errorCode: ERROR_CODES.borrowNotAllowed, message: 'Only a floating license can be borrowed and returned.' };
334
+ return this.release();
335
+ }
144
336
  /** Removes the license from this device and frees its seat on the server. */
145
337
  async deactivate() {
146
338
  this.stopHeartbeat();
147
339
  const token = this.read(this.tokenPath);
148
340
  if (!token)
149
341
  return { success: true, message: 'There is no license on this device.' };
150
- const floating = verifyToken(token, this.key)?.floating === true;
342
+ const payload = verifyToken(token, this.key);
343
+ if (payload?.trial === true) {
344
+ this.clear(); // a trial has no seat to free
345
+ return { success: true, message: 'The license has been removed from this device.' };
346
+ }
347
+ const floating = payload?.floating === true;
151
348
  const r = await this.post(floating ? '/api/client/v2/floating/release' : '/api/client/v2/deactivate', { token, fingerprint: this.fingerprint() }).catch(() => null);
152
349
  if (!r)
153
- return { success: false, errorCode: 'network', message: 'Removing the license needs an internet connection.' };
350
+ return offline('Removing the license needs an internet connection.');
154
351
  if (!r.ok && !(r.error && REVOKING_CODES.has(r.error.code)))
155
352
  return { success: false, errorCode: r.error?.code, message: r.error?.message ?? `Server error (${r.status}).` };
156
353
  this.clear();
@@ -158,22 +355,24 @@ export class LicenseClient {
158
355
  ? { success: true, message: 'The license has been removed from this device.' }
159
356
  : { success: false, errorCode: 'wrong_machine', message: r.error.message };
160
357
  }
161
- /** Asks the server for a fresh token now (floating licenses: a heartbeat). */
358
+ /** Asks the server for a fresh token now (floating licenses: a heartbeat). A keyless trial is never sent: it stays as it is. */
162
359
  async refresh(anomalies) {
163
360
  const token = this.read(this.tokenPath);
164
361
  if (!token)
165
362
  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 });
363
+ const payload = verifyToken(token, this.key);
364
+ if (payload?.trial === true)
365
+ return;
366
+ const floating = payload?.floating === true;
367
+ const r = await this.post(floating ? '/api/client/v2/floating/heartbeat' : '/api/client/v2/refresh', { token, fingerprint: this.fingerprint(), appVersion: this.options.appVersion ?? null, anomalies: anomalies ?? null, clientTime: this.clientTime() });
168
368
  if (r.ok)
169
369
  this.saveIfValid(r.token);
170
- else if (r.error && REVOKING_CODES.has(r.error.code)) {
370
+ else if (removesLicense(r)) {
171
371
  this.clear();
172
372
  this.lastServerMessage = r.error.message;
173
373
  }
174
- else if (r.error?.code === 'lease_expired') {
175
- this.clear();
176
- this.lastServerMessage = r.error.message;
374
+ else if (r.error) {
375
+ this.lastServerMessage = r.error.message; // e.g. clock_offset or app_version_not_allowed: the license stays
177
376
  }
178
377
  }
179
378
  /** A user-facing sentence for a status. */
@@ -203,7 +402,7 @@ export class LicenseClient {
203
402
  });
204
403
  const text = await res.text();
205
404
  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 };
405
+ return res.ok ? { ok: true, status: res.status, token: json.token, json } : { ok: false, status: res.status, error: json.code ? json : undefined };
207
406
  }
208
407
  finally {
209
408
  clearTimeout(timer);
@@ -238,6 +437,10 @@ export class LicenseClient {
238
437
  writeFileSync(path, value, 'utf8');
239
438
  }
240
439
  }
440
+ /** The one rule (refresh, consume, borrow) for removing the local license: a revoking code or lease_expired. */
441
+ function removesLicense(r) {
442
+ return !!r.error && (REVOKING_CODES.has(r.error.code) || r.error.code === 'lease_expired');
443
+ }
241
444
  function defaultStorageDir(product) {
242
445
  const base = platform() === 'win32'
243
446
  ? process.env.LOCALAPPDATA ?? join(homedir(), 'AppData', 'Local')
package/dist/core.d.ts CHANGED
@@ -8,6 +8,8 @@ export interface Fingerprint {
8
8
  /** windows, macos, linux, android or ios. */
9
9
  os?: string | null;
10
10
  }
11
+ /** Device matching: 'default' (board id + one other, or 2 of 3), 'strict' (every registered part) or 'loose' (any one part). */
12
+ export type MatchingStrategy = 'default' | 'strict' | 'loose';
11
13
  /** The signed license content (token payload). v2 fields are optional. */
12
14
  export interface LicensePayload {
13
15
  licenseId: string;
@@ -28,8 +30,29 @@ export interface LicensePayload {
28
30
  metadata?: Record<string, unknown>;
29
31
  floating?: boolean;
30
32
  leaseExpiresAt?: string;
33
+ /** Device matching applied offline: 'strict' or 'loose'; absent = default. */
34
+ matching?: MatchingStrategy | string;
35
+ /** The newest app version this license may run; absent = any. */
36
+ maxAppVersion?: string;
37
+ /** The license has expired but its strategy keeps it working (maintain or allow); expiresAt is then absent. */
38
+ expired?: boolean;
39
+ /** The license expired and works until this time (grace); expiresAt is the same moment. */
40
+ graceUntil?: string;
41
+ /** Floating: the seat is borrowed for offline use until this time. */
42
+ borrowedUntil?: string;
43
+ /** Use counting: the license's limit, and the uses when the token was issued. */
44
+ maxUses?: number;
45
+ uses?: number;
46
+ /** More devices are active than the license's seats (overdraft). */
47
+ overage?: boolean;
48
+ /** The license's own expiry, for display (absent/null = perpetual); never enforced (the offline check uses expiresAt). */
49
+ licenseExpiresAt?: string | null;
50
+ /** A keyless trial: valid until expiresAt, never refreshed. */
51
+ trial?: boolean;
31
52
  }
32
- export type LicenseStatus = 'Valid' | 'Missing' | 'InvalidSignature' | 'WrongProduct' | 'WrongMachine' | 'Expired' | 'OfflineTooLong' | 'ClockTampered' | 'Unverified' | 'Suspended';
53
+ export type LicenseStatus = 'Valid' | 'Missing' | 'InvalidSignature' | 'WrongProduct' | 'WrongMachine' | 'Expired' | 'OfflineTooLong' | 'ClockTampered' | 'Unverified' | 'Suspended'
54
+ /** The app is newer than the license's maxAppVersion. */
55
+ | 'AppVersionNotAllowed';
33
56
  export declare const UNAVAILABLE = "none";
34
57
  /** The clock going back slightly during NTP sync is normal. */
35
58
  export declare const CLOCK_TOLERANCE_MS: number;
@@ -37,6 +60,53 @@ export declare const CLOCK_TOLERANCE_MS: number;
37
60
  export declare const ISSUED_AT_TOLERANCE_MS: number;
38
61
  /** Error codes on which the local license is deleted; on any other error (network, 402…) it is kept. */
39
62
  export declare const REVOKING_CODES: Set<string>;
63
+ /** The `code` values the client API returns (`ActivationResult.errorCode`, `UseResult.errorCode`). */
64
+ export declare const ERROR_CODES: {
65
+ readonly badRequest: "bad_request";
66
+ /** Returned by the SDK without a request: there is no license on this device (borrow, consume). */
67
+ readonly noLicense: "no_license";
68
+ readonly network: "network";
69
+ readonly licenseNotFound: "license_not_found";
70
+ readonly wrongProduct: "wrong_product";
71
+ readonly licenseSuspended: "license_suspended";
72
+ readonly licenseExpired: "license_expired";
73
+ readonly licenseRevoked: "license_revoked";
74
+ readonly licenseInUse: "license_in_use";
75
+ readonly activationRevoked: "activation_revoked";
76
+ readonly wrongMachine: "wrong_machine";
77
+ readonly invalidToken: "invalid_token";
78
+ readonly seatLimitReached: "seat_limit_reached";
79
+ readonly leaseExpired: "lease_expired";
80
+ readonly tenantSuspended: "tenant_suspended";
81
+ readonly insufficientBalance: "insufficient_balance";
82
+ readonly rateLimited: "rate_limited";
83
+ readonly deviceNotIdentified: "device_not_identified";
84
+ readonly trialUnavailable: "trial_unavailable";
85
+ readonly trialEnded: "trial_ended";
86
+ /** The vendor blocked the address the request came from. */
87
+ readonly ipBlocked: "ip_blocked";
88
+ /** This device used up the license's lifetime deactivations; only the vendor can free the seat. */
89
+ readonly deactivationLimitReached: "deactivation_limit_reached";
90
+ /** The vendor banned this device from the license. */
91
+ readonly deviceBanned: "device_banned";
92
+ /** Too many failed activations: new devices are locked until the vendor unlocks the license. */
93
+ readonly licenseLocked: "license_locked";
94
+ /** The device clock is too far from the server's. */
95
+ readonly clockOffset: "clock_offset";
96
+ /** The app version is older than the product's minimum or newer than the license's maximum. */
97
+ readonly appVersionNotAllowed: "app_version_not_allowed";
98
+ /** The license can't be used from this country or network. */
99
+ readonly locationNotAllowed: "location_not_allowed";
100
+ /** Borrowing is off for the license, or more hours were asked than it allows. */
101
+ readonly borrowNotAllowed: "borrow_not_allowed";
102
+ /** A seat was just released by another device and can't be taken yet. */
103
+ readonly seatCoolingDown: "seat_cooling_down";
104
+ /** All uses of the license are used up. */
105
+ readonly useLimitReached: "use_limit_reached";
106
+ /** The product doesn't allow new activations or trials on virtual machines. */
107
+ readonly virtualMachineNotAllowed: "virtual_machine_not_allowed";
108
+ };
109
+ export type ErrorCode = (typeof ERROR_CODES)[keyof typeof ERROR_CODES];
40
110
  export declare function importPublicKey(pem: string): KeyObject;
41
111
  /**
42
112
  * Verifies `base64url(json).base64url(signature)` (ECDSA P-256 / SHA-256, IEEE P1363 r||s) over the ASCII bytes of the encoded
@@ -48,10 +118,30 @@ export declare function verifyToken(token: string, publicKey: KeyObject | string
48
118
  * `vendor` is the organization ID from the dashboard (ten_...); it never changes, so device identities stay stable.
49
119
  */
50
120
  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;
121
+ /** Host platforms whose installations are licensed like devices (an app inside YouTrack, not a computer). */
122
+ export declare const HOST_PLATFORMS: readonly string[];
123
+ /**
124
+ * Whether `presented` is the device `registered` was issued for (call on the registered fingerprint). `strategy` is the token's
125
+ * `matching` field: default (board id + one other part, or 2 of 3 without a board id), 'strict' (every part the registered device
126
+ * has) or 'loose' (any one part). When both sides name an operating system it must be the same; host installations always
127
+ * match exactly (same platform and id).
128
+ */
129
+ export declare function fingerprintMatches(registered: Fingerprint, presented: Fingerprint, strategy?: MatchingStrategy | string | null): boolean;
130
+ /** A version the server compares: after trimming whitespace, 1 to 50 characters and the first is an ASCII digit. */
131
+ export declare function isVersion(v: string | null | undefined): v is string;
132
+ /**
133
+ * "1.10.2" > "1.9"; a leading v/V is ignored; missing parts are 0; anything after the leading run of ASCII digits and dots
134
+ * (-beta, +build) is ignored; a part above 2147483647 counts as 0. Same as the server (test-vectors/versions.json).
135
+ */
136
+ export declare function compareVersions(a: string, b: string): number;
137
+ /** Whether `appVersion` may run under a license limited to `maxAppVersion` (unknown or missing versions aren't refused). */
138
+ export declare function appVersionAllowed(maxAppVersion: string | null | undefined, appVersion: string | null | undefined): boolean;
139
+ /**
140
+ * Offline check, identical in every SDK (see the shared test vectors). `appVersion` (optional) is checked against the token's
141
+ * `maxAppVersion`. Grace (`graceUntil`) and expired-but-kept licenses (`expired: true`) need nothing extra: the server sets
142
+ * `expiresAt` to the end of grace, or leaves it out.
143
+ */
144
+ export declare function evaluate(payload: LicensePayload | null, product: string, machine: Fingerprint, now: Date, lastSeen: Date | null, appVersion?: string | null): LicenseStatus;
55
145
  /** Tamper-evident "last run" record: `{epochMs}.{hmac}` keyed to the product and device. */
56
146
  export declare function encodeRunHistory(at: Date, vendor: string, product: string, machine: Fingerprint): string;
57
147
  export declare function decodeRunHistory(value: string | null | undefined, vendor: string, product: string, machine: Fingerprint): Date | null;
package/dist/core.js CHANGED
@@ -8,6 +8,52 @@ export const ISSUED_AT_TOLERANCE_MS = 24 * 60 * 60 * 1000;
8
8
  export const REVOKING_CODES = new Set([
9
9
  'license_not_found', 'license_suspended', 'license_expired', 'activation_revoked', 'wrong_machine', 'invalid_token', 'license_revoked',
10
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
+ };
11
57
  function fromBase64Url(text) {
12
58
  if (!/^[A-Za-z0-9_-]*$/.test(text) || text.length % 4 === 1)
13
59
  throw new Error('invalid base64url');
@@ -50,12 +96,30 @@ export function hashComponent(vendor, product, part, raw) {
50
96
  return UNAVAILABLE;
51
97
  return createHash('sha256').update(`${vendor}:${product}:${part}:${raw.trim().toUpperCase()}`, 'utf8').digest('hex');
52
98
  }
99
+ /** Host platforms whose installations are licensed like devices (an app inside YouTrack, not a computer). */
100
+ export const HOST_PLATFORMS = ['youtrack'];
53
101
  const available = (v) => !!v && v !== UNAVAILABLE;
54
102
  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) {
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);
57
113
  if (registered.os && presented.os && registered.os.toLowerCase() !== presented.os.toLowerCase())
58
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
+ }
59
123
  let matches = 0;
60
124
  if (same(registered.machineId, presented.machineId))
61
125
  matches++;
@@ -65,16 +129,70 @@ export function fingerprintMatches(registered, presented) {
65
129
  matches++;
66
130
  return available(registered.boardId) ? same(registered.boardId, presented.boardId) && matches >= 1 : matches >= 2;
67
131
  }
68
- /** Offline check, identical in every SDK (see the shared test vectors). */
69
- export function evaluate(payload, product, machine, now, lastSeen) {
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) {
70
186
  if (!payload)
71
187
  return 'InvalidSignature';
72
188
  if (payload.product.toLowerCase() !== product.toLowerCase())
73
189
  return 'WrongProduct';
74
- if (!fingerprintMatches(payload.fingerprint, machine))
190
+ if (!fingerprintMatches(payload.fingerprint, machine, payload.matching))
75
191
  return 'WrongMachine';
76
192
  if (payload.suspended)
77
193
  return 'Suspended';
194
+ if (!appVersionAllowed(payload.maxAppVersion, appVersion))
195
+ return 'AppVersionNotAllowed';
78
196
  if (!lastSeen)
79
197
  return 'Unverified';
80
198
  const t = now.getTime();
package/dist/index.d.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  export * from './core.js';
2
2
  export { collectFingerprint } from './fingerprint.js';
3
- export { License, LicenseClient, type ActivationResult, type CheckResult, type LicenseClientOptions } from './client.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';
4
5
  export { ApiRequestError, ManagementClient, verifyWebhook, type ManagementOptions } from './management.js';
package/dist/index.js CHANGED
@@ -1,4 +1,5 @@
1
1
  export * from './core.js';
2
2
  export { collectFingerprint } from './fingerprint.js';
3
+ export { detectVirtualMachine, isVirtualMachine, isVirtualHardware, cpuInfoHasHypervisor, cgroupIsContainer, sysctlSaysVirtual, isWsl, linuxIsVirtual, parseWindowsComputerSystem, VM_PROBE_TIMEOUT_MS, } from './vm.js';
3
4
  export { License, LicenseClient } from './client.js';
4
5
  export { ApiRequestError, ManagementClient, verifyWebhook } from './management.js';
@@ -48,6 +48,21 @@ export declare class ManagementClient {
48
48
  notes?: string;
49
49
  }) => Promise<any>;
50
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>;
51
66
  updateLicense: (id: string, patch: Record<string, unknown>) => Promise<any>;
52
67
  suspendLicense: (id: string) => Promise<any>;
53
68
  resumeLicense: (id: string) => Promise<any>;
@@ -36,6 +36,13 @@ export class ManagementClient {
36
36
  createCustomer = (body) => this.request('POST', '/customers', body);
37
37
  createLicenses = (body) => this.request('POST', '/licenses', body);
38
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)}`);
39
46
  updateLicense = (id, patch) => this.request('PATCH', `/licenses/${id}`, patch);
40
47
  suspendLicense = (id) => this.request('POST', `/licenses/${id}/suspend`);
41
48
  resumeLicense = (id) => this.request('POST', `/licenses/${id}/resume`);
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;
package/dist/vm.js ADDED
@@ -0,0 +1,184 @@
1
+ import { execFileSync, spawn } from 'node:child_process';
2
+ import { existsSync, readFileSync } from 'node:fs';
3
+ import { platform } from 'node:os';
4
+ // Best-effort detection of virtual machines and containers, without admin rights or dependencies. Products can refuse new
5
+ // activations and trials on virtual machines; the client sends the result as `virtualMachine`. The rules are the same in every
6
+ // LicenseRail SDK (license-rules.md, "Virtual machine detection") and deliberately narrow: a false positive refuses a paying
7
+ // customer. The parsers are exported so they can be tested with sample text.
8
+ /** How long the probe (PowerShell on Windows, sysctl on macOS) may run before it is killed. */
9
+ export const VM_PROBE_TIMEOUT_MS = 5000;
10
+ const HYPERVISOR_NAME = /\b(?:vmware|virtualbox|innotek|qemu|kvm|xen|hvm domu|parallels|bochs|bhyve)\b/i;
11
+ const HYPER_V_GUEST = /\bvirtual machine\b/i;
12
+ const CONTAINER_CGROUP = ['docker', 'kubepods', 'containerd', 'lxc'];
13
+ const WINDOWS_PROBE = ['-NoProfile', '-NonInteractive', '-Command', '$c = Get-CimInstance Win32_ComputerSystem; $c.Manufacturer; $c.Model'];
14
+ /**
15
+ * Whether a system manufacturer and model (Windows Win32_ComputerSystem; Linux /sys/class/dmi/id sys_vendor and product_name)
16
+ * name a hypervisor: VMware, VirtualBox, innotek, QEMU, KVM, Xen, HVM domU, Parallels, Bochs or bhyve as whole words
17
+ * (case-insensitive), or "Virtual Machine" made by "Microsoft Corporation" (a Hyper-V guest). Cloud vendor names are not on the
18
+ * list: they also sell bare metal.
19
+ */
20
+ export function isVirtualHardware(manufacturer, model) {
21
+ const m = (manufacturer ?? '').trim();
22
+ const p = (model ?? '').trim();
23
+ if (!m && !p)
24
+ return false;
25
+ if (m.toLowerCase() === 'microsoft corporation' && HYPER_V_GUEST.test(p))
26
+ return true;
27
+ return HYPERVISOR_NAME.test(m) || HYPERVISOR_NAME.test(p);
28
+ }
29
+ /**
30
+ * The Windows probe's output (Win32_ComputerSystem Manufacturer, then Model, one per line); null when there is no output (the
31
+ * probe failed). Windows hosts with Hyper-V or VBS enabled report their real maker and model, so they don't match.
32
+ */
33
+ export function parseWindowsComputerSystem(output) {
34
+ const lines = (output ?? '').split(/\r?\n/).map((l) => l.trim()).filter(Boolean);
35
+ return lines.length === 0 ? null : isVirtualHardware(lines[0], lines[1]);
36
+ }
37
+ /** Whether /proc/sys/kernel/osrelease is a WSL kernel (contains "microsoft" or "WSL"). WSL is not a virtual machine. */
38
+ export function isWsl(osrelease) {
39
+ return !!osrelease && /microsoft|wsl/i.test(osrelease);
40
+ }
41
+ /** Whether /proc/cpuinfo lists the "hypervisor" CPU flag. */
42
+ export function cpuInfoHasHypervisor(cpuinfo) {
43
+ return !!cpuinfo && cpuinfo.split('\n').some((l) => l.startsWith('flags') && /\bhypervisor\b/.test(l));
44
+ }
45
+ /** Whether /proc/1/cgroup shows a container runtime (docker, kubepods, containerd or lxc). */
46
+ export function cgroupIsContainer(cgroup) {
47
+ const c = (cgroup ?? '').toLowerCase();
48
+ return CONTAINER_CGROUP.some((w) => c.includes(w));
49
+ }
50
+ /** macOS `sysctl -n kern.hv_vmm_present`: "1" in a virtual machine. */
51
+ export function sysctlSaysVirtual(output) {
52
+ return output?.trim() === '1';
53
+ }
54
+ /**
55
+ * The Linux rule: false under WSL; otherwise true when the DMI vendor or product names a hypervisor, the CPU has the
56
+ * `hypervisor` flag, or the process runs in a container.
57
+ */
58
+ export function linuxIsVirtual(p) {
59
+ if (isWsl(p.osrelease))
60
+ return false;
61
+ return isVirtualHardware(p.sysVendor, p.productName) || cpuInfoHasHypervisor(p.cpuinfo) || !!p.containerFile || cgroupIsContainer(p.cgroup);
62
+ }
63
+ function read(path) {
64
+ try {
65
+ return existsSync(path) ? readFileSync(path, 'utf8') : null;
66
+ }
67
+ catch {
68
+ return null;
69
+ }
70
+ }
71
+ function linuxProbe() {
72
+ return linuxIsVirtual({
73
+ osrelease: read('/proc/sys/kernel/osrelease'),
74
+ sysVendor: read('/sys/class/dmi/id/sys_vendor'),
75
+ productName: read('/sys/class/dmi/id/product_name'),
76
+ cpuinfo: read('/proc/cpuinfo'),
77
+ containerFile: existsSync('/.dockerenv') || existsSync('/run/.containerenv'),
78
+ cgroup: read('/proc/1/cgroup'),
79
+ });
80
+ }
81
+ /** Runs a probe without a window; resolves null on error, a non-zero exit or the timeout (the process is killed). */
82
+ function run(cmd, args) {
83
+ return new Promise((resolve) => {
84
+ let out = '';
85
+ let done = false;
86
+ const finish = (value) => {
87
+ if (done)
88
+ return;
89
+ done = true;
90
+ clearTimeout(timer);
91
+ resolve(value);
92
+ };
93
+ let child;
94
+ try {
95
+ child = spawn(cmd, args, { windowsHide: true, stdio: ['ignore', 'pipe', 'ignore'] });
96
+ }
97
+ catch {
98
+ resolve(null);
99
+ return;
100
+ }
101
+ const timer = setTimeout(() => {
102
+ try {
103
+ child.kill('SIGKILL');
104
+ }
105
+ catch { /* already gone */ }
106
+ finish(null);
107
+ }, VM_PROBE_TIMEOUT_MS);
108
+ timer.unref?.();
109
+ child.stdout?.setEncoding('utf8');
110
+ child.stdout?.on('data', (d) => { out += d; });
111
+ child.on('error', () => finish(null));
112
+ child.on('close', (code) => finish(code === 0 ? out : null));
113
+ });
114
+ }
115
+ function runSync(cmd, args) {
116
+ try {
117
+ return execFileSync(cmd, args, { encoding: 'utf8', timeout: VM_PROBE_TIMEOUT_MS, killSignal: 'SIGKILL', windowsHide: true, stdio: ['ignore', 'pipe', 'ignore'] });
118
+ }
119
+ catch {
120
+ return null;
121
+ }
122
+ }
123
+ let cached = null;
124
+ let settled;
125
+ async function detectNow() {
126
+ try {
127
+ const os = platform();
128
+ if (os === 'win32')
129
+ return parseWindowsComputerSystem(await run('powershell.exe', WINDOWS_PROBE));
130
+ if (os === 'darwin') {
131
+ const out = await run('sysctl', ['-n', 'kern.hv_vmm_present']);
132
+ return out === null ? null : sysctlSaysVirtual(out);
133
+ }
134
+ return linuxProbe();
135
+ }
136
+ catch {
137
+ return null;
138
+ }
139
+ }
140
+ /**
141
+ * Whether this process runs in a virtual machine or a container: detected once per process without blocking (the probe runs
142
+ * 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
143
+ * import time: the probe starts on the first call (the client calls it at the first activate, checkout or trial, or from
144
+ * warmUpVirtualMachineDetection()).
145
+ */
146
+ export function detectVirtualMachine() {
147
+ if (!cached) {
148
+ cached = detectNow();
149
+ void cached.then((v) => { settled = v; });
150
+ }
151
+ return cached;
152
+ }
153
+ /**
154
+ * Synchronous form of detectVirtualMachine() (false when not detected). It never starts a second probe: once detection has
155
+ * finished it returns the cached result; while the asynchronous probe is still running it returns false at once (the answer
156
+ * isn't known yet; await detectVirtualMachine() for it). Only before the first detection has started does it run the probe
157
+ * itself and block the event loop until it ends (up to 5 seconds, once per process); that result is then cached for both forms.
158
+ * @deprecated Use detectVirtualMachine().
159
+ */
160
+ export function isVirtualMachine() {
161
+ if (settled !== undefined)
162
+ return settled === true;
163
+ if (cached)
164
+ return false; // the async probe is running: don't start a second one or block on it
165
+ let value;
166
+ try {
167
+ const os = platform();
168
+ value = os === 'win32'
169
+ ? parseWindowsComputerSystem(runSync('powershell.exe', WINDOWS_PROBE))
170
+ : os === 'darwin'
171
+ ? (() => { const out = runSync('sysctl', ['-n', 'kern.hv_vmm_present']); return out === null ? null : sysctlSaysVirtual(out); })()
172
+ : linuxProbe();
173
+ }
174
+ catch {
175
+ value = null;
176
+ }
177
+ settled = value;
178
+ cached = Promise.resolve(value);
179
+ return value === true;
180
+ }
181
+ /** Whether detection has started in this process (for tests: the probe never starts at import or client construction). */
182
+ export function virtualMachineDetectionStarted() {
183
+ return cached !== null;
184
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@codeo-engineering/licenserail",
3
- "version": "0.1.0",
3
+ "version": "0.1.6",
4
4
  "description": "LicenseRail client SDK: offline license verification, activation, refresh, floating leases and the management API.",
5
5
  "license": "MIT",
6
6
  "publishConfig": { "access": "public" },
@@ -15,7 +15,7 @@
15
15
  "engines": { "node": ">=18" },
16
16
  "scripts": {
17
17
  "build": "tsc -p tsconfig.json",
18
- "test": "npm run build && node --test test/"
18
+ "test": "npm run build && node --test"
19
19
  },
20
20
  "devDependencies": {
21
21
  "@types/node": "^20.11.0",