clearcote 0.53.1 → 0.55.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/license.js CHANGED
@@ -9,14 +9,33 @@
9
9
  // With NO license key this is entirely inert — the free build never calls the
10
10
  // backend and never gates. See clearcoat/PRIVATE-SDK-LICENSING-PLAN.md.
11
11
  import { offlineLease } from "./offline.js";
12
- import { existsSync, readFileSync, mkdirSync, writeFileSync, rmSync, chmodSync } from "node:fs";
12
+ import { existsSync, readFileSync, mkdirSync, writeFileSync, renameSync, rmSync, chmodSync } from "node:fs";
13
13
  import { homedir, tmpdir } from "node:os";
14
14
  import { join } from "node:path";
15
- import { createHash, randomUUID } from "node:crypto";
15
+ import { createHash, randomBytes, randomUUID } from "node:crypto";
16
+ import { setTimeout as sleep } from "node:timers/promises";
16
17
  import { proxiedRequest, toProxySpec } from "./net.js";
17
18
  /** Default backend. Override with `licenseApiBase` or CLEARCOTE_LICENSE_API. */
18
19
  const DEFAULT_API_BASE = "https://www.clearcotelabs.com";
20
+ /** The licence lease server: lease checkout, heartbeat, check-in and seats go there first. */
21
+ const DEFAULT_LEASE_BASE = "https://lease.clearcotelabs.com";
19
22
  const RUN_TOKEN_ENV = "CLEARCOTE_RUN_TOKEN";
23
+ /**
24
+ * Where the lease calls go when no base is set (`licenseApiBase`, CLEARCOTE_LICENSE_API, CLEARCOTE_LEASE_API),
25
+ * and the timings of the fallback and of the rate-limit retries. Tests point the bases at local servers and
26
+ * shorten the timings; nothing else changes them.
27
+ */
28
+ export const leaseDefaults = {
29
+ primary: DEFAULT_LEASE_BASE,
30
+ /** Gets a lease call the primary could not take (see leaseCall()). */
31
+ fallback: DEFAULT_API_BASE,
32
+ /** After the primary failed, lease calls skip it for this long (ms) and go straight to the fallback. */
33
+ breakerMs: 60_000,
34
+ /** Waits (ms) before each retry of a checkout the server answered with RATE_LIMITED. */
35
+ rateLimitRetryMs: [1_000, 2_000, 4_000],
36
+ };
37
+ /** The 429 code for "this address's request budget is spent", which says nothing about the licence. */
38
+ const RATE_LIMITED = "RATE_LIMITED";
20
39
  /**
21
40
  * Names this SDK and its version on every licence call (fetch alone says just "node"), so the licence
22
41
  * server's logs can tell SDK builds apart, and tell clients that are not an SDK from ours. Spelled
@@ -38,6 +57,8 @@ export function licenseThroughProxyRequested(opt, env = process.env) {
38
57
  }
39
58
  export class LicenseError extends Error {
40
59
  code;
60
+ /** HTTP status of the answer this error reports; undefined when the licence server never answered. */
61
+ status;
41
62
  constructor(message, code = "LICENSE_ERROR") {
42
63
  super(message);
43
64
  this.name = "LicenseError";
@@ -56,6 +77,19 @@ export class LicenseRevokedError extends LicenseError {
56
77
  this.name = "LicenseRevokedError";
57
78
  }
58
79
  }
80
+ /**
81
+ * The licence server never answered: something in front of it (a CDN firewall or bot check, e.g. the
82
+ * "Vercel Security Checkpoint") returned a challenge page instead of a licence verdict. Says nothing about
83
+ * the licence itself, which is NOT revoked or over its limit. Retryable: such challenges are usually
84
+ * temporary and tied to this machine's network; `licenseThroughProxy` sends the calls another way.
85
+ */
86
+ export class LicenseServerChallengeError extends LicenseError {
87
+ retryable = true;
88
+ constructor(message) {
89
+ super(message, "LICENSE_SERVER_CHALLENGE");
90
+ this.name = "LicenseServerChallengeError";
91
+ }
92
+ }
59
93
  /** Resolve a license key: explicit > CLEARCOTE_LICENSE_KEY env > ~/.clearcote/license.key. */
60
94
  export function resolveLicenseKey(explicit) {
61
95
  if (explicit && explicit.trim())
@@ -114,17 +148,74 @@ function apiBase(opts) {
114
148
  export function licenseApiBase(explicit) {
115
149
  return apiBase({ licenseApiBase: explicit });
116
150
  }
151
+ /**
152
+ * The lease call bases (checkout, heartbeat, check-in, seats). A base that is set is the only one used:
153
+ * `licenseApiBase` > CLEARCOTE_LICENSE_API > CLEARCOTE_LEASE_API. Otherwise the licence lease server, with
154
+ * clearcotelabs.com as its fallback. Every other licence route (the PRO download, device login) keeps
155
+ * {@link licenseApiBase}.
156
+ */
157
+ function leaseRoute(opts, env = process.env) {
158
+ const set = opts.licenseApiBase || env.CLEARCOTE_LICENSE_API || env.CLEARCOTE_LEASE_API;
159
+ if (set)
160
+ return { primary: set.replace(/\/$/, ""), fallback: null };
161
+ return { primary: leaseDefaults.primary.replace(/\/$/, ""), fallback: leaseDefaults.fallback.replace(/\/$/, "") };
162
+ }
163
+ /** Per process: until when (epoch ms) a route skips its primary, after the primary could not be reached. */
164
+ const primarySkippedUntil = new Map();
165
+ /** Gateway and CDN errors: the request never reached the lease server. */
166
+ function gatewayStatus(status) {
167
+ return status === 502 || status === 503 || status === 504 || (status >= 520 && status <= 527) || status === 530;
168
+ }
169
+ /** Whether the primary's answer is not the lease server's: a gateway error, or a challenge page. */
170
+ async function notTheServer(res) {
171
+ if (gatewayStatus(res.status))
172
+ return true;
173
+ if (res.status < 400)
174
+ return false;
175
+ // Read a copy: a JSON answer is final and goes to the caller unread.
176
+ const copy = typeof res.clone === "function" ? res.clone() : res;
177
+ const text = await copy.text().catch(() => "");
178
+ return challengeReason(res.status, headerOf(res, "content-type"), text, headerOf(res, "x-vercel-mitigated")) !== null;
179
+ }
180
+ /**
181
+ * Send one lease call over `route`. With the default bases, a call the primary cannot take (a network error
182
+ * or timeout, a gateway error, a challenge page) is sent once more to the fallback, and the primary is
183
+ * skipped for the next `leaseDefaults.breakerMs`. Any answer from the lease server itself (a 200 or a JSON
184
+ * error: 401, 403, 409, 426, 429, ...) is final. `via` keeps a proxied route's skip apart from the direct one.
185
+ */
186
+ async function leaseCall(route, via, send) {
187
+ if (!route.fallback)
188
+ return send(route.primary);
189
+ const key = `${route.primary}|${via?.server ?? ""}`;
190
+ if ((primarySkippedUntil.get(key) ?? 0) > Date.now())
191
+ return send(route.fallback);
192
+ try {
193
+ const res = await send(route.primary);
194
+ if (!(await notTheServer(res)))
195
+ return res;
196
+ res.body?.cancel().catch(() => { }); // not read: let its connection go
197
+ }
198
+ catch {
199
+ /* not reached: the fallback below */
200
+ }
201
+ primarySkippedUntil.set(key, Date.now() + leaseDefaults.breakerMs);
202
+ return send(route.fallback);
203
+ }
117
204
  /** The User-Agent every licence call sends ("clearcote-sdk-node/<version>"). */
118
205
  export function licenseUserAgent() {
119
206
  return LICENSE_USER_AGENT;
120
207
  }
121
208
  const osTag = () => ({ win32: "windows", linux: "linux", darwin: "macos" }[process.platform] ?? "unknown");
122
209
  // ── shared token cache (cross-process reuse + offline grace) ───────────────
123
- // {token, exp, lease_id}. A second process on the machine reuses a still-valid
124
- // token instead of checking out again. Older caches without lease_id are honored.
210
+ // {token, exp, lease_id, scope}. A second process on the machine reuses a still-valid
211
+ // token instead of checking out again, but only from a file marked `scope: "machine"`: this
212
+ // SDK writes the mark when a checkout that offered the browser scope got the machine lease.
213
+ // An unmarked file (an older SDK's, which never offered it) says nothing about the licence's
214
+ // scope, so the first launch checks out to learn it; it still serves as offline grace.
215
+ // Older caches without lease_id are honored.
216
+ const keyHash = (licenseKey) => createHash("sha256").update(licenseKey).digest("hex").slice(0, 16);
125
217
  function cachePath(licenseKey) {
126
- const id = createHash("sha256").update(licenseKey).digest("hex").slice(0, 16);
127
- return join(homedir(), ".clearcote", `lease-${id}.json`);
218
+ return join(homedir(), ".clearcote", `lease-${keyHash(licenseKey)}.json`);
128
219
  }
129
220
  function readCache(licenseKey) {
130
221
  try {
@@ -190,15 +281,75 @@ export function engineHwm(env = process.env) {
190
281
  return 0;
191
282
  }
192
283
  }
193
- function writeCache(licenseKey, token, exp, leaseId) {
284
+ /** `machine`: mark the file as a confirmed machine lease (see the cache comment above). */
285
+ function writeCache(licenseKey, token, exp, leaseId, machine = false) {
194
286
  try {
195
287
  const dir = join(homedir(), ".clearcote");
196
288
  mkdirSync(dir, { recursive: true });
197
- writeFileSync(cachePath(licenseKey), JSON.stringify({ token, exp, lease_id: leaseId ?? null }));
289
+ // token / exp / lease_id stay exactly as older SDKs read them; `scope` is an addition they ignore.
290
+ writeFileSync(cachePath(licenseKey), JSON.stringify({ token, exp, lease_id: leaseId ?? null, ...(machine ? { scope: "machine" } : {}) }));
291
+ }
292
+ catch {
293
+ /* ignore */
294
+ }
295
+ }
296
+ // ── grace token (paid per-browser leases) ──────────────────────────────────
297
+ // {token, exp}: the newest paid run-token of a per-browser lease, kept so a paid browser can still start
298
+ // while the licence server cannot be reached (see MachineLease.uncountedLaunch). A file of its own: older
299
+ // SDKs read lease-<hash>.json and would hand a per-browser token to every launch.
300
+ function gracePath(licenseKey) {
301
+ return join(homedir(), ".clearcote", `grace-${keyHash(licenseKey)}.json`);
302
+ }
303
+ function readGrace(licenseKey) {
304
+ try {
305
+ const d = JSON.parse(readFileSync(gracePath(licenseKey), "utf8"));
306
+ if (d && typeof d.token === "string" && typeof d.exp === "number" && tokenPlan(d.token) !== PER_BROWSER_PLAN)
307
+ return d;
198
308
  }
199
309
  catch {
200
310
  /* ignore */
201
311
  }
312
+ return null;
313
+ }
314
+ /** Keep a paid per-browser token as the grace token, unless the one kept was minted later. Best-effort. */
315
+ function writeGrace(licenseKey, token, exp) {
316
+ if (tokenPlan(token) === PER_BROWSER_PLAN)
317
+ return; // a free token is never a fallback
318
+ const final = gracePath(licenseKey);
319
+ let kept = 0;
320
+ try {
321
+ const d = JSON.parse(readFileSync(final, "utf8"));
322
+ if (d && typeof d.token === "string")
323
+ kept = tokenIat(d.token) ?? 0;
324
+ }
325
+ catch {
326
+ /* none kept, or unreadable: replace it */
327
+ }
328
+ if ((tokenIat(token) ?? 0) < kept)
329
+ return;
330
+ // Written to a temporary file and renamed into place, so another process never reads half a file.
331
+ const tmp = `${final}.tmp-${randomBytes(4).toString("hex")}`;
332
+ try {
333
+ mkdirSync(join(homedir(), ".clearcote"), { recursive: true });
334
+ writeFileSync(tmp, JSON.stringify({ token, exp }));
335
+ renameSync(tmp, final);
336
+ }
337
+ catch {
338
+ try {
339
+ rmSync(tmp, { force: true });
340
+ }
341
+ catch { /* ignore */ }
342
+ }
343
+ }
344
+ /** Per process and licence key: browsers started on a cached token, not yet reported by a checkout. */
345
+ const uncountedLaunches = new Map();
346
+ /** Notices the licence server sent, printed once per process. */
347
+ const noticesShown = new Set();
348
+ function showNotice(notice, quiet) {
349
+ if (typeof notice !== "string" || !notice.trim() || quiet || noticesShown.has(notice))
350
+ return;
351
+ noticesShown.add(notice);
352
+ process.stderr.write(`[clearcote] [license] ${notice.trim()}\n`);
202
353
  }
203
354
  /** The plan whose tokens are per browser. Only used to keep such tokens out of the shared cache. */
204
355
  const PER_BROWSER_PLAN = "free";
@@ -212,19 +363,115 @@ async function postJson(url, licenseKey, body, proxy) {
212
363
  headers: { authorization: `Bearer ${licenseKey}`, "content-type": "application/json", "User-Agent": LICENSE_USER_AGENT },
213
364
  body: JSON.stringify(body),
214
365
  };
215
- // Through the launch proxy when licenseThroughProxy is on; otherwise the plain fetch path, which
216
- // is unchanged from before the option existed.
366
+ // Through the launch proxy when licenseThroughProxy is on; otherwise the plain fetch path. Both give
367
+ // up after 30 s, so a server that never answers counts as unreachable (see leaseCall()).
217
368
  if (proxy)
218
369
  return proxiedRequest(url, { ...init, proxy, timeoutMs: 30_000 });
219
- return fetch(url, init);
370
+ return fetch(url, { ...init, signal: AbortSignal.timeout(30_000) });
371
+ }
372
+ function headerOf(res, name) {
373
+ const h = res.headers;
374
+ if (!h)
375
+ return "";
376
+ if (typeof h.get === "function")
377
+ return h.get(name) ?? "";
378
+ return h[name] ?? "";
379
+ }
380
+ /**
381
+ * Why an error answer is a firewall/bot challenge rather than the licence server's verdict, or null.
382
+ * The licence server answers every error with JSON. A Vercel challenge sets `x-vercel-mitigated` and serves
383
+ * an HTML page titled "Vercel Security Checkpoint"; any other non-JSON 403/429 comes from something in
384
+ * front of the server too, so it is not a revoke or a concurrency verdict either.
385
+ */
386
+ export function challengeReason(status, contentType, text, mitigated = "") {
387
+ if (status < 400)
388
+ return null;
389
+ if (mitigated)
390
+ return `x-vercel-mitigated: ${mitigated}`;
391
+ if (text.includes("Vercel Security Checkpoint"))
392
+ return "Vercel Security Checkpoint";
393
+ if ((status === 403 || status === 429) && text.trim()) {
394
+ try {
395
+ JSON.parse(text);
396
+ return null;
397
+ }
398
+ catch {
399
+ return `non-JSON ${contentType.split(";")[0].trim() || "body"}`;
400
+ }
401
+ }
402
+ return null;
403
+ }
404
+ /** Read an error response once: a challenge page's reason, or the licence server's JSON body. */
405
+ async function readError(res) {
406
+ const text = await res.text().catch(() => "");
407
+ const challenge = challengeReason(res.status, headerOf(res, "content-type"), text, headerOf(res, "x-vercel-mitigated"));
408
+ if (challenge)
409
+ return { challenge, body: {} };
410
+ try {
411
+ const body = JSON.parse(text || "{}");
412
+ return { challenge: null, body: body && typeof body === "object" ? body : {} };
413
+ }
414
+ catch {
415
+ return { challenge: null, body: {} };
416
+ }
417
+ }
418
+ function challengeError(status, why) {
419
+ const err = new LicenseServerChallengeError(`The licence server could not be reached: a firewall in front of it answered with a security challenge ` +
420
+ `(HTTP ${status}, ${why}) instead of a licence verdict, so your licence was not checked (it is not revoked). ` +
421
+ `This is usually temporary and tied to this machine's network: retry later, or send the licence calls ` +
422
+ `through your proxy (licenseThroughProxy: true).`);
423
+ err.status = status;
424
+ return err;
220
425
  }
221
426
  function throwForStatus(status, body) {
222
427
  const msg = body?.error || `License request failed (${status}).`;
428
+ let err;
223
429
  if (status === 429 || body?.code === "CONCURRENCY_LIMIT_EXCEEDED")
224
- throw new ConcurrencyLimitError(msg);
225
- if (status === 403 || body?.code === "LICENSE_REVOKED" || body?.code === "LICENSE_EXPIRED")
226
- throw new LicenseRevokedError(msg);
227
- throw new LicenseError(msg, body?.code || `HTTP_${status}`);
430
+ err = new ConcurrencyLimitError(msg);
431
+ else if (status === 403 || body?.code === "LICENSE_REVOKED" || body?.code === "LICENSE_EXPIRED")
432
+ err = new LicenseRevokedError(msg);
433
+ else
434
+ err = new LicenseError(msg, body?.code || `HTTP_${status}`);
435
+ err.status = status;
436
+ throw err;
437
+ }
438
+ /** A checkout still rate-limited after its retries: this address's request budget, not the licence's limit. */
439
+ function rateLimitedError(body) {
440
+ const err = new LicenseError(`${body.error || "Rate limit exceeded."} The licence server is limiting requests from this network ` +
441
+ `(${RATE_LIMITED}); this is not the licence's concurrency limit. Retry in a minute.`, RATE_LIMITED);
442
+ err.status = 429;
443
+ return err;
444
+ }
445
+ /**
446
+ * A checkout failure that is no verdict on the licence: the server was not reached (a network error, a
447
+ * timeout, a challenge page), could not answer (HTTP 5xx), or rate-limited this address. A refusal (401,
448
+ * 403, 409, 426, a concurrency limit) is a verdict.
449
+ */
450
+ function noVerdict(e) {
451
+ if (!(e instanceof LicenseError))
452
+ return true;
453
+ return e instanceof LicenseServerChallengeError || e.code === RATE_LIMITED || (e.status ?? 0) >= 500;
454
+ }
455
+ /** A few words on why a checkout got no verdict, for the one line an uncounted launch prints. */
456
+ function failureReason(e) {
457
+ if (e instanceof LicenseServerChallengeError)
458
+ return `security challenge, HTTP ${e.status ?? "?"}`;
459
+ if (e instanceof LicenseError)
460
+ return e.code === RATE_LIMITED ? "rate limited" : `HTTP ${e.status ?? e.code}`;
461
+ const cause = e?.cause?.code;
462
+ const msg = e instanceof Error ? e.message : String(e);
463
+ return typeof cause === "string" ? `${msg}: ${cause}` : msg;
464
+ }
465
+ /** The handle of a browser started on a cached token: no lease, so nothing to beat or check in. */
466
+ function uncountedSession(token) {
467
+ const files = new TokenFileSet();
468
+ return {
469
+ token,
470
+ leaseId: "uncounted",
471
+ stop: async () => files.closeAll(),
472
+ bindLaunch: () => files.bind(token),
473
+ refreshToken: async () => false,
474
+ };
228
475
  }
229
476
  // Seconds of headroom kept before a token's exp: reuse it only while still valid
230
477
  // with this much slack, so an in-flight launch never ships an expiring token.
@@ -288,7 +535,7 @@ class TokenFileSet {
288
535
  */
289
536
  class MachineLease {
290
537
  key;
291
- base;
538
+ route;
292
539
  instanceId;
293
540
  sdkVersion;
294
541
  quiet;
@@ -305,8 +552,19 @@ class MachineLease {
305
552
  leaseId = null;
306
553
  /** Learned from the first checkout: "browser" means every launch holds its own lease. */
307
554
  scope = "machine";
308
- /** A per-browser checkout made by ensure(), waiting for the one launch that asked for it. */
555
+ /**
556
+ * The machine lease held was confirmed as one: by a checkout that offered the browser scope, or by a
557
+ * cache file marked so. Only then are the cache writes marked (a lease taken from an older SDK's file
558
+ * during an outage, and its re-checkouts without a launch_id, say nothing about the licence's scope).
559
+ */
560
+ machineConfirmed = false;
561
+ /**
562
+ * What ensure() learned for the one launch that asked for it: a per-browser checkout, or a checkout
563
+ * that got no verdict while a paid grace token was at hand (that launch starts on it, uncounted).
564
+ */
309
565
  pendingBrowser = null;
566
+ /** The plan of the last per-browser lease this process got ("free" never falls back to a cached token). */
567
+ browserPlan;
310
568
  browsers = new Set();
311
569
  hbSec = 270;
312
570
  owner = false;
@@ -315,12 +573,12 @@ class MachineLease {
315
573
  ensuring = null;
316
574
  refreshing = null;
317
575
  engineResolved = null;
318
- constructor(key, base, instanceId, sdkVersion, quiet,
576
+ constructor(key, route, instanceId, sdkVersion, quiet,
319
577
  // Resolved browser build (e.g. "150.0.7871.114"). A string, or a thunk that resolves it lazily
320
578
  // so the catalog is only consulted on a cold checkout — never per launch. Telemetry only.
321
579
  engineVersion, proxy = null) {
322
580
  this.key = key;
323
- this.base = base;
581
+ this.route = route;
324
582
  this.instanceId = instanceId;
325
583
  this.sdkVersion = sdkVersion;
326
584
  this.quiet = quiet;
@@ -357,12 +615,14 @@ class MachineLease {
357
615
  return;
358
616
  const now = Math.floor(Date.now() / 1000);
359
617
  const cached = readCache(this.key);
360
- if (cached && cached.exp > now + SKEW_SEC) {
361
- // cross-process reuse: another process's owner keeps the slot alive.
618
+ if (cached && cached.scope === "machine" && cached.exp > now + SKEW_SEC) {
619
+ // cross-process reuse: another process's owner keeps the slot alive. Only from a file this SDK
620
+ // marked as a machine lease: an older SDK's file is checked out past, to learn the licence's scope.
362
621
  this.token = cached.token;
363
622
  this.exp = cached.exp;
364
623
  this.leaseId = cached.lease_id ?? null;
365
624
  this.owner = false;
625
+ this.machineConfirmed = true;
366
626
  return; // NO checkout, NO heartbeat
367
627
  }
368
628
  await this.checkout();
@@ -371,25 +631,51 @@ class MachineLease {
371
631
  this.owner = true;
372
632
  this.startHeartbeat();
373
633
  }
374
- /** POST a checkout for one launch. Throws the backend's verdict; network errors propagate. */
634
+ /**
635
+ * POST a checkout: for one launch (`launchId`), or without one for the machine heartbeat's re-checkout.
636
+ * A RATE_LIMITED answer is retried after `leaseDefaults.rateLimitRetryMs`. Throws the backend's verdict;
637
+ * network errors propagate.
638
+ */
375
639
  async checkoutFor(launchId) {
376
- const res = await postJson(`${this.base}/api/v1/lease/checkout`, this.key, {
640
+ const body = {
377
641
  instance_id: this.instanceId,
378
642
  // Per-browser plans count each launch_id as its own slot; machine plans ignore it.
379
- launch_id: launchId,
643
+ ...(launchId ? { launch_id: launchId } : {}),
380
644
  os: osTag(),
381
645
  sdk_version: this.sdkVersion,
382
646
  engine_version: await this.engineVer(),
383
- }, this.proxy);
384
- if (!res.ok) {
385
- const body = (await res.json().catch(() => ({})));
386
- throwForStatus(res.status, body);
647
+ // This SDK runs every browser on its own lease when the backend says so (lease_scope "browser").
648
+ lease_scope_supported: ["browser"],
649
+ };
650
+ const waits = leaseDefaults.rateLimitRetryMs;
651
+ for (let attempt = 0;; attempt++) {
652
+ // Browsers started on a cached token while the server was unreachable, reported by the next checkout.
653
+ const uncounted = uncountedLaunches.get(this.key) ?? 0;
654
+ const res = await this.post("/api/v1/lease/checkout", uncounted ? { ...body, uncounted_launches: uncounted } : body);
655
+ if (res.ok) {
656
+ const co = (await res.json());
657
+ if (uncounted)
658
+ uncountedLaunches.set(this.key, Math.max(0, (uncountedLaunches.get(this.key) ?? 0) - uncounted));
659
+ showNotice(co.notice, this.quiet);
660
+ return co;
661
+ }
662
+ const { challenge, body: err } = await readError(res);
663
+ if (challenge)
664
+ throw challengeError(res.status, challenge);
665
+ if (res.status === 429 && err.code === RATE_LIMITED) {
666
+ // This address's request budget is spent: wait and ask again. Never a concurrency verdict.
667
+ if (attempt < waits.length) {
668
+ await sleep(waits[attempt]);
669
+ continue;
670
+ }
671
+ throw rateLimitedError(err);
672
+ }
673
+ throwForStatus(res.status, err);
387
674
  }
388
- return (await res.json());
389
675
  }
390
- /** Heartbeat / re-checkout / check-in for a BrowserLease, over this lease's route (direct or proxy). */
676
+ /** One lease call (checkout / heartbeat / check-in) over this lease's route (direct or proxy). */
391
677
  post(path, body) {
392
- return postJson(`${this.base}${path}`, this.key, body, this.proxy);
678
+ return leaseCall(this.route, this.proxy, (base) => postJson(`${base}${path}`, this.key, body, this.proxy));
393
679
  }
394
680
  async checkout() {
395
681
  try {
@@ -405,10 +691,22 @@ class MachineLease {
405
691
  this.exp = co.exp;
406
692
  this.leaseId = co.lease_id;
407
693
  this.hbSec = Math.max(5, co.heartbeat_interval_sec || 270);
408
- writeCache(this.key, co.token, co.exp, co.lease_id);
694
+ // Offered the browser scope (with a launch_id) and got the machine lease: a confirmed machine lease.
695
+ this.machineConfirmed = true;
696
+ writeCache(this.key, co.token, co.exp, co.lease_id, true);
409
697
  }
410
698
  catch (e) {
411
- if (e instanceof LicenseError)
699
+ // A paid grace token means this licence runs every browser on its own lease: without a verdict, the
700
+ // launch starts on it like any per-browser launch would (see uncountedLaunch()).
701
+ if (noVerdict(e) && this.usableGrace()) {
702
+ this.scope = "browser";
703
+ this.pendingBrowser = { error: e };
704
+ return;
705
+ }
706
+ // A challenge or a rate limit is not a verdict (the server was never reached, or did not decide):
707
+ // offline grace like a network error, and the error itself surfaces when there is no cached token.
708
+ const passing = e instanceof LicenseServerChallengeError || (e instanceof LicenseError && e.code === RATE_LIMITED);
709
+ if (e instanceof LicenseError && !passing)
412
710
  throw e; // definitive verdict must surface
413
711
  const cached = readCache(this.key);
414
712
  const now = Math.floor(Date.now() / 1000);
@@ -418,41 +716,68 @@ class MachineLease {
418
716
  this.token = cached.token;
419
717
  this.exp = cached.exp;
420
718
  this.leaseId = cached.lease_id ?? null;
719
+ this.machineConfirmed = cached.scope === "machine"; // an older SDK's file is offline grace only
421
720
  return;
422
721
  }
722
+ if (passing)
723
+ throw e;
423
724
  throw new LicenseError(`Could not reach the license server and no valid cached token: ${String(e)}`);
424
725
  }
425
726
  }
727
+ /** The grace token, while still valid with SKEW_SEC to spare. */
728
+ usableGrace() {
729
+ const grace = readGrace(this.key);
730
+ return grace && grace.exp > Math.floor(Date.now() / 1000) + SKEW_SEC ? grace : null;
731
+ }
732
+ /**
733
+ * A paid browser starts without a lease when its checkout got no verdict (see noVerdict()): on the grace
734
+ * token, else on a still-valid machine cache token. It is not counted, nothing beats or checks it in, and
735
+ * the next checkout reports it (`uncounted_launches`). Null on a free licence or with no usable token.
736
+ */
737
+ uncountedLaunch(e) {
738
+ if (this.browserPlan === PER_BROWSER_PLAN)
739
+ return null; // free stays fail-closed
740
+ const now = Math.floor(Date.now() / 1000);
741
+ const cached = readCache(this.key);
742
+ const token = this.usableGrace()?.token ?? (cached && cached.exp > now + SKEW_SEC ? cached.token : null);
743
+ if (!token)
744
+ return null;
745
+ if (!this.quiet)
746
+ process.stderr.write(`[clearcote] [license] licence server unreachable (${failureReason(e)}); this browser starts on a cached run-token and is not counted.\n`);
747
+ uncountedLaunches.set(this.key, (uncountedLaunches.get(this.key) ?? 0) + 1);
748
+ return uncountedSession(token);
749
+ }
750
+ /** The error a per-browser launch raises when its checkout failed and it cannot start uncounted. */
751
+ browserFailure(e) {
752
+ if (e instanceof LicenseError)
753
+ return e;
754
+ // No offline grace here: without the backend there is no slot for this browser.
755
+ return new LicenseError(`Could not reach the license server to start this browser: ${String(e)}`);
756
+ }
426
757
  startHeartbeat() {
427
758
  if (this.timer)
428
759
  return;
429
760
  this.timer = setInterval(async () => {
430
761
  try {
431
- const res = await postJson(`${this.base}/api/v1/lease/heartbeat`, this.key, {
762
+ const res = await this.post("/api/v1/lease/heartbeat", {
432
763
  lease_id: this.leaseId,
433
764
  nonce: randomUUID(),
434
- }, this.proxy);
765
+ });
435
766
  if (res.status === 409) {
436
- const co = await postJson(`${this.base}/api/v1/lease/checkout`, this.key, {
437
- instance_id: this.instanceId,
438
- os: osTag(),
439
- sdk_version: this.sdkVersion,
440
- engine_version: await this.engineVer(),
441
- }, this.proxy);
442
- if (co.ok) {
443
- const d = (await co.json());
444
- this.leaseId = d.lease_id;
445
- this.token = d.token;
446
- this.exp = d.exp;
447
- writeCache(this.key, d.token, d.exp, d.lease_id);
448
- }
767
+ // Re-checkout without a launch_id: the backend keeps a machine lease a machine lease. A refusal
768
+ // or a network error changes nothing; the next beat tries again.
769
+ const d = await this.checkoutFor();
770
+ this.leaseId = d.lease_id;
771
+ this.token = d.token;
772
+ this.exp = d.exp;
773
+ writeCache(this.key, d.token, d.exp, d.lease_id, this.machineConfirmed);
449
774
  return;
450
775
  }
451
776
  if (res.ok) {
452
777
  const d = (await res.json());
453
778
  this.token = d.token;
454
779
  this.exp = d.exp;
455
- writeCache(this.key, d.token, d.exp, this.leaseId ?? undefined);
780
+ writeCache(this.key, d.token, d.exp, this.leaseId ?? undefined, this.machineConfirmed);
456
781
  }
457
782
  }
458
783
  catch {
@@ -492,17 +817,17 @@ class MachineLease {
492
817
  async freshToken() {
493
818
  if (this.leaseId) {
494
819
  try {
495
- const res = await postJson(`${this.base}/api/v1/lease/heartbeat`, this.key, {
820
+ const res = await this.post("/api/v1/lease/heartbeat", {
496
821
  lease_id: this.leaseId,
497
822
  nonce: randomUUID(),
498
- }, this.proxy);
823
+ });
499
824
  if (res.ok) {
500
825
  const d = (await res.json());
501
826
  if (typeof d.token === "string") {
502
827
  this.token = d.token;
503
828
  if (typeof d.exp === "number")
504
829
  this.exp = d.exp;
505
- writeCache(this.key, d.token, this.exp, this.leaseId);
830
+ writeCache(this.key, d.token, this.exp, this.leaseId, this.machineConfirmed);
506
831
  return true;
507
832
  }
508
833
  }
@@ -530,7 +855,15 @@ class MachineLease {
530
855
  // made; every other launch (including ones that were waiting on the same ensure) checks out its own.
531
856
  const pending = this.pendingBrowser;
532
857
  this.pendingBrowser = null;
533
- return pending ? this.startBrowser(pending.co, pending.launchId) : this.acquireBrowser();
858
+ if (!pending)
859
+ return this.acquireBrowser();
860
+ if ("error" in pending) {
861
+ const uncounted = this.uncountedLaunch(pending.error);
862
+ if (uncounted)
863
+ return uncounted;
864
+ throw this.browserFailure(pending.error);
865
+ }
866
+ return this.startBrowser(pending.co, pending.launchId);
534
867
  }
535
868
  await this.refreshIfBehindEngine();
536
869
  this.refs++;
@@ -559,7 +892,10 @@ class MachineLease {
559
892
  if (this.refs > 0)
560
893
  this.refs--;
561
894
  }
562
- /** A new launch on a per-browser plan: its own checkout. A refusal (one browser already running) throws. */
895
+ /**
896
+ * A new launch on a per-browser plan: its own checkout. A refusal (one browser already running) throws.
897
+ * A paid licence's checkout that gets no verdict starts the browser uncounted when it can.
898
+ */
563
899
  async acquireBrowser() {
564
900
  const launchId = newLaunchId();
565
901
  let co;
@@ -567,18 +903,24 @@ class MachineLease {
567
903
  co = await this.checkoutFor(launchId);
568
904
  }
569
905
  catch (e) {
570
- if (e instanceof LicenseError)
571
- throw e;
572
- // No offline grace here: without the backend there is no slot for this browser.
573
- throw new LicenseError(`Could not reach the license server to start this browser: ${String(e)}`);
906
+ const uncounted = noVerdict(e) ? this.uncountedLaunch(e) : null;
907
+ if (uncounted)
908
+ return uncounted;
909
+ throw this.browserFailure(e);
574
910
  }
575
911
  return this.startBrowser(co, launchId);
576
912
  }
577
913
  startBrowser(co, launchId) {
914
+ this.browserPlan = tokenPlan(co.token);
578
915
  const lease = new BrowserLease(this, co, launchId, () => this.browsers.delete(lease));
579
916
  this.browsers.add(lease);
580
917
  return lease.session();
581
918
  }
919
+ /** Keep a per-browser lease's newest paid token as the grace token (free tokens are skipped). */
920
+ keepGrace(token, exp) {
921
+ if (typeof exp === "number")
922
+ writeGrace(this.key, token, exp);
923
+ }
582
924
  async shutdown() {
583
925
  this.tokenFiles.closeAll();
584
926
  // Per-browser leases still open at exit (a browser nobody closed): release their slots too.
@@ -589,7 +931,7 @@ class MachineLease {
589
931
  }
590
932
  if (this.owner && this.leaseId) {
591
933
  try {
592
- await postJson(`${this.base}/api/v1/lease/checkin`, this.key, { lease_id: this.leaseId }, this.proxy);
934
+ await this.post("/api/v1/lease/checkin", { lease_id: this.leaseId });
593
935
  }
594
936
  catch {
595
937
  /* best-effort; the lease TTL reclaims it anyway */
@@ -598,10 +940,11 @@ class MachineLease {
598
940
  }
599
941
  }
600
942
  /**
601
- * One browser's own lease on a per-browser plan (the free tier: "1 browser at a time").
943
+ * One browser's own lease on a per-browser plan (the free tier: "1 browser at a time"; uncapped paid plans).
602
944
  *
603
945
  * Checked out for exactly one launch, heartbeated while that browser runs, checked in when it closes.
604
- * Its token is never written to the shared cache and never handed to another launch.
946
+ * Its token is never written to the shared cache and never handed to another launch. A paid token is kept
947
+ * as the grace token (see writeGrace()).
605
948
  */
606
949
  class BrowserLease {
607
950
  owner;
@@ -620,7 +963,7 @@ class BrowserLease {
620
963
  this.owner = owner;
621
964
  this.launchId = launchId;
622
965
  this.onStop = onStop;
623
- this.token = co.token;
966
+ this.take(co.token, co.exp);
624
967
  this.leaseId = co.lease_id;
625
968
  const hbMs = Math.max(5, co.heartbeat_interval_sec || 120) * 1000;
626
969
  this.timer = setInterval(() => void this.beat(), hbMs);
@@ -636,13 +979,13 @@ class BrowserLease {
636
979
  // as this browser's own lease. If another browser took the slot meanwhile, this is refused.
637
980
  const co = await this.owner.checkoutFor(this.launchId);
638
981
  this.leaseId = co.lease_id;
639
- this.token = co.token;
982
+ this.take(co.token, co.exp);
640
983
  return;
641
984
  }
642
985
  if (res.ok) {
643
986
  const d = (await res.json());
644
987
  if (typeof d.token === "string")
645
- this.token = d.token;
988
+ this.take(d.token, d.exp);
646
989
  }
647
990
  }
648
991
  catch {
@@ -658,7 +1001,7 @@ class BrowserLease {
658
1001
  if (res.ok) {
659
1002
  const d = (await res.json());
660
1003
  if (typeof d.token === "string") {
661
- this.token = d.token;
1004
+ this.take(d.token, d.exp);
662
1005
  return true;
663
1006
  }
664
1007
  return false;
@@ -667,9 +1010,14 @@ class BrowserLease {
667
1010
  return false;
668
1011
  const co = await this.owner.checkoutFor(this.launchId); // a refusal (another browser holds it) throws
669
1012
  this.leaseId = co.lease_id;
670
- this.token = co.token;
1013
+ this.take(co.token, co.exp);
671
1014
  return true;
672
1015
  }
1016
+ /** A new token for this browser (checkout or heartbeat). */
1017
+ take(token, exp) {
1018
+ this.token = token;
1019
+ this.owner.keepGrace(token, exp);
1020
+ }
673
1021
  async stop() {
674
1022
  if (this.stopped)
675
1023
  return;
@@ -707,13 +1055,15 @@ let exitHooked = false;
707
1055
  /**
708
1056
  * Acquire a concurrency lease for one launch. Returns `null` in free mode (no key).
709
1057
  *
710
- * Machine plans (every paid plan): a per-MACHINE lease shared across every launch in this process
1058
+ * Machine plans (capped paid plans): a per-MACHINE lease shared across every launch in this process
711
1059
  * (checks out ~once per token-TTL, not once per launch); `stop()` only drops a reference.
712
- * Per-browser plans (the GitHub free tier, told by the backend's `lease_scope: "browser"`): every
713
- * launch checks out its own slot, and `stop()` releases it, so a second browser is refused while one runs.
1060
+ * Per-browser plans (the GitHub free tier and uncapped paid plans, told by the backend's
1061
+ * `lease_scope: "browser"`): every launch checks out its own slot, and `stop()` releases it, so a second
1062
+ * browser is refused while one runs on a plan that allows one.
714
1063
  * Throws {@link ConcurrencyLimitError} / {@link LicenseRevokedError} /
715
1064
  * {@link LicenseError} only on a cold checkout the backend definitively refuses;
716
- * falls back to a cached, still-valid token on a transient network failure.
1065
+ * falls back to a cached, still-valid token on a transient network failure (a paid per-browser launch
1066
+ * then starts uncounted; a free one never falls back).
717
1067
  */
718
1068
  export async function acquireLease(opts = {}) {
719
1069
  // Offline mode: the key file's token is the run token; nothing is checked out (./offline.ts).
@@ -723,7 +1073,7 @@ export async function acquireLease(opts = {}) {
723
1073
  const licenseKey = resolveLicenseKey(opts.licenseKey);
724
1074
  if (!licenseKey)
725
1075
  return null; // free mode — inert
726
- const base = apiBase(opts);
1076
+ const route = leaseRoute(opts);
727
1077
  const viaProxy = licenseThroughProxyRequested(opts.licenseThroughProxy) ? toProxySpec(opts.proxy ?? null) : null;
728
1078
  if (licenseThroughProxyRequested(opts.licenseThroughProxy) && !viaProxy && !opts.quiet) {
729
1079
  process.stderr.write("[clearcote] [license] licenseThroughProxy is on but this launch has no proxy; licence calls go direct.\n");
@@ -734,7 +1084,7 @@ export async function acquireLease(opts = {}) {
734
1084
  const mapKey = viaProxy ? `${licenseKey}|${viaProxy.server}|${viaProxy.username ?? ""}` : licenseKey;
735
1085
  let ml = machineLeases.get(mapKey);
736
1086
  if (!ml) {
737
- ml = new MachineLease(licenseKey, base, resolveInstanceId(), opts.sdkVersion, !!opts.quiet, opts.engineVersion, viaProxy);
1087
+ ml = new MachineLease(licenseKey, route, resolveInstanceId(), opts.sdkVersion, !!opts.quiet, opts.engineVersion, viaProxy);
738
1088
  machineLeases.set(mapKey, ml);
739
1089
  }
740
1090
  if (!exitHooked) {
@@ -771,13 +1121,25 @@ export async function getSessionSeats(opts = {}) {
771
1121
  return { state: "no-key" };
772
1122
  const via = licenseThroughProxyRequested(opts.licenseThroughProxy) ? toProxySpec(opts.proxy ?? null) : null;
773
1123
  try {
774
- const res = await proxiedRequest(`${apiBase(opts)}/api/v1/lease/seats`, {
1124
+ const res = await leaseCall(leaseRoute(opts), via, (base) => proxiedRequest(`${base}/api/v1/lease/seats`, {
775
1125
  method: "GET",
776
1126
  headers: { authorization: `Bearer ${key}`, "User-Agent": LICENSE_USER_AGENT },
777
1127
  proxy: via,
778
1128
  timeoutMs: 15_000,
779
- });
780
- const body = (await res.json().catch(() => ({})));
1129
+ }));
1130
+ const text = await res.text().catch(() => "");
1131
+ const why = challengeReason(res.status, headerOf(res, "content-type"), text, headerOf(res, "x-vercel-mitigated"));
1132
+ if (why)
1133
+ return { state: "unavailable", reason: `licence server behind a security challenge (${why})` };
1134
+ let body = {};
1135
+ try {
1136
+ const parsed = JSON.parse(text || "{}");
1137
+ if (parsed && typeof parsed === "object")
1138
+ body = parsed;
1139
+ }
1140
+ catch {
1141
+ /* non-JSON: reported by status below */
1142
+ }
781
1143
  if (res.ok && typeof body.used === "number") {
782
1144
  return { state: "ok", used: body.used, limit: body.limit ?? null, plan: body.plan };
783
1145
  }