@agenticcli/shipguard 0.7.1 → 0.8.1

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.
@@ -2,14 +2,13 @@ import {
2
2
  EXEC_RULE_FIELDS,
3
3
  RE2JS_V1_RUNTIME_ID,
4
4
  canonicalJson,
5
- compileCached,
6
5
  computeExecutableHash,
7
6
  parseFlags,
8
7
  parseStrictNoDup,
9
8
  re2jsV1Executor,
10
9
  selectExpected,
11
10
  verifyExactSet
12
- } from "./chunk-MPQ42F54.js";
11
+ } from "./chunk-KGIK7XNK.js";
13
12
 
14
13
  // src/core/pro-scanner.ts
15
14
  import * as path2 from "path";
@@ -57,6 +56,12 @@ function assertTrustedApiUrl(url) {
57
56
  );
58
57
  }
59
58
 
59
+ // src/core/links.ts
60
+ var GO_BASE = "https://agenticcli.dev/go/";
61
+ function goLink(slot) {
62
+ return `${GO_BASE}${slot}`;
63
+ }
64
+
60
65
  // src/utils/secure-fs.ts
61
66
  import { chmodSync, mkdirSync, statSync, writeFileSync } from "fs";
62
67
  var SECURE_DIR_MODE = 448;
@@ -71,6 +76,29 @@ function writeSecureFileSync(file, data) {
71
76
  if (isPosix) chmodSync(file, SECURE_FILE_MODE);
72
77
  }
73
78
 
79
+ // src/core/platform-status.ts
80
+ var PLATFORM_UNAVAILABLE_CODE = "PLATFORM_UNAVAILABLE";
81
+ var PlatformUnavailableError = class extends Error {
82
+ code = PLATFORM_UNAVAILABLE_CODE;
83
+ retryAfterSeconds;
84
+ constructor(message, retryAfterSeconds) {
85
+ super(message);
86
+ this.name = "PlatformUnavailableError";
87
+ this.retryAfterSeconds = retryAfterSeconds;
88
+ }
89
+ };
90
+ function parseRetryAfterSeconds(headers) {
91
+ const raw = typeof headers?.get === "function" ? headers.get("Retry-After") : null;
92
+ if (raw === null || raw.trim() === "") return void 0;
93
+ const seconds = Number(raw.trim());
94
+ return Number.isFinite(seconds) && seconds >= 0 ? Math.floor(seconds) : void 0;
95
+ }
96
+ function isPlatformUnavailable(res, body) {
97
+ const header = typeof res.headers?.get === "function" ? res.headers.get("X-Platform-Status") : null;
98
+ return body?.code === PLATFORM_UNAVAILABLE_CODE || res.status === 503 && header === "unavailable";
99
+ }
100
+ var PLATFORM_UNAVAILABLE_DEFAULT_MESSAGE = "Service temporarily unavailable. Please try again later.";
101
+
74
102
  // src/core/auth.ts
75
103
  var FILE_MODE = 384;
76
104
  var UNSAFE_PERM_MASK = 63;
@@ -138,22 +166,29 @@ async function exchangeApiKeyForToken(apiKey, apiUrl) {
138
166
  if (res.status === 401) {
139
167
  console.error("[shipguard] SHIPGUARD_API_KEY exchange rejected \u2014 invalid or revoked key");
140
168
  throw new Error(
141
- "SHIPGUARD_API_KEY is invalid or has been revoked. Check the key value or generate a new one at https://agenticcli.dev/dashboard."
169
+ `SHIPGUARD_API_KEY is invalid or has been revoked. Check the key value or generate a new one at ${goLink("dashboard")}.`
142
170
  );
143
171
  }
144
172
  if (res.status === 402) {
145
173
  console.error("[shipguard] SHIPGUARD_API_KEY exchange rejected \u2014 monthly budget exhausted");
146
174
  throw new Error(
147
- "SHIPGUARD_API_KEY has exhausted its monthly credit budget. Buy more at https://agenticcli.dev/dashboard/billing"
175
+ `SHIPGUARD_API_KEY has exhausted its monthly credit budget. Buy more at ${goLink("billing")}`
148
176
  );
149
177
  }
150
178
  if (!res.ok) {
151
179
  let detail = res.statusText;
180
+ let body2 = null;
152
181
  try {
153
- const body2 = await res.json();
182
+ body2 = await res.json();
154
183
  detail = body2?.error_description ?? body2?.error ?? detail;
155
184
  } catch {
156
185
  }
186
+ if (isPlatformUnavailable(res, body2)) {
187
+ throw new PlatformUnavailableError(
188
+ typeof body2?.error === "string" ? body2.error : PLATFORM_UNAVAILABLE_DEFAULT_MESSAGE,
189
+ parseRetryAfterSeconds(res.headers)
190
+ );
191
+ }
157
192
  console.error(`[shipguard] SHIPGUARD_API_KEY exchange failed (${res.status}): ${detail}`);
158
193
  throw new Error(`SHIPGUARD_API_KEY exchange failed (${res.status}): ${detail}`);
159
194
  }
@@ -172,6 +207,62 @@ async function exchangeApiKeyForToken(apiKey, apiUrl) {
172
207
  };
173
208
  return body.access_token;
174
209
  }
210
+ var RefreshUnavailableError = class extends Error {
211
+ constructor(message, retryAfterSeconds) {
212
+ super(message);
213
+ this.retryAfterSeconds = retryAfterSeconds;
214
+ this.name = "RefreshUnavailableError";
215
+ }
216
+ retryAfterSeconds;
217
+ };
218
+ var REFRESH_MAX_TRIES = 3;
219
+ var REFRESH_MAX_WAIT_SECONDS = 10;
220
+ var sleepMs = (ms) => new Promise((r) => setTimeout(r, ms));
221
+ async function readBodyQuietly(res) {
222
+ try {
223
+ const probe = typeof res.clone === "function" ? res.clone() : res;
224
+ return await probe.json();
225
+ } catch {
226
+ return null;
227
+ }
228
+ }
229
+ async function fetchRefreshWithRetry(apiUrl, refreshToken) {
230
+ let lastWait = 1;
231
+ for (let attempt = 1; ; attempt++) {
232
+ const backoff = 2 ** (attempt - 1);
233
+ let res;
234
+ let detail;
235
+ let wait = backoff;
236
+ let sleepSeconds = Math.random() * backoff;
237
+ try {
238
+ res = await fetch(`${apiUrl}/api/auth/device/refresh`, {
239
+ method: "POST",
240
+ headers: { "Content-Type": "application/json" },
241
+ body: JSON.stringify({ refresh_token: refreshToken })
242
+ });
243
+ const transient = res.status === 429 || res.status === 408 || res.status === 425 || res.status >= 500;
244
+ if (res.ok || !transient) return res;
245
+ if (res.status >= 500 && isPlatformUnavailable(res, await readBodyQuietly(res))) return res;
246
+ const retryAfter = parseRetryAfterSeconds(res.headers);
247
+ if (retryAfter !== void 0) {
248
+ wait = Math.max(retryAfter, backoff);
249
+ sleepSeconds = wait;
250
+ }
251
+ detail = `HTTP ${res.status}`;
252
+ } catch (err) {
253
+ detail = err instanceof Error ? err.message : String(err);
254
+ }
255
+ lastWait = wait;
256
+ if (attempt >= REFRESH_MAX_TRIES || wait > REFRESH_MAX_WAIT_SECONDS) {
257
+ throw new RefreshUnavailableError(
258
+ `Token refresh is rate limited or temporarily unavailable (${detail}); your login is kept, try again in ${lastWait} s.`,
259
+ lastWait
260
+ );
261
+ }
262
+ console.error(`[shipguard] Token refresh got ${detail}; retrying in ${wait} s (attempt ${attempt}/${REFRESH_MAX_TRIES}).`);
263
+ await sleepMs(sleepSeconds * 1e3);
264
+ }
265
+ }
175
266
  async function getAuthToken(apiUrl) {
176
267
  const apiKey = process.env.SHIPGUARD_API_KEY;
177
268
  if (apiKey) {
@@ -187,11 +278,7 @@ async function getAuthToken(apiUrl) {
187
278
  if (creds.refreshToken && creds.apiUrl) {
188
279
  try {
189
280
  assertTrustedApiUrl(creds.apiUrl);
190
- const res = await fetch(`${creds.apiUrl}/api/auth/device/refresh`, {
191
- method: "POST",
192
- headers: { "Content-Type": "application/json" },
193
- body: JSON.stringify({ refresh_token: creds.refreshToken })
194
- });
281
+ const res = await fetchRefreshWithRetry(creds.apiUrl, creds.refreshToken);
195
282
  if (res.ok) {
196
283
  const { access_token, refresh_token, expires_in } = await res.json();
197
284
  await saveCredentials({
@@ -202,10 +289,19 @@ async function getAuthToken(apiUrl) {
202
289
  });
203
290
  return access_token;
204
291
  }
292
+ const refusedBody = await readBodyQuietly(res);
293
+ if (isPlatformUnavailable(res, refusedBody)) {
294
+ throw new PlatformUnavailableError(
295
+ typeof refusedBody?.error === "string" ? refusedBody.error : PLATFORM_UNAVAILABLE_DEFAULT_MESSAGE,
296
+ parseRetryAfterSeconds(res.headers)
297
+ );
298
+ }
205
299
  console.error(
206
300
  `[shipguard] Token refresh refused by ${creds.apiUrl} (HTTP ${res.status} ${res.statusText}) \u2014 you will be asked to log in again.`
207
301
  );
208
302
  } catch (err) {
303
+ if (err instanceof PlatformUnavailableError) throw err;
304
+ if (err instanceof RefreshUnavailableError) throw err;
209
305
  const detail = err instanceof Error ? err.message : String(err);
210
306
  console.error(
211
307
  `[shipguard] Token refresh failed \u2014 you will be asked to log in again. Reason: ${detail}`
@@ -221,62 +317,91 @@ import * as path from "path";
221
317
  import { sha256 } from "@noble/hashes/sha2.js";
222
318
 
223
319
  // src/core/crypto.ts
224
- var MIN_ACCEPTABLE_EPOCH = 1;
320
+ import { createHash } from "crypto";
321
+
322
+ // src/core/keyring-ceremony-output.ts
323
+ var CEREMONY_OUTPUT = {
324
+ ra: {
325
+ kid: "ra-k2-2026",
326
+ fingerprint: "a3c0751a14d6933c2e0dbfca69f50a0189ed749153d62b1b76727fc714bf043c",
327
+ publicKey: "-----BEGIN PUBLIC KEY-----\nMCowBQYDK2VwAyEAI5sKq3SF+toDqPO3Brz1FkWOl7INL/O9K3BBtPS3zTo=\n-----END PUBLIC KEY-----"
328
+ },
329
+ cf: {
330
+ kid: "cf-k2-2026",
331
+ fingerprint: "3535a1f5bdd798af75e893aaa93346df6b7e421632ca8bc0105ff866a89c0cee",
332
+ publicKey: "-----BEGIN PUBLIC KEY-----\nMCowBQYDK2VwAyEAjyVy38g4NcfXqD3WmZP7ygit8m4aoywK0KsA0jYiEv4=\n-----END PUBLIC KEY-----"
333
+ },
334
+ bundle: {
335
+ kid: "k3-2026",
336
+ fingerprint: "3cbd12f5c1ef05c33527899f0d074585cb26bacdfe6f13a63cbea243d5c8e57e",
337
+ publicKey: "-----BEGIN PUBLIC KEY-----\nMCowBQYDK2VwAyEA4seZCqwlRq+QzOsIA6+RJUHXHWe4lb1ok6hwL0Bvqzs=\n-----END PUBLIC KEY-----"
338
+ }
339
+ };
340
+
341
+ // src/core/crypto.ts
342
+ var PINNED_KEYS = {};
343
+ var DEFAULT_KID = CEREMONY_OUTPUT.bundle.kid;
344
+ var MIN_ACCEPTABLE_EPOCH = 2;
345
+ var REVOKED_FINGERPRINTS = /* @__PURE__ */ new Set([
346
+ "855e81b870c16d377efd8354e9761fadca2d22d16536f291fb77e690f9d65abc",
347
+ // keys no longer trusted
348
+ "003837c9c656f66163a29e7b0d043a084fc83c2febc420a5e27889205a27b878",
349
+ // keys no longer trusted
350
+ "87787b86689151fd9a9b763e3baa2cae884bf897d51dc02a211c70640e2c4f9d",
351
+ // keys no longer trusted
352
+ "57873aac03421fa0740fdd9520729536223010067ea3012135db2b255a2b263c"
353
+ // keys no longer trusted
354
+ ]);
355
+ var KEYRING_PLACEHOLDER_MARKER = "SHIPGUARD_KEYRING_PLACEHOLDER";
356
+ function isKeyringPlaceholder(entry) {
357
+ return entry.publicKey.includes(KEYRING_PLACEHOLDER_MARKER) || entry.fingerprint.includes(KEYRING_PLACEHOLDER_MARKER);
358
+ }
359
+ function spkiDerFromPem(pem) {
360
+ const m = /^-----BEGIN PUBLIC KEY-----\s*([A-Za-z0-9+/=\s]+?)\s*-----END PUBLIC KEY-----\s*$/.exec(pem.trim());
361
+ if (!m) throw new Error("not a PEM-encoded SPKI public key");
362
+ const der = Buffer.from(m[1].replace(/\s/g, ""), "base64");
363
+ if (der.length === 0) throw new Error("empty SPKI public key");
364
+ return der;
365
+ }
225
366
  var KEYRING = [
226
- // ----- RELEASE-ATTESTATION (REAL production keypair ra-k1-2026, generated 2026-07-20) -----
227
- // Signs corpus manifest + release attestation objects. CI only.
228
- // Private half lives ONLY in ~/.secrets/prod-deploy.env (mode 600) — never shipped, never repo.
367
+ // ----- RELEASE-ATTESTATION (ra-k2-2026, epoch 2) -----
368
+ // Signs corpus manifest + release attestation objects. The private half is never shipped and never stored in this repository.
229
369
  {
230
- kid: "ra-k1-2026",
370
+ kid: CEREMONY_OUTPUT.ra.kid,
231
371
  role: "release-attestation",
232
- epoch: 1,
233
- expiry: 1798761600,
234
- // 2027-01-01 00:00:00 UTC — real production expiry, unchanged from provisioning
235
- fingerprint: "003837c9c656f66163a29e7b0d043a084fc83c2febc420a5e27889205a27b878",
236
- publicKey: `-----BEGIN PUBLIC KEY-----
237
- MCowBQYDK2VwAyEANcib9WOOIys1wLQW30T/RvRv+3d/+2DAWKOKwEj5sS0=
238
- -----END PUBLIC KEY-----`
372
+ epoch: 2,
373
+ expiry: 1822348800,
374
+ // 2027-10-01 00:00:00 UTC
375
+ fingerprint: CEREMONY_OUTPUT.ra.fingerprint,
376
+ publicKey: CEREMONY_OUTPUT.ra.publicKey
239
377
  },
240
- // ----- CI-FRESHNESS (REAL production keypair cf-k1-2026, generated 2026-07-20) -----
241
- // Signs short-TTL freshness tokens. CI only.
242
- // Private half lives ONLY in ~/.secrets/prod-deploy.env (mode 600) — never shipped, never repo.
378
+ // ----- CI-FRESHNESS (cf-k2-2026, epoch 2) -----
379
+ // Signs short-TTL freshness tokens. The private half is never stored in this repository.
243
380
  {
244
- kid: "cf-k1-2026",
381
+ kid: CEREMONY_OUTPUT.cf.kid,
245
382
  role: "ci-freshness",
246
- epoch: 1,
247
- expiry: 1798761600,
248
- // 2027-01-01 00:00:00 UTC — real production expiry, unchanged from provisioning
249
- fingerprint: "87787b86689151fd9a9b763e3baa2cae884bf897d51dc02a211c70640e2c4f9d",
250
- publicKey: `-----BEGIN PUBLIC KEY-----
251
- MCowBQYDK2VwAyEAaQ49ermPqqsENKA7fFi8K0zIEyxYEje56a34Pus6UhM=
252
- -----END PUBLIC KEY-----`
253
- },
254
- // ----- BUNDLE keys (existing k1-2026 and k2-2026) -----
255
- // Convex-held; signs per-request bundle envelopes. PINNED_KEYS stays in sync.
256
- {
257
- kid: "k1-2026",
258
- role: "bundle",
259
- epoch: 1,
260
- expiry: 1798761600,
261
- fingerprint: "855e81b870c16d377efd8354e9761fadca2d22d16536f291fb77e690f9d65abc",
262
- publicKey: `-----BEGIN PUBLIC KEY-----
263
- MCowBQYDK2VwAyEAkpeX0A3zIOttGn8t+jagJHLRTv5Q809vqIZU37lE6xQ=
264
- -----END PUBLIC KEY-----`
383
+ epoch: 2,
384
+ expiry: 1822348800,
385
+ // 2027-10-01 00:00:00 UTC
386
+ fingerprint: CEREMONY_OUTPUT.cf.fingerprint,
387
+ publicKey: CEREMONY_OUTPUT.cf.publicKey
265
388
  },
389
+ // ----- BUNDLE key (k3-2026, epoch 3; Convex-held; signs per-request bundle envelopes) -----
266
390
  {
267
- kid: "k2-2026",
391
+ kid: CEREMONY_OUTPUT.bundle.kid,
268
392
  role: "bundle",
269
- epoch: 2,
270
- expiry: 1798761600,
271
- fingerprint: "57873aac03421fa0740fdd9520729536223010067ea3012135db2b255a2b263c",
272
- publicKey: `-----BEGIN PUBLIC KEY-----
273
- MCowBQYDK2VwAyEA1DXW6sA9dllAbfXMa/G+50Sw00svQF2X5bcU+YcP6M8=
274
- -----END PUBLIC KEY-----`
393
+ epoch: 3,
394
+ expiry: 1822348800,
395
+ // 2027-10-01 00:00:00 UTC
396
+ fingerprint: CEREMONY_OUTPUT.bundle.fingerprint,
397
+ publicKey: CEREMONY_OUTPUT.bundle.publicKey
275
398
  }
276
399
  // AUTH key: managed separately via JWKS endpoint; the CLI does NOT pin auth keys for
277
- // release trust — only for reference/documentation completeness. Wired separately.
278
- // If you need to add auth-k1-2026 here, obtain the public PEM from the auth service JWKS.
400
+ // release trust.
279
401
  ];
402
+ PINNED_KEYS = Object.fromEntries(
403
+ KEYRING.filter((e) => e.role === "bundle" && !isKeyringPlaceholder(e)).map((e) => [e.kid, e.publicKey])
404
+ );
280
405
  function validateKeyringEntry(entry) {
281
406
  if (entry.epoch < MIN_ACCEPTABLE_EPOCH) {
282
407
  throw new Error(
@@ -289,11 +414,6 @@ function validateKeyringEntry(entry) {
289
414
  );
290
415
  }
291
416
  }
292
- function pemToArrayBuffer(pem) {
293
- const b64 = pem.replace(/-----BEGIN PUBLIC KEY-----/, "").replace(/-----END PUBLIC KEY-----/, "").replace(/\s/g, "");
294
- const binary = Buffer.from(b64, "base64");
295
- return binary.buffer.slice(binary.byteOffset, binary.byteOffset + binary.byteLength);
296
- }
297
417
  async function resolveAndImportKey(kid, expectedRole) {
298
418
  const entry = KEYRING.find((e) => e.kid === kid);
299
419
  if (!entry) {
@@ -301,15 +421,38 @@ async function resolveAndImportKey(kid, expectedRole) {
301
421
  `Unknown key "${kid}" \u2014 not found in KEYRING. Upgrade shipguard to a version that supports this key id.`
302
422
  );
303
423
  }
424
+ if (isKeyringPlaceholder(entry)) {
425
+ throw new Error(
426
+ `Key "${kid}" is an unfilled key-ceremony placeholder \u2014 this build cannot verify it. Upgrade shipguard to a released version.`
427
+ );
428
+ }
304
429
  validateKeyringEntry(entry);
305
430
  if (entry.role !== expectedRole) {
306
431
  throw new Error(
307
432
  `key role mismatch: expected ${expectedRole}, got ${entry.role} \u2014 cross-role replay rejected`
308
433
  );
309
434
  }
435
+ let der;
436
+ try {
437
+ der = spkiDerFromPem(entry.publicKey);
438
+ } catch (err) {
439
+ const msg = err instanceof Error ? err.message : String(err);
440
+ throw new Error(`Key "${kid}" has an unreadable public key: ${msg}`);
441
+ }
442
+ const computed = createHash("sha256").update(der).digest("hex");
443
+ if (computed !== entry.fingerprint.toLowerCase()) {
444
+ throw new Error(
445
+ `Key "${kid}" fingerprint mismatch: declared ${entry.fingerprint}, computed ${computed} \u2014 refusing key`
446
+ );
447
+ }
448
+ if (REVOKED_FINGERPRINTS.has(computed)) {
449
+ throw new Error(
450
+ `Key "${kid}" is revoked (fingerprint ${computed} is on the revoked-key denylist) \u2014 refusing key`
451
+ );
452
+ }
310
453
  return globalThis.crypto.subtle.importKey(
311
454
  "spki",
312
- pemToArrayBuffer(entry.publicKey),
455
+ der.buffer.slice(der.byteOffset, der.byteOffset + der.byteLength),
313
456
  { name: "Ed25519" },
314
457
  false,
315
458
  ["verify"]
@@ -392,6 +535,31 @@ function acquireFloorLock(lockPath, timeoutMs = 5e3) {
392
535
  }
393
536
  throw new Error(`floor lock timeout after ${timeoutMs}ms \u2014 concurrent CLI writer?`);
394
537
  }
538
+ function compareFloorTuples(floor, incoming) {
539
+ if (incoming.keyringEpoch > floor.keyringEpoch) return { decision: "advance" };
540
+ if (incoming.keyringEpoch < floor.keyringEpoch) {
541
+ return {
542
+ decision: "reject",
543
+ reason: `keyring epoch rollback rejected: incoming epoch=${incoming.keyringEpoch}, floor epoch=${floor.keyringEpoch}`
544
+ };
545
+ }
546
+ if (incoming.sequence < floor.sequence) {
547
+ return {
548
+ decision: "reject",
549
+ reason: `sequence rollback rejected: incoming=${incoming.sequence}, floor=${floor.sequence} (epoch ${floor.keyringEpoch})`
550
+ };
551
+ }
552
+ if (incoming.sequence === floor.sequence) {
553
+ if (incoming.releaseId === floor.releaseId && incoming.manifestDigest === floor.manifestDigest) {
554
+ return { decision: "idempotent" };
555
+ }
556
+ return {
557
+ decision: "reject",
558
+ reason: `same-sequence/different-tuple rejected: sequence=${incoming.sequence} (epoch ${floor.keyringEpoch})`
559
+ };
560
+ }
561
+ return { decision: "advance" };
562
+ }
395
563
  function atomicAcceptFloor(floorPath, incoming) {
396
564
  const lockPath = `${floorPath}.lock`;
397
565
  const dir = path.dirname(floorPath);
@@ -430,22 +598,11 @@ function atomicAcceptFloor(floorPath, incoming) {
430
598
  }
431
599
  }
432
600
  if (lockedFloor !== null) {
433
- if (incoming.sequence < lockedFloor.sequence) {
434
- return {
435
- accepted: false,
436
- reason: `sequence rollback rejected (under-lock): incoming=${incoming.sequence}, locked-floor=${lockedFloor.sequence}`
437
- };
601
+ const decision = compareFloorTuples(lockedFloor, incoming);
602
+ if (decision.decision === "reject") {
603
+ return { accepted: false, reason: `${decision.reason} (under-lock)` };
438
604
  }
439
- if (incoming.sequence === lockedFloor.sequence) {
440
- const sameReleaseId = incoming.releaseId === lockedFloor.releaseId;
441
- const sameManifest = incoming.manifestDigest === lockedFloor.manifestDigest;
442
- const sameEpoch = incoming.keyringEpoch === lockedFloor.keyringEpoch;
443
- if (!sameReleaseId || !sameManifest || !sameEpoch) {
444
- return {
445
- accepted: false,
446
- reason: `same-sequence/different-tuple rejected (under-lock): sequence=${incoming.sequence}`
447
- };
448
- }
605
+ if (decision.decision === "idempotent") {
449
606
  return { accepted: true, wrote: false };
450
607
  }
451
608
  }
@@ -960,7 +1117,7 @@ async function verifyBundleResponse(response, request, floorPath) {
960
1117
  if (freshnessTok["manifestDigest"] !== manifestDigest) {
961
1118
  return {
962
1119
  ok: false,
963
- reason: `freshnessTok.manifestDigest mismatch \u2014 token bound to a different manifest (GC.4d)`,
1120
+ reason: `freshnessTok.manifestDigest mismatch \u2014 token bound to a different manifest`,
964
1121
  nonSafe: true
965
1122
  };
966
1123
  }
@@ -1062,7 +1219,14 @@ async function verifyBundleResponse(response, request, floorPath) {
1062
1219
  };
1063
1220
  }
1064
1221
  const attestationEntry = KEYRING.find((e) => e.kid === attestation["kid"]);
1065
- const incomingKeyringEpoch = attestationEntry?.epoch ?? 1;
1222
+ if (!attestationEntry) {
1223
+ return {
1224
+ ok: false,
1225
+ reason: `attestation kid "${String(attestation["kid"])}" vanished from KEYRING after verification`,
1226
+ nonSafe: true
1227
+ };
1228
+ }
1229
+ const incomingKeyringEpoch = attestationEntry.epoch;
1066
1230
  const incomingTuple = {
1067
1231
  sequence: incomingSequence,
1068
1232
  releaseId: incomingReleaseId,
@@ -1193,7 +1357,7 @@ function compileDetectorRegex(source, flags = "") {
1193
1357
  }
1194
1358
 
1195
1359
  // src/core/redact.ts
1196
- import { createHash } from "crypto";
1360
+ import { createHash as createHash2 } from "crypto";
1197
1361
  function redactSecretValue(value) {
1198
1362
  if (value.length <= 8) return "***";
1199
1363
  return value.slice(0, 8) + "***";
@@ -1270,7 +1434,7 @@ function redactEvidence(evidence, category) {
1270
1434
  }
1271
1435
  function computeFindingKey(finding) {
1272
1436
  const basis = finding.evidence && finding.evidence.length > 0 ? finding.evidence : finding.title;
1273
- return createHash("sha256").update(basis).digest("hex").slice(0, 16);
1437
+ return createHash2("sha256").update(basis).digest("hex").slice(0, 16);
1274
1438
  }
1275
1439
  var FINDING_KEY_PROP = "_findingKey";
1276
1440
  function getFindingKey(finding) {
@@ -1442,7 +1606,7 @@ var SECRET_PATTERNS = [
1442
1606
  recommendation: "Remove from source code. Use process.env.RAZORPAY_KEY_SECRET and store in a gitignored .env file."
1443
1607
  },
1444
1608
  // JWT secret
1445
- // Task #81 gap 3 fix: the opening quote used to be MANDATORY (`['"]([^'"]{16,})`),
1609
+ // Free-tier secret gaps: the opening quote used to be MANDATORY (`['"]([^'"]{16,})`),
1446
1610
  // which only matches source-file assignment style (`const x = "value"`). A .env
1447
1611
  // file's `JWT_SECRET=value` line has no quotes at all, so this pattern never
1448
1612
  // matched .env content. Quotes are now optional on both sides, and the capture
@@ -1462,10 +1626,10 @@ var SECRET_PATTERNS = [
1462
1626
  recommendation: "Remove from source code. Generate a strong random secret, store it in environment variables."
1463
1627
  },
1464
1628
  // Supabase service-role key — current key format (2025+ rotation: sb_secret_...)
1465
- // Task #81 gap 2: the free tier had no Supabase-specific service-role pattern at
1629
+ // Free-tier secret gaps: the free tier had no Supabase-specific service-role pattern at
1466
1630
  // all — a variable literally named SERVICE_ROLE_KEY matched none of the generic
1467
1631
  // secret-name keywords (api_key/secret/token/password/auth_key/access_key) below,
1468
- // per the evidenced miss in apps/web/content/blog/supabase-rls-ai-built-apps.mdx.
1632
+ // per a miss seen on a real project.
1469
1633
  // This prefix match covers the current opaque key format; the legacy JWT format
1470
1634
  // (pre-2025 projects) is handled separately by checkSupabaseServiceRoleJwt below,
1471
1635
  // which decodes the payload rather than pattern-matching the shape.
@@ -1495,10 +1659,9 @@ var SECRET_PATTERNS = [
1495
1659
  // D.4 REWRITE: Removed native negative-lookahead (?!\s*\+|\.) — not supported by re2js.
1496
1660
  // Equivalent behavior is achieved via postExcludeFollowedBy() which checks the
1497
1661
  // character immediately after the closing quote. See DIFFERENTIAL NOTE above.
1498
- // Task #81 gap 3 fix: both quotes used to be MANDATORY (`['"](...)['"]`), which only
1662
+ // Free-tier secret gaps: both quotes used to be MANDATORY (`['"](...)['"]`), which only
1499
1663
  // matches source-file assignment style (`const x = "value"`) and never a .env file's
1500
- // unquoted `TOKEN=value` line — confirmed by the evidenced miss in
1501
- // apps/web/content/blog/github-secret-scanner-vs-cli-tools.md (INTERNAL_DEPLOY_TOKEN
1664
+ // unquoted `TOKEN=value` line — confirmed by a miss seen on a real project (INTERNAL_DEPLOY_TOKEN
1502
1665
  // caught when moved into config.ts, not when left in .env). Quotes are now optional;
1503
1666
  // the capture class already excludes whitespace and quote characters, so an unquoted
1504
1667
  // .env value still terminates correctly instead of over-capturing.
@@ -2203,11 +2366,10 @@ var MIGRATION_PATTERNS = [
2203
2366
  /^migrations\/.+\.sql$/i,
2204
2367
  /^db\/.+\.sql$/i,
2205
2368
  // Supabase CLI default layout (`supabase init` / `supabase migration new`) —
2206
- // task #81 gap 1: this was missing entirely, so every DEFAULT Supabase project's
2369
+ // free-tier secret gaps: this was missing entirely, so every DEFAULT Supabase project's
2207
2370
  // migrations silently skipped the destructive-migration checks below (DROP TABLE,
2208
- // TRUNCATE, DELETE FROM without WHERE, etc.). See
2209
- // apps/web/content/blog/supabase-rls-ai-built-apps.mdx for the evidenced repro:
2210
- // `supabase/migrations/0001_create_orders.sql` went unclassified and unscanned.
2371
+ // TRUNCATE, DELETE FROM without WHERE, etc.). A
2372
+ // real-world repro: `supabase/migrations/0001_create_orders.sql` went unclassified and unscanned.
2211
2373
  /^supabase\/migrations\/.+\.sql$/i,
2212
2374
  /^[^/]+\.sql$/i
2213
2375
  // root-level .sql files
@@ -3235,8 +3397,34 @@ function applySuppressions(findings, files) {
3235
3397
  return findings;
3236
3398
  }
3237
3399
 
3238
- // src/core/pro-scanner.ts
3400
+ // src/core/re2js-compile-cache.ts
3239
3401
  import { RE2JS as RE2JS2 } from "re2js";
3402
+ var COMPILE_CACHE_MAX = 2e4;
3403
+ var cache = /* @__PURE__ */ new Map();
3404
+ var INSTALLED = /* @__PURE__ */ Symbol.for("agenticcli.re2js.compileCache");
3405
+ function installRe2jsCompileCache() {
3406
+ const target = RE2JS2;
3407
+ if (target[INSTALLED]) return;
3408
+ const original = target.compile.bind(RE2JS2);
3409
+ target.compile = (pattern, flags = 0) => {
3410
+ const key = `${flags}\0${pattern}`;
3411
+ const hit = cache.get(key);
3412
+ if (hit !== void 0) return hit;
3413
+ const compiled = original(pattern, flags);
3414
+ if (cache.size >= COMPILE_CACHE_MAX) cache.clear();
3415
+ cache.set(key, compiled);
3416
+ return compiled;
3417
+ };
3418
+ target[INSTALLED] = true;
3419
+ }
3420
+ function compileCached(pattern, flags) {
3421
+ installRe2jsCompileCache();
3422
+ return RE2JS2.compile(pattern, flags);
3423
+ }
3424
+
3425
+ // src/core/pro-scanner.ts
3426
+ import { RE2JS as RE2JS3 } from "re2js";
3427
+ installRe2jsCompileCache();
3240
3428
  var activeExecutor = re2jsV1Executor;
3241
3429
  var DEFAULT_FLOOR_PATH = path2.join(os.homedir(), ".shipguard", "release-floor.json");
3242
3430
  var NoRulesAppliedError = class extends Error {
@@ -3248,7 +3436,7 @@ var NoRulesAppliedError = class extends Error {
3248
3436
  };
3249
3437
  var ProFetchError = class extends Error {
3250
3438
  code;
3251
- /** Only populated for RATE_LIMITED, when the server sends a `Retry-After` header. */
3439
+ /** Only populated for RATE_LIMITED and PLATFORM_UNAVAILABLE, when the server sends a usable `Retry-After` header. */
3252
3440
  retryAfterSeconds;
3253
3441
  constructor(code, message, opts) {
3254
3442
  super(message);
@@ -3257,9 +3445,26 @@ var ProFetchError = class extends Error {
3257
3445
  this.retryAfterSeconds = opts?.retryAfterSeconds;
3258
3446
  }
3259
3447
  };
3448
+ function parseCreditsRemaining(headers) {
3449
+ const raw = headers.get("X-Credits-Remaining");
3450
+ if (raw === null || raw.trim() === "") return void 0;
3451
+ const credits = Number(raw.trim());
3452
+ return Number.isFinite(credits) ? credits : void 0;
3453
+ }
3260
3454
  async function fetchProRules(frameworks, categories, apiUrl, scanId, floorPath) {
3261
3455
  assertTrustedApiUrl(apiUrl);
3262
- const token = await getAuthToken(apiUrl);
3456
+ let token;
3457
+ try {
3458
+ token = await getAuthToken(apiUrl);
3459
+ } catch (err) {
3460
+ if (err instanceof PlatformUnavailableError) {
3461
+ throw new ProFetchError("PLATFORM_UNAVAILABLE", err.message, { retryAfterSeconds: err.retryAfterSeconds });
3462
+ }
3463
+ if (err instanceof RefreshUnavailableError) {
3464
+ throw new ProFetchError("RATE_LIMITED", err.message, { retryAfterSeconds: err.retryAfterSeconds });
3465
+ }
3466
+ throw err;
3467
+ }
3263
3468
  if (!token) throw new ProFetchError("AUTH_FAILED", "Not authenticated. Run `shipguard login` first.");
3264
3469
  let res;
3265
3470
  try {
@@ -3292,15 +3497,20 @@ async function fetchProRules(frameworks, categories, apiUrl, scanId, floorPath)
3292
3497
  errorBody.error ?? "No rule release has ever been activated on the server \u2014 Pro rules genuinely cannot be served right now (a server-side activation gap, not a transient outage)."
3293
3498
  );
3294
3499
  }
3500
+ if (isPlatformUnavailable(res, errorBody)) {
3501
+ throw new ProFetchError(
3502
+ "PLATFORM_UNAVAILABLE",
3503
+ errorBody?.error ?? PLATFORM_UNAVAILABLE_DEFAULT_MESSAGE,
3504
+ { retryAfterSeconds: parseRetryAfterSeconds(res.headers) }
3505
+ );
3506
+ }
3295
3507
  if (res.status === 401) throw new ProFetchError("AUTH_FAILED", "Auth expired. Run `shipguard login` again.");
3296
- if (res.status === 402) throw new ProFetchError("INSUFFICIENT_CREDITS", "No credits. Buy at https://agenticcli.dev/dashboard/billing");
3508
+ if (res.status === 402) throw new ProFetchError("INSUFFICIENT_CREDITS", `No credits. Buy at ${goLink("billing")}`);
3297
3509
  if (res.status === 429) {
3298
- const retryAfterHeader = res.headers.get("Retry-After");
3299
- const retryAfterSeconds = retryAfterHeader ? parseInt(retryAfterHeader, 10) : void 0;
3300
3510
  throw new ProFetchError(
3301
3511
  "RATE_LIMITED",
3302
3512
  `Rate limited (429): too many pro rule fetches.`,
3303
- { retryAfterSeconds: Number.isFinite(retryAfterSeconds) ? retryAfterSeconds : void 0 }
3513
+ { retryAfterSeconds: parseRetryAfterSeconds(res.headers) }
3304
3514
  );
3305
3515
  }
3306
3516
  if (res.status === 409) throw new ProFetchError("SERVER_ERROR", `Rule fetch conflict (409): ${res.statusText}`);
@@ -3316,12 +3526,12 @@ async function fetchProRules(frameworks, categories, apiUrl, scanId, floorPath)
3316
3526
  if (res.status >= 500) throw new ProFetchError("SERVER_ERROR", `Rule fetch failed (${res.status}): ${res.statusText}`);
3317
3527
  throw new ProFetchError("SERVER_ERROR", `Rule fetch failed: ${res.statusText}`);
3318
3528
  }
3319
- const credits = parseInt(res.headers.get("X-Credits-Remaining") ?? "0", 10);
3529
+ const credits = parseCreditsRemaining(res.headers);
3320
3530
  const rulesVersion = res.headers.get("X-Rules-Version") ?? void 0;
3321
3531
  const rawText = await res.text();
3322
3532
  let responseJson;
3323
3533
  try {
3324
- const { parseStrictNoDup: parseStrict } = await import("./dist-3SW45O4F.js");
3534
+ const { parseStrictNoDup: parseStrict } = await import("./dist-YSE6YNXH.js");
3325
3535
  responseJson = parseStrict(rawText);
3326
3536
  } catch (parseErr) {
3327
3537
  const msg = parseErr instanceof Error ? parseErr.message : String(parseErr);
@@ -3361,10 +3571,10 @@ async function fetchProRules(frameworks, categories, apiUrl, scanId, floorPath)
3361
3571
  explanation: r.title,
3362
3572
  recommendation: "",
3363
3573
  action,
3364
- // Task #16 (hardcoded-confidence fix): carry the rule's REAL signed confidence.
3574
+ // Per-rule confidence (hardcoded-confidence fix): carry the rule's REAL signed confidence.
3365
3575
  // verifyBundleResponse has already fail-closed if any rule lacks confidence, so
3366
3576
  // r.confidence is guaranteed present here — never a silent HIGH default. Corpus
3367
- // governance (rule-corpus/rule-logic.md §4) calibrates action to this value, and
3577
+ // governance calibrates action to this value, and
3368
3578
  // deriveBlocking() + CLI output/JSON depend on it being the author's signed intent.
3369
3579
  confidence: r.confidence,
3370
3580
  matcher: {
@@ -3374,7 +3584,7 @@ async function fetchProRules(frameworks, categories, apiUrl, scanId, floorPath)
3374
3584
  patterns: r.pattern ? [r.pattern] : [],
3375
3585
  antiPatterns: r.antiPattern ? [r.antiPattern] : [],
3376
3586
  flags: r.flags,
3377
- // FIX 1 (CRITICAL): antiPatternScope and boundary are now part of the 20-field
3587
+ // antiPatternScope and boundary are now part of the 20-field
3378
3588
  // hash preimage (contract 0.5.0) and ARE delivered on the wire ExecutableRule.
3379
3589
  // They were missing from this mapping, causing runProRules to always default to
3380
3590
  // antiPatternScope:'statement' / boundary:'none' — ignoring the corpus values.
@@ -3402,14 +3612,14 @@ async function fetchProRules(frameworks, categories, apiUrl, scanId, floorPath)
3402
3612
  }
3403
3613
  throw new ProFetchError(
3404
3614
  "BUNDLE_INVALID",
3405
- "legacy-bundle-rejected: attestation required \u2014 server response lacks fullManifest. The server must deliver a BundleResponse with fullManifest + corpusAttestation (attested-release protocol, GC.14). Exit non-safe."
3615
+ "legacy-bundle-rejected: attestation required \u2014 server response lacks fullManifest. The server must deliver a BundleResponse with fullManifest + corpusAttestation (attested-release protocol). Exit non-safe."
3406
3616
  );
3407
3617
  }
3408
3618
  function toRe2jsFlags2(flags) {
3409
3619
  let bits = 0;
3410
- if (flags.has("i")) bits |= RE2JS2.CASE_INSENSITIVE;
3411
- if (flags.has("m")) bits |= RE2JS2.MULTILINE;
3412
- if (flags.has("s")) bits |= RE2JS2.DOTALL;
3620
+ if (flags.has("i")) bits |= RE2JS3.CASE_INSENSITIVE;
3621
+ if (flags.has("m")) bits |= RE2JS3.MULTILINE;
3622
+ if (flags.has("s")) bits |= RE2JS3.DOTALL;
3413
3623
  return bits;
3414
3624
  }
3415
3625
  function validateBundleCompile(rules) {
@@ -3441,7 +3651,7 @@ function validateBundleCompile(rules) {
3441
3651
  const msg = err instanceof Error ? err.message : String(err);
3442
3652
  return {
3443
3653
  ok: false,
3444
- reason: `Rule ${rule.id}: anti-pattern "${ap}" fails re2js compilation \u2014 ${msg}. The entire bundle is degraded rather than running the rule without its anti-pattern guard (atomic compile, FIX 5 fail-closed).`
3654
+ reason: `Rule ${rule.id}: anti-pattern "${ap}" fails re2js compilation \u2014 ${msg}. The entire bundle is degraded rather than running the rule without its anti-pattern guard (atomic compile, fail-closed).`
3445
3655
  };
3446
3656
  }
3447
3657
  }
@@ -3496,7 +3706,7 @@ function runProRules(rules, files, _policy) {
3496
3706
  patterns: rule.matcher.patterns,
3497
3707
  antiPatterns: rule.matcher.antiPatterns,
3498
3708
  flags: rule.matcher.flags ?? "",
3499
- // FIX 1+2: pass through delivered values; executor defaults to 'none'/'statement'.
3709
+ // pass through delivered values; executor defaults to 'none'/'statement'.
3500
3710
  ...boundary !== void 0 && { boundary },
3501
3711
  ...antiPatternScope !== void 0 && { antiPatternScope }
3502
3712
  };
@@ -3565,7 +3775,7 @@ function runProRules(rules, files, _policy) {
3565
3775
  recommendation: rule.recommendation,
3566
3776
  blocking: isSuppressed ? false : deriveBlocking(rule),
3567
3777
  suppressed: isSuppressed,
3568
- // New fields from contract integration (Task A-CLI-INT.2)
3778
+ // New fields from contract integration
3569
3779
  suppressionState: isSuppressed ? "suppressed" : "active",
3570
3780
  matcherType: cf.matcherType,
3571
3781
  // releaseId: 'pre-attestation' — not set on Finding until Phase C wires
@@ -3622,6 +3832,7 @@ function runProRulesWithDispatch(rules, files, policy, cliVersion, table, manife
3622
3832
  }
3623
3833
 
3624
3834
  export {
3835
+ goLink,
3625
3836
  logger,
3626
3837
  getFindingKey,
3627
3838
  redactFindingsEvidence,