Lint: the new route inventory, its tests and the touched tests
Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
co-authored by
Claude Opus 5.5
parent
d4fe3bf4ba
commit
8f443c9214
@@ -17,9 +17,6 @@ export { AUDIT_RULE_MAP, parseToolOutput } from '../modules/doctor/rules/tooling
|
||||
export { applySettings, AUDIT_SKIP_RULES, doctorRules, globToRegExp, runDeepProbe, runDoctor } from '../modules/doctor/run.js'
|
||||
export type { RunDoctorOptions } from '../modules/doctor/run.js'
|
||||
export { buildDoctorEndpoint, collectDoctorStatus } from '../modules/doctor/status.js'
|
||||
// routes:check — the site's public routes against the judged snapshot (docs/security.md "Routes nobody has judged")
|
||||
export { runRouteCheck } from '../modules/security/routeCheck.js'
|
||||
export type { RunRouteCheckOptions } from '../modules/security/routeCheck.js'
|
||||
export type { DoctorEndpointOptions } from '../modules/doctor/status.js'
|
||||
export type {
|
||||
DoctorConfig,
|
||||
@@ -32,3 +29,6 @@ export type {
|
||||
DoctorStatus,
|
||||
RuleFinding,
|
||||
} from '../modules/doctor/types.js'
|
||||
// routes:check — the site's public routes against the judged snapshot (docs/security.md "Routes nobody has judged")
|
||||
export { runRouteCheck } from '../modules/security/routeCheck.js'
|
||||
export type { RunRouteCheckOptions } from '../modules/security/routeCheck.js'
|
||||
|
||||
@@ -65,10 +65,10 @@ export const securityRules: DoctorRule[] = [
|
||||
// first segment merely STARTS with those letters (/administracja, /apis): no locale redirect, and no CSP from the
|
||||
// proxy on a single-locale site (IAWL idea 36, fixed in the documented literal in 1.17.1).
|
||||
id: 'proxy-matcher',
|
||||
check: async (ctx) => {
|
||||
check: (ctx) => {
|
||||
const file = `${ctx.src}proxy.ts`
|
||||
const code = stripComments(ctx.read(file))
|
||||
const loose = [...code.matchAll(/\(\?!((?:[\w-]+\|)*[\w-]+)\|/g)].map((m) => m[1]!.split('|')).find((names) => names.some((n) => ['_next', 'admin', 'api'].includes(n)))
|
||||
const loose = [...code.matchAll(/\(\?!((?:[\w-]+\|)*[\w-]+)\|/g)].map((m) => m[1].split('|')).find((names) => names.some((n) => ['_next', 'admin', 'api'].includes(n)))
|
||||
if (!loose) {return []}
|
||||
return [{
|
||||
file,
|
||||
|
||||
@@ -59,6 +59,7 @@ function walk(dir: string): string[] {
|
||||
*/
|
||||
export async function runRouteCheck(options: RunRouteCheckOptions): Promise<number> {
|
||||
const cwd = options.cwd ?? process.cwd()
|
||||
// eslint-disable-next-line no-console -- a command-line check prints its report
|
||||
const log = options.log ?? ((line: string) => console.log(line))
|
||||
const appDir = join(cwd, options.appDir ?? 'src/app')
|
||||
const snapshotFile = join(cwd, options.snapshot ?? 'e2e/routes.snapshot.json')
|
||||
|
||||
@@ -80,7 +80,7 @@ export function listNextRouteFiles(
|
||||
for (const file of files) {
|
||||
const parts = file.split('/').filter((p) => p && !/^\(.*\)$/.test(p))
|
||||
const name = parts.pop() ?? ''
|
||||
const base = name.replace(/\.(?:[cm]?[jt]sx?)$/, '')
|
||||
const base = name.replace(/\.[cm]?[jt]sx?$/, '')
|
||||
const path = `/${parts.join('/')}`
|
||||
if (base === 'route') {
|
||||
const code = read(file)
|
||||
@@ -99,12 +99,12 @@ export function listNextRouteFiles(
|
||||
export type RouteSnapshot = Record<string, string>
|
||||
|
||||
export type RouteSnapshotDiff = {
|
||||
/** Routes the snapshot has and the config no longer opens (not a failure; `--update` drops them). */
|
||||
gone: string[]
|
||||
/** Entries whose reason is empty or still says TODO. */
|
||||
unexplained: string[]
|
||||
/** Routes the config has and the snapshot does not. */
|
||||
unjudged: string[]
|
||||
/** Routes the snapshot has and the config no longer opens (not a failure; `--update` drops them). */
|
||||
gone: string[]
|
||||
}
|
||||
|
||||
export function compareRouteSnapshot(current: string[], snapshot: RouteSnapshot): RouteSnapshotDiff {
|
||||
@@ -112,7 +112,7 @@ export function compareRouteSnapshot(current: string[], snapshot: RouteSnapshot)
|
||||
const now = new Set(current)
|
||||
return {
|
||||
gone: [...judged].filter((id) => !now.has(id)).sort(),
|
||||
unexplained: [...judged].filter((id) => now.has(id) && (!snapshot[id]?.trim() || /^TODO\b/i.test(snapshot[id]!.trim()))).sort(),
|
||||
unexplained: [...judged].filter((id) => now.has(id) && (!snapshot[id]?.trim() || /^TODO\b/i.test(snapshot[id].trim()))).sort(),
|
||||
unjudged: current.filter((id) => !judged.has(id)),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -369,7 +369,7 @@ describe('3 · refused files leave no submission and send no e-mail', () => {
|
||||
|
||||
test('a program inside an Office file is found also with trailing dots or spaces (Windows drops them)', async () => {
|
||||
for (const entry of ['word/setup.exe', 'word/setup.exe.', 'word/setup.exe ', 'word/setup.EXE. .', 'word/vbaProject.bin.']) {
|
||||
const data = zip({ '[Content_Types].xml': '<Types/>', 'word/document.xml': '<w:document/>', [entry]: 'x' })
|
||||
const data = zip({ '[Content_Types].xml': '<Types/>', [entry]: 'x', 'word/document.xml': '<w:document/>' })
|
||||
await refused([{ name: 'cv.docx', data }], notAcceptable('cv.docx'))
|
||||
}
|
||||
})
|
||||
|
||||
@@ -16,13 +16,13 @@ const { getMiddlewareMatchers } = createRequire(import.meta.url)(path.join(next,
|
||||
getMiddlewareMatchers: (matchers: string[], nextConfig: object) => { regexp: string }[]
|
||||
}
|
||||
const runs = (matcher: string) => {
|
||||
const re = new RegExp(getMiddlewareMatchers([matcher], {})[0]!.regexp)
|
||||
const re = new RegExp(getMiddlewareMatchers([matcher], {})[0].regexp)
|
||||
return (pathname: string) => re.test(pathname)
|
||||
}
|
||||
|
||||
describe('the proxy matcher', () => {
|
||||
test('skips /api, /admin and /_next as whole segments and files; runs on pages that only START with those letters', () => {
|
||||
const proxy = runs(DEFAULT_PROXY_MATCHER[0]!)
|
||||
const proxy = runs(DEFAULT_PROXY_MATCHER[0])
|
||||
for (const skipped of ['/api', '/api/users', '/api/ipal/hit', '/admin', '/admin/', '/admin/collections/users', '/_next/static/chunk.js', '/robots.txt', '/sitemap.xml']) {
|
||||
expect([skipped, proxy(skipped)]).toEqual([skipped, false])
|
||||
}
|
||||
@@ -33,6 +33,6 @@ describe('the proxy matcher', () => {
|
||||
|
||||
test('the reference site uses the same literal (Next reads it statically, it cannot be imported)', () => {
|
||||
const proxyFile = readFileSync(path.join(root, 'reference/src/proxy.ts'), 'utf8')
|
||||
expect(proxyFile).toContain(`matcher: ['${DEFAULT_PROXY_MATCHER[0]!.replace(/\\/g, '\\\\')}']`)
|
||||
expect(proxyFile).toContain(`matcher: ['${DEFAULT_PROXY_MATCHER[0].replace(/\\/g, '\\\\')}']`)
|
||||
})
|
||||
})
|
||||
|
||||
@@ -16,8 +16,8 @@ import { describe, expect, test, vi } from 'vitest'
|
||||
|
||||
import type { GraphqlSchemaLike } from '../src/modules/security/routeInventory.js'
|
||||
|
||||
import { iapl } from '../src/plugin.js'
|
||||
import { compareRouteSnapshot, listNextRouteFiles, listPublicRoutes, updateRouteSnapshot } from '../src/modules/security/routeInventory.js'
|
||||
import { iapl } from '../src/plugin.js'
|
||||
import { buildTestConfig } from './helpers.js'
|
||||
|
||||
vi.mock('server-only', () => ({}))
|
||||
@@ -67,7 +67,7 @@ describe('listPublicRoutes', () => {
|
||||
const config = await build(adapter())
|
||||
lists[name] = listPublicRoutes(config, { graphqlSchema: await configToSchema(config) })
|
||||
}
|
||||
const sqlite = lists.sqlite!
|
||||
const sqlite = lists.sqlite
|
||||
expect(lists.mongodb).toEqual(sqlite)
|
||||
expect(lists.postgres).toEqual(sqlite)
|
||||
for (const id of [
|
||||
@@ -88,15 +88,15 @@ describe('listPublicRoutes', () => {
|
||||
|
||||
test('Next route files: exported methods, route groups left out, metadata routes', () => {
|
||||
const code: Record<string, string> = {
|
||||
'(frontend)/[locale]/page.tsx': 'export default function Page() {}',
|
||||
'(payload)/api/[...slug]/route.ts': 'export const GET = a\nexport const POST = b\nexport const OPTIONS = c',
|
||||
'api/health/route.ts': 'export async function GET() {}',
|
||||
'api/mcp/route.ts': "export { mcpGET as GET, mcpPOST as POST } from '@/lib/content'",
|
||||
'md/[locale]/[[...slug]]/route.ts': 'export const dynamic = "force-dynamic"\nexport function GET() {}',
|
||||
'robots.ts': 'export default function robots() {}',
|
||||
'sitemap.xml/route.ts': 'export const GET = handler',
|
||||
'(frontend)/[locale]/page.tsx': 'export default function Page() {}',
|
||||
}
|
||||
expect(listNextRouteFiles(Object.keys(code), (f) => code[f]!)).toEqual([
|
||||
expect(listNextRouteFiles(Object.keys(code), (f) => code[f])).toEqual([
|
||||
{ methods: ['GET', 'OPTIONS', 'POST'], path: '/api/[...slug]' },
|
||||
{ methods: ['GET'], path: '/api/health' },
|
||||
{ methods: ['GET', 'POST'], path: '/api/mcp' },
|
||||
|
||||
@@ -294,7 +294,7 @@ describe('starter: links and paths (IAWL ideas 12, 13)', () => {
|
||||
const dir = path.join(parent, 'site')
|
||||
try {
|
||||
for (const bad of ['../escaped.txt', 'a/../../escaped.txt', path.join(parent, 'abs.txt')]) {
|
||||
expect(() => writeFiles(dir, { 'ok.txt': 'fine', [bad]: 'no' }), bad).toThrow(/outside the new folder/)
|
||||
expect(() => writeFiles(dir, { [bad]: 'no', 'ok.txt': 'fine' }), bad).toThrow(/outside the new folder/)
|
||||
}
|
||||
expect(readdirSync(parent)).toEqual([])
|
||||
writeFiles(dir, { 'ok.txt': 'fine', 'src/a/b.ts': 'x' })
|
||||
|
||||
Reference in New Issue
Block a user