A server endpoint that accepts form data without checking it, does not check who is asking, or has no limit on how often it can be called. Your forms talk to these directly, so a gap here is a gap in the UI.
Add "API route checks" from ntent to this repo.
Fetch https://ntent.app/r/f/check-api-routes as plain text. Write it verbatim to scripts/check-api-routes.mjs. Then make exactly these edits and no others: Set CONFIG.routeDirs to where this repo keeps its handlers, and add your own validation, auth and rate-limit helper names to the three matcher lists.
Then check it: Add a POST handler with no schema parse. The check names the file and the missing piece.Reads https://ntent.app/r/f/check-api-routes
Read the code
check-api-routes.mjsscripts/check-api-routes.mjs
421 lines
#!/usr/bin/env node
/**
* API contract gate: every route handler validates its input, checks who is
* calling, and declares a rate limit.
*
* Why presence checks are worth it. These three are the most common API defects
* and all three are invisible to the type system. TypeScript will happily let
* you write `const body = await req.json()` and treat the result as whatever
* you claim it is, because `json()` returns `any`. Nothing warns you that a
* handler has no auth check. Nothing counts requests.
*
* This does not verify the checks are correct. It verifies they are present.
* That is a much weaker claim and still catches the overwhelming majority of
* real cases, because the usual failure is not a subtly wrong auth check, it is
* no auth check at all in a handler somebody added at 6pm.
*
* PRESENT HAS TO MEAN PRESENT. Two things kept that claim from being true.
* A bare `.parse(` matcher counted `JSON.parse(await req.text())` as schema
* validation, and JSON.parse is the exact thing this check exists to find
* unaccompanied: it decodes, it does not validate, and TypeScript is just as
* happy with the `any` that comes out. And every matcher ran over the whole
* file, so validation in the GET handler, or in a comment, or in a string,
* satisfied the POST. Now comments and string literals are stripped first, and
* every check is attributed to the handler it is about.
*
* ATTRIBUTION APPLIES TO AUTH TOO, and that was the last leak. A file-wide auth
* search means one authenticated handler vouches for every other handler in the
* file: a route with an authed GET and an unauthenticated POST beside it passed
* --check, which is the exact shape of the 6pm handler this gate exists to
* catch. What one handler's own body can no longer do is speak for another's.
*
* DECLARED IS NOT CALLED. The shared code above the first export used to count
* towards every handler whole, and `function auth(req)` matched the auth
* pattern by itself. So a file that declared auth and validateInput and called
* neither passed, with a handler that returned whatever it was sent. Now the
* file is read one top-level declaration at a time, and a declaration counts
* for a handler only when that handler names it, directly or through another
* declaration it names. The wrapper case still works for that reason: a
* handler wrapped in `withUser`, or one that calls `guard()`, names the helper
* its auth lives in. A helper written below the last handler is treated the
* same as one written above the first.
*
* WHAT IS STILL HEURISTIC. It reads text, not types. A helper named
* validateInput that validates nothing passes, and validation reached through
* an unusual indirection is missed. Naming a helper counts as using it, so a
* handler that mentions `guard` and never calls it passes, and so does an arrow
* function declared inside a handler and left uncalled. It tells you a check is
* THERE.
*
* Four checks:
* 1. NO-INPUT-SCHEMA a body-taking method that never calls .parse/.safeParse
* 2. NO-AUTH no recognised auth call, and not declared public
* 3. NO-RATE-LIMIT no recognised rate-limit call, and not exempt
* 4. UNDECLARED-PUBLIC a route marked public with no reason given
*
* Check 4 matters more than it looks. Making a route public is a real decision
* and it should read like one. A bare marker with no sentence next to it is how
* an endpoint ends up public because someone was debugging.
*
* Declare an exemption in the route file itself, so it travels with the code
* and shows up in the diff that makes it true:
*
* // @api-public: Stripe calls this before any session exists. Signature
* // verified below via stripe.webhooks.constructEvent.
* // @api-no-rate-limit: Stripe retries with backoff and we must not drop them.
*
* Usage:
* node scripts/check-api-routes.mjs
* node scripts/check-api-routes.mjs --check
*/
import { readFileSync, readdirSync, statSync, existsSync } from 'node:fs'
import { join, relative } from 'node:path'
// ---------------------------------------------------------------- CONFIG ---
const CONFIG = {
// Next.js App Router. For Pages Router use ['src/pages/api'] and drop the
// filename filter below.
routeDirs: ['src/app'],
routeFileNames: ['route.ts', 'route.tsx', 'route.js'],
ignoreDirs: ['node_modules', '.next', 'dist', '.git'],
// Methods that carry a body and therefore need input validation.
bodyMethods: ['POST', 'PUT', 'PATCH'],
allMethods: ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'HEAD', 'OPTIONS'],
// Anything that counts as validating input. Add your own helper names.
//
// The lookbehind is the point of this list. `.parse(` on its own is a fine
// signal for zod, valibot and arktype, and a terrible one on its own line
// because JSON.parse shares the shape and validates nothing. Exclude it by
// name rather than dropping the generic form, which would miss every schema
// library that spells its method parse.
validationCalls: [
/(?<!\bJSON\s*)\.\s*safeParse\s*\(/,
/(?<!\bJSON\s*)\.\s*parse\s*\(/,
/\bvalidate(?:Body|Input|Request)\s*\(/,
],
// Anything that counts as establishing who is calling. Add your own.
authCalls: [
/\bauth\s*\(/,
/getServerSession\s*\(/,
/requireUser\s*\(/,
/requireSession\s*\(/,
/currentUser\s*\(/,
/getUser\s*\(/,
/verifyWebhook\s*\(/,
/constructEvent\s*\(/,
],
// Anything that counts as a rate limit.
rateLimitCalls: [/rateLimit\s*\(/, /ratelimit\s*\./, /limiter\s*\./, /checkRateLimit\s*\(/],
// In-file exemption markers.
//
// [ \t]* and [^\n]*, never \s* and .*, because \s matches a newline: an
// earlier version of this let `// @api-public` with no reason swallow the
// NEXT line's text as its reason and pass the length check. The rule this
// proves is the red gate in `03-gates.md#probe`: write a probe that must
// fail before you trust a new check, or you ship something that reads as
// coverage and is not.
markers: {
public: /@api-public:?[ \t]*([^\n]*)/,
noRateLimit: /@api-no-rate-limit:?[ \t]*([^\n]*)/,
noSchema: /@api-no-schema:?[ \t]*([^\n]*)/,
},
// A reason shorter than this reads as no reason.
minReasonLength: 20,
}
// --------------------------------------------------------------- HELPERS ---
function walk(dir, acc = []) {
let entries
try {
entries = readdirSync(dir)
} catch {
return acc
}
for (const entry of entries) {
if (CONFIG.ignoreDirs.includes(entry)) continue
const full = join(dir, entry)
if (statSync(full).isDirectory()) walk(full, acc)
else if (CONFIG.routeFileNames.includes(entry)) acc.push(full)
}
return acc
}
/** Which HTTP methods this file exports. */
function methodsIn(text) {
return CONFIG.allMethods.filter((m) =>
new RegExp(`export\\s+(?:async\\s+)?(?:function\\s+${m}\\b|const\\s+${m}\\s*[:=])`).test(text)
)
}
const anyMatch = (patterns, text) => patterns.some((p) => p.test(text))
/**
* Comments and string literals blanked out, positions preserved.
*
* A matcher that reads a file as raw text believes anything anybody wrote about
* the code. `// TODO: add schema.parse here` used to satisfy the input check,
* which is the worst possible failure for a presence check: the comment saying
* the work is outstanding was accepted as the work. Same length out as in, so
* the handler slicing below still lines up with the original offsets.
*/
function blankNoise(text) {
const blank = (m) => m.replace(/[^\n]/g, ' ')
return text
.replace(/\/\*[\s\S]*?\*\//g, blank)
.replace(/\/\/[^\n]*/g, blank)
.replace(/`(?:\\.|[^`\\])*`/g, blank)
.replace(/'(?:\\.|[^'\\\n])*'/g, blank)
.replace(/"(?:\\.|[^"\\\n])*"/g, blank)
}
/** A line that opens a top-level statement, once it is known to sit at depth 0. */
const STATEMENT_START =
/(?:^|[\n;])[ \t]*(?=(?:import|export|async\s+function|function|const|let|var|class|type|interface|enum|declare)\b)/g
/** What a statement declares, or undefined for an import, a type, or a bare call. */
const declaredName = (statement) =>
statement
.replace(/^(?:export\s+)?(?:default\s+)?(?:declare\s+)?(?:async\s+)?/, '')
.match(/^(?:function\s*\*?|const|let|var|class)\s+([A-Za-z_$][\w$]*)/)?.[1]
/**
* The file as top-level statements, each with the name it declares.
*
* Crude on purpose: no parse, no dependency. It counts brackets to tell a
* statement at the top of the file from one inside a function, and that is all
* it knows. A regex literal holding an unmatched bracket throws the count, so
* the count starts again at every handler export, which is the one boundary
* that is always found. The cost of a thrown count is a helper read as part of
* the statement above it, which is what this did for every helper before.
*/
function statements(text, marks) {
const handlerAt = new Map(marks.map((m) => [m.at, m.method]))
const starts = new Set([0, ...handlerAt.keys()])
const candidates = new Set()
for (const hit of text.matchAll(STATEMENT_START)) candidates.add(hit.index + hit[0].length)
let depth = 0
for (let i = 0; i < text.length; i++) {
if (handlerAt.has(i)) depth = 0
if (depth === 0 && candidates.has(i)) starts.add(i)
const c = text[i]
if (c === '{' || c === '(' || c === '[') depth++
else if ((c === '}' || c === ')' || c === ']') && depth > 0) depth--
}
const ordered = [...starts].sort((a, b) => a - b)
return ordered.map((at, i) => {
const source = text.slice(at, ordered[i + 1] ?? text.length)
const method = handlerAt.get(at)
return { source, method, name: method ?? declaredName(source.trimStart()) }
})
}
const names = (source) =>
new RegExp(`(?<![.\\w$])(?:${source})(?![\\w$])`)
/**
* The source each exported handler answers for: its own, and every top-level
* declaration it names.
*
* What this buys is attribution. A file-wide search cannot tell you whether the
* validation it found belongs to the POST that needs it or the GET beside it,
* and "some handler in this file validates something" is not a claim worth
* gating on. Nor is "something in this file is called auth".
*/
function handlerBodies(text) {
const marks = []
for (const m of CONFIG.allMethods) {
const re = new RegExp(`export\\s+(?:async\\s+)?(?:function\\s+${m}\\b|const\\s+${m}\\s*[:=])`, 'g')
let hit
while ((hit = re.exec(text))) marks.push({ method: m, at: hit.index })
}
marks.sort((a, b) => a.at - b.at)
const all = statements(text, marks)
// A statement that declares nothing cannot be named, so it is everybody's:
// a bare call at the top of the file, or a destructured
// `const { user } = await auth()`.
const shared = all.filter((s) => !s.name).map((s) => s.source).join('')
const declared = all.filter((s) => s.name && !s.method)
const bodies = new Map()
for (const method of new Set(marks.map((m) => m.method))) {
let body = shared + all.filter((s) => s.method === method).map((s) => s.source).join('')
const taken = new Set()
// Follow the names until they stop leading anywhere: the handler calls
// guard, guard calls requireUser.
for (let grew = true; grew; ) {
grew = false
for (const s of declared) {
if (taken.has(s) || !names(s.name.replace(/\$/g, '\\$')).test(body)) continue
taken.add(s)
body += s.source
grew = true
}
}
// `function auth(req)` is a declaration and reads like a call. Take the
// name out, so only a call is left to match.
bodies.set(method, body.replace(/\bfunction\s*\*?\s*[A-Za-z_$][\w$]*/g, 'function'))
}
return bodies
}
/** Read a marker and its reason. Returns null, or { reason }. */
function marker(text, re) {
const m = text.match(re)
if (!m) return null
return { reason: (m[1] || '').trim() }
}
// ------------------------------------------------------------------ MAIN ---
function main() {
const strict = process.argv.includes('--check')
// What the pre-commit hook triggers on, asked of the checker so that moving
// CONFIG.routeDirs moves the gate with it. A hook that hardcoded src/app/api
// never ran this check for a repo that keeps its routes in app/.
if (process.argv.includes('--print-config')) {
for (const dir of CONFIG.routeDirs) console.log(`watchDir\t${dir}`)
for (const name of CONFIG.routeFileNames) console.log(`watchName\t${name}`)
process.exit(0)
}
const files = CONFIG.routeDirs.filter(existsSync).flatMap((d) => walk(d))
const findings = []
// A scan that found no route file checked nothing, and "ok. 0 route file(s)"
// reads exactly like a pass. In the field study 34 of 46 repos got that line,
// because this reads Next route handlers and nothing else. Say so, and say
// what to change, instead of letting the gate show as passed.
if (!files.length) {
const missing = CONFIG.routeDirs.filter((d) => !existsSync(d))
console.log(
`api: could not check. Read 0 route files under ${CONFIG.routeDirs.join(', ')}` +
` (looking for ${CONFIG.routeFileNames.join(', ')}).\n` +
(missing.length
? ` ${missing.join(', ')} ${missing.length === 1 ? 'does' : 'do'} not exist here.\n`
: '') +
` This checker reads Next route.ts handlers only; Express, Hono, Fastify, Nest and pages/api are not read.\n` +
` Point CONFIG.routeDirs at your app router, or drop this check.`,
)
process.exit(2)
}
for (const file of files) {
const raw = readFileSync(file, 'utf8')
// Markers are read from the raw text: they live in comments by design.
const text = blankNoise(raw)
const where = relative(process.cwd(), file)
const methods = methodsIn(text)
if (!methods.length) continue
const bodies = handlerBodies(text)
const isPublic = marker(raw, CONFIG.markers.public)
const noRateLimit = marker(raw, CONFIG.markers.noRateLimit)
const noSchema = marker(raw, CONFIG.markers.noSchema)
// 1. Input validation, per body-carrying method, in that method's own body.
const unvalidated = methods
.filter((m) => CONFIG.bodyMethods.includes(m))
.filter((m) => !anyMatch(CONFIG.validationCalls, bodies.get(m) ?? ''))
if (unvalidated.length && !noSchema) {
const decodesOnly = unvalidated.some((m) => /\bJSON\s*\.\s*parse\s*\(/.test(bodies.get(m) ?? ''))
findings.push({
level: 'error',
code: 'NO-INPUT-SCHEMA',
where,
msg:
`${unvalidated.join('/')} accepts a body but nothing validates it.\n` +
(decodesOnly
? ` It calls JSON.parse, which decodes and does not validate: the result\n` +
` is any, exactly as req.json() would have been.\n`
: ` req.json() returns any, so the handler trusts whatever arrives.\n`) +
` fix: define a Zod schema and call schema.safeParse(await req.json()),\n` +
` returning 400 on failure. If this genuinely takes no structured\n` +
` body, add: // @api-no-schema: <reason>`,
})
}
// 2. Auth, per handler, in that handler's body plus the helpers it names.
const unauthed = methods.filter((m) => !anyMatch(CONFIG.authCalls, bodies.get(m) ?? ''))
if (unauthed.length && !isPublic) {
findings.push({
level: 'error',
code: 'NO-AUTH',
where,
msg:
`${unauthed.join('/')} has no recognised auth check.\n` +
` fix: call your session helper and return 401 when there is no user.\n` +
` If this route is deliberately public, add:\n` +
` // @api-public: <why, and what protects it instead>`,
})
}
// 3. Rate limit, per handler, for the same reason as auth.
const unlimited = methods.filter((m) => !anyMatch(CONFIG.rateLimitCalls, bodies.get(m) ?? ''))
if (unlimited.length && !noRateLimit) {
findings.push({
level: 'warning',
code: 'NO-RATE-LIMIT',
where,
msg:
`${unlimited.join('/')} declares no rate limit.\n` +
` fix: wrap it in your limiter, or add:\n` +
` // @api-no-rate-limit: <reason>`,
})
}
// 4. A public route with no stated reason.
for (const [name, found] of [
['@api-public', isPublic],
['@api-no-rate-limit', noRateLimit],
['@api-no-schema', noSchema],
]) {
if (found && found.reason.length < CONFIG.minReasonLength) {
findings.push({
level: 'error',
code: 'UNDECLARED-EXEMPTION',
where,
msg:
`${name} is set but says nothing useful.\n` +
` An exemption with no reason becomes permanent. Write the sentence:\n` +
` what makes this safe, or what protects it instead.`,
})
}
}
}
// -------------------------------------------------------------- REPORT ---
const errors = findings.filter((f) => f.level === 'error')
const warnings = findings.filter((f) => f.level === 'warning')
if (!findings.length) {
console.log(`api: ok. ${files.length} route file(s), all validated, authed and limited.`)
process.exit(0)
}
if (errors.length) {
console.log(`\napi: ${errors.length} error(s)\n`)
for (const f of errors) console.log(` ${f.code} ${f.where}\n ${f.msg}\n`)
}
if (warnings.length) {
console.log(`api: ${warnings.length} warning(s)\n`)
for (const f of warnings) console.log(` ${f.code} ${f.where}\n ${f.msg}\n`)
}
process.exit(strict && errors.length ? 1 : 0)
}
main()
How to tell it works: Add a POST handler with no schema parse. The check names the file and the missing piece.