@agenticcli/shipguard 0.11.0 → 0.12.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.
@@ -1737,6 +1737,62 @@ function extractJwtRoleClaim(payloadSegment) {
1737
1737
  return null;
1738
1738
  }
1739
1739
  }
1740
+ var PUBLISHABLE_PREFIX_RE = compileDetectorRegex(`^(?:pk_(?:live|test)_|sb_publishable_|phc_)[A-Za-z0-9_\\-]+$`);
1741
+ var PLACEHOLDER_VALUE_RE = compileDetectorRegex(
1742
+ // Every alternative is anchored to the WHOLE value (or, for a URL, to the whole password part).
1743
+ `^(?:[a-z]{1,6}[_-]){0,3}x{3,}(?:[_-]x{3,})*$|\\*{3,}|\\.{3}|\u2026|^(?:[a-z0-9]{1,8}[_\\-]){0,3}your[_\\- ].*$|^.*[_\\-]here$|^(?:[a-z0-9]{1,8}[_\\-]){0,3}(?:replace[_\\-]?me|change[_\\-]?me|placeholder|redacted|dummy|todo|tbd|fixme)(?:[_\\-](?:replace[_\\-]?me|change[_\\-]?me|placeholder|redacted|dummy|todo|tbd|fixme))*$|^(?:changeme|secret|password|passw0rd|test|example|none|null|undefined)$|^<[^>]{1,60}>$|^\\{\\{.*\\}\\}$|^\\$\\{.*\\}$|^\\[[a-z0-9_\\- ]+\\]$|^%[a-z0-9_]+%$|:\\/\\/[^\\s:\\/@]*:(?:<[^>@]{1,40}>|\\$\\{[^}@]+\\}|\\{\\{[^}@]+\\}\\}|%[A-Za-z0-9_]+%|your[_\\-]?password|change[_\\-]?me|\\*+|x{3,})@`,
1744
+ "i"
1745
+ );
1746
+ var ASSIGNED_LITERAL_RE = compileDetectorRegex(`[=:]\\s*['"\`]?([^\\s'"\`;,]+)`);
1747
+ function isPublicKeyValue(value) {
1748
+ const v = value.trim();
1749
+ if (PUBLISHABLE_PREFIX_RE.test(v)) return true;
1750
+ const parts = v.split(".");
1751
+ if (parts.length === 3 && parts[0].startsWith("eyJ") && parts[1].startsWith("eyJ")) {
1752
+ return extractJwtRoleClaim(parts[1]) === "anon";
1753
+ }
1754
+ return false;
1755
+ }
1756
+ function isPlaceholderValue(value) {
1757
+ return PLACEHOLDER_VALUE_RE.test(value);
1758
+ }
1759
+ var FAKE_MARKER_RE = compileDetectorRegex(
1760
+ "example|sample|dummy|fake|not[_\\-]?real|placeholder|replace[_\\-]?me|change[_\\-]?me|your[_\\-]?(?:api|key|secret|token)|test[_\\-]?key|insert[_\\-]?(?:key|here)",
1761
+ "i"
1762
+ );
1763
+ var SEQUENCE_RUNS = [
1764
+ "01234567890123456789",
1765
+ "abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz",
1766
+ "0123456789abcdef0123456789abcdef",
1767
+ "qwertyuiopasdfghjklzxcvbnm"
1768
+ ];
1769
+ function looksFakeKey(value) {
1770
+ const v = value.trim();
1771
+ if (v === "") return false;
1772
+ if (isPlaceholderValue(v) || FAKE_MARKER_RE.test(v)) return true;
1773
+ let body = v;
1774
+ for (; ; ) {
1775
+ const dash = body.indexOf("-");
1776
+ const under = body.indexOf("_");
1777
+ const sep = dash < 0 ? under : under < 0 ? dash : Math.min(dash, under);
1778
+ if (sep < 1 || sep > 10) break;
1779
+ body = body.slice(sep + 1);
1780
+ }
1781
+ if (body.length < 8) return false;
1782
+ if (isPlaceholderValue(body)) return true;
1783
+ if (new Set(body.toLowerCase()).size <= 2) return true;
1784
+ for (let unit = 1; unit <= 10 && unit * 2 <= body.length; unit++) {
1785
+ if (body.length % unit !== 0) continue;
1786
+ const chunk = body.slice(0, unit);
1787
+ if (chunk.repeat(body.length / unit) === body) return true;
1788
+ }
1789
+ const lower = body.toLowerCase();
1790
+ return lower.length >= 10 && SEQUENCE_RUNS.some((run) => run.includes(lower));
1791
+ }
1792
+ function assignedLiteral(rest) {
1793
+ const m = ASSIGNED_LITERAL_RE.exec(rest);
1794
+ return m ? m.groups[0] ?? "" : "";
1795
+ }
1740
1796
  function checkSupabaseServiceRoleJwt(file, findings, policy, dedupe) {
1741
1797
  const { content, relativePath } = file;
1742
1798
  const lines = content.split("\n");
@@ -1766,12 +1822,64 @@ function checkSupabaseServiceRoleJwt(file, findings, policy, dedupe) {
1766
1822
  }
1767
1823
  }
1768
1824
  }
1825
+ var SECRET_KEY_NAME_RE = compileDetectorRegex(
1826
+ `(?:SECRET|PASS|PWD|PRIVATE|TOKEN|API_?KEY|ACCESS_?KEY|SERVICE_?ROLE|CREDENTIAL|DATABASE_URL|DB_URL|CONNECTION_STRING|SALT|SESSION|JWT|COOKIE|SIGNING|WEBHOOK|DSN|AUTH|_KEY$|_PAT$|^KEY$)`,
1827
+ "i"
1828
+ );
1829
+ var STRONG_SECRET_NAME_RE = compileDetectorRegex(`(?:SECRET|PRIVATE|PASSWORD|PASSWD|SERVICE_?ROLE|SIGNING)`, "i");
1830
+ var PUBLIC_PREFIX_KEY_RE = compileDetectorRegex(`^(?:NEXT_PUBLIC|VITE|EXPO_PUBLIC|PUBLIC|REACT_APP|NUXT_PUBLIC|GATSBY)_`);
1831
+ var URL_USERINFO_RE = compileDetectorRegex(`^[a-z][a-z0-9+.\\-]*:\\/\\/([^\\/\\s@?#]*)@`, "i");
1832
+ var PUBLIC_CONFIG_VALUE_RE = compileDetectorRegex(
1833
+ `^(?:true|false|yes|no|on|off|0|1|[0-9]{1,5}|development|production|test|staging|preview|local|debug|info|warn|error|trace|silent|[a-z]{2}-[a-z]+-[0-9]|https?:\\/\\/[^\\s@]+|[a-z0-9][a-z0-9.\\-]*\\.[a-z]{2,}(?::[0-9]{1,5})?(?:\\/[^\\s@]*)?|localhost(?::[0-9]{1,5})?|127\\.0\\.0\\.1(?::[0-9]{1,5})?)$`,
1834
+ "i"
1835
+ );
1836
+ var EXPORT_PREFIX_RE = compileDetectorRegex(`^export\\s+`);
1837
+ var INLINE_COMMENT_RE = compileDetectorRegex(`\\s+#`);
1838
+ function urlHasRealPassword(value) {
1839
+ const m = URL_USERINFO_RE.exec(value);
1840
+ if (!m) return false;
1841
+ const info = m.groups[0] ?? "";
1842
+ const colon = info.indexOf(":");
1843
+ if (colon === -1) return false;
1844
+ const pw = info.slice(colon + 1);
1845
+ if (pw === "") return false;
1846
+ return !isPlaceholderValue(`://u:${pw}@`);
1847
+ }
1848
+ function envFileHasSecret(content) {
1849
+ for (const raw of content.split("\n")) {
1850
+ const line = raw.trim();
1851
+ if (line === "" || line.startsWith("#")) continue;
1852
+ const eq = line.indexOf("=");
1853
+ if (eq <= 0) continue;
1854
+ const key = EXPORT_PREFIX_RE.replace(line.slice(0, eq), "").trim();
1855
+ let value = line.slice(eq + 1).trim();
1856
+ const q = value.charAt(0);
1857
+ if ((q === '"' || q === "'") && value.indexOf(q, 1) > 0) value = value.slice(1, value.indexOf(q, 1));
1858
+ else {
1859
+ const c = INLINE_COMMENT_RE.exec(value);
1860
+ value = (c ? value.slice(0, c.index) : value).trim();
1861
+ }
1862
+ if (value === "") continue;
1863
+ if (URL_USERINFO_RE.test(value)) {
1864
+ if (urlHasRealPassword(value)) return true;
1865
+ continue;
1866
+ }
1867
+ if (isPublicKeyValue(value) || isPlaceholderValue(value)) continue;
1868
+ if (value.includes("hooks.slack.com/") || value.includes("/api/webhooks/")) return true;
1869
+ if (PUBLIC_PREFIX_KEY_RE.test(key) && !STRONG_SECRET_NAME_RE.test(key)) continue;
1870
+ if (!SECRET_KEY_NAME_RE.test(key) && PUBLIC_CONFIG_VALUE_RE.test(value)) continue;
1871
+ return true;
1872
+ }
1873
+ return false;
1874
+ }
1769
1875
  function checkSecrets(files, policy) {
1770
1876
  const findings = [];
1771
1877
  for (const file of files) {
1772
1878
  const { content, relativePath } = file;
1879
+ let envFindingIdx = -1;
1773
1880
  if (isDotEnvFile(relativePath)) {
1774
1881
  const id = "exposed_env";
1882
+ envFindingIdx = findings.length;
1775
1883
  findings.push({
1776
1884
  id,
1777
1885
  title: ".env file tracked in git",
@@ -1809,6 +1917,7 @@ function checkSecrets(files, policy) {
1809
1917
  const line = lines2[i];
1810
1918
  const match = NEXT_PUBLIC_SECRET_RE.exec(line);
1811
1919
  if (match && match.groups[0]) {
1920
+ if (isPublicKeyValue(assignedLiteral(line.slice(match.index))) || isPlaceholderValue(match.groups[0])) continue;
1812
1921
  const id = "exposed_env";
1813
1922
  findings.push({
1814
1923
  id,
@@ -1843,6 +1952,9 @@ function checkSecrets(files, policy) {
1843
1952
  if (pattern.postExcludeFollowedBy(restAfterMatch)) continue;
1844
1953
  }
1845
1954
  const secretValue = lineMatch.groups[0] ?? lineMatch.match;
1955
+ if (isPlaceholderValue(secretValue)) continue;
1956
+ const isAssignMatch = lineMatch.match.includes("=") || lineMatch.match.includes(":");
1957
+ if (isPublicKeyValue((isAssignMatch ? assignedLiteral(line.slice(lineMatch.index)) : "") || secretValue)) continue;
1846
1958
  const secretFinding = {
1847
1959
  id: pattern.id,
1848
1960
  title: pattern.name,
@@ -1851,7 +1963,7 @@ function checkSecrets(files, policy) {
1851
1963
  file: relativePath,
1852
1964
  line: i + 1,
1853
1965
  evidence: `...${redactSecretValue(secretValue)}...`,
1854
- confidence: pattern.confidence,
1966
+ confidence: looksFakeKey(secretValue) ? "LOW" : pattern.confidence,
1855
1967
  explanation: pattern.explanation,
1856
1968
  recommendation: pattern.recommendation,
1857
1969
  blocking: policy.block.includes(pattern.id)
@@ -1862,6 +1974,9 @@ function checkSecrets(files, policy) {
1862
1974
  }
1863
1975
  }
1864
1976
  }
1977
+ if (envFindingIdx >= 0 && !envFileHasSecret(content) && !findings.slice(envFindingIdx + 1).some((f) => f.file === relativePath)) {
1978
+ findings.splice(envFindingIdx, 1);
1979
+ }
1865
1980
  }
1866
1981
  return findings;
1867
1982
  }
@@ -1881,7 +1996,7 @@ var RE2_EXPRESS_ROUTE_DEFINITION = compileDetectorRegex(
1881
1996
  "i"
1882
1997
  );
1883
1998
  var RE2_AUTH_CALL_PATTERN = compileDetectorRegex(
1884
- `(?:auth|getServerSession|requireAuth|verifyToken|withAuth|clerkMiddleware|authMiddleware)\\s*\\(`
1999
+ `(?:auth|getAuth|getServerSession|getSession|getUser|getClaims|currentUser|requireAuth|requireUser|requireSession|requireAdmin|verifyToken|verifyAuth|withAuth|validateRequest|clerkMiddleware|authMiddleware)\\s*\\(`
1885
2000
  );
1886
2001
  var RE2_COMMENTED_AUTH_PATTERN = compileDetectorRegex(
1887
2002
  `^\\s*(?:\\/\\/|\\/\\*|\\*)[^\\n]*(?:auth|getServerSession|requireAuth|verifyToken)\\s*\\(`,
@@ -1894,11 +2009,96 @@ var RE2_EXPRESS_AUTH_MIDDLEWARE_PATTERN = compileDetectorRegex(
1894
2009
  var RE2_MIDDLEWARE_ADMIN_COVERAGE = compileDetectorRegex(
1895
2010
  `(?:admin|dashboard|billing|account|management)`
1896
2011
  );
2012
+ var RE2_SENSITIVE_PREFIX = compileDetectorRegex(
2013
+ `(?:admin|dashboard|billing|account|management|settings)`
2014
+ );
2015
+ function stripComments(src) {
2016
+ let out = "";
2017
+ let i = 0;
2018
+ while (i < src.length) {
2019
+ const c = src[i];
2020
+ if (c === '"' || c === "'" || c === "`") {
2021
+ let j = i + 1;
2022
+ while (j < src.length && src[j] !== c) j += src[j] === "\\" ? 2 : 1;
2023
+ out += src.slice(i, j + 1);
2024
+ i = j + 1;
2025
+ } else if (c === "/" && src[i + 1] === "/") {
2026
+ while (i < src.length && src[i] !== "\n") i++;
2027
+ } else if (c === "/" && src[i + 1] === "*") {
2028
+ const end = src.indexOf("*/", i + 2);
2029
+ i = end === -1 ? src.length : end + 2;
2030
+ out += " ";
2031
+ } else {
2032
+ out += c;
2033
+ i++;
2034
+ }
2035
+ }
2036
+ return out;
2037
+ }
2038
+ function matcherLiterals(code) {
2039
+ const key = code.indexOf("matcher");
2040
+ if (key === -1) return [];
2041
+ let i = code.indexOf(":", key);
2042
+ if (i === -1) return [];
2043
+ i++;
2044
+ while (i < code.length && " \r\n".includes(code[i])) i++;
2045
+ const lits = [];
2046
+ let depth = 0;
2047
+ for (; i < code.length; i++) {
2048
+ const c = code[i];
2049
+ if (c === '"' || c === "'" || c === "`") {
2050
+ let j = i + 1;
2051
+ while (j < code.length && code[j] !== c) j += code[j] === "\\" ? 2 : 1;
2052
+ lits.push(code.slice(i + 1, j));
2053
+ i = j;
2054
+ if (depth === 0) break;
2055
+ } else if (c === "[") depth++;
2056
+ else if (c === "]") {
2057
+ depth--;
2058
+ if (depth <= 0) break;
2059
+ } else if (depth === 0) break;
2060
+ }
2061
+ return lits;
2062
+ }
2063
+ function isSafeCatchAll(lit) {
2064
+ const start = lit.indexOf("(?!");
2065
+ if (start === -1 || !lit.startsWith("/(")) return false;
2066
+ let depth = 0;
2067
+ let end = -1;
2068
+ for (let i = start; i < lit.length; i++) {
2069
+ if (lit[i] === "\\") i++;
2070
+ else if (lit[i] === "(") depth++;
2071
+ else if (lit[i] === ")" && --depth === 0) {
2072
+ end = i;
2073
+ break;
2074
+ }
2075
+ }
2076
+ if (end === -1) return false;
2077
+ const rest = lit.slice(end + 1);
2078
+ if (rest !== ".*)" && rest !== ".*") return false;
2079
+ return !RE2_SENSITIVE_PREFIX.test(lit.slice(start, end + 1));
2080
+ }
2081
+ function middlewareCoversRoutes(content) {
2082
+ const code = stripComments(content);
2083
+ let words = "";
2084
+ for (let i = 0; i < code.length; i++) {
2085
+ if (code.startsWith("(?!", i)) {
2086
+ let depth = 0;
2087
+ for (; i < code.length; i++) {
2088
+ if (code[i] === "\\") i++;
2089
+ else if (code[i] === "(") depth++;
2090
+ else if (code[i] === ")" && --depth === 0) break;
2091
+ }
2092
+ } else words += code[i];
2093
+ }
2094
+ if (RE2_MIDDLEWARE_ADMIN_COVERAGE.test(words)) return true;
2095
+ return matcherLiterals(code).some(isSafeCatchAll);
2096
+ }
1897
2097
  var RE2_INLINE_AUTH_CHECK = compileDetectorRegex(
1898
2098
  `requireAuth|verifyToken|isAuth|isLogged|passport\\.authenticate`,
1899
2099
  "i"
1900
2100
  );
1901
- var MIDDLEWARE_FILE_PATTERN = /^(?:src\/)?middleware\.[tj]s$/;
2101
+ var MIDDLEWARE_FILE_PATTERN = /^(?:src\/)?(?:middleware|proxy)\.[tj]s$/;
1902
2102
  var NEXT_APP_ROUTER_PATH = /^(?:src\/)?(?:app\/|app$)/;
1903
2103
  var NEXT_CONFIG_FILE = /^(?:src\/)?next\.config\.[cm]?[jt]s$/;
1904
2104
  function isNextjsProject(files) {
@@ -2209,6 +2409,152 @@ function hasActiveAuthCall(content) {
2209
2409
  const execText = extractExecutableText(content);
2210
2410
  return RE2_AUTH_CALL_PATTERN.test(execText);
2211
2411
  }
2412
+ var PAGE_FILE_PATTERN = /(?:^|\/)page\.[tj]sx?$/;
2413
+ function isPageFile(rp) {
2414
+ return PAGE_FILE_PATTERN.test(rp);
2415
+ }
2416
+ function layoutChain(pagePath, byPath) {
2417
+ const segs = pagePath.split("/").slice(0, -1);
2418
+ const start = segs.findIndex((x) => RE2_SENSITIVE_SEGMENT.test(x));
2419
+ const out = [];
2420
+ if (start === -1) return out;
2421
+ for (let n = start + 1; n <= segs.length; n++) {
2422
+ const dir = segs.slice(0, n).join("/");
2423
+ for (const ext of ["tsx", "ts", "jsx", "js"]) {
2424
+ const f = byPath.get(`${dir}/layout.${ext}`);
2425
+ if (f) out.push(f);
2426
+ }
2427
+ }
2428
+ return out;
2429
+ }
2430
+ var RE2_SENSITIVE_SEGMENT = compileDetectorRegex(`^(?:admin|dashboard|billing|account|settings|management|debug|internal)$`);
2431
+ var RE2_ENFORCING_CALL = compileDetectorRegex(
2432
+ `\\b(?:require(?:Auth|User|Session|Admin|Login)\\w*|assertAuth\\w*|ensureAuth\\w*|withAuth\\w*|verifyToken|clerkMiddleware|authMiddleware)\\s*\\(|\\bauth\\.protect\\s*\\(`
2433
+ );
2434
+ var RE2_SESSION_FETCH = compileDetectorRegex(
2435
+ `\\b(?:auth|getAuth|getUser|getSession|getClaims|currentUser|validateRequest|getCurrentUser)\\s*\\(\\s*(?:supabase|client|sb|req|request|ctx|context)?\\s*\\)|\\bgetServerSession\\s*\\(|\\buse(?:Session|User|Auth)\\s*\\(`
2436
+ );
2437
+ var RE2_GUARD_ACTION = compileDetectorRegex(
2438
+ `^\\s*(?:\\{\\s*)?(?:return\\s+)?(?:(?:redirect|permanentRedirect|notFound|unauthorized|forbidden)\\s*\\(|throw\\b|null\\b|<|router\\.(?:push|replace)\\s*\\()`
2439
+ );
2440
+ var RE2_IF_OPEN = compileDetectorRegex(`\\bif\\s*\\(`);
2441
+ var RE2_INLINE_GUARD = compileDetectorRegex(`^[^\\n;]{0,60}(?:\\|\\||\\?\\?)\\s*(?:redirect|notFound|unauthorized|forbidden)\\s*\\(`);
2442
+ var RE2_ASSIGN_TARGET = compileDetectorRegex(`^(?:const|let|var)\\s+([^=;]{1,120}?)\\s*=`);
2443
+ var RE2_IDENT = compileDetectorRegex(`[A-Za-z_$][\\w$]*`);
2444
+ var RE2_DEFAULT_FN = compileDetectorRegex(`export\\s+default\\s+(?:async\\s+)?function\\s*(\\w*)\\s*\\(`);
2445
+ var RE2_DEFAULT_REF = compileDetectorRegex(`export\\s+default\\s+(\\w+)\\s*;?\\s*$`, "m");
2446
+ var RE2_CALL_NAME = compileDetectorRegex(`\\b([A-Za-z_]\\w*)\\s*\\(`);
2447
+ function braceBody(code, from) {
2448
+ const open = code.indexOf("{", from);
2449
+ if (open === -1) return "";
2450
+ let depth = 0;
2451
+ for (let i = open; i < code.length; i++) {
2452
+ if (code[i] === "{") depth++;
2453
+ else if (code[i] === "}" && --depth === 0) return code.slice(open, i + 1);
2454
+ }
2455
+ return "";
2456
+ }
2457
+ function afterParens(code, open) {
2458
+ let depth = 0;
2459
+ for (let i = open; i < code.length; i++) {
2460
+ if (code[i] === "(") depth++;
2461
+ else if (code[i] === ")" && --depth === 0) return i + 1;
2462
+ }
2463
+ return open;
2464
+ }
2465
+ function functionBody(code, name) {
2466
+ const fn = compileDetectorRegex(`(?:function\\s+${name}\\s*\\(|(?:const|let)\\s+${name}\\s*=\\s*(?:async\\s*)?(?:function\\s*)?\\()`).exec(code);
2467
+ if (!fn) return "";
2468
+ const paren = code.indexOf("(", fn.index + fn.match.length - 1);
2469
+ return braceBody(code, afterParens(code, paren));
2470
+ }
2471
+ function componentText(code) {
2472
+ let body = "";
2473
+ const decl = RE2_DEFAULT_FN.exec(code);
2474
+ if (decl) {
2475
+ body = braceBody(code, afterParens(code, decl.index + decl.match.length - 1));
2476
+ } else {
2477
+ const ref = RE2_DEFAULT_REF.exec(code);
2478
+ if (ref) body = functionBody(code, ref.groups[0] ?? "") || "";
2479
+ }
2480
+ if (body === "") return code;
2481
+ let extra = "";
2482
+ for (const m of RE2_CALL_NAME.matchAll(body)) {
2483
+ const name = m.groups[0] ?? "";
2484
+ if (name === "if" || name === "function" || name === "") continue;
2485
+ extra += functionBody(code, name);
2486
+ }
2487
+ return body + "\n" + extra;
2488
+ }
2489
+ function assignedNames(text, fetchIdx) {
2490
+ const before = text.slice(Math.max(0, fetchIdx - 300), fetchIdx);
2491
+ const kw = Math.max(before.lastIndexOf("const "), before.lastIndexOf("let "), before.lastIndexOf("var "));
2492
+ if (kw === -1 || before.slice(kw).includes(";")) return [];
2493
+ const m = RE2_ASSIGN_TARGET.exec(before.slice(kw));
2494
+ if (!m) return [];
2495
+ const names = [];
2496
+ const lhs = m.groups[0] ?? "";
2497
+ for (const id of RE2_IDENT.matchAll(lhs)) {
2498
+ let k = id.index + id.match.length;
2499
+ while (k < lhs.length && (lhs[k] === " " || lhs[k] === " " || lhs[k] === "\n" || lhs[k] === "\r")) k++;
2500
+ if (lhs[k] === ":") continue;
2501
+ names.push(id.match);
2502
+ }
2503
+ return names;
2504
+ }
2505
+ function trimLead(t) {
2506
+ let k = 0;
2507
+ while (k < t.length && (t[k] === " " || t[k] === " " || t[k] === "\n" || t[k] === "\r" || t[k] === ")")) k++;
2508
+ return t.slice(k);
2509
+ }
2510
+ function firstLines(text, n) {
2511
+ let end = 0;
2512
+ for (let k = 0; k < n; k++) {
2513
+ const nl = text.indexOf("\n", end);
2514
+ if (nl === -1) return text;
2515
+ end = nl + 1;
2516
+ }
2517
+ return text.slice(0, end);
2518
+ }
2519
+ function testsVariableThenTurnsAway(win, names) {
2520
+ for (const open of RE2_IF_OPEN.matchAll(win)) {
2521
+ let depth = 0;
2522
+ let close = -1;
2523
+ for (let k = open.index + open.match.length - 1; k < win.length && k < open.index + 200; k++) {
2524
+ if (win[k] === "(") depth++;
2525
+ else if (win[k] === ")" && --depth === 0) {
2526
+ close = k;
2527
+ break;
2528
+ }
2529
+ }
2530
+ if (close === -1) continue;
2531
+ const cond = win.slice(open.index + open.match.length, close);
2532
+ const condIds = /* @__PURE__ */ new Set();
2533
+ for (const id of RE2_IDENT.matchAll(cond)) condIds.add(id.match);
2534
+ const namesIt = names.some((nm) => condIds.has(nm));
2535
+ const tests = cond.includes("!") || cond.includes("==");
2536
+ if (namesIt && tests && RE2_GUARD_ACTION.test(win.slice(close + 1))) return true;
2537
+ }
2538
+ for (const nm of names) {
2539
+ const tail = win.split(nm);
2540
+ for (let k = 1; k < tail.length; k++) if (RE2_INLINE_GUARD.test(tail[k])) return true;
2541
+ }
2542
+ return false;
2543
+ }
2544
+ function gatesAccess(src) {
2545
+ const text = componentText(extractExecutableText(src));
2546
+ if (RE2_ENFORCING_CALL.test(text)) return true;
2547
+ for (const m of RE2_SESSION_FETCH.matchAll(text)) {
2548
+ const end = m.index + m.match.length;
2549
+ const lineStart = text.lastIndexOf("\n", m.index) + 1;
2550
+ const prefix = text.slice(lineStart, m.index);
2551
+ if (RE2_IF_OPEN.test(prefix) && RE2_GUARD_ACTION.test(trimLead(text.slice(text.indexOf(")", end) + 1)))) return true;
2552
+ if (RE2_INLINE_GUARD.test(text.slice(end))) return true;
2553
+ const names = assignedNames(text, m.index);
2554
+ if (names.length > 0 && testsVariableThenTurnsAway(firstLines(text.slice(end), 7), names)) return true;
2555
+ }
2556
+ return false;
2557
+ }
2212
2558
  function hasCommentedAuthCall(content) {
2213
2559
  return RE2_COMMENTED_AUTH_PATTERN.test(content);
2214
2560
  }
@@ -2236,19 +2582,7 @@ var authCheck = {
2236
2582
  const findings = [];
2237
2583
  const middlewareFile = files.find((f) => MIDDLEWARE_FILE_PATTERN.test(f.relativePath));
2238
2584
  if (isNextjsProject(files)) {
2239
- if (!middlewareFile) {
2240
- findings.push({
2241
- id: "public_admin_route",
2242
- title: "No Next.js middleware.ts found",
2243
- severity: "high",
2244
- category: "auth",
2245
- file: "middleware.ts",
2246
- confidence: "MEDIUM",
2247
- explanation: "No middleware.ts file was found. Next.js App Router relies on middleware to enforce route-level auth for admin, dashboard, and billing routes. Without it, protection depends entirely on individual Server Components and Route Handlers, which is error-prone.",
2248
- recommendation: "Create middleware.ts at the project root (or src/middleware.ts) and add a matcher that covers /admin, /dashboard, and /billing. Use auth() from next-auth/auth.js or clerkMiddleware() to redirect unauthenticated requests.",
2249
- blocking: policy.block.includes("public_admin_route")
2250
- });
2251
- } else if (!RE2_MIDDLEWARE_ADMIN_COVERAGE.test(middlewareFile.content)) {
2585
+ if (middlewareFile && !middlewareCoversRoutes(middlewareFile.content)) {
2252
2586
  findings.push({
2253
2587
  id: "public_admin_route",
2254
2588
  title: "middleware.ts does not cover admin/dashboard routes",
@@ -2262,13 +2596,15 @@ var authCheck = {
2262
2596
  });
2263
2597
  }
2264
2598
  }
2599
+ const filesByPath = new Map(files.map((f) => [f.relativePath, f]));
2265
2600
  for (const file of files) {
2266
2601
  const { relativePath: rp, content } = file;
2267
2602
  if (WEBHOOK_PATH_PATTERN.test(rp)) {
2268
2603
  continue;
2269
2604
  }
2270
2605
  if (SENSITIVE_NEXTJS_PAGE_PATTERN.test(rp)) {
2271
- if (!hasActiveAuthCall(content)) {
2606
+ if (!isPageFile(rp)) continue;
2607
+ if (!gatesAccess(content) && !layoutChain(rp, filesByPath).some((l) => gatesAccess(l.content))) {
2272
2608
  const wasRemoved = hasCommentedAuthCall(content);
2273
2609
  findings.push({
2274
2610
  id: "public_admin_route",
@@ -3038,15 +3374,17 @@ var deploymentCheck = {
3038
3374
  };
3039
3375
 
3040
3376
  // src/checks/payments.ts
3041
- function isStripeWebhookRoute(relativePath) {
3377
+ function isStripeWebhookRoute(relativePath, content) {
3042
3378
  const p = relativePath.toLowerCase();
3043
3379
  if (!p.includes("api/") && !p.includes("api\\")) return false;
3380
+ if (p.includes("razorpay") && RE_RAZORPAY_WORD.test(content) && !RE_STRIPE_WORD.test(content)) return false;
3044
3381
  return p.includes("webhook") || p.includes("stripe");
3045
3382
  }
3046
- function isRazorpayWebhookRoute(relativePath) {
3383
+ function isRazorpayWebhookRoute(relativePath, content) {
3047
3384
  const p = relativePath.toLowerCase();
3048
3385
  if (!p.includes("api/") && !p.includes("api\\")) return false;
3049
- return p.includes("razorpay") || p.includes("webhook") && p.includes("razorpay");
3386
+ if (!p.includes("razorpay")) return false;
3387
+ return RE_RAZORPAY_WORD.test(content) || !RE_STRIPE_WORD.test(content);
3050
3388
  }
3051
3389
  function isPaymentRoute(relativePath) {
3052
3390
  const p = relativePath.toLowerCase();
@@ -3059,6 +3397,8 @@ function isClientSideFile(relativePath) {
3059
3397
  return p.startsWith("app/") || p.startsWith("pages/") || p.startsWith("components/");
3060
3398
  }
3061
3399
  var RE_STRIPE_CONSTRUCT_EVENT = compileDetectorRegex("stripe\\.webhooks\\.constructEvent", "i");
3400
+ var RE_STRIPE_WORD = compileDetectorRegex("stripe", "i");
3401
+ var RE_RAZORPAY_WORD = compileDetectorRegex("razorpay", "i");
3062
3402
  var RE_STRIPE_SIGNATURE = compileDetectorRegex("stripe-signature", "i");
3063
3403
  var RE_RAZORPAY_VALIDATE = compileDetectorRegex("validateWebhookSignature", "i");
3064
3404
  var RE_IDEMPOTENCY_WORD = compileDetectorRegex("idempoten(?:cy|t)", "i");
@@ -3094,39 +3434,26 @@ var payments = {
3094
3434
  const findings = [];
3095
3435
  for (const file of files) {
3096
3436
  const { relativePath, content } = file;
3097
- if (isStripeWebhookRoute(relativePath)) {
3098
- if (!hasStripeConstructEvent(content)) {
3437
+ if (isStripeWebhookRoute(relativePath, content)) {
3438
+ const noConstructEvent = !hasStripeConstructEvent(content);
3439
+ const noSignatureHeader = !hasStripeSignatureHeader(content);
3440
+ if (noConstructEvent || noSignatureHeader) {
3099
3441
  const id = "payment_webhook_without_signature_check";
3100
3442
  findings.push({
3101
3443
  id,
3102
- title: "Stripe webhook missing signature verification",
3444
+ title: noConstructEvent ? "Stripe webhook missing signature verification" : "Stripe webhook does not read stripe-signature header",
3103
3445
  severity: "critical",
3104
3446
  category: "payments",
3105
3447
  file: relativePath,
3106
- evidence: "No call to stripe.webhooks.constructEvent() found",
3448
+ evidence: noConstructEvent && noSignatureHeader ? "No call to stripe.webhooks.constructEvent() and no reference to the stripe-signature header found" : noConstructEvent ? "No call to stripe.webhooks.constructEvent() found" : "No reference to stripe-signature header found",
3107
3449
  confidence: "MEDIUM",
3108
- explanation: "Without calling stripe.webhooks.constructEvent(), the webhook endpoint cannot verify that requests originate from Stripe. Attackers can send forged events to trigger payment logic (e.g., fake payment_intent.succeeded) without making a real payment.",
3109
- recommendation: "Verify every incoming webhook with stripe.webhooks.constructEvent(rawBody, sig, webhookSecret). Pass the raw request body \u2014 not a parsed JSON object \u2014 to prevent HMAC mismatch.",
3110
- blocking: isBlocking(id, policy)
3111
- });
3112
- }
3113
- if (!hasStripeSignatureHeader(content)) {
3114
- const id = "payment_webhook_without_signature_check";
3115
- findings.push({
3116
- id,
3117
- title: "Stripe webhook does not read stripe-signature header",
3118
- severity: "critical",
3119
- category: "payments",
3120
- file: relativePath,
3121
- evidence: "No reference to stripe-signature header found",
3122
- confidence: "MEDIUM",
3123
- explanation: "The Stripe-Signature header carries the HMAC timestamp+hash that proves the request originated from Stripe. Without reading it, signature verification is impossible.",
3124
- recommendation: 'Read the header with request.headers.get("stripe-signature") (Next.js) or req.headers["stripe-signature"] (Express) before calling constructEvent().',
3450
+ explanation: noConstructEvent ? "Without calling stripe.webhooks.constructEvent(), the webhook endpoint cannot verify that requests originate from Stripe. Attackers can send forged events to trigger payment logic (e.g., fake payment_intent.succeeded) without making a real payment." + (noSignatureHeader ? " The stripe-signature header, which carries the proof, is not read either." : "") : "The Stripe-Signature header carries the HMAC timestamp+hash that proves the request originated from Stripe. Without reading it, signature verification is impossible.",
3451
+ recommendation: 'Verify every incoming webhook with stripe.webhooks.constructEvent(rawBody, sig, webhookSecret). Pass the raw request body, not a parsed JSON object, to prevent HMAC mismatch. Read the header with request.headers.get("stripe-signature") (Next.js) or req.headers["stripe-signature"] (Express) first.',
3125
3452
  blocking: isBlocking(id, policy)
3126
3453
  });
3127
3454
  }
3128
3455
  }
3129
- if (isRazorpayWebhookRoute(relativePath)) {
3456
+ if (isRazorpayWebhookRoute(relativePath, content)) {
3130
3457
  if (!hasRazorpayValidateWebhook(content)) {
3131
3458
  const id = "payment_webhook_without_signature_check";
3132
3459
  findings.push({
@@ -3177,19 +3504,20 @@ var payments = {
3177
3504
  });
3178
3505
  }
3179
3506
  }
3180
- if (isStripeWebhookRoute(relativePath) || isRazorpayWebhookRoute(relativePath)) {
3507
+ if (isStripeWebhookRoute(relativePath, content) || isRazorpayWebhookRoute(relativePath, content)) {
3181
3508
  if (!hasIdempotencyHandling(content)) {
3182
3509
  const id = "missing_idempotency";
3183
3510
  findings.push({
3184
3511
  id,
3185
- title: "Webhook handler lacks idempotency protection",
3186
- severity: "medium",
3512
+ title: "No idempotency (duplicate-delivery) check found in webhook handler",
3513
+ // Robustness, not a security hole: a duplicate delivery repeats an action, it does not open access.
3514
+ severity: "low",
3187
3515
  category: "payments",
3188
3516
  file: relativePath,
3189
- evidence: "No idempotency key, event.id check, or duplicate-detection logic found",
3517
+ evidence: "No idempotency key, event.id check, or duplicate-detection logic found in this file",
3190
3518
  confidence: "LOW",
3191
- explanation: "Payment providers may deliver the same webhook event more than once (retries after network failure, provider-side bugs). Without idempotency guards, duplicate deliveries can cause double-charges, double-fulfillments, or double-refunds.",
3192
- recommendation: "Record processed event IDs (e.g., store event.id in a database) before acting on the event. If the ID already exists, return 200 immediately without reprocessing.",
3519
+ explanation: "Payment providers can send the same webhook event more than once (for example after a timeout). This file has no sign of a check for events it has already handled, so a repeat could run the same action twice, such as a second order fulfilment or refund. If you handle repeats elsewhere (a shared helper or the database), this finding can be ignored.",
3520
+ recommendation: "Store each processed event.id before acting on the event. If the ID is already stored, return 200 right away without running the action again.",
3193
3521
  blocking: isBlocking(id, policy)
3194
3522
  });
3195
3523
  }
@@ -3705,11 +4033,32 @@ function runProRules(rules, files, _policy) {
3705
4033
  `Unreachable: unsupported matcher type "${rule.matcher.type}" on rule "${rule.id}"`
3706
4034
  );
3707
4035
  }
3708
- const matched = files.filter((f) => minimatch(f.relativePath, rule.matcher.fileGlob));
4036
+ let matched = files.filter((f) => minimatch(f.relativePath, rule.matcher.fileGlob));
4037
+ let requiresFailClosed;
4038
+ if (rule.matcher.type === "pattern") {
4039
+ const reqPattern = rule.matcher.context?.requiresPattern;
4040
+ if (reqPattern !== void 0) {
4041
+ try {
4042
+ const reqRe = compileCached(reqPattern, 0);
4043
+ matched = matched.filter((f) => reqRe.matcher(f.content).find());
4044
+ } catch (reqErr) {
4045
+ console.error(
4046
+ `[shipguard] requiresPattern compile error for rule ${rule.id}: ${reqErr instanceof Error ? reqErr.message : String(reqErr)} \u2014 fail closed`
4047
+ );
4048
+ requiresFailClosed = reqPattern;
4049
+ }
4050
+ }
4051
+ }
3709
4052
  for (const file of matched) {
3710
4053
  let canonicalFindings;
3711
4054
  try {
3712
- canonicalFindings = activeExecutor.evaluate(
4055
+ canonicalFindings = requiresFailClosed !== void 0 ? [{
4056
+ line: 1,
4057
+ column: 1,
4058
+ evidence: `requiresPattern "${requiresFailClosed}" (compile error \u2014 fail closed)`,
4059
+ suppressionState: "active",
4060
+ matcherType: "pattern"
4061
+ }] : activeExecutor.evaluate(
3713
4062
  matcherForExecutor,
3714
4063
  { relativePath: file.relativePath, content: file.content },
3715
4064
  ctx
@@ -3799,8 +4148,10 @@ function runProRulesWithDispatch(rules, files, policy, cliVersion, table, manife
3799
4148
 
3800
4149
  export {
3801
4150
  goLink,
4151
+ compileDetectorRegex,
3802
4152
  getFindingKey,
3803
4153
  redactFindingsEvidence,
4154
+ looksFakeKey,
3804
4155
  secretsCheck,
3805
4156
  authCheck,
3806
4157
  databaseCheck,