Files
Kelx/scripts/find-unguarded-awaited-routes.js
T
2026-11-30 16:32:37 +00:00

318 lines
11 KiB
JavaScript

#!/usr/bin/env node
"use strict";
// Finds route handlers whose own async context contains an `await` that is
// not lexically enclosed by a try-with-catch. Express 4 does not catch
// async-handler rejections, so such an await turns a transient error (a DB
// hiccup, a socket reset) into an unanswered request: the process-level
// unhandledRejection handler only logs, and the client hangs.
//
// What counts as guarded:
// - the await sits inside a try block that has a catch (finally-only does
// NOT stop propagation), at any depth of the handler body;
// - the awaited expression is chained with .catch(...) in the same
// statement;
// - the await sits inside a nested function body (arrow, function
// expression, async expression arrow) — a separate async context whose
// rejection never reaches the Express layer.
//
// What this scanner does NOT see (by design, keep it simple): awaits inside
// template-literal ${...} expressions (template text is blanked), object/
// class method shorthand bodies, and for-await-of loops are matched by the
// plain `await` scan. Treat the output as a high-precision candidate list:
// every reported site must still be confirmed by reading the handler before
// fixing, and every fix must keep the route's response order unchanged.
//
// Usage: node scripts/find-unguarded-awaited-routes.js [files...]
const fs = require("fs");
// Replace comments, string literals and template-literal text with spaces
// (length-preserving) so brace/paren tracking cannot be derailed by braces in
// strings. Template ${...} expression code is blanked too — see the header
// note.
function cleanSource(src) {
const out = src.split("");
const n = src.length;
const blank = (from, to) => {
for (let k = Math.max(0, from); k < Math.min(n, to); k++) {
if (out[k] !== "\n") out[k] = " ";
}
};
const skipString = (i, quote) => {
let j = i + 1;
while (j < n) {
if (src[j] === "\\") { j += 2; continue; }
if (src[j] === quote || src[j] === "\n") { return j + (src[j] === quote ? 1 : 0); }
j++;
}
return j;
};
let i = 0;
while (i < n) {
const c = src[i];
if (c === "/" && src[i + 1] === "/") {
let j = src.indexOf("\n", i); if (j < 0) j = n;
blank(i, j); i = j; continue;
}
if (c === "/" && src[i + 1] === "*") {
let j = src.indexOf("*/", i + 2); j = j < 0 ? n : j + 2;
blank(i, j); i = j; continue;
}
if (c === '"' || c === "'") {
const j = skipString(i, c);
blank(i + 1, j - 1); i = j; continue;
}
if (c === "`") {
let j = i + 1;
while (j < n) {
if (src[j] === "\\") { j += 2; continue; }
if (src[j] === "`") { j++; break; }
if (src[j] === "$" && src[j + 1] === "{") {
let depth = 1; let k = j + 2;
while (k < n && depth > 0) {
const d = src[k];
if (d === '"' || d === "'") { k = skipString(k, d); continue; }
if (d === "`") { k = skipString(k, "`"); continue; }
if (d === "{") depth++;
else if (d === "}") depth--;
k++;
}
j = k; continue;
}
j++;
}
blank(i + 1, j - 1); i = j; continue;
}
i++;
}
return out.join("");
}
function lineOf(src, pos) {
let line = 1;
for (let k = 0; k < pos && k < src.length; k++) if (src[k] === "\n") line++;
return line;
}
// Walks from the character after a route call's opening paren, returns the
// [start, end) of the last-argument handler's body braces, or null when the
// registration has no inline handler (e.g. app.use(router)).
function findHandlerBody(clean, callOpenPos) {
let depth = 1; // inside the route call's paren
let i = callOpenPos + 1;
const n = clean.length;
while (i < n && depth > 0) {
const c = clean[i];
if (c === "(") { depth++; i++; continue; }
if (c === ")") { depth--; i++; continue; }
if (c === "{" || c === "}") { i++; continue; }
// arrow introducing a block-bodied handler: => {
if (c === "=" && clean[i + 1] === ">" && depth === 1) {
let j = i + 2;
while (j < n && /\s/.test(clean[j])) j++;
if (clean[j] === "{") {
// body from j to its matching }
let bdepth = 0; let k = j;
for (; k < n; k++) {
if (clean[k] === "{") bdepth++;
else if (clean[k] === "}") { bdepth--; if (bdepth === 0) return [j + 1, k]; }
}
return null;
}
}
i++;
}
return null;
}
// Regions of the handler body that are nested function bodies (separate async
// contexts) plus the ranges of try blocks that have a catch.
function analyzeBody(clean, start, end) {
const nested = [];
const guardedTry = [];
const i0 = start, iN = end;
const matchBrace = (openPos) => {
let d = 0;
for (let k = openPos; k < iN; k++) {
if (clean[k] === "{") d++;
else if (clean[k] === "}") { d--; if (d === 0) return k; }
}
return -1;
};
// paren stack for async-expression-arrow regions
const parenStack = [];
let i = i0;
while (i < iN) {
const c = clean[i];
if (c === "(") { parenStack.push(i); i++; continue; }
if (c === ")") { parenStack.pop(); i++; continue; }
if (c === "{" ) {
// try block?
let j = i - 1;
while (j >= i0 && /\s/.test(clean[j])) j--;
const before = clean.slice(Math.max(i0, j - 3), j + 1);
if (/try$/.test(before)) {
const close = matchBrace(i);
if (close > 0) {
// does a catch follow?
let m = close + 1;
while (m < iN && /\s/.test(clean[m])) m++;
if (clean.startsWith("catch", m)) {
const catchBrace = clean.indexOf("{", m);
const catchClose = catchBrace > 0 ? matchBrace(catchBrace) : -1;
guardedTry.push([i, catchClose > 0 ? catchClose : close]);
i = (catchClose > 0 ? catchClose : close) + 1;
continue;
}
// finally-only: not guarded; skip the try block only
i = close + 1;
continue;
}
}
// arrow/function bodies were handled when their introducer was seen —
// but a plain `{` after `=>` whose params contain no parens (x => {...})
// still needs marking; detect by looking back for `=>`.
let j2 = i - 1;
while (j2 >= i0 && /\s/.test(clean[j2])) j2--;
if (j2 >= i0 && clean[j2] === ">" && clean[j2 - 1] === "=") {
const close = matchBrace(i);
if (close > 0) { nested.push([i, close]); i = close + 1; continue; }
}
i++; continue;
}
if (c === "=" && clean[i + 1] === ">" ) {
let j = i + 2;
while (j < iN && /\s/.test(clean[j])) j++;
if (clean[j] === "{") {
const close = matchBrace(j);
if (close > 0) { nested.push([j, close]); i = close + 1; continue; }
} else {
// expression arrow: if introduced by `async`, its body extends to the
// enclosing paren group's close. The async keyword may sit directly
// before the arrow (async x => ...), or before the parameter group
// (async (x) => ...).
let kw = -1;
let b = i - 1;
while (b >= i0 && /\s/.test(clean[b])) b--;
if (b >= i0 && clean[b] === ")") {
// match backwards over the parameter group
let d = 0; let k = b;
for (; k >= i0; k--) {
if (clean[k] === ")") d++;
else if (clean[k] === "(") { d--; if (d === 0) break; }
}
let g = k - 1;
while (g >= i0 && /\s/.test(clean[g])) g--;
if (g - 4 >= i0 && clean.slice(g - 4, g + 1) === "async") kw = g - 4;
} else if (/[A-Za-z0-9_$]/.test(clean[b] || "")) {
let g = b;
while (g >= i0 && /[A-Za-z0-9_$]/.test(clean[g])) g--;
if (g - 4 >= i0 && clean.slice(g - 4, g + 1) === "async") kw = g - 4;
}
if (kw >= 0 && parenStack.length) {
const open = parenStack[parenStack.length - 1];
let d = 0; let k = open;
for (; k < iN; k++) {
if (clean[k] === "(") d++;
else if (clean[k] === ")") { d--; if (d === 0) break; }
}
if (k < iN) { nested.push([kw, k]); i = k; continue; }
}
}
i += 2; continue;
}
if (c === "f" && clean.startsWith("function", i)) {
// function expression declaration: skip name/params, mark body
let j = i + 8;
while (j < iN && /\s/.test(clean[j])) j++;
if (/[A-Za-z_$]/.test(clean[j] || "")) { while (j < iN && /[A-Za-z0-9_$]/.test(clean[j])) j++; }
// skip generics-less params
if (clean[j] === "(") {
let d = 0; let k = j;
for (; k < iN; k++) {
if (clean[k] === "(") d++;
else if (clean[k] === ")") { d--; if (d === 0) break; }
}
let b = k + 1;
while (b < iN && /\s/.test(clean[b])) b++;
if (clean[b] === "{") {
const close = matchBrace(b);
if (close > 0) { nested.push([b, close]); i = close + 1; continue; }
}
i = k + 1; continue;
}
i += 8; continue;
}
i++;
}
return { nested, guardedTry };
}
function scanFile(path) {
const raw = fs.readFileSync(path, "utf8");
const clean = cleanSource(raw);
const findings = [];
const ROUTE_RE = /\b(?:app|router)\.(get|post|put|delete|patch|all|use)\s*\(/g;
let m;
while ((m = ROUTE_RE.exec(clean)) !== null) {
const callOpen = clean.indexOf("(", m.index);
const body = findHandlerBody(clean, callOpen);
if (!body) continue;
const [bs, be] = body;
const { nested, guardedTry } = analyzeBody(clean, bs, be);
const inRegions = (pos, regions) => regions.some(([a, b]) => pos >= a && pos < b);
const AWAIT_RE = /\bawait\b/g;
let a;
while ((a = AWAIT_RE.exec(clean.slice(bs, be))) !== null) {
const abs = bs + a.index;
if (inRegions(abs, nested)) continue;
if (inRegions(abs, guardedTry)) continue;
// .catch chain in the same statement?
const stmtEnd = (() => {
let d = 0; let k = abs;
for (; k < be; k++) {
if (clean[k] === "(") d++;
else if (clean[k] === ")") { d--; if (d < 0) break; }
if (clean[k] === ";" && d === 0) break;
if (clean[k] === "\n" && d === 0) {
// statement may continue on the next line — look ahead past the
// newline: if the next non-space char cannot start a continuation
// (heuristic: line ends with an operator or open paren handled by
// depth), stop here.
const rest = clean.slice(k + 1, k + 3);
if (!/^\s*[.[]/.test(rest)) break;
}
}
return Math.min(k, abs + 400);
})();
const stmt = clean.slice(abs, stmtEnd);
if (/\.catch\s*\(/.test(stmt)) continue;
findings.push({
file: path,
routeLine: lineOf(raw, m.index),
method: m[1],
awaitLine: lineOf(raw, abs),
text: raw.slice(abs, raw.indexOf("\n", abs) < 0 ? abs + 120 : raw.indexOf("\n", abs)).trim().slice(0, 120),
});
}
}
return findings;
}
const files = process.argv.slice(2);
if (!files.length) {
console.error("usage: node scripts/find-unguarded-awaited-routes.js <file.js> [...]");
process.exit(2);
}
let total = 0;
for (const f of files) {
const found = scanFile(f);
total += found.length;
for (const x of found) {
console.log(`${x.file}:${x.awaitLine} [${x.method} @ line ${x.routeLine}] ${x.text}`);
}
}
console.error(`${total} unguarded await(s) found.`);
process.exit(0);