@agenticcli/shipguard 0.5.1 → 0.7.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,13 +2,14 @@ import {
2
2
  EXEC_RULE_FIELDS,
3
3
  RE2JS_V1_RUNTIME_ID,
4
4
  canonicalJson,
5
+ compileCached,
5
6
  computeExecutableHash,
6
7
  parseFlags,
7
8
  parseStrictNoDup,
8
9
  re2jsV1Executor,
9
10
  selectExpected,
10
11
  verifyExactSet
11
- } from "./chunk-5T42QTNT.js";
12
+ } from "./chunk-MPQ42F54.js";
12
13
 
13
14
  // src/core/pro-scanner.ts
14
15
  import * as path2 from "path";
@@ -43,6 +44,13 @@ function assertTrustedApiUrl(url) {
43
44
  );
44
45
  }
45
46
  const hostname = parsed.hostname.toLowerCase();
47
+ const scheme = parsed.protocol.toLowerCase();
48
+ const isLoopback = hostname === "localhost" || hostname === "127.0.0.1" || hostname === "[::1]";
49
+ if (scheme !== "https:" && !(isLoopback && scheme === "http:")) {
50
+ throw new Error(
51
+ `[shipguard] Untrusted API URL "${url}" \u2014 scheme "${scheme.replace(":", "")}" is not permitted. A Bearer token must never travel over a plaintext or non-HTTP transport. Use https:// (http:// is allowed only for localhost and 127.0.0.1).`
52
+ );
53
+ }
46
54
  if (BUILT_IN_TRUSTED.has(hostname)) return;
47
55
  const extra = (process.env.SHIPGUARD_EXTRA_HOSTS ?? "").split(",").map((h) => h.trim().toLowerCase()).filter(Boolean);
48
56
  if (extra.includes(hostname)) return;
@@ -185,7 +193,14 @@ async function getAuthToken(apiUrl) {
185
193
  });
186
194
  return access_token;
187
195
  }
188
- } catch {
196
+ console.error(
197
+ `[shipguard] Token refresh refused by ${creds.apiUrl} (HTTP ${res.status} ${res.statusText}) \u2014 you will be asked to log in again.`
198
+ );
199
+ } catch (err) {
200
+ const detail = err instanceof Error ? err.message : String(err);
201
+ console.error(
202
+ `[shipguard] Token refresh failed \u2014 you will be asked to log in again. Reason: ${detail}`
203
+ );
189
204
  }
190
205
  }
191
206
  return null;
@@ -1167,11 +1182,135 @@ function compileDetectorRegex(source, flags = "") {
1167
1182
  };
1168
1183
  }
1169
1184
 
1170
- // src/checks/secrets.ts
1171
- function redact(value) {
1185
+ // src/core/redact.ts
1186
+ import { createHash } from "crypto";
1187
+ function redactSecretValue(value) {
1172
1188
  if (value.length <= 8) return "***";
1173
1189
  return value.slice(0, 8) + "***";
1174
1190
  }
1191
+ var NON_SECRET_EVIDENCE_RE = compileDetectorRegex(
1192
+ `^(?:-----BEGIN [A-Z ]{0,30}PRIVATE KEY-----|"type"\\s*:\\s*"service_account")$`
1193
+ );
1194
+ var URL_CREDENTIAL_RE = compileDetectorRegex(
1195
+ `(://[^\\s:/@'"]*:)([^\\s'"]+)(@[^\\s@'"/]+)`
1196
+ );
1197
+ var TOKEN_SHAPE_RE = compileDetectorRegex(
1198
+ "((?:rk|sk)_(?:live|test)_[A-Za-z0-9]{10,}|whsec_[A-Za-z0-9]{20,}|sk-[A-Za-z0-9_-]{20,}|(?:AKIA|ASIA|AGPA|AIDA|AROA|AIPA|ANPA|ANVA)[A-Z0-9]{16}|(?:ghp|gho|ghu|ghs|ghr)_[A-Za-z0-9]{20,}|github_pat_[A-Za-z0-9_]{20,}|glpat-[A-Za-z0-9_-]{20,}|xox[bpoas]-[0-9A-Za-z-]{10,}|xapp-[0-9A-Za-z-]{20,}|hf_[A-Za-z0-9]{30,}|npm_[A-Za-z0-9]{30,}|SG\\.[A-Za-z0-9_-]{16,}\\.[A-Za-z0-9_-]{16,}|AIza[0-9A-Za-z_-]{35}|sb_secret_[A-Za-z0-9_-]{20,}|eyJ[A-Za-z0-9_-]{10,}\\.eyJ[A-Za-z0-9_-]{10,}\\.[A-Za-z0-9_-]{10,})"
1199
+ );
1200
+ var SECRET_ASSIGNMENT_RE = compileDetectorRegex(
1201
+ `((?:api[_-]?key|secret|token|pass|passw(?:or)?d|pwd|credentials?|auth[_-]?key|access[_-]?key|private[_-]?key)[A-Za-z0-9_]{0,40}['"]?\\s*[=:]\\s*)("[^"]{4,}"|'[^']{4,}'|[^\\s'",;]{6,})`,
1202
+ "i"
1203
+ );
1204
+ var AUTH_ASSIGNMENT_RE = compileDetectorRegex(
1205
+ `(\\bauth(?:orization)?['"]?\\s*[=:]\\s*)("[^"]{4,}"|'[^']{4,}'|[^\\s'",;]{6,})`,
1206
+ "i"
1207
+ );
1208
+ var BEARER_RE = compileDetectorRegex(`(\\bBearer\\s+)([A-Za-z0-9._~+/=*-]{8,})`, "i");
1209
+ var BASIC_RE = compileDetectorRegex(`(\\bBasic\\s+)([A-Za-z0-9+/=]{16,})`, "i");
1210
+ var MYSQL_P_FLAG_RE = compileDetectorRegex(`(\\s-p)(\\S{6,})`);
1211
+ var CLI_FLAG_SECRET_RE = compileDetectorRegex(
1212
+ `(\\s--?(?:[A-Za-z0-9]+[-_])*(?:password|passwd|pass|pwd|token|api[-_]?key|secret|access[-_]?key)(?:\\s+|=))([^\\s'"]{6,})`,
1213
+ "i"
1214
+ );
1215
+ var CURL_USER_RE = compileDetectorRegex(`(\\s(?:-u|--user)[\\s=]*[^\\s:]+:)(\\S+)`);
1216
+ var SQL_PASSWORD_RE = compileDetectorRegex(
1217
+ `((?:password|identified\\s+by)\\s+(?:=\\s*)?['"])([^'"]+)`,
1218
+ "i"
1219
+ );
1220
+ function replaceGroup(text, re, groupIndex, mask) {
1221
+ let out = "";
1222
+ let cursor = 0;
1223
+ for (const m of re.matchAll(text)) {
1224
+ const groups = m.groups.map((g) => g ?? "");
1225
+ const offsetInMatch = groups.slice(0, groupIndex).reduce((n, g) => n + g.length, 0);
1226
+ const start = m.index + offsetInMatch;
1227
+ const value = groups[groupIndex];
1228
+ out += text.slice(cursor, start) + mask(value);
1229
+ cursor = start + value.length;
1230
+ }
1231
+ return out + text.slice(cursor);
1232
+ }
1233
+ function maskAssignedValue(value) {
1234
+ if (/^(bearer|basic|token)$/i.test(value)) return value;
1235
+ const q = value[0];
1236
+ if ((q === '"' || q === "'") && value.length >= 2 && value.endsWith(q)) {
1237
+ return q + redactSecretValue(value.slice(1, -1)) + q;
1238
+ }
1239
+ return redactSecretValue(value);
1240
+ }
1241
+ function scrubSecretShapes(text) {
1242
+ let out = replaceGroup(text, URL_CREDENTIAL_RE, 1, () => "***");
1243
+ out = replaceGroup(out, TOKEN_SHAPE_RE, 0, redactSecretValue);
1244
+ out = replaceGroup(out, BEARER_RE, 1, redactSecretValue);
1245
+ out = replaceGroup(out, BASIC_RE, 1, redactSecretValue);
1246
+ out = replaceGroup(out, MYSQL_P_FLAG_RE, 1, redactSecretValue);
1247
+ out = replaceGroup(out, CLI_FLAG_SECRET_RE, 1, redactSecretValue);
1248
+ out = replaceGroup(out, CURL_USER_RE, 1, () => "***");
1249
+ out = replaceGroup(out, SQL_PASSWORD_RE, 1, redactSecretValue);
1250
+ out = replaceGroup(out, SECRET_ASSIGNMENT_RE, 1, maskAssignedValue);
1251
+ return replaceGroup(out, AUTH_ASSIGNMENT_RE, 1, maskAssignedValue);
1252
+ }
1253
+ function redactEvidence(evidence, category) {
1254
+ if (category === "secrets") {
1255
+ const trimmed = evidence.trim();
1256
+ if (NON_SECRET_EVIDENCE_RE.test(trimmed)) return evidence;
1257
+ return `...${redactSecretValue(trimmed)}...`;
1258
+ }
1259
+ return scrubSecretShapes(evidence);
1260
+ }
1261
+ function computeFindingKey(finding) {
1262
+ const basis = finding.evidence && finding.evidence.length > 0 ? finding.evidence : finding.title;
1263
+ return createHash("sha256").update(basis).digest("hex").slice(0, 16);
1264
+ }
1265
+ var FINDING_KEY_PROP = "_findingKey";
1266
+ function getFindingKey(finding) {
1267
+ const stamped = finding[FINDING_KEY_PROP];
1268
+ return typeof stamped === "string" ? stamped : computeFindingKey(finding);
1269
+ }
1270
+ function redactFindingsEvidence(findings, alreadyRedacted = /* @__PURE__ */ new Set()) {
1271
+ for (const f of findings) {
1272
+ Object.defineProperty(f, FINDING_KEY_PROP, {
1273
+ value: computeFindingKey(f),
1274
+ enumerable: false,
1275
+ writable: true,
1276
+ configurable: true
1277
+ });
1278
+ if (typeof f.evidence !== "string" || f.evidence.length === 0) continue;
1279
+ if (alreadyRedacted.has(f)) continue;
1280
+ f.evidence = redactEvidence(f.evidence, f.category);
1281
+ }
1282
+ return findings;
1283
+ }
1284
+
1285
+ // src/checks/secrets.ts
1286
+ var SECRET_SEVERITY_RANK = { critical: 4, high: 3, medium: 2, low: 1, info: 0 };
1287
+ var SecretDedupe = class {
1288
+ byLine = /* @__PURE__ */ new Map();
1289
+ /** Returns true when the finding was folded into an existing one (do not push it). */
1290
+ fold(findings, lineIdx, start, value, candidate) {
1291
+ const end = start + value.length;
1292
+ let spans = this.byLine.get(lineIdx);
1293
+ if (!spans) {
1294
+ spans = [];
1295
+ this.byLine.set(lineIdx, spans);
1296
+ }
1297
+ const hit = spans.find((sp) => start < sp.end && sp.start < end || sp.value === value);
1298
+ if (!hit) {
1299
+ spans.push({ start, end, value, idx: findings.length });
1300
+ return false;
1301
+ }
1302
+ if ((SECRET_SEVERITY_RANK[candidate.severity] ?? 0) > (SECRET_SEVERITY_RANK[findings[hit.idx].severity] ?? 0)) {
1303
+ findings[hit.idx] = candidate;
1304
+ }
1305
+ hit.start = Math.min(hit.start, start);
1306
+ hit.end = Math.max(hit.end, end);
1307
+ return true;
1308
+ }
1309
+ };
1310
+ function secretStart(lineMatch, secretValue) {
1311
+ const off = lineMatch.match.indexOf(secretValue);
1312
+ return lineMatch.index + (off >= 0 ? off : 0);
1313
+ }
1175
1314
  var SAFE_EXCLUSIONS_RE = compileDetectorRegex(`\\.(example|sample|template|dist|tmpl|test)$`, "i");
1176
1315
  var FRONTEND_PATH_RE = compileDetectorRegex(`^(app|pages|components|src\\/(app|pages|components))\\/`);
1177
1316
  function isDotEnvFile(relativePath) {
@@ -1293,11 +1432,18 @@ var SECRET_PATTERNS = [
1293
1432
  recommendation: "Remove from source code. Use process.env.RAZORPAY_KEY_SECRET and store in a gitignored .env file."
1294
1433
  },
1295
1434
  // JWT secret
1435
+ // Task #81 gap 3 fix: the opening quote used to be MANDATORY (`['"]([^'"]{16,})`),
1436
+ // which only matches source-file assignment style (`const x = "value"`). A .env
1437
+ // file's `JWT_SECRET=value` line has no quotes at all, so this pattern never
1438
+ // matched .env content. Quotes are now optional on both sides, and the capture
1439
+ // class excludes whitespace/quotes/`#` (env comment marker) so an unquoted value
1440
+ // still terminates correctly at end-of-value instead of swallowing trailing
1441
+ // content. Quoted-value behavior (source files) is unchanged.
1296
1442
  {
1297
1443
  id: "hardcoded_secret",
1298
1444
  name: "JWT Secret",
1299
1445
  compiled: compileDetectorRegex(
1300
- `(?:jwt[_\\-]?secret|JWT_SECRET)\\s*[=:]\\s*['"]([^'"]{16,})['"]?`,
1446
+ `(?:jwt[_\\-]?secret|JWT_SECRET)\\s*[=:]\\s*['"]?([^\\s'"#]{16,})['"]?`,
1301
1447
  "im"
1302
1448
  ),
1303
1449
  severity: "high",
@@ -1305,6 +1451,23 @@ var SECRET_PATTERNS = [
1305
1451
  explanation: "Hardcoded JWT secret detected. Exposing this allows attackers to forge valid JWT tokens and bypass authentication.",
1306
1452
  recommendation: "Remove from source code. Generate a strong random secret, store it in environment variables."
1307
1453
  },
1454
+ // 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
1456
+ // all — a variable literally named SERVICE_ROLE_KEY matched none of the generic
1457
+ // 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.
1459
+ // This prefix match covers the current opaque key format; the legacy JWT format
1460
+ // (pre-2025 projects) is handled separately by checkSupabaseServiceRoleJwt below,
1461
+ // which decodes the payload rather than pattern-matching the shape.
1462
+ {
1463
+ id: "hardcoded_secret",
1464
+ name: "Supabase Service-Role Key",
1465
+ compiled: compileDetectorRegex(`['"]?(sb_secret_[a-zA-Z0-9_\\-]{20,})['"]?`, "m"),
1466
+ severity: "critical",
1467
+ confidence: "HIGH",
1468
+ explanation: "Hardcoded Supabase service-role key detected (current sb_secret_ key format). This key bypasses Row Level Security entirely and grants full read/write access to every table.",
1469
+ recommendation: "Remove from source code and any .env file committed to git. Use process.env.SUPABASE_SERVICE_ROLE_KEY server-side only \u2014 never a NEXT_PUBLIC_/VITE_/EXPO_PUBLIC_-prefixed variable. Rotate the key in the Supabase dashboard (Project Settings \u2192 API)."
1470
+ },
1308
1471
  // Database URL with embedded credentials
1309
1472
  {
1310
1473
  id: "hardcoded_secret",
@@ -1322,11 +1485,18 @@ var SECRET_PATTERNS = [
1322
1485
  // D.4 REWRITE: Removed native negative-lookahead (?!\s*\+|\.) — not supported by re2js.
1323
1486
  // Equivalent behavior is achieved via postExcludeFollowedBy() which checks the
1324
1487
  // character immediately after the closing quote. See DIFFERENTIAL NOTE above.
1488
+ // Task #81 gap 3 fix: both quotes used to be MANDATORY (`['"](...)['"]`), which only
1489
+ // 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
1492
+ // caught when moved into config.ts, not when left in .env). Quotes are now optional;
1493
+ // the capture class already excludes whitespace and quote characters, so an unquoted
1494
+ // .env value still terminates correctly instead of over-capturing.
1325
1495
  {
1326
1496
  id: "hardcoded_secret",
1327
1497
  name: "High-Entropy Secret String",
1328
1498
  compiled: compileDetectorRegex(
1329
- `(?:api[_\\-]?key|secret|token|password|passwd|auth[_\\-]?key|access[_\\-]?key)\\s*[=:]\\s*['"]([a-zA-Z0-9\\/+_\\-]{32,64})['"]`,
1499
+ `(?:api[_\\-]?key|secret|token|password|passwd|auth[_\\-]?key|access[_\\-]?key)\\s*[=:]\\s*['"]?([a-zA-Z0-9\\/+_\\-]{32,64})['"]?`,
1330
1500
  "im"
1331
1501
  ),
1332
1502
  severity: "medium",
@@ -1370,6 +1540,56 @@ var NEXT_PUBLIC_SECRET_RE = compileDetectorRegex(
1370
1540
  var ENV_REFERENCE_ONLY_RE = compileDetectorRegex(`process\\.env\\.[A-Z_]+`);
1371
1541
  var LITERAL_ASSIGN_RE = compileDetectorRegex(`=\\s*['"]`);
1372
1542
  var LINE_COMMENT_RE = compileDetectorRegex(`^\\s*(\\/\\/|#)`, "m");
1543
+ var JWT_SHAPE_RE = compileDetectorRegex(
1544
+ `(eyJ[A-Za-z0-9_\\-]{5,})\\.(eyJ[A-Za-z0-9_\\-]{5,})\\.([A-Za-z0-9_\\-]{10,})`
1545
+ );
1546
+ function base64UrlDecodeJwtSegment(segment) {
1547
+ try {
1548
+ const decoded = Buffer.from(segment, "base64url").toString("utf8");
1549
+ return decoded.length > 0 ? decoded : null;
1550
+ } catch {
1551
+ return null;
1552
+ }
1553
+ }
1554
+ function extractJwtRoleClaim(payloadSegment) {
1555
+ const decoded = base64UrlDecodeJwtSegment(payloadSegment);
1556
+ if (decoded === null) return null;
1557
+ try {
1558
+ const parsed = JSON.parse(decoded);
1559
+ return typeof parsed["role"] === "string" ? parsed["role"] : null;
1560
+ } catch {
1561
+ return null;
1562
+ }
1563
+ }
1564
+ function checkSupabaseServiceRoleJwt(file, findings, policy, dedupe) {
1565
+ const { content, relativePath } = file;
1566
+ const lines = content.split("\n");
1567
+ for (let i = 0; i < lines.length; i++) {
1568
+ const line = lines[i];
1569
+ if (LINE_COMMENT_RE.test(line)) continue;
1570
+ for (const m of JWT_SHAPE_RE.matchAll(line)) {
1571
+ const payloadSegment = m.groups[1];
1572
+ if (!payloadSegment) continue;
1573
+ const role = extractJwtRoleClaim(payloadSegment);
1574
+ if (role !== "service_role") continue;
1575
+ const id = "hardcoded_secret";
1576
+ const jwtFinding = {
1577
+ id,
1578
+ title: "Supabase Service-Role Key (legacy JWT format)",
1579
+ severity: "critical",
1580
+ category: "secrets",
1581
+ file: relativePath,
1582
+ line: i + 1,
1583
+ evidence: `...${redactSecretValue(m.match)}...`,
1584
+ confidence: "HIGH",
1585
+ explanation: 'A legacy-format Supabase service-role key was found \u2014 a JWT whose decoded payload contains "role":"service_role". This key bypasses Row Level Security entirely and grants full read/write access to every table, regardless of any RLS policy.',
1586
+ recommendation: "Remove immediately, including from any .env file. Never reference it from a NEXT_PUBLIC_/VITE_/EXPO_PUBLIC_-prefixed variable or client-side code. Use it only in server-only code via process.env.SUPABASE_SERVICE_ROLE_KEY, and rotate it in the Supabase dashboard (Project Settings \u2192 API) since any repo exposure must be treated as compromised.",
1587
+ blocking: policy.block.includes(id)
1588
+ };
1589
+ if (!dedupe.fold(findings, i, m.index, m.match, jwtFinding)) findings.push(jwtFinding);
1590
+ }
1591
+ }
1592
+ }
1373
1593
  function checkSecrets(files, policy) {
1374
1594
  const findings = [];
1375
1595
  for (const file of files) {
@@ -1406,7 +1626,8 @@ function checkSecrets(files, policy) {
1406
1626
  blocking: policy.block.includes(id)
1407
1627
  });
1408
1628
  }
1409
- if (isFrontendFile(relativePath)) {
1629
+ const isEnvFileForNextPublicCheck = isDotEnvFile(relativePath);
1630
+ if (isFrontendFile(relativePath) || isEnvFileForNextPublicCheck) {
1410
1631
  const lines2 = content.split("\n");
1411
1632
  for (let i = 0; i < lines2.length; i++) {
1412
1633
  const line = lines2[i];
@@ -1420,15 +1641,17 @@ function checkSecrets(files, policy) {
1420
1641
  category: "secrets",
1421
1642
  file: relativePath,
1422
1643
  line: i + 1,
1423
- evidence: `${line.split("=")[0].trim()}=${redact(match.groups[0])}`,
1644
+ evidence: `${line.split("=")[0].trim()}=${redactSecretValue(match.groups[0])}`,
1424
1645
  confidence: "HIGH",
1425
- explanation: "An environment variable with NEXT_PUBLIC_ prefix containing a secret-sounding name is used in a frontend file. NEXT_PUBLIC_ variables are bundled into client-side JavaScript and exposed to all users.",
1646
+ explanation: "An environment variable with NEXT_PUBLIC_ prefix containing a secret-sounding name is declared " + (isEnvFileForNextPublicCheck ? "in a .env file. NEXT_PUBLIC_ variables are bundled into client-side JavaScript and exposed to all users regardless of which file declares them." : "in a frontend file. NEXT_PUBLIC_ variables are bundled into client-side JavaScript and exposed to all users."),
1426
1647
  recommendation: "Move secret API calls to a server-side route (e.g., Next.js API route or Server Action). Never use NEXT_PUBLIC_ for keys, tokens, or secrets.",
1427
1648
  blocking: policy.block.includes(id)
1428
1649
  });
1429
1650
  }
1430
1651
  }
1431
1652
  }
1653
+ const secretDedupe = new SecretDedupe();
1654
+ checkSupabaseServiceRoleJwt(file, findings, policy, secretDedupe);
1432
1655
  const lines = content.split("\n");
1433
1656
  for (const pattern of SECRET_PATTERNS) {
1434
1657
  if (!pattern.compiled.test(content)) continue;
@@ -1444,19 +1667,22 @@ function checkSecrets(files, policy) {
1444
1667
  if (pattern.postExcludeFollowedBy(restAfterMatch)) continue;
1445
1668
  }
1446
1669
  const secretValue = lineMatch.groups[0] ?? lineMatch.match;
1447
- findings.push({
1670
+ const secretFinding = {
1448
1671
  id: pattern.id,
1449
1672
  title: pattern.name,
1450
1673
  severity: pattern.severity,
1451
1674
  category: "secrets",
1452
1675
  file: relativePath,
1453
1676
  line: i + 1,
1454
- evidence: `...${redact(secretValue)}...`,
1677
+ evidence: `...${redactSecretValue(secretValue)}...`,
1455
1678
  confidence: pattern.confidence,
1456
1679
  explanation: pattern.explanation,
1457
1680
  recommendation: pattern.recommendation,
1458
1681
  blocking: policy.block.includes(pattern.id)
1459
- });
1682
+ };
1683
+ if (!secretDedupe.fold(findings, i, secretStart(lineMatch, secretValue), secretValue, secretFinding)) {
1684
+ findings.push(secretFinding);
1685
+ }
1460
1686
  }
1461
1687
  }
1462
1688
  }
@@ -1476,6 +1702,13 @@ var logger = {
1476
1702
  success: (msg) => console.error(chalk.green("\u2713"), msg),
1477
1703
  warn: (msg) => console.error(chalk.yellow("\u26A0"), msg),
1478
1704
  error: (msg) => console.error(chalk.red("\u2717"), msg),
1705
+ // Diagnostics that are true and worth being able to inspect, but too detailed for a
1706
+ // normal run — e.g. "this legacy finding was superseded by a governed corpus rule on
1707
+ // the same line". Deliberately NOT a silent drop: the information is always produced
1708
+ // and one env var makes it visible. Stderr only, like every other logger method.
1709
+ debug: (msg) => {
1710
+ if (process.env.SHIPGUARD_DEBUG) console.error(chalk.gray("\xB7"), msg);
1711
+ },
1479
1712
  finding: (severity, msg) => {
1480
1713
  const colors = {
1481
1714
  critical: chalk.bgRed.white,
@@ -1500,9 +1733,9 @@ var logger = {
1500
1733
  };
1501
1734
 
1502
1735
  // src/checks/auth.ts
1503
- var SENSITIVE_NEXTJS_PAGE_PATTERN = /^(?:src\/)?app\/(admin|dashboard|billing|account|settings|management)(\/|$)/;
1504
- var SENSITIVE_API_ROUTE_PATTERN = /^(?:src\/)?app\/api\/(admin|users|billing|account|management)(\/|$)/;
1505
- var SENSITIVE_EXPRESS_PATHS = /\/(admin|users|billing|account|management)(\/|$)/;
1736
+ var SENSITIVE_NEXTJS_PAGE_PATTERN = /^(?:src\/)?app\/(admin|dashboard|billing|account|settings|management|debug|internal)(\/|$)/;
1737
+ var SENSITIVE_API_ROUTE_PATTERN = /^(?:src\/)?app\/api\/(admin|users|billing|account|management|debug|internal|env|_debug)(\/|$)/;
1738
+ var SENSITIVE_EXPRESS_PATHS = /\/(admin|users|billing|account|management|debug|internal|env|_debug|dev)(\/|$)/;
1506
1739
  var WEBHOOK_PATH_PATTERN = /\/webhooks?\//;
1507
1740
  var RE2_EXPRESS_ROUTE_DEFINITION = compileDetectorRegex(
1508
1741
  `(?:router|app)\\.(get|post|put|patch|delete|all)\\s*\\(\\s*['"\`]([^'"\`,)]+)['"\`]`,
@@ -1959,6 +2192,13 @@ var MIGRATION_PATTERNS = [
1959
2192
  /^drizzle\/.+\.sql$/i,
1960
2193
  /^migrations\/.+\.sql$/i,
1961
2194
  /^db\/.+\.sql$/i,
2195
+ // Supabase CLI default layout (`supabase init` / `supabase migration new`) —
2196
+ // task #81 gap 1: this was missing entirely, so every DEFAULT Supabase project's
2197
+ // 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.
2201
+ /^supabase\/migrations\/.+\.sql$/i,
1962
2202
  /^[^/]+\.sql$/i
1963
2203
  // root-level .sql files
1964
2204
  ];
@@ -2170,7 +2410,7 @@ var databaseCheck = {
2170
2410
  };
2171
2411
 
2172
2412
  // src/checks/deployment.ts
2173
- import { basename } from "path";
2413
+ import { basename, extname } from "path";
2174
2414
  var RE_CORS_NEXT_VALUE = compileDetectorRegex(
2175
2415
  `Access-Control-Allow-Origin['"]\\s*,\\s*value\\s*:\\s*['"]?\\s*\\*\\s*['"]?`,
2176
2416
  "i"
@@ -2208,6 +2448,11 @@ var RE_CONFIG_CORS_WILDCARD = compileDetectorRegex(
2208
2448
  `["']?origin["']?\\s*:\\s*["']?\\*["']?`,
2209
2449
  "i"
2210
2450
  );
2451
+ var RE_CONFIG_CORS_WILDCARD_JSON = compileDetectorRegex(
2452
+ `["']?origin["']?\\s*:\\s*["']\\*["']`,
2453
+ "i"
2454
+ );
2455
+ var JSON_FAMILY_EXTENSIONS = /* @__PURE__ */ new Set([".json", ".jsonc", ".json5"]);
2211
2456
  var RE_CONFIG_DEBUG_MODE = compileDetectorRegex(
2212
2457
  `["']?debug["']?\\s*:\\s*true`,
2213
2458
  "i"
@@ -2222,6 +2467,15 @@ function findLine(content, pattern) {
2222
2467
  }
2223
2468
  return void 0;
2224
2469
  }
2470
+ function findMatchStartLine(content, pattern) {
2471
+ const m = pattern.exec(content);
2472
+ if (!m) return void 0;
2473
+ let line = 1;
2474
+ for (let i = 0; i < m.index; i++) {
2475
+ if (content.charCodeAt(i) === 10) line++;
2476
+ }
2477
+ return line;
2478
+ }
2225
2479
  function findLineStr(content, literal) {
2226
2480
  const lines = content.split("\n");
2227
2481
  for (let i = 0; i < lines.length; i++) {
@@ -2234,7 +2488,7 @@ function checkNextConfig(file) {
2234
2488
  const { content, relativePath } = file;
2235
2489
  if (RE_CORS_NEXT_VALUE.test(content) || RE_CORS_NEXT_HEADER.test(content)) {
2236
2490
  const matchedPattern = RE_CORS_NEXT_VALUE.test(content) ? RE_CORS_NEXT_VALUE : RE_CORS_NEXT_HEADER;
2237
- const line = findLine(content, matchedPattern);
2491
+ const line = findMatchStartLine(content, matchedPattern);
2238
2492
  findings.push({
2239
2493
  id: makeId("cors_wildcard"),
2240
2494
  title: "Permissive CORS: Access-Control-Allow-Origin set to wildcard (*)",
@@ -2539,8 +2793,9 @@ function checkPackageJson2(file) {
2539
2793
  function checkGeneralConfigs(file) {
2540
2794
  const findings = [];
2541
2795
  const { content, relativePath } = file;
2542
- if (RE_CONFIG_CORS_WILDCARD.test(content)) {
2543
- const line = findLine(content, RE_CONFIG_CORS_WILDCARD);
2796
+ const corsRe = JSON_FAMILY_EXTENSIONS.has(extname(relativePath).toLowerCase()) ? RE_CONFIG_CORS_WILDCARD_JSON : RE_CONFIG_CORS_WILDCARD;
2797
+ if (corsRe.test(content)) {
2798
+ const line = findMatchStartLine(content, corsRe);
2544
2799
  findings.push({
2545
2800
  id: makeId("config_cors_wildcard_origin"),
2546
2801
  title: `CORS origin wildcard (*) detected in ${relativePath}`,
@@ -2573,6 +2828,37 @@ function checkGeneralConfigs(file) {
2573
2828
  }
2574
2829
  return findings;
2575
2830
  }
2831
+ var CONFIG_CANDIDATE_EXTENSIONS = /* @__PURE__ */ new Set([
2832
+ ".js",
2833
+ ".mjs",
2834
+ ".cjs",
2835
+ ".jsx",
2836
+ ".ts",
2837
+ ".mts",
2838
+ ".cts",
2839
+ ".tsx",
2840
+ ".json",
2841
+ ".jsonc",
2842
+ ".json5",
2843
+ ".yml",
2844
+ ".yaml",
2845
+ ".toml",
2846
+ ".ini",
2847
+ ".conf",
2848
+ ".cfg",
2849
+ ".env",
2850
+ ".py",
2851
+ ".rb",
2852
+ ".go",
2853
+ ".php"
2854
+ ]);
2855
+ function isConfigCandidate(relativePath) {
2856
+ const base = basename(relativePath);
2857
+ if (base === ".env" || base.startsWith(".env.")) return true;
2858
+ const dot = base.lastIndexOf(".");
2859
+ if (dot <= 0) return false;
2860
+ return CONFIG_CANDIDATE_EXTENSIONS.has(base.slice(dot).toLowerCase());
2861
+ }
2576
2862
  var deploymentCheck = {
2577
2863
  id: "deployment",
2578
2864
  name: "Deployment & Configuration",
@@ -2604,7 +2890,9 @@ var deploymentCheck = {
2604
2890
  findings.push(...checkPackageJson2(file));
2605
2891
  continue;
2606
2892
  }
2607
- findings.push(...checkGeneralConfigs(file));
2893
+ if (isConfigCandidate(file.relativePath)) {
2894
+ findings.push(...checkGeneralConfigs(file));
2895
+ }
2608
2896
  }
2609
2897
  findings.push(...checkEnvFiles(files));
2610
2898
  return findings;
@@ -2978,41 +3266,52 @@ async function fetchProRules(frameworks, categories, apiUrl, scanId, floorPath)
2978
3266
  const msg = networkErr instanceof Error ? networkErr.message : String(networkErr);
2979
3267
  throw new ProFetchError("SERVER_ERROR", `Network error contacting pro rules API: ${msg}`);
2980
3268
  }
2981
- if (res.status === 401) throw new ProFetchError("AUTH_FAILED", "Auth expired. Run `shipguard login` again.");
2982
- if (res.status === 402) throw new ProFetchError("INSUFFICIENT_CREDITS", "No credits. Buy at https://agenticcli.dev/dashboard/billing");
2983
- if (res.status === 429) {
2984
- const retryAfterHeader = res.headers.get("Retry-After");
2985
- const retryAfterSeconds = retryAfterHeader ? parseInt(retryAfterHeader, 10) : void 0;
2986
- throw new ProFetchError(
2987
- "RATE_LIMITED",
2988
- `Rate limited (429): too many pro rule fetches.`,
2989
- { retryAfterSeconds: Number.isFinite(retryAfterSeconds) ? retryAfterSeconds : void 0 }
2990
- );
2991
- }
2992
- if (res.status === 409) throw new ProFetchError("SERVER_ERROR", `Rule fetch conflict (409): ${res.statusText}`);
2993
- if (res.status === 422) {
2994
- let detail = res.statusText;
3269
+ if (!res.ok) {
3270
+ let errorBody;
2995
3271
  try {
2996
- const body = await res.json();
2997
- if (body?.code === "NO_RULES_APPLIED") {
3272
+ errorBody = await res.json();
3273
+ } catch (parseErr) {
3274
+ const msg = parseErr instanceof Error ? parseErr.message : String(parseErr);
3275
+ console.error(
3276
+ `[shipguard] Pro-fetch error response body was not parsable JSON \u2014 falling back to HTTP-status classification: ${msg}`
3277
+ );
3278
+ }
3279
+ if (errorBody?.code === "NO_ACTIVE_RELEASE") {
3280
+ throw new ProFetchError(
3281
+ "NO_ACTIVE_RELEASE",
3282
+ 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
+ );
3284
+ }
3285
+ 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");
3287
+ if (res.status === 429) {
3288
+ const retryAfterHeader = res.headers.get("Retry-After");
3289
+ const retryAfterSeconds = retryAfterHeader ? parseInt(retryAfterHeader, 10) : void 0;
3290
+ throw new ProFetchError(
3291
+ "RATE_LIMITED",
3292
+ `Rate limited (429): too many pro rule fetches.`,
3293
+ { retryAfterSeconds: Number.isFinite(retryAfterSeconds) ? retryAfterSeconds : void 0 }
3294
+ );
3295
+ }
3296
+ if (res.status === 409) throw new ProFetchError("SERVER_ERROR", `Rule fetch conflict (409): ${res.statusText}`);
3297
+ if (res.status === 422) {
3298
+ if (errorBody?.code === "NO_RULES_APPLIED") {
2998
3299
  throw new NoRulesAppliedError(
2999
- body.error ?? "Pro rule fetch resolved zero rules \u2014 the scan checked nothing (fail-closed). This is NOT a clean pass."
3300
+ errorBody.error ?? "Pro rule fetch resolved zero rules \u2014 the scan checked nothing (fail-closed). This is NOT a clean pass."
3000
3301
  );
3001
3302
  }
3002
- detail = body?.error ?? detail;
3003
- } catch (err) {
3004
- if (err instanceof NoRulesAppliedError) throw err;
3303
+ const detail = errorBody?.error ?? res.statusText;
3304
+ throw new ProFetchError("BUNDLE_INVALID", `Rule fetch failed (422): ${detail}`);
3005
3305
  }
3006
- throw new ProFetchError("BUNDLE_INVALID", `Rule fetch failed (422): ${detail}`);
3306
+ if (res.status >= 500) throw new ProFetchError("SERVER_ERROR", `Rule fetch failed (${res.status}): ${res.statusText}`);
3307
+ throw new ProFetchError("SERVER_ERROR", `Rule fetch failed: ${res.statusText}`);
3007
3308
  }
3008
- if (res.status >= 500) throw new ProFetchError("SERVER_ERROR", `Rule fetch failed (${res.status}): ${res.statusText}`);
3009
- if (!res.ok) throw new ProFetchError("SERVER_ERROR", `Rule fetch failed: ${res.statusText}`);
3010
3309
  const credits = parseInt(res.headers.get("X-Credits-Remaining") ?? "0", 10);
3011
3310
  const rulesVersion = res.headers.get("X-Rules-Version") ?? void 0;
3012
3311
  const rawText = await res.text();
3013
3312
  let responseJson;
3014
3313
  try {
3015
- const { parseStrictNoDup: parseStrict } = await import("./dist-PI34PRNW.js");
3314
+ const { parseStrictNoDup: parseStrict } = await import("./dist-3SW45O4F.js");
3016
3315
  responseJson = parseStrict(rawText);
3017
3316
  } catch (parseErr) {
3018
3317
  const msg = parseErr instanceof Error ? parseErr.message : String(parseErr);
@@ -3116,7 +3415,7 @@ function validateBundleCompile(rules) {
3116
3415
  const re2jsFlags = toRe2jsFlags2(flagsResult.flags);
3117
3416
  for (const p of rule.matcher.patterns) {
3118
3417
  try {
3119
- RE2JS2.compile(p, re2jsFlags);
3418
+ compileCached(p, re2jsFlags);
3120
3419
  } catch (err) {
3121
3420
  const msg = err instanceof Error ? err.message : String(err);
3122
3421
  return {
@@ -3127,7 +3426,7 @@ function validateBundleCompile(rules) {
3127
3426
  }
3128
3427
  for (const ap of rule.matcher.antiPatterns) {
3129
3428
  try {
3130
- RE2JS2.compile(ap, re2jsFlags);
3429
+ compileCached(ap, re2jsFlags);
3131
3430
  } catch (err) {
3132
3431
  const msg = err instanceof Error ? err.message : String(err);
3133
3432
  return {
@@ -3314,6 +3613,8 @@ function runProRulesWithDispatch(rules, files, policy, cliVersion, table, manife
3314
3613
 
3315
3614
  export {
3316
3615
  logger,
3616
+ getFindingKey,
3617
+ redactFindingsEvidence,
3317
3618
  secretsCheck,
3318
3619
  authCheck,
3319
3620
  databaseCheck,
@@ -3326,6 +3627,7 @@ export {
3326
3627
  isTokenExpired,
3327
3628
  getAuthToken,
3328
3629
  loadChecksumManifest,
3630
+ isLineSuppressed,
3329
3631
  applySuppressions,
3330
3632
  NoRulesAppliedError,
3331
3633
  ProFetchError,