@agenticcli/shipguard 0.7.0 → 0.8.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.
@@ -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";
@@ -18,12 +17,10 @@ import * as os from "os";
18
17
  // src/core/auth.ts
19
18
  import {
20
19
  readFileSync,
21
- writeFileSync,
22
- mkdirSync,
20
+ writeFileSync as writeFileSync2,
23
21
  rmSync,
24
22
  existsSync,
25
- statSync,
26
- chmodSync
23
+ statSync as statSync2
27
24
  } from "fs";
28
25
  import { join, dirname } from "path";
29
26
  import { homedir } from "os";
@@ -59,17 +56,59 @@ function assertTrustedApiUrl(url) {
59
56
  );
60
57
  }
61
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
+
65
+ // src/utils/secure-fs.ts
66
+ import { chmodSync, mkdirSync, statSync, writeFileSync } from "fs";
67
+ var SECURE_DIR_MODE = 448;
68
+ var SECURE_FILE_MODE = 384;
69
+ var isPosix = process.platform !== "win32";
70
+ function ensureSecureDir(dir) {
71
+ mkdirSync(dir, { recursive: true, mode: SECURE_DIR_MODE });
72
+ if (isPosix && statSync(dir).uid === process.getuid?.()) chmodSync(dir, SECURE_DIR_MODE);
73
+ }
74
+ function writeSecureFileSync(file, data) {
75
+ writeFileSync(file, data, { mode: SECURE_FILE_MODE });
76
+ if (isPosix) chmodSync(file, SECURE_FILE_MODE);
77
+ }
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
+
62
102
  // src/core/auth.ts
63
- var DIR_MODE = 448;
64
103
  var FILE_MODE = 384;
65
104
  var UNSAFE_PERM_MASK = 63;
66
- var isPosix = process.platform !== "win32";
105
+ var isPosix2 = process.platform !== "win32";
67
106
  function getCredentialsPath() {
68
107
  return join(homedir(), ".config", "shipguard", "credentials.json");
69
108
  }
70
109
  function hasUnsafePermissions(path3) {
71
- if (!isPosix) return false;
72
- const mode = statSync(path3).mode & 511;
110
+ if (!isPosix2) return false;
111
+ const mode = statSync2(path3).mode & 511;
73
112
  return (mode & UNSAFE_PERM_MASK) !== 0;
74
113
  }
75
114
  function loadCredentials() {
@@ -91,17 +130,15 @@ function loadCredentials() {
91
130
  async function saveCredentials(creds) {
92
131
  const p = getCredentialsPath();
93
132
  const dir = dirname(p);
94
- mkdirSync(dir, { recursive: true, mode: DIR_MODE });
95
- if (isPosix) chmodSync(dir, DIR_MODE);
96
- writeFileSync(p, JSON.stringify(creds, null, 2), { mode: FILE_MODE });
97
- if (isPosix) chmodSync(p, FILE_MODE);
133
+ ensureSecureDir(dir);
134
+ writeSecureFileSync(p, JSON.stringify(creds, null, 2));
98
135
  }
99
136
  function clearCredentials() {
100
137
  const p = getCredentialsPath();
101
138
  if (!existsSync(p)) return;
102
139
  try {
103
- const size = statSync(p).size;
104
- if (size > 0) writeFileSync(p, Buffer.alloc(size, 0), { mode: FILE_MODE });
140
+ const size = statSync2(p).size;
141
+ if (size > 0) writeFileSync2(p, Buffer.alloc(size, 0), { mode: FILE_MODE });
105
142
  } catch {
106
143
  }
107
144
  rmSync(p, { force: true });
@@ -129,22 +166,29 @@ async function exchangeApiKeyForToken(apiKey, apiUrl) {
129
166
  if (res.status === 401) {
130
167
  console.error("[shipguard] SHIPGUARD_API_KEY exchange rejected \u2014 invalid or revoked key");
131
168
  throw new Error(
132
- "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")}.`
133
170
  );
134
171
  }
135
172
  if (res.status === 402) {
136
173
  console.error("[shipguard] SHIPGUARD_API_KEY exchange rejected \u2014 monthly budget exhausted");
137
174
  throw new Error(
138
- "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")}`
139
176
  );
140
177
  }
141
178
  if (!res.ok) {
142
179
  let detail = res.statusText;
180
+ let body2 = null;
143
181
  try {
144
- const body2 = await res.json();
182
+ body2 = await res.json();
145
183
  detail = body2?.error_description ?? body2?.error ?? detail;
146
184
  } catch {
147
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
+ }
148
192
  console.error(`[shipguard] SHIPGUARD_API_KEY exchange failed (${res.status}): ${detail}`);
149
193
  throw new Error(`SHIPGUARD_API_KEY exchange failed (${res.status}): ${detail}`);
150
194
  }
@@ -193,10 +237,24 @@ async function getAuthToken(apiUrl) {
193
237
  });
194
238
  return access_token;
195
239
  }
240
+ let refusedBody = null;
241
+ try {
242
+ const probe = typeof res.clone === "function" ? res.clone() : res;
243
+ refusedBody = await probe.json();
244
+ } catch {
245
+ refusedBody = null;
246
+ }
247
+ if (isPlatformUnavailable(res, refusedBody)) {
248
+ throw new PlatformUnavailableError(
249
+ typeof refusedBody?.error === "string" ? refusedBody.error : PLATFORM_UNAVAILABLE_DEFAULT_MESSAGE,
250
+ parseRetryAfterSeconds(res.headers)
251
+ );
252
+ }
196
253
  console.error(
197
254
  `[shipguard] Token refresh refused by ${creds.apiUrl} (HTTP ${res.status} ${res.statusText}) \u2014 you will be asked to log in again.`
198
255
  );
199
256
  } catch (err) {
257
+ if (err instanceof PlatformUnavailableError) throw err;
200
258
  const detail = err instanceof Error ? err.message : String(err);
201
259
  console.error(
202
260
  `[shipguard] Token refresh failed \u2014 you will be asked to log in again. Reason: ${detail}`
@@ -212,62 +270,91 @@ import * as path from "path";
212
270
  import { sha256 } from "@noble/hashes/sha2.js";
213
271
 
214
272
  // src/core/crypto.ts
215
- var MIN_ACCEPTABLE_EPOCH = 1;
273
+ import { createHash } from "crypto";
274
+
275
+ // src/core/keyring-ceremony-output.ts
276
+ var CEREMONY_OUTPUT = {
277
+ ra: {
278
+ kid: "ra-k2-2026",
279
+ fingerprint: "a3c0751a14d6933c2e0dbfca69f50a0189ed749153d62b1b76727fc714bf043c",
280
+ publicKey: "-----BEGIN PUBLIC KEY-----\nMCowBQYDK2VwAyEAI5sKq3SF+toDqPO3Brz1FkWOl7INL/O9K3BBtPS3zTo=\n-----END PUBLIC KEY-----"
281
+ },
282
+ cf: {
283
+ kid: "cf-k2-2026",
284
+ fingerprint: "3535a1f5bdd798af75e893aaa93346df6b7e421632ca8bc0105ff866a89c0cee",
285
+ publicKey: "-----BEGIN PUBLIC KEY-----\nMCowBQYDK2VwAyEAjyVy38g4NcfXqD3WmZP7ygit8m4aoywK0KsA0jYiEv4=\n-----END PUBLIC KEY-----"
286
+ },
287
+ bundle: {
288
+ kid: "k3-2026",
289
+ fingerprint: "3cbd12f5c1ef05c33527899f0d074585cb26bacdfe6f13a63cbea243d5c8e57e",
290
+ publicKey: "-----BEGIN PUBLIC KEY-----\nMCowBQYDK2VwAyEA4seZCqwlRq+QzOsIA6+RJUHXHWe4lb1ok6hwL0Bvqzs=\n-----END PUBLIC KEY-----"
291
+ }
292
+ };
293
+
294
+ // src/core/crypto.ts
295
+ var PINNED_KEYS = {};
296
+ var DEFAULT_KID = CEREMONY_OUTPUT.bundle.kid;
297
+ var MIN_ACCEPTABLE_EPOCH = 2;
298
+ var REVOKED_FINGERPRINTS = /* @__PURE__ */ new Set([
299
+ "855e81b870c16d377efd8354e9761fadca2d22d16536f291fb77e690f9d65abc",
300
+ // keys no longer trusted
301
+ "003837c9c656f66163a29e7b0d043a084fc83c2febc420a5e27889205a27b878",
302
+ // keys no longer trusted
303
+ "87787b86689151fd9a9b763e3baa2cae884bf897d51dc02a211c70640e2c4f9d",
304
+ // keys no longer trusted
305
+ "57873aac03421fa0740fdd9520729536223010067ea3012135db2b255a2b263c"
306
+ // keys no longer trusted
307
+ ]);
308
+ var KEYRING_PLACEHOLDER_MARKER = "SHIPGUARD_KEYRING_PLACEHOLDER";
309
+ function isKeyringPlaceholder(entry) {
310
+ return entry.publicKey.includes(KEYRING_PLACEHOLDER_MARKER) || entry.fingerprint.includes(KEYRING_PLACEHOLDER_MARKER);
311
+ }
312
+ function spkiDerFromPem(pem) {
313
+ const m = /^-----BEGIN PUBLIC KEY-----\s*([A-Za-z0-9+/=\s]+?)\s*-----END PUBLIC KEY-----\s*$/.exec(pem.trim());
314
+ if (!m) throw new Error("not a PEM-encoded SPKI public key");
315
+ const der = Buffer.from(m[1].replace(/\s/g, ""), "base64");
316
+ if (der.length === 0) throw new Error("empty SPKI public key");
317
+ return der;
318
+ }
216
319
  var KEYRING = [
217
- // ----- RELEASE-ATTESTATION (REAL production keypair ra-k1-2026, generated 2026-07-20) -----
218
- // Signs corpus manifest + release attestation objects. CI only.
219
- // Private half lives ONLY in ~/.secrets/prod-deploy.env (mode 600) — never shipped, never repo.
320
+ // ----- RELEASE-ATTESTATION (ra-k2-2026, epoch 2) -----
321
+ // Signs corpus manifest + release attestation objects. The private half is never shipped and never stored in this repository.
220
322
  {
221
- kid: "ra-k1-2026",
323
+ kid: CEREMONY_OUTPUT.ra.kid,
222
324
  role: "release-attestation",
223
- epoch: 1,
224
- expiry: 1798761600,
225
- // 2027-01-01 00:00:00 UTC — real production expiry, unchanged from provisioning
226
- fingerprint: "003837c9c656f66163a29e7b0d043a084fc83c2febc420a5e27889205a27b878",
227
- publicKey: `-----BEGIN PUBLIC KEY-----
228
- MCowBQYDK2VwAyEANcib9WOOIys1wLQW30T/RvRv+3d/+2DAWKOKwEj5sS0=
229
- -----END PUBLIC KEY-----`
325
+ epoch: 2,
326
+ expiry: 1822348800,
327
+ // 2027-10-01 00:00:00 UTC
328
+ fingerprint: CEREMONY_OUTPUT.ra.fingerprint,
329
+ publicKey: CEREMONY_OUTPUT.ra.publicKey
230
330
  },
231
- // ----- CI-FRESHNESS (REAL production keypair cf-k1-2026, generated 2026-07-20) -----
232
- // Signs short-TTL freshness tokens. CI only.
233
- // Private half lives ONLY in ~/.secrets/prod-deploy.env (mode 600) — never shipped, never repo.
331
+ // ----- CI-FRESHNESS (cf-k2-2026, epoch 2) -----
332
+ // Signs short-TTL freshness tokens. The private half is never stored in this repository.
234
333
  {
235
- kid: "cf-k1-2026",
334
+ kid: CEREMONY_OUTPUT.cf.kid,
236
335
  role: "ci-freshness",
237
- epoch: 1,
238
- expiry: 1798761600,
239
- // 2027-01-01 00:00:00 UTC — real production expiry, unchanged from provisioning
240
- fingerprint: "87787b86689151fd9a9b763e3baa2cae884bf897d51dc02a211c70640e2c4f9d",
241
- publicKey: `-----BEGIN PUBLIC KEY-----
242
- MCowBQYDK2VwAyEAaQ49ermPqqsENKA7fFi8K0zIEyxYEje56a34Pus6UhM=
243
- -----END PUBLIC KEY-----`
244
- },
245
- // ----- BUNDLE keys (existing k1-2026 and k2-2026) -----
246
- // Convex-held; signs per-request bundle envelopes. PINNED_KEYS stays in sync.
247
- {
248
- kid: "k1-2026",
249
- role: "bundle",
250
- epoch: 1,
251
- expiry: 1798761600,
252
- fingerprint: "855e81b870c16d377efd8354e9761fadca2d22d16536f291fb77e690f9d65abc",
253
- publicKey: `-----BEGIN PUBLIC KEY-----
254
- MCowBQYDK2VwAyEAkpeX0A3zIOttGn8t+jagJHLRTv5Q809vqIZU37lE6xQ=
255
- -----END PUBLIC KEY-----`
336
+ epoch: 2,
337
+ expiry: 1822348800,
338
+ // 2027-10-01 00:00:00 UTC
339
+ fingerprint: CEREMONY_OUTPUT.cf.fingerprint,
340
+ publicKey: CEREMONY_OUTPUT.cf.publicKey
256
341
  },
342
+ // ----- BUNDLE key (k3-2026, epoch 3; Convex-held; signs per-request bundle envelopes) -----
257
343
  {
258
- kid: "k2-2026",
344
+ kid: CEREMONY_OUTPUT.bundle.kid,
259
345
  role: "bundle",
260
- epoch: 2,
261
- expiry: 1798761600,
262
- fingerprint: "57873aac03421fa0740fdd9520729536223010067ea3012135db2b255a2b263c",
263
- publicKey: `-----BEGIN PUBLIC KEY-----
264
- MCowBQYDK2VwAyEA1DXW6sA9dllAbfXMa/G+50Sw00svQF2X5bcU+YcP6M8=
265
- -----END PUBLIC KEY-----`
346
+ epoch: 3,
347
+ expiry: 1822348800,
348
+ // 2027-10-01 00:00:00 UTC
349
+ fingerprint: CEREMONY_OUTPUT.bundle.fingerprint,
350
+ publicKey: CEREMONY_OUTPUT.bundle.publicKey
266
351
  }
267
352
  // AUTH key: managed separately via JWKS endpoint; the CLI does NOT pin auth keys for
268
- // release trust — only for reference/documentation completeness. Wired separately.
269
- // If you need to add auth-k1-2026 here, obtain the public PEM from the auth service JWKS.
353
+ // release trust.
270
354
  ];
355
+ PINNED_KEYS = Object.fromEntries(
356
+ KEYRING.filter((e) => e.role === "bundle" && !isKeyringPlaceholder(e)).map((e) => [e.kid, e.publicKey])
357
+ );
271
358
  function validateKeyringEntry(entry) {
272
359
  if (entry.epoch < MIN_ACCEPTABLE_EPOCH) {
273
360
  throw new Error(
@@ -280,11 +367,6 @@ function validateKeyringEntry(entry) {
280
367
  );
281
368
  }
282
369
  }
283
- function pemToArrayBuffer(pem) {
284
- const b64 = pem.replace(/-----BEGIN PUBLIC KEY-----/, "").replace(/-----END PUBLIC KEY-----/, "").replace(/\s/g, "");
285
- const binary = Buffer.from(b64, "base64");
286
- return binary.buffer.slice(binary.byteOffset, binary.byteOffset + binary.byteLength);
287
- }
288
370
  async function resolveAndImportKey(kid, expectedRole) {
289
371
  const entry = KEYRING.find((e) => e.kid === kid);
290
372
  if (!entry) {
@@ -292,15 +374,38 @@ async function resolveAndImportKey(kid, expectedRole) {
292
374
  `Unknown key "${kid}" \u2014 not found in KEYRING. Upgrade shipguard to a version that supports this key id.`
293
375
  );
294
376
  }
377
+ if (isKeyringPlaceholder(entry)) {
378
+ throw new Error(
379
+ `Key "${kid}" is an unfilled key-ceremony placeholder \u2014 this build cannot verify it. Upgrade shipguard to a released version.`
380
+ );
381
+ }
295
382
  validateKeyringEntry(entry);
296
383
  if (entry.role !== expectedRole) {
297
384
  throw new Error(
298
385
  `key role mismatch: expected ${expectedRole}, got ${entry.role} \u2014 cross-role replay rejected`
299
386
  );
300
387
  }
388
+ let der;
389
+ try {
390
+ der = spkiDerFromPem(entry.publicKey);
391
+ } catch (err) {
392
+ const msg = err instanceof Error ? err.message : String(err);
393
+ throw new Error(`Key "${kid}" has an unreadable public key: ${msg}`);
394
+ }
395
+ const computed = createHash("sha256").update(der).digest("hex");
396
+ if (computed !== entry.fingerprint.toLowerCase()) {
397
+ throw new Error(
398
+ `Key "${kid}" fingerprint mismatch: declared ${entry.fingerprint}, computed ${computed} \u2014 refusing key`
399
+ );
400
+ }
401
+ if (REVOKED_FINGERPRINTS.has(computed)) {
402
+ throw new Error(
403
+ `Key "${kid}" is revoked (fingerprint ${computed} is on the revoked-key denylist) \u2014 refusing key`
404
+ );
405
+ }
301
406
  return globalThis.crypto.subtle.importKey(
302
407
  "spki",
303
- pemToArrayBuffer(entry.publicKey),
408
+ der.buffer.slice(der.byteOffset, der.byteOffset + der.byteLength),
304
409
  { name: "Ed25519" },
305
410
  false,
306
411
  ["verify"]
@@ -365,7 +470,7 @@ function acquireFloorLock(lockPath, timeoutMs = 5e3) {
365
470
  const deadline = Date.now() + timeoutMs;
366
471
  while (Date.now() < deadline) {
367
472
  try {
368
- const fd = fs.openSync(lockPath, "wx");
473
+ const fd = fs.openSync(lockPath, "wx", SECURE_FILE_MODE);
369
474
  fs.closeSync(fd);
370
475
  return () => {
371
476
  try {
@@ -383,10 +488,36 @@ function acquireFloorLock(lockPath, timeoutMs = 5e3) {
383
488
  }
384
489
  throw new Error(`floor lock timeout after ${timeoutMs}ms \u2014 concurrent CLI writer?`);
385
490
  }
491
+ function compareFloorTuples(floor, incoming) {
492
+ if (incoming.keyringEpoch > floor.keyringEpoch) return { decision: "advance" };
493
+ if (incoming.keyringEpoch < floor.keyringEpoch) {
494
+ return {
495
+ decision: "reject",
496
+ reason: `keyring epoch rollback rejected: incoming epoch=${incoming.keyringEpoch}, floor epoch=${floor.keyringEpoch}`
497
+ };
498
+ }
499
+ if (incoming.sequence < floor.sequence) {
500
+ return {
501
+ decision: "reject",
502
+ reason: `sequence rollback rejected: incoming=${incoming.sequence}, floor=${floor.sequence} (epoch ${floor.keyringEpoch})`
503
+ };
504
+ }
505
+ if (incoming.sequence === floor.sequence) {
506
+ if (incoming.releaseId === floor.releaseId && incoming.manifestDigest === floor.manifestDigest) {
507
+ return { decision: "idempotent" };
508
+ }
509
+ return {
510
+ decision: "reject",
511
+ reason: `same-sequence/different-tuple rejected: sequence=${incoming.sequence} (epoch ${floor.keyringEpoch})`
512
+ };
513
+ }
514
+ return { decision: "advance" };
515
+ }
386
516
  function atomicAcceptFloor(floorPath, incoming) {
387
517
  const lockPath = `${floorPath}.lock`;
388
518
  const dir = path.dirname(floorPath);
389
519
  const tmpPath = path.join(dir, `.floor-tmp-${process.pid}-${Date.now()}.json`);
520
+ ensureSecureDir(dir);
390
521
  const releaseLock = acquireFloorLock(lockPath);
391
522
  try {
392
523
  let lockedFloor = null;
@@ -420,26 +551,15 @@ function atomicAcceptFloor(floorPath, incoming) {
420
551
  }
421
552
  }
422
553
  if (lockedFloor !== null) {
423
- if (incoming.sequence < lockedFloor.sequence) {
424
- return {
425
- accepted: false,
426
- reason: `sequence rollback rejected (under-lock): incoming=${incoming.sequence}, locked-floor=${lockedFloor.sequence}`
427
- };
554
+ const decision = compareFloorTuples(lockedFloor, incoming);
555
+ if (decision.decision === "reject") {
556
+ return { accepted: false, reason: `${decision.reason} (under-lock)` };
428
557
  }
429
- if (incoming.sequence === lockedFloor.sequence) {
430
- const sameReleaseId = incoming.releaseId === lockedFloor.releaseId;
431
- const sameManifest = incoming.manifestDigest === lockedFloor.manifestDigest;
432
- const sameEpoch = incoming.keyringEpoch === lockedFloor.keyringEpoch;
433
- if (!sameReleaseId || !sameManifest || !sameEpoch) {
434
- return {
435
- accepted: false,
436
- reason: `same-sequence/different-tuple rejected (under-lock): sequence=${incoming.sequence}`
437
- };
438
- }
558
+ if (decision.decision === "idempotent") {
439
559
  return { accepted: true, wrote: false };
440
560
  }
441
561
  }
442
- fs.writeFileSync(tmpPath, JSON.stringify(incoming), "utf-8");
562
+ writeSecureFileSync(tmpPath, JSON.stringify(incoming));
443
563
  const tmpFd = fs.openSync(tmpPath, "r+");
444
564
  try {
445
565
  fs.fsyncSync(tmpFd);
@@ -950,7 +1070,7 @@ async function verifyBundleResponse(response, request, floorPath) {
950
1070
  if (freshnessTok["manifestDigest"] !== manifestDigest) {
951
1071
  return {
952
1072
  ok: false,
953
- reason: `freshnessTok.manifestDigest mismatch \u2014 token bound to a different manifest (GC.4d)`,
1073
+ reason: `freshnessTok.manifestDigest mismatch \u2014 token bound to a different manifest`,
954
1074
  nonSafe: true
955
1075
  };
956
1076
  }
@@ -1052,7 +1172,14 @@ async function verifyBundleResponse(response, request, floorPath) {
1052
1172
  };
1053
1173
  }
1054
1174
  const attestationEntry = KEYRING.find((e) => e.kid === attestation["kid"]);
1055
- const incomingKeyringEpoch = attestationEntry?.epoch ?? 1;
1175
+ if (!attestationEntry) {
1176
+ return {
1177
+ ok: false,
1178
+ reason: `attestation kid "${String(attestation["kid"])}" vanished from KEYRING after verification`,
1179
+ nonSafe: true
1180
+ };
1181
+ }
1182
+ const incomingKeyringEpoch = attestationEntry.epoch;
1056
1183
  const incomingTuple = {
1057
1184
  sequence: incomingSequence,
1058
1185
  releaseId: incomingReleaseId,
@@ -1183,7 +1310,7 @@ function compileDetectorRegex(source, flags = "") {
1183
1310
  }
1184
1311
 
1185
1312
  // src/core/redact.ts
1186
- import { createHash } from "crypto";
1313
+ import { createHash as createHash2 } from "crypto";
1187
1314
  function redactSecretValue(value) {
1188
1315
  if (value.length <= 8) return "***";
1189
1316
  return value.slice(0, 8) + "***";
@@ -1260,7 +1387,7 @@ function redactEvidence(evidence, category) {
1260
1387
  }
1261
1388
  function computeFindingKey(finding) {
1262
1389
  const basis = finding.evidence && finding.evidence.length > 0 ? finding.evidence : finding.title;
1263
- return createHash("sha256").update(basis).digest("hex").slice(0, 16);
1390
+ return createHash2("sha256").update(basis).digest("hex").slice(0, 16);
1264
1391
  }
1265
1392
  var FINDING_KEY_PROP = "_findingKey";
1266
1393
  function getFindingKey(finding) {
@@ -1432,7 +1559,7 @@ var SECRET_PATTERNS = [
1432
1559
  recommendation: "Remove from source code. Use process.env.RAZORPAY_KEY_SECRET and store in a gitignored .env file."
1433
1560
  },
1434
1561
  // JWT secret
1435
- // Task #81 gap 3 fix: the opening quote used to be MANDATORY (`['"]([^'"]{16,})`),
1562
+ // Free-tier secret gaps: the opening quote used to be MANDATORY (`['"]([^'"]{16,})`),
1436
1563
  // which only matches source-file assignment style (`const x = "value"`). A .env
1437
1564
  // file's `JWT_SECRET=value` line has no quotes at all, so this pattern never
1438
1565
  // matched .env content. Quotes are now optional on both sides, and the capture
@@ -1452,10 +1579,10 @@ var SECRET_PATTERNS = [
1452
1579
  recommendation: "Remove from source code. Generate a strong random secret, store it in environment variables."
1453
1580
  },
1454
1581
  // Supabase service-role key — current key format (2025+ rotation: sb_secret_...)
1455
- // Task #81 gap 2: the free tier had no Supabase-specific service-role pattern at
1582
+ // Free-tier secret gaps: the free tier had no Supabase-specific service-role pattern at
1456
1583
  // all — a variable literally named SERVICE_ROLE_KEY matched none of the generic
1457
1584
  // secret-name keywords (api_key/secret/token/password/auth_key/access_key) below,
1458
- // per the evidenced miss in apps/web/content/blog/supabase-rls-ai-built-apps.mdx.
1585
+ // per a miss seen on a real project.
1459
1586
  // This prefix match covers the current opaque key format; the legacy JWT format
1460
1587
  // (pre-2025 projects) is handled separately by checkSupabaseServiceRoleJwt below,
1461
1588
  // which decodes the payload rather than pattern-matching the shape.
@@ -1485,10 +1612,9 @@ var SECRET_PATTERNS = [
1485
1612
  // D.4 REWRITE: Removed native negative-lookahead (?!\s*\+|\.) — not supported by re2js.
1486
1613
  // Equivalent behavior is achieved via postExcludeFollowedBy() which checks the
1487
1614
  // character immediately after the closing quote. See DIFFERENTIAL NOTE above.
1488
- // Task #81 gap 3 fix: both quotes used to be MANDATORY (`['"](...)['"]`), which only
1615
+ // Free-tier secret gaps: both quotes used to be MANDATORY (`['"](...)['"]`), which only
1489
1616
  // matches source-file assignment style (`const x = "value"`) and never a .env file's
1490
- // unquoted `TOKEN=value` line — confirmed by the evidenced miss in
1491
- // apps/web/content/blog/github-secret-scanner-vs-cli-tools.md (INTERNAL_DEPLOY_TOKEN
1617
+ // unquoted `TOKEN=value` line — confirmed by a miss seen on a real project (INTERNAL_DEPLOY_TOKEN
1492
1618
  // caught when moved into config.ts, not when left in .env). Quotes are now optional;
1493
1619
  // the capture class already excludes whitespace and quote characters, so an unquoted
1494
1620
  // .env value still terminates correctly instead of over-capturing.
@@ -2193,11 +2319,10 @@ var MIGRATION_PATTERNS = [
2193
2319
  /^migrations\/.+\.sql$/i,
2194
2320
  /^db\/.+\.sql$/i,
2195
2321
  // Supabase CLI default layout (`supabase init` / `supabase migration new`) —
2196
- // task #81 gap 1: this was missing entirely, so every DEFAULT Supabase project's
2322
+ // free-tier secret gaps: this was missing entirely, so every DEFAULT Supabase project's
2197
2323
  // migrations silently skipped the destructive-migration checks below (DROP TABLE,
2198
- // TRUNCATE, DELETE FROM without WHERE, etc.). See
2199
- // apps/web/content/blog/supabase-rls-ai-built-apps.mdx for the evidenced repro:
2200
- // `supabase/migrations/0001_create_orders.sql` went unclassified and unscanned.
2324
+ // TRUNCATE, DELETE FROM without WHERE, etc.). A
2325
+ // real-world repro: `supabase/migrations/0001_create_orders.sql` went unclassified and unscanned.
2201
2326
  /^supabase\/migrations\/.+\.sql$/i,
2202
2327
  /^[^/]+\.sql$/i
2203
2328
  // root-level .sql files
@@ -3225,8 +3350,34 @@ function applySuppressions(findings, files) {
3225
3350
  return findings;
3226
3351
  }
3227
3352
 
3228
- // src/core/pro-scanner.ts
3353
+ // src/core/re2js-compile-cache.ts
3229
3354
  import { RE2JS as RE2JS2 } from "re2js";
3355
+ var COMPILE_CACHE_MAX = 2e4;
3356
+ var cache = /* @__PURE__ */ new Map();
3357
+ var INSTALLED = /* @__PURE__ */ Symbol.for("agenticcli.re2js.compileCache");
3358
+ function installRe2jsCompileCache() {
3359
+ const target = RE2JS2;
3360
+ if (target[INSTALLED]) return;
3361
+ const original = target.compile.bind(RE2JS2);
3362
+ target.compile = (pattern, flags = 0) => {
3363
+ const key = `${flags}\0${pattern}`;
3364
+ const hit = cache.get(key);
3365
+ if (hit !== void 0) return hit;
3366
+ const compiled = original(pattern, flags);
3367
+ if (cache.size >= COMPILE_CACHE_MAX) cache.clear();
3368
+ cache.set(key, compiled);
3369
+ return compiled;
3370
+ };
3371
+ target[INSTALLED] = true;
3372
+ }
3373
+ function compileCached(pattern, flags) {
3374
+ installRe2jsCompileCache();
3375
+ return RE2JS2.compile(pattern, flags);
3376
+ }
3377
+
3378
+ // src/core/pro-scanner.ts
3379
+ import { RE2JS as RE2JS3 } from "re2js";
3380
+ installRe2jsCompileCache();
3230
3381
  var activeExecutor = re2jsV1Executor;
3231
3382
  var DEFAULT_FLOOR_PATH = path2.join(os.homedir(), ".shipguard", "release-floor.json");
3232
3383
  var NoRulesAppliedError = class extends Error {
@@ -3238,7 +3389,7 @@ var NoRulesAppliedError = class extends Error {
3238
3389
  };
3239
3390
  var ProFetchError = class extends Error {
3240
3391
  code;
3241
- /** Only populated for RATE_LIMITED, when the server sends a `Retry-After` header. */
3392
+ /** Only populated for RATE_LIMITED and PLATFORM_UNAVAILABLE, when the server sends a usable `Retry-After` header. */
3242
3393
  retryAfterSeconds;
3243
3394
  constructor(code, message, opts) {
3244
3395
  super(message);
@@ -3247,9 +3398,23 @@ var ProFetchError = class extends Error {
3247
3398
  this.retryAfterSeconds = opts?.retryAfterSeconds;
3248
3399
  }
3249
3400
  };
3401
+ function parseCreditsRemaining(headers) {
3402
+ const raw = headers.get("X-Credits-Remaining");
3403
+ if (raw === null || raw.trim() === "") return void 0;
3404
+ const credits = Number(raw.trim());
3405
+ return Number.isFinite(credits) ? credits : void 0;
3406
+ }
3250
3407
  async function fetchProRules(frameworks, categories, apiUrl, scanId, floorPath) {
3251
3408
  assertTrustedApiUrl(apiUrl);
3252
- const token = await getAuthToken(apiUrl);
3409
+ let token;
3410
+ try {
3411
+ token = await getAuthToken(apiUrl);
3412
+ } catch (err) {
3413
+ if (err instanceof PlatformUnavailableError) {
3414
+ throw new ProFetchError("PLATFORM_UNAVAILABLE", err.message, { retryAfterSeconds: err.retryAfterSeconds });
3415
+ }
3416
+ throw err;
3417
+ }
3253
3418
  if (!token) throw new ProFetchError("AUTH_FAILED", "Not authenticated. Run `shipguard login` first.");
3254
3419
  let res;
3255
3420
  try {
@@ -3282,15 +3447,20 @@ async function fetchProRules(frameworks, categories, apiUrl, scanId, floorPath)
3282
3447
  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)."
3283
3448
  );
3284
3449
  }
3450
+ if (isPlatformUnavailable(res, errorBody)) {
3451
+ throw new ProFetchError(
3452
+ "PLATFORM_UNAVAILABLE",
3453
+ errorBody?.error ?? PLATFORM_UNAVAILABLE_DEFAULT_MESSAGE,
3454
+ { retryAfterSeconds: parseRetryAfterSeconds(res.headers) }
3455
+ );
3456
+ }
3285
3457
  if (res.status === 401) throw new ProFetchError("AUTH_FAILED", "Auth expired. Run `shipguard login` again.");
3286
- if (res.status === 402) throw new ProFetchError("INSUFFICIENT_CREDITS", "No credits. Buy at https://agenticcli.dev/dashboard/billing");
3458
+ if (res.status === 402) throw new ProFetchError("INSUFFICIENT_CREDITS", `No credits. Buy at ${goLink("billing")}`);
3287
3459
  if (res.status === 429) {
3288
- const retryAfterHeader = res.headers.get("Retry-After");
3289
- const retryAfterSeconds = retryAfterHeader ? parseInt(retryAfterHeader, 10) : void 0;
3290
3460
  throw new ProFetchError(
3291
3461
  "RATE_LIMITED",
3292
3462
  `Rate limited (429): too many pro rule fetches.`,
3293
- { retryAfterSeconds: Number.isFinite(retryAfterSeconds) ? retryAfterSeconds : void 0 }
3463
+ { retryAfterSeconds: parseRetryAfterSeconds(res.headers) }
3294
3464
  );
3295
3465
  }
3296
3466
  if (res.status === 409) throw new ProFetchError("SERVER_ERROR", `Rule fetch conflict (409): ${res.statusText}`);
@@ -3306,12 +3476,12 @@ async function fetchProRules(frameworks, categories, apiUrl, scanId, floorPath)
3306
3476
  if (res.status >= 500) throw new ProFetchError("SERVER_ERROR", `Rule fetch failed (${res.status}): ${res.statusText}`);
3307
3477
  throw new ProFetchError("SERVER_ERROR", `Rule fetch failed: ${res.statusText}`);
3308
3478
  }
3309
- const credits = parseInt(res.headers.get("X-Credits-Remaining") ?? "0", 10);
3479
+ const credits = parseCreditsRemaining(res.headers);
3310
3480
  const rulesVersion = res.headers.get("X-Rules-Version") ?? void 0;
3311
3481
  const rawText = await res.text();
3312
3482
  let responseJson;
3313
3483
  try {
3314
- const { parseStrictNoDup: parseStrict } = await import("./dist-3SW45O4F.js");
3484
+ const { parseStrictNoDup: parseStrict } = await import("./dist-YSE6YNXH.js");
3315
3485
  responseJson = parseStrict(rawText);
3316
3486
  } catch (parseErr) {
3317
3487
  const msg = parseErr instanceof Error ? parseErr.message : String(parseErr);
@@ -3351,10 +3521,10 @@ async function fetchProRules(frameworks, categories, apiUrl, scanId, floorPath)
3351
3521
  explanation: r.title,
3352
3522
  recommendation: "",
3353
3523
  action,
3354
- // Task #16 (hardcoded-confidence fix): carry the rule's REAL signed confidence.
3524
+ // Per-rule confidence (hardcoded-confidence fix): carry the rule's REAL signed confidence.
3355
3525
  // verifyBundleResponse has already fail-closed if any rule lacks confidence, so
3356
3526
  // r.confidence is guaranteed present here — never a silent HIGH default. Corpus
3357
- // governance (rule-corpus/rule-logic.md §4) calibrates action to this value, and
3527
+ // governance calibrates action to this value, and
3358
3528
  // deriveBlocking() + CLI output/JSON depend on it being the author's signed intent.
3359
3529
  confidence: r.confidence,
3360
3530
  matcher: {
@@ -3364,7 +3534,7 @@ async function fetchProRules(frameworks, categories, apiUrl, scanId, floorPath)
3364
3534
  patterns: r.pattern ? [r.pattern] : [],
3365
3535
  antiPatterns: r.antiPattern ? [r.antiPattern] : [],
3366
3536
  flags: r.flags,
3367
- // FIX 1 (CRITICAL): antiPatternScope and boundary are now part of the 20-field
3537
+ // antiPatternScope and boundary are now part of the 20-field
3368
3538
  // hash preimage (contract 0.5.0) and ARE delivered on the wire ExecutableRule.
3369
3539
  // They were missing from this mapping, causing runProRules to always default to
3370
3540
  // antiPatternScope:'statement' / boundary:'none' — ignoring the corpus values.
@@ -3392,14 +3562,14 @@ async function fetchProRules(frameworks, categories, apiUrl, scanId, floorPath)
3392
3562
  }
3393
3563
  throw new ProFetchError(
3394
3564
  "BUNDLE_INVALID",
3395
- "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."
3565
+ "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."
3396
3566
  );
3397
3567
  }
3398
3568
  function toRe2jsFlags2(flags) {
3399
3569
  let bits = 0;
3400
- if (flags.has("i")) bits |= RE2JS2.CASE_INSENSITIVE;
3401
- if (flags.has("m")) bits |= RE2JS2.MULTILINE;
3402
- if (flags.has("s")) bits |= RE2JS2.DOTALL;
3570
+ if (flags.has("i")) bits |= RE2JS3.CASE_INSENSITIVE;
3571
+ if (flags.has("m")) bits |= RE2JS3.MULTILINE;
3572
+ if (flags.has("s")) bits |= RE2JS3.DOTALL;
3403
3573
  return bits;
3404
3574
  }
3405
3575
  function validateBundleCompile(rules) {
@@ -3431,7 +3601,7 @@ function validateBundleCompile(rules) {
3431
3601
  const msg = err instanceof Error ? err.message : String(err);
3432
3602
  return {
3433
3603
  ok: false,
3434
- 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).`
3604
+ 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).`
3435
3605
  };
3436
3606
  }
3437
3607
  }
@@ -3486,7 +3656,7 @@ function runProRules(rules, files, _policy) {
3486
3656
  patterns: rule.matcher.patterns,
3487
3657
  antiPatterns: rule.matcher.antiPatterns,
3488
3658
  flags: rule.matcher.flags ?? "",
3489
- // FIX 1+2: pass through delivered values; executor defaults to 'none'/'statement'.
3659
+ // pass through delivered values; executor defaults to 'none'/'statement'.
3490
3660
  ...boundary !== void 0 && { boundary },
3491
3661
  ...antiPatternScope !== void 0 && { antiPatternScope }
3492
3662
  };
@@ -3555,7 +3725,7 @@ function runProRules(rules, files, _policy) {
3555
3725
  recommendation: rule.recommendation,
3556
3726
  blocking: isSuppressed ? false : deriveBlocking(rule),
3557
3727
  suppressed: isSuppressed,
3558
- // New fields from contract integration (Task A-CLI-INT.2)
3728
+ // New fields from contract integration
3559
3729
  suppressionState: isSuppressed ? "suppressed" : "active",
3560
3730
  matcherType: cf.matcherType,
3561
3731
  // releaseId: 'pre-attestation' — not set on Finding until Phase C wires
@@ -3612,6 +3782,7 @@ function runProRulesWithDispatch(rules, files, policy, cliVersion, table, manife
3612
3782
  }
3613
3783
 
3614
3784
  export {
3785
+ goLink,
3615
3786
  logger,
3616
3787
  getFindingKey,
3617
3788
  redactFindingsEvidence,
@@ -3621,6 +3792,8 @@ export {
3621
3792
  payments,
3622
3793
  deploymentCheck,
3623
3794
  assertTrustedApiUrl,
3795
+ ensureSecureDir,
3796
+ writeSecureFileSync,
3624
3797
  loadCredentials,
3625
3798
  saveCredentials,
3626
3799
  clearCredentials,