xploitscan-shared-rules 2.4.25 → 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.cjs CHANGED
@@ -76,6 +76,7 @@ __export(index_exports, {
76
76
  attachInlineSuppressed: () => attachInlineSuppressed,
77
77
  attachScanSuppression: () => attachScanSuppression,
78
78
  authPrefixCovers: () => authPrefixCovers,
79
+ bearerProvenanceSafe: () => bearerProvenanceSafe,
79
80
  billingWebhookUnmatchedProps: () => billingWebhookUnmatchedProps,
80
81
  bucketFiles: () => bucketFiles,
81
82
  buildMarkerIndex: () => buildMarkerIndex,
@@ -86,6 +87,7 @@ __export(index_exports, {
86
87
  calculateGrade: () => calculateGrade,
87
88
  callSpreads: () => callSpreads,
88
89
  capWarnings: () => capWarnings,
90
+ capabilityTokenHandler: () => capabilityTokenHandler,
89
91
  checkIntent: () => checkIntent,
90
92
  clampCount: () => clampCount,
91
93
  classifyExposure: () => classifyExposure,
@@ -180,11 +182,15 @@ __export(index_exports, {
180
182
  parseSupabaseConfig: () => parseSupabaseConfig,
181
183
  perCallTimeoutMs: () => perCallTimeoutMs,
182
184
  planCause: () => planCause,
185
+ publicHttpsUrl: () => publicHttpsUrl,
186
+ publicReadOnlyHandler: () => publicReadOnlyHandler,
183
187
  publicSuppressedRecord: () => publicSuppressedRecord,
184
188
  qualityRules: () => qualityRules,
185
189
  readInlineSuppressed: () => readInlineSuppressed,
186
190
  readScanSuppression: () => readScanSuppression,
191
+ refineDirectObjectFindings: () => refineDirectObjectFindings,
187
192
  replaceBlockComments: () => replaceBlockComments,
193
+ resetStructuralState: () => resetStructuralState,
188
194
  routeForFile: () => routeForFile,
189
195
  routePathFromFile: () => routePathFromFile,
190
196
  runCustomRules: () => runCustomRules,
@@ -195,8 +201,10 @@ __export(index_exports, {
195
201
  scanMultiFile: () => scanMultiFile,
196
202
  scanQuality: () => scanQuality,
197
203
  scanTokenNullProps: () => scanTokenNullProps,
204
+ setStructuralFaultForTest: () => setStructuralFaultForTest,
198
205
  sqlInjection: () => sqlInjection,
199
206
  stripeWebhookUnprotected: () => stripeWebhookUnprotected,
207
+ structuralParseCount: () => structuralParseCount,
200
208
  supabaseFunctionName: () => supabaseFunctionName,
201
209
  supabaseNoRLS: () => supabaseNoRLS,
202
210
  suppressionSummary: () => suppressionSummary,
@@ -219,7 +227,7 @@ __export(index_exports, {
219
227
  module.exports = __toCommonJS(index_exports);
220
228
 
221
229
  // src/version.ts
222
- var SCANNER_VERSION = "2.4.25";
230
+ var SCANNER_VERSION = "2.4.26";
223
231
 
224
232
  // src/snippet.ts
225
233
  var cacheContent = null;
@@ -2159,6 +2167,1374 @@ function checkIntent(files, findings) {
2159
2167
  return { statements, mismatches, sources, unchallenged, uncheckable };
2160
2168
  }
2161
2169
 
2170
+ // src/structural-handlers.ts
2171
+ var import_traverse = __toESM(require("@babel/traverse"), 1);
2172
+
2173
+ // src/ast/parse.ts
2174
+ var import_parser = require("@babel/parser");
2175
+ var MAX_CACHE = 256;
2176
+ var cache = /* @__PURE__ */ new Map();
2177
+ function cacheKey(filename, digest2) {
2178
+ return `${filename}:${digest2}`;
2179
+ }
2180
+ function fullDigest(s) {
2181
+ let h1 = 5381;
2182
+ let h2 = 52711;
2183
+ for (let i = 0; i < s.length; i++) {
2184
+ const c = s.charCodeAt(i);
2185
+ h1 = Math.imul(h1, 33) + c | 0;
2186
+ h2 = Math.imul(h2, 31) + c | 0;
2187
+ }
2188
+ return `${s.length}:${h1}:${h2}`;
2189
+ }
2190
+ function pickLanguage(filename) {
2191
+ if (/\.tsx$/i.test(filename)) return "tsx";
2192
+ if (/\.jsx$/i.test(filename)) return "jsx";
2193
+ if (/\.(ts|cts|mts)$/i.test(filename)) return "ts";
2194
+ if (/\.(js|cjs|mjs)$/i.test(filename)) return "js";
2195
+ return null;
2196
+ }
2197
+ function parseFile(content, filename) {
2198
+ const lang = pickLanguage(filename);
2199
+ if (!lang) return null;
2200
+ if (!content || content.length === 0) return null;
2201
+ const key = cacheKey(filename, fullDigest(content));
2202
+ const hit = cache.get(key);
2203
+ if (hit && hit.content === content) return hit.value;
2204
+ const plugins = [];
2205
+ if (lang === "ts" || lang === "tsx") plugins.push("typescript");
2206
+ if (lang === "jsx" || lang === "tsx") plugins.push("jsx");
2207
+ plugins.push("decorators-legacy", "classProperties", "dynamicImport", "topLevelAwait");
2208
+ let ast = null;
2209
+ try {
2210
+ ast = (0, import_parser.parse)(content, {
2211
+ sourceType: "unambiguous",
2212
+ allowImportExportEverywhere: true,
2213
+ allowReturnOutsideFunction: true,
2214
+ allowAwaitOutsideFunction: true,
2215
+ allowUndeclaredExports: true,
2216
+ errorRecovery: true,
2217
+ plugins
2218
+ });
2219
+ } catch {
2220
+ cache.set(key, { content, value: null });
2221
+ if (cache.size > MAX_CACHE) {
2222
+ const firstKey = cache.keys().next().value;
2223
+ if (firstKey !== void 0) cache.delete(firstKey);
2224
+ }
2225
+ return null;
2226
+ }
2227
+ const entry = { ast, language: lang };
2228
+ cache.set(key, { content, value: entry });
2229
+ if (cache.size > MAX_CACHE) {
2230
+ const firstKey = cache.keys().next().value;
2231
+ if (firstKey !== void 0) cache.delete(firstKey);
2232
+ }
2233
+ return entry;
2234
+ }
2235
+
2236
+ // src/structural-handlers.ts
2237
+ var traverse = typeof import_traverse.default === "function" ? import_traverse.default : import_traverse.default.default;
2238
+ var PARSE_BYTES = 256 * 1024;
2239
+ var LOOKUP_LIMIT = 200;
2240
+ var METHODS = /* @__PURE__ */ new Set(["get", "head", "post", "put", "patch", "delete"]);
2241
+ var ROLE_WORD = /^(admin|superadmin|staff|owner)$/i;
2242
+ var faultName = null;
2243
+ var parseCount = 0;
2244
+ var modelCache = /* @__PURE__ */ new Map();
2245
+ var bearerSpanCache = /* @__PURE__ */ new Map();
2246
+ function setStructuralFaultForTest(name) {
2247
+ faultName = name;
2248
+ }
2249
+ function structuralParseCount() {
2250
+ return parseCount;
2251
+ }
2252
+ function resetStructuralState() {
2253
+ parseCount = 0;
2254
+ modelCache.clear();
2255
+ bearerSpanCache.clear();
2256
+ faultName = null;
2257
+ }
2258
+ function fault(name) {
2259
+ if (faultName === name || faultName === "all") throw new Error("injected");
2260
+ }
2261
+ function digest(text) {
2262
+ let h1 = 5381;
2263
+ let h2 = 52711;
2264
+ for (let i = 0; i < text.length; i++) {
2265
+ const c = text.charCodeAt(i);
2266
+ h1 = Math.imul(h1, 33) + c | 0;
2267
+ h2 = Math.imul(h2, 31) + c | 0;
2268
+ }
2269
+ return `${text.length}:${h1}:${h2}`;
2270
+ }
2271
+ function lineAt(content, index) {
2272
+ let line = 1;
2273
+ const end = Math.min(index, content.length);
2274
+ for (let i = 0; i < end; i++) if (content.charCodeAt(i) === 10) line++;
2275
+ return line;
2276
+ }
2277
+ function unwrap(node) {
2278
+ let cur = node;
2279
+ while (cur) {
2280
+ if (cur.type === "AwaitExpression" || cur.type === "ParenthesizedExpression" || cur.type === "TSAsExpression" || cur.type === "TSNonNullExpression" || cur.type === "TSSatisfiesExpression" || cur.type === "TSTypeAssertion" || cur.type === "ChainExpression") {
2281
+ cur = cur.expression ?? cur.argument;
2282
+ continue;
2283
+ }
2284
+ break;
2285
+ }
2286
+ return cur;
2287
+ }
2288
+ function propName(prop) {
2289
+ if (!prop) return "";
2290
+ if (prop.key?.type === "Identifier" && !prop.computed) return String(prop.key.name);
2291
+ if (prop.key?.type === "StringLiteral") return String(prop.key.value);
2292
+ return "";
2293
+ }
2294
+ function walk(node, visit) {
2295
+ if (!node || typeof node !== "object" || !node.type) return;
2296
+ visit(node);
2297
+ for (const key of Object.keys(node)) {
2298
+ if (key === "loc" || key === "start" || key === "end" || key === "range" || key === "leadingComments" || key === "trailingComments" || key === "innerComments") {
2299
+ continue;
2300
+ }
2301
+ const child = node[key];
2302
+ if (Array.isArray(child)) {
2303
+ for (const item of child) if (item && typeof item === "object" && item.type) walk(item, visit);
2304
+ } else if (child && typeof child === "object" && child.type) {
2305
+ walk(child, visit);
2306
+ }
2307
+ }
2308
+ }
2309
+ function paramNames(fn) {
2310
+ const names = [];
2311
+ for (const param of fn.params ?? []) {
2312
+ if (param?.type === "Identifier") names.push(param.name);
2313
+ else if (param?.type === "AssignmentPattern" && param.left?.type === "Identifier") names.push(param.left.name);
2314
+ else if (param?.type === "ObjectPattern") {
2315
+ for (const prop of param.properties ?? []) {
2316
+ if (prop?.type === "ObjectProperty" && prop.key?.type === "Identifier") names.push(prop.key.name);
2317
+ }
2318
+ }
2319
+ }
2320
+ return names;
2321
+ }
2322
+ function statementsOf(fn) {
2323
+ const body = fn?.body;
2324
+ if (!body) return [];
2325
+ if (body.type === "BlockStatement") return body.body ?? [];
2326
+ return [{ type: "ReturnStatement", argument: body, start: body.start, end: body.end }];
2327
+ }
2328
+ function usable(parsed, content) {
2329
+ if (!parsed?.ast) return false;
2330
+ const ast = parsed.ast;
2331
+ if (Array.isArray(ast.errors) && ast.errors.length > 0) return false;
2332
+ if (typeof ast.end === "number" && ast.end !== content.length) return false;
2333
+ return true;
2334
+ }
2335
+ function controlScope(path) {
2336
+ let cur = path?.parentPath;
2337
+ while (cur) {
2338
+ const t = cur.node?.type;
2339
+ if (t === "IfStatement" || t === "ForStatement" || t === "WhileStatement" || t === "DoWhileStatement" || t === "ForInStatement" || t === "ForOfStatement" || t === "SwitchStatement" || t === "TryStatement" || t === "CatchClause" || t === "ConditionalExpression") {
2340
+ return null;
2341
+ }
2342
+ if (t === "FunctionDeclaration" || t === "FunctionExpression" || t === "ArrowFunctionExpression" || t === "ObjectMethod" || t === "ClassMethod") {
2343
+ return cur.node.start ?? 0;
2344
+ }
2345
+ if (t === "Program") return 0;
2346
+ cur = cur.parentPath;
2347
+ }
2348
+ return 0;
2349
+ }
2350
+ function stringEntries(node) {
2351
+ const value = unwrap(node);
2352
+ if (!value) return null;
2353
+ let array = value;
2354
+ if (value.type === "NewExpression" && value.callee?.type === "Identifier" && value.callee.name === "Set") {
2355
+ if ((value.arguments ?? []).length !== 1) return null;
2356
+ array = value.arguments[0];
2357
+ }
2358
+ if (array?.type !== "ArrayExpression") return null;
2359
+ const entries = [];
2360
+ for (const el of array.elements ?? []) {
2361
+ if (!el || el.type !== "StringLiteral") return null;
2362
+ entries.push(String(el.value));
2363
+ }
2364
+ return entries.length > 0 ? entries : null;
2365
+ }
2366
+ function staticString(node) {
2367
+ const value = unwrap(node);
2368
+ if (!value) return null;
2369
+ if (value.type === "StringLiteral") return String(value.value);
2370
+ if (value.type === "TemplateLiteral" && (value.expressions ?? []).length === 0) {
2371
+ return value.quasis.map((q) => q.value?.cooked ?? "").join("");
2372
+ }
2373
+ return null;
2374
+ }
2375
+ function isProcessEnv(node) {
2376
+ const value = unwrap(node);
2377
+ if (value?.type !== "MemberExpression" || value.computed) return false;
2378
+ if (value.property?.type !== "Identifier") return false;
2379
+ const env = value.object;
2380
+ return env?.type === "MemberExpression" && !env.computed && env.property?.name === "env" && env.object?.type === "Identifier" && env.object.name === "process";
2381
+ }
2382
+ function isEnvRead(node) {
2383
+ const value = unwrap(node);
2384
+ if (!value) return false;
2385
+ if (value.type === "MemberExpression") {
2386
+ if (value.object?.type === "Identifier" && value.object.name === "process" && value.property?.name === "env") return true;
2387
+ if (isProcessEnv(value)) return true;
2388
+ if (value.object?.type === "Identifier" && value.object.name === "env") return true;
2389
+ if (value.object?.type === "MemberExpression" && value.object.property?.name === "env" && (value.object.object?.name === "Deno" || value.object.object?.name === "Bun")) {
2390
+ return true;
2391
+ }
2392
+ if (value.object?.type === "MetaProperty" && value.property?.name === "env") return true;
2393
+ }
2394
+ if (value.type === "CallExpression" && value.callee?.type === "MemberExpression" && value.callee.property?.name === "get" && value.callee.object?.type === "MemberExpression" && value.callee.object.property?.name === "env") {
2395
+ return true;
2396
+ }
2397
+ return false;
2398
+ }
2399
+ function registrationOk(content, start, method, appRouter) {
2400
+ const slice = content.slice(start, start + 160).replace(/^\s+/, "");
2401
+ if (appRouter) return new RegExp(`^export\\s+(?:async\\s+)?function\\s+${method}\\b`).test(slice);
2402
+ return new RegExp(`^[A-Za-z_$][\\w$]*\\s*\\.\\s*${method}\\s*\\(`, "i").test(slice);
2403
+ }
2404
+ function pushHandler(handlers, content, fn, method, path, receiver, line, regStart, routeArgs, appRouter, scope) {
2405
+ if (typeof fn?.start !== "number" || typeof fn?.end !== "number") return;
2406
+ if (!registrationOk(content, regStart, appRouter ? method.toUpperCase() : method, appRouter)) return;
2407
+ const params = paramNames(fn);
2408
+ handlers.push({
2409
+ method,
2410
+ path,
2411
+ receiver,
2412
+ line,
2413
+ fnStart: fn.start,
2414
+ fnEnd: fn.end,
2415
+ regStart,
2416
+ params,
2417
+ statements: statementsOf(fn),
2418
+ fn,
2419
+ appRouter,
2420
+ routeArgs,
2421
+ scope,
2422
+ requestName: params[0] ?? "req",
2423
+ replyName: params[1] ?? "res"
2424
+ });
2425
+ }
2426
+ function build(parsed, content) {
2427
+ const ast = parsed.ast;
2428
+ const handlers = [];
2429
+ const uses = [];
2430
+ const functions = [];
2431
+ const consts = /* @__PURE__ */ new Set();
2432
+ const assigned = /* @__PURE__ */ new Set();
2433
+ traverse(ast, {
2434
+ FunctionExpression(path) {
2435
+ const node = path.node;
2436
+ if (typeof node.start === "number" && typeof node.end === "number") functions.push({ start: node.start, end: node.end });
2437
+ },
2438
+ ArrowFunctionExpression(path) {
2439
+ const node = path.node;
2440
+ if (typeof node.start === "number" && typeof node.end === "number") functions.push({ start: node.start, end: node.end });
2441
+ },
2442
+ VariableDeclaration(path) {
2443
+ if (path.node.kind !== "const") return;
2444
+ for (const decl of path.node.declarations ?? []) {
2445
+ if (decl?.id?.type === "Identifier") consts.add(decl.id.name);
2446
+ }
2447
+ },
2448
+ AssignmentExpression(path) {
2449
+ if (path.node.left?.type === "Identifier") assigned.add(path.node.left.name);
2450
+ },
2451
+ FunctionDeclaration(path) {
2452
+ const node = path.node;
2453
+ if (typeof node.start === "number" && typeof node.end === "number") functions.push({ start: node.start, end: node.end });
2454
+ if (path.parent?.type !== "ExportNamedDeclaration") return;
2455
+ const name = path.node.id?.name;
2456
+ if (!name || !/^(GET|HEAD|POST|PUT|PATCH|DELETE)$/.test(name)) return;
2457
+ const reg = path.parent;
2458
+ pushHandler(
2459
+ handlers,
2460
+ content,
2461
+ path.node,
2462
+ name.toLowerCase(),
2463
+ "",
2464
+ "",
2465
+ reg.loc?.start?.line ?? path.node.loc?.start?.line ?? 0,
2466
+ reg.start ?? path.node.start,
2467
+ [],
2468
+ true,
2469
+ 0
2470
+ );
2471
+ },
2472
+ CallExpression(path) {
2473
+ const node = path.node;
2474
+ const callee = node.callee;
2475
+ const deno = callee?.type === "MemberExpression" && callee.object?.name === "Deno" && callee.property?.name === "serve" || callee?.type === "Identifier" && callee.name === "serve";
2476
+ if (deno) {
2477
+ const args2 = node.arguments ?? [];
2478
+ const last2 = args2[args2.length - 1];
2479
+ if (last2?.type === "FunctionExpression" || last2?.type === "ArrowFunctionExpression") {
2480
+ pushHandler(handlers, content, last2, "serve", "", "Deno", node.loc?.start?.line ?? 0, node.start ?? 0, args2.slice(0, -1), false, controlScope(path) ?? 0);
2481
+ }
2482
+ return;
2483
+ }
2484
+ if (callee?.type !== "MemberExpression" || callee.computed || callee.optional) return;
2485
+ if (callee.object?.type !== "Identifier" || callee.property?.type !== "Identifier") return;
2486
+ const method = String(callee.property.name);
2487
+ const receiver = String(callee.object.name);
2488
+ if (method === "use") {
2489
+ uses.push({
2490
+ receiver,
2491
+ start: node.start ?? 0,
2492
+ args: node.arguments ?? [],
2493
+ scope: controlScope(path),
2494
+ constReceiver: consts.has(receiver) && !assigned.has(receiver)
2495
+ });
2496
+ return;
2497
+ }
2498
+ const lower = method.toLowerCase();
2499
+ if (!METHODS.has(lower)) return;
2500
+ const args = node.arguments ?? [];
2501
+ const last = args[args.length - 1];
2502
+ if (last?.type !== "FunctionExpression" && last?.type !== "ArrowFunctionExpression") return;
2503
+ const pathArg = args[0];
2504
+ const routePath = pathArg?.type === "StringLiteral" ? String(pathArg.value) : staticString(pathArg) ?? "";
2505
+ pushHandler(
2506
+ handlers,
2507
+ content,
2508
+ last,
2509
+ lower,
2510
+ routePath,
2511
+ receiver,
2512
+ node.loc?.start?.line ?? 0,
2513
+ node.start ?? 0,
2514
+ args.slice(0, -1),
2515
+ false,
2516
+ controlScope(path) ?? 0
2517
+ );
2518
+ }
2519
+ });
2520
+ for (const use of uses) use.constReceiver = consts.has(use.receiver) && !assigned.has(use.receiver);
2521
+ return {
2522
+ ast,
2523
+ handlers,
2524
+ uses,
2525
+ functions,
2526
+ sets: moduleSets(ast),
2527
+ primitives: modulePrimitives(ast),
2528
+ cryptoName: importedName(ast, ["crypto", "node:crypto"]),
2529
+ hasherNames: importedNames(ast, ["bcrypt", "bcryptjs", "argon2"]),
2530
+ hashFns: hashFunctions(ast, importedName(ast, ["crypto", "node:crypto"])),
2531
+ randomNames: randomBindings(ast, importedName(ast, ["crypto", "node:crypto"]))
2532
+ };
2533
+ }
2534
+ function topLevel(ast) {
2535
+ const out = [];
2536
+ for (const stmt of ast.program?.body ?? []) {
2537
+ if (stmt?.type === "ExportNamedDeclaration" && stmt.declaration) out.push(stmt.declaration);
2538
+ else out.push(stmt);
2539
+ }
2540
+ return out;
2541
+ }
2542
+ function moduleSets(ast) {
2543
+ const sets = /* @__PURE__ */ new Map();
2544
+ for (const stmt of topLevel(ast)) {
2545
+ if (stmt?.type !== "VariableDeclaration" || stmt.kind !== "const") continue;
2546
+ for (const decl of stmt.declarations ?? []) {
2547
+ if (decl?.id?.type !== "Identifier") continue;
2548
+ const entries = stringEntries(decl.init);
2549
+ if (!entries) continue;
2550
+ if (entries.every((entry) => publicHttpsUrl(httpsHost(entry)))) sets.set(decl.id.name, entries);
2551
+ }
2552
+ }
2553
+ const mutated = /* @__PURE__ */ new Set();
2554
+ walk(ast, (node) => {
2555
+ if (node.type === "AssignmentExpression" && node.left?.type === "Identifier" && sets.has(node.left.name)) mutated.add(node.left.name);
2556
+ if (node.type === "CallExpression" && node.callee?.type === "MemberExpression" && node.callee.object?.type === "Identifier") {
2557
+ const name = node.callee.property?.name;
2558
+ if ((name === "add" || name === "delete" || name === "clear" || name === "push") && sets.has(node.callee.object.name)) {
2559
+ mutated.add(node.callee.object.name);
2560
+ }
2561
+ }
2562
+ });
2563
+ for (const name of mutated) sets.delete(name);
2564
+ return sets;
2565
+ }
2566
+ function httpsHost(host) {
2567
+ return host.includes("://") ? host : `https://${host}`;
2568
+ }
2569
+ function modulePrimitives(ast) {
2570
+ const names = /* @__PURE__ */ new Set();
2571
+ for (const stmt of topLevel(ast)) {
2572
+ if (stmt?.type !== "VariableDeclaration" || stmt.kind !== "const") continue;
2573
+ for (const decl of stmt.declarations ?? []) {
2574
+ const init = unwrap(decl?.init);
2575
+ if (decl?.id?.type === "Identifier" && init && (init.type === "StringLiteral" || init.type === "NumericLiteral" || init.type === "BooleanLiteral")) {
2576
+ names.add(decl.id.name);
2577
+ }
2578
+ }
2579
+ }
2580
+ return names;
2581
+ }
2582
+ function importedName(ast, sources) {
2583
+ const names = importedNames(ast, sources);
2584
+ return names.values().next().value ?? null;
2585
+ }
2586
+ function importedNames(ast, sources) {
2587
+ const names = /* @__PURE__ */ new Set();
2588
+ const accept = new Set(sources);
2589
+ for (const stmt of ast.program?.body ?? []) {
2590
+ if (stmt?.type === "ImportDeclaration" && accept.has(String(stmt.source?.value))) {
2591
+ for (const spec of stmt.specifiers ?? []) {
2592
+ if (spec.type === "ImportDefaultSpecifier" || spec.type === "ImportNamespaceSpecifier") names.add(spec.local.name);
2593
+ }
2594
+ }
2595
+ if (stmt?.type === "VariableDeclaration") {
2596
+ for (const decl of stmt.declarations ?? []) {
2597
+ const init = unwrap(decl?.init);
2598
+ if (decl?.id?.type !== "Identifier" || init?.type !== "CallExpression") continue;
2599
+ if (init.callee?.type !== "Identifier" || init.callee.name !== "require") continue;
2600
+ const arg = init.arguments?.[0];
2601
+ if (arg?.type === "StringLiteral" && accept.has(String(arg.value))) names.add(decl.id.name);
2602
+ }
2603
+ }
2604
+ }
2605
+ return names;
2606
+ }
2607
+ function isCreateHashChain(node, param, cryptoName) {
2608
+ const digest2 = unwrap(node);
2609
+ if (digest2?.type !== "CallExpression" || digest2.callee?.type !== "MemberExpression" || digest2.callee.property?.name !== "digest") return false;
2610
+ const digestArgs = digest2.arguments ?? [];
2611
+ if (digestArgs.length > 1) return false;
2612
+ if (digestArgs.length === 1 && digestArgs[0]?.type !== "StringLiteral") return false;
2613
+ const update = digest2.callee.object;
2614
+ if (update?.type !== "CallExpression" || update.callee?.type !== "MemberExpression" || update.callee.property?.name !== "update") return false;
2615
+ if ((update.arguments ?? []).length !== 1 || update.arguments[0]?.type !== "Identifier" || update.arguments[0].name !== param) return false;
2616
+ const created = update.callee.object;
2617
+ if (created?.type !== "CallExpression" || created.callee?.type !== "MemberExpression") return false;
2618
+ if (created.callee.property?.name !== "createHash" || created.callee.object?.name !== cryptoName) return false;
2619
+ return (created.arguments ?? []).length === 1 && created.arguments[0]?.type === "StringLiteral";
2620
+ }
2621
+ function hashFunctions(ast, cryptoName) {
2622
+ const names = /* @__PURE__ */ new Set();
2623
+ if (!cryptoName) return names;
2624
+ walk(ast, (node) => {
2625
+ if (node.type === "FunctionDeclaration" && node.id?.name && hashBody(node, cryptoName)) names.add(node.id.name);
2626
+ if (node.type === "VariableDeclarator" && node.id?.type === "Identifier") {
2627
+ const init = node.init;
2628
+ if ((init?.type === "ArrowFunctionExpression" || init?.type === "FunctionExpression") && hashBody(init, cryptoName)) names.add(node.id.name);
2629
+ }
2630
+ });
2631
+ return names;
2632
+ }
2633
+ function hashBody(fn, cryptoName) {
2634
+ if ((fn.params ?? []).length !== 1 || fn.params[0]?.type !== "Identifier") return false;
2635
+ const param = fn.params[0].name;
2636
+ let body = fn.body;
2637
+ if (body?.type === "BlockStatement") {
2638
+ if ((body.body ?? []).length !== 1 || body.body[0]?.type !== "ReturnStatement") return false;
2639
+ body = body.body[0].argument;
2640
+ }
2641
+ return isCreateHashChain(body, param, cryptoName);
2642
+ }
2643
+ function randomBindings(ast, cryptoName) {
2644
+ const names = /* @__PURE__ */ new Set();
2645
+ if (!cryptoName) return names;
2646
+ walk(ast, (node) => {
2647
+ if (node.type !== "VariableDeclarator" || node.id?.type !== "Identifier") return;
2648
+ if (isRandomBytes(unwrap(node.init), cryptoName)) names.add(node.id.name);
2649
+ });
2650
+ return names;
2651
+ }
2652
+ function isRandomBytes(node, cryptoName) {
2653
+ let call = node;
2654
+ if (call?.type === "CallExpression" && call.callee?.type === "MemberExpression" && call.callee.property?.name === "toString") {
2655
+ call = call.callee.object;
2656
+ }
2657
+ if (call?.type !== "CallExpression" || call.callee?.type !== "MemberExpression" || call.callee.property?.name !== "randomBytes") return false;
2658
+ if (call.callee.object?.name !== cryptoName) return false;
2659
+ const n = call.arguments?.[0];
2660
+ return n?.type === "NumericLiteral" && typeof n.value === "number" && n.value >= 16 && (call.arguments ?? []).length === 1;
2661
+ }
2662
+ function load(content, filePath) {
2663
+ fault("parse");
2664
+ if (content.length > PARSE_BYTES) return null;
2665
+ const key = `${filePath}\0${digest(content)}`;
2666
+ const hit = modelCache.get(key);
2667
+ if (hit && hit.content === content) return hit.model;
2668
+ parseCount += 1;
2669
+ const parsed = parseFile(content, filePath);
2670
+ const model = parsed && usable(parsed, content) ? build(parsed, content) : null;
2671
+ modelCache.set(key, { content, model });
2672
+ if (modelCache.size > 128) {
2673
+ const first = modelCache.keys().next().value;
2674
+ if (first !== void 0) modelCache.delete(first);
2675
+ }
2676
+ return model;
2677
+ }
2678
+ function onLine(model, content, index) {
2679
+ const line = lineAt(content, index);
2680
+ const found = model.handlers.filter((handler) => handler.line === line);
2681
+ return found.length === 1 ? found[0] : null;
2682
+ }
2683
+ function publicHttpsUrl(value) {
2684
+ try {
2685
+ fault("publicHttpsUrl");
2686
+ const url = new URL(value);
2687
+ if (url.protocol !== "https:") return false;
2688
+ if (url.username || url.password) return false;
2689
+ if (url.port !== "") return false;
2690
+ const host = url.hostname.toLowerCase().replace(/\.$/, "");
2691
+ if (!host || !host.includes(".")) return false;
2692
+ if (/^\d{1,3}(?:\.\d{1,3}){3}$/.test(host) || host.includes(":")) return false;
2693
+ if (host === "localhost" || host.endsWith(".localhost") || host.endsWith(".local") || host.endsWith(".internal") || host.endsWith(".lan") || host.endsWith(".home.arpa")) {
2694
+ return false;
2695
+ }
2696
+ return true;
2697
+ } catch {
2698
+ return false;
2699
+ }
2700
+ }
2701
+ function isReq(node, requestName) {
2702
+ const value = unwrap(node);
2703
+ return value?.type === "Identifier" && (value.name === requestName || value.name === "req" || value.name === "request" || value.name === "ctx");
2704
+ }
2705
+ function isRequestInput(node, requestName) {
2706
+ const value = unwrap(node);
2707
+ if (!value || value.type !== "MemberExpression" || value.computed) return false;
2708
+ const prop = value.property?.name;
2709
+ if (["query", "params", "body", "searchParams"].includes(prop) && isReq(value.object, requestName)) return true;
2710
+ return isRequestInput(value.object, requestName);
2711
+ }
2712
+ function hasIdentity(fn, requestName) {
2713
+ let bad = false;
2714
+ walk(fn, (node) => {
2715
+ if (node.type === "CallExpression") {
2716
+ if (node.callee?.type === "Identifier" && (node.callee.name === "cookies" || node.callee.name === "headers")) bad = true;
2717
+ if (node.callee?.type === "MemberExpression" && node.callee.property?.name === "get") {
2718
+ const arg = node.arguments?.[0];
2719
+ if (arg?.type === "StringLiteral" && /^(authorization|cookie|x-api-key)$/i.test(String(arg.value))) bad = true;
2720
+ }
2721
+ }
2722
+ if ((node.type === "MemberExpression" || node.type === "OptionalMemberExpression") && !node.computed) {
2723
+ const prop = node.property?.name;
2724
+ if (["user", "session", "cookies", "auth", "signedCookies"].includes(prop) && isReq(node.object, requestName)) bad = true;
2725
+ if (prop === "user" && node.object?.type === "MemberExpression" && node.object.property?.name === "state") bad = true;
2726
+ }
2727
+ });
2728
+ return bad;
2729
+ }
2730
+ function evalExpr(node, env, depth = 0) {
2731
+ if (!node || depth > 40) return "no";
2732
+ const value = unwrap(node);
2733
+ if (!value) return "no";
2734
+ if (value.type === "StringLiteral" || value.type === "NumericLiteral" || value.type === "BooleanLiteral" || value.type === "NullLiteral") return "value";
2735
+ if (value.type === "TemplateLiteral" && (value.expressions ?? []).length === 0) return "value";
2736
+ if (isEnvRead(value)) {
2737
+ env.bad = true;
2738
+ return "no";
2739
+ }
2740
+ if (value.type === "Identifier") {
2741
+ const known = env.allowed.get(value.name);
2742
+ if (known) return known;
2743
+ if (env.primitives.has(value.name)) return "value";
2744
+ return "no";
2745
+ }
2746
+ if (value.type === "MemberExpression" || value.type === "OptionalMemberExpression") {
2747
+ if (value.optional || value.type === "OptionalMemberExpression") return "no";
2748
+ if (value.computed) {
2749
+ if (isReq(value.property, env.requestName) || isRequestInput(value.property, env.requestName)) env.bad = true;
2750
+ return "no";
2751
+ }
2752
+ if (isRequestInput(value, env.requestName)) return "value";
2753
+ const obj = value.object;
2754
+ if (obj?.type === "Identifier" && env.allowed.get(obj.name) === "url" && (value.property?.name === "hostname" || value.property?.name === "href")) return "value";
2755
+ const inner = evalExpr(obj, env, depth + 1);
2756
+ if (inner === "value") return "value";
2757
+ return "no";
2758
+ }
2759
+ if (value.type === "NewExpression" && value.callee?.type === "Identifier" && value.callee.name === "URL") {
2760
+ if ((value.arguments ?? []).length < 1 || evalExpr(value.arguments[0], env, depth + 1) === "no") return "no";
2761
+ return "url";
2762
+ }
2763
+ if (value.type === "ObjectExpression") {
2764
+ for (const prop of value.properties ?? []) {
2765
+ if (prop?.type !== "ObjectProperty" || prop.computed) return "no";
2766
+ if (evalExpr(prop.value, env, depth + 1) === "no") return "no";
2767
+ }
2768
+ return "value";
2769
+ }
2770
+ if (value.type === "ArrayExpression") {
2771
+ for (const el of value.elements ?? []) if (!el || evalExpr(el, env, depth + 1) === "no") return "no";
2772
+ return "value";
2773
+ }
2774
+ if (value.type === "CallExpression" || value.type === "OptionalCallExpression") {
2775
+ if (value.optional || value.type === "OptionalCallExpression") return "no";
2776
+ return evalCall(value, env, depth);
2777
+ }
2778
+ return "no";
2779
+ }
2780
+ function argsAllowed(node, env, depth) {
2781
+ return (node.arguments ?? []).every((arg) => arg && evalExpr(arg, env, depth + 1) !== "no");
2782
+ }
2783
+ function callbackOk(fn, env) {
2784
+ if (!fn || fn.type !== "ArrowFunctionExpression" && fn.type !== "FunctionExpression") return false;
2785
+ const saved = new Map(env.allowed);
2786
+ const responded = env.responded;
2787
+ const bad = env.bad;
2788
+ for (const name of paramNames(fn)) env.allowed.set(name, "value");
2789
+ let ok = false;
2790
+ if (fn.body?.type === "BlockStatement") ok = (fn.body.body ?? []).every((stmt) => execStmt(stmt, env));
2791
+ else ok = evalExpr(fn.body, env) !== "no";
2792
+ env.allowed = saved;
2793
+ env.responded = responded;
2794
+ env.bad = bad;
2795
+ return ok;
2796
+ }
2797
+ function isReply(node, env) {
2798
+ const value = unwrap(node);
2799
+ return value?.type === "Identifier" && (value.name === "res" || value.name === "reply" || value.name === env.replyName);
2800
+ }
2801
+ function responseCall(node, env, depth) {
2802
+ if (node?.type === "NewExpression" && node.callee?.name === "Response") return argsAllowed(node, env, depth);
2803
+ if (node?.type !== "CallExpression") return false;
2804
+ const callee = node.callee;
2805
+ if (callee?.type === "MemberExpression" && callee.object?.type === "Identifier" && (callee.object.name === "NextResponse" || callee.object.name === "Response") && callee.property?.name === "json") {
2806
+ return argsAllowed(node, env, depth);
2807
+ }
2808
+ if (callee?.type !== "MemberExpression") return false;
2809
+ const prop = callee.property?.name;
2810
+ if (prop === "render") {
2811
+ if (!isReply(callee.object, env)) return false;
2812
+ if (node.arguments?.[0]?.type !== "StringLiteral") return false;
2813
+ return node.arguments.length < 2 || evalExpr(node.arguments[1], env, depth + 1) !== "no";
2814
+ }
2815
+ if (prop !== "json" && prop !== "send" && prop !== "end") return false;
2816
+ const target = callee.object;
2817
+ if (isReply(target, env)) return argsAllowed(node, env, depth);
2818
+ if (target?.type === "CallExpression" && target.callee?.type === "MemberExpression") {
2819
+ const inner = target.callee.property?.name;
2820
+ if ((inner === "status" || inner === "code") && isReply(target.callee.object, env) && target.arguments?.[0]?.type === "NumericLiteral") {
2821
+ return argsAllowed(node, env, depth);
2822
+ }
2823
+ }
2824
+ return false;
2825
+ }
2826
+ function urlBinding(node, env) {
2827
+ const value = unwrap(node);
2828
+ if (value?.type === "Identifier" && env.allowed.get(value.name) === "url") return value.name;
2829
+ if (value?.type === "MemberExpression" && !value.computed && value.property?.name === "href" && value.object?.type === "Identifier" && env.allowed.get(value.object.name) === "url") {
2830
+ return value.object.name;
2831
+ }
2832
+ 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") {
2833
+ return value.callee.object.name;
2834
+ }
2835
+ return null;
2836
+ }
2837
+ var MODEL_PATH = /^\/(?:v\d+(?:beta\d*)?\/)?models\/?$/;
2838
+ function optionState(node) {
2839
+ if (!node) return "absent";
2840
+ if (node.type !== "ObjectExpression") return "bad";
2841
+ let secret = false;
2842
+ for (const prop of node.properties ?? []) {
2843
+ if (prop?.type !== "ObjectProperty" || prop.computed) return "bad";
2844
+ const key = propName(prop);
2845
+ if (key !== "headers" && key !== "cache" && key !== "next" && key !== "method") return "bad";
2846
+ if (key === "method") {
2847
+ const text = staticString(prop.value);
2848
+ if (text !== "GET" && text !== "HEAD" && text !== "get" && text !== "head") return "bad";
2849
+ continue;
2850
+ }
2851
+ if (key === "headers") {
2852
+ if (prop.value?.type !== "ObjectExpression") return "bad";
2853
+ for (const header of prop.value.properties ?? []) {
2854
+ if (header?.type !== "ObjectProperty" || header.computed || !literalValue(header.value)) secret = true;
2855
+ }
2856
+ continue;
2857
+ }
2858
+ if (staticString(prop.value) === null && prop.value?.type !== "NumericLiteral" && prop.value?.type !== "BooleanLiteral") secret = true;
2859
+ }
2860
+ return secret ? "secret" : "ok";
2861
+ }
2862
+ function literalValue(node) {
2863
+ const value = unwrap(node);
2864
+ if (!value) return false;
2865
+ if (value.type === "StringLiteral" || value.type === "NumericLiteral" || value.type === "BooleanLiteral" || value.type === "NullLiteral") return true;
2866
+ if (value.type === "TemplateLiteral") return (value.expressions ?? []).length === 0;
2867
+ if (value.type === "ObjectExpression") {
2868
+ return (value.properties ?? []).every((prop) => prop?.type === "ObjectProperty" && !prop.computed && literalValue(prop.value));
2869
+ }
2870
+ if (value.type === "ArrayExpression") return (value.elements ?? []).every((el) => Boolean(el) && literalValue(el));
2871
+ return false;
2872
+ }
2873
+ function evalCall(node, env, depth) {
2874
+ if (responseCall(node, env, depth)) {
2875
+ env.responded = true;
2876
+ return "value";
2877
+ }
2878
+ const callee = node.callee;
2879
+ if (callee?.type === "Identifier" && callee.name === "fetch") {
2880
+ const state = optionState(node.arguments?.[1]);
2881
+ if (state === "bad" || (node.arguments ?? []).length > 2) return "no";
2882
+ const secret = state === "secret";
2883
+ const literal = staticString(node.arguments?.[0]);
2884
+ if (literal !== null) {
2885
+ if (!publicHttpsUrl(literal)) return "no";
2886
+ if (secret) {
2887
+ const url = new URL(literal);
2888
+ if (url.search || url.hash || !MODEL_PATH.test(url.pathname)) return "no";
2889
+ }
2890
+ env.fetchSeen = true;
2891
+ return "fetch";
2892
+ }
2893
+ const binding = urlBinding(node.arguments?.[0], env);
2894
+ if (!binding || !env.rejected.has(binding) || secret) return "no";
2895
+ env.fetchSeen = true;
2896
+ return "fetch";
2897
+ }
2898
+ if (callee?.type === "Identifier" && (callee.name === "String" || callee.name === "Number" || callee.name === "Boolean")) {
2899
+ return argsAllowed(node, env, depth) ? "value" : "no";
2900
+ }
2901
+ if (callee?.type === "MemberExpression" && !callee.computed) {
2902
+ const obj = callee.object;
2903
+ const prop = callee.property?.name;
2904
+ if (obj?.type === "Identifier" && obj.name === "JSON" && (prop === "parse" || prop === "stringify")) return argsAllowed(node, env, depth) ? "value" : "no";
2905
+ if (obj?.type === "Identifier" && obj.name === "Object" && (prop === "keys" || prop === "values" || prop === "entries")) return argsAllowed(node, env, depth) ? "value" : "no";
2906
+ if (obj?.type === "Identifier" && obj.name === "Array" && prop === "isArray") return argsAllowed(node, env, depth) ? "value" : "no";
2907
+ if ((prop === "json" || prop === "text") && obj?.type === "Identifier" && env.allowed.get(obj.name) === "fetch") return "value";
2908
+ if ((prop === "has" || prop === "includes") && obj?.type === "Identifier" && env.sets.has(obj.name)) return "value";
2909
+ if ((prop === "map" || prop === "filter") && evalExpr(obj, env, depth + 1) === "value") return callbackOk(node.arguments?.[0], env) ? "value" : "no";
2910
+ if ((prop === "slice" || prop === "join" || prop === "toString") && evalExpr(obj, env, depth + 1) !== "no") return argsAllowed(node, env, depth) ? "value" : "no";
2911
+ }
2912
+ return "no";
2913
+ }
2914
+ function has4xx(node) {
2915
+ let number = false;
2916
+ let call = false;
2917
+ walk(node, (current) => {
2918
+ if (current.type === "NumericLiteral" && current.value >= 400 && current.value < 500) number = true;
2919
+ if (current.type === "CallExpression" && ["status", "code", "json", "send"].includes(current.callee?.property?.name)) call = true;
2920
+ });
2921
+ return number && call;
2922
+ }
2923
+ function rejectConsequent(node) {
2924
+ if (!node) return false;
2925
+ if (node.type === "BlockStatement") return (node.body ?? []).length === 1 && rejectConsequent(node.body[0]);
2926
+ if (node.type === "ThrowStatement") return true;
2927
+ if (node.type === "ReturnStatement" || node.type === "ExpressionStatement") {
2928
+ const value = node.argument ?? node.expression;
2929
+ return has4xx(value);
2930
+ }
2931
+ return false;
2932
+ }
2933
+ function allowlistIf(stmt, env) {
2934
+ if (stmt?.type !== "IfStatement" || stmt.alternate || env.fetchSeen) return false;
2935
+ const test = unwrap(stmt.test);
2936
+ if (test?.type !== "UnaryExpression" || test.operator !== "!") return false;
2937
+ const call = unwrap(test.argument);
2938
+ if (call?.type !== "CallExpression" || call.callee?.type !== "MemberExpression") return false;
2939
+ const setName = call.callee.object?.type === "Identifier" ? call.callee.object.name : "";
2940
+ if (!env.sets.has(setName) || call.callee.property?.name !== "has" && call.callee.property?.name !== "includes") return false;
2941
+ const arg = call.arguments?.[0];
2942
+ if (arg?.type !== "MemberExpression" || arg.computed || arg.property?.name !== "hostname" || arg.object?.type !== "Identifier") return false;
2943
+ if (env.allowed.get(arg.object.name) !== "url") return false;
2944
+ if (!rejectConsequent(stmt.consequent)) return false;
2945
+ env.rejected.add(arg.object.name);
2946
+ return true;
2947
+ }
2948
+ function bind(id, kind, env) {
2949
+ if (!id) return false;
2950
+ if (id.type === "Identifier") {
2951
+ env.allowed.set(id.name, kind);
2952
+ return true;
2953
+ }
2954
+ if (id.type === "ObjectPattern") {
2955
+ return (id.properties ?? []).every((prop) => prop?.type === "ObjectProperty" && bind(prop.value, kind, env));
2956
+ }
2957
+ return false;
2958
+ }
2959
+ function execStmt(stmt, env) {
2960
+ if (!stmt || stmt.type === "EmptyStatement") return true;
2961
+ if (allowlistIf(stmt, env)) return true;
2962
+ if (stmt.type === "VariableDeclaration") {
2963
+ if (stmt.kind === "var") return false;
2964
+ if (stmt.kind !== "const") {
2965
+ for (const decl of stmt.declarations ?? []) {
2966
+ const init = unwrap(decl?.init);
2967
+ if (init?.type === "NewExpression" && init.callee?.type === "Identifier" && init.callee.name === "URL") return false;
2968
+ }
2969
+ }
2970
+ for (const decl of stmt.declarations ?? []) {
2971
+ const kind = evalExpr(decl.init, env);
2972
+ if (kind === "no" || !bind(decl.id, kind, env)) return false;
2973
+ }
2974
+ return true;
2975
+ }
2976
+ if (stmt.type === "ReturnStatement") {
2977
+ if (stmt.argument && evalExpr(stmt.argument, env) === "no") return false;
2978
+ env.responded = true;
2979
+ return true;
2980
+ }
2981
+ if (stmt.type === "ExpressionStatement") {
2982
+ const kind = evalExpr(stmt.expression, env);
2983
+ return kind !== "no";
2984
+ }
2985
+ return false;
2986
+ }
2987
+ function readOnlyBody(content, model, handler) {
2988
+ if (handler.method !== "get" && handler.method !== "head") return false;
2989
+ if (hasIdentity(handler.fn, handler.requestName)) return false;
2990
+ const env = {
2991
+ allowed: /* @__PURE__ */ new Map(),
2992
+ sets: model.sets,
2993
+ primitives: model.primitives,
2994
+ requestName: handler.requestName,
2995
+ replyName: handler.replyName,
2996
+ rejected: /* @__PURE__ */ new Set(),
2997
+ fetchSeen: false,
2998
+ responded: false,
2999
+ bad: false
3000
+ };
3001
+ for (const stmt of handler.statements) {
3002
+ if (!execStmt(stmt, env) || env.bad) return false;
3003
+ }
3004
+ return env.responded && !env.bad && content.length >= 0;
3005
+ }
3006
+ function sourceGuarded(content, handler) {
3007
+ const slice = content.slice(handler.fnStart, handler.fnEnd);
3008
+ return /requireUser|requireAuth|withAuth|getServerSession|\bauth\s*\(|passport|isAuthenticated|verifyAdmin|requireAdmin|verifyToken/.test(slice);
3009
+ }
3010
+ function publicReadOnlyHandler(content, filePath, index, strictApp = false) {
3011
+ try {
3012
+ fault("readOnly");
3013
+ const model = load(content, filePath);
3014
+ if (!model) return false;
3015
+ const handler = onLine(model, content, index);
3016
+ if (!handler || !readOnlyBody(content, model, handler)) return false;
3017
+ if (strictApp && handler.appRouter) {
3018
+ for (const other of model.handlers) {
3019
+ if (!other.appRouter || other === handler) continue;
3020
+ const ok = (other.method === "get" || other.method === "head") && readOnlyBody(content, model, other) || capabilityBody(model, other) || sourceGuarded(content, other);
3021
+ if (!ok) return false;
3022
+ }
3023
+ }
3024
+ return true;
3025
+ } catch {
3026
+ return false;
3027
+ }
3028
+ }
3029
+ function roleLiteral(node) {
3030
+ if (node?.type === "StringLiteral") return ROLE_WORD.test(String(node.value));
3031
+ if (node?.type === "ArrayExpression") {
3032
+ const elements = node.elements ?? [];
3033
+ return elements.length > 0 && elements.every((el) => el?.type === "StringLiteral" && ROLE_WORD.test(String(el.value)));
3034
+ }
3035
+ return false;
3036
+ }
3037
+ function argIsRole(node) {
3038
+ if (!node) return false;
3039
+ if (node.type === "Identifier") return node.name === "requireAdmin" || node.name === "verifyAdmin";
3040
+ if (node.type === "CallExpression" && node.callee?.type === "Identifier" && node.callee.name === "requireRole") {
3041
+ const args = node.arguments ?? [];
3042
+ return args.length > 0 && args.every((arg) => roleLiteral(arg));
3043
+ }
3044
+ if (node.type === "ArrayExpression") return (node.elements ?? []).some((el) => argIsRole(el));
3045
+ return false;
3046
+ }
3047
+ function lookupHasTwoParams(content, lookup, params) {
3048
+ const query = querySlice(content, lookup);
3049
+ if (!query) return false;
3050
+ const used = /* @__PURE__ */ new Set();
3051
+ const re = /req\.params\.([A-Za-z_$][\w$]*)/g;
3052
+ let match;
3053
+ while (match = re.exec(query)) used.add(match[1]);
3054
+ return [...used].filter((name) => params.includes(name)).length >= 2;
3055
+ }
3056
+ function memberScoped(content, handler, lookups) {
3057
+ const params = [...handler.path.matchAll(/:([A-Za-z_$][\w$]*)/g)].map((match) => match[1]);
3058
+ if (params.length < 2) return false;
3059
+ const inside = lookups.filter((index) => index >= handler.fnStart && index < handler.fnEnd);
3060
+ if (inside.length === 0) return false;
3061
+ return inside.every((lookup) => lookupHasTwoParams(content, lookup, params));
3062
+ }
3063
+ function narrowedGuard(content, model, handler, lookups) {
3064
+ const member = (args) => args.some((arg) => arg?.type === "Identifier" && arg.name === "requireMember") && memberScoped(content, handler, lookups);
3065
+ if (handler.routeArgs.some((arg) => argIsRole(arg)) || member(handler.routeArgs)) return true;
3066
+ for (const use of model.uses) {
3067
+ if (use.receiver !== handler.receiver || !handler.receiver) continue;
3068
+ if (use.start >= handler.regStart || use.scope === null || use.scope !== handler.scope || !use.constReceiver) continue;
3069
+ if (use.args.some((arg) => argIsRole(arg)) || member(use.args)) return true;
3070
+ }
3071
+ return false;
3072
+ }
3073
+ function paramAccess(node) {
3074
+ const value = unwrap(node);
3075
+ if (value?.type !== "MemberExpression" || value.computed || value.property?.type !== "Identifier") return null;
3076
+ const prop = String(value.property.name);
3077
+ const obj = value.object;
3078
+ if (obj?.type === "Identifier" && obj.name === "params") return prop;
3079
+ if (obj?.type === "MemberExpression" && !obj.computed && obj.property?.name === "params") return prop;
3080
+ return null;
3081
+ }
3082
+ function isNow(node) {
3083
+ const value = unwrap(node);
3084
+ if (value?.type === "CallExpression" && value.callee?.object?.name === "Date" && value.callee?.property?.name === "now" && (value.arguments ?? []).length === 0) return true;
3085
+ return value?.type === "NewExpression" && value.callee?.name === "Date" && (value.arguments ?? []).length === 0;
3086
+ }
3087
+ function filterOf(obj, hashFns, cryptoName) {
3088
+ let target = obj;
3089
+ if ((obj?.properties ?? []).length === 1 && propName(obj.properties[0]) === "where" && obj.properties[0].value?.type === "ObjectExpression") {
3090
+ target = obj.properties[0].value;
3091
+ }
3092
+ const props = target?.properties ?? [];
3093
+ if (props.length !== 2 || props.some((prop) => prop?.type !== "ObjectProperty")) return null;
3094
+ let field = "";
3095
+ let param = "";
3096
+ let expiry = "";
3097
+ for (const prop of props) {
3098
+ const key = propName(prop);
3099
+ const value = unwrap(prop.value);
3100
+ if (value?.type === "CallExpression" && value.callee?.type === "Identifier" && hashFns.has(value.callee.name)) {
3101
+ if ((value.arguments ?? []).length !== 1) return null;
3102
+ const accessed = paramAccess(value.arguments[0]);
3103
+ if (!accessed) return null;
3104
+ field = key;
3105
+ param = accessed;
3106
+ } else if (value?.type === "CallExpression") {
3107
+ const accessed = paramAccess(inlineUpdateArg(value, cryptoName));
3108
+ if (!accessed) return null;
3109
+ field = key;
3110
+ param = accessed;
3111
+ } else if (value?.type === "ObjectExpression" && (value.properties ?? []).length === 1) {
3112
+ const inner = value.properties[0];
3113
+ const name = propName(inner);
3114
+ if (name !== "$gt" && name !== "gt" || !isNow(inner.value)) return null;
3115
+ expiry = key;
3116
+ } else return null;
3117
+ }
3118
+ if (!field || !param || !expiry) return null;
3119
+ return { field, param, expiry };
3120
+ }
3121
+ function assignedFromRandom(ast, field, hashFns, randomNames, cryptoName) {
3122
+ let found = false;
3123
+ walk(ast, (node) => {
3124
+ if (node.type !== "AssignmentExpression" || node.left?.type !== "MemberExpression") return;
3125
+ if (propName(node.left) !== field && node.left.property?.name !== field) return;
3126
+ const right = unwrap(node.right);
3127
+ if (right?.type !== "CallExpression") return;
3128
+ if (right.callee?.type === "Identifier" && hashFns.has(right.callee.name)) {
3129
+ const arg2 = right.arguments?.[0];
3130
+ if (arg2?.type === "Identifier" && randomNames.has(arg2.name)) found = true;
3131
+ return;
3132
+ }
3133
+ const arg = inlineUpdateArg(right, cryptoName);
3134
+ if (arg?.type === "Identifier" && randomNames.has(arg.name)) found = true;
3135
+ });
3136
+ return found;
3137
+ }
3138
+ function inlineUpdateArg(node, cryptoName) {
3139
+ const digest2 = unwrap(node);
3140
+ if (!cryptoName || digest2?.type !== "CallExpression" || digest2.callee?.type !== "MemberExpression" || digest2.callee.property?.name !== "digest") return null;
3141
+ const update = digest2.callee.object;
3142
+ if (update?.type !== "CallExpression" || update.callee?.type !== "MemberExpression" || update.callee.property?.name !== "update") return null;
3143
+ if ((update.arguments ?? []).length !== 1) return null;
3144
+ const created = update.callee.object;
3145
+ if (created?.type !== "CallExpression" || created.callee?.type !== "MemberExpression") return null;
3146
+ if (created.callee.property?.name !== "createHash" || created.callee.object?.name !== cryptoName) return null;
3147
+ if ((created.arguments ?? []).length !== 1 || created.arguments[0]?.type !== "StringLiteral") return null;
3148
+ return update.arguments[0];
3149
+ }
3150
+ function isPasswordAssign(stmt, user, hashers) {
3151
+ if (stmt?.type !== "ExpressionStatement" || stmt.expression?.type !== "AssignmentExpression") return false;
3152
+ const left = stmt.expression.left;
3153
+ if (left?.type !== "MemberExpression" || left.object?.name !== user) return false;
3154
+ const right = unwrap(stmt.expression.right);
3155
+ if (right?.type !== "CallExpression" || right.callee?.type !== "MemberExpression" || right.callee.property?.name !== "hash") return false;
3156
+ if (right.callee.object?.type !== "Identifier" || !hashers.has(right.callee.object.name)) return false;
3157
+ let cur = right.arguments?.[0];
3158
+ let body = false;
3159
+ while (cur?.type === "MemberExpression") {
3160
+ if (cur.property?.name === "body") body = true;
3161
+ cur = cur.object;
3162
+ }
3163
+ return body && right.arguments?.[1]?.type === "NumericLiteral";
3164
+ }
3165
+ function isClear(stmt, user, field) {
3166
+ if (stmt?.type !== "ExpressionStatement" || stmt.expression?.type !== "AssignmentExpression") return false;
3167
+ const left = stmt.expression.left;
3168
+ if (left?.type !== "MemberExpression" || left.object?.name !== user || left.property?.name !== field) return false;
3169
+ const right = unwrap(stmt.expression.right);
3170
+ return right?.type === "Identifier" && right.name === "undefined" || right?.type === "NullLiteral";
3171
+ }
3172
+ function isSave(stmt, user) {
3173
+ if (stmt?.type !== "ExpressionStatement") return false;
3174
+ const call = unwrap(stmt.expression);
3175
+ return call?.type === "CallExpression" && call.callee?.type === "MemberExpression" && call.callee.property?.name === "save" && call.callee.object?.name === user && (call.arguments ?? []).length === 0;
3176
+ }
3177
+ function isSuccess(stmt, _user, _param) {
3178
+ const value = stmt?.type === "ReturnStatement" ? stmt.argument : stmt?.type === "ExpressionStatement" ? stmt.expression : null;
3179
+ const call = unwrap(value);
3180
+ if (call?.type !== "CallExpression") return false;
3181
+ const callee = call.callee;
3182
+ const name = callee?.property?.name;
3183
+ 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");
3184
+ if (!ok || (call.arguments ?? []).length < 1) return false;
3185
+ return literalValue(call.arguments[0]);
3186
+ }
3187
+ function capabilityBody(model, handler) {
3188
+ if (handler.method !== "post" && handler.method !== "put" && handler.method !== "patch") return false;
3189
+ const stmts = handler.statements.filter((stmt) => stmt?.type !== "EmptyStatement");
3190
+ if (stmts.length < 2 || stmts[0]?.type !== "VariableDeclaration" || (stmts[0].declarations ?? []).length !== 1) return false;
3191
+ const decl = stmts[0].declarations[0];
3192
+ if (decl?.id?.type !== "Identifier") return false;
3193
+ const lookup = unwrap(decl.init);
3194
+ if (lookup?.type !== "CallExpression" || lookup.callee?.type !== "MemberExpression") return false;
3195
+ if (!["findOne", "findUnique", "findFirst"].includes(lookup.callee.property?.name)) return false;
3196
+ const filter = filterOf(lookup.arguments?.[0], model.hashFns, model.cryptoName);
3197
+ if (!filter) return false;
3198
+ if (!handler.appRouter && !handler.path.includes(`:${filter.param}`)) return false;
3199
+ if (!assignedFromRandom(model.ast, filter.field, model.hashFns, model.randomNames, model.cryptoName)) return false;
3200
+ const guard = stmts[1];
3201
+ if (guard?.type !== "IfStatement" || guard.alternate) return false;
3202
+ const test = unwrap(guard.test);
3203
+ if (test?.type !== "UnaryExpression" || test.operator !== "!" || test.argument?.type !== "Identifier" || test.argument.name !== decl.id.name) return false;
3204
+ if (!rejectConsequent(guard.consequent)) return false;
3205
+ let clearF = false;
3206
+ let clearE = false;
3207
+ let password = false;
3208
+ let saved = false;
3209
+ let done = false;
3210
+ for (const stmt of stmts.slice(2)) {
3211
+ if (done) return false;
3212
+ if (isPasswordAssign(stmt, decl.id.name, model.hasherNames)) {
3213
+ if (password || saved) return false;
3214
+ password = true;
3215
+ continue;
3216
+ }
3217
+ if (isClear(stmt, decl.id.name, filter.field)) {
3218
+ if (saved) return false;
3219
+ clearF = true;
3220
+ continue;
3221
+ }
3222
+ if (isClear(stmt, decl.id.name, filter.expiry)) {
3223
+ if (saved) return false;
3224
+ clearE = true;
3225
+ continue;
3226
+ }
3227
+ if (isSave(stmt, decl.id.name)) {
3228
+ if (!clearF || !clearE || !password || saved) return false;
3229
+ saved = true;
3230
+ continue;
3231
+ }
3232
+ if (isSuccess(stmt, decl.id.name, filter.param)) {
3233
+ if (!saved) return false;
3234
+ done = true;
3235
+ continue;
3236
+ }
3237
+ return false;
3238
+ }
3239
+ return done && clearF && clearE && password && saved;
3240
+ }
3241
+ function capabilityTokenHandler(content, filePath, index) {
3242
+ try {
3243
+ fault("capability");
3244
+ const model = load(content, filePath);
3245
+ if (!model) return false;
3246
+ const handler = onLine(model, content, index);
3247
+ return handler ? capabilityBody(model, handler) : false;
3248
+ } catch {
3249
+ return false;
3250
+ }
3251
+ }
3252
+ function bearerExpr(node) {
3253
+ const value = unwrap(node);
3254
+ if (value?.type !== "TemplateLiteral" || (value.expressions ?? []).length !== 1) return null;
3255
+ const lead = value.quasis?.[0]?.value?.cooked ?? "";
3256
+ const tail = value.quasis?.[1]?.value?.cooked ?? "";
3257
+ if (!/^Bearer $/i.test(lead) || tail !== "") return null;
3258
+ return value.expressions[0];
3259
+ }
3260
+ function bindPattern(id, init, map) {
3261
+ if (!id) return;
3262
+ if (id.type === "Identifier") map.set(id.name, init);
3263
+ if (id.type === "ObjectPattern") {
3264
+ for (const prop of id.properties ?? []) {
3265
+ if (prop?.type === "ObjectProperty") bindPattern(prop.value, { type: "Destructure", object: init, key: propName(prop) }, map);
3266
+ }
3267
+ }
3268
+ }
3269
+ function declaredNames(id, into) {
3270
+ if (!id) return;
3271
+ if (id.type === "Identifier") into.push(id.name);
3272
+ if (id.type === "ObjectPattern" || id.type === "ArrayPattern") {
3273
+ const parts = id.properties ?? id.elements ?? [];
3274
+ for (const part of parts) {
3275
+ if (part?.type === "ObjectProperty" || part?.type === "RestElement") declaredNames(part.value ?? part.argument, into);
3276
+ else declaredNames(part, into);
3277
+ }
3278
+ }
3279
+ if (id.type === "AssignmentPattern") declaredNames(id.left, into);
3280
+ }
3281
+ function bindingMap(fn) {
3282
+ const map = /* @__PURE__ */ new Map();
3283
+ const body = fn?.body?.type === "BlockStatement" ? fn.body.body ?? [] : [];
3284
+ for (const stmt of body) {
3285
+ if (stmt?.type !== "VariableDeclaration" || stmt.kind !== "const") continue;
3286
+ for (const decl of stmt.declarations ?? []) {
3287
+ if (decl?.init) bindPattern(decl.id, unwrap(decl.init), map);
3288
+ }
3289
+ }
3290
+ const counts = /* @__PURE__ */ new Map();
3291
+ const assigned = /* @__PURE__ */ new Set();
3292
+ walk(fn, (node) => {
3293
+ if (node.type === "VariableDeclarator") {
3294
+ const names = [];
3295
+ declaredNames(node.id, names);
3296
+ for (const name of names) counts.set(name, (counts.get(name) ?? 0) + 1);
3297
+ }
3298
+ if (node.type === "AssignmentExpression" || node.type === "UpdateExpression") {
3299
+ const names = [];
3300
+ declaredNames(node.left ?? node.argument, names);
3301
+ for (const name of names) assigned.add(name);
3302
+ }
3303
+ });
3304
+ for (const [name, count] of counts) if (count > 1) map.delete(name);
3305
+ for (const name of assigned) map.delete(name);
3306
+ return map;
3307
+ }
3308
+ function isCookieValue(node, map) {
3309
+ const member = unwrap(node);
3310
+ if (!member || member.type !== "MemberExpression" && member.type !== "OptionalMemberExpression" || member.property?.name !== "value") return false;
3311
+ const call = unwrap(member.object);
3312
+ if (call?.type !== "CallExpression" || call.callee?.type !== "MemberExpression" || call.callee.property?.name !== "get") return false;
3313
+ if (call.arguments?.[0]?.type !== "StringLiteral") return false;
3314
+ const obj = unwrap(call.callee.object);
3315
+ if (obj?.type === "CallExpression" && obj.callee?.name === "cookies") return true;
3316
+ if (obj?.type === "Identifier") {
3317
+ const bound = unwrap(map.get(obj.name));
3318
+ if (bound?.type === "CallExpression" && bound.callee?.name === "cookies") return true;
3319
+ }
3320
+ return false;
3321
+ }
3322
+ function isSessionToken(node, map) {
3323
+ const member = unwrap(node);
3324
+ if (!member || member.type !== "MemberExpression" && member.type !== "OptionalMemberExpression" || member.property?.name !== "access_token") return false;
3325
+ if (member.object?.type !== "Identifier") return false;
3326
+ let current = map.get(member.object.name);
3327
+ const seen = /* @__PURE__ */ new Set();
3328
+ while (current && current.type === "Destructure" && !seen.has(current)) {
3329
+ seen.add(current);
3330
+ current = current.object;
3331
+ }
3332
+ const call = unwrap(current);
3333
+ if (call?.type !== "CallExpression" || call.callee?.property?.name !== "getSession" || call.callee?.object?.property?.name !== "auth") return false;
3334
+ const clientName = call.callee.object.object?.name;
3335
+ const client = unwrap(map.get(clientName));
3336
+ return client?.type === "CallExpression" && (client.callee?.name === "createClient" || client.callee?.property?.name === "createClient");
3337
+ }
3338
+ function fetchLiteral(node) {
3339
+ const call = unwrap(node);
3340
+ if (call?.type !== "CallExpression" || call.callee?.name !== "fetch") return null;
3341
+ return staticString(call.arguments?.[0]);
3342
+ }
3343
+ function isOAuthToken(node, map, here) {
3344
+ if (node?.type !== "Identifier") return false;
3345
+ let current = map.get(node.name);
3346
+ const seen = /* @__PURE__ */ new Set();
3347
+ while (current && current.type === "Destructure" && !seen.has(current)) {
3348
+ seen.add(current);
3349
+ current = current.object;
3350
+ }
3351
+ const json = unwrap(current);
3352
+ if (json?.type !== "CallExpression" || json.callee?.property?.name !== "json" || json.callee?.object?.type !== "Identifier") return false;
3353
+ const tokenUrl = fetchLiteral(map.get(json.callee.object.name));
3354
+ if (!tokenUrl || !here) return false;
3355
+ if (!publicHttpsUrl(tokenUrl) || !publicHttpsUrl(here)) return false;
3356
+ const tokenHost = new URL(tokenUrl).hostname.toLowerCase();
3357
+ const hereHost = new URL(here).hostname.toLowerCase();
3358
+ return tokenHost === hereHost || hereHost.endsWith(`.${tokenHost}`);
3359
+ }
3360
+ function envUrl(node) {
3361
+ const value = unwrap(node);
3362
+ if (value?.type !== "TemplateLiteral" || (value.expressions ?? []).length !== 1) return false;
3363
+ if (!isProcessEnv(value.expressions[0]) || value.expressions[0]?.type === "LogicalExpression") return false;
3364
+ const lead = value.quasis?.[0]?.value?.cooked ?? "";
3365
+ const rest = value.quasis?.[1]?.value?.cooked ?? "";
3366
+ return lead === "" && rest.startsWith("/") && !rest.includes("?");
3367
+ }
3368
+ function headerQualifies(model, propPath) {
3369
+ const index = propPath.node.start;
3370
+ const options = propPath.parent;
3371
+ const call = propPath.parentPath?.parentPath?.node;
3372
+ if (options?.type !== "ObjectExpression" || call?.type !== "CallExpression") return false;
3373
+ if (call.arguments?.[1] !== options || call.callee?.name !== "fetch") return false;
3374
+ const headers = propPath.node.value;
3375
+ if (headers?.type !== "ObjectExpression") return false;
3376
+ const auth = (headers.properties ?? []).find((prop) => prop?.type === "ObjectProperty" && propName(prop).toLowerCase() === "authorization");
3377
+ const expr = bearerExpr(auth?.value);
3378
+ if (!expr) return false;
3379
+ const inner = model.functions.filter((fn) => fn.start <= index && index < fn.end).sort((a, b) => a.end - a.start - (b.end - b.start))[0];
3380
+ const handler = model.handlers.find((item) => item.fnStart === inner?.start && item.fnEnd === inner?.end);
3381
+ if (!handler || handler.method !== "serve" && !METHODS.has(handler.method)) return false;
3382
+ const map = bindingMap(handler.fn);
3383
+ const urlNode = call.arguments?.[0];
3384
+ const direct = unwrap(expr);
3385
+ const resolved = direct?.type === "Identifier" ? unwrap(map.get(direct.name)) ?? direct : direct;
3386
+ if (isCookieValue(direct, map) || isCookieValue(resolved, map) || isSessionToken(direct, map) || isSessionToken(resolved, map)) return envUrl(urlNode);
3387
+ const here = staticString(urlNode);
3388
+ return here !== null && isOAuthToken(unwrap(expr), map, here);
3389
+ }
3390
+ function bearerSpans(content, filePath, model) {
3391
+ const key = `${filePath}\0${digest(content)}`;
3392
+ const hit = bearerSpanCache.get(key);
3393
+ if (hit && hit.content === content) return hit.spans;
3394
+ const spans = [];
3395
+ traverse(model.ast, {
3396
+ ObjectProperty(path) {
3397
+ const node = path.node;
3398
+ if (typeof node.start !== "number" || typeof node.end !== "number") return;
3399
+ if (propName(node).toLowerCase() !== "headers") return;
3400
+ spans.push({ start: node.start, end: node.end, ok: headerQualifies(model, path) });
3401
+ }
3402
+ });
3403
+ bearerSpanCache.set(key, { content, spans });
3404
+ if (bearerSpanCache.size > 128) {
3405
+ const first = bearerSpanCache.keys().next().value;
3406
+ if (first !== void 0) bearerSpanCache.delete(first);
3407
+ }
3408
+ return spans;
3409
+ }
3410
+ function bearerProvenanceSafe(content, filePath, index) {
3411
+ try {
3412
+ fault("bearer");
3413
+ if (!content.includes("fetch")) return false;
3414
+ const model = load(content, filePath);
3415
+ if (!model) return false;
3416
+ let count = 0;
3417
+ let ok = false;
3418
+ for (const span of bearerSpans(content, filePath, model)) {
3419
+ if (index < span.start || index >= span.end) continue;
3420
+ count += 1;
3421
+ ok = span.ok;
3422
+ }
3423
+ return count === 1 && ok;
3424
+ } catch {
3425
+ return false;
3426
+ }
3427
+ }
3428
+ 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;
3429
+ var REF_RE = /params\.id|params\.(?:slug|uuid)|req\.params\.\w+|req\.params\b|req\.(?:body|query)\.\w*id/gi;
3430
+ var OWNER_RE = /userId|ownerId|createdBy|user_id|owner_id|AND.*user|where.*user|authorize|canAccess|checkPermission|isOwner|belongsTo/i;
3431
+ var AUTH_RE = /requireUser|requireUserForApi|requireAuth|withAuth|getServerSession|auth\(\)|passport|isAuthenticated/i;
3432
+ function maskLocal(content) {
3433
+ let open = content.indexOf("/*");
3434
+ let blocked2 = content;
3435
+ if (open !== -1) {
3436
+ const parts = [];
3437
+ let copied = 0;
3438
+ while (open !== -1) {
3439
+ const close = content.indexOf("*/", open + 2);
3440
+ if (close === -1) break;
3441
+ parts.push(content.slice(copied, open), content.slice(open, close + 2).replace(/[^\n]/g, " "));
3442
+ copied = close + 2;
3443
+ open = content.indexOf("/*", copied);
3444
+ }
3445
+ parts.push(content.slice(copied));
3446
+ blocked2 = parts.join("");
3447
+ }
3448
+ return blocked2.replace(/(^|[^:])\/\/[^\n]*/gm, (match, lead) => lead + " ".repeat(match.length - lead.length));
3449
+ }
3450
+ function matchIndexes(text, re) {
3451
+ const copy = new RegExp(re.source, re.flags);
3452
+ const out = [];
3453
+ let match;
3454
+ while (match = copy.exec(text)) {
3455
+ out.push(match.index);
3456
+ if (match[0].length === 0) copy.lastIndex += 1;
3457
+ if (out.length > LOOKUP_LIMIT) break;
3458
+ }
3459
+ return out;
3460
+ }
3461
+ function balancedCall(content, open) {
3462
+ let depth = 0;
3463
+ for (let i = open; i < content.length; i++) {
3464
+ const c = content[i];
3465
+ if (c === "(") depth += 1;
3466
+ else if (c === ")") {
3467
+ depth -= 1;
3468
+ if (depth === 0) return content.slice(open, i + 1);
3469
+ }
3470
+ }
3471
+ return null;
3472
+ }
3473
+ function querySlice(content, index) {
3474
+ if (/^where\b/i.test(content.slice(index, index + 5))) {
3475
+ let depth = 0;
3476
+ for (let i = index; i >= 0; i--) {
3477
+ const c = content[i];
3478
+ if (c === ")") depth += 1;
3479
+ else if (c === "(") {
3480
+ if (depth === 0) return balancedCall(content, i);
3481
+ depth -= 1;
3482
+ }
3483
+ }
3484
+ }
3485
+ const open = content.indexOf("(", index);
3486
+ if (open === -1 || open - index > 80) return null;
3487
+ return balancedCall(content, open);
3488
+ }
3489
+ function handlerAt(model, index) {
3490
+ const found = model.handlers.filter((handler) => handler.fnStart <= index && index < handler.fnEnd);
3491
+ found.sort((a, b) => a.fnEnd - a.fnStart - (b.fnEnd - b.fnStart));
3492
+ return found[0] ?? null;
3493
+ }
3494
+ function handlerQualifies(content, filePath, handler, lookups) {
3495
+ const slice = content.slice(handler.fnStart, handler.fnEnd);
3496
+ const registered = content.slice(handler.regStart, handler.fnEnd);
3497
+ if (AUTH_RE.test(registered)) return false;
3498
+ const lookup = lookups.find((index) => index >= handler.fnStart && index < handler.fnEnd);
3499
+ if (lookup === void 0) return false;
3500
+ const query = querySlice(content, lookup) ?? slice;
3501
+ if (OWNER_RE.test(query)) return false;
3502
+ const reads = /req\.params\b|req\.(?:body|query)\.\w*id\b|params\.id|params\.(?:slug|uuid)/i.test(slice);
3503
+ if (!reads) return false;
3504
+ if (handler.appRouter) return /\/api\//i.test(filePath) && /^(get|put|patch|delete)$/.test(handler.method);
3505
+ return METHODS.has(handler.method);
3506
+ }
3507
+ function refineDirectObjectFindings(content, filePath, legacyLines) {
3508
+ try {
3509
+ fault("refine");
3510
+ if (content.length > PARSE_BYTES) return null;
3511
+ const masked = maskLocal(content);
3512
+ const lookups = matchIndexes(masked, LOOKUP_RE);
3513
+ if (lookups.length > LOOKUP_LIMIT) return null;
3514
+ const model = load(content, filePath);
3515
+ if (!model || model.handlers.length === 0) return null;
3516
+ const refs = matchIndexes(masked, REF_RE);
3517
+ if (refs.length === 0) return null;
3518
+ const cleared = (handler) => narrowedGuard(content, model, handler, lookups) || capabilityTokenHandler(content, filePath, handler.regStart);
3519
+ let every = true;
3520
+ for (const ref of refs) {
3521
+ const handler = handlerAt(model, ref);
3522
+ if (!handler || !cleared(handler)) every = false;
3523
+ }
3524
+ const lines = /* @__PURE__ */ new Set();
3525
+ if (!every) for (const line of legacyLines) lines.add(line);
3526
+ for (const handler of model.handlers) {
3527
+ if (cleared(handler) || !handlerQualifies(content, filePath, handler, lookups)) continue;
3528
+ const ref = refs.find((index) => index >= handler.fnStart && index < handler.fnEnd);
3529
+ if (ref === void 0) continue;
3530
+ lines.add(lineAt(content, ref));
3531
+ }
3532
+ return [...lines].sort((a, b) => a - b);
3533
+ } catch {
3534
+ return null;
3535
+ }
3536
+ }
3537
+
2162
3538
  // src/auth-scope.ts
2163
3539
  var GUARD_NAMES = ["requireAdmin", "requireMember", "requireRole", "requireUser", "verifyToken", "verifyAdmin"];
2164
3540
  var PUBLIC_LAST = /^(?:login|logout|signup|register|forgot(?:-password)?|reset(?:-password)?|callback)$/i;
@@ -2633,10 +4009,10 @@ function useCoversRoute(content, index) {
2633
4009
  if (routeKey === "exhausted") return false;
2634
4010
  for (const site of usesInScope(content, routeKey)) {
2635
4011
  if (site.receiver !== receiver || site.index >= lineStart) continue;
2636
- const stringPrefix = /^\s*["'`]([^"'`]*)["'`]/.exec(site.first)?.[1];
4012
+ const stringPrefix2 = /^\s*["'`]([^"'`]*)["'`]/.exec(site.first)?.[1];
2637
4013
  const firstIsGuard = /^[A-Za-z_$][\w$]*$/.test(site.first) && GUARD_NAMES.includes(site.first) && guardNameCounts(content, site.first);
2638
- if (stringPrefix === void 0 && !firstIsGuard) continue;
2639
- const prefix = stringPrefix ?? "";
4014
+ if (stringPrefix2 === void 0 && !firstIsGuard) continue;
4015
+ const prefix = stringPrefix2 ?? "";
2640
4016
  if (prefix && !authPrefixCovers(prefix, path)) continue;
2641
4017
  if (!guardMentioned(content, site.args) && !firstIsGuard) continue;
2642
4018
  return true;
@@ -2837,10 +4213,13 @@ function widenedAuthSuppressesBody(content, filePath, index, handler) {
2837
4213
  if (cronSecretGates(maskedHandler)) return true;
2838
4214
  return false;
2839
4215
  }
2840
- function widenedAuthSuppresses(content, filePath, index, handler) {
4216
+ function widenedAuthSuppresses(content, filePath, index, handler, rawContent, capability = false, strictApp = false) {
2841
4217
  try {
2842
4218
  if (authFaultForTest) throw new Error("injected");
2843
- return widenedAuthSuppressesBody(content, filePath, index, handler);
4219
+ if (widenedAuthSuppressesBody(content, filePath, index, handler)) return true;
4220
+ if (!rawContent) return false;
4221
+ if (publicReadOnlyHandler(rawContent, filePath, index, strictApp)) return true;
4222
+ return capability && capabilityTokenHandler(rawContent, filePath, index);
2844
4223
  } catch {
2845
4224
  return false;
2846
4225
  }
@@ -2881,29 +4260,345 @@ function wordIn(tokens, word) {
2881
4260
  function hasPf(text) {
2882
4261
  return nameTokens(text).some(isPf);
2883
4262
  }
4263
+ var TOKEN_PARTS = /* @__PURE__ */ new Set(["token", "code", "otp", "nonce"]);
4264
+ var METHOD_NAMES = /* @__PURE__ */ new Set(["encode", "hexdigest", "toString"]);
4265
+ var RUN_TOGETHER = /^(?:reset|forgot|recover|change)?(?:password|passwd|passphrase|pwd)(?:reset|forgot|recover|change)?(?:token|code|otp|nonce)$/;
4266
+ function languageOf(filePath) {
4267
+ if (filePath.endsWith(".py")) return "py";
4268
+ if (filePath.endsWith(".rb")) return "rb";
4269
+ return "js";
4270
+ }
4271
+ function namesIn(text) {
4272
+ const names = [];
4273
+ const re = /[A-Za-z_$][\w$]*/g;
4274
+ let match;
4275
+ while (match = re.exec(text)) {
4276
+ if (!METHOD_NAMES.has(match[0])) names.push(match[0]);
4277
+ }
4278
+ return names;
4279
+ }
4280
+ function nameHasPassword(name) {
4281
+ return nameTokens(name).some(isPf);
4282
+ }
4283
+ function nameHasToken(name) {
4284
+ const parts = nameTokens(name);
4285
+ if (parts.some((part) => TOKEN_PARTS.has(part))) return true;
4286
+ return name === name.toLowerCase() && RUN_TOGETHER.test(name);
4287
+ }
4288
+ function argumentHasPasswordOnly(expr) {
4289
+ return namesIn(expr).some((name) => nameHasPassword(name) && !nameHasToken(name));
4290
+ }
4291
+ function argumentGivesTokenCredit(expr) {
4292
+ const names = namesIn(expr);
4293
+ if (names.some((name) => nameHasPassword(name) && !nameHasToken(name))) return false;
4294
+ return names.some((name) => nameHasToken(name));
4295
+ }
2884
4296
  function isTokenValue(expr) {
2885
- const tokens = nameTokens(expr);
2886
- const pf = tokens.filter(isPf);
2887
- if (pf.some((token) => !TOKEN_WORDS.some((word) => token.includes(word)))) return false;
2888
- if (TOKEN_WORDS.some((word) => tokens.includes(word))) return true;
2889
- return TOKEN_WORDS.some((word) => wordIn(tokens, word));
4297
+ return argumentGivesTokenCredit(expr);
4298
+ }
4299
+ function containsPasswordWord(text) {
4300
+ const lower = text.toLowerCase().replace(/passwordless/g, "");
4301
+ return PF_RE.test(lower);
4302
+ }
4303
+ function isBracketKey(raw, start, end) {
4304
+ let j = start - 1;
4305
+ while (j >= 0 && /\s/.test(raw[j])) j--;
4306
+ if (j < 0 || raw[j] !== "[") return false;
4307
+ const prev = raw[j - 1] ?? "";
4308
+ const prev2 = raw[j - 2] ?? "";
4309
+ const member = /[A-Za-z0-9_$)\]]/.test(prev) || prev === "." && prev2 === "?";
4310
+ if (!member) return false;
4311
+ let a = end + 1;
4312
+ while (a < raw.length && /\s/.test(raw[a])) a++;
4313
+ return raw[a] === "]";
4314
+ }
4315
+ function isLookupCallArg(raw, start, end) {
4316
+ if (!/(?:\.(?:get|getItem|getAttribute|param)\s*\(\s*)$/.test(raw.slice(0, start))) return false;
4317
+ let a = end + 1;
4318
+ while (a < raw.length && /\s/.test(raw[a])) a++;
4319
+ return raw[a] === ")";
4320
+ }
4321
+ function applyString(chars, raw, open, close, content, lookup) {
4322
+ const ident = /^[A-Za-z_$][\w$]*$/.test(content);
4323
+ if (lookup && ident) {
4324
+ chars[open] = " ";
4325
+ chars[close] = " ";
4326
+ return;
4327
+ }
4328
+ if (lookup && containsPasswordWord(content)) {
4329
+ const marker = "pwd";
4330
+ for (let k = open; k <= close; k++) if (chars[k] !== "\n") chars[k] = " ";
4331
+ for (let k = 0; k < marker.length && open + 1 + k < close; k++) chars[open + 1 + k] = marker[k];
4332
+ return;
4333
+ }
4334
+ for (let k = open; k <= close; k++) if (chars[k] !== "\n") chars[k] = " ";
4335
+ }
4336
+ function stringPrefix(chars, quoteAt) {
4337
+ for (let len = 2; len >= 1; len--) {
4338
+ if (quoteAt - len < 0) continue;
4339
+ let ok = true;
4340
+ for (let j = 1; j <= len; j++) {
4341
+ if (!/[rRbBuUfF]/.test(chars[quoteAt - j] ?? "")) ok = false;
4342
+ }
4343
+ const before = chars[quoteAt - len - 1] ?? "";
4344
+ if (before && /[A-Za-z0-9_]/.test(before)) ok = false;
4345
+ if (ok) return len;
4346
+ }
4347
+ return 0;
4348
+ }
4349
+ function maskArgument(raw, lang) {
4350
+ const chars = raw.split("");
4351
+ const n = chars.length;
4352
+ let i = 0;
4353
+ const blank = (from, to) => {
4354
+ for (let k = from; k < to && k < n; k++) if (chars[k] !== "\n") chars[k] = " ";
4355
+ };
4356
+ while (i < n) {
4357
+ if (lang === "js" && chars[i] === "/" && chars[i + 1] === "/") {
4358
+ const start = i;
4359
+ while (i < n && chars[i] !== "\n") i++;
4360
+ blank(start, i);
4361
+ continue;
4362
+ }
4363
+ if (lang === "js" && chars[i] === "/" && chars[i + 1] === "*") {
4364
+ const start = i;
4365
+ i += 2;
4366
+ while (i < n && !(chars[i] === "*" && chars[i + 1] === "/")) i++;
4367
+ if (i < n) i += 2;
4368
+ blank(start, i);
4369
+ continue;
4370
+ }
4371
+ if ((lang === "py" || lang === "rb") && chars[i] === "#") {
4372
+ const start = i;
4373
+ while (i < n && chars[i] !== "\n") i++;
4374
+ blank(start, i);
4375
+ continue;
4376
+ }
4377
+ const quote = chars[i];
4378
+ const prefix = quote === "'" || quote === '"' ? stringPrefix(chars, i) : 0;
4379
+ const fstring = prefix > 0 && /[fF]/.test(chars.slice(i - prefix, i).join(""));
4380
+ if ((quote === "'" || quote === '"') && i + 2 < n && chars[i + 1] === quote && chars[i + 2] === quote) {
4381
+ const start = i - prefix;
4382
+ i += 3;
4383
+ const keptTriple = [];
4384
+ while (i + 2 < n && !(chars[i] === quote && chars[i + 1] === quote && chars[i + 2] === quote)) {
4385
+ if (fstring && chars[i] === "{") {
4386
+ const from = i;
4387
+ let depth = 1;
4388
+ i++;
4389
+ while (i < n && depth > 0) {
4390
+ if (chars[i] === "{") depth++;
4391
+ else if (chars[i] === "}") depth--;
4392
+ i++;
4393
+ }
4394
+ keptTriple.push([from, i]);
4395
+ continue;
4396
+ }
4397
+ if (lang === "rb" && quote === '"' && chars[i] === "#" && chars[i + 1] === "{") {
4398
+ i += 2;
4399
+ let depth = 1;
4400
+ while (i < n && depth > 0) {
4401
+ if (chars[i] === "{") depth++;
4402
+ else if (chars[i] === "}") depth--;
4403
+ i++;
4404
+ }
4405
+ continue;
4406
+ }
4407
+ i++;
4408
+ }
4409
+ const end = Math.min(n, i + 3);
4410
+ blank(start, end);
4411
+ for (const [from, to] of keptTriple) {
4412
+ for (let k = from; k < to && k < n; k++) chars[k] = raw[k];
4413
+ }
4414
+ i = end;
4415
+ continue;
4416
+ }
4417
+ if (quote === "'" || quote === '"') {
4418
+ const start = i - prefix;
4419
+ i++;
4420
+ const kept = [];
4421
+ while (i < n) {
4422
+ if (chars[i] === "\\") {
4423
+ i += 2;
4424
+ continue;
4425
+ }
4426
+ if (chars[i] === "\n") break;
4427
+ if (fstring && chars[i] === "{") {
4428
+ const from = i;
4429
+ let depth = 1;
4430
+ i++;
4431
+ while (i < n && depth > 0) {
4432
+ if (chars[i] === "{") depth++;
4433
+ else if (chars[i] === "}") depth--;
4434
+ i++;
4435
+ }
4436
+ kept.push([from, i]);
4437
+ continue;
4438
+ }
4439
+ if (lang === "rb" && quote === '"' && chars[i] === "#" && chars[i + 1] === "{") {
4440
+ const from = i;
4441
+ i += 2;
4442
+ let depth = 1;
4443
+ while (i < n && depth > 0) {
4444
+ if (chars[i] === "{") depth++;
4445
+ else if (chars[i] === "}") depth--;
4446
+ i++;
4447
+ }
4448
+ kept.push([from, i]);
4449
+ continue;
4450
+ }
4451
+ if (chars[i] === quote) break;
4452
+ i++;
4453
+ }
4454
+ const end = i < n && chars[i] === quote ? i : i;
4455
+ if (kept.length === 0 && end < n && chars[end] === quote) {
4456
+ const content = raw.slice(start + prefix + 1, end);
4457
+ const lookup = isBracketKey(raw, start + prefix, end) || isLookupCallArg(raw, start + prefix, end);
4458
+ applyString(chars, raw, start, end, content, lookup);
4459
+ } else {
4460
+ blank(start, end + (end < n && chars[end] === quote ? 1 : 0));
4461
+ for (const [from, to] of kept) {
4462
+ for (let k = from; k < to; k++) chars[k] = raw[k];
4463
+ }
4464
+ }
4465
+ i = end < n && chars[end] === quote ? end + 1 : end;
4466
+ continue;
4467
+ }
4468
+ if (quote === "`") {
4469
+ const start = i;
4470
+ i++;
4471
+ const kept = [];
4472
+ while (i < n) {
4473
+ if (chars[i] === "\\") {
4474
+ i += 2;
4475
+ continue;
4476
+ }
4477
+ if (chars[i] === "`") break;
4478
+ if (chars[i] === "$" && chars[i + 1] === "{") {
4479
+ const from = i;
4480
+ i += 2;
4481
+ let depth = 1;
4482
+ while (i < n && depth > 0) {
4483
+ if (chars[i] === "{") depth++;
4484
+ else if (chars[i] === "}") depth--;
4485
+ i++;
4486
+ }
4487
+ kept.push([from, i]);
4488
+ continue;
4489
+ }
4490
+ i++;
4491
+ }
4492
+ const end = i < n && chars[i] === "`" ? i : i;
4493
+ blank(start, end + (end < n && chars[end] === "`" ? 1 : 0));
4494
+ for (const [from, to] of kept) {
4495
+ for (let k = from; k < to; k++) chars[k] = raw[k];
4496
+ }
4497
+ i = end < n && chars[end] === "`" ? end + 1 : end;
4498
+ continue;
4499
+ }
4500
+ i++;
4501
+ }
4502
+ return chars.join("");
4503
+ }
4504
+ function digestLhsNames(content, digestAt) {
4505
+ const lineStart = content.lastIndexOf("\n", Math.max(0, digestAt - 1)) + 1;
4506
+ const line = content.slice(lineStart, digestAt);
4507
+ const assigned = /([A-Za-z_@][\w.]*)\s*=\s*$/.exec(line);
4508
+ if (!assigned) return [];
4509
+ return assigned[1].split(".").map((part) => part.replace(/^@/, "")).filter(Boolean);
4510
+ }
4511
+ function pushCall(content, open, items, veto, emptySkips) {
4512
+ const close = matchingCloser(content, open, "(", ")", ARG_CAP2);
4513
+ if (close < 0) {
4514
+ items.push({ kind: "fail", text: "", veto });
4515
+ return;
4516
+ }
4517
+ const raw = content.slice(open + 1, close);
4518
+ if (raw.trim() === "") {
4519
+ items.push({ kind: emptySkips ? "skip" : "fail", text: "", veto });
4520
+ return;
4521
+ }
4522
+ items.push({ kind: "arg", text: raw, veto });
4523
+ }
4524
+ function scopeSlice(slice, lang, hitIndent) {
4525
+ if (lang !== "js") {
4526
+ const re = /\n([ \t]*)(?:async[ \t]+)?(?:def|class)[ \t]/g;
4527
+ let m;
4528
+ while (m = re.exec(slice)) {
4529
+ const head = slice.slice(0, m.index);
4530
+ if ((head.split('"""').length - 1) % 2 === 1 || (head.split("'''").length - 1) % 2 === 1) continue;
4531
+ if (m[1].length < hitIndent) return slice.slice(0, m.index);
4532
+ }
4533
+ return slice;
4534
+ }
4535
+ let depth = 0, paren = 0, q = "";
4536
+ for (let i = 0; i < slice.length; i++) {
4537
+ const c = slice[i];
4538
+ if (q) {
4539
+ if (c === "\\") i++;
4540
+ else if (c === q) q = "";
4541
+ continue;
4542
+ }
4543
+ if (c === "'" || c === '"' || c === "`") q = c;
4544
+ else if (c === "(") paren++;
4545
+ else if (c === ")") paren--;
4546
+ else if (paren <= 0 && c === "{") depth++;
4547
+ else if (paren <= 0 && c === "}" && --depth < 0) return slice.slice(0, i);
4548
+ }
4549
+ return slice;
4550
+ }
4551
+ function collectArguments(content, lineStart, filePath) {
4552
+ const scanEnd = Math.min(content.length, lineStart + ARG_CAP2 + 40);
4553
+ const hitIndent = (/^[ \t]*/.exec(content.slice(lineStart)) ?? [""])[0].length;
4554
+ const slice = scopeSlice(content.slice(lineStart, scanEnd), languageOf(filePath), hitIndent);
4555
+ const items = [];
4556
+ const updateRe = /\.update\s*\(/g;
4557
+ let match;
4558
+ while (match = updateRe.exec(slice)) {
4559
+ if (match.index >= ARG_CAP2) break;
4560
+ const open = lineStart + match.index + match[0].lastIndexOf("(");
4561
+ pushCall(content, open, items, [], false);
4562
+ }
4563
+ const ctorRe = /hashlib\s*\.\s*[A-Za-z_]\w*\s*\(|Digest::[A-Za-z0-9_]+\s*\.\s*hexdigest\s*\(/g;
4564
+ while (match = ctorRe.exec(slice)) {
4565
+ if (match.index >= ARG_CAP2) break;
4566
+ const at = lineStart + match.index;
4567
+ const open = at + match[0].lastIndexOf("(");
4568
+ const veto = match[0].includes("Digest") ? digestLhsNames(content, at) : [];
4569
+ pushCall(content, open, items, veto, true);
4570
+ }
4571
+ const lang = languageOf(filePath);
4572
+ return items.map((item) => item.kind === "arg" ? { ...item, text: maskArgument(item.text, lang) } : item);
4573
+ }
4574
+ function gatherTokenDecision(content, lineStart, filePath) {
4575
+ const items = collectArguments(content, lineStart, filePath);
4576
+ const veto = items.flatMap((item) => item.veto);
4577
+ if (veto.some((name) => nameHasPassword(name) && !nameHasToken(name))) return false;
4578
+ const kept = items.filter((item) => item.kind !== "skip");
4579
+ if (kept.length === 0) return false;
4580
+ if (kept.some((item) => item.kind === "fail")) return false;
4581
+ if (kept.some((item) => argumentHasPasswordOnly(item.text))) return false;
4582
+ return kept.every((item) => argumentGivesTokenCredit(item.text));
2890
4583
  }
2891
4584
  function blocked(text, words) {
2892
4585
  const tokens = nameTokens(text);
2893
4586
  return words.some((word) => wordIn(tokens, word));
2894
4587
  }
2895
- function namedHasher(name, expr) {
4588
+ function namedHasher(name, expr, tokenIs) {
2896
4589
  if (!hasPf(name)) return false;
2897
- if (blocked(name, RESET_WORDS) && isTokenValue(expr)) return false;
4590
+ const token = tokenIs === void 0 ? isTokenValue(expr) : tokenIs;
4591
+ if (blocked(name, RESET_WORDS) && token) return false;
2898
4592
  return true;
2899
4593
  }
2900
4594
  function hasHashVerb(name) {
2901
4595
  const tokens = nameTokens(name);
2902
4596
  return HASH_VERBS.some((word) => wordIn(tokens, word));
2903
4597
  }
2904
- function perCallKeeps(name, expr) {
2905
- if (isTokenValue(expr)) return namedHasher(name, expr) && hasHashVerb(name);
2906
- return hasPf(expr) || namedHasher(name, expr);
4598
+ function perCallKeeps(name, expr, tokenIs) {
4599
+ const token = tokenIs === void 0 ? isTokenValue(expr) : tokenIs;
4600
+ if (token) return namedHasher(name, expr, token) && hasHashVerb(name);
4601
+ return hasPf(expr) || namedHasher(name, expr, token);
2907
4602
  }
2908
4603
  function hashedExprAt(content, index) {
2909
4604
  const slice = content.slice(index, index + ARG_CAP2);
@@ -3382,69 +5077,9 @@ function dotenvValue(raw) {
3382
5077
  return (hash === -1 ? v : v.slice(0, hash)).trim();
3383
5078
  }
3384
5079
 
3385
- // src/ast/parse.ts
3386
- var import_parser = require("@babel/parser");
3387
- var MAX_CACHE = 256;
3388
- var cache = /* @__PURE__ */ new Map();
3389
- function cacheKey(filename, contentHash) {
3390
- return `${filename}:${contentHash}`;
3391
- }
3392
- function quickHash(s) {
3393
- let h = 5381;
3394
- const step = Math.max(1, Math.floor(s.length / 32));
3395
- for (let i = 0; i < s.length; i += step) {
3396
- h = (h << 5) + h + s.charCodeAt(i) | 0;
3397
- }
3398
- return h * 31 + s.length | 0;
3399
- }
3400
- function pickLanguage(filename) {
3401
- if (/\.tsx$/i.test(filename)) return "tsx";
3402
- if (/\.jsx$/i.test(filename)) return "jsx";
3403
- if (/\.(ts|cts|mts)$/i.test(filename)) return "ts";
3404
- if (/\.(js|cjs|mjs)$/i.test(filename)) return "js";
3405
- return null;
3406
- }
3407
- function parseFile(content, filename) {
3408
- const lang = pickLanguage(filename);
3409
- if (!lang) return null;
3410
- if (!content || content.length === 0) return null;
3411
- const key = cacheKey(filename, quickHash(content));
3412
- if (cache.has(key)) return cache.get(key) ?? null;
3413
- const plugins = [];
3414
- if (lang === "ts" || lang === "tsx") plugins.push("typescript");
3415
- if (lang === "jsx" || lang === "tsx") plugins.push("jsx");
3416
- plugins.push("decorators-legacy", "classProperties", "dynamicImport", "topLevelAwait");
3417
- let ast = null;
3418
- try {
3419
- ast = (0, import_parser.parse)(content, {
3420
- sourceType: "unambiguous",
3421
- allowImportExportEverywhere: true,
3422
- allowReturnOutsideFunction: true,
3423
- allowAwaitOutsideFunction: true,
3424
- allowUndeclaredExports: true,
3425
- errorRecovery: true,
3426
- plugins
3427
- });
3428
- } catch {
3429
- cache.set(key, null);
3430
- if (cache.size > MAX_CACHE) {
3431
- const firstKey = cache.keys().next().value;
3432
- if (firstKey !== void 0) cache.delete(firstKey);
3433
- }
3434
- return null;
3435
- }
3436
- const entry = { ast, language: lang };
3437
- cache.set(key, entry);
3438
- if (cache.size > MAX_CACHE) {
3439
- const firstKey = cache.keys().next().value;
3440
- if (firstKey !== void 0) cache.delete(firstKey);
3441
- }
3442
- return entry;
3443
- }
3444
-
3445
5080
  // src/ast/taint.ts
3446
- var import_traverse = __toESM(require("@babel/traverse"), 1);
3447
- var traverse = typeof import_traverse.default === "function" ? import_traverse.default : import_traverse.default.default;
5081
+ var import_traverse2 = __toESM(require("@babel/traverse"), 1);
5082
+ var traverse2 = typeof import_traverse2.default === "function" ? import_traverse2.default : import_traverse2.default.default;
3448
5083
  var TAINTED_PROP_SUFFIXES = /* @__PURE__ */ new Set([
3449
5084
  "body",
3450
5085
  "query",
@@ -3615,8 +5250,8 @@ function buildTaintMap(parsed) {
3615
5250
  if (!node) return false;
3616
5251
  if (node.type === "MemberExpression") {
3617
5252
  const prop = node.property;
3618
- const propName = prop.type === "Identifier" ? prop.name : prop.type === "StringLiteral" ? prop.value : "";
3619
- if (TAINTED_PROP_SUFFIXES.has(propName)) {
5253
+ const propName2 = prop.type === "Identifier" ? prop.name : prop.type === "StringLiteral" ? prop.value : "";
5254
+ if (TAINTED_PROP_SUFFIXES.has(propName2)) {
3620
5255
  const obj = node.object;
3621
5256
  if (obj.type === "Identifier" && TAINTED_REQUEST_OBJECTS.has(obj.name)) {
3622
5257
  return true;
@@ -3709,7 +5344,7 @@ function buildTaintMap(parsed) {
3709
5344
  const pt = computePassthrough(fn);
3710
5345
  if (pt.size > 0) fnPassthrough.set(name, pt);
3711
5346
  };
3712
- traverse(parsed.ast, {
5347
+ traverse2(parsed.ast, {
3713
5348
  FunctionDeclaration(path) {
3714
5349
  const n = path.node;
3715
5350
  if (n.type === "FunctionDeclaration" && n.id && n.id.type === "Identifier") {
@@ -3732,7 +5367,7 @@ function buildTaintMap(parsed) {
3732
5367
  (a, i) => pt.has(i) && a.type !== "SpreadElement" && rec(a)
3733
5368
  );
3734
5369
  }
3735
- traverse(parsed.ast, {
5370
+ traverse2(parsed.ast, {
3736
5371
  VariableDeclarator(path) {
3737
5372
  const node = path.node;
3738
5373
  if (node.type !== "VariableDeclarator") return;
@@ -3854,10 +5489,10 @@ function buildTaintMap(parsed) {
3854
5489
  }
3855
5490
 
3856
5491
  // src/ast/traverse.ts
3857
- var import_traverse2 = __toESM(require("@babel/traverse"), 1);
3858
- var traverse2 = typeof import_traverse2.default === "function" ? import_traverse2.default : import_traverse2.default.default;
5492
+ var import_traverse3 = __toESM(require("@babel/traverse"), 1);
5493
+ var traverse3 = typeof import_traverse3.default === "function" ? import_traverse3.default : import_traverse3.default.default;
3859
5494
  function visitBinary(parsed, visit) {
3860
- traverse2(parsed.ast, {
5495
+ traverse3(parsed.ast, {
3861
5496
  BinaryExpression(path) {
3862
5497
  const line = path.node.loc?.start.line ?? 1;
3863
5498
  visit(path.node, line);
@@ -3865,7 +5500,7 @@ function visitBinary(parsed, visit) {
3865
5500
  });
3866
5501
  }
3867
5502
  function visitCalls(parsed, matchCallee, visit) {
3868
- traverse2(parsed.ast, {
5503
+ traverse3(parsed.ast, {
3869
5504
  CallExpression(path) {
3870
5505
  const node = path.node;
3871
5506
  if (!matchCallee(node.callee)) return;
@@ -4985,9 +6620,9 @@ function maskOutboundAuthNoise(code) {
4985
6620
  /\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,
4986
6621
  blankKeepLines
4987
6622
  );
4988
- let bindingMap = null;
6623
+ let bindingMap2 = null;
4989
6624
  const bindingSource = out;
4990
- const bindings = () => bindingMap ??= collectBindings(bindingSource);
6625
+ const bindings = () => bindingMap2 ??= collectBindings(bindingSource);
4991
6626
  out = out.replace(
4992
6627
  /\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,
4993
6628
  (call, value, at) => credentialValueReadsCaller(value, at, bindings) ? call : blankKeepLines(call)
@@ -5380,7 +7015,7 @@ var missingAuthMiddleware = {
5380
7015
  const unauthenticated = matches.filter((m) => {
5381
7016
  const index = indexOfLine(m.line);
5382
7017
  if (isPublicRootGet(index) || handlerHasAuth(index)) return false;
5383
- if (widenedAuthSuppresses(maskedForScope, filePath, index, scopeAt(index))) return false;
7018
+ if (widenedAuthSuppresses(maskedForScope, filePath, index, scopeAt(index), content, true, true)) return false;
5384
7019
  const namedExport = NAMED_ROUTE_EXPORT_RE.exec(lineText(index));
5385
7020
  if (namedExport && secretGuarded && /^[A-Z]+$/.test(namedExport[1])) return false;
5386
7021
  if (useServerPatterns.length > 0 && (!routeLines.has(m.line) || namedExport !== null && !/^[A-Z]+$/.test(namedExport[1]))) {
@@ -6768,8 +8403,9 @@ var weakHashing = {
6768
8403
  if (matches.some((existing) => existing.line === m.line)) continue;
6769
8404
  const lineStart = indexOfLineNo(m.line);
6770
8405
  const expr = hashedExprAt(content, lineStart);
8406
+ const token = gatherTokenDecision(content, lineStart, filePath);
6771
8407
  const name = braceEnclosingName(lineStart);
6772
- if (!perCallKeeps(name, expr)) continue;
8408
+ if (!perCallKeeps(name, expr, token)) continue;
6773
8409
  matches.push(m);
6774
8410
  }
6775
8411
  }
@@ -10487,7 +12123,7 @@ function isClientTarget(file) {
10487
12123
  function isServerTarget(file) {
10488
12124
  return !file.excluded && file.isServer;
10489
12125
  }
10490
- function lineAt(content, index) {
12126
+ function lineAt2(content, index) {
10491
12127
  let line = 1;
10492
12128
  for (let i = 0; i < index && i < content.length; i++) {
10493
12129
  if (content[i] === "\n") line++;
@@ -10590,7 +12226,7 @@ var silentFailedRead = {
10590
12226
  if (!allValuesEmpty(payload)) continue;
10591
12227
  if (HAS_MARKER.test(payload)) continue;
10592
12228
  if (/\bstatus\s*:\s*[45]\d\d/.test(body)) continue;
10593
- hits.push({ file: file.path, line: lineAt(file.content, index) });
12229
+ hits.push({ file: file.path, line: lineAt2(file.content, index) });
10594
12230
  break;
10595
12231
  }
10596
12232
  }
@@ -10600,8 +12236,8 @@ var silentFailedRead = {
10600
12236
  };
10601
12237
 
10602
12238
  // src/quality/rules/silent-failed-write.ts
10603
- var import_traverse4 = __toESM(require("@babel/traverse"), 1);
10604
- var traverse3 = typeof import_traverse4.default === "function" ? import_traverse4.default : import_traverse4.default.default;
12239
+ var import_traverse5 = __toESM(require("@babel/traverse"), 1);
12240
+ var traverse4 = typeof import_traverse5.default === "function" ? import_traverse5.default : import_traverse5.default.default;
10605
12241
  var EXTRA_EXCLUDED_PATHS = [
10606
12242
  /(?:^|\/)generated\//i,
10607
12243
  /(?:^|\/)__generated__\//i,
@@ -10735,7 +12371,7 @@ function collectFunctions(file) {
10735
12371
  const byNode = /* @__PURE__ */ new Map();
10736
12372
  if (!parsed) return { reachable: /* @__PURE__ */ new Map() };
10737
12373
  const handlerRefNames = /* @__PURE__ */ new Set();
10738
- traverse3(parsed.ast, {
12374
+ traverse4(parsed.ast, {
10739
12375
  JSXAttribute(path) {
10740
12376
  const name = path.node.name;
10741
12377
  if (name.type !== "JSXIdentifier" || !HANDLER_ATTRIBUTE.test(name.name)) return;
@@ -10745,7 +12381,7 @@ function collectFunctions(file) {
10745
12381
  if (expr.type === "Identifier") handlerRefNames.add(expr.name);
10746
12382
  }
10747
12383
  });
10748
- traverse3(parsed.ast, {
12384
+ traverse4(parsed.ast, {
10749
12385
  Function(path) {
10750
12386
  const info = {
10751
12387
  path,
@@ -10762,7 +12398,7 @@ function collectFunctions(file) {
10762
12398
  byNode.set(path.node, info);
10763
12399
  }
10764
12400
  });
10765
- traverse3(parsed.ast, {
12401
+ traverse4(parsed.ast, {
10766
12402
  CallExpression(path) {
10767
12403
  const name = calleeName(path.node.callee);
10768
12404
  if (!name) return;
@@ -10950,7 +12586,7 @@ var silentFailedWrite = {
10950
12586
  const reachableByNode = /* @__PURE__ */ new Map();
10951
12587
  for (const info of reachable.keys()) reachableByNode.set(info.path.node, info);
10952
12588
  const reportedUnits = /* @__PURE__ */ new Set();
10953
- traverse3(parsed.ast, {
12589
+ traverse4(parsed.ast, {
10954
12590
  CallExpression(path) {
10955
12591
  if (!isFetchCallee(path.node.callee)) return;
10956
12592
  if (inAmbientContext(path)) return;
@@ -10998,7 +12634,7 @@ var silentFailedWrite = {
10998
12634
  reportedUnits.add(unit.start);
10999
12635
  hits.push({
11000
12636
  file: file.path,
11001
- line: lineAt(file.content, nodeStart(call)),
12637
+ line: lineAt2(file.content, nodeStart(call)),
11002
12638
  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
11003
12639
  });
11004
12640
  }
@@ -11526,8 +13162,8 @@ var stateBeforeEffect = {
11526
13162
  const columnLabel = `${transition.table.replace(/["'`]/g, "")}.${transition.column.replace(/["'`]/g, "")}`;
11527
13163
  hits.push({
11528
13164
  file: file.path,
11529
- line: lineAt(file.content, effect.index),
11530
- 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.`
13165
+ line: lineAt2(file.content, effect.index),
13166
+ 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.`
11531
13167
  });
11532
13168
  }
11533
13169
  }
@@ -11545,22 +13181,22 @@ var SKIP_KEYS = /* @__PURE__ */ new Set([
11545
13181
  "trailingComments",
11546
13182
  "innerComments"
11547
13183
  ]);
11548
- function walk(node, visit) {
13184
+ function walk2(node, visit) {
11549
13185
  if (!node || typeof node !== "object") return;
11550
13186
  if (Array.isArray(node)) {
11551
- for (const child of node) walk(child, visit);
13187
+ for (const child of node) walk2(child, visit);
11552
13188
  return;
11553
13189
  }
11554
13190
  const record = node;
11555
13191
  if (typeof record.type === "string") visit(node);
11556
13192
  for (const key of Object.keys(record)) {
11557
13193
  if (SKIP_KEYS.has(key)) continue;
11558
- walk(record[key], visit);
13194
+ walk2(record[key], visit);
11559
13195
  }
11560
13196
  }
11561
13197
  function containsType(root, types) {
11562
13198
  let found = false;
11563
- walk(root, (n) => {
13199
+ walk2(root, (n) => {
11564
13200
  if (types.includes(n.type)) found = true;
11565
13201
  });
11566
13202
  return found;
@@ -11674,7 +13310,7 @@ function hasEnvSchemaFor(code, name) {
11674
13310
  }
11675
13311
  function readsRequestHeader(node, facts) {
11676
13312
  let found = false;
11677
- walk(node, (n) => {
13313
+ walk2(node, (n) => {
11678
13314
  if (found) return;
11679
13315
  if (n.type === "Identifier" && n.name === "headers") found = true;
11680
13316
  if (n.type === "CallExpression" || n.type === "OptionalCallExpression") {
@@ -11694,7 +13330,7 @@ function collectFacts(file) {
11694
13330
  };
11695
13331
  const ast = file.parsed?.ast;
11696
13332
  if (!ast) return facts;
11697
- walk(ast, (n) => {
13333
+ walk2(ast, (n) => {
11698
13334
  if (n.type !== "VariableDeclarator" || !n.init) return;
11699
13335
  const init = n.init;
11700
13336
  let source = init;
@@ -11740,13 +13376,13 @@ function collectFacts(file) {
11740
13376
  }
11741
13377
  });
11742
13378
  const names = /* @__PURE__ */ new Set([...facts.envAlias.values()]);
11743
- walk(ast, (n) => {
13379
+ walk2(ast, (n) => {
11744
13380
  if (n.type === "MemberExpression" || n.type === "CallExpression") {
11745
13381
  const direct = envVarName(n);
11746
13382
  if (direct) names.add(direct);
11747
13383
  }
11748
13384
  });
11749
- walk(ast, (n) => {
13385
+ walk2(ast, (n) => {
11750
13386
  if (n.type === "IfStatement") {
11751
13387
  for (const name of names) {
11752
13388
  if (facts.guarded.has(name)) continue;
@@ -12067,7 +13703,7 @@ var mouseOnlyControl = {
12067
13703
  if (isAsChildTrigger(jsxParent)) return;
12068
13704
  const dressed = attributeSource(findAttribute(opening, "className"), file.code) + " " + attributeSource(findAttribute(opening, "class"), file.code) + " " + attributeSource(findAttribute(opening, "style"), file.code);
12069
13705
  if (!AFFORDANCE.test(dressed)) return;
12070
- const line = opening.loc?.start.line ?? lineAt(file.content, opening.start ?? 0);
13706
+ const line = opening.loc?.start.line ?? lineAt2(file.content, opening.start ?? 0);
12071
13707
  hits.push({ file: file.path, line });
12072
13708
  });
12073
13709
  }
@@ -12315,7 +13951,7 @@ var undeclaredModal = {
12315
13951
  if (!hasFocusableDescendant(element)) continue;
12316
13952
  if (declaresSemantics(element)) continue;
12317
13953
  if (!isOpenGated(element, parents, baseName2)) continue;
12318
- const line = opening.loc?.start.line ?? lineAt(file.content, opening.start ?? 0);
13954
+ const line = opening.loc?.start.line ?? lineAt2(file.content, opening.start ?? 0);
12319
13955
  hits.push({ file: file.path, line });
12320
13956
  break;
12321
13957
  }
@@ -12535,7 +14171,7 @@ var unboundedList = {
12535
14171
  if (REDUCING_MEMBER.test(afterQuery)) return;
12536
14172
  const binding = resultBinding(statement);
12537
14173
  if (binding && nextUseReduces(file.code, binding, end)) return;
12538
- const line = node.loc?.start.line ?? lineAt(file.content, node.start ?? 0);
14174
+ const line = node.loc?.start.line ?? lineAt2(file.content, node.start ?? 0);
12539
14175
  hits.push({ file: file.path, line });
12540
14176
  reported = true;
12541
14177
  });
@@ -12691,7 +14327,7 @@ var unassociatedLabel = {
12691
14327
  const field = fieldAfter(element.end, openings);
12692
14328
  if (!field) continue;
12693
14329
  if (fieldIsNamed(field)) continue;
12694
- const line = opening.loc?.start.line ?? lineAt(file.content, opening.start ?? 0);
14330
+ const line = opening.loc?.start.line ?? lineAt2(file.content, opening.start ?? 0);
12695
14331
  hits.push({ file: file.path, line });
12696
14332
  }
12697
14333
  }
@@ -12700,11 +14336,11 @@ var unassociatedLabel = {
12700
14336
  };
12701
14337
 
12702
14338
  // src/quality/rules/failed-read-empty-state.ts
12703
- var import_traverse5 = __toESM(require("@babel/traverse"), 1);
14339
+ var import_traverse6 = __toESM(require("@babel/traverse"), 1);
12704
14340
  var import_types = require("@babel/types");
12705
14341
 
12706
14342
  // src/quality/rules/scope.ts
12707
- function unwrap(node) {
14343
+ function unwrap2(node) {
12708
14344
  let cur = node;
12709
14345
  while (cur.type === "TSAsExpression" || cur.type === "TSNonNullExpression" || cur.type === "TSTypeAssertion" || cur.type === "TSSatisfiesExpression") {
12710
14346
  cur = cur.expression;
@@ -12750,7 +14386,7 @@ function isEmptyInitial(node) {
12750
14386
  }
12751
14387
 
12752
14388
  // src/quality/rules/failed-read-empty-state.ts
12753
- var traverse4 = typeof import_traverse5.default === "function" ? import_traverse5.default : import_traverse5.default.default;
14389
+ var traverse5 = typeof import_traverse6.default === "function" ? import_traverse6.default : import_traverse6.default.default;
12754
14390
  var READ_ERROR_PATH_SIGNALS = ERROR_PATH_SIGNALS.filter(
12755
14391
  (re) => re.source !== /\.catch\s*\(/.source
12756
14392
  );
@@ -12771,10 +14407,10 @@ function mentionsJsonParse(node, code) {
12771
14407
  return /\.json\s*\(/.test(code.slice(nodeStart(node), nodeEnd(node)));
12772
14408
  }
12773
14409
  function chainParsesBody(node, code) {
12774
- let cur = unwrap(node);
14410
+ let cur = unwrap2(node);
12775
14411
  for (; ; ) {
12776
14412
  if (cur.type === "CallExpression" || cur.type === "OptionalCallExpression") {
12777
- const callee = unwrap(cur.callee);
14413
+ const callee = unwrap2(cur.callee);
12778
14414
  if ((callee.type === "MemberExpression" || callee.type === "OptionalMemberExpression") && callee.property.type === "Identifier") {
12779
14415
  const method = callee.property.name;
12780
14416
  if (method === "json") return true;
@@ -12784,14 +14420,14 @@ function chainParsesBody(node, code) {
12784
14420
  return true;
12785
14421
  }
12786
14422
  }
12787
- cur = unwrap(callee.object);
14423
+ cur = unwrap2(callee.object);
12788
14424
  continue;
12789
14425
  }
12790
14426
  cur = callee;
12791
14427
  continue;
12792
14428
  }
12793
14429
  if (cur.type === "MemberExpression" || cur.type === "OptionalMemberExpression") {
12794
- cur = unwrap(cur.object);
14430
+ cur = unwrap2(cur.object);
12795
14431
  continue;
12796
14432
  }
12797
14433
  return false;
@@ -12805,7 +14441,7 @@ function parsedBodyBindings(unit, code) {
12805
14441
  const names = /* @__PURE__ */ new Set();
12806
14442
  const record = (id, init) => {
12807
14443
  if (!id || !init) return;
12808
- const awaited = unwrap(init);
14444
+ const awaited = unwrap2(init);
12809
14445
  if (awaited.type !== "AwaitExpression") return;
12810
14446
  if (!chainParsesBody(awaited.argument, code)) return;
12811
14447
  boundNames(id, names);
@@ -12841,12 +14477,12 @@ function parsedBodyBindings(unit, code) {
12841
14477
  return names;
12842
14478
  }
12843
14479
  function derivesFromParsedBody(node, bodies, code) {
12844
- let cur = unwrap(node);
14480
+ let cur = unwrap2(node);
12845
14481
  while (cur && (cur.type === "MemberExpression" || cur.type === "OptionalMemberExpression")) {
12846
- cur = unwrap(cur.object);
14482
+ cur = unwrap2(cur.object);
12847
14483
  }
12848
14484
  if (cur.type === "Identifier") return bodies.has(cur.name);
12849
- if (cur.type === "AwaitExpression") cur = unwrap(cur.argument);
14485
+ if (cur.type === "AwaitExpression") cur = unwrap2(cur.argument);
12850
14486
  return chainParsesBody(cur, code);
12851
14487
  }
12852
14488
  function emptyFallbackArgument(node) {
@@ -12901,7 +14537,7 @@ var failedReadEmptyState = {
12901
14537
  const parsed = file.parsed;
12902
14538
  if (!parsed) continue;
12903
14539
  const examined = /* @__PURE__ */ new Set();
12904
- traverse4(parsed.ast, {
14540
+ traverse5(parsed.ast, {
12905
14541
  CallExpression(path) {
12906
14542
  if (!isFetchCallee(path.node.callee)) return;
12907
14543
  const unit = unitFor(path);
@@ -12923,7 +14559,7 @@ var failedReadEmptyState = {
12923
14559
  const fallback = emptyFallbackArgument(arg);
12924
14560
  if (!fallback) return;
12925
14561
  if (!derivesFromParsedBody(fallback.left, bodies, file.code)) return;
12926
- hit = { line: lineAt(file.content, nodeStart(fallback)), setter: name };
14562
+ hit = { line: lineAt2(file.content, nodeStart(fallback)), setter: name };
12927
14563
  }
12928
14564
  });
12929
14565
  if (!hit) return;
@@ -12941,8 +14577,8 @@ var failedReadEmptyState = {
12941
14577
  };
12942
14578
 
12943
14579
  // src/quality/rules/autosave-armed-by-failed-load.ts
12944
- var import_traverse6 = __toESM(require("@babel/traverse"), 1);
12945
- var traverse5 = typeof import_traverse6.default === "function" ? import_traverse6.default : import_traverse6.default.default;
14580
+ var import_traverse7 = __toESM(require("@babel/traverse"), 1);
14581
+ var traverse6 = typeof import_traverse7.default === "function" ? import_traverse7.default : import_traverse7.default.default;
12946
14582
  function writerTouchesEmptyState(writers) {
12947
14583
  for (const writer of writers) {
12948
14584
  let found = false;
@@ -13022,7 +14658,7 @@ var autosaveArmedByFailedLoad = {
13022
14658
  if (!parsed) continue;
13023
14659
  if (!EMPTY_INITIAL.test(file.code)) continue;
13024
14660
  const armedInFinally = /* @__PURE__ */ new Map();
13025
- traverse5(parsed.ast, {
14661
+ traverse6(parsed.ast, {
13026
14662
  TryStatement(path) {
13027
14663
  const finalizer = path.get("finalizer");
13028
14664
  if (!finalizer || Array.isArray(finalizer) || !finalizer.node) return;
@@ -13040,7 +14676,7 @@ var autosaveArmedByFailedLoad = {
13040
14676
  });
13041
14677
  if (armedInFinally.size === 0) continue;
13042
14678
  const writingFunctions = /* @__PURE__ */ new Map();
13043
- traverse5(parsed.ast, {
14679
+ traverse6(parsed.ast, {
13044
14680
  Function(path) {
13045
14681
  const src = file.code.slice(nodeStart(path.node), nodeEnd(path.node));
13046
14682
  if (!PERSISTENT_WRITE.test(src)) return;
@@ -13061,7 +14697,7 @@ var autosaveArmedByFailedLoad = {
13061
14697
  }
13062
14698
  });
13063
14699
  const reported = /* @__PURE__ */ new Set();
13064
- traverse5(parsed.ast, {
14700
+ traverse6(parsed.ast, {
13065
14701
  CallExpression(path) {
13066
14702
  if (!isEffectCall2(path.node)) return;
13067
14703
  const cb = path.get("arguments.0");
@@ -13085,7 +14721,7 @@ var autosaveArmedByFailedLoad = {
13085
14721
  reported.add(state);
13086
14722
  hits.push({
13087
14723
  file: file.path,
13088
- line: lineAt(file.content, armLine),
14724
+ line: lineAt2(file.content, armLine),
13089
14725
  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.`
13090
14726
  });
13091
14727
  }
@@ -13097,8 +14733,8 @@ var autosaveArmedByFailedLoad = {
13097
14733
  };
13098
14734
 
13099
14735
  // src/quality/rules/config-skipped-work.ts
13100
- var import_traverse7 = __toESM(require("@babel/traverse"), 1);
13101
- var traverse6 = typeof import_traverse7.default === "function" ? import_traverse7.default : import_traverse7.default.default;
14736
+ var import_traverse8 = __toESM(require("@babel/traverse"), 1);
14737
+ var traverse7 = typeof import_traverse8.default === "function" ? import_traverse8.default : import_traverse8.default.default;
13102
14738
  var MUTATING_METHODS = /* @__PURE__ */ new Set(["POST", "PUT", "PATCH", "DELETE"]);
13103
14739
  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;
13104
14740
  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;
@@ -13151,7 +14787,7 @@ var configSkippedWork = {
13151
14787
  if (BOOKKEEPING.test(file.path)) continue;
13152
14788
  const parsed = file.parsed;
13153
14789
  if (!parsed) continue;
13154
- traverse6(parsed.ast, {
14790
+ traverse7(parsed.ast, {
13155
14791
  Function(path) {
13156
14792
  const node = path.node;
13157
14793
  let name = node.id?.name ?? null;
@@ -13193,7 +14829,7 @@ var configSkippedWork = {
13193
14829
  if (writeMatch && BOOKKEEPING.test(after.slice(writeMatch.index, writeMatch.index + 120))) continue;
13194
14830
  hits.push({
13195
14831
  file: file.path,
13196
- line: lineAt(file.content, guard.start),
14832
+ line: lineAt2(file.content, guard.start),
13197
14833
  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.`
13198
14834
  });
13199
14835
  break;
@@ -13216,8 +14852,8 @@ function isConfigAbsenceTest(test, ifPath, code) {
13216
14852
  }
13217
14853
 
13218
14854
  // src/quality/rules/stale-response-wins.ts
13219
- var import_traverse8 = __toESM(require("@babel/traverse"), 1);
13220
- var traverse7 = typeof import_traverse8.default === "function" ? import_traverse8.default : import_traverse8.default.default;
14855
+ var import_traverse9 = __toESM(require("@babel/traverse"), 1);
14856
+ var traverse8 = typeof import_traverse9.default === "function" ? import_traverse9.default : import_traverse9.default.default;
13221
14857
  var ORDERING_GUARD = /\breturn\s*\(\s*\)\s*=>|\bAbortController\b|\bsignal\b|\bcancell?ed\b|\bignore\b|\bstale\b|\bisMounted\b|\baborted\b/i;
13222
14858
  var SETTER2 = /^set[A-Z][A-Za-z0-9_]*$/;
13223
14859
  function calleeIdentifier2(node) {
@@ -13313,7 +14949,7 @@ var staleResponseWins = {
13313
14949
  if (!isClientTarget(file)) continue;
13314
14950
  const parsed = file.parsed;
13315
14951
  if (!parsed) continue;
13316
- traverse7(parsed.ast, {
14952
+ traverse8(parsed.ast, {
13317
14953
  CallExpression(path) {
13318
14954
  if (!isEffectCall3(path.node)) return;
13319
14955
  const args = path.node.arguments;
@@ -13359,7 +14995,7 @@ var staleResponseWins = {
13359
14995
  (d) => derivesFromDep(ident2, /* @__PURE__ */ new Set([d]), cb, file.code)
13360
14996
  );
13361
14997
  if (!driving.some((d) => userDriven(d, cb))) continue;
13362
- hit = { line: lineAt(file.content, nodeStart(inner.node)), ident: ident2 };
14998
+ hit = { line: lineAt2(file.content, nodeStart(inner.node)), ident: ident2 };
13363
14999
  return;
13364
15000
  }
13365
15001
  }
@@ -13400,8 +15036,8 @@ function userDriven(dep, at) {
13400
15036
  }
13401
15037
 
13402
15038
  // src/quality/rules/lost-update-counter.ts
13403
- var import_traverse9 = __toESM(require("@babel/traverse"), 1);
13404
- var traverse8 = typeof import_traverse9.default === "function" ? import_traverse9.default : import_traverse9.default.default;
15039
+ var import_traverse10 = __toESM(require("@babel/traverse"), 1);
15040
+ var traverse9 = typeof import_traverse10.default === "function" ? import_traverse10.default : import_traverse10.default.default;
13405
15041
  var COUNTER_COLUMN = /^(?:credits?|balance|stock|quantity|qty|tokens?|seats?|points?|inventory|remaining|available)$/i;
13406
15042
  var WRITE_CALL = /\bUPDATE\s+\w|\.\s*update\s*\(|\.\s*set\s*\(|\bprisma\s*\.\s*\w+\s*\.\s*update\b/i;
13407
15043
  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;
@@ -13439,7 +15075,7 @@ var lostUpdateCounter = {
13439
15075
  const parsed = file.parsed;
13440
15076
  if (!parsed) continue;
13441
15077
  let firedInFile = false;
13442
- traverse8(parsed.ast, {
15078
+ traverse9(parsed.ast, {
13443
15079
  BinaryExpression(path) {
13444
15080
  if (firedInFile || hits.length >= MAX_PER_SCAN2) return;
13445
15081
  const op = path.node.operator;
@@ -13466,7 +15102,7 @@ var lostUpdateCounter = {
13466
15102
  firedInFile = true;
13467
15103
  hits.push({
13468
15104
  file: file.path,
13469
- line: lineAt(file.content, nodeStart(path.node)),
15105
+ line: lineAt2(file.content, nodeStart(path.node)),
13470
15106
  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.`
13471
15107
  });
13472
15108
  }
@@ -13998,6 +15634,7 @@ function scanQuality(input, rules = qualityRules) {
13998
15634
  attachInlineSuppressed,
13999
15635
  attachScanSuppression,
14000
15636
  authPrefixCovers,
15637
+ bearerProvenanceSafe,
14001
15638
  billingWebhookUnmatchedProps,
14002
15639
  bucketFiles,
14003
15640
  buildMarkerIndex,
@@ -14008,6 +15645,7 @@ function scanQuality(input, rules = qualityRules) {
14008
15645
  calculateGrade,
14009
15646
  callSpreads,
14010
15647
  capWarnings,
15648
+ capabilityTokenHandler,
14011
15649
  checkIntent,
14012
15650
  clampCount,
14013
15651
  classifyExposure,
@@ -14102,11 +15740,15 @@ function scanQuality(input, rules = qualityRules) {
14102
15740
  parseSupabaseConfig,
14103
15741
  perCallTimeoutMs,
14104
15742
  planCause,
15743
+ publicHttpsUrl,
15744
+ publicReadOnlyHandler,
14105
15745
  publicSuppressedRecord,
14106
15746
  qualityRules,
14107
15747
  readInlineSuppressed,
14108
15748
  readScanSuppression,
15749
+ refineDirectObjectFindings,
14109
15750
  replaceBlockComments,
15751
+ resetStructuralState,
14110
15752
  routeForFile,
14111
15753
  routePathFromFile,
14112
15754
  runCustomRules,
@@ -14117,8 +15759,10 @@ function scanQuality(input, rules = qualityRules) {
14117
15759
  scanMultiFile,
14118
15760
  scanQuality,
14119
15761
  scanTokenNullProps,
15762
+ setStructuralFaultForTest,
14120
15763
  sqlInjection,
14121
15764
  stripeWebhookUnprotected,
15765
+ structuralParseCount,
14122
15766
  supabaseFunctionName,
14123
15767
  supabaseNoRLS,
14124
15768
  suppressionSummary,