xploitscan-shared-rules 2.4.24 → 2.4.26

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,5 +1,5 @@
1
1
  // src/version.ts
2
- var SCANNER_VERSION = "2.4.24";
2
+ var SCANNER_VERSION = "2.4.26";
3
3
 
4
4
  // src/snippet.ts
5
5
  var cacheContent = null;
@@ -1939,230 +1939,2774 @@ function checkIntent(files, findings) {
1939
1939
  return { statements, mismatches, sources, unchallenged, uncheckable };
1940
1940
  }
1941
1941
 
1942
- // src/auth-scope.ts
1943
- var GUARD_NAMES = ["requireAdmin", "requireMember", "requireRole", "requireUser", "verifyToken", "verifyAdmin"];
1944
- var PUBLIC_LAST = /^(?:login|logout|signup|register|forgot(?:-password)?|reset(?:-password)?|callback)$/i;
1945
- var SIDE_EFFECT_RE = /\.(?:save|deleteMany|deleteOne|updateMany|updateOne|createMany|findMany|findOne|findUnique|findFirst|findByIdAndDelete|findByIdAndUpdate|remove|destroy|delete|update|create|insert|insertOne|upsert)\s*\(|\.(?:query|execute|exec|rm)\s*\(|\b(?:kv|redis)\s*\.\s*(?:set|del)\s*\(|\bsql\s*`|\bfetch\s*\(|\b(?:readFileSync|readFile|writeFileSync|writeFile|createReadStream|unlinkSync|unlink|mkdirSync|mkdir|execFileSync|execFile|spawn)\s*\(|\bcookies\s*\(\s*\)\s*\.\s*set\s*\(|\bres\s*\.\s*(?:json|send|redirect|end)\s*\(|\bres\s*\.\s*status\s*\([^)]*\)\s*\.\s*(?:json|send|end)\s*\(|\breturn\b/g;
1946
- function blankComments(content) {
1947
- let open = content.indexOf("/*");
1948
- let blocked = content;
1949
- if (open !== -1) {
1950
- const parts = [];
1951
- let copied = 0;
1952
- while (open !== -1) {
1953
- const close = content.indexOf("*/", open + 2);
1954
- if (close === -1) break;
1955
- parts.push(content.slice(copied, open), content.slice(open, close + 2).replace(/[^\n]/g, " "));
1956
- copied = close + 2;
1957
- open = content.indexOf("/*", copied);
1942
+ // src/structural-handlers.ts
1943
+ import _traverse from "@babel/traverse";
1944
+
1945
+ // src/ast/parse.ts
1946
+ import { parse } from "@babel/parser";
1947
+ var MAX_CACHE = 256;
1948
+ var cache = /* @__PURE__ */ new Map();
1949
+ function cacheKey(filename, digest2) {
1950
+ return `${filename}:${digest2}`;
1951
+ }
1952
+ function fullDigest(s) {
1953
+ let h1 = 5381;
1954
+ let h2 = 52711;
1955
+ for (let i = 0; i < s.length; i++) {
1956
+ const c = s.charCodeAt(i);
1957
+ h1 = Math.imul(h1, 33) + c | 0;
1958
+ h2 = Math.imul(h2, 31) + c | 0;
1959
+ }
1960
+ return `${s.length}:${h1}:${h2}`;
1961
+ }
1962
+ function pickLanguage(filename) {
1963
+ if (/\.tsx$/i.test(filename)) return "tsx";
1964
+ if (/\.jsx$/i.test(filename)) return "jsx";
1965
+ if (/\.(ts|cts|mts)$/i.test(filename)) return "ts";
1966
+ if (/\.(js|cjs|mjs)$/i.test(filename)) return "js";
1967
+ return null;
1968
+ }
1969
+ function parseFile(content, filename) {
1970
+ const lang = pickLanguage(filename);
1971
+ if (!lang) return null;
1972
+ if (!content || content.length === 0) return null;
1973
+ const key = cacheKey(filename, fullDigest(content));
1974
+ const hit = cache.get(key);
1975
+ if (hit && hit.content === content) return hit.value;
1976
+ const plugins = [];
1977
+ if (lang === "ts" || lang === "tsx") plugins.push("typescript");
1978
+ if (lang === "jsx" || lang === "tsx") plugins.push("jsx");
1979
+ plugins.push("decorators-legacy", "classProperties", "dynamicImport", "topLevelAwait");
1980
+ let ast = null;
1981
+ try {
1982
+ ast = parse(content, {
1983
+ sourceType: "unambiguous",
1984
+ allowImportExportEverywhere: true,
1985
+ allowReturnOutsideFunction: true,
1986
+ allowAwaitOutsideFunction: true,
1987
+ allowUndeclaredExports: true,
1988
+ errorRecovery: true,
1989
+ plugins
1990
+ });
1991
+ } catch {
1992
+ cache.set(key, { content, value: null });
1993
+ if (cache.size > MAX_CACHE) {
1994
+ const firstKey = cache.keys().next().value;
1995
+ if (firstKey !== void 0) cache.delete(firstKey);
1958
1996
  }
1959
- parts.push(content.slice(copied));
1960
- blocked = parts.join("");
1997
+ return null;
1998
+ }
1999
+ const entry = { ast, language: lang };
2000
+ cache.set(key, { content, value: entry });
2001
+ if (cache.size > MAX_CACHE) {
2002
+ const firstKey = cache.keys().next().value;
2003
+ if (firstKey !== void 0) cache.delete(firstKey);
1961
2004
  }
1962
- return blocked.replace(/(^|[^:])\/\/[^\n]*/gm, (m, lead) => lead + " ".repeat(m.length - lead.length));
2005
+ return entry;
1963
2006
  }
1964
- function matchingCloser(text, open, openCh, closeCh) {
1965
- let depth = 0;
1966
- let quote = "";
1967
- for (let i = open; i < text.length; i++) {
1968
- const c = text[i];
1969
- if (quote) {
1970
- if (c === "\\") {
1971
- i++;
1972
- continue;
1973
- }
1974
- if (c === quote) quote = "";
2007
+
2008
+ // src/structural-handlers.ts
2009
+ var traverse = typeof _traverse === "function" ? _traverse : _traverse.default;
2010
+ var PARSE_BYTES = 256 * 1024;
2011
+ var LOOKUP_LIMIT = 200;
2012
+ var METHODS = /* @__PURE__ */ new Set(["get", "head", "post", "put", "patch", "delete"]);
2013
+ var ROLE_WORD = /^(admin|superadmin|staff|owner)$/i;
2014
+ var faultName = null;
2015
+ var parseCount = 0;
2016
+ var modelCache = /* @__PURE__ */ new Map();
2017
+ var bearerSpanCache = /* @__PURE__ */ new Map();
2018
+ function setStructuralFaultForTest(name) {
2019
+ faultName = name;
2020
+ }
2021
+ function structuralParseCount() {
2022
+ return parseCount;
2023
+ }
2024
+ function resetStructuralState() {
2025
+ parseCount = 0;
2026
+ modelCache.clear();
2027
+ bearerSpanCache.clear();
2028
+ faultName = null;
2029
+ }
2030
+ function fault(name) {
2031
+ if (faultName === name || faultName === "all") throw new Error("injected");
2032
+ }
2033
+ function digest(text) {
2034
+ let h1 = 5381;
2035
+ let h2 = 52711;
2036
+ for (let i = 0; i < text.length; i++) {
2037
+ const c = text.charCodeAt(i);
2038
+ h1 = Math.imul(h1, 33) + c | 0;
2039
+ h2 = Math.imul(h2, 31) + c | 0;
2040
+ }
2041
+ return `${text.length}:${h1}:${h2}`;
2042
+ }
2043
+ function lineAt(content, index) {
2044
+ let line = 1;
2045
+ const end = Math.min(index, content.length);
2046
+ for (let i = 0; i < end; i++) if (content.charCodeAt(i) === 10) line++;
2047
+ return line;
2048
+ }
2049
+ function unwrap(node) {
2050
+ let cur = node;
2051
+ while (cur) {
2052
+ if (cur.type === "AwaitExpression" || cur.type === "ParenthesizedExpression" || cur.type === "TSAsExpression" || cur.type === "TSNonNullExpression" || cur.type === "TSSatisfiesExpression" || cur.type === "TSTypeAssertion" || cur.type === "ChainExpression") {
2053
+ cur = cur.expression ?? cur.argument;
1975
2054
  continue;
1976
2055
  }
1977
- if (c === "'" || c === '"' || c === "`") {
1978
- quote = c;
2056
+ break;
2057
+ }
2058
+ return cur;
2059
+ }
2060
+ function propName(prop) {
2061
+ if (!prop) return "";
2062
+ if (prop.key?.type === "Identifier" && !prop.computed) return String(prop.key.name);
2063
+ if (prop.key?.type === "StringLiteral") return String(prop.key.value);
2064
+ return "";
2065
+ }
2066
+ function walk(node, visit) {
2067
+ if (!node || typeof node !== "object" || !node.type) return;
2068
+ visit(node);
2069
+ for (const key of Object.keys(node)) {
2070
+ if (key === "loc" || key === "start" || key === "end" || key === "range" || key === "leadingComments" || key === "trailingComments" || key === "innerComments") {
1979
2071
  continue;
1980
2072
  }
1981
- if (c === openCh) depth++;
1982
- else if (c === closeCh) {
1983
- depth--;
1984
- if (depth === 0) return i;
2073
+ const child = node[key];
2074
+ if (Array.isArray(child)) {
2075
+ for (const item of child) if (item && typeof item === "object" && item.type) walk(item, visit);
2076
+ } else if (child && typeof child === "object" && child.type) {
2077
+ walk(child, visit);
1985
2078
  }
1986
2079
  }
1987
- return -1;
1988
2080
  }
1989
- function firstSideEffect(handler) {
1990
- SIDE_EFFECT_RE.lastIndex = 0;
1991
- const match = SIDE_EFFECT_RE.exec(handler);
1992
- return match ? match.index : -1;
2081
+ function paramNames(fn) {
2082
+ const names = [];
2083
+ for (const param of fn.params ?? []) {
2084
+ if (param?.type === "Identifier") names.push(param.name);
2085
+ else if (param?.type === "AssignmentPattern" && param.left?.type === "Identifier") names.push(param.left.name);
2086
+ else if (param?.type === "ObjectPattern") {
2087
+ for (const prop of param.properties ?? []) {
2088
+ if (prop?.type === "ObjectProperty" && prop.key?.type === "Identifier") names.push(prop.key.name);
2089
+ }
2090
+ }
2091
+ }
2092
+ return names;
1993
2093
  }
1994
- function beforeSideEffect(handler, index) {
1995
- const at = firstSideEffect(handler);
1996
- return at === -1 || index < at;
2094
+ function statementsOf(fn) {
2095
+ const body = fn?.body;
2096
+ if (!body) return [];
2097
+ if (body.type === "BlockStatement") return body.body ?? [];
2098
+ return [{ type: "ReturnStatement", argument: body, start: body.start, end: body.end }];
2099
+ }
2100
+ function usable(parsed, content) {
2101
+ if (!parsed?.ast) return false;
2102
+ const ast = parsed.ast;
2103
+ if (Array.isArray(ast.errors) && ast.errors.length > 0) return false;
2104
+ if (typeof ast.end === "number" && ast.end !== content.length) return false;
2105
+ return true;
1997
2106
  }
1998
- function localGuardBody(content, name) {
1999
- const fn = new RegExp(`\\b(?:async\\s+)?function\\s+${name}\\s*\\([^)]*\\)\\s*\\{`).exec(content);
2000
- if (fn && fn.index !== void 0) {
2001
- const brace = content.indexOf("{", fn.index);
2002
- const end = matchingCloser(content, brace, "{", "}");
2003
- return end < 0 ? "" : content.slice(brace + 1, end);
2107
+ function controlScope(path) {
2108
+ let cur = path?.parentPath;
2109
+ while (cur) {
2110
+ const t = cur.node?.type;
2111
+ if (t === "IfStatement" || t === "ForStatement" || t === "WhileStatement" || t === "DoWhileStatement" || t === "ForInStatement" || t === "ForOfStatement" || t === "SwitchStatement" || t === "TryStatement" || t === "CatchClause" || t === "ConditionalExpression") {
2112
+ return null;
2113
+ }
2114
+ if (t === "FunctionDeclaration" || t === "FunctionExpression" || t === "ArrowFunctionExpression" || t === "ObjectMethod" || t === "ClassMethod") {
2115
+ return cur.node.start ?? 0;
2116
+ }
2117
+ if (t === "Program") return 0;
2118
+ cur = cur.parentPath;
2004
2119
  }
2005
- const arrow = new RegExp(
2006
- `\\b(?:const|let|var)\\s+${name}\\s*=\\s*(?:async\\s*)?(?:function\\s*\\([^)]*\\)|(?:\\([^)]*\\)|[A-Za-z_]\\w*)\\s*=>)`
2007
- ).exec(content);
2008
- if (!arrow || arrow.index === void 0) return null;
2009
- const after = arrow.index + arrow[0].length;
2010
- const rest = content.slice(after);
2011
- if (/^\s*\{/.test(rest)) {
2012
- const brace = content.indexOf("{", after);
2013
- const end = matchingCloser(content, brace, "{", "}");
2014
- return end < 0 ? "" : content.slice(brace + 1, end);
2120
+ return 0;
2121
+ }
2122
+ function stringEntries(node) {
2123
+ const value = unwrap(node);
2124
+ if (!value) return null;
2125
+ let array = value;
2126
+ if (value.type === "NewExpression" && value.callee?.type === "Identifier" && value.callee.name === "Set") {
2127
+ if ((value.arguments ?? []).length !== 1) return null;
2128
+ array = value.arguments[0];
2015
2129
  }
2016
- const semi = content.indexOf(";", after);
2017
- return content.slice(after, semi === -1 ? content.length : semi);
2130
+ if (array?.type !== "ArrayExpression") return null;
2131
+ const entries = [];
2132
+ for (const el of array.elements ?? []) {
2133
+ if (!el || el.type !== "StringLiteral") return null;
2134
+ entries.push(String(el.value));
2135
+ }
2136
+ return entries.length > 0 ? entries : null;
2018
2137
  }
2019
- function guardBodyQualifies(body) {
2020
- const flat = body.replace(/\s+/g, " ").trim();
2021
- if (!flat) return false;
2022
- if (/^(?:return\s+)?next\s*\(\s*\)\s*;?$/.test(flat)) return false;
2023
- return /\bthrow\b|\bredirect\s*\(|\bauth\s*\(|\bgetServerSession\s*\(|\bgetUser\s*\(|\bjwt\s*\.\s*verify\s*\(|\b(?:status(?:Code)?|sendStatus)\s*[:(]\s*40[13]\b/.test(body);
2138
+ function staticString(node) {
2139
+ const value = unwrap(node);
2140
+ if (!value) return null;
2141
+ if (value.type === "StringLiteral") return String(value.value);
2142
+ if (value.type === "TemplateLiteral" && (value.expressions ?? []).length === 0) {
2143
+ return value.quasis.map((q) => q.value?.cooked ?? "").join("");
2144
+ }
2145
+ return null;
2024
2146
  }
2025
- function guardNameCounts(content, name) {
2026
- const body = localGuardBody(content, name);
2027
- if (body === null) return true;
2028
- return guardBodyQualifies(body);
2147
+ function isProcessEnv(node) {
2148
+ const value = unwrap(node);
2149
+ if (value?.type !== "MemberExpression" || value.computed) return false;
2150
+ if (value.property?.type !== "Identifier") return false;
2151
+ const env = value.object;
2152
+ return env?.type === "MemberExpression" && !env.computed && env.property?.name === "env" && env.object?.type === "Identifier" && env.object.name === "process";
2029
2153
  }
2030
- function guardMentioned(content, args) {
2031
- return GUARD_NAMES.some((name) => new RegExp(`\\b${name}\\b`).test(args) && guardNameCounts(content, name));
2154
+ function isEnvRead(node) {
2155
+ const value = unwrap(node);
2156
+ if (!value) return false;
2157
+ if (value.type === "MemberExpression") {
2158
+ if (value.object?.type === "Identifier" && value.object.name === "process" && value.property?.name === "env") return true;
2159
+ if (isProcessEnv(value)) return true;
2160
+ if (value.object?.type === "Identifier" && value.object.name === "env") return true;
2161
+ if (value.object?.type === "MemberExpression" && value.object.property?.name === "env" && (value.object.object?.name === "Deno" || value.object.object?.name === "Bun")) {
2162
+ return true;
2163
+ }
2164
+ if (value.object?.type === "MetaProperty" && value.property?.name === "env") return true;
2165
+ }
2166
+ if (value.type === "CallExpression" && value.callee?.type === "MemberExpression" && value.callee.property?.name === "get" && value.callee.object?.type === "MemberExpression" && value.callee.object.property?.name === "env") {
2167
+ return true;
2168
+ }
2169
+ return false;
2032
2170
  }
2033
- function handlerBodyOpen(handler) {
2034
- const arrow = handler.search(/=>\s*\{/);
2035
- const fn = handler.search(/\)\s*\{/);
2036
- const at = [arrow, fn].filter((index) => index >= 0);
2037
- if (at.length === 0) return handler.indexOf("{");
2038
- return handler.indexOf("{", Math.min(...at));
2171
+ function registrationOk(content, start, method, appRouter) {
2172
+ const slice = content.slice(start, start + 160).replace(/^\s+/, "");
2173
+ if (appRouter) return new RegExp(`^export\\s+(?:async\\s+)?function\\s+${method}\\b`).test(slice);
2174
+ return new RegExp(`^[A-Za-z_$][\\w$]*\\s*\\.\\s*${method}\\s*\\(`, "i").test(slice);
2175
+ }
2176
+ function pushHandler(handlers, content, fn, method, path, receiver, line, regStart, routeArgs, appRouter, scope) {
2177
+ if (typeof fn?.start !== "number" || typeof fn?.end !== "number") return;
2178
+ if (!registrationOk(content, regStart, appRouter ? method.toUpperCase() : method, appRouter)) return;
2179
+ const params = paramNames(fn);
2180
+ handlers.push({
2181
+ method,
2182
+ path,
2183
+ receiver,
2184
+ line,
2185
+ fnStart: fn.start,
2186
+ fnEnd: fn.end,
2187
+ regStart,
2188
+ params,
2189
+ statements: statementsOf(fn),
2190
+ fn,
2191
+ appRouter,
2192
+ routeArgs,
2193
+ scope,
2194
+ requestName: params[0] ?? "req",
2195
+ replyName: params[1] ?? "res"
2196
+ });
2039
2197
  }
2040
- function guardStatementCounts(handler, callIndex) {
2041
- const bodyOpen = handlerBodyOpen(handler);
2042
- if (bodyOpen < 0 || callIndex <= bodyOpen) return false;
2043
- let brace = 0;
2044
- let paren = 0;
2045
- let bracket = 0;
2046
- let quote = "";
2047
- let stmtStart = bodyOpen + 1;
2048
- for (let i = bodyOpen; i < callIndex; i++) {
2049
- const c = handler[i];
2050
- if (quote) {
2051
- if (c === "\\") {
2052
- i++;
2053
- continue;
2198
+ function build(parsed, content) {
2199
+ const ast = parsed.ast;
2200
+ const handlers = [];
2201
+ const uses = [];
2202
+ const functions = [];
2203
+ const consts = /* @__PURE__ */ new Set();
2204
+ const assigned = /* @__PURE__ */ new Set();
2205
+ traverse(ast, {
2206
+ FunctionExpression(path) {
2207
+ const node = path.node;
2208
+ if (typeof node.start === "number" && typeof node.end === "number") functions.push({ start: node.start, end: node.end });
2209
+ },
2210
+ ArrowFunctionExpression(path) {
2211
+ const node = path.node;
2212
+ if (typeof node.start === "number" && typeof node.end === "number") functions.push({ start: node.start, end: node.end });
2213
+ },
2214
+ VariableDeclaration(path) {
2215
+ if (path.node.kind !== "const") return;
2216
+ for (const decl of path.node.declarations ?? []) {
2217
+ if (decl?.id?.type === "Identifier") consts.add(decl.id.name);
2054
2218
  }
2055
- if (c === quote) quote = "";
2056
- continue;
2219
+ },
2220
+ AssignmentExpression(path) {
2221
+ if (path.node.left?.type === "Identifier") assigned.add(path.node.left.name);
2222
+ },
2223
+ FunctionDeclaration(path) {
2224
+ const node = path.node;
2225
+ if (typeof node.start === "number" && typeof node.end === "number") functions.push({ start: node.start, end: node.end });
2226
+ if (path.parent?.type !== "ExportNamedDeclaration") return;
2227
+ const name = path.node.id?.name;
2228
+ if (!name || !/^(GET|HEAD|POST|PUT|PATCH|DELETE)$/.test(name)) return;
2229
+ const reg = path.parent;
2230
+ pushHandler(
2231
+ handlers,
2232
+ content,
2233
+ path.node,
2234
+ name.toLowerCase(),
2235
+ "",
2236
+ "",
2237
+ reg.loc?.start?.line ?? path.node.loc?.start?.line ?? 0,
2238
+ reg.start ?? path.node.start,
2239
+ [],
2240
+ true,
2241
+ 0
2242
+ );
2243
+ },
2244
+ CallExpression(path) {
2245
+ const node = path.node;
2246
+ const callee = node.callee;
2247
+ const deno = callee?.type === "MemberExpression" && callee.object?.name === "Deno" && callee.property?.name === "serve" || callee?.type === "Identifier" && callee.name === "serve";
2248
+ if (deno) {
2249
+ const args2 = node.arguments ?? [];
2250
+ const last2 = args2[args2.length - 1];
2251
+ if (last2?.type === "FunctionExpression" || last2?.type === "ArrowFunctionExpression") {
2252
+ pushHandler(handlers, content, last2, "serve", "", "Deno", node.loc?.start?.line ?? 0, node.start ?? 0, args2.slice(0, -1), false, controlScope(path) ?? 0);
2253
+ }
2254
+ return;
2255
+ }
2256
+ if (callee?.type !== "MemberExpression" || callee.computed || callee.optional) return;
2257
+ if (callee.object?.type !== "Identifier" || callee.property?.type !== "Identifier") return;
2258
+ const method = String(callee.property.name);
2259
+ const receiver = String(callee.object.name);
2260
+ if (method === "use") {
2261
+ uses.push({
2262
+ receiver,
2263
+ start: node.start ?? 0,
2264
+ args: node.arguments ?? [],
2265
+ scope: controlScope(path),
2266
+ constReceiver: consts.has(receiver) && !assigned.has(receiver)
2267
+ });
2268
+ return;
2269
+ }
2270
+ const lower = method.toLowerCase();
2271
+ if (!METHODS.has(lower)) return;
2272
+ const args = node.arguments ?? [];
2273
+ const last = args[args.length - 1];
2274
+ if (last?.type !== "FunctionExpression" && last?.type !== "ArrowFunctionExpression") return;
2275
+ const pathArg = args[0];
2276
+ const routePath = pathArg?.type === "StringLiteral" ? String(pathArg.value) : staticString(pathArg) ?? "";
2277
+ pushHandler(
2278
+ handlers,
2279
+ content,
2280
+ last,
2281
+ lower,
2282
+ routePath,
2283
+ receiver,
2284
+ node.loc?.start?.line ?? 0,
2285
+ node.start ?? 0,
2286
+ args.slice(0, -1),
2287
+ false,
2288
+ controlScope(path) ?? 0
2289
+ );
2057
2290
  }
2058
- if (c === "'" || c === '"' || c === "`") {
2059
- quote = c;
2060
- continue;
2291
+ });
2292
+ for (const use of uses) use.constReceiver = consts.has(use.receiver) && !assigned.has(use.receiver);
2293
+ return {
2294
+ ast,
2295
+ handlers,
2296
+ uses,
2297
+ functions,
2298
+ sets: moduleSets(ast),
2299
+ primitives: modulePrimitives(ast),
2300
+ cryptoName: importedName(ast, ["crypto", "node:crypto"]),
2301
+ hasherNames: importedNames(ast, ["bcrypt", "bcryptjs", "argon2"]),
2302
+ hashFns: hashFunctions(ast, importedName(ast, ["crypto", "node:crypto"])),
2303
+ randomNames: randomBindings(ast, importedName(ast, ["crypto", "node:crypto"]))
2304
+ };
2305
+ }
2306
+ function topLevel(ast) {
2307
+ const out = [];
2308
+ for (const stmt of ast.program?.body ?? []) {
2309
+ if (stmt?.type === "ExportNamedDeclaration" && stmt.declaration) out.push(stmt.declaration);
2310
+ else out.push(stmt);
2311
+ }
2312
+ return out;
2313
+ }
2314
+ function moduleSets(ast) {
2315
+ const sets = /* @__PURE__ */ new Map();
2316
+ for (const stmt of topLevel(ast)) {
2317
+ if (stmt?.type !== "VariableDeclaration" || stmt.kind !== "const") continue;
2318
+ for (const decl of stmt.declarations ?? []) {
2319
+ if (decl?.id?.type !== "Identifier") continue;
2320
+ const entries = stringEntries(decl.init);
2321
+ if (!entries) continue;
2322
+ if (entries.every((entry) => publicHttpsUrl(httpsHost(entry)))) sets.set(decl.id.name, entries);
2061
2323
  }
2062
- if (c === "{") {
2063
- brace++;
2064
- if (brace === 1) stmtStart = i + 1;
2065
- } else if (c === "}") {
2066
- brace--;
2067
- if (brace === 1) stmtStart = i + 1;
2068
- } else if (c === "(") paren++;
2069
- else if (c === ")") paren--;
2070
- else if (c === "[") bracket++;
2071
- else if (c === "]") bracket--;
2072
- else if (c === ";" && brace === 1 && paren === 0 && bracket === 0) stmtStart = i + 1;
2073
2324
  }
2074
- if (brace !== 1 || paren !== 0 || bracket !== 0) return false;
2075
- const stmt = handler.slice(stmtStart, callIndex);
2076
- if (/&&|\|\||\?\?|\?(?!\.)/.test(stmt)) return false;
2077
- if (/\b(?:if|while|for|switch)\b/.test(stmt)) return false;
2078
- if (!/\b(?:const|let|var)\b|=/.test(stmt)) return true;
2079
- const assigned = /\b(?:const|let|var)\s+([A-Za-z_$][\w$]*)/.exec(stmt)?.[1] ?? /([A-Za-z_$][\w$]*)\s*=\s*(?:await\s*)?$/.exec(stmt)?.[1];
2080
- if (!assigned) return false;
2081
- return new RegExp(`\\b${assigned}\\b`).test(handler.slice(callIndex + 1));
2325
+ const mutated = /* @__PURE__ */ new Set();
2326
+ walk(ast, (node) => {
2327
+ if (node.type === "AssignmentExpression" && node.left?.type === "Identifier" && sets.has(node.left.name)) mutated.add(node.left.name);
2328
+ if (node.type === "CallExpression" && node.callee?.type === "MemberExpression" && node.callee.object?.type === "Identifier") {
2329
+ const name = node.callee.property?.name;
2330
+ if ((name === "add" || name === "delete" || name === "clear" || name === "push") && sets.has(node.callee.object.name)) {
2331
+ mutated.add(node.callee.object.name);
2332
+ }
2333
+ }
2334
+ });
2335
+ for (const name of mutated) sets.delete(name);
2336
+ return sets;
2082
2337
  }
2083
- function guardCallBeforeSideEffect(content, handler) {
2084
- const re = new RegExp(`\\b(${GUARD_NAMES.join("|")})\\s*\\(`, "g");
2085
- let match;
2086
- while (match = re.exec(handler)) {
2087
- const pre = handler.slice(Math.max(0, match.index - 24), match.index);
2088
- if (/\bfunction\s+$/.test(pre)) continue;
2089
- if (!beforeSideEffect(handler, match.index)) continue;
2090
- if (!guardStatementCounts(handler, match.index)) continue;
2091
- if (guardNameCounts(content, match[1])) return true;
2338
+ function httpsHost(host) {
2339
+ return host.includes("://") ? host : `https://${host}`;
2340
+ }
2341
+ function modulePrimitives(ast) {
2342
+ const names = /* @__PURE__ */ new Set();
2343
+ for (const stmt of topLevel(ast)) {
2344
+ if (stmt?.type !== "VariableDeclaration" || stmt.kind !== "const") continue;
2345
+ for (const decl of stmt.declarations ?? []) {
2346
+ const init = unwrap(decl?.init);
2347
+ if (decl?.id?.type === "Identifier" && init && (init.type === "StringLiteral" || init.type === "NumericLiteral" || init.type === "BooleanLiteral")) {
2348
+ names.add(decl.id.name);
2349
+ }
2350
+ }
2092
2351
  }
2093
- return false;
2352
+ return names;
2094
2353
  }
2095
- function routeArgsQualify(content, handler) {
2096
- const match = handler.match(/\.(?:get|post|put|patch|delete|all)\s*\(\s*["'`][^"'`]+["'`]\s*,/i);
2097
- if (!match || match.index === void 0) return false;
2098
- const start = match.index + match[0].length;
2099
- const brace = handler.indexOf("{", start);
2100
- const args = handler.slice(start, brace === -1 ? handler.length : brace);
2101
- return guardMentioned(content, args);
2354
+ function importedName(ast, sources) {
2355
+ const names = importedNames(ast, sources);
2356
+ return names.values().next().value ?? null;
2102
2357
  }
2103
- function authPrefixCovers(prefix, path) {
2104
- const normalized = prefix.length > 1 ? prefix.replace(/\/+$/, "") : prefix;
2105
- return path === normalized || path.startsWith(normalized + "/");
2358
+ function importedNames(ast, sources) {
2359
+ const names = /* @__PURE__ */ new Set();
2360
+ const accept = new Set(sources);
2361
+ for (const stmt of ast.program?.body ?? []) {
2362
+ if (stmt?.type === "ImportDeclaration" && accept.has(String(stmt.source?.value))) {
2363
+ for (const spec of stmt.specifiers ?? []) {
2364
+ if (spec.type === "ImportDefaultSpecifier" || spec.type === "ImportNamespaceSpecifier") names.add(spec.local.name);
2365
+ }
2366
+ }
2367
+ if (stmt?.type === "VariableDeclaration") {
2368
+ for (const decl of stmt.declarations ?? []) {
2369
+ const init = unwrap(decl?.init);
2370
+ if (decl?.id?.type !== "Identifier" || init?.type !== "CallExpression") continue;
2371
+ if (init.callee?.type !== "Identifier" || init.callee.name !== "require") continue;
2372
+ const arg = init.arguments?.[0];
2373
+ if (arg?.type === "StringLiteral" && accept.has(String(arg.value))) names.add(decl.id.name);
2374
+ }
2375
+ }
2376
+ }
2377
+ return names;
2106
2378
  }
2107
- function useCoversRoute(content, index) {
2379
+ function isCreateHashChain(node, param, cryptoName) {
2380
+ const digest2 = unwrap(node);
2381
+ if (digest2?.type !== "CallExpression" || digest2.callee?.type !== "MemberExpression" || digest2.callee.property?.name !== "digest") return false;
2382
+ const digestArgs = digest2.arguments ?? [];
2383
+ if (digestArgs.length > 1) return false;
2384
+ if (digestArgs.length === 1 && digestArgs[0]?.type !== "StringLiteral") return false;
2385
+ const update = digest2.callee.object;
2386
+ if (update?.type !== "CallExpression" || update.callee?.type !== "MemberExpression" || update.callee.property?.name !== "update") return false;
2387
+ if ((update.arguments ?? []).length !== 1 || update.arguments[0]?.type !== "Identifier" || update.arguments[0].name !== param) return false;
2388
+ const created = update.callee.object;
2389
+ if (created?.type !== "CallExpression" || created.callee?.type !== "MemberExpression") return false;
2390
+ if (created.callee.property?.name !== "createHash" || created.callee.object?.name !== cryptoName) return false;
2391
+ return (created.arguments ?? []).length === 1 && created.arguments[0]?.type === "StringLiteral";
2392
+ }
2393
+ function hashFunctions(ast, cryptoName) {
2394
+ const names = /* @__PURE__ */ new Set();
2395
+ if (!cryptoName) return names;
2396
+ walk(ast, (node) => {
2397
+ if (node.type === "FunctionDeclaration" && node.id?.name && hashBody(node, cryptoName)) names.add(node.id.name);
2398
+ if (node.type === "VariableDeclarator" && node.id?.type === "Identifier") {
2399
+ const init = node.init;
2400
+ if ((init?.type === "ArrowFunctionExpression" || init?.type === "FunctionExpression") && hashBody(init, cryptoName)) names.add(node.id.name);
2401
+ }
2402
+ });
2403
+ return names;
2404
+ }
2405
+ function hashBody(fn, cryptoName) {
2406
+ if ((fn.params ?? []).length !== 1 || fn.params[0]?.type !== "Identifier") return false;
2407
+ const param = fn.params[0].name;
2408
+ let body = fn.body;
2409
+ if (body?.type === "BlockStatement") {
2410
+ if ((body.body ?? []).length !== 1 || body.body[0]?.type !== "ReturnStatement") return false;
2411
+ body = body.body[0].argument;
2412
+ }
2413
+ return isCreateHashChain(body, param, cryptoName);
2414
+ }
2415
+ function randomBindings(ast, cryptoName) {
2416
+ const names = /* @__PURE__ */ new Set();
2417
+ if (!cryptoName) return names;
2418
+ walk(ast, (node) => {
2419
+ if (node.type !== "VariableDeclarator" || node.id?.type !== "Identifier") return;
2420
+ if (isRandomBytes(unwrap(node.init), cryptoName)) names.add(node.id.name);
2421
+ });
2422
+ return names;
2423
+ }
2424
+ function isRandomBytes(node, cryptoName) {
2425
+ let call = node;
2426
+ if (call?.type === "CallExpression" && call.callee?.type === "MemberExpression" && call.callee.property?.name === "toString") {
2427
+ call = call.callee.object;
2428
+ }
2429
+ if (call?.type !== "CallExpression" || call.callee?.type !== "MemberExpression" || call.callee.property?.name !== "randomBytes") return false;
2430
+ if (call.callee.object?.name !== cryptoName) return false;
2431
+ const n = call.arguments?.[0];
2432
+ return n?.type === "NumericLiteral" && typeof n.value === "number" && n.value >= 16 && (call.arguments ?? []).length === 1;
2433
+ }
2434
+ function load(content, filePath) {
2435
+ fault("parse");
2436
+ if (content.length > PARSE_BYTES) return null;
2437
+ const key = `${filePath}\0${digest(content)}`;
2438
+ const hit = modelCache.get(key);
2439
+ if (hit && hit.content === content) return hit.model;
2440
+ parseCount += 1;
2441
+ const parsed = parseFile(content, filePath);
2442
+ const model = parsed && usable(parsed, content) ? build(parsed, content) : null;
2443
+ modelCache.set(key, { content, model });
2444
+ if (modelCache.size > 128) {
2445
+ const first = modelCache.keys().next().value;
2446
+ if (first !== void 0) modelCache.delete(first);
2447
+ }
2448
+ return model;
2449
+ }
2450
+ function onLine(model, content, index) {
2451
+ const line = lineAt(content, index);
2452
+ const found = model.handlers.filter((handler) => handler.line === line);
2453
+ return found.length === 1 ? found[0] : null;
2454
+ }
2455
+ function publicHttpsUrl(value) {
2456
+ try {
2457
+ fault("publicHttpsUrl");
2458
+ const url = new URL(value);
2459
+ if (url.protocol !== "https:") return false;
2460
+ if (url.username || url.password) return false;
2461
+ if (url.port !== "") return false;
2462
+ const host = url.hostname.toLowerCase().replace(/\.$/, "");
2463
+ if (!host || !host.includes(".")) return false;
2464
+ if (/^\d{1,3}(?:\.\d{1,3}){3}$/.test(host) || host.includes(":")) return false;
2465
+ if (host === "localhost" || host.endsWith(".localhost") || host.endsWith(".local") || host.endsWith(".internal") || host.endsWith(".lan") || host.endsWith(".home.arpa")) {
2466
+ return false;
2467
+ }
2468
+ return true;
2469
+ } catch {
2470
+ return false;
2471
+ }
2472
+ }
2473
+ function isReq(node, requestName) {
2474
+ const value = unwrap(node);
2475
+ return value?.type === "Identifier" && (value.name === requestName || value.name === "req" || value.name === "request" || value.name === "ctx");
2476
+ }
2477
+ function isRequestInput(node, requestName) {
2478
+ const value = unwrap(node);
2479
+ if (!value || value.type !== "MemberExpression" || value.computed) return false;
2480
+ const prop = value.property?.name;
2481
+ if (["query", "params", "body", "searchParams"].includes(prop) && isReq(value.object, requestName)) return true;
2482
+ return isRequestInput(value.object, requestName);
2483
+ }
2484
+ function hasIdentity(fn, requestName) {
2485
+ let bad = false;
2486
+ walk(fn, (node) => {
2487
+ if (node.type === "CallExpression") {
2488
+ if (node.callee?.type === "Identifier" && (node.callee.name === "cookies" || node.callee.name === "headers")) bad = true;
2489
+ if (node.callee?.type === "MemberExpression" && node.callee.property?.name === "get") {
2490
+ const arg = node.arguments?.[0];
2491
+ if (arg?.type === "StringLiteral" && /^(authorization|cookie|x-api-key)$/i.test(String(arg.value))) bad = true;
2492
+ }
2493
+ }
2494
+ if ((node.type === "MemberExpression" || node.type === "OptionalMemberExpression") && !node.computed) {
2495
+ const prop = node.property?.name;
2496
+ if (["user", "session", "cookies", "auth", "signedCookies"].includes(prop) && isReq(node.object, requestName)) bad = true;
2497
+ if (prop === "user" && node.object?.type === "MemberExpression" && node.object.property?.name === "state") bad = true;
2498
+ }
2499
+ });
2500
+ return bad;
2501
+ }
2502
+ function evalExpr(node, env, depth = 0) {
2503
+ if (!node || depth > 40) return "no";
2504
+ const value = unwrap(node);
2505
+ if (!value) return "no";
2506
+ if (value.type === "StringLiteral" || value.type === "NumericLiteral" || value.type === "BooleanLiteral" || value.type === "NullLiteral") return "value";
2507
+ if (value.type === "TemplateLiteral" && (value.expressions ?? []).length === 0) return "value";
2508
+ if (isEnvRead(value)) {
2509
+ env.bad = true;
2510
+ return "no";
2511
+ }
2512
+ if (value.type === "Identifier") {
2513
+ const known = env.allowed.get(value.name);
2514
+ if (known) return known;
2515
+ if (env.primitives.has(value.name)) return "value";
2516
+ return "no";
2517
+ }
2518
+ if (value.type === "MemberExpression" || value.type === "OptionalMemberExpression") {
2519
+ if (value.optional || value.type === "OptionalMemberExpression") return "no";
2520
+ if (value.computed) {
2521
+ if (isReq(value.property, env.requestName) || isRequestInput(value.property, env.requestName)) env.bad = true;
2522
+ return "no";
2523
+ }
2524
+ if (isRequestInput(value, env.requestName)) return "value";
2525
+ const obj = value.object;
2526
+ if (obj?.type === "Identifier" && env.allowed.get(obj.name) === "url" && (value.property?.name === "hostname" || value.property?.name === "href")) return "value";
2527
+ const inner = evalExpr(obj, env, depth + 1);
2528
+ if (inner === "value") return "value";
2529
+ return "no";
2530
+ }
2531
+ if (value.type === "NewExpression" && value.callee?.type === "Identifier" && value.callee.name === "URL") {
2532
+ if ((value.arguments ?? []).length < 1 || evalExpr(value.arguments[0], env, depth + 1) === "no") return "no";
2533
+ return "url";
2534
+ }
2535
+ if (value.type === "ObjectExpression") {
2536
+ for (const prop of value.properties ?? []) {
2537
+ if (prop?.type !== "ObjectProperty" || prop.computed) return "no";
2538
+ if (evalExpr(prop.value, env, depth + 1) === "no") return "no";
2539
+ }
2540
+ return "value";
2541
+ }
2542
+ if (value.type === "ArrayExpression") {
2543
+ for (const el of value.elements ?? []) if (!el || evalExpr(el, env, depth + 1) === "no") return "no";
2544
+ return "value";
2545
+ }
2546
+ if (value.type === "CallExpression" || value.type === "OptionalCallExpression") {
2547
+ if (value.optional || value.type === "OptionalCallExpression") return "no";
2548
+ return evalCall(value, env, depth);
2549
+ }
2550
+ return "no";
2551
+ }
2552
+ function argsAllowed(node, env, depth) {
2553
+ return (node.arguments ?? []).every((arg) => arg && evalExpr(arg, env, depth + 1) !== "no");
2554
+ }
2555
+ function callbackOk(fn, env) {
2556
+ if (!fn || fn.type !== "ArrowFunctionExpression" && fn.type !== "FunctionExpression") return false;
2557
+ const saved = new Map(env.allowed);
2558
+ const responded = env.responded;
2559
+ const bad = env.bad;
2560
+ for (const name of paramNames(fn)) env.allowed.set(name, "value");
2561
+ let ok = false;
2562
+ if (fn.body?.type === "BlockStatement") ok = (fn.body.body ?? []).every((stmt) => execStmt(stmt, env));
2563
+ else ok = evalExpr(fn.body, env) !== "no";
2564
+ env.allowed = saved;
2565
+ env.responded = responded;
2566
+ env.bad = bad;
2567
+ return ok;
2568
+ }
2569
+ function isReply(node, env) {
2570
+ const value = unwrap(node);
2571
+ return value?.type === "Identifier" && (value.name === "res" || value.name === "reply" || value.name === env.replyName);
2572
+ }
2573
+ function responseCall(node, env, depth) {
2574
+ if (node?.type === "NewExpression" && node.callee?.name === "Response") return argsAllowed(node, env, depth);
2575
+ if (node?.type !== "CallExpression") return false;
2576
+ const callee = node.callee;
2577
+ if (callee?.type === "MemberExpression" && callee.object?.type === "Identifier" && (callee.object.name === "NextResponse" || callee.object.name === "Response") && callee.property?.name === "json") {
2578
+ return argsAllowed(node, env, depth);
2579
+ }
2580
+ if (callee?.type !== "MemberExpression") return false;
2581
+ const prop = callee.property?.name;
2582
+ if (prop === "render") {
2583
+ if (!isReply(callee.object, env)) return false;
2584
+ if (node.arguments?.[0]?.type !== "StringLiteral") return false;
2585
+ return node.arguments.length < 2 || evalExpr(node.arguments[1], env, depth + 1) !== "no";
2586
+ }
2587
+ if (prop !== "json" && prop !== "send" && prop !== "end") return false;
2588
+ const target = callee.object;
2589
+ if (isReply(target, env)) return argsAllowed(node, env, depth);
2590
+ if (target?.type === "CallExpression" && target.callee?.type === "MemberExpression") {
2591
+ const inner = target.callee.property?.name;
2592
+ if ((inner === "status" || inner === "code") && isReply(target.callee.object, env) && target.arguments?.[0]?.type === "NumericLiteral") {
2593
+ return argsAllowed(node, env, depth);
2594
+ }
2595
+ }
2596
+ return false;
2597
+ }
2598
+ function urlBinding(node, env) {
2599
+ const value = unwrap(node);
2600
+ if (value?.type === "Identifier" && env.allowed.get(value.name) === "url") return value.name;
2601
+ if (value?.type === "MemberExpression" && !value.computed && value.property?.name === "href" && value.object?.type === "Identifier" && env.allowed.get(value.object.name) === "url") {
2602
+ return value.object.name;
2603
+ }
2604
+ if (value?.type === "CallExpression" && value.callee?.type === "MemberExpression" && value.callee.property?.name === "toString" && (value.arguments ?? []).length === 0 && value.callee.object?.type === "Identifier" && env.allowed.get(value.callee.object.name) === "url") {
2605
+ return value.callee.object.name;
2606
+ }
2607
+ return null;
2608
+ }
2609
+ var MODEL_PATH = /^\/(?:v\d+(?:beta\d*)?\/)?models\/?$/;
2610
+ function optionState(node) {
2611
+ if (!node) return "absent";
2612
+ if (node.type !== "ObjectExpression") return "bad";
2613
+ let secret = false;
2614
+ for (const prop of node.properties ?? []) {
2615
+ if (prop?.type !== "ObjectProperty" || prop.computed) return "bad";
2616
+ const key = propName(prop);
2617
+ if (key !== "headers" && key !== "cache" && key !== "next" && key !== "method") return "bad";
2618
+ if (key === "method") {
2619
+ const text = staticString(prop.value);
2620
+ if (text !== "GET" && text !== "HEAD" && text !== "get" && text !== "head") return "bad";
2621
+ continue;
2622
+ }
2623
+ if (key === "headers") {
2624
+ if (prop.value?.type !== "ObjectExpression") return "bad";
2625
+ for (const header of prop.value.properties ?? []) {
2626
+ if (header?.type !== "ObjectProperty" || header.computed || !literalValue(header.value)) secret = true;
2627
+ }
2628
+ continue;
2629
+ }
2630
+ if (staticString(prop.value) === null && prop.value?.type !== "NumericLiteral" && prop.value?.type !== "BooleanLiteral") secret = true;
2631
+ }
2632
+ return secret ? "secret" : "ok";
2633
+ }
2634
+ function literalValue(node) {
2635
+ const value = unwrap(node);
2636
+ if (!value) return false;
2637
+ if (value.type === "StringLiteral" || value.type === "NumericLiteral" || value.type === "BooleanLiteral" || value.type === "NullLiteral") return true;
2638
+ if (value.type === "TemplateLiteral") return (value.expressions ?? []).length === 0;
2639
+ if (value.type === "ObjectExpression") {
2640
+ return (value.properties ?? []).every((prop) => prop?.type === "ObjectProperty" && !prop.computed && literalValue(prop.value));
2641
+ }
2642
+ if (value.type === "ArrayExpression") return (value.elements ?? []).every((el) => Boolean(el) && literalValue(el));
2643
+ return false;
2644
+ }
2645
+ function evalCall(node, env, depth) {
2646
+ if (responseCall(node, env, depth)) {
2647
+ env.responded = true;
2648
+ return "value";
2649
+ }
2650
+ const callee = node.callee;
2651
+ if (callee?.type === "Identifier" && callee.name === "fetch") {
2652
+ const state = optionState(node.arguments?.[1]);
2653
+ if (state === "bad" || (node.arguments ?? []).length > 2) return "no";
2654
+ const secret = state === "secret";
2655
+ const literal = staticString(node.arguments?.[0]);
2656
+ if (literal !== null) {
2657
+ if (!publicHttpsUrl(literal)) return "no";
2658
+ if (secret) {
2659
+ const url = new URL(literal);
2660
+ if (url.search || url.hash || !MODEL_PATH.test(url.pathname)) return "no";
2661
+ }
2662
+ env.fetchSeen = true;
2663
+ return "fetch";
2664
+ }
2665
+ const binding = urlBinding(node.arguments?.[0], env);
2666
+ if (!binding || !env.rejected.has(binding) || secret) return "no";
2667
+ env.fetchSeen = true;
2668
+ return "fetch";
2669
+ }
2670
+ if (callee?.type === "Identifier" && (callee.name === "String" || callee.name === "Number" || callee.name === "Boolean")) {
2671
+ return argsAllowed(node, env, depth) ? "value" : "no";
2672
+ }
2673
+ if (callee?.type === "MemberExpression" && !callee.computed) {
2674
+ const obj = callee.object;
2675
+ const prop = callee.property?.name;
2676
+ if (obj?.type === "Identifier" && obj.name === "JSON" && (prop === "parse" || prop === "stringify")) return argsAllowed(node, env, depth) ? "value" : "no";
2677
+ if (obj?.type === "Identifier" && obj.name === "Object" && (prop === "keys" || prop === "values" || prop === "entries")) return argsAllowed(node, env, depth) ? "value" : "no";
2678
+ if (obj?.type === "Identifier" && obj.name === "Array" && prop === "isArray") return argsAllowed(node, env, depth) ? "value" : "no";
2679
+ if ((prop === "json" || prop === "text") && obj?.type === "Identifier" && env.allowed.get(obj.name) === "fetch") return "value";
2680
+ if ((prop === "has" || prop === "includes") && obj?.type === "Identifier" && env.sets.has(obj.name)) return "value";
2681
+ if ((prop === "map" || prop === "filter") && evalExpr(obj, env, depth + 1) === "value") return callbackOk(node.arguments?.[0], env) ? "value" : "no";
2682
+ if ((prop === "slice" || prop === "join" || prop === "toString") && evalExpr(obj, env, depth + 1) !== "no") return argsAllowed(node, env, depth) ? "value" : "no";
2683
+ }
2684
+ return "no";
2685
+ }
2686
+ function has4xx(node) {
2687
+ let number = false;
2688
+ let call = false;
2689
+ walk(node, (current) => {
2690
+ if (current.type === "NumericLiteral" && current.value >= 400 && current.value < 500) number = true;
2691
+ if (current.type === "CallExpression" && ["status", "code", "json", "send"].includes(current.callee?.property?.name)) call = true;
2692
+ });
2693
+ return number && call;
2694
+ }
2695
+ function rejectConsequent(node) {
2696
+ if (!node) return false;
2697
+ if (node.type === "BlockStatement") return (node.body ?? []).length === 1 && rejectConsequent(node.body[0]);
2698
+ if (node.type === "ThrowStatement") return true;
2699
+ if (node.type === "ReturnStatement" || node.type === "ExpressionStatement") {
2700
+ const value = node.argument ?? node.expression;
2701
+ return has4xx(value);
2702
+ }
2703
+ return false;
2704
+ }
2705
+ function allowlistIf(stmt, env) {
2706
+ if (stmt?.type !== "IfStatement" || stmt.alternate || env.fetchSeen) return false;
2707
+ const test = unwrap(stmt.test);
2708
+ if (test?.type !== "UnaryExpression" || test.operator !== "!") return false;
2709
+ const call = unwrap(test.argument);
2710
+ if (call?.type !== "CallExpression" || call.callee?.type !== "MemberExpression") return false;
2711
+ const setName = call.callee.object?.type === "Identifier" ? call.callee.object.name : "";
2712
+ if (!env.sets.has(setName) || call.callee.property?.name !== "has" && call.callee.property?.name !== "includes") return false;
2713
+ const arg = call.arguments?.[0];
2714
+ if (arg?.type !== "MemberExpression" || arg.computed || arg.property?.name !== "hostname" || arg.object?.type !== "Identifier") return false;
2715
+ if (env.allowed.get(arg.object.name) !== "url") return false;
2716
+ if (!rejectConsequent(stmt.consequent)) return false;
2717
+ env.rejected.add(arg.object.name);
2718
+ return true;
2719
+ }
2720
+ function bind(id, kind, env) {
2721
+ if (!id) return false;
2722
+ if (id.type === "Identifier") {
2723
+ env.allowed.set(id.name, kind);
2724
+ return true;
2725
+ }
2726
+ if (id.type === "ObjectPattern") {
2727
+ return (id.properties ?? []).every((prop) => prop?.type === "ObjectProperty" && bind(prop.value, kind, env));
2728
+ }
2729
+ return false;
2730
+ }
2731
+ function execStmt(stmt, env) {
2732
+ if (!stmt || stmt.type === "EmptyStatement") return true;
2733
+ if (allowlistIf(stmt, env)) return true;
2734
+ if (stmt.type === "VariableDeclaration") {
2735
+ if (stmt.kind === "var") return false;
2736
+ if (stmt.kind !== "const") {
2737
+ for (const decl of stmt.declarations ?? []) {
2738
+ const init = unwrap(decl?.init);
2739
+ if (init?.type === "NewExpression" && init.callee?.type === "Identifier" && init.callee.name === "URL") return false;
2740
+ }
2741
+ }
2742
+ for (const decl of stmt.declarations ?? []) {
2743
+ const kind = evalExpr(decl.init, env);
2744
+ if (kind === "no" || !bind(decl.id, kind, env)) return false;
2745
+ }
2746
+ return true;
2747
+ }
2748
+ if (stmt.type === "ReturnStatement") {
2749
+ if (stmt.argument && evalExpr(stmt.argument, env) === "no") return false;
2750
+ env.responded = true;
2751
+ return true;
2752
+ }
2753
+ if (stmt.type === "ExpressionStatement") {
2754
+ const kind = evalExpr(stmt.expression, env);
2755
+ return kind !== "no";
2756
+ }
2757
+ return false;
2758
+ }
2759
+ function readOnlyBody(content, model, handler) {
2760
+ if (handler.method !== "get" && handler.method !== "head") return false;
2761
+ if (hasIdentity(handler.fn, handler.requestName)) return false;
2762
+ const env = {
2763
+ allowed: /* @__PURE__ */ new Map(),
2764
+ sets: model.sets,
2765
+ primitives: model.primitives,
2766
+ requestName: handler.requestName,
2767
+ replyName: handler.replyName,
2768
+ rejected: /* @__PURE__ */ new Set(),
2769
+ fetchSeen: false,
2770
+ responded: false,
2771
+ bad: false
2772
+ };
2773
+ for (const stmt of handler.statements) {
2774
+ if (!execStmt(stmt, env) || env.bad) return false;
2775
+ }
2776
+ return env.responded && !env.bad && content.length >= 0;
2777
+ }
2778
+ function sourceGuarded(content, handler) {
2779
+ const slice = content.slice(handler.fnStart, handler.fnEnd);
2780
+ return /requireUser|requireAuth|withAuth|getServerSession|\bauth\s*\(|passport|isAuthenticated|verifyAdmin|requireAdmin|verifyToken/.test(slice);
2781
+ }
2782
+ function publicReadOnlyHandler(content, filePath, index, strictApp = false) {
2783
+ try {
2784
+ fault("readOnly");
2785
+ const model = load(content, filePath);
2786
+ if (!model) return false;
2787
+ const handler = onLine(model, content, index);
2788
+ if (!handler || !readOnlyBody(content, model, handler)) return false;
2789
+ if (strictApp && handler.appRouter) {
2790
+ for (const other of model.handlers) {
2791
+ if (!other.appRouter || other === handler) continue;
2792
+ const ok = (other.method === "get" || other.method === "head") && readOnlyBody(content, model, other) || capabilityBody(model, other) || sourceGuarded(content, other);
2793
+ if (!ok) return false;
2794
+ }
2795
+ }
2796
+ return true;
2797
+ } catch {
2798
+ return false;
2799
+ }
2800
+ }
2801
+ function roleLiteral(node) {
2802
+ if (node?.type === "StringLiteral") return ROLE_WORD.test(String(node.value));
2803
+ if (node?.type === "ArrayExpression") {
2804
+ const elements = node.elements ?? [];
2805
+ return elements.length > 0 && elements.every((el) => el?.type === "StringLiteral" && ROLE_WORD.test(String(el.value)));
2806
+ }
2807
+ return false;
2808
+ }
2809
+ function argIsRole(node) {
2810
+ if (!node) return false;
2811
+ if (node.type === "Identifier") return node.name === "requireAdmin" || node.name === "verifyAdmin";
2812
+ if (node.type === "CallExpression" && node.callee?.type === "Identifier" && node.callee.name === "requireRole") {
2813
+ const args = node.arguments ?? [];
2814
+ return args.length > 0 && args.every((arg) => roleLiteral(arg));
2815
+ }
2816
+ if (node.type === "ArrayExpression") return (node.elements ?? []).some((el) => argIsRole(el));
2817
+ return false;
2818
+ }
2819
+ function lookupHasTwoParams(content, lookup, params) {
2820
+ const query = querySlice(content, lookup);
2821
+ if (!query) return false;
2822
+ const used = /* @__PURE__ */ new Set();
2823
+ const re = /req\.params\.([A-Za-z_$][\w$]*)/g;
2824
+ let match;
2825
+ while (match = re.exec(query)) used.add(match[1]);
2826
+ return [...used].filter((name) => params.includes(name)).length >= 2;
2827
+ }
2828
+ function memberScoped(content, handler, lookups) {
2829
+ const params = [...handler.path.matchAll(/:([A-Za-z_$][\w$]*)/g)].map((match) => match[1]);
2830
+ if (params.length < 2) return false;
2831
+ const inside = lookups.filter((index) => index >= handler.fnStart && index < handler.fnEnd);
2832
+ if (inside.length === 0) return false;
2833
+ return inside.every((lookup) => lookupHasTwoParams(content, lookup, params));
2834
+ }
2835
+ function narrowedGuard(content, model, handler, lookups) {
2836
+ const member = (args) => args.some((arg) => arg?.type === "Identifier" && arg.name === "requireMember") && memberScoped(content, handler, lookups);
2837
+ if (handler.routeArgs.some((arg) => argIsRole(arg)) || member(handler.routeArgs)) return true;
2838
+ for (const use of model.uses) {
2839
+ if (use.receiver !== handler.receiver || !handler.receiver) continue;
2840
+ if (use.start >= handler.regStart || use.scope === null || use.scope !== handler.scope || !use.constReceiver) continue;
2841
+ if (use.args.some((arg) => argIsRole(arg)) || member(use.args)) return true;
2842
+ }
2843
+ return false;
2844
+ }
2845
+ function paramAccess(node) {
2846
+ const value = unwrap(node);
2847
+ if (value?.type !== "MemberExpression" || value.computed || value.property?.type !== "Identifier") return null;
2848
+ const prop = String(value.property.name);
2849
+ const obj = value.object;
2850
+ if (obj?.type === "Identifier" && obj.name === "params") return prop;
2851
+ if (obj?.type === "MemberExpression" && !obj.computed && obj.property?.name === "params") return prop;
2852
+ return null;
2853
+ }
2854
+ function isNow(node) {
2855
+ const value = unwrap(node);
2856
+ if (value?.type === "CallExpression" && value.callee?.object?.name === "Date" && value.callee?.property?.name === "now" && (value.arguments ?? []).length === 0) return true;
2857
+ return value?.type === "NewExpression" && value.callee?.name === "Date" && (value.arguments ?? []).length === 0;
2858
+ }
2859
+ function filterOf(obj, hashFns, cryptoName) {
2860
+ let target = obj;
2861
+ if ((obj?.properties ?? []).length === 1 && propName(obj.properties[0]) === "where" && obj.properties[0].value?.type === "ObjectExpression") {
2862
+ target = obj.properties[0].value;
2863
+ }
2864
+ const props = target?.properties ?? [];
2865
+ if (props.length !== 2 || props.some((prop) => prop?.type !== "ObjectProperty")) return null;
2866
+ let field = "";
2867
+ let param = "";
2868
+ let expiry = "";
2869
+ for (const prop of props) {
2870
+ const key = propName(prop);
2871
+ const value = unwrap(prop.value);
2872
+ if (value?.type === "CallExpression" && value.callee?.type === "Identifier" && hashFns.has(value.callee.name)) {
2873
+ if ((value.arguments ?? []).length !== 1) return null;
2874
+ const accessed = paramAccess(value.arguments[0]);
2875
+ if (!accessed) return null;
2876
+ field = key;
2877
+ param = accessed;
2878
+ } else if (value?.type === "CallExpression") {
2879
+ const accessed = paramAccess(inlineUpdateArg(value, cryptoName));
2880
+ if (!accessed) return null;
2881
+ field = key;
2882
+ param = accessed;
2883
+ } else if (value?.type === "ObjectExpression" && (value.properties ?? []).length === 1) {
2884
+ const inner = value.properties[0];
2885
+ const name = propName(inner);
2886
+ if (name !== "$gt" && name !== "gt" || !isNow(inner.value)) return null;
2887
+ expiry = key;
2888
+ } else return null;
2889
+ }
2890
+ if (!field || !param || !expiry) return null;
2891
+ return { field, param, expiry };
2892
+ }
2893
+ function assignedFromRandom(ast, field, hashFns, randomNames, cryptoName) {
2894
+ let found = false;
2895
+ walk(ast, (node) => {
2896
+ if (node.type !== "AssignmentExpression" || node.left?.type !== "MemberExpression") return;
2897
+ if (propName(node.left) !== field && node.left.property?.name !== field) return;
2898
+ const right = unwrap(node.right);
2899
+ if (right?.type !== "CallExpression") return;
2900
+ if (right.callee?.type === "Identifier" && hashFns.has(right.callee.name)) {
2901
+ const arg2 = right.arguments?.[0];
2902
+ if (arg2?.type === "Identifier" && randomNames.has(arg2.name)) found = true;
2903
+ return;
2904
+ }
2905
+ const arg = inlineUpdateArg(right, cryptoName);
2906
+ if (arg?.type === "Identifier" && randomNames.has(arg.name)) found = true;
2907
+ });
2908
+ return found;
2909
+ }
2910
+ function inlineUpdateArg(node, cryptoName) {
2911
+ const digest2 = unwrap(node);
2912
+ if (!cryptoName || digest2?.type !== "CallExpression" || digest2.callee?.type !== "MemberExpression" || digest2.callee.property?.name !== "digest") return null;
2913
+ const update = digest2.callee.object;
2914
+ if (update?.type !== "CallExpression" || update.callee?.type !== "MemberExpression" || update.callee.property?.name !== "update") return null;
2915
+ if ((update.arguments ?? []).length !== 1) return null;
2916
+ const created = update.callee.object;
2917
+ if (created?.type !== "CallExpression" || created.callee?.type !== "MemberExpression") return null;
2918
+ if (created.callee.property?.name !== "createHash" || created.callee.object?.name !== cryptoName) return null;
2919
+ if ((created.arguments ?? []).length !== 1 || created.arguments[0]?.type !== "StringLiteral") return null;
2920
+ return update.arguments[0];
2921
+ }
2922
+ function isPasswordAssign(stmt, user, hashers) {
2923
+ if (stmt?.type !== "ExpressionStatement" || stmt.expression?.type !== "AssignmentExpression") return false;
2924
+ const left = stmt.expression.left;
2925
+ if (left?.type !== "MemberExpression" || left.object?.name !== user) return false;
2926
+ const right = unwrap(stmt.expression.right);
2927
+ if (right?.type !== "CallExpression" || right.callee?.type !== "MemberExpression" || right.callee.property?.name !== "hash") return false;
2928
+ if (right.callee.object?.type !== "Identifier" || !hashers.has(right.callee.object.name)) return false;
2929
+ let cur = right.arguments?.[0];
2930
+ let body = false;
2931
+ while (cur?.type === "MemberExpression") {
2932
+ if (cur.property?.name === "body") body = true;
2933
+ cur = cur.object;
2934
+ }
2935
+ return body && right.arguments?.[1]?.type === "NumericLiteral";
2936
+ }
2937
+ function isClear(stmt, user, field) {
2938
+ if (stmt?.type !== "ExpressionStatement" || stmt.expression?.type !== "AssignmentExpression") return false;
2939
+ const left = stmt.expression.left;
2940
+ if (left?.type !== "MemberExpression" || left.object?.name !== user || left.property?.name !== field) return false;
2941
+ const right = unwrap(stmt.expression.right);
2942
+ return right?.type === "Identifier" && right.name === "undefined" || right?.type === "NullLiteral";
2943
+ }
2944
+ function isSave(stmt, user) {
2945
+ if (stmt?.type !== "ExpressionStatement") return false;
2946
+ const call = unwrap(stmt.expression);
2947
+ return call?.type === "CallExpression" && call.callee?.type === "MemberExpression" && call.callee.property?.name === "save" && call.callee.object?.name === user && (call.arguments ?? []).length === 0;
2948
+ }
2949
+ function isSuccess(stmt, _user, _param) {
2950
+ const value = stmt?.type === "ReturnStatement" ? stmt.argument : stmt?.type === "ExpressionStatement" ? stmt.expression : null;
2951
+ const call = unwrap(value);
2952
+ if (call?.type !== "CallExpression") return false;
2953
+ const callee = call.callee;
2954
+ const name = callee?.property?.name;
2955
+ const ok = callee?.type === "MemberExpression" && (name === "json" || name === "send") && (callee.object?.name === "res" || callee.object?.name === "reply" || callee.object?.name === "NextResponse" || callee.object?.name === "Response");
2956
+ if (!ok || (call.arguments ?? []).length < 1) return false;
2957
+ return literalValue(call.arguments[0]);
2958
+ }
2959
+ function capabilityBody(model, handler) {
2960
+ if (handler.method !== "post" && handler.method !== "put" && handler.method !== "patch") return false;
2961
+ const stmts = handler.statements.filter((stmt) => stmt?.type !== "EmptyStatement");
2962
+ if (stmts.length < 2 || stmts[0]?.type !== "VariableDeclaration" || (stmts[0].declarations ?? []).length !== 1) return false;
2963
+ const decl = stmts[0].declarations[0];
2964
+ if (decl?.id?.type !== "Identifier") return false;
2965
+ const lookup = unwrap(decl.init);
2966
+ if (lookup?.type !== "CallExpression" || lookup.callee?.type !== "MemberExpression") return false;
2967
+ if (!["findOne", "findUnique", "findFirst"].includes(lookup.callee.property?.name)) return false;
2968
+ const filter = filterOf(lookup.arguments?.[0], model.hashFns, model.cryptoName);
2969
+ if (!filter) return false;
2970
+ if (!handler.appRouter && !handler.path.includes(`:${filter.param}`)) return false;
2971
+ if (!assignedFromRandom(model.ast, filter.field, model.hashFns, model.randomNames, model.cryptoName)) return false;
2972
+ const guard = stmts[1];
2973
+ if (guard?.type !== "IfStatement" || guard.alternate) return false;
2974
+ const test = unwrap(guard.test);
2975
+ if (test?.type !== "UnaryExpression" || test.operator !== "!" || test.argument?.type !== "Identifier" || test.argument.name !== decl.id.name) return false;
2976
+ if (!rejectConsequent(guard.consequent)) return false;
2977
+ let clearF = false;
2978
+ let clearE = false;
2979
+ let password = false;
2980
+ let saved = false;
2981
+ let done = false;
2982
+ for (const stmt of stmts.slice(2)) {
2983
+ if (done) return false;
2984
+ if (isPasswordAssign(stmt, decl.id.name, model.hasherNames)) {
2985
+ if (password || saved) return false;
2986
+ password = true;
2987
+ continue;
2988
+ }
2989
+ if (isClear(stmt, decl.id.name, filter.field)) {
2990
+ if (saved) return false;
2991
+ clearF = true;
2992
+ continue;
2993
+ }
2994
+ if (isClear(stmt, decl.id.name, filter.expiry)) {
2995
+ if (saved) return false;
2996
+ clearE = true;
2997
+ continue;
2998
+ }
2999
+ if (isSave(stmt, decl.id.name)) {
3000
+ if (!clearF || !clearE || !password || saved) return false;
3001
+ saved = true;
3002
+ continue;
3003
+ }
3004
+ if (isSuccess(stmt, decl.id.name, filter.param)) {
3005
+ if (!saved) return false;
3006
+ done = true;
3007
+ continue;
3008
+ }
3009
+ return false;
3010
+ }
3011
+ return done && clearF && clearE && password && saved;
3012
+ }
3013
+ function capabilityTokenHandler(content, filePath, index) {
3014
+ try {
3015
+ fault("capability");
3016
+ const model = load(content, filePath);
3017
+ if (!model) return false;
3018
+ const handler = onLine(model, content, index);
3019
+ return handler ? capabilityBody(model, handler) : false;
3020
+ } catch {
3021
+ return false;
3022
+ }
3023
+ }
3024
+ function bearerExpr(node) {
3025
+ const value = unwrap(node);
3026
+ if (value?.type !== "TemplateLiteral" || (value.expressions ?? []).length !== 1) return null;
3027
+ const lead = value.quasis?.[0]?.value?.cooked ?? "";
3028
+ const tail = value.quasis?.[1]?.value?.cooked ?? "";
3029
+ if (!/^Bearer $/i.test(lead) || tail !== "") return null;
3030
+ return value.expressions[0];
3031
+ }
3032
+ function bindPattern(id, init, map) {
3033
+ if (!id) return;
3034
+ if (id.type === "Identifier") map.set(id.name, init);
3035
+ if (id.type === "ObjectPattern") {
3036
+ for (const prop of id.properties ?? []) {
3037
+ if (prop?.type === "ObjectProperty") bindPattern(prop.value, { type: "Destructure", object: init, key: propName(prop) }, map);
3038
+ }
3039
+ }
3040
+ }
3041
+ function declaredNames(id, into) {
3042
+ if (!id) return;
3043
+ if (id.type === "Identifier") into.push(id.name);
3044
+ if (id.type === "ObjectPattern" || id.type === "ArrayPattern") {
3045
+ const parts = id.properties ?? id.elements ?? [];
3046
+ for (const part of parts) {
3047
+ if (part?.type === "ObjectProperty" || part?.type === "RestElement") declaredNames(part.value ?? part.argument, into);
3048
+ else declaredNames(part, into);
3049
+ }
3050
+ }
3051
+ if (id.type === "AssignmentPattern") declaredNames(id.left, into);
3052
+ }
3053
+ function bindingMap(fn) {
3054
+ const map = /* @__PURE__ */ new Map();
3055
+ const body = fn?.body?.type === "BlockStatement" ? fn.body.body ?? [] : [];
3056
+ for (const stmt of body) {
3057
+ if (stmt?.type !== "VariableDeclaration" || stmt.kind !== "const") continue;
3058
+ for (const decl of stmt.declarations ?? []) {
3059
+ if (decl?.init) bindPattern(decl.id, unwrap(decl.init), map);
3060
+ }
3061
+ }
3062
+ const counts = /* @__PURE__ */ new Map();
3063
+ const assigned = /* @__PURE__ */ new Set();
3064
+ walk(fn, (node) => {
3065
+ if (node.type === "VariableDeclarator") {
3066
+ const names = [];
3067
+ declaredNames(node.id, names);
3068
+ for (const name of names) counts.set(name, (counts.get(name) ?? 0) + 1);
3069
+ }
3070
+ if (node.type === "AssignmentExpression" || node.type === "UpdateExpression") {
3071
+ const names = [];
3072
+ declaredNames(node.left ?? node.argument, names);
3073
+ for (const name of names) assigned.add(name);
3074
+ }
3075
+ });
3076
+ for (const [name, count] of counts) if (count > 1) map.delete(name);
3077
+ for (const name of assigned) map.delete(name);
3078
+ return map;
3079
+ }
3080
+ function isCookieValue(node, map) {
3081
+ const member = unwrap(node);
3082
+ if (!member || member.type !== "MemberExpression" && member.type !== "OptionalMemberExpression" || member.property?.name !== "value") return false;
3083
+ const call = unwrap(member.object);
3084
+ if (call?.type !== "CallExpression" || call.callee?.type !== "MemberExpression" || call.callee.property?.name !== "get") return false;
3085
+ if (call.arguments?.[0]?.type !== "StringLiteral") return false;
3086
+ const obj = unwrap(call.callee.object);
3087
+ if (obj?.type === "CallExpression" && obj.callee?.name === "cookies") return true;
3088
+ if (obj?.type === "Identifier") {
3089
+ const bound = unwrap(map.get(obj.name));
3090
+ if (bound?.type === "CallExpression" && bound.callee?.name === "cookies") return true;
3091
+ }
3092
+ return false;
3093
+ }
3094
+ function isSessionToken(node, map) {
3095
+ const member = unwrap(node);
3096
+ if (!member || member.type !== "MemberExpression" && member.type !== "OptionalMemberExpression" || member.property?.name !== "access_token") return false;
3097
+ if (member.object?.type !== "Identifier") return false;
3098
+ let current = map.get(member.object.name);
3099
+ const seen = /* @__PURE__ */ new Set();
3100
+ while (current && current.type === "Destructure" && !seen.has(current)) {
3101
+ seen.add(current);
3102
+ current = current.object;
3103
+ }
3104
+ const call = unwrap(current);
3105
+ if (call?.type !== "CallExpression" || call.callee?.property?.name !== "getSession" || call.callee?.object?.property?.name !== "auth") return false;
3106
+ const clientName = call.callee.object.object?.name;
3107
+ const client = unwrap(map.get(clientName));
3108
+ return client?.type === "CallExpression" && (client.callee?.name === "createClient" || client.callee?.property?.name === "createClient");
3109
+ }
3110
+ function fetchLiteral(node) {
3111
+ const call = unwrap(node);
3112
+ if (call?.type !== "CallExpression" || call.callee?.name !== "fetch") return null;
3113
+ return staticString(call.arguments?.[0]);
3114
+ }
3115
+ function isOAuthToken(node, map, here) {
3116
+ if (node?.type !== "Identifier") return false;
3117
+ let current = map.get(node.name);
3118
+ const seen = /* @__PURE__ */ new Set();
3119
+ while (current && current.type === "Destructure" && !seen.has(current)) {
3120
+ seen.add(current);
3121
+ current = current.object;
3122
+ }
3123
+ const json = unwrap(current);
3124
+ if (json?.type !== "CallExpression" || json.callee?.property?.name !== "json" || json.callee?.object?.type !== "Identifier") return false;
3125
+ const tokenUrl = fetchLiteral(map.get(json.callee.object.name));
3126
+ if (!tokenUrl || !here) return false;
3127
+ if (!publicHttpsUrl(tokenUrl) || !publicHttpsUrl(here)) return false;
3128
+ const tokenHost = new URL(tokenUrl).hostname.toLowerCase();
3129
+ const hereHost = new URL(here).hostname.toLowerCase();
3130
+ return tokenHost === hereHost || hereHost.endsWith(`.${tokenHost}`);
3131
+ }
3132
+ function envUrl(node) {
3133
+ const value = unwrap(node);
3134
+ if (value?.type !== "TemplateLiteral" || (value.expressions ?? []).length !== 1) return false;
3135
+ if (!isProcessEnv(value.expressions[0]) || value.expressions[0]?.type === "LogicalExpression") return false;
3136
+ const lead = value.quasis?.[0]?.value?.cooked ?? "";
3137
+ const rest = value.quasis?.[1]?.value?.cooked ?? "";
3138
+ return lead === "" && rest.startsWith("/") && !rest.includes("?");
3139
+ }
3140
+ function headerQualifies(model, propPath) {
3141
+ const index = propPath.node.start;
3142
+ const options = propPath.parent;
3143
+ const call = propPath.parentPath?.parentPath?.node;
3144
+ if (options?.type !== "ObjectExpression" || call?.type !== "CallExpression") return false;
3145
+ if (call.arguments?.[1] !== options || call.callee?.name !== "fetch") return false;
3146
+ const headers = propPath.node.value;
3147
+ if (headers?.type !== "ObjectExpression") return false;
3148
+ const auth = (headers.properties ?? []).find((prop) => prop?.type === "ObjectProperty" && propName(prop).toLowerCase() === "authorization");
3149
+ const expr = bearerExpr(auth?.value);
3150
+ if (!expr) return false;
3151
+ const inner = model.functions.filter((fn) => fn.start <= index && index < fn.end).sort((a, b) => a.end - a.start - (b.end - b.start))[0];
3152
+ const handler = model.handlers.find((item) => item.fnStart === inner?.start && item.fnEnd === inner?.end);
3153
+ if (!handler || handler.method !== "serve" && !METHODS.has(handler.method)) return false;
3154
+ const map = bindingMap(handler.fn);
3155
+ const urlNode = call.arguments?.[0];
3156
+ const direct = unwrap(expr);
3157
+ const resolved = direct?.type === "Identifier" ? unwrap(map.get(direct.name)) ?? direct : direct;
3158
+ if (isCookieValue(direct, map) || isCookieValue(resolved, map) || isSessionToken(direct, map) || isSessionToken(resolved, map)) return envUrl(urlNode);
3159
+ const here = staticString(urlNode);
3160
+ return here !== null && isOAuthToken(unwrap(expr), map, here);
3161
+ }
3162
+ function bearerSpans(content, filePath, model) {
3163
+ const key = `${filePath}\0${digest(content)}`;
3164
+ const hit = bearerSpanCache.get(key);
3165
+ if (hit && hit.content === content) return hit.spans;
3166
+ const spans = [];
3167
+ traverse(model.ast, {
3168
+ ObjectProperty(path) {
3169
+ const node = path.node;
3170
+ if (typeof node.start !== "number" || typeof node.end !== "number") return;
3171
+ if (propName(node).toLowerCase() !== "headers") return;
3172
+ spans.push({ start: node.start, end: node.end, ok: headerQualifies(model, path) });
3173
+ }
3174
+ });
3175
+ bearerSpanCache.set(key, { content, spans });
3176
+ if (bearerSpanCache.size > 128) {
3177
+ const first = bearerSpanCache.keys().next().value;
3178
+ if (first !== void 0) bearerSpanCache.delete(first);
3179
+ }
3180
+ return spans;
3181
+ }
3182
+ function bearerProvenanceSafe(content, filePath, index) {
3183
+ try {
3184
+ fault("bearer");
3185
+ if (!content.includes("fetch")) return false;
3186
+ const model = load(content, filePath);
3187
+ if (!model) return false;
3188
+ let count = 0;
3189
+ let ok = false;
3190
+ for (const span of bearerSpans(content, filePath, model)) {
3191
+ if (index < span.start || index >= span.end) continue;
3192
+ count += 1;
3193
+ ok = span.ok;
3194
+ }
3195
+ return count === 1 && ok;
3196
+ } catch {
3197
+ return false;
3198
+ }
3199
+ }
3200
+ var LOOKUP_RE = /findUnique|findFirst|findById|\.findOne\b|\.find\s*\(\s*\{|WHERE[\s\S]{0,120}?(?:params|req\.(?:body|query))|\.get\([^)]{0,500}(?:params|req\.(?:body|query))/gi;
3201
+ var REF_RE = /params\.id|params\.(?:slug|uuid)|req\.params\.\w+|req\.params\b|req\.(?:body|query)\.\w*id/gi;
3202
+ var OWNER_RE = /userId|ownerId|createdBy|user_id|owner_id|AND.*user|where.*user|authorize|canAccess|checkPermission|isOwner|belongsTo/i;
3203
+ var AUTH_RE = /requireUser|requireUserForApi|requireAuth|withAuth|getServerSession|auth\(\)|passport|isAuthenticated/i;
3204
+ function maskLocal(content) {
3205
+ let open = content.indexOf("/*");
3206
+ let blocked2 = content;
3207
+ if (open !== -1) {
3208
+ const parts = [];
3209
+ let copied = 0;
3210
+ while (open !== -1) {
3211
+ const close = content.indexOf("*/", open + 2);
3212
+ if (close === -1) break;
3213
+ parts.push(content.slice(copied, open), content.slice(open, close + 2).replace(/[^\n]/g, " "));
3214
+ copied = close + 2;
3215
+ open = content.indexOf("/*", copied);
3216
+ }
3217
+ parts.push(content.slice(copied));
3218
+ blocked2 = parts.join("");
3219
+ }
3220
+ return blocked2.replace(/(^|[^:])\/\/[^\n]*/gm, (match, lead) => lead + " ".repeat(match.length - lead.length));
3221
+ }
3222
+ function matchIndexes(text, re) {
3223
+ const copy = new RegExp(re.source, re.flags);
3224
+ const out = [];
3225
+ let match;
3226
+ while (match = copy.exec(text)) {
3227
+ out.push(match.index);
3228
+ if (match[0].length === 0) copy.lastIndex += 1;
3229
+ if (out.length > LOOKUP_LIMIT) break;
3230
+ }
3231
+ return out;
3232
+ }
3233
+ function balancedCall(content, open) {
3234
+ let depth = 0;
3235
+ for (let i = open; i < content.length; i++) {
3236
+ const c = content[i];
3237
+ if (c === "(") depth += 1;
3238
+ else if (c === ")") {
3239
+ depth -= 1;
3240
+ if (depth === 0) return content.slice(open, i + 1);
3241
+ }
3242
+ }
3243
+ return null;
3244
+ }
3245
+ function querySlice(content, index) {
3246
+ if (/^where\b/i.test(content.slice(index, index + 5))) {
3247
+ let depth = 0;
3248
+ for (let i = index; i >= 0; i--) {
3249
+ const c = content[i];
3250
+ if (c === ")") depth += 1;
3251
+ else if (c === "(") {
3252
+ if (depth === 0) return balancedCall(content, i);
3253
+ depth -= 1;
3254
+ }
3255
+ }
3256
+ }
3257
+ const open = content.indexOf("(", index);
3258
+ if (open === -1 || open - index > 80) return null;
3259
+ return balancedCall(content, open);
3260
+ }
3261
+ function handlerAt(model, index) {
3262
+ const found = model.handlers.filter((handler) => handler.fnStart <= index && index < handler.fnEnd);
3263
+ found.sort((a, b) => a.fnEnd - a.fnStart - (b.fnEnd - b.fnStart));
3264
+ return found[0] ?? null;
3265
+ }
3266
+ function handlerQualifies(content, filePath, handler, lookups) {
3267
+ const slice = content.slice(handler.fnStart, handler.fnEnd);
3268
+ const registered = content.slice(handler.regStart, handler.fnEnd);
3269
+ if (AUTH_RE.test(registered)) return false;
3270
+ const lookup = lookups.find((index) => index >= handler.fnStart && index < handler.fnEnd);
3271
+ if (lookup === void 0) return false;
3272
+ const query = querySlice(content, lookup) ?? slice;
3273
+ if (OWNER_RE.test(query)) return false;
3274
+ const reads = /req\.params\b|req\.(?:body|query)\.\w*id\b|params\.id|params\.(?:slug|uuid)/i.test(slice);
3275
+ if (!reads) return false;
3276
+ if (handler.appRouter) return /\/api\//i.test(filePath) && /^(get|put|patch|delete)$/.test(handler.method);
3277
+ return METHODS.has(handler.method);
3278
+ }
3279
+ function refineDirectObjectFindings(content, filePath, legacyLines) {
3280
+ try {
3281
+ fault("refine");
3282
+ if (content.length > PARSE_BYTES) return null;
3283
+ const masked = maskLocal(content);
3284
+ const lookups = matchIndexes(masked, LOOKUP_RE);
3285
+ if (lookups.length > LOOKUP_LIMIT) return null;
3286
+ const model = load(content, filePath);
3287
+ if (!model || model.handlers.length === 0) return null;
3288
+ const refs = matchIndexes(masked, REF_RE);
3289
+ if (refs.length === 0) return null;
3290
+ const cleared = (handler) => narrowedGuard(content, model, handler, lookups) || capabilityTokenHandler(content, filePath, handler.regStart);
3291
+ let every = true;
3292
+ for (const ref of refs) {
3293
+ const handler = handlerAt(model, ref);
3294
+ if (!handler || !cleared(handler)) every = false;
3295
+ }
3296
+ const lines = /* @__PURE__ */ new Set();
3297
+ if (!every) for (const line of legacyLines) lines.add(line);
3298
+ for (const handler of model.handlers) {
3299
+ if (cleared(handler) || !handlerQualifies(content, filePath, handler, lookups)) continue;
3300
+ const ref = refs.find((index) => index >= handler.fnStart && index < handler.fnEnd);
3301
+ if (ref === void 0) continue;
3302
+ lines.add(lineAt(content, ref));
3303
+ }
3304
+ return [...lines].sort((a, b) => a - b);
3305
+ } catch {
3306
+ return null;
3307
+ }
3308
+ }
3309
+
3310
+ // src/auth-scope.ts
3311
+ var GUARD_NAMES = ["requireAdmin", "requireMember", "requireRole", "requireUser", "verifyToken", "verifyAdmin"];
3312
+ var PUBLIC_LAST = /^(?:login|logout|signup|register|forgot(?:-password)?|reset(?:-password)?|callback)$/i;
3313
+ var SIDE_EFFECT_RE = /\.(?:save|deleteMany|deleteOne|updateMany|updateOne|createMany|findMany|findOne|findUnique|findFirst|findByIdAndDelete|findByIdAndUpdate|remove|destroy|delete|update|create|insert|insertOne|upsert)\s*\(|\.(?:query|execute|exec|rm)\s*\(|\b(?:kv|redis)\s*\.\s*(?:set|del)\s*\(|\bsql\s*`|\bfetch\s*\(|\b(?:readFileSync|readFile|writeFileSync|writeFile|createReadStream|unlinkSync|unlink|mkdirSync|mkdir|execFileSync|execFile|spawn)\s*\(|\bcookies\s*\(\s*\)\s*\.\s*set\s*\(|\bres\s*\.\s*(?:json|send|redirect|end)\s*\(|\bres\s*\.\s*status\s*\([^)]*\)\s*\.\s*(?:json|send|end)\s*\(|\breturn\b/g;
3314
+ function blankComments(content) {
3315
+ let open = content.indexOf("/*");
3316
+ let blocked2 = content;
3317
+ if (open !== -1) {
3318
+ const parts = [];
3319
+ let copied = 0;
3320
+ while (open !== -1) {
3321
+ const close = content.indexOf("*/", open + 2);
3322
+ if (close === -1) break;
3323
+ parts.push(content.slice(copied, open), content.slice(open, close + 2).replace(/[^\n]/g, " "));
3324
+ copied = close + 2;
3325
+ open = content.indexOf("/*", copied);
3326
+ }
3327
+ parts.push(content.slice(copied));
3328
+ blocked2 = parts.join("");
3329
+ }
3330
+ return blocked2.replace(/(^|[^:])\/\/[^\n]*/gm, (m, lead) => lead + " ".repeat(m.length - lead.length));
3331
+ }
3332
+ var ARG_CAP = 300;
3333
+ var IF_BODY_CAP = 2e3;
3334
+ var BRACE_CAP = 2e4;
3335
+ function matchingCloser(text, open, openCh, closeCh, maxLen = Infinity) {
3336
+ let depth = 0;
3337
+ let quote = "";
3338
+ const end = maxLen === Infinity ? text.length : Math.min(text.length, open + maxLen);
3339
+ for (let i = open; i < end; i++) {
3340
+ const c = text[i];
3341
+ if (quote) {
3342
+ if (c === "\\") {
3343
+ i++;
3344
+ continue;
3345
+ }
3346
+ if (c === quote) quote = "";
3347
+ continue;
3348
+ }
3349
+ if (c === "'" || c === '"' || c === "`") {
3350
+ quote = c;
3351
+ continue;
3352
+ }
3353
+ if (c === openCh) depth++;
3354
+ else if (c === closeCh) {
3355
+ depth--;
3356
+ if (depth === 0) return i;
3357
+ }
3358
+ }
3359
+ return -1;
3360
+ }
3361
+ function escapeRegExp(value) {
3362
+ return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
3363
+ }
3364
+ function maskStrings(content) {
3365
+ const chars = content.split("");
3366
+ let i = 0;
3367
+ while (i < chars.length) {
3368
+ const c = chars[i];
3369
+ if (c === "'" || c === '"') {
3370
+ const quote = c;
3371
+ chars[i] = " ";
3372
+ i++;
3373
+ while (i < chars.length) {
3374
+ if (chars[i] === "\\") {
3375
+ chars[i] = " ";
3376
+ if (i + 1 < chars.length && chars[i + 1] !== "\n") chars[i + 1] = " ";
3377
+ i += 2;
3378
+ continue;
3379
+ }
3380
+ if (chars[i] === "\n") break;
3381
+ if (chars[i] === quote) {
3382
+ chars[i] = " ";
3383
+ i++;
3384
+ break;
3385
+ }
3386
+ chars[i] = " ";
3387
+ i++;
3388
+ }
3389
+ continue;
3390
+ }
3391
+ if (c === "`") {
3392
+ chars[i] = " ";
3393
+ i++;
3394
+ let expr = 0;
3395
+ while (i < chars.length) {
3396
+ if (expr === 0 && chars[i] === "\\") {
3397
+ chars[i] = " ";
3398
+ if (i + 1 < chars.length && chars[i + 1] !== "\n") chars[i + 1] = " ";
3399
+ i += 2;
3400
+ continue;
3401
+ }
3402
+ if (expr === 0 && chars[i] === "`") {
3403
+ chars[i] = " ";
3404
+ i++;
3405
+ break;
3406
+ }
3407
+ if (expr === 0 && chars[i] === "$" && chars[i + 1] === "{") {
3408
+ chars[i] = " ";
3409
+ chars[i + 1] = " ";
3410
+ expr = 1;
3411
+ i += 2;
3412
+ continue;
3413
+ }
3414
+ if (expr > 0) {
3415
+ if (chars[i] === "{") expr++;
3416
+ else if (chars[i] === "}") expr--;
3417
+ i++;
3418
+ continue;
3419
+ }
3420
+ if (chars[i] !== "\n") chars[i] = " ";
3421
+ i++;
3422
+ }
3423
+ continue;
3424
+ }
3425
+ i++;
3426
+ }
3427
+ return chars.join("");
3428
+ }
3429
+ var REJECT_RE = /\bthrow\b|\bredirect\s*\(|\b(?:status(?:Code)?|sendStatus)\s*[:(=]\s*40[13]\b/;
3430
+ function localImportedNames(clause) {
3431
+ const names = [];
3432
+ for (const part of clause.split(",")) {
3433
+ const bits = part.trim().split(/\s+as\s+/i);
3434
+ const local = (bits[1] ?? bits[0] ?? "").replace(/^\s*type\s+/, "").trim();
3435
+ const ident = /^([A-Za-z_$][\w$]*)$/.exec(local);
3436
+ if (ident) names.push(ident[1]);
3437
+ }
3438
+ return names;
3439
+ }
3440
+ function isImportedName(content, name) {
3441
+ const id = escapeRegExp(name);
3442
+ if (new RegExp(`\\bimport\\s+${id}\\s+from\\b`).test(content)) return true;
3443
+ if (new RegExp(`\\b(?:const|let|var)\\s+${id}\\s*=\\s*require\\s*\\(`).test(content)) return true;
3444
+ for (const match of content.matchAll(/\bimport\s+(?:type\s+)?\{([^}]+)\}\s*from/g)) {
3445
+ if (localImportedNames(match[1]).includes(name)) return true;
3446
+ }
3447
+ for (const match of content.matchAll(/\b(?:const|let|var)\s*\{([^}]+)\}\s*=\s*require\s*\(/g)) {
3448
+ if (localImportedNames(match[1]).includes(name)) return true;
3449
+ }
3450
+ return false;
3451
+ }
3452
+ function jwtBindingSpan(file, name) {
3453
+ const id = escapeRegExp(name);
3454
+ const patterns = [
3455
+ new RegExp(`\\bimport\\s+${id}\\s+from\\s+["']jsonwebtoken["']`),
3456
+ new RegExp(`\\bimport\\s*\\*\\s*as\\s+${id}\\s+from\\s+["']jsonwebtoken["']`),
3457
+ new RegExp(
3458
+ `(?:const|let|var)\\s+${id}\\s*=\\s*require\\(\\s*["']jsonwebtoken["']\\s*\\)\\s*;?(?=\\s*(?:$|\\n|\\r))`
3459
+ )
3460
+ ];
3461
+ for (const pattern of patterns) {
3462
+ const match = pattern.exec(file);
3463
+ if (!match || match.index === void 0) continue;
3464
+ return [match.index, match.index + match[0].length];
3465
+ }
3466
+ return null;
3467
+ }
3468
+ function bindingIsShadowed(file, name, span) {
3469
+ const id = escapeRegExp(name);
3470
+ const checks = [
3471
+ new RegExp(`\\b(?:const|let|var)\\s+${id}\\b`, "g"),
3472
+ new RegExp(`\\b${id}\\s*=(?!=)`, "g"),
3473
+ new RegExp(`[(,]\\s*${id}\\s*[,)=:]`, "g")
3474
+ ];
3475
+ for (const pattern of checks) {
3476
+ let match;
3477
+ while (match = pattern.exec(file)) {
3478
+ if (match.index >= span[0] && match.index < span[1]) continue;
3479
+ return true;
3480
+ }
3481
+ }
3482
+ return false;
3483
+ }
3484
+ function identifierIsObjectLiteral(file, name) {
3485
+ const id = escapeRegExp(name);
3486
+ return new RegExp(`(?:\\b(?:const|let|var)\\s+|(?<![\\w$.]))${id}\\s*=(?!=)\\s*\\{`).test(file);
3487
+ }
3488
+ function verifyCallForm(source, callIndex, file) {
3489
+ const open = source.indexOf("(", callIndex);
3490
+ if (open < 0) return "none";
3491
+ const close = matchingCloser(source, open, "(", ")", ARG_CAP);
3492
+ if (close < 0) return "none";
3493
+ const args = splitArgs(source.slice(open + 1, close)).map((part) => part.trim()).filter(Boolean);
3494
+ if (args.length === 2) return "sync";
3495
+ if (args.length >= 4) return "callback";
3496
+ if (args.length !== 3) return "none";
3497
+ const third = args[2];
3498
+ if (/=>/.test(third) || /^\s*(?:async\s+)?function\b/.test(third)) return "callback";
3499
+ if (/^\s*\{/.test(third)) return "sync";
3500
+ const ident = /^\s*([A-Za-z_$][\w$]*)\s*$/.exec(third);
3501
+ if (!ident) return "callback";
3502
+ return identifierIsObjectLiteral(file, ident[1]) ? "sync" : "callback";
3503
+ }
3504
+ function syncJwtCredits(body, file) {
3505
+ const masked = maskStrings(body);
3506
+ const re = /\b([A-Za-z_$][\w$]*)\s*\.\s*verify\s*\(/g;
3507
+ let match;
3508
+ while (match = re.exec(masked)) {
3509
+ const span = jwtBindingSpan(file, match[1]);
3510
+ if (!span || bindingIsShadowed(file, match[1], span)) continue;
3511
+ if (verifyCallForm(masked, match.index, file) !== "sync") continue;
3512
+ if (!errorPathRejects(masked, match.index)) continue;
3513
+ return true;
3514
+ }
3515
+ return false;
3516
+ }
3517
+ var fnCacheContent = null;
3518
+ var fnCacheSpans = [];
3519
+ function headerIsFunction(content, brace) {
3520
+ const header = content.slice(Math.max(0, brace - 180), brace);
3521
+ const last = header.slice(header.lastIndexOf("\n") + 1);
3522
+ if (/=>\s*$/.test(last) || /\bfunction\b/.test(last)) return true;
3523
+ const method = /^\s*(?:(?:public|private|protected|static|async|override)\s+)*([A-Za-z_$][\w$]*)\s*\([^)]*\)\s*(?::\s*[^{]+)?$/.exec(last);
3524
+ if (!method) return false;
3525
+ return !/^(?:if|for|while|switch|catch|function|return|else|try)$/.test(method[1]);
3526
+ }
3527
+ function buildFnSpans(content) {
3528
+ const spans = [];
3529
+ const stack = [];
3530
+ let quote = "";
3531
+ for (let i = 0; i < content.length; i++) {
3532
+ const c = content[i];
3533
+ if (quote) {
3534
+ if (c === "\\" && quote !== "`") {
3535
+ i++;
3536
+ continue;
3537
+ }
3538
+ if (c === quote) quote = "";
3539
+ else if (quote !== "`" && c === "\n") quote = "";
3540
+ continue;
3541
+ }
3542
+ if (c === "'" || c === '"' || c === "`") {
3543
+ quote = c;
3544
+ continue;
3545
+ }
3546
+ if (c === "{") stack.push({ open: i, isFn: headerIsFunction(content, i) });
3547
+ else if (c === "}" && stack.length) {
3548
+ const frame = stack.pop();
3549
+ if (frame?.isFn) spans.push({ open: frame.open, close: i });
3550
+ }
3551
+ }
3552
+ for (const frame of stack) {
3553
+ if (frame.isFn) spans.push({ open: frame.open, close: content.length });
3554
+ }
3555
+ return spans;
3556
+ }
3557
+ var fnPrefixMax = [];
3558
+ function prepareFnCache(content) {
3559
+ if (fnCacheContent === content) return;
3560
+ fnCacheContent = content;
3561
+ fnCacheSpans = buildFnSpans(content).sort((a, b) => a.open - b.open || a.close - b.close);
3562
+ fnPrefixMax = new Array(fnCacheSpans.length);
3563
+ for (let i = 0; i < fnCacheSpans.length; i++) {
3564
+ fnPrefixMax[i] = i === 0 ? fnCacheSpans[i].close : Math.max(fnPrefixMax[i - 1], fnCacheSpans[i].close);
3565
+ }
3566
+ }
3567
+ function fnKeyAt(content, index) {
3568
+ prepareFnCache(content);
3569
+ const spans = fnCacheSpans;
3570
+ let lo = 0;
3571
+ let hi = spans.length - 1;
3572
+ let found = -1;
3573
+ while (lo <= hi) {
3574
+ const mid = lo + hi >> 1;
3575
+ if (spans[mid].open < index) {
3576
+ found = mid;
3577
+ lo = mid + 1;
3578
+ } else {
3579
+ hi = mid - 1;
3580
+ }
3581
+ }
3582
+ for (let i = found; i >= 0; i--) {
3583
+ if (fnPrefixMax[i] < index) break;
3584
+ const span = spans[i];
3585
+ if (index <= span.close) {
3586
+ if (index - span.open > BRACE_CAP) return "exhausted";
3587
+ return "fn@" + span.open;
3588
+ }
3589
+ }
3590
+ return "top";
3591
+ }
3592
+ function firstSideEffect(handler) {
3593
+ SIDE_EFFECT_RE.lastIndex = 0;
3594
+ const match = SIDE_EFFECT_RE.exec(handler);
3595
+ return match ? match.index : -1;
3596
+ }
3597
+ function beforeSideEffect(handler, index) {
3598
+ const at = firstSideEffect(handler);
3599
+ return at === -1 || index < at;
3600
+ }
3601
+ function localGuardBody(content, name) {
3602
+ const id = escapeRegExp(name);
3603
+ const fn = new RegExp(`\\b(?:async\\s+)?function\\s+${id}\\s*\\([^)]*\\)\\s*\\{`).exec(content);
3604
+ if (fn && fn.index !== void 0) {
3605
+ const brace = content.indexOf("{", fn.index);
3606
+ const end = matchingCloser(content, brace, "{", "}", BRACE_CAP);
3607
+ return end < 0 ? "" : content.slice(brace + 1, end);
3608
+ }
3609
+ const arrow = new RegExp(
3610
+ `\\b(?:const|let|var)\\s+${id}\\s*=\\s*(?:async\\s*)?(?:function\\s*\\([^)]*\\)|(?:\\([^)]*\\)|[A-Za-z_]\\w*)\\s*=>)`
3611
+ ).exec(content);
3612
+ if (!arrow || arrow.index === void 0) return null;
3613
+ const after = arrow.index + arrow[0].length;
3614
+ const rest = content.slice(after);
3615
+ if (/^\s*\{/.test(rest)) {
3616
+ const brace = content.indexOf("{", after);
3617
+ const end = matchingCloser(content, brace, "{", "}", BRACE_CAP);
3618
+ return end < 0 ? "" : content.slice(brace + 1, end);
3619
+ }
3620
+ const semi = content.indexOf(";", after);
3621
+ return content.slice(after, semi === -1 ? content.length : semi);
3622
+ }
3623
+ function guardBodyQualifies(body, file) {
3624
+ const masked = maskStrings(body);
3625
+ const flat = masked.replace(/\s+/g, " ").trim();
3626
+ if (!flat) return false;
3627
+ if (/^(?:return\s+)?next\s*\(\s*\)\s*;?$/.test(flat)) return false;
3628
+ if (REJECT_RE.test(masked)) return true;
3629
+ return syncJwtCredits(body, file);
3630
+ }
3631
+ var guardCacheContent = null;
3632
+ var guardCache = /* @__PURE__ */ new Map();
3633
+ function guardNameCounts(content, name) {
3634
+ if (guardCacheContent !== content) {
3635
+ guardCacheContent = content;
3636
+ guardCache.clear();
3637
+ }
3638
+ const cached = guardCache.get(name);
3639
+ if (cached !== void 0) return cached;
3640
+ const body = localGuardBody(content, name);
3641
+ const result = body === null ? isImportedName(content, name) : guardBodyQualifies(body, content);
3642
+ guardCache.set(name, result);
3643
+ return result;
3644
+ }
3645
+ function guardMentioned(content, args) {
3646
+ return GUARD_NAMES.some((name) => new RegExp(`\\b${escapeRegExp(name)}\\b`).test(args) && guardNameCounts(content, name));
3647
+ }
3648
+ function handlerBodyOpen(handler) {
3649
+ const arrow = handler.search(/=>\s*\{/);
3650
+ const fn = handler.search(/\)\s*\{/);
3651
+ const at = [arrow, fn].filter((index) => index >= 0);
3652
+ if (at.length === 0) return handler.indexOf("{");
3653
+ return handler.indexOf("{", Math.min(...at));
3654
+ }
3655
+ function guardStatementCounts(handler, callIndex) {
3656
+ const bodyOpen = handlerBodyOpen(handler);
3657
+ if (bodyOpen < 0 || callIndex <= bodyOpen) return false;
3658
+ let brace = 0;
3659
+ let paren = 0;
3660
+ let bracket = 0;
3661
+ let quote = "";
3662
+ let stmtStart = bodyOpen + 1;
3663
+ for (let i = bodyOpen; i < callIndex; i++) {
3664
+ const c = handler[i];
3665
+ if (quote) {
3666
+ if (c === "\\") {
3667
+ i++;
3668
+ continue;
3669
+ }
3670
+ if (c === quote) quote = "";
3671
+ continue;
3672
+ }
3673
+ if (c === "'" || c === '"' || c === "`") {
3674
+ quote = c;
3675
+ continue;
3676
+ }
3677
+ if (c === "{") {
3678
+ brace++;
3679
+ if (brace === 1) stmtStart = i + 1;
3680
+ } else if (c === "}") {
3681
+ brace--;
3682
+ if (brace === 1) stmtStart = i + 1;
3683
+ } else if (c === "(") paren++;
3684
+ else if (c === ")") paren--;
3685
+ else if (c === "[") bracket++;
3686
+ else if (c === "]") bracket--;
3687
+ else if (c === "\n" && brace === 1 && paren === 0 && bracket === 0) {
3688
+ let j = i - 1;
3689
+ while (j > bodyOpen && /[ \t\r]/.test(handler[j])) j--;
3690
+ const prev = handler[j] ?? "";
3691
+ if (!",([{+-*/=&|?:.".includes(prev)) stmtStart = i + 1;
3692
+ } else if (c === ";" && brace === 1 && paren === 0 && bracket === 0) stmtStart = i + 1;
3693
+ }
3694
+ if (brace !== 1 || paren !== 0 || bracket !== 0) return false;
3695
+ const stmt = handler.slice(stmtStart, callIndex);
3696
+ if (/&&|\|\||\?\?|\?(?!\.)/.test(stmt)) return false;
3697
+ if (/\b(?:if|else|while|for|switch|catch|try)\b/.test(stmt)) return false;
3698
+ if (!/\b(?:const|let|var)\b|=/.test(stmt)) return true;
3699
+ const assigned = lastAssignedName(stmt);
3700
+ if (!assigned) return false;
3701
+ return new RegExp(`\\b${escapeRegExp(assigned)}\\b`).test(handler.slice(callIndex + 1));
3702
+ }
3703
+ function lastAssignedName(stmt) {
3704
+ let name;
3705
+ let at = -1;
3706
+ for (const match of stmt.matchAll(/\b(?:const|let|var)\s+([A-Za-z_$][\w$]*)/g)) {
3707
+ if (match.index !== void 0 && match.index >= at) {
3708
+ at = match.index;
3709
+ name = match[1];
3710
+ }
3711
+ }
3712
+ for (const match of stmt.matchAll(/([A-Za-z_$][\w$]*)\s*=(?!=)/g)) {
3713
+ if (match.index !== void 0 && match.index >= at) {
3714
+ at = match.index;
3715
+ name = match[1];
3716
+ }
3717
+ }
3718
+ return name;
3719
+ }
3720
+ function guardCallBeforeSideEffect(content, handler) {
3721
+ const re = new RegExp(`\\b(${GUARD_NAMES.join("|")})\\s*\\(`, "g");
3722
+ let match;
3723
+ while (match = re.exec(handler)) {
3724
+ const pre = handler.slice(Math.max(0, match.index - 24), match.index);
3725
+ if (/\bfunction\s+$/.test(pre)) continue;
3726
+ if (!beforeSideEffect(handler, match.index)) continue;
3727
+ if (!guardStatementCounts(handler, match.index)) continue;
3728
+ if (guardNameCounts(content, match[1])) return true;
3729
+ }
3730
+ return false;
3731
+ }
3732
+ function routeArgsQualify(content, handler) {
3733
+ const match = handler.match(/\.(?:get|post|put|patch|delete|all)\s*\(\s*["'`][^"'`]+["'`]\s*,/i);
3734
+ if (!match || match.index === void 0) return false;
3735
+ const start = match.index + match[0].length;
3736
+ const brace = handler.indexOf("{", start);
3737
+ const args = handler.slice(start, brace === -1 ? handler.length : brace);
3738
+ return guardMentioned(content, args);
3739
+ }
3740
+ function authPrefixCovers(prefix, path) {
3741
+ const normalized = prefix.length > 1 ? prefix.replace(/\/+$/, "") : prefix;
3742
+ return path === normalized || path.startsWith(normalized + "/");
3743
+ }
3744
+ var useCacheContent = null;
3745
+ var useCacheByKey = /* @__PURE__ */ new Map();
3746
+ function usesInScope(content, key) {
3747
+ if (useCacheContent === content) return useCacheByKey.get(key) ?? [];
3748
+ const byKey = /* @__PURE__ */ new Map();
3749
+ const re = /\b([A-Za-z_$][\w$]*)\s*\.\s*use\s*\(/g;
3750
+ let match;
3751
+ while (match = re.exec(content)) {
3752
+ const open = match.index + match[0].length - 1;
3753
+ const close = matchingCloser(content, open, "(", ")", ARG_CAP);
3754
+ if (close < 0) continue;
3755
+ const args = content.slice(open + 1, close);
3756
+ const siteKey = fnKeyAt(content, match.index);
3757
+ const site = {
3758
+ index: match.index,
3759
+ receiver: match[1],
3760
+ args,
3761
+ first: (splitArgs(args)[0] ?? "").trim(),
3762
+ key: siteKey
3763
+ };
3764
+ const list = byKey.get(siteKey);
3765
+ if (list) list.push(site);
3766
+ else byKey.set(siteKey, [site]);
3767
+ }
3768
+ useCacheContent = content;
3769
+ useCacheByKey = byKey;
3770
+ return byKey.get(key) ?? [];
3771
+ }
3772
+ function useCoversRoute(content, index) {
3773
+ const lineStart = content.lastIndexOf("\n", Math.max(0, index - 1)) + 1;
3774
+ const lineEnd = content.indexOf("\n", index);
3775
+ const line = content.slice(lineStart, lineEnd === -1 ? content.length : lineEnd);
3776
+ const route = line.match(/\b([A-Za-z_$][\w$]*)\s*\.\s*(?:get|post|put|patch|delete|all)\s*\(\s*["'`]([^"'`]+)["'`]/i);
3777
+ if (!route) return false;
3778
+ const receiver = route[1];
3779
+ const path = route[2];
3780
+ const routeKey = fnKeyAt(content, index);
3781
+ if (routeKey === "exhausted") return false;
3782
+ for (const site of usesInScope(content, routeKey)) {
3783
+ if (site.receiver !== receiver || site.index >= lineStart) continue;
3784
+ const stringPrefix2 = /^\s*["'`]([^"'`]*)["'`]/.exec(site.first)?.[1];
3785
+ const firstIsGuard = /^[A-Za-z_$][\w$]*$/.test(site.first) && GUARD_NAMES.includes(site.first) && guardNameCounts(content, site.first);
3786
+ if (stringPrefix2 === void 0 && !firstIsGuard) continue;
3787
+ const prefix = stringPrefix2 ?? "";
3788
+ if (prefix && !authPrefixCovers(prefix, path)) continue;
3789
+ if (!guardMentioned(content, site.args) && !firstIsGuard) continue;
3790
+ return true;
3791
+ }
3792
+ return false;
3793
+ }
3794
+ function isAnchoredPublicAuthPath(routePath) {
3795
+ const parts = routePath.split("/").filter(Boolean);
3796
+ if (parts.length === 0) return false;
3797
+ const last = parts[parts.length - 1];
3798
+ if (!PUBLIC_LAST.test(last)) return false;
3799
+ if (parts.length === 1) return true;
3800
+ return parts[parts.length - 2].toLowerCase() === "auth";
3801
+ }
3802
+ function isOgRoutePath(routePath) {
3803
+ return routePath.split("/").some((part) => part.toLowerCase() === "og");
3804
+ }
3805
+ function routePathFromFile(filePath) {
3806
+ const norm = filePath.replace(/\\/g, "/");
3807
+ const app = norm.match(/(?:^|\/)app\/(.*?)\/route\.[mc]?[jt]sx?$/);
3808
+ if (app) return "/" + app[1];
3809
+ const pages = norm.match(/(?:^|\/)pages\/api\/(.*)\.[mc]?[jt]sx?$/);
3810
+ if (pages) return "/api/" + pages[1].replace(/\/index$/, "");
3811
+ return null;
3812
+ }
3813
+ function expressRoutePath(handler) {
3814
+ const bodyOpen = handlerBodyOpen(handler);
3815
+ const header = bodyOpen < 0 ? handler : handler.slice(0, bodyOpen);
3816
+ const match = header.match(/\b[A-Za-z_$][\w$]*\s*\.\s*(?:get|post|put|patch|delete|all)\s*\(\s*["'`](\/[^"'`]*)["'`]/i);
3817
+ return match ? match[1] : null;
3818
+ }
3819
+ function mutatesKeyedOnParams(handler) {
3820
+ const mutates = /\.(?:updateMany|updateOne|deleteMany|deleteOne|findByIdAndUpdate|findByIdAndDelete|update|delete|save|remove|destroy)\s*\(/i.test(handler) || /\b(?:UPDATE|DELETE)\b/.test(handler);
3821
+ if (!mutates) return false;
3822
+ return /\b(?:req|request|ctx)\s*\.\s*params\b|\bparams\s*\.\s*[A-Za-z_]/.test(handler);
3823
+ }
3824
+ function splitArgs(args) {
3825
+ const parts = [];
3826
+ let start = 0;
3827
+ let depth = 0;
3828
+ let quote = "";
3829
+ for (let i = 0; i < args.length; i++) {
3830
+ const c = args[i];
3831
+ if (quote) {
3832
+ if (c === "\\") {
3833
+ i++;
3834
+ continue;
3835
+ }
3836
+ if (c === quote) quote = "";
3837
+ continue;
3838
+ }
3839
+ if (c === "'" || c === '"' || c === "`") {
3840
+ quote = c;
3841
+ continue;
3842
+ }
3843
+ if (c === "(" || c === "{" || c === "[") depth++;
3844
+ else if (c === ")" || c === "}" || c === "]") depth--;
3845
+ else if (c === "," && depth === 0) {
3846
+ parts.push(args.slice(start, i));
3847
+ start = i + 1;
3848
+ }
3849
+ }
3850
+ parts.push(args.slice(start));
3851
+ return parts;
3852
+ }
3853
+ function unwrapSecret(value) {
3854
+ let bare = value.trim().replace(/!+$/, "").trim();
3855
+ for (let n = 0; n < 4; n++) {
3856
+ if (!bare.startsWith("(")) break;
3857
+ const end = matchingCloser(bare, 0, "(", ")", ARG_CAP);
3858
+ if (end < 0 || end !== bare.length - 1) break;
3859
+ bare = bare.slice(1, -1).trim().replace(/!+$/, "").trim();
3860
+ }
3861
+ return bare;
3862
+ }
3863
+ function secretValueReal(value) {
3864
+ const bare = unwrapSecret(value);
3865
+ if (bare === '""' || bare === "''" || bare === "``" || bare === "undefined" || bare === "") return false;
3866
+ if (/(\|\||\?\?)\s*(["'`])[^"'`]*\2\s*$/.test(bare)) return false;
3867
+ return true;
3868
+ }
3869
+ function secretArgOk(args) {
3870
+ const parts = splitArgs(args).map((part) => part.trim()).filter(Boolean);
3871
+ if (parts.length >= 3) return secretValueReal(parts[2]);
3872
+ if (parts.length === 1 && parts[0].startsWith("{")) {
3873
+ const prop = parts[0].match(/\b(?:secret|signingKey|currentSigningKey|token)\s*:\s*([^,}\n]+)/i);
3874
+ if (!prop) return false;
3875
+ return secretValueReal(prop[1]);
3876
+ }
3877
+ return false;
3878
+ }
3879
+ function errorPathRejects(handler, callIndex) {
3880
+ const tryRe = /\btry\b/g;
3881
+ let tryIndex = -1;
3882
+ let match;
3883
+ while (match = tryRe.exec(handler)) {
3884
+ if (match.index < callIndex) tryIndex = match.index;
3885
+ else break;
3886
+ }
3887
+ if (tryIndex < 0) return true;
3888
+ const catchRe = /\bcatch\b/g;
3889
+ catchRe.lastIndex = callIndex;
3890
+ const caught = catchRe.exec(handler);
3891
+ if (!caught) return true;
3892
+ const brace = handler.indexOf("{", caught.index);
3893
+ if (brace < 0) return false;
3894
+ const end = matchingCloser(handler, brace, "{", "}", BRACE_CAP);
3895
+ if (end < 0) return false;
3896
+ const body = handler.slice(brace, end);
3897
+ return /\bthrow\b/.test(body) || /\breturn\b/.test(body) && /\b4\d\d\b/.test(body);
3898
+ }
3899
+ function signatureCheckQualifies(handler) {
3900
+ const callRe = /(?:\bconstructEvent|\bverifyQstashSignature)\s*\(/g;
3901
+ let match;
3902
+ while (match = callRe.exec(handler)) {
3903
+ const open = match.index + match[0].length - 1;
3904
+ const close = matchingCloser(handler, open, "(", ")", ARG_CAP);
3905
+ if (close < 0) continue;
3906
+ const args = handler.slice(open + 1, close);
3907
+ if (!/\.text\s*\(/.test(handler) && !/\.text\s*\(/.test(args)) continue;
3908
+ if (!/stripe-signature|upstash-signature/i.test(handler)) continue;
3909
+ if (!secretArgOk(args)) continue;
3910
+ if (!beforeSideEffect(handler, match.index)) continue;
3911
+ if (!errorPathRejects(handler, match.index)) continue;
3912
+ return true;
3913
+ }
3914
+ return false;
3915
+ }
3916
+ function ifBranchBody(handler, closeParen) {
3917
+ let i = closeParen + 1;
3918
+ while (i < handler.length && /\s/.test(handler[i])) i++;
3919
+ if (i >= handler.length) return null;
3920
+ if (handler[i] === "{") {
3921
+ const end = matchingCloser(handler, i, "{", "}", IF_BODY_CAP);
3922
+ if (end < 0) return null;
3923
+ return handler.slice(i + 1, end);
3924
+ }
3925
+ const limit = Math.min(handler.length, i + IF_BODY_CAP);
3926
+ const semi = handler.indexOf(";", i);
3927
+ if (semi < 0 || semi >= limit) return null;
3928
+ return handler.slice(i, semi);
3929
+ }
3930
+ function branchRejects401(body) {
3931
+ return /\breturn\b/.test(body) && /\b401\b/.test(body) || /\b(?:status|sendStatus)\s*\(\s*401\b/.test(body);
3932
+ }
3933
+ function cronSecretGates(handler) {
3934
+ const re = /\bif\s*\(/g;
3935
+ let match;
3936
+ while (match = re.exec(handler)) {
3937
+ const open = match.index + match[0].length - 1;
3938
+ const close = matchingCloser(handler, open, "(", ")", ARG_CAP);
3939
+ if (close < 0) continue;
3940
+ const cond = handler.slice(open + 1, close);
3941
+ if (!/\bCRON_SECRET\b/.test(cond)) continue;
3942
+ if (/CRON_SECRET\s*(?:&&|\?)/.test(cond)) continue;
3943
+ if (!/(?:!==|!=(?!=))/.test(cond)) continue;
3944
+ if (!beforeSideEffect(handler, match.index)) continue;
3945
+ const body = ifBranchBody(handler, close);
3946
+ if (body && branchRejects401(body)) return true;
3947
+ }
3948
+ return false;
3949
+ }
3950
+ function handlerVerb(content, index, _handler) {
2108
3951
  const lineStart = content.lastIndexOf("\n", Math.max(0, index - 1)) + 1;
2109
- const lineEnd = content.indexOf("\n", index);
3952
+ const lineEnd = content.indexOf("\n", Math.max(index, lineStart));
2110
3953
  const line = content.slice(lineStart, lineEnd === -1 ? content.length : lineEnd);
2111
- const route = line.match(/\b([A-Za-z_$][\w$]*)\s*\.\s*(?:get|post|put|patch|delete|all)\s*\(\s*["'`]([^"'`]+)["'`]/i);
2112
- if (!route) return false;
2113
- const receiver = route[1];
2114
- const path = route[2];
2115
- const useRe = new RegExp(`\\b${receiver}\\s*\\.\\s*use\\s*\\(`, "g");
3954
+ const registered = line.match(/\b[A-Za-z_$][\w$]*\s*\.\s*(get|head|post|put|patch|delete|all)\s*\(\s*["'`]/i);
3955
+ if (registered) return registered[1].toLowerCase();
3956
+ const windowStart = Math.max(0, index - 120);
3957
+ const window = content.slice(windowStart, index + 180);
3958
+ const re = /export\s+(?:async\s+)?function\s+(GET|HEAD|POST|PUT|PATCH|DELETE)\b|export\s+const\s+(GET|HEAD|POST|PUT|PATCH|DELETE)\s*(?::[^=\n]{0,120})?=/g;
3959
+ let best = null;
2116
3960
  let match;
2117
- while (match = useRe.exec(content)) {
2118
- if (match.index >= lineStart) continue;
2119
- const open = content.indexOf("(", match.index);
2120
- const close = matchingCloser(content, open, "(", ")");
2121
- if (close < 0) continue;
2122
- const args = content.slice(open + 1, close);
2123
- const prefix = /^\s*["'`]([^"'`]+)["'`]/.exec(args)?.[1] ?? "";
2124
- if (prefix && !authPrefixCovers(prefix, path)) continue;
2125
- if (guardMentioned(content, args)) return true;
3961
+ while (match = re.exec(window)) {
3962
+ const at = windowStart + match.index;
3963
+ if (at > index) continue;
3964
+ const verb = (match[1] || match[2]).toLowerCase();
3965
+ if (!best || Math.abs(at - index) < Math.abs(best.at - index)) best = { at, verb };
3966
+ }
3967
+ return best ? best.verb : null;
3968
+ }
3969
+ var authFaultForTest = false;
3970
+ function widenedAuthSuppressesBody(content, filePath, index, handler) {
3971
+ if (!handler) return false;
3972
+ const masked = blankComments(content);
3973
+ const maskedHandler = blankComments(handler);
3974
+ prepareFnCache(masked);
3975
+ if (guardCallBeforeSideEffect(masked, maskedHandler)) return true;
3976
+ if (routeArgsQualify(masked, maskedHandler)) return true;
3977
+ if (useCoversRoute(masked, index)) return true;
3978
+ const routePath = routePathFromFile(filePath) ?? expressRoutePath(maskedHandler);
3979
+ if (routePath && isAnchoredPublicAuthPath(routePath) && !mutatesKeyedOnParams(maskedHandler)) return true;
3980
+ if (routePath && isOgRoutePath(routePath)) {
3981
+ const verb = handlerVerb(masked, index, maskedHandler);
3982
+ if (verb === "get" || verb === "head") return true;
2126
3983
  }
3984
+ if (signatureCheckQualifies(maskedHandler)) return true;
3985
+ if (cronSecretGates(maskedHandler)) return true;
2127
3986
  return false;
2128
3987
  }
2129
- function isAnchoredPublicAuthPath(routePath) {
2130
- const parts = routePath.split("/").filter(Boolean);
2131
- if (parts.length === 0) return false;
2132
- const last = parts[parts.length - 1];
2133
- if (!PUBLIC_LAST.test(last)) return false;
2134
- if (parts.length === 1) return true;
2135
- return parts[parts.length - 2].toLowerCase() === "auth";
3988
+ function widenedAuthSuppresses(content, filePath, index, handler, rawContent, capability = false, strictApp = false) {
3989
+ try {
3990
+ if (authFaultForTest) throw new Error("injected");
3991
+ if (widenedAuthSuppressesBody(content, filePath, index, handler)) return true;
3992
+ if (!rawContent) return false;
3993
+ if (publicReadOnlyHandler(rawContent, filePath, index, strictApp)) return true;
3994
+ return capability && capabilityTokenHandler(rawContent, filePath, index);
3995
+ } catch {
3996
+ return false;
3997
+ }
2136
3998
  }
2137
- function isOgRoutePath(routePath) {
2138
- return routePath.split("/").some((part) => part.toLowerCase() === "og");
3999
+
4000
+ // src/weak-hash.ts
4001
+ var ARG_CAP2 = 300;
4002
+ var PF_RE = /password|passwd|passphrase|pwd/;
4003
+ var TOKEN_WORDS = ["token", "code", "otp", "nonce"];
4004
+ var RESET_WORDS = ["reset", "forgot", "recover"];
4005
+ var HASH_VERBS = ["hash", "encrypt", "digest", "verify"];
4006
+ var KEY_BLOCK = ["token", "code", "otp", "nonce", "reset", "forgot", "recover"];
4007
+ function escapeRegExp2(value) {
4008
+ return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
4009
+ }
4010
+ function nameTokens(text) {
4011
+ const out = [];
4012
+ for (const part of text.split(/[^A-Za-z0-9]+/)) {
4013
+ if (!part) continue;
4014
+ const bits = part.split(
4015
+ /(?<=[a-z])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])|(?<=[A-Za-z])(?=\d)|(?<=\d)(?=[A-Za-z])/
4016
+ );
4017
+ for (const bit of bits) if (bit) out.push(bit.toLowerCase());
4018
+ const lower = part.toLowerCase();
4019
+ if (PF_RE.test(lower) && !lower.includes("passwordless") && !bits.some((bit) => bit && PF_RE.test(bit.toLowerCase()))) {
4020
+ out.push(lower);
4021
+ }
4022
+ }
4023
+ return out;
2139
4024
  }
2140
- function routePathFromFile(filePath) {
2141
- const norm = filePath.replace(/\\/g, "/");
2142
- const app = norm.match(/(?:^|\/)app\/(.*?)\/route\.[mc]?[jt]sx?$/);
2143
- if (app) return "/" + app[1];
2144
- const pages = norm.match(/(?:^|\/)pages\/api\/(.*)\.[mc]?[jt]sx?$/);
2145
- if (pages) return "/api/" + pages[1].replace(/\/index$/, "");
2146
- return null;
4025
+ function isPf(token) {
4026
+ return PF_RE.test(token) && !token.includes("passwordless");
4027
+ }
4028
+ function wordIn(tokens, word) {
4029
+ if (tokens.some((token) => token === word)) return true;
4030
+ return tokens.some((token) => isPf(token) && token.includes(word));
4031
+ }
4032
+ function hasPf(text) {
4033
+ return nameTokens(text).some(isPf);
4034
+ }
4035
+ var TOKEN_PARTS = /* @__PURE__ */ new Set(["token", "code", "otp", "nonce"]);
4036
+ var METHOD_NAMES = /* @__PURE__ */ new Set(["encode", "hexdigest", "toString"]);
4037
+ var RUN_TOGETHER = /^(?:reset|forgot|recover|change)?(?:password|passwd|passphrase|pwd)(?:reset|forgot|recover|change)?(?:token|code|otp|nonce)$/;
4038
+ function languageOf(filePath) {
4039
+ if (filePath.endsWith(".py")) return "py";
4040
+ if (filePath.endsWith(".rb")) return "rb";
4041
+ return "js";
4042
+ }
4043
+ function namesIn(text) {
4044
+ const names = [];
4045
+ const re = /[A-Za-z_$][\w$]*/g;
4046
+ let match;
4047
+ while (match = re.exec(text)) {
4048
+ if (!METHOD_NAMES.has(match[0])) names.push(match[0]);
4049
+ }
4050
+ return names;
4051
+ }
4052
+ function nameHasPassword(name) {
4053
+ return nameTokens(name).some(isPf);
4054
+ }
4055
+ function nameHasToken(name) {
4056
+ const parts = nameTokens(name);
4057
+ if (parts.some((part) => TOKEN_PARTS.has(part))) return true;
4058
+ return name === name.toLowerCase() && RUN_TOGETHER.test(name);
4059
+ }
4060
+ function argumentHasPasswordOnly(expr) {
4061
+ return namesIn(expr).some((name) => nameHasPassword(name) && !nameHasToken(name));
4062
+ }
4063
+ function argumentGivesTokenCredit(expr) {
4064
+ const names = namesIn(expr);
4065
+ if (names.some((name) => nameHasPassword(name) && !nameHasToken(name))) return false;
4066
+ return names.some((name) => nameHasToken(name));
4067
+ }
4068
+ function isTokenValue(expr) {
4069
+ return argumentGivesTokenCredit(expr);
4070
+ }
4071
+ function containsPasswordWord(text) {
4072
+ const lower = text.toLowerCase().replace(/passwordless/g, "");
4073
+ return PF_RE.test(lower);
4074
+ }
4075
+ function isBracketKey(raw, start, end) {
4076
+ let j = start - 1;
4077
+ while (j >= 0 && /\s/.test(raw[j])) j--;
4078
+ if (j < 0 || raw[j] !== "[") return false;
4079
+ const prev = raw[j - 1] ?? "";
4080
+ const prev2 = raw[j - 2] ?? "";
4081
+ const member = /[A-Za-z0-9_$)\]]/.test(prev) || prev === "." && prev2 === "?";
4082
+ if (!member) return false;
4083
+ let a = end + 1;
4084
+ while (a < raw.length && /\s/.test(raw[a])) a++;
4085
+ return raw[a] === "]";
4086
+ }
4087
+ function isLookupCallArg(raw, start, end) {
4088
+ if (!/(?:\.(?:get|getItem|getAttribute|param)\s*\(\s*)$/.test(raw.slice(0, start))) return false;
4089
+ let a = end + 1;
4090
+ while (a < raw.length && /\s/.test(raw[a])) a++;
4091
+ return raw[a] === ")";
4092
+ }
4093
+ function applyString(chars, raw, open, close, content, lookup) {
4094
+ const ident = /^[A-Za-z_$][\w$]*$/.test(content);
4095
+ if (lookup && ident) {
4096
+ chars[open] = " ";
4097
+ chars[close] = " ";
4098
+ return;
4099
+ }
4100
+ if (lookup && containsPasswordWord(content)) {
4101
+ const marker = "pwd";
4102
+ for (let k = open; k <= close; k++) if (chars[k] !== "\n") chars[k] = " ";
4103
+ for (let k = 0; k < marker.length && open + 1 + k < close; k++) chars[open + 1 + k] = marker[k];
4104
+ return;
4105
+ }
4106
+ for (let k = open; k <= close; k++) if (chars[k] !== "\n") chars[k] = " ";
4107
+ }
4108
+ function stringPrefix(chars, quoteAt) {
4109
+ for (let len = 2; len >= 1; len--) {
4110
+ if (quoteAt - len < 0) continue;
4111
+ let ok = true;
4112
+ for (let j = 1; j <= len; j++) {
4113
+ if (!/[rRbBuUfF]/.test(chars[quoteAt - j] ?? "")) ok = false;
4114
+ }
4115
+ const before = chars[quoteAt - len - 1] ?? "";
4116
+ if (before && /[A-Za-z0-9_]/.test(before)) ok = false;
4117
+ if (ok) return len;
4118
+ }
4119
+ return 0;
4120
+ }
4121
+ function maskArgument(raw, lang) {
4122
+ const chars = raw.split("");
4123
+ const n = chars.length;
4124
+ let i = 0;
4125
+ const blank = (from, to) => {
4126
+ for (let k = from; k < to && k < n; k++) if (chars[k] !== "\n") chars[k] = " ";
4127
+ };
4128
+ while (i < n) {
4129
+ if (lang === "js" && chars[i] === "/" && chars[i + 1] === "/") {
4130
+ const start = i;
4131
+ while (i < n && chars[i] !== "\n") i++;
4132
+ blank(start, i);
4133
+ continue;
4134
+ }
4135
+ if (lang === "js" && chars[i] === "/" && chars[i + 1] === "*") {
4136
+ const start = i;
4137
+ i += 2;
4138
+ while (i < n && !(chars[i] === "*" && chars[i + 1] === "/")) i++;
4139
+ if (i < n) i += 2;
4140
+ blank(start, i);
4141
+ continue;
4142
+ }
4143
+ if ((lang === "py" || lang === "rb") && chars[i] === "#") {
4144
+ const start = i;
4145
+ while (i < n && chars[i] !== "\n") i++;
4146
+ blank(start, i);
4147
+ continue;
4148
+ }
4149
+ const quote = chars[i];
4150
+ const prefix = quote === "'" || quote === '"' ? stringPrefix(chars, i) : 0;
4151
+ const fstring = prefix > 0 && /[fF]/.test(chars.slice(i - prefix, i).join(""));
4152
+ if ((quote === "'" || quote === '"') && i + 2 < n && chars[i + 1] === quote && chars[i + 2] === quote) {
4153
+ const start = i - prefix;
4154
+ i += 3;
4155
+ const keptTriple = [];
4156
+ while (i + 2 < n && !(chars[i] === quote && chars[i + 1] === quote && chars[i + 2] === quote)) {
4157
+ if (fstring && chars[i] === "{") {
4158
+ const from = i;
4159
+ let depth = 1;
4160
+ i++;
4161
+ while (i < n && depth > 0) {
4162
+ if (chars[i] === "{") depth++;
4163
+ else if (chars[i] === "}") depth--;
4164
+ i++;
4165
+ }
4166
+ keptTriple.push([from, i]);
4167
+ continue;
4168
+ }
4169
+ if (lang === "rb" && quote === '"' && chars[i] === "#" && chars[i + 1] === "{") {
4170
+ i += 2;
4171
+ let depth = 1;
4172
+ while (i < n && depth > 0) {
4173
+ if (chars[i] === "{") depth++;
4174
+ else if (chars[i] === "}") depth--;
4175
+ i++;
4176
+ }
4177
+ continue;
4178
+ }
4179
+ i++;
4180
+ }
4181
+ const end = Math.min(n, i + 3);
4182
+ blank(start, end);
4183
+ for (const [from, to] of keptTriple) {
4184
+ for (let k = from; k < to && k < n; k++) chars[k] = raw[k];
4185
+ }
4186
+ i = end;
4187
+ continue;
4188
+ }
4189
+ if (quote === "'" || quote === '"') {
4190
+ const start = i - prefix;
4191
+ i++;
4192
+ const kept = [];
4193
+ while (i < n) {
4194
+ if (chars[i] === "\\") {
4195
+ i += 2;
4196
+ continue;
4197
+ }
4198
+ if (chars[i] === "\n") break;
4199
+ if (fstring && chars[i] === "{") {
4200
+ const from = i;
4201
+ let depth = 1;
4202
+ i++;
4203
+ while (i < n && depth > 0) {
4204
+ if (chars[i] === "{") depth++;
4205
+ else if (chars[i] === "}") depth--;
4206
+ i++;
4207
+ }
4208
+ kept.push([from, i]);
4209
+ continue;
4210
+ }
4211
+ if (lang === "rb" && quote === '"' && chars[i] === "#" && chars[i + 1] === "{") {
4212
+ const from = i;
4213
+ i += 2;
4214
+ let depth = 1;
4215
+ while (i < n && depth > 0) {
4216
+ if (chars[i] === "{") depth++;
4217
+ else if (chars[i] === "}") depth--;
4218
+ i++;
4219
+ }
4220
+ kept.push([from, i]);
4221
+ continue;
4222
+ }
4223
+ if (chars[i] === quote) break;
4224
+ i++;
4225
+ }
4226
+ const end = i < n && chars[i] === quote ? i : i;
4227
+ if (kept.length === 0 && end < n && chars[end] === quote) {
4228
+ const content = raw.slice(start + prefix + 1, end);
4229
+ const lookup = isBracketKey(raw, start + prefix, end) || isLookupCallArg(raw, start + prefix, end);
4230
+ applyString(chars, raw, start, end, content, lookup);
4231
+ } else {
4232
+ blank(start, end + (end < n && chars[end] === quote ? 1 : 0));
4233
+ for (const [from, to] of kept) {
4234
+ for (let k = from; k < to; k++) chars[k] = raw[k];
4235
+ }
4236
+ }
4237
+ i = end < n && chars[end] === quote ? end + 1 : end;
4238
+ continue;
4239
+ }
4240
+ if (quote === "`") {
4241
+ const start = i;
4242
+ i++;
4243
+ const kept = [];
4244
+ while (i < n) {
4245
+ if (chars[i] === "\\") {
4246
+ i += 2;
4247
+ continue;
4248
+ }
4249
+ if (chars[i] === "`") break;
4250
+ if (chars[i] === "$" && chars[i + 1] === "{") {
4251
+ const from = i;
4252
+ i += 2;
4253
+ let depth = 1;
4254
+ while (i < n && depth > 0) {
4255
+ if (chars[i] === "{") depth++;
4256
+ else if (chars[i] === "}") depth--;
4257
+ i++;
4258
+ }
4259
+ kept.push([from, i]);
4260
+ continue;
4261
+ }
4262
+ i++;
4263
+ }
4264
+ const end = i < n && chars[i] === "`" ? i : i;
4265
+ blank(start, end + (end < n && chars[end] === "`" ? 1 : 0));
4266
+ for (const [from, to] of kept) {
4267
+ for (let k = from; k < to; k++) chars[k] = raw[k];
4268
+ }
4269
+ i = end < n && chars[end] === "`" ? end + 1 : end;
4270
+ continue;
4271
+ }
4272
+ i++;
4273
+ }
4274
+ return chars.join("");
4275
+ }
4276
+ function digestLhsNames(content, digestAt) {
4277
+ const lineStart = content.lastIndexOf("\n", Math.max(0, digestAt - 1)) + 1;
4278
+ const line = content.slice(lineStart, digestAt);
4279
+ const assigned = /([A-Za-z_@][\w.]*)\s*=\s*$/.exec(line);
4280
+ if (!assigned) return [];
4281
+ return assigned[1].split(".").map((part) => part.replace(/^@/, "")).filter(Boolean);
4282
+ }
4283
+ function pushCall(content, open, items, veto, emptySkips) {
4284
+ const close = matchingCloser(content, open, "(", ")", ARG_CAP2);
4285
+ if (close < 0) {
4286
+ items.push({ kind: "fail", text: "", veto });
4287
+ return;
4288
+ }
4289
+ const raw = content.slice(open + 1, close);
4290
+ if (raw.trim() === "") {
4291
+ items.push({ kind: emptySkips ? "skip" : "fail", text: "", veto });
4292
+ return;
4293
+ }
4294
+ items.push({ kind: "arg", text: raw, veto });
4295
+ }
4296
+ function scopeSlice(slice, lang, hitIndent) {
4297
+ if (lang !== "js") {
4298
+ const re = /\n([ \t]*)(?:async[ \t]+)?(?:def|class)[ \t]/g;
4299
+ let m;
4300
+ while (m = re.exec(slice)) {
4301
+ const head = slice.slice(0, m.index);
4302
+ if ((head.split('"""').length - 1) % 2 === 1 || (head.split("'''").length - 1) % 2 === 1) continue;
4303
+ if (m[1].length < hitIndent) return slice.slice(0, m.index);
4304
+ }
4305
+ return slice;
4306
+ }
4307
+ let depth = 0, paren = 0, q = "";
4308
+ for (let i = 0; i < slice.length; i++) {
4309
+ const c = slice[i];
4310
+ if (q) {
4311
+ if (c === "\\") i++;
4312
+ else if (c === q) q = "";
4313
+ continue;
4314
+ }
4315
+ if (c === "'" || c === '"' || c === "`") q = c;
4316
+ else if (c === "(") paren++;
4317
+ else if (c === ")") paren--;
4318
+ else if (paren <= 0 && c === "{") depth++;
4319
+ else if (paren <= 0 && c === "}" && --depth < 0) return slice.slice(0, i);
4320
+ }
4321
+ return slice;
4322
+ }
4323
+ function collectArguments(content, lineStart, filePath) {
4324
+ const scanEnd = Math.min(content.length, lineStart + ARG_CAP2 + 40);
4325
+ const hitIndent = (/^[ \t]*/.exec(content.slice(lineStart)) ?? [""])[0].length;
4326
+ const slice = scopeSlice(content.slice(lineStart, scanEnd), languageOf(filePath), hitIndent);
4327
+ const items = [];
4328
+ const updateRe = /\.update\s*\(/g;
4329
+ let match;
4330
+ while (match = updateRe.exec(slice)) {
4331
+ if (match.index >= ARG_CAP2) break;
4332
+ const open = lineStart + match.index + match[0].lastIndexOf("(");
4333
+ pushCall(content, open, items, [], false);
4334
+ }
4335
+ const ctorRe = /hashlib\s*\.\s*[A-Za-z_]\w*\s*\(|Digest::[A-Za-z0-9_]+\s*\.\s*hexdigest\s*\(/g;
4336
+ while (match = ctorRe.exec(slice)) {
4337
+ if (match.index >= ARG_CAP2) break;
4338
+ const at = lineStart + match.index;
4339
+ const open = at + match[0].lastIndexOf("(");
4340
+ const veto = match[0].includes("Digest") ? digestLhsNames(content, at) : [];
4341
+ pushCall(content, open, items, veto, true);
4342
+ }
4343
+ const lang = languageOf(filePath);
4344
+ return items.map((item) => item.kind === "arg" ? { ...item, text: maskArgument(item.text, lang) } : item);
4345
+ }
4346
+ function gatherTokenDecision(content, lineStart, filePath) {
4347
+ const items = collectArguments(content, lineStart, filePath);
4348
+ const veto = items.flatMap((item) => item.veto);
4349
+ if (veto.some((name) => nameHasPassword(name) && !nameHasToken(name))) return false;
4350
+ const kept = items.filter((item) => item.kind !== "skip");
4351
+ if (kept.length === 0) return false;
4352
+ if (kept.some((item) => item.kind === "fail")) return false;
4353
+ if (kept.some((item) => argumentHasPasswordOnly(item.text))) return false;
4354
+ return kept.every((item) => argumentGivesTokenCredit(item.text));
4355
+ }
4356
+ function blocked(text, words) {
4357
+ const tokens = nameTokens(text);
4358
+ return words.some((word) => wordIn(tokens, word));
4359
+ }
4360
+ function namedHasher(name, expr, tokenIs) {
4361
+ if (!hasPf(name)) return false;
4362
+ const token = tokenIs === void 0 ? isTokenValue(expr) : tokenIs;
4363
+ if (blocked(name, RESET_WORDS) && token) return false;
4364
+ return true;
4365
+ }
4366
+ function hasHashVerb(name) {
4367
+ const tokens = nameTokens(name);
4368
+ return HASH_VERBS.some((word) => wordIn(tokens, word));
4369
+ }
4370
+ function perCallKeeps(name, expr, tokenIs) {
4371
+ const token = tokenIs === void 0 ? isTokenValue(expr) : tokenIs;
4372
+ if (token) return namedHasher(name, expr, token) && hasHashVerb(name);
4373
+ return hasPf(expr) || namedHasher(name, expr, token);
4374
+ }
4375
+ function hashedExprAt(content, index) {
4376
+ const slice = content.slice(index, index + ARG_CAP2);
4377
+ const updateAt = slice.search(/\.update\s*\(/);
4378
+ if (updateAt >= 0) {
4379
+ const open = index + slice.indexOf("(", updateAt);
4380
+ const close = matchingCloser(content, open, "(", ")", ARG_CAP2);
4381
+ return close < 0 ? "" : content.slice(open + 1, close);
4382
+ }
4383
+ const libAt = slice.search(/hashlib\s*\.\s*(?:md5|sha1|sha256)\s*\(/);
4384
+ if (libAt >= 0) {
4385
+ const open = index + slice.indexOf("(", libAt);
4386
+ const close = matchingCloser(content, open, "(", ")", ARG_CAP2);
4387
+ return close < 0 ? "" : content.slice(open + 1, close);
4388
+ }
4389
+ return slice.slice(0, 160);
4390
+ }
4391
+ var METHOD_RE = /^\s*(?:(?:public|private|protected|static|async|override)\s+)*([A-Za-z_$][\w$]*)\s*\([^)]*\)\s*(?::\s*[^{]+)?$/;
4392
+ var METHOD_SKIP = /* @__PURE__ */ new Set(["if", "for", "while", "switch", "catch", "function", "return"]);
4393
+ function methodHeaderName(header) {
4394
+ const last = header.slice(header.lastIndexOf("\n") + 1);
4395
+ const method = METHOD_RE.exec(last);
4396
+ if (!method || METHOD_SKIP.has(method[1])) return "";
4397
+ return method[1];
4398
+ }
4399
+ var memo = null;
4400
+ var helperFault = false;
4401
+ function lineStartsOf(content) {
4402
+ const starts = [0];
4403
+ for (let i = 0; i < content.length; i++) if (content[i] === "\n") starts.push(i + 1);
4404
+ return starts;
4405
+ }
4406
+ function lineNoAt(content, index) {
4407
+ const starts = memo && memo.content === content ? memo.lineStarts : lineStartsOf(content);
4408
+ let lo = 0;
4409
+ let hi = starts.length - 1;
4410
+ while (lo < hi) {
4411
+ const mid = lo + hi + 1 >> 1;
4412
+ if (starts[mid] <= index) lo = mid;
4413
+ else hi = mid - 1;
4414
+ }
4415
+ return lo + 1;
4416
+ }
4417
+ function maskCallSites(content, py) {
4418
+ const chars = content.split("");
4419
+ let i = 0;
4420
+ const blankUntil = (pred) => {
4421
+ while (i < chars.length && !pred(i)) {
4422
+ if (chars[i] !== "\n") chars[i] = " ";
4423
+ i++;
4424
+ }
4425
+ };
4426
+ while (i < chars.length) {
4427
+ const c = chars[i];
4428
+ if (!py && c === "/" && chars[i + 1] === "/") {
4429
+ while (i < chars.length && chars[i] !== "\n") {
4430
+ chars[i] = " ";
4431
+ i++;
4432
+ }
4433
+ continue;
4434
+ }
4435
+ if (!py && c === "/" && chars[i + 1] === "*") {
4436
+ chars[i] = " ";
4437
+ chars[i + 1] = " ";
4438
+ i += 2;
4439
+ blankUntil((n) => chars[n] === "*" && chars[n + 1] === "/");
4440
+ if (i < chars.length) {
4441
+ chars[i] = " ";
4442
+ chars[i + 1] = " ";
4443
+ i += 2;
4444
+ }
4445
+ continue;
4446
+ }
4447
+ if (py && c === "#") {
4448
+ while (i < chars.length && chars[i] !== "\n") {
4449
+ chars[i] = " ";
4450
+ i++;
4451
+ }
4452
+ continue;
4453
+ }
4454
+ if ((c === '"' || c === "'") && chars[i + 1] === c && chars[i + 2] === c) {
4455
+ const q = c;
4456
+ chars[i] = chars[i + 1] = chars[i + 2] = " ";
4457
+ i += 3;
4458
+ blankUntil((n) => chars[n] === q && chars[n + 1] === q && chars[n + 2] === q);
4459
+ if (i < chars.length) {
4460
+ chars[i] = chars[i + 1] = chars[i + 2] = " ";
4461
+ i += 3;
4462
+ }
4463
+ continue;
4464
+ }
4465
+ if (c === "'" || c === '"') {
4466
+ const q = c;
4467
+ chars[i] = " ";
4468
+ i++;
4469
+ while (i < chars.length) {
4470
+ if (chars[i] === "\\") {
4471
+ chars[i] = " ";
4472
+ if (i + 1 < chars.length && chars[i + 1] !== "\n") chars[i + 1] = " ";
4473
+ i += 2;
4474
+ continue;
4475
+ }
4476
+ if (chars[i] === "\n") break;
4477
+ if (chars[i] === q) {
4478
+ chars[i] = " ";
4479
+ i++;
4480
+ break;
4481
+ }
4482
+ chars[i] = " ";
4483
+ i++;
4484
+ }
4485
+ continue;
4486
+ }
4487
+ if (c === "`") {
4488
+ chars[i] = " ";
4489
+ i++;
4490
+ let expr = 0;
4491
+ while (i < chars.length) {
4492
+ if (expr === 0 && chars[i] === "\\") {
4493
+ chars[i] = " ";
4494
+ if (i + 1 < chars.length && chars[i + 1] !== "\n") chars[i + 1] = " ";
4495
+ i += 2;
4496
+ continue;
4497
+ }
4498
+ if (expr === 0 && chars[i] === "`") {
4499
+ chars[i] = " ";
4500
+ i++;
4501
+ break;
4502
+ }
4503
+ if (expr === 0 && chars[i] === "$" && chars[i + 1] === "{") {
4504
+ chars[i] = " ";
4505
+ chars[i + 1] = " ";
4506
+ expr = 1;
4507
+ i += 2;
4508
+ continue;
4509
+ }
4510
+ if (expr > 0) {
4511
+ if (chars[i] === "{") expr++;
4512
+ else if (chars[i] === "}") expr--;
4513
+ i++;
4514
+ continue;
4515
+ }
4516
+ if (chars[i] !== "\n") chars[i] = " ";
4517
+ i++;
4518
+ }
4519
+ continue;
4520
+ }
4521
+ i++;
4522
+ }
4523
+ return chars.join("");
2147
4524
  }
2148
- function expressRoutePath(handler) {
2149
- const bodyOpen = handlerBodyOpen(handler);
2150
- const header = bodyOpen < 0 ? handler : handler.slice(0, bodyOpen);
2151
- const match = header.match(/\b[A-Za-z_$][\w$]*\s*\.\s*(?:get|post|put|patch|delete|all)\s*\(\s*["'`](\/[^"'`]*)["'`]/i);
2152
- return match ? match[1] : null;
4525
+ function remember(content, filePath) {
4526
+ const py = filePath.endsWith(".py");
4527
+ if (memo && memo.content === content && memo.py === py) return memo;
4528
+ memo = {
4529
+ content,
4530
+ py,
4531
+ masked: maskCallSites(content, py),
4532
+ lineStarts: lineStartsOf(content)
4533
+ };
4534
+ return memo;
4535
+ }
4536
+ function argIsParam(expr, param) {
4537
+ const trimmed = expr.trim();
4538
+ const id = escapeRegExp2(param);
4539
+ return new RegExp(`^${id}$`).test(trimmed) || new RegExp(`^String\\(${id}\\)$`).test(trimmed) || new RegExp(`^Buffer\\.from\\(${id}\\)$`).test(trimmed) || new RegExp(`^${id}\\.encode\\([\\s\\S]*\\)$`).test(trimmed);
4540
+ }
4541
+ function argumentOf(content, chain, base) {
4542
+ const update = /createHash\s*\(\s*["'`](?:md5|sha1|sha256)["'`]\s*\)/.exec(chain);
4543
+ if (update) {
4544
+ const after = chain.slice(update.index + update[0].length);
4545
+ const upd = /\.update\s*\(/.exec(after);
4546
+ if (!upd) return null;
4547
+ const open2 = base + update.index + update[0].length + upd.index + upd[0].lastIndexOf("(");
4548
+ const close2 = matchingCloser(content, open2, "(", ")", ARG_CAP2);
4549
+ if (close2 < 0) return null;
4550
+ return { expr: content.slice(open2 + 1, close2), at: base + update.index };
4551
+ }
4552
+ const lib = /hashlib\s*\.\s*(?:md5|sha1|sha256)\s*\(/.exec(chain);
4553
+ if (!lib) return null;
4554
+ const open = base + lib.index + lib[0].lastIndexOf("(");
4555
+ const close = matchingCloser(content, open, "(", ")", ARG_CAP2);
4556
+ if (close < 0) return null;
4557
+ return { expr: content.slice(open + 1, close), at: base + lib.index };
4558
+ }
4559
+ function onlyReturn(body) {
4560
+ const lines = body.split("\n").map((line) => line.trim()).filter(Boolean);
4561
+ if (lines.length !== 1) return null;
4562
+ const match = /^return\s+([\s\S]+?);?$/.exec(lines[0]);
4563
+ return match ? match[1].replace(/;$/, "").trim() : null;
4564
+ }
4565
+ function qualifyingHelpers(content) {
4566
+ const found = [];
4567
+ const counts = /* @__PURE__ */ new Map();
4568
+ const note = (name) => counts.set(name, (counts.get(name) ?? 0) + 1);
4569
+ const arrow = /(?:^|[\n;])\s*(?:export\s+)?(?:const|let|var)\s+([A-Za-z_$][\w$]*)\s*=\s*(?:async\s+)?(?:\(\s*([A-Za-z_$][\w$]*)\s*(?::\s*[^)=]+)?\s*\)|([A-Za-z_$][\w$]*))\s*=>/g;
4570
+ let match;
4571
+ while (match = arrow.exec(content)) {
4572
+ const name = match[1];
4573
+ const param = match[2] || match[3];
4574
+ note(name);
4575
+ if (!param) continue;
4576
+ const at = match.index + match[0].length;
4577
+ const rest = content.slice(at);
4578
+ let chain = "";
4579
+ let base = at;
4580
+ if (/^\s*\{/.test(rest)) {
4581
+ const brace = content.indexOf("{", at);
4582
+ const end = matchingCloser(content, brace, "{", "}", 2e4);
4583
+ if (end < 0) continue;
4584
+ const body = onlyReturn(content.slice(brace + 1, end));
4585
+ if (body === null) continue;
4586
+ chain = body;
4587
+ base = brace + 1 + content.slice(brace + 1, end).indexOf(body);
4588
+ } else {
4589
+ const lineEnd = content.indexOf("\n", at);
4590
+ const semi = content.indexOf(";", at);
4591
+ let stop = lineEnd < 0 ? content.length : lineEnd;
4592
+ if (semi >= 0 && semi < stop) stop = semi;
4593
+ chain = content.slice(at, stop);
4594
+ base = at;
4595
+ }
4596
+ const hashed = argumentOf(content, chain, base);
4597
+ if (hashed && argIsParam(hashed.expr, param)) found.push({ name, at: hashed.at });
4598
+ }
4599
+ const fn = /(?:^|[\n;])\s*(?:export\s+)?(?:async\s+)?function\s+([A-Za-z_$][\w$]*)\s*\(\s*([A-Za-z_$][\w$]*)\s*(?::\s*[^)=]+)?\s*\)\s*\{/g;
4600
+ while (match = fn.exec(content)) {
4601
+ const name = match[1];
4602
+ const param = match[2];
4603
+ note(name);
4604
+ const brace = content.indexOf("{", match.index);
4605
+ const end = matchingCloser(content, brace, "{", "}", 2e4);
4606
+ if (end < 0) continue;
4607
+ const body = onlyReturn(content.slice(brace + 1, end));
4608
+ if (body === null) continue;
4609
+ const base = brace + 1 + content.slice(brace + 1, end).indexOf(body);
4610
+ const hashed = argumentOf(content, body, base);
4611
+ if (hashed && argIsParam(hashed.expr, param)) found.push({ name, at: hashed.at });
4612
+ }
4613
+ const lines = content.split("\n");
4614
+ let offset = 0;
4615
+ for (let i = 0; i < lines.length; i++) {
4616
+ const line = lines[i];
4617
+ const same = /^(\s*)def\s+([A-Za-z_]\w*)\s*\(\s*([A-Za-z_]\w*)\s*\)\s*:\s*return\s+(.+)$/.exec(line);
4618
+ if (same) {
4619
+ note(same[2]);
4620
+ const chainAt = offset + line.indexOf(same[4]);
4621
+ const hashed = argumentOf(content, same[4], chainAt);
4622
+ if (hashed && argIsParam(hashed.expr, same[3])) found.push({ name: same[2], at: hashed.at });
4623
+ } else {
4624
+ const head = /^(\s*)def\s+([A-Za-z_]\w*)\s*\(\s*([A-Za-z_]\w*)\s*\)\s*:\s*$/.exec(line);
4625
+ if (head) {
4626
+ note(head[2]);
4627
+ const next = lines[i + 1] ?? "";
4628
+ const body = /^(\s+)return\s+(.+)$/.exec(next);
4629
+ if (body && body[1].length > head[1].length) {
4630
+ let more = false;
4631
+ for (let j = i + 2; j < lines.length; j++) {
4632
+ if (!lines[j].trim()) continue;
4633
+ const ind = /^[ \t]*/.exec(lines[j])?.[0].length ?? 0;
4634
+ if (ind > head[1].length) more = true;
4635
+ break;
4636
+ }
4637
+ if (!more) {
4638
+ const chainAt = offset + line.length + 1 + next.indexOf(body[2]);
4639
+ const hashed = argumentOf(content, body[2], chainAt);
4640
+ if (hashed && argIsParam(hashed.expr, head[3])) found.push({ name: head[2], at: hashed.at });
4641
+ }
4642
+ }
4643
+ }
4644
+ }
4645
+ offset += line.length + 1;
4646
+ }
4647
+ const good = /* @__PURE__ */ new Map();
4648
+ for (const helper of found) good.set(helper.name, (good.get(helper.name) ?? 0) + 1);
4649
+ const kept = /* @__PURE__ */ new Set();
4650
+ for (const [name, count] of counts) {
4651
+ if (good.get(name) === count) kept.add(name);
4652
+ }
4653
+ const seen = /* @__PURE__ */ new Set();
4654
+ return found.filter((helper) => {
4655
+ if (!kept.has(helper.name) || seen.has(helper.name)) return false;
4656
+ seen.add(helper.name);
4657
+ return true;
4658
+ });
2153
4659
  }
2154
- function mutatesKeyedOnParams(handler) {
2155
- const mutates = /\.(?:updateMany|updateOne|deleteMany|deleteOne|findByIdAndUpdate|findByIdAndDelete|update|delete|save|remove|destroy)\s*\(/i.test(handler) || /\b(?:UPDATE|DELETE)\b/.test(handler);
2156
- if (!mutates) return false;
2157
- return /\b(?:req|request|ctx)\s*\.\s*params\b|\bparams\s*\.\s*[A-Za-z_]/.test(handler);
4660
+ function hasConditionalQuestion(window) {
4661
+ let depth = 0;
4662
+ let quote = "";
4663
+ let open = false;
4664
+ for (let i = 0; i < window.length; i++) {
4665
+ const c = window[i];
4666
+ if (quote) {
4667
+ if (c === "\\") {
4668
+ i++;
4669
+ continue;
4670
+ }
4671
+ if (c === quote) quote = "";
4672
+ continue;
4673
+ }
4674
+ if (c === "'" || c === '"' || c === "`") {
4675
+ quote = c;
4676
+ continue;
4677
+ }
4678
+ if (c === "(" || c === "[" || c === "{") depth++;
4679
+ else if (c === ")" || c === "]" || c === "}") depth = Math.max(0, depth - 1);
4680
+ else if (depth === 0 && (c === ";" || c === "\n")) open = false;
4681
+ else if (c === "?" && depth === 0 && window[i + 1] !== "?" && window[i + 1] !== "." && window[i - 1] !== "?") {
4682
+ open = true;
4683
+ }
4684
+ }
4685
+ return open;
4686
+ }
4687
+ function rawNames(content, callIndex) {
4688
+ const start = Math.max(0, callIndex - 200);
4689
+ const slice = content.slice(start, callIndex);
4690
+ const nl = slice.lastIndexOf("\n");
4691
+ const window = nl < 0 ? slice : slice.slice(nl + 1);
4692
+ const names = [];
4693
+ if (!hasConditionalQuestion(window)) {
4694
+ const key = /(["']?)([A-Za-z_$][\w$]*)\1\s*:\s*$/.exec(window);
4695
+ if (key) names.push(key[2]);
4696
+ }
4697
+ const assigned = /([A-Za-z_$][\w$.]*)(?:\s*:\s*[^=]{1,80}?)?\s*=\s*$/.exec(window);
4698
+ if (assigned) names.push(assigned[1]);
4699
+ const sub = /\[\s*(["'])([A-Za-z_$][\w$]*)\1\s*\]\s*=\s*$/.exec(window);
4700
+ if (sub) names.push(sub[2]);
4701
+ return names;
2158
4702
  }
2159
- function splitArgs(args) {
2160
- const parts = [];
2161
- let start = 0;
4703
+ function firstArg(content, open) {
4704
+ const close = matchingCloser(content, open, "(", ")", ARG_CAP2);
4705
+ if (close < 0) return null;
2162
4706
  let depth = 0;
2163
4707
  let quote = "";
2164
- for (let i = 0; i < args.length; i++) {
2165
- const c = args[i];
4708
+ for (let i = open + 1; i < close; i++) {
4709
+ const c = content[i];
2166
4710
  if (quote) {
2167
4711
  if (c === "\\") {
2168
4712
  i++;
@@ -2177,95 +4721,61 @@ function splitArgs(args) {
2177
4721
  }
2178
4722
  if (c === "(" || c === "{" || c === "[") depth++;
2179
4723
  else if (c === ")" || c === "}" || c === "]") depth--;
2180
- else if (c === "," && depth === 0) {
2181
- parts.push(args.slice(start, i));
2182
- start = i + 1;
2183
- }
4724
+ else if (c === "," && depth === 0) return content.slice(open + 1, i);
2184
4725
  }
2185
- parts.push(args.slice(start));
2186
- return parts;
4726
+ return content.slice(open + 1, close);
2187
4727
  }
2188
- function secretArgOk(args) {
2189
- const parts = splitArgs(args).map((part) => part.trim()).filter(Boolean);
2190
- const empty = (value) => {
2191
- const bare = value.replace(/!+$/, "").trim();
2192
- return bare === '""' || bare === "''" || bare === "``" || bare === "undefined" || bare === "";
2193
- };
2194
- if (parts.length >= 3) return !empty(parts[2]);
2195
- if (parts.length === 1 && parts[0].startsWith("{")) {
2196
- const prop = parts[0].match(/\b(?:secret|signingKey|currentSigningKey|token)\s*:\s*([^,}\n]+)/i);
2197
- if (!prop) return false;
2198
- return !empty(prop[1]);
4728
+ function callQualifies(content, masked, name) {
4729
+ const re = new RegExp(`(?<![\\w$.])${escapeRegExp2(name)}\\(`, "g");
4730
+ let match;
4731
+ while (match = re.exec(masked)) {
4732
+ const before = masked.slice(Math.max(0, match.index - 24), match.index);
4733
+ if (/\b(?:function|def)\s+$/.test(before)) continue;
4734
+ if (/\b(?:const|let|var)\s+$/.test(before)) continue;
4735
+ const arg = firstArg(masked, match.index + name.length);
4736
+ if (arg === null) continue;
4737
+ const names = rawNames(content, match.index);
4738
+ const argOk = hasPf(arg) && !blocked(arg, TOKEN_WORDS);
4739
+ const nameOk = names.some((label) => hasPf(label) && !blocked(label, KEY_BLOCK));
4740
+ if (argOk || nameOk) return true;
2199
4741
  }
2200
4742
  return false;
2201
4743
  }
2202
- function errorPathRejects(handler, callIndex) {
2203
- const tryRe = /\btry\b/g;
2204
- let tryIndex = -1;
2205
- let match;
2206
- while (match = tryRe.exec(handler)) {
2207
- if (match.index < callIndex) tryIndex = match.index;
2208
- else break;
4744
+ function helperWeakIndexes(content, filePath) {
4745
+ try {
4746
+ if (helperFault) throw new Error("injected");
4747
+ const slot = remember(content, filePath);
4748
+ const helpers = qualifyingHelpers(content);
4749
+ const indexes = [];
4750
+ for (const helper of helpers) {
4751
+ if (callQualifies(content, slot.masked, helper.name)) indexes.push(helper.at);
4752
+ }
4753
+ return indexes;
4754
+ } catch {
4755
+ remember(content, filePath);
4756
+ return [];
2209
4757
  }
2210
- if (tryIndex < 0) return true;
2211
- const catchRe = /\bcatch\b/g;
2212
- catchRe.lastIndex = callIndex;
2213
- const caught = catchRe.exec(handler);
2214
- if (!caught) return true;
2215
- const brace = handler.indexOf("{", caught.index);
2216
- if (brace < 0) return false;
2217
- const end = matchingCloser(handler, brace, "{", "}");
2218
- if (end < 0) return false;
2219
- const body = handler.slice(brace, end);
2220
- return /\bthrow\b/.test(body) || /\breturn\b/.test(body) && /\b4\d\d\b/.test(body);
2221
4758
  }
2222
- function signatureCheckQualifies(handler) {
2223
- const callRe = /(?:\bconstructEvent|\bverifyQstashSignature)\s*\(/g;
4759
+ function pythonDefs(content) {
4760
+ const defs = [];
4761
+ const re = /^([ \t]*)def\s+([A-Za-z_]\w*)\s*\(/gm;
2224
4762
  let match;
2225
- while (match = callRe.exec(handler)) {
2226
- const open = match.index + match[0].length - 1;
2227
- const close = matchingCloser(handler, open, "(", ")");
2228
- if (close < 0) continue;
2229
- const args = handler.slice(open + 1, close);
2230
- if (!/\.text\s*\(/.test(handler) && !/\.text\s*\(/.test(args)) continue;
2231
- if (!/stripe-signature|upstash-signature/i.test(handler)) continue;
2232
- if (!secretArgOk(args)) continue;
2233
- if (!beforeSideEffect(handler, match.index)) continue;
2234
- if (!errorPathRejects(handler, match.index)) continue;
2235
- return true;
4763
+ while (match = re.exec(content)) {
4764
+ defs.push({ name: match[2], indent: match[1].length, at: match.index });
2236
4765
  }
2237
- return false;
4766
+ return defs;
2238
4767
  }
2239
- function cronSecretGates(handler) {
2240
- const re = /\bif\s*\(/g;
2241
- let match;
2242
- while (match = re.exec(handler)) {
2243
- const open = match.index + match[0].length - 1;
2244
- const close = matchingCloser(handler, open, "(", ")");
2245
- if (close < 0) continue;
2246
- const cond = handler.slice(open + 1, close);
2247
- if (!/\bCRON_SECRET\b/.test(cond)) continue;
2248
- if (!/(?:!==|!=(?!=))/.test(cond)) continue;
2249
- if (!beforeSideEffect(handler, match.index)) continue;
2250
- const after = handler.slice(close, close + 400);
2251
- if (/\breturn\b/.test(after) && /\b401\b/.test(after)) return true;
2252
- if (/\bstatus\s*\(\s*401\b/.test(after)) return true;
4768
+ function pythonDefName(content, index, defs) {
4769
+ const lineStart = content.lastIndexOf("\n", Math.max(0, index - 1)) + 1;
4770
+ const indent = /^[ \t]*/.exec(content.slice(lineStart))?.[0].length ?? 0;
4771
+ let name = "";
4772
+ let defIndent = -1;
4773
+ for (const def of defs) {
4774
+ if (def.at >= index) break;
4775
+ name = def.name;
4776
+ defIndent = def.indent;
2253
4777
  }
2254
- return false;
2255
- }
2256
- function widenedAuthSuppresses(content, filePath, index, handler) {
2257
- if (!handler) return false;
2258
- const masked = blankComments(content);
2259
- const maskedHandler = blankComments(handler);
2260
- if (guardCallBeforeSideEffect(masked, maskedHandler)) return true;
2261
- if (routeArgsQualify(masked, maskedHandler)) return true;
2262
- if (useCoversRoute(masked, index)) return true;
2263
- const routePath = routePathFromFile(filePath) ?? expressRoutePath(maskedHandler);
2264
- if (routePath && isAnchoredPublicAuthPath(routePath) && !mutatesKeyedOnParams(maskedHandler)) return true;
2265
- if (routePath && isOgRoutePath(routePath)) return true;
2266
- if (signatureCheckQualifies(maskedHandler)) return true;
2267
- if (cronSecretGates(maskedHandler)) return true;
2268
- return false;
4778
+ return name && indent > defIndent ? name : "";
2269
4779
  }
2270
4780
 
2271
4781
  // src/public-env.ts
@@ -2339,69 +4849,9 @@ function dotenvValue(raw) {
2339
4849
  return (hash === -1 ? v : v.slice(0, hash)).trim();
2340
4850
  }
2341
4851
 
2342
- // src/ast/parse.ts
2343
- import { parse } from "@babel/parser";
2344
- var MAX_CACHE = 256;
2345
- var cache = /* @__PURE__ */ new Map();
2346
- function cacheKey(filename, contentHash) {
2347
- return `${filename}:${contentHash}`;
2348
- }
2349
- function quickHash(s) {
2350
- let h = 5381;
2351
- const step = Math.max(1, Math.floor(s.length / 32));
2352
- for (let i = 0; i < s.length; i += step) {
2353
- h = (h << 5) + h + s.charCodeAt(i) | 0;
2354
- }
2355
- return h * 31 + s.length | 0;
2356
- }
2357
- function pickLanguage(filename) {
2358
- if (/\.tsx$/i.test(filename)) return "tsx";
2359
- if (/\.jsx$/i.test(filename)) return "jsx";
2360
- if (/\.(ts|cts|mts)$/i.test(filename)) return "ts";
2361
- if (/\.(js|cjs|mjs)$/i.test(filename)) return "js";
2362
- return null;
2363
- }
2364
- function parseFile(content, filename) {
2365
- const lang = pickLanguage(filename);
2366
- if (!lang) return null;
2367
- if (!content || content.length === 0) return null;
2368
- const key = cacheKey(filename, quickHash(content));
2369
- if (cache.has(key)) return cache.get(key) ?? null;
2370
- const plugins = [];
2371
- if (lang === "ts" || lang === "tsx") plugins.push("typescript");
2372
- if (lang === "jsx" || lang === "tsx") plugins.push("jsx");
2373
- plugins.push("decorators-legacy", "classProperties", "dynamicImport", "topLevelAwait");
2374
- let ast = null;
2375
- try {
2376
- ast = parse(content, {
2377
- sourceType: "unambiguous",
2378
- allowImportExportEverywhere: true,
2379
- allowReturnOutsideFunction: true,
2380
- allowAwaitOutsideFunction: true,
2381
- allowUndeclaredExports: true,
2382
- errorRecovery: true,
2383
- plugins
2384
- });
2385
- } catch {
2386
- cache.set(key, null);
2387
- if (cache.size > MAX_CACHE) {
2388
- const firstKey = cache.keys().next().value;
2389
- if (firstKey !== void 0) cache.delete(firstKey);
2390
- }
2391
- return null;
2392
- }
2393
- const entry = { ast, language: lang };
2394
- cache.set(key, entry);
2395
- if (cache.size > MAX_CACHE) {
2396
- const firstKey = cache.keys().next().value;
2397
- if (firstKey !== void 0) cache.delete(firstKey);
2398
- }
2399
- return entry;
2400
- }
2401
-
2402
4852
  // src/ast/taint.ts
2403
- import _traverse from "@babel/traverse";
2404
- var traverse = typeof _traverse === "function" ? _traverse : _traverse.default;
4853
+ import _traverse2 from "@babel/traverse";
4854
+ var traverse2 = typeof _traverse2 === "function" ? _traverse2 : _traverse2.default;
2405
4855
  var TAINTED_PROP_SUFFIXES = /* @__PURE__ */ new Set([
2406
4856
  "body",
2407
4857
  "query",
@@ -2572,8 +5022,8 @@ function buildTaintMap(parsed) {
2572
5022
  if (!node) return false;
2573
5023
  if (node.type === "MemberExpression") {
2574
5024
  const prop = node.property;
2575
- const propName = prop.type === "Identifier" ? prop.name : prop.type === "StringLiteral" ? prop.value : "";
2576
- if (TAINTED_PROP_SUFFIXES.has(propName)) {
5025
+ const propName2 = prop.type === "Identifier" ? prop.name : prop.type === "StringLiteral" ? prop.value : "";
5026
+ if (TAINTED_PROP_SUFFIXES.has(propName2)) {
2577
5027
  const obj = node.object;
2578
5028
  if (obj.type === "Identifier" && TAINTED_REQUEST_OBJECTS.has(obj.name)) {
2579
5029
  return true;
@@ -2666,7 +5116,7 @@ function buildTaintMap(parsed) {
2666
5116
  const pt = computePassthrough(fn);
2667
5117
  if (pt.size > 0) fnPassthrough.set(name, pt);
2668
5118
  };
2669
- traverse(parsed.ast, {
5119
+ traverse2(parsed.ast, {
2670
5120
  FunctionDeclaration(path) {
2671
5121
  const n = path.node;
2672
5122
  if (n.type === "FunctionDeclaration" && n.id && n.id.type === "Identifier") {
@@ -2689,7 +5139,7 @@ function buildTaintMap(parsed) {
2689
5139
  (a, i) => pt.has(i) && a.type !== "SpreadElement" && rec(a)
2690
5140
  );
2691
5141
  }
2692
- traverse(parsed.ast, {
5142
+ traverse2(parsed.ast, {
2693
5143
  VariableDeclarator(path) {
2694
5144
  const node = path.node;
2695
5145
  if (node.type !== "VariableDeclarator") return;
@@ -2811,10 +5261,10 @@ function buildTaintMap(parsed) {
2811
5261
  }
2812
5262
 
2813
5263
  // src/ast/traverse.ts
2814
- import _traverse2 from "@babel/traverse";
2815
- var traverse2 = typeof _traverse2 === "function" ? _traverse2 : _traverse2.default;
5264
+ import _traverse3 from "@babel/traverse";
5265
+ var traverse3 = typeof _traverse3 === "function" ? _traverse3 : _traverse3.default;
2816
5266
  function visitBinary(parsed, visit) {
2817
- traverse2(parsed.ast, {
5267
+ traverse3(parsed.ast, {
2818
5268
  BinaryExpression(path) {
2819
5269
  const line = path.node.loc?.start.line ?? 1;
2820
5270
  visit(path.node, line);
@@ -2822,7 +5272,7 @@ function visitBinary(parsed, visit) {
2822
5272
  });
2823
5273
  }
2824
5274
  function visitCalls(parsed, matchCallee, visit) {
2825
- traverse2(parsed.ast, {
5275
+ traverse3(parsed.ast, {
2826
5276
  CallExpression(path) {
2827
5277
  const node = path.node;
2828
5278
  if (!matchCallee(node.callee)) return;
@@ -3942,9 +6392,9 @@ function maskOutboundAuthNoise(code) {
3942
6392
  /\bapi_?key["']?\s{0,20}:\s{0,20}(?:process\.env\.\w{1,80}|Deno\.env\.get\(\s*["'][\w-]{1,80}["']\s*\)|import\.meta\.env\.\w{1,80}|[A-Z][A-Z0-9_]{2,79}\b)/gi,
3943
6393
  blankKeepLines
3944
6394
  );
3945
- let bindingMap = null;
6395
+ let bindingMap2 = null;
3946
6396
  const bindingSource = out;
3947
- const bindings = () => bindingMap ??= collectBindings(bindingSource);
6397
+ const bindings = () => bindingMap2 ??= collectBindings(bindingSource);
3948
6398
  out = out.replace(
3949
6399
  /\b\w{0,40}[Hh]eaders\s*\.\s*(?:set|append)\s*\(\s*["'](?:authorization|x-api-key|api-key|x-goog-api-key)["']\s*,([^\n]{0,300})/gi,
3950
6400
  (call, value, at) => credentialValueReadsCaller(value, at, bindings) ? call : blankKeepLines(call)
@@ -4119,10 +6569,10 @@ function unauthenticatedTanStackHandlers(masked, filePath) {
4119
6569
  return hasAuthMiddleware(handlersAt === -1 ? block : block.slice(0, handlersAt));
4120
6570
  })();
4121
6571
  if (!routeLevelAuth) {
4122
- const METHOD_RE = /\b(GET|POST|PUT|PATCH|DELETE)\s*:\s*(?:async\s+)?(?:\(|function\b|\{|[A-Za-z_$][\w$]{0,40}\s*=>)/g;
6572
+ const METHOD_RE2 = /\b(GET|POST|PUT|PATCH|DELETE)\s*:\s*(?:async\s+)?(?:\(|function\b|\{|[A-Za-z_$][\w$]{0,40}\s*=>)/g;
4123
6573
  const methodStarts = [];
4124
6574
  let m;
4125
- while ((m = METHOD_RE.exec(masked)) !== null && methodStarts.length < 200) methodStarts.push(m.index);
6575
+ while ((m = METHOD_RE2.exec(masked)) !== null && methodStarts.length < 200) methodStarts.push(m.index);
4126
6576
  for (let k = 0; k < methodStarts.length; k++) {
4127
6577
  const start = methodStarts[k];
4128
6578
  const limit = k + 1 < methodStarts.length ? methodStarts[k + 1] : Math.min(masked.length, start + 4e4);
@@ -4337,7 +6787,7 @@ var missingAuthMiddleware = {
4337
6787
  const unauthenticated = matches.filter((m) => {
4338
6788
  const index = indexOfLine(m.line);
4339
6789
  if (isPublicRootGet(index) || handlerHasAuth(index)) return false;
4340
- if (widenedAuthSuppresses(maskedForScope, filePath, index, scopeAt(index))) return false;
6790
+ if (widenedAuthSuppresses(maskedForScope, filePath, index, scopeAt(index), content, true, true)) return false;
4341
6791
  const namedExport = NAMED_ROUTE_EXPORT_RE.exec(lineText(index));
4342
6792
  if (namedExport && secretGuarded && /^[A-Z]+$/.test(namedExport[1])) return false;
4343
6793
  if (useServerPatterns.length > 0 && (!routeLines.has(m.line) || namedExport !== null && !/^[A-Z]+$/.test(namedExport[1]))) {
@@ -5653,8 +8103,8 @@ var weakHashing = {
5653
8103
  () => "Use bcrypt, scrypt, or argon2 for password hashing \u2014 they're intentionally slow. Example: const hash = await bcrypt.hash(password, 12);"
5654
8104
  ));
5655
8105
  }
5656
- const passwordValue = /password|passwd|passphrase|pwd/i;
5657
- const resetName = /forgot|reset|recover/i;
8106
+ const defs = pythonDefs(content);
8107
+ const nameAt = /* @__PURE__ */ new Map();
5658
8108
  const weakCallPatterns = [
5659
8109
  /createHash\s*\(\s*["'`](?:md5|sha1|sha256)["'`]\s*\)/gi,
5660
8110
  /hashlib\.(?:md5|sha1|sha256)\s*\(/gi,
@@ -5669,58 +8119,49 @@ var weakHashing = {
5669
8119
  }
5670
8120
  return at;
5671
8121
  };
5672
- const hashedExpr = (index) => {
5673
- const slice = content.slice(index, index + 300);
5674
- const update = slice.match(/\.update\s*\(\s*([^)]{0,200})\)/);
5675
- if (update) return update[1];
5676
- const lib = slice.match(/hashlib\s*\.\s*(?:md5|sha1|sha256)\s*\(\s*([^)]{0,200})\)/);
5677
- if (lib) return lib[1];
5678
- return slice.slice(0, 160);
5679
- };
5680
- const tokenValue = (expr) => {
5681
- if (passwordValue.test(expr)) return false;
5682
- return /token|otp|(?:^|[^A-Za-z])code(?:[^A-Za-z]|$)/i.test(expr);
5683
- };
5684
8122
  const braceEnclosingName = (index) => {
5685
- let searchFrom = index;
5686
- for (let level = 0; level < 8; level++) {
5687
- let depth = 0;
5688
- let open = -1;
5689
- for (let i = searchFrom; i >= 0; i--) {
5690
- const c = content[i];
5691
- if (c === "}") depth++;
5692
- else if (c === "{") {
5693
- if (depth === 0) {
5694
- open = i;
5695
- break;
8123
+ const cached = nameAt.get(index);
8124
+ if (cached !== void 0) return cached;
8125
+ let name = "";
8126
+ try {
8127
+ let searchFrom = index;
8128
+ for (let level = 0; level < 8 && index - searchFrom < 2e4; level++) {
8129
+ let depth = 0;
8130
+ let open = -1;
8131
+ const limit = Math.max(0, index - 2e4);
8132
+ for (let i = searchFrom; i >= limit; i--) {
8133
+ const c = content[i];
8134
+ if (c === "}") depth++;
8135
+ else if (c === "{") {
8136
+ if (depth === 0) {
8137
+ open = i;
8138
+ break;
8139
+ }
8140
+ depth--;
5696
8141
  }
5697
- depth--;
5698
8142
  }
8143
+ if (open < 0) break;
8144
+ const header = content.slice(Math.max(0, open - 180), open);
8145
+ const named = /(?:function|def)\s+([A-Za-z_]\w*)\s*\([^)]*\)\s*$/.exec(header) || /(?:const|let|var)\s+([A-Za-z_]\w*)\s*=\s*(?:async\s*)?(?:function\b|\([^)]*\)\s*=>|[A-Za-z_]\w*\s*=>)\s*$/.exec(header);
8146
+ if (named?.[1]) {
8147
+ name = named[1];
8148
+ break;
8149
+ }
8150
+ const method = methodHeaderName(header);
8151
+ if (method) {
8152
+ name = method;
8153
+ break;
8154
+ }
8155
+ searchFrom = open - 1;
5699
8156
  }
5700
- if (open < 0) return "";
5701
- const header = content.slice(Math.max(0, open - 180), open);
5702
- const named = /(?:function|def)\s+([A-Za-z_]\w*)\s*\([^)]*\)\s*$/.exec(header) || /(?:const|let|var)\s+([A-Za-z_]\w*)\s*=\s*(?:async\s*)?(?:function\b|\([^)]*\)\s*=>|[A-Za-z_]\w*\s*=>)\s*$/.exec(header);
5703
- if (named?.[1]) return named[1];
5704
- searchFrom = open - 1;
5705
- }
5706
- return "";
5707
- };
5708
- const pythonDefName = (index) => {
5709
- const lineStart = content.lastIndexOf("\n", Math.max(0, index - 1)) + 1;
5710
- const indent = /^[ \t]*/.exec(content.slice(lineStart))?.[0].length ?? 0;
5711
- const re = /^([ \t]*)def\s+([A-Za-z_]\w*)\s*\(/gm;
5712
- re.lastIndex = 0;
5713
- const before = content.slice(0, index);
5714
- let name = "";
5715
- let defIndent = -1;
5716
- let found;
5717
- while (found = re.exec(before)) {
5718
- name = found[2];
5719
- defIndent = found[1].length;
8157
+ if (!name) name = pythonDefName(content, index, defs);
8158
+ } catch {
8159
+ name = "";
5720
8160
  }
5721
- return name && indent > defIndent ? name : "";
8161
+ nameAt.set(index, name);
8162
+ return name;
5722
8163
  };
5723
- const enclosingFunctionName = (index) => braceEnclosingName(index) || pythonDefName(index);
8164
+ const rawHits = [];
5724
8165
  for (const p of weakCallPatterns) {
5725
8166
  const raw = findMatches(
5726
8167
  content,
@@ -5729,16 +8170,23 @@ var weakHashing = {
5729
8170
  filePath,
5730
8171
  () => "Use bcrypt, scrypt, or argon2 for password hashing. These algorithms are intentionally slow so brute-force attacks are infeasible."
5731
8172
  );
8173
+ rawHits.push(...raw);
5732
8174
  for (const m of raw) {
5733
8175
  if (matches.some((existing) => existing.line === m.line)) continue;
5734
8176
  const lineStart = indexOfLineNo(m.line);
5735
- const expr = hashedExpr(lineStart);
5736
- const name = enclosingFunctionName(lineStart);
5737
- const namedHasher = /password/i.test(name) && !(resetName.test(name) && tokenValue(expr));
5738
- if (!passwordValue.test(expr) && !namedHasher) continue;
8177
+ const expr = hashedExprAt(content, lineStart);
8178
+ const token = gatherTokenDecision(content, lineStart, filePath);
8179
+ const name = braceEnclosingName(lineStart);
8180
+ if (!perCallKeeps(name, expr, token)) continue;
5739
8181
  matches.push(m);
5740
8182
  }
5741
8183
  }
8184
+ for (const at of helperWeakIndexes(content, filePath)) {
8185
+ const line = lineNoAt(content, at);
8186
+ if (matches.some((existing) => existing.line === line)) continue;
8187
+ const hit = rawHits.find((m) => m.line === line);
8188
+ if (hit) matches.push(hit);
8189
+ }
5742
8190
  return matches;
5743
8191
  }
5744
8192
  };
@@ -9447,7 +11895,7 @@ function isClientTarget(file) {
9447
11895
  function isServerTarget(file) {
9448
11896
  return !file.excluded && file.isServer;
9449
11897
  }
9450
- function lineAt(content, index) {
11898
+ function lineAt2(content, index) {
9451
11899
  let line = 1;
9452
11900
  for (let i = 0; i < index && i < content.length; i++) {
9453
11901
  if (content[i] === "\n") line++;
@@ -9550,7 +11998,7 @@ var silentFailedRead = {
9550
11998
  if (!allValuesEmpty(payload)) continue;
9551
11999
  if (HAS_MARKER.test(payload)) continue;
9552
12000
  if (/\bstatus\s*:\s*[45]\d\d/.test(body)) continue;
9553
- hits.push({ file: file.path, line: lineAt(file.content, index) });
12001
+ hits.push({ file: file.path, line: lineAt2(file.content, index) });
9554
12002
  break;
9555
12003
  }
9556
12004
  }
@@ -9560,8 +12008,8 @@ var silentFailedRead = {
9560
12008
  };
9561
12009
 
9562
12010
  // src/quality/rules/silent-failed-write.ts
9563
- import _traverse3 from "@babel/traverse";
9564
- var traverse3 = typeof _traverse3 === "function" ? _traverse3 : _traverse3.default;
12011
+ import _traverse4 from "@babel/traverse";
12012
+ var traverse4 = typeof _traverse4 === "function" ? _traverse4 : _traverse4.default;
9565
12013
  var EXTRA_EXCLUDED_PATHS = [
9566
12014
  /(?:^|\/)generated\//i,
9567
12015
  /(?:^|\/)__generated__\//i,
@@ -9695,7 +12143,7 @@ function collectFunctions(file) {
9695
12143
  const byNode = /* @__PURE__ */ new Map();
9696
12144
  if (!parsed) return { reachable: /* @__PURE__ */ new Map() };
9697
12145
  const handlerRefNames = /* @__PURE__ */ new Set();
9698
- traverse3(parsed.ast, {
12146
+ traverse4(parsed.ast, {
9699
12147
  JSXAttribute(path) {
9700
12148
  const name = path.node.name;
9701
12149
  if (name.type !== "JSXIdentifier" || !HANDLER_ATTRIBUTE.test(name.name)) return;
@@ -9705,7 +12153,7 @@ function collectFunctions(file) {
9705
12153
  if (expr.type === "Identifier") handlerRefNames.add(expr.name);
9706
12154
  }
9707
12155
  });
9708
- traverse3(parsed.ast, {
12156
+ traverse4(parsed.ast, {
9709
12157
  Function(path) {
9710
12158
  const info = {
9711
12159
  path,
@@ -9722,7 +12170,7 @@ function collectFunctions(file) {
9722
12170
  byNode.set(path.node, info);
9723
12171
  }
9724
12172
  });
9725
- traverse3(parsed.ast, {
12173
+ traverse4(parsed.ast, {
9726
12174
  CallExpression(path) {
9727
12175
  const name = calleeName(path.node.callee);
9728
12176
  if (!name) return;
@@ -9910,7 +12358,7 @@ var silentFailedWrite = {
9910
12358
  const reachableByNode = /* @__PURE__ */ new Map();
9911
12359
  for (const info of reachable.keys()) reachableByNode.set(info.path.node, info);
9912
12360
  const reportedUnits = /* @__PURE__ */ new Set();
9913
- traverse3(parsed.ast, {
12361
+ traverse4(parsed.ast, {
9914
12362
  CallExpression(path) {
9915
12363
  if (!isFetchCallee(path.node.callee)) return;
9916
12364
  if (inAmbientContext(path)) return;
@@ -9958,7 +12406,7 @@ var silentFailedWrite = {
9958
12406
  reportedUnits.add(unit.start);
9959
12407
  hits.push({
9960
12408
  file: file.path,
9961
- line: lineAt(file.content, nodeStart(call)),
12409
+ line: lineAt2(file.content, nodeStart(call)),
9962
12410
  detail: okShape === true ? `${unit.name ? `\`${unit.name}\` ` : "This handler "}checks the response status and then does nothing with the failure \u2014 it falls through to the same success message, optimistic update or redirect it would show on a 200. The user is told a destructive change landed when it may not have.` : void 0
9963
12411
  });
9964
12412
  }
@@ -10486,8 +12934,8 @@ var stateBeforeEffect = {
10486
12934
  const columnLabel = `${transition.table.replace(/["'`]/g, "")}.${transition.column.replace(/["'`]/g, "")}`;
10487
12935
  hits.push({
10488
12936
  file: file.path,
10489
- line: lineAt(file.content, effect.index),
10490
- detail: `\`${columnLabel}\` is moved out of \`${normValue(consumed.value)}\` on line ${lineAt(file.content, transition.index)}, and only then does \`${effect.label}\` run \u2014 with its failure caught and swallowed. If the transfer fails, the row says it was paid, the money never moved, and the pending query will never select that row again.`
12937
+ line: lineAt2(file.content, effect.index),
12938
+ detail: `\`${columnLabel}\` is moved out of \`${normValue(consumed.value)}\` on line ${lineAt2(file.content, transition.index)}, and only then does \`${effect.label}\` run \u2014 with its failure caught and swallowed. If the transfer fails, the row says it was paid, the money never moved, and the pending query will never select that row again.`
10491
12939
  });
10492
12940
  }
10493
12941
  }
@@ -10505,22 +12953,22 @@ var SKIP_KEYS = /* @__PURE__ */ new Set([
10505
12953
  "trailingComments",
10506
12954
  "innerComments"
10507
12955
  ]);
10508
- function walk(node, visit) {
12956
+ function walk2(node, visit) {
10509
12957
  if (!node || typeof node !== "object") return;
10510
12958
  if (Array.isArray(node)) {
10511
- for (const child of node) walk(child, visit);
12959
+ for (const child of node) walk2(child, visit);
10512
12960
  return;
10513
12961
  }
10514
12962
  const record = node;
10515
12963
  if (typeof record.type === "string") visit(node);
10516
12964
  for (const key of Object.keys(record)) {
10517
12965
  if (SKIP_KEYS.has(key)) continue;
10518
- walk(record[key], visit);
12966
+ walk2(record[key], visit);
10519
12967
  }
10520
12968
  }
10521
12969
  function containsType(root, types) {
10522
12970
  let found = false;
10523
- walk(root, (n) => {
12971
+ walk2(root, (n) => {
10524
12972
  if (types.includes(n.type)) found = true;
10525
12973
  });
10526
12974
  return found;
@@ -10634,7 +13082,7 @@ function hasEnvSchemaFor(code, name) {
10634
13082
  }
10635
13083
  function readsRequestHeader(node, facts) {
10636
13084
  let found = false;
10637
- walk(node, (n) => {
13085
+ walk2(node, (n) => {
10638
13086
  if (found) return;
10639
13087
  if (n.type === "Identifier" && n.name === "headers") found = true;
10640
13088
  if (n.type === "CallExpression" || n.type === "OptionalCallExpression") {
@@ -10654,7 +13102,7 @@ function collectFacts(file) {
10654
13102
  };
10655
13103
  const ast = file.parsed?.ast;
10656
13104
  if (!ast) return facts;
10657
- walk(ast, (n) => {
13105
+ walk2(ast, (n) => {
10658
13106
  if (n.type !== "VariableDeclarator" || !n.init) return;
10659
13107
  const init = n.init;
10660
13108
  let source = init;
@@ -10700,13 +13148,13 @@ function collectFacts(file) {
10700
13148
  }
10701
13149
  });
10702
13150
  const names = /* @__PURE__ */ new Set([...facts.envAlias.values()]);
10703
- walk(ast, (n) => {
13151
+ walk2(ast, (n) => {
10704
13152
  if (n.type === "MemberExpression" || n.type === "CallExpression") {
10705
13153
  const direct = envVarName(n);
10706
13154
  if (direct) names.add(direct);
10707
13155
  }
10708
13156
  });
10709
- walk(ast, (n) => {
13157
+ walk2(ast, (n) => {
10710
13158
  if (n.type === "IfStatement") {
10711
13159
  for (const name of names) {
10712
13160
  if (facts.guarded.has(name)) continue;
@@ -11027,7 +13475,7 @@ var mouseOnlyControl = {
11027
13475
  if (isAsChildTrigger(jsxParent)) return;
11028
13476
  const dressed = attributeSource(findAttribute(opening, "className"), file.code) + " " + attributeSource(findAttribute(opening, "class"), file.code) + " " + attributeSource(findAttribute(opening, "style"), file.code);
11029
13477
  if (!AFFORDANCE.test(dressed)) return;
11030
- const line = opening.loc?.start.line ?? lineAt(file.content, opening.start ?? 0);
13478
+ const line = opening.loc?.start.line ?? lineAt2(file.content, opening.start ?? 0);
11031
13479
  hits.push({ file: file.path, line });
11032
13480
  });
11033
13481
  }
@@ -11275,7 +13723,7 @@ var undeclaredModal = {
11275
13723
  if (!hasFocusableDescendant(element)) continue;
11276
13724
  if (declaresSemantics(element)) continue;
11277
13725
  if (!isOpenGated(element, parents, baseName2)) continue;
11278
- const line = opening.loc?.start.line ?? lineAt(file.content, opening.start ?? 0);
13726
+ const line = opening.loc?.start.line ?? lineAt2(file.content, opening.start ?? 0);
11279
13727
  hits.push({ file: file.path, line });
11280
13728
  break;
11281
13729
  }
@@ -11495,7 +13943,7 @@ var unboundedList = {
11495
13943
  if (REDUCING_MEMBER.test(afterQuery)) return;
11496
13944
  const binding = resultBinding(statement);
11497
13945
  if (binding && nextUseReduces(file.code, binding, end)) return;
11498
- const line = node.loc?.start.line ?? lineAt(file.content, node.start ?? 0);
13946
+ const line = node.loc?.start.line ?? lineAt2(file.content, node.start ?? 0);
11499
13947
  hits.push({ file: file.path, line });
11500
13948
  reported = true;
11501
13949
  });
@@ -11651,7 +14099,7 @@ var unassociatedLabel = {
11651
14099
  const field = fieldAfter(element.end, openings);
11652
14100
  if (!field) continue;
11653
14101
  if (fieldIsNamed(field)) continue;
11654
- const line = opening.loc?.start.line ?? lineAt(file.content, opening.start ?? 0);
14102
+ const line = opening.loc?.start.line ?? lineAt2(file.content, opening.start ?? 0);
11655
14103
  hits.push({ file: file.path, line });
11656
14104
  }
11657
14105
  }
@@ -11660,11 +14108,11 @@ var unassociatedLabel = {
11660
14108
  };
11661
14109
 
11662
14110
  // src/quality/rules/failed-read-empty-state.ts
11663
- import _traverse4 from "@babel/traverse";
14111
+ import _traverse5 from "@babel/traverse";
11664
14112
  import { getBindingIdentifiers } from "@babel/types";
11665
14113
 
11666
14114
  // src/quality/rules/scope.ts
11667
- function unwrap(node) {
14115
+ function unwrap2(node) {
11668
14116
  let cur = node;
11669
14117
  while (cur.type === "TSAsExpression" || cur.type === "TSNonNullExpression" || cur.type === "TSTypeAssertion" || cur.type === "TSSatisfiesExpression") {
11670
14118
  cur = cur.expression;
@@ -11710,7 +14158,7 @@ function isEmptyInitial(node) {
11710
14158
  }
11711
14159
 
11712
14160
  // src/quality/rules/failed-read-empty-state.ts
11713
- var traverse4 = typeof _traverse4 === "function" ? _traverse4 : _traverse4.default;
14161
+ var traverse5 = typeof _traverse5 === "function" ? _traverse5 : _traverse5.default;
11714
14162
  var READ_ERROR_PATH_SIGNALS = ERROR_PATH_SIGNALS.filter(
11715
14163
  (re) => re.source !== /\.catch\s*\(/.source
11716
14164
  );
@@ -11731,10 +14179,10 @@ function mentionsJsonParse(node, code) {
11731
14179
  return /\.json\s*\(/.test(code.slice(nodeStart(node), nodeEnd(node)));
11732
14180
  }
11733
14181
  function chainParsesBody(node, code) {
11734
- let cur = unwrap(node);
14182
+ let cur = unwrap2(node);
11735
14183
  for (; ; ) {
11736
14184
  if (cur.type === "CallExpression" || cur.type === "OptionalCallExpression") {
11737
- const callee = unwrap(cur.callee);
14185
+ const callee = unwrap2(cur.callee);
11738
14186
  if ((callee.type === "MemberExpression" || callee.type === "OptionalMemberExpression") && callee.property.type === "Identifier") {
11739
14187
  const method = callee.property.name;
11740
14188
  if (method === "json") return true;
@@ -11744,14 +14192,14 @@ function chainParsesBody(node, code) {
11744
14192
  return true;
11745
14193
  }
11746
14194
  }
11747
- cur = unwrap(callee.object);
14195
+ cur = unwrap2(callee.object);
11748
14196
  continue;
11749
14197
  }
11750
14198
  cur = callee;
11751
14199
  continue;
11752
14200
  }
11753
14201
  if (cur.type === "MemberExpression" || cur.type === "OptionalMemberExpression") {
11754
- cur = unwrap(cur.object);
14202
+ cur = unwrap2(cur.object);
11755
14203
  continue;
11756
14204
  }
11757
14205
  return false;
@@ -11765,7 +14213,7 @@ function parsedBodyBindings(unit, code) {
11765
14213
  const names = /* @__PURE__ */ new Set();
11766
14214
  const record = (id, init) => {
11767
14215
  if (!id || !init) return;
11768
- const awaited = unwrap(init);
14216
+ const awaited = unwrap2(init);
11769
14217
  if (awaited.type !== "AwaitExpression") return;
11770
14218
  if (!chainParsesBody(awaited.argument, code)) return;
11771
14219
  boundNames(id, names);
@@ -11801,12 +14249,12 @@ function parsedBodyBindings(unit, code) {
11801
14249
  return names;
11802
14250
  }
11803
14251
  function derivesFromParsedBody(node, bodies, code) {
11804
- let cur = unwrap(node);
14252
+ let cur = unwrap2(node);
11805
14253
  while (cur && (cur.type === "MemberExpression" || cur.type === "OptionalMemberExpression")) {
11806
- cur = unwrap(cur.object);
14254
+ cur = unwrap2(cur.object);
11807
14255
  }
11808
14256
  if (cur.type === "Identifier") return bodies.has(cur.name);
11809
- if (cur.type === "AwaitExpression") cur = unwrap(cur.argument);
14257
+ if (cur.type === "AwaitExpression") cur = unwrap2(cur.argument);
11810
14258
  return chainParsesBody(cur, code);
11811
14259
  }
11812
14260
  function emptyFallbackArgument(node) {
@@ -11861,7 +14309,7 @@ var failedReadEmptyState = {
11861
14309
  const parsed = file.parsed;
11862
14310
  if (!parsed) continue;
11863
14311
  const examined = /* @__PURE__ */ new Set();
11864
- traverse4(parsed.ast, {
14312
+ traverse5(parsed.ast, {
11865
14313
  CallExpression(path) {
11866
14314
  if (!isFetchCallee(path.node.callee)) return;
11867
14315
  const unit = unitFor(path);
@@ -11883,7 +14331,7 @@ var failedReadEmptyState = {
11883
14331
  const fallback = emptyFallbackArgument(arg);
11884
14332
  if (!fallback) return;
11885
14333
  if (!derivesFromParsedBody(fallback.left, bodies, file.code)) return;
11886
- hit = { line: lineAt(file.content, nodeStart(fallback)), setter: name };
14334
+ hit = { line: lineAt2(file.content, nodeStart(fallback)), setter: name };
11887
14335
  }
11888
14336
  });
11889
14337
  if (!hit) return;
@@ -11901,8 +14349,8 @@ var failedReadEmptyState = {
11901
14349
  };
11902
14350
 
11903
14351
  // src/quality/rules/autosave-armed-by-failed-load.ts
11904
- import _traverse5 from "@babel/traverse";
11905
- var traverse5 = typeof _traverse5 === "function" ? _traverse5 : _traverse5.default;
14352
+ import _traverse6 from "@babel/traverse";
14353
+ var traverse6 = typeof _traverse6 === "function" ? _traverse6 : _traverse6.default;
11906
14354
  function writerTouchesEmptyState(writers) {
11907
14355
  for (const writer of writers) {
11908
14356
  let found = false;
@@ -11982,7 +14430,7 @@ var autosaveArmedByFailedLoad = {
11982
14430
  if (!parsed) continue;
11983
14431
  if (!EMPTY_INITIAL.test(file.code)) continue;
11984
14432
  const armedInFinally = /* @__PURE__ */ new Map();
11985
- traverse5(parsed.ast, {
14433
+ traverse6(parsed.ast, {
11986
14434
  TryStatement(path) {
11987
14435
  const finalizer = path.get("finalizer");
11988
14436
  if (!finalizer || Array.isArray(finalizer) || !finalizer.node) return;
@@ -12000,7 +14448,7 @@ var autosaveArmedByFailedLoad = {
12000
14448
  });
12001
14449
  if (armedInFinally.size === 0) continue;
12002
14450
  const writingFunctions = /* @__PURE__ */ new Map();
12003
- traverse5(parsed.ast, {
14451
+ traverse6(parsed.ast, {
12004
14452
  Function(path) {
12005
14453
  const src = file.code.slice(nodeStart(path.node), nodeEnd(path.node));
12006
14454
  if (!PERSISTENT_WRITE.test(src)) return;
@@ -12021,7 +14469,7 @@ var autosaveArmedByFailedLoad = {
12021
14469
  }
12022
14470
  });
12023
14471
  const reported = /* @__PURE__ */ new Set();
12024
- traverse5(parsed.ast, {
14472
+ traverse6(parsed.ast, {
12025
14473
  CallExpression(path) {
12026
14474
  if (!isEffectCall2(path.node)) return;
12027
14475
  const cb = path.get("arguments.0");
@@ -12045,7 +14493,7 @@ var autosaveArmedByFailedLoad = {
12045
14493
  reported.add(state);
12046
14494
  hits.push({
12047
14495
  file: file.path,
12048
- line: lineAt(file.content, armLine),
14496
+ line: lineAt2(file.content, armLine),
12049
14497
  detail: `\`${state}\` is what permits this component to write the user's state back, and it is set in a \`finally\` \u2014 so a load that threw arms the write exactly like one that succeeded, while the component still holds its initial empty values.`
12050
14498
  });
12051
14499
  }
@@ -12057,8 +14505,8 @@ var autosaveArmedByFailedLoad = {
12057
14505
  };
12058
14506
 
12059
14507
  // src/quality/rules/config-skipped-work.ts
12060
- import _traverse6 from "@babel/traverse";
12061
- var traverse6 = typeof _traverse6 === "function" ? _traverse6 : _traverse6.default;
14508
+ import _traverse7 from "@babel/traverse";
14509
+ var traverse7 = typeof _traverse7 === "function" ? _traverse7 : _traverse7.default;
12062
14510
  var MUTATING_METHODS = /* @__PURE__ */ new Set(["POST", "PUT", "PATCH", "DELETE"]);
12063
14511
  var DURABLE_WRITE = /\b(?:INSERT\s+INTO\b|UPDATE\s+\w+\s+SET\b|DELETE\s+FROM\b)|\bprisma\s*\.\s*\w+\s*\.\s*(?:create|createMany|update|updateMany|delete|deleteMany|upsert)\s*\(|\.from\s*\([^)]*\)\s*\.\s*(?:insert|update|delete|upsert)\s*\(|\b(?:db|tx|trx)\s*\.\s*(?:insert|update|delete)\s*\(/i;
12064
14512
  var EXTERNAL_MUTATION = /\b\w+\s*\.\s*\w+\s*\.\s*(?:create|send|update|delete|cancel|charge|capture|refund)\s*\(|\bfetch\s*\([^)]{0,300}?method\s*:\s*["'`](?:POST|PUT|PATCH|DELETE)["'`]/is;
@@ -12111,7 +14559,7 @@ var configSkippedWork = {
12111
14559
  if (BOOKKEEPING.test(file.path)) continue;
12112
14560
  const parsed = file.parsed;
12113
14561
  if (!parsed) continue;
12114
- traverse6(parsed.ast, {
14562
+ traverse7(parsed.ast, {
12115
14563
  Function(path) {
12116
14564
  const node = path.node;
12117
14565
  let name = node.id?.name ?? null;
@@ -12153,7 +14601,7 @@ var configSkippedWork = {
12153
14601
  if (writeMatch && BOOKKEEPING.test(after.slice(writeMatch.index, writeMatch.index + 120))) continue;
12154
14602
  hits.push({
12155
14603
  file: file.path,
12156
- line: lineAt(file.content, guard.start),
14604
+ line: lineAt2(file.content, guard.start),
12157
14605
  detail: `This early return answers with the same payload shape (\`{${guard.shape}}\`) as the handler's success return, so a caller cannot tell that the work was skipped. ${fnSource.length > 0 ? "" : ""}The write below it never runs, and whoever made the request is told it did.`
12158
14606
  });
12159
14607
  break;
@@ -12176,8 +14624,8 @@ function isConfigAbsenceTest(test, ifPath, code) {
12176
14624
  }
12177
14625
 
12178
14626
  // src/quality/rules/stale-response-wins.ts
12179
- import _traverse7 from "@babel/traverse";
12180
- var traverse7 = typeof _traverse7 === "function" ? _traverse7 : _traverse7.default;
14627
+ import _traverse8 from "@babel/traverse";
14628
+ var traverse8 = typeof _traverse8 === "function" ? _traverse8 : _traverse8.default;
12181
14629
  var ORDERING_GUARD = /\breturn\s*\(\s*\)\s*=>|\bAbortController\b|\bsignal\b|\bcancell?ed\b|\bignore\b|\bstale\b|\bisMounted\b|\baborted\b/i;
12182
14630
  var SETTER2 = /^set[A-Z][A-Za-z0-9_]*$/;
12183
14631
  function calleeIdentifier2(node) {
@@ -12273,7 +14721,7 @@ var staleResponseWins = {
12273
14721
  if (!isClientTarget(file)) continue;
12274
14722
  const parsed = file.parsed;
12275
14723
  if (!parsed) continue;
12276
- traverse7(parsed.ast, {
14724
+ traverse8(parsed.ast, {
12277
14725
  CallExpression(path) {
12278
14726
  if (!isEffectCall3(path.node)) return;
12279
14727
  const args = path.node.arguments;
@@ -12319,7 +14767,7 @@ var staleResponseWins = {
12319
14767
  (d) => derivesFromDep(ident2, /* @__PURE__ */ new Set([d]), cb, file.code)
12320
14768
  );
12321
14769
  if (!driving.some((d) => userDriven(d, cb))) continue;
12322
- hit = { line: lineAt(file.content, nodeStart(inner.node)), ident: ident2 };
14770
+ hit = { line: lineAt2(file.content, nodeStart(inner.node)), ident: ident2 };
12323
14771
  return;
12324
14772
  }
12325
14773
  }
@@ -12360,8 +14808,8 @@ function userDriven(dep, at) {
12360
14808
  }
12361
14809
 
12362
14810
  // src/quality/rules/lost-update-counter.ts
12363
- import _traverse8 from "@babel/traverse";
12364
- var traverse8 = typeof _traverse8 === "function" ? _traverse8 : _traverse8.default;
14811
+ import _traverse9 from "@babel/traverse";
14812
+ var traverse9 = typeof _traverse9 === "function" ? _traverse9 : _traverse9.default;
12365
14813
  var COUNTER_COLUMN = /^(?:credits?|balance|stock|quantity|qty|tokens?|seats?|points?|inventory|remaining|available)$/i;
12366
14814
  var WRITE_CALL = /\bUPDATE\s+\w|\.\s*update\s*\(|\.\s*set\s*\(|\bprisma\s*\.\s*\w+\s*\.\s*update\b/i;
12367
14815
  var ATOMIC_OR_SERIALISED = /\b(?:increment|decrement)\s*:|\bsql`[^`]*\b\w+\s*[-+]\s*|\bSET\s+(\w+)\s*=\s*\1\s*[-+]|\.\s*rpc\s*\(|\btransaction\s*\(|\bBEGIN\s+IMMEDIATE\b|\bFOR\s+UPDATE\b|\block\s*\.\s*acquire\s*\(|\bmutex\b|\bredlock\b|\bWHERE[^;]{0,120}\b\w+\s*=\s*\?[^;]{0,40}\bAND\b[^;]{0,120}\bversion\b/i;
@@ -12399,7 +14847,7 @@ var lostUpdateCounter = {
12399
14847
  const parsed = file.parsed;
12400
14848
  if (!parsed) continue;
12401
14849
  let firedInFile = false;
12402
- traverse8(parsed.ast, {
14850
+ traverse9(parsed.ast, {
12403
14851
  BinaryExpression(path) {
12404
14852
  if (firedInFile || hits.length >= MAX_PER_SCAN2) return;
12405
14853
  const op = path.node.operator;
@@ -12426,7 +14874,7 @@ var lostUpdateCounter = {
12426
14874
  firedInFile = true;
12427
14875
  hits.push({
12428
14876
  file: file.path,
12429
- line: lineAt(file.content, nodeStart(path.node)),
14877
+ line: lineAt2(file.content, nodeStart(path.node)),
12430
14878
  detail: `\`${readLocal}.${column}\` is read, changed here, and written back, so two requests that arrive together both start from the same value and one of the two changes is lost. Let the database do the arithmetic instead.`
12431
14879
  });
12432
14880
  }
@@ -12957,6 +15405,7 @@ export {
12957
15405
  attachInlineSuppressed,
12958
15406
  attachScanSuppression,
12959
15407
  authPrefixCovers,
15408
+ bearerProvenanceSafe,
12960
15409
  billingWebhookUnmatchedProps,
12961
15410
  bucketFiles,
12962
15411
  buildMarkerIndex,
@@ -12967,6 +15416,7 @@ export {
12967
15416
  calculateGrade,
12968
15417
  callSpreads,
12969
15418
  capWarnings,
15419
+ capabilityTokenHandler,
12970
15420
  checkIntent,
12971
15421
  clampCount,
12972
15422
  classifyExposure,
@@ -13061,11 +15511,15 @@ export {
13061
15511
  parseSupabaseConfig,
13062
15512
  perCallTimeoutMs,
13063
15513
  planCause,
15514
+ publicHttpsUrl,
15515
+ publicReadOnlyHandler,
13064
15516
  publicSuppressedRecord,
13065
15517
  qualityRules,
13066
15518
  readInlineSuppressed,
13067
15519
  readScanSuppression,
15520
+ refineDirectObjectFindings,
13068
15521
  replaceBlockComments,
15522
+ resetStructuralState,
13069
15523
  routeForFile,
13070
15524
  routePathFromFile,
13071
15525
  runCustomRules,
@@ -13076,8 +15530,10 @@ export {
13076
15530
  scanMultiFile,
13077
15531
  scanQuality,
13078
15532
  scanTokenNullProps,
15533
+ setStructuralFaultForTest,
13079
15534
  sqlInjection,
13080
15535
  stripeWebhookUnprotected,
15536
+ structuralParseCount,
13081
15537
  supabaseFunctionName,
13082
15538
  supabaseNoRLS,
13083
15539
  suppressionSummary,