From fa75ad06ba03450e1cb893bead751546be58e667 Mon Sep 17 00:00:00 2001 From: cj-vana Date: Thu, 5 Nov 2026 12:42:17 -0700 Subject: [PATCH 1/8] build: require Playwright 1.64.1 or newer The range was ^1.49.1, which nothing tested below the locked 1.63.0. The suite and the Firefox and WebKit smokes pass on 1.64.1, and on a 1.65 build with the 1.65.0 browser revisions, so the floor moves to what was tested. 1.64.0 stays out of range: its Chromium aborts a preflighted cross-origin redirect whenever any route is registered (microsoft/playwright#43242, fixed in 1.64.1), and the fence always registers one. --- package-lock.json | 16 ++++++++-------- package.json | 2 +- 2 files changed, 9 insertions(+), 9 deletions(-) diff --git a/package-lock.json b/package-lock.json index 0c213da..d6e3853 100644 --- a/package-lock.json +++ b/package-lock.json @@ -13,7 +13,7 @@ "commander": "^12.1.0", "jiti": "^2.4.2", "picocolors": "^1.1.1", - "playwright": "^1.49.1", + "playwright": "^1.64.1", "zod": "^3.24.1" }, "bin": { @@ -3455,12 +3455,12 @@ } }, "node_modules/playwright": { - "version": "1.63.0", - "resolved": "https://registry.npmjs.org/playwright/-/playwright-1.63.0.tgz", - "integrity": "sha512-+7ziBLidS4NaNCdt57SUDT+wYmmd5fmiQejUic/kb+YsYSCPyOOE9sebzMjNmQrsnNpDJqd4WHvV/8lfKfUDUg==", + "version": "1.64.1", + "resolved": "https://registry.npmjs.org/playwright/-/playwright-1.64.1.tgz", + "integrity": "sha512-HCrVhHr5QQuwYoswEUGTb7gGp522yflbv/ST8nF4sFWGuLjQCt17Q/EubpGGSNKYn1tsTCPZxqHhHCfVURu7UA==", "license": "Apache-2.0", "dependencies": { - "playwright-core": "1.63.0" + "playwright-core": "1.64.1" }, "bin": { "playwright": "cli.js" @@ -3470,9 +3470,9 @@ } }, "node_modules/playwright-core": { - "version": "1.63.0", - "resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.63.0.tgz", - "integrity": "sha512-rYCsBF/M5HjUch52bbtVONEFjv6Xu8sm8h72dNlR5bzIE1fvC/bxgspzkjSfU+MweEMmPM8KJebG6nnyxo5mCg==", + "version": "1.64.1", + "resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.64.1.tgz", + "integrity": "sha512-BC4s8y6SEVA6Q1rSxZTto8hI1KUI3xXlHGZgvGqP4IqPdI/a6FX9H29IDNz7vKo9l21b6LfYosScPL6M3xxyDQ==", "license": "Apache-2.0", "bin": { "playwright-core": "cli.js" diff --git a/package.json b/package.json index 9b88614..761e767 100644 --- a/package.json +++ b/package.json @@ -64,7 +64,7 @@ "commander": "^12.1.0", "jiti": "^2.4.2", "picocolors": "^1.1.1", - "playwright": "^1.49.1", + "playwright": "^1.64.1", "zod": "^3.24.1" }, "devDependencies": { From ea45d32b8d3cadd1e792edebaffa8890877e869a Mon Sep 17 00:00:00 2001 From: cj-vana Date: Thu, 5 Nov 2026 12:42:17 -0700 Subject: [PATCH 2/8] fix(explorer): skip controls in iframes a user can't reach Each frame's controls were judged inside the frame's own document, so a button in an iframe the page hid (visibility: hidden), made inert, or covered with an open modal looked reachable. A Playwright click on it waits until it times out (Chromium, Firefox and WebKit on 1.64.1 and 1.65; Chromium on 1.63), so each pick became a low driver-error finding. The document that holds an ' + + '', + ), + ).toEqual(['Shown frame']); + }); + + it('skips controls in an inert iframe and under an inert ancestor', async () => { + expect( + await namesOn( + '' + + '
' + + '', + ), + ).toEqual(['Awake']); + }); + + it('skips a frame nested in a hidden frame', async () => { + expect( + await namesOn( + `` + + '', + ), + ).toEqual(['Outside']); + }); + + it('keeps only the frames inside an open modal dialog', async () => { + expect( + await namesOn( + '' + + '', + (page) => + page.evaluate(() => (document.getElementById('d') as HTMLDialogElement).showModal()), + ), + ).toEqual(['In the dialog']); + }); +}); + describe('discovery under a modal dialog', () => { it('offers only the controls of an open aria-modal dialog', async () => { expect( From 14b2b13254f2bd79e3c0f8a71596cd1b5b78bf52 Mon Sep 17 00:00:00 2001 From: cj-vana Date: Thu, 5 Nov 2026 12:42:17 -0700 Subject: [PATCH 3/8] feat(fence): block requests by method, and report what the fence blocked Requested in #3. blockedPathPatterns matches the path only, so a write that shares its path with a read (DELETE /things/:id next to GET /things/:id) could not be fenced without breaking the read. guardrails.blockedRequests takes rules with an optional method and an optional path regex; when a rule has both, both must match. Methods are upper-cased when the config loads, and a rule with neither part is a config error. The fence checks rules before the path guards, with the same exemption for scripts, styles, images, fonts and media. A rule that refuses GET also keeps the crawl, client-side navigations and link clicks off its path, and closes WebSockets to it; a rule for another method leaves those alone. Every request the fence refuses for a path, a rule or another origin is now recorded as an info finding in a new `fence` category, keyed without the page URL so one route is one finding with a count. Page loads from another origin group by origin. blockMedia noise is not reported, and a payment provider's pages stay with the billing guard, so a live checkout is still one finding. --- src/config/schema.ts | 22 +++++++ src/core/types.ts | 1 + src/detectors/aggregate.ts | 5 +- src/explorer/actions.ts | 3 +- src/explorer/runner.ts | 26 +++++--- src/guardrails/fence.ts | 124 ++++++++++++++++++++++++++++++++----- test/config.test.ts | 35 +++++++++++ test/fence-billing.test.ts | 1 + test/fence-browser.test.ts | 85 +++++++++++++++++++++++++ 9 files changed, 277 insertions(+), 25 deletions(-) diff --git a/src/config/schema.ts b/src/config/schema.ts index 39b1279..bb3a636 100644 --- a/src/config/schema.ts +++ b/src/config/schema.ts @@ -191,12 +191,34 @@ const SecretsSchema = z }) .default({}); +/** One request the fence refuses. Both parts are optional, and when both are + * given both must match: `{ method: 'DELETE' }` refuses every delete, while + * `{ method: 'POST', path: '^/api/admin/' }` refuses only admin writes. */ +const BlockedRequestSchema = z + .object({ + /** HTTP method, in any case. */ + method: z + .string() + .regex(/^[A-Za-z]+$/, 'must be an HTTP method such as POST or DELETE') + .transform((method) => method.toUpperCase()) + .optional(), + /** Regex for the path with its query, matched as blockedPathPatterns are. */ + path: RegexSchema.optional(), + }) + .refine((rule) => rule.method !== undefined || rule.path !== undefined, { + message: 'needs a method, a path, or both', + }); + const GuardrailsSchema = z .object({ /** Origins the monkey may navigate to. Empty → just the target's origin. */ allowedOrigins: z.array(z.string()).default([]), /** Extra regex strings for paths to hard-block, even on allowed origins. */ blockedPathPatterns: z.array(RegexSchema).default([]), + /** Requests to refuse by HTTP method, path, or both. Unlike a blocked path, + * a rule with a method leaves the path's other methods alone, so a read + * of the same path still loads. */ + blockedRequests: z.array(BlockedRequestSchema).default([]), /** If non-empty, only crawl paths matching one of these regexes (scope a * sweep to e.g. ^/app/). */ includePaths: z.array(RegexSchema).default([]), diff --git a/src/core/types.ts b/src/core/types.ts index e06551b..a8e2527 100644 --- a/src/core/types.ts +++ b/src/core/types.ts @@ -186,6 +186,7 @@ export type SignalKind = | 'form-validation' | 'session-lost' | 'guardrail' + | 'fence' | 'custom' | 'driver'; diff --git a/src/detectors/aggregate.ts b/src/detectors/aggregate.ts index 21d17d9..cfd1d1a 100644 --- a/src/detectors/aggregate.ts +++ b/src/detectors/aggregate.ts @@ -67,18 +67,21 @@ const KIND_META: Record = { label: 'Session lost (logged out mid-run)', }, guardrail: { category: 'guardrail', defaultSeverity: 'info', label: 'Guardrail' }, + fence: { category: 'fence', defaultSeverity: 'info', label: 'Blocked by the fence' }, custom: { category: 'custom', defaultSeverity: 'medium', label: 'Custom rule' }, driver: { category: 'driver-error', defaultSeverity: 'medium', label: 'Driver error' }, }; /** Network failures are resource-scoped, not page-scoped: the same broken * asset/endpoint (its URL is in the detail) referenced from ten pages is one - * bug, not ten findings — so these kinds drop the page URL from their key. */ + * bug, not ten findings, so these kinds drop the page URL from their key. + * A fence block is the same: one finding per blocked route. */ const RESOURCE_KINDS = new Set([ 'http.4xx', 'http.5xx', 'requestfailed', 'broken-image', + 'fence', ]); /** The part of a signal's detail that identifies the bug. An axe violation's diff --git a/src/explorer/actions.ts b/src/explorer/actions.ts index 6150ef4..b2a195e 100644 --- a/src/explorer/actions.ts +++ b/src/explorer/actions.ts @@ -13,6 +13,7 @@ import { combineRegexes, compileRegexes } from '../core/regex'; import type { Rng } from '../core/rng'; import type { ActionKind, ElementDescriptor, FormDescriptor } from '../core/types'; import { classifyControl } from '../guardrails/destructive'; +import { navigationBlockedPatterns } from '../guardrails/fence'; import type { SignalRecorder } from '../detectors/recorder'; import { addCanary, type DetectorState } from '../detectors/page-checks'; import { locate } from './discover'; @@ -163,7 +164,7 @@ export function gatePlan(plan: Plan, cfg: ResolvedConfig, recorder: SignalRecord // A link into a path the user blocked. The fence stops a real navigation // there, but not a hash-router or pushState route. - const blockedPaths = combineRegexes(compileRegexes(cfg.guardrails.blockedPathPatterns)); + const blockedPaths = combineRegexes(compileRegexes(navigationBlockedPatterns(cfg.guardrails))); if (el?.href && blockedPaths && MUTATING.has(kind)) { let dest: URL | undefined; try { diff --git a/src/explorer/runner.ts b/src/explorer/runner.ts index b23d640..91149f4 100644 --- a/src/explorer/runner.ts +++ b/src/explorer/runner.ts @@ -34,9 +34,11 @@ import { DANGEROUS_PATH_RE } from '../guardrails/destructive'; import { redactString } from '../guardrails/secrets'; import { attachPageFence, + compileRequestRules, FenceLog, installContextFence, isAllowedOrigin, + navigationBlockedPatterns, } from '../guardrails/fence'; import { launchBrowser, createDeterministicContext } from '../session/browser'; import { performScriptedLogin, validateStorageState } from '../session/auth'; @@ -131,11 +133,20 @@ export async function runButtonmash(cfg: ResolvedConfig): Promise billingLive, @@ -212,7 +224,7 @@ export async function runButtonmash(cfg: ResolvedConfig): Promise ({ + method: rule.method?.toUpperCase(), + path: rule.path === undefined ? null : new RegExp(rule.path, 'i'), + })); +} + +/** Index of the first rule that refuses `method` to `u`, or -1. */ +export function matchRequestRule(rules: readonly RequestRule[], method: string, u: URL): number { + return rules.findIndex( + (rule) => + (rule.method === undefined || rule.method === method) && + (rule.path === null || isDangerousRoute(u, rule.path)), + ); +} + +/** Path patterns that keep the crawl and link clicks away from a page: every + * blockedPathPatterns entry, plus the path of each blockedRequests rule that + * refuses a GET, since loading a page there would only be refused. */ +export function navigationBlockedPatterns(guardrails: { + blockedPathPatterns: readonly string[]; + blockedRequests: readonly { method?: string; path?: string }[]; +}): string[] { + const refusesGet = guardrails.blockedRequests.flatMap((rule) => + rule.path !== undefined && (rule.method === undefined || rule.method.toUpperCase() === 'GET') + ? [rule.path] + : [], + ); + return [...guardrails.blockedPathPatterns, ...refusesGet]; +} + export interface FenceOptions { allowedOrigins: readonly string[]; /** Combined dangerous-path regex (or null). */ blockedPathRe: RegExp | null; + /** Compiled `guardrails.blockedRequests`. */ + blockedRequests?: readonly RequestRule[]; /** Block media/font requests to cut noise. Images are kept so the * broken-image detector stays meaningful. */ blockMedia: boolean; @@ -74,7 +120,7 @@ const ASSET_TYPES = new Set(['script', 'stylesheet', 'image', 'font', 'media']); const REDIRECT_STATUSES = new Set([301, 302, 303, 307, 308]); /** Why the fence refuses a request. */ -type Refusal = 'path' | 'origin' | 'live-payment' | 'latched-payment'; +type Refusal = 'request' | 'path' | 'origin' | 'live-payment' | 'latched-payment'; function safeOrigin(url: string): string { try { @@ -157,14 +203,24 @@ export async function installContextFence( }); const billingSeverity = opts.billingMode === 'refuse' ? 'critical' : 'medium'; + const requestRules = opts.blockedRequests ?? []; /** Checks 1-3, shared by a request and by a redirect it answers with. */ - const refusal = (u: URL, type: string, postData: () => string | null): Refusal | null => { - // 1. Dangerous paths (logout/delete/cancel) — block navigations, API calls, - // and beacons, but NOT static asset/module loads. Otherwise a bundler - // serving modules from paths like /src/features/billing/* (resource type - // 'script') would be blocked and the SPA would never mount. - if (!ASSET_TYPES.has(type) && isDangerousRoute(u, opts.blockedPathRe)) return 'path'; + const refusal = ( + u: URL, + type: string, + method: string, + postData: () => string | null, + ): Refusal | null => { + // 1. Configured requests, then dangerous paths (logout/delete/cancel). + // Both block navigations, API calls and beacons, but NOT static + // asset/module loads. Otherwise a bundler serving modules from paths + // like /src/features/billing/* (resource type 'script') would be + // blocked and the SPA would never mount. + if (!ASSET_TYPES.has(type)) { + if (matchRequestRule(requestRules, method, u) !== -1) return 'request'; + if (isDangerousRoute(u, opts.blockedPathRe)) return 'path'; + } // 2. Off-origin document navigations. if (type === 'document' && !allowed.has(u.origin)) return 'origin'; @@ -178,6 +234,30 @@ export async function installContextFence( return null; }; + /** Which guard refused `method` to `u`, for the finding. */ + const guardName = (method: string, u: URL): string => { + const rule = matchRequestRule(requestRules, method, u); + return rule === -1 ? 'blocked path' : `guardrails.blockedRequests[${rule}]`; + }; + + /** + * Record a refusal as an info `fence` finding, so a run shows what the fence + * stopped, including a block it should not have made. Findings group by + * route, and page loads from another origin by origin. Payment refusals, + * and a payment provider's pages while billing detection is on, are the + * billing guard's to report. + */ + const report = (refused: Refusal, method: string, u: URL): void => { + if (refused === 'origin') { + if (opts.billingMode !== 'off' && isPaymentHost(u.hostname)) return; + recorder.add('fence', `page load from ${u.origin}, outside the allowed origins`, { + severity: 'info', + }); + } else if (refused === 'request' || refused === 'path') { + recorder.add('fence', `${method} ${u.href} (${guardName(method, u)})`, { severity: 'info' }); + } + }; + /** * Playwright calls the route handler once per request and follows a 3xx * itself, so a page that redirected to /logout, or to another origin, went @@ -194,17 +274,20 @@ export async function installContextFence( // browser send it, as it did before this check existed. return route.continue().catch(() => {}); } - const location = REDIRECT_STATUSES.has(response.status()) - ? response.headers()['location'] - : undefined; + const status = response.status(); + const location = REDIRECT_STATUSES.has(status) ? response.headers()['location'] : undefined; const target = location ? parseUrl(location, from) : null; - const refused = target && refusal(target, 'document', () => null); + // 307 and 308 repeat the request's method; the other redirects load a page. + const method = status === 307 || status === 308 ? route.request().method() : 'GET'; + const refused = target && refusal(target, 'document', method, () => null); if (target && refused) { // No request is ever made for this hop, so nothing else records it. - if (refused !== 'path' && refused !== 'origin') { + if (refused === 'live-payment' || refused === 'latched-payment') { recorder.add('billing-live', `blocked a redirect to a payment page on ${target.hostname}`, { severity: billingSeverity, }); + } else { + report(refused, method, target); } opts.aborted?.record(route.request().url()); return route.abort('blockedbyclient').catch(() => {}); @@ -218,12 +301,17 @@ export async function installContextFence( opts.vetRedirects === true && context.browser()?.browserType().name() !== 'webkit'; // WebSocket handshakes never reach context.route. A socket to a dangerous - // path (ws://host/logout) is routed here and closed without contacting the + // path (ws://host/logout), or one a blockedRequests rule refuses as the GET + // its handshake is, is routed here and closed without contacting the // server; every other socket connects natively, as fetch and XHR do. await context.routeWebSocket( - (url) => isDangerousRoute(url, opts.blockedPathRe), + (url) => + matchRequestRule(requestRules, 'GET', url) !== -1 || + isDangerousRoute(url, opts.blockedPathRe), (ws) => { opts.aborted?.record(ws.url()); + const u = new URL(ws.url()); + recorder.add('fence', `WebSocket ${u.href} (${guardName('GET', u)})`, { severity: 'info' }); return ws.close({ code: 1008, reason: 'blocked by buttonmash' }); }, ); @@ -243,7 +331,8 @@ export async function installContextFence( return route.continue(); } - const refused = refusal(u, type, () => safePostData(req)); + const method = req.method(); + const refused = refusal(u, type, method, () => safePostData(req)); // Live evidence carried by the request itself is recorded, and the run // latched, by the signal listeners' `request` handler. Only a block that // rests on the latch alone is recorded here, so one event is one signal. @@ -254,7 +343,10 @@ export async function installContextFence( { severity: billingSeverity }, ); } - if (refused) return block(); + if (refused) { + report(refused, method, u); + return block(); + } // 4. Media/font noise (images kept so broken-image detection works). if (opts.blockMedia && (type === 'media' || type === 'font')) { diff --git a/test/config.test.ts b/test/config.test.ts index b58acaa..1caf282 100644 --- a/test/config.test.ts +++ b/test/config.test.ts @@ -177,6 +177,41 @@ describe('loadConfig', () => { ).rejects.toBeInstanceOf(ConfigError); }); + it('reads blockedRequests rules and rejects one that could not block what was meant', async () => { + const cfg = await loadConfig({ + ignoreConfigFile: true, + overrides: { + target: 'https://x.test', + guardrails: { blockedRequests: [{ method: 'delete' }, { method: 'POST', path: '^/api/' }] }, + }, + }); + expect(cfg.guardrails.blockedRequests).toEqual([ + { method: 'DELETE' }, + { method: 'POST', path: '^/api/' }, + ]); + + const cases: [unknown, string][] = [ + [{ method: 'DROP TABLE' }, 'guardrails.blockedRequests.0.method: must be an HTTP method'], + [ + { path: 'admin (' }, + 'guardrails.blockedRequests.0.path: must be a valid regular expression', + ], + [{}, 'guardrails.blockedRequests.0: needs a method, a path, or both'], + [{ methods: 'DELETE' }, 'guardrails.blockedRequests.0: needs a method, a path, or both'], + ]; + for (const [rule, message] of cases) { + const load = loadConfig({ + ignoreConfigFile: true, + overrides: { + target: 'https://x.test', + guardrails: { blockedRequests: [rule as { method?: string }] }, + }, + }); + await expect(load).rejects.toBeInstanceOf(ConfigError); + await expect(load).rejects.toThrow(message); + } + }); + it('rejects every invalid regex field instead of dropping the pattern', async () => { // A dropped blockedPathPatterns entry silently removes a safety block, and // an all-invalid includePaths widens the crawl to the whole site. diff --git a/test/fence-billing.test.ts b/test/fence-billing.test.ts index 4ff8cee..ac4a299 100644 --- a/test/fence-billing.test.ts +++ b/test/fence-billing.test.ts @@ -16,6 +16,7 @@ type Handler = (route: Route) => unknown; function fakeRequest(url: string, resourceType = 'script'): Request { return { url: () => url, + method: () => 'GET', resourceType: () => resourceType, postData: () => null, } as unknown as Request; diff --git a/test/fence-browser.test.ts b/test/fence-browser.test.ts index dfd50ef..7c40558 100644 --- a/test/fence-browser.test.ts +++ b/test/fence-browser.test.ts @@ -9,11 +9,13 @@ import { createServer, type Server } from 'node:http'; import { chromium, type Browser, type BrowserContext, type Page } from 'playwright'; import { combineRegexes } from '../src/core/regex'; +import { aggregateFindings } from '../src/detectors/aggregate'; import { SignalRecorder } from '../src/detectors/recorder'; import { DANGEROUS_PATH_RE } from '../src/guardrails/destructive'; import { FenceLog, attachPageFence, + compileRequestRules, installContextFence, type FenceOptions, } from '../src/guardrails/fence'; @@ -209,6 +211,89 @@ describe('dangerous routes outside the pathname', () => { }); }); +describe('blockedRequests', () => { + /** Send `method` to `path` from the page, as an app's fetch would. */ + const send = (method: string, path: string) => + page.evaluate( + ([m, p]) => + fetch(p as string, { method: m as string }).then( + () => 'sent', + () => 'refused', + ), + [method, path], + ); + const fenceNotes = () => recorder.signals.filter((s) => s.kind === 'fence').map((s) => s.detail); + + it('refuses a method on a path while a read of the same path goes through', async () => { + await setUp({ blockedRequests: compileRequestRules([{ method: 'delete' }]) }); + expect(await send('DELETE', '/api/workspace')).toBe('refused'); + expect(await send('GET', '/api/workspace')).toBe('sent'); + expect(requested()).toEqual([`GET 127.0.0.1:${port}/api/workspace`]); + expect(fenceNotes()).toEqual([`DELETE ${base}/api/workspace (guardrails.blockedRequests[0])`]); + }); + + it('needs both the method and the path when a rule has both', async () => { + await setUp({ + blockedRequests: compileRequestRules([{ method: 'POST', path: '^/api/admin/' }]), + }); + expect(await send('POST', '/api/admin/users')).toBe('refused'); + expect(await send('GET', '/api/admin/users')).toBe('sent'); + expect(await send('POST', '/api/notes')).toBe('sent'); + expect(requested()).toEqual([ + `GET 127.0.0.1:${port}/api/admin/users`, + `POST 127.0.0.1:${port}/api/notes`, + ]); + }); + + it('closes a socket whose handshake a path rule refuses', async () => { + await setUp({ blockedRequests: compileRequestRules([{ path: '^/live' }]) }); + const ended = await page.evaluate( + (target) => + new Promise((resolve) => { + const ws = new WebSocket(target); + ws.onclose = (event) => resolve(`closed ${event.code}`); + setTimeout(() => resolve('pending'), 2_000); + }), + `ws://127.0.0.1:${port}/live`, + ); + expect(ended).toBe('closed 1008'); + await settle(); + expect(requested()).toEqual([]); + expect(fenceNotes()).toEqual([ + `WebSocket ws://127.0.0.1:${port}/live (guardrails.blockedRequests[0])`, + ]); + }); + + it('reports blocked paths and page loads from other origins, not media blocking', async () => { + await setUp({ blockMedia: true }); + expect(await send('POST', '/logout')).toBe('refused'); + await page.evaluate(() => new FontFace('brand', 'url(/brand.woff2)').load().catch(() => {})); + await expect(page.goto(`${offsite}/elsewhere`)).rejects.toThrow(/ERR_BLOCKED_BY_CLIENT/); + await settle(); + expect(fenced.has(`${base}/brand.woff2`)).toBe(true); + expect(fenceNotes()).toEqual([ + `POST ${base}/logout (blocked path)`, + `page load from ${offsite}, outside the allowed origins`, + ]); + }); + + it('groups blocks of one route from different pages into one finding', async () => { + await setUp({ blockedRequests: compileRequestRules([{ method: 'DELETE' }]) }); + for (const from of ['/start', '/other']) { + await page.goto(`${base}${from}`); + recorder.setContext(0, page.url()); + await send('DELETE', '/api/things/48213'); + await send('DELETE', '/api/things/59724'); + } + const findings = aggregateFindings({ + signals: recorder.signals, + actions: [], + screenshots: new Map(), + }); + expect(findings.map((f) => [f.category, f.severity, f.count])).toEqual([['fence', 'info', 4]]); + }); +}); + describe('commits with an opaque origin', () => { it('does not report or undo the error page Chromium shows for a fenced navigation', async () => { await expect(page.goto(`${offsite}/elsewhere`)).rejects.toThrow(/ERR_BLOCKED_BY_CLIENT/); From 3a09aa219eb47a548d80a013ee6a45daddea3598 Mon Sep 17 00:00:00 2001 From: cj-vana Date: Thu, 5 Nov 2026 12:42:17 -0700 Subject: [PATCH 4/8] fix(cli): name the install command for buttonmash's own Playwright When a browser build was missing, run printed `npx playwright install`. In a project that pins a different Playwright, npm gives buttonmash a copy of its own, and that command downloads browsers for the project's copy, so the next run failed the same way. run and doctor now print `npx playwright@ install --with-deps ` for the Playwright buttonmash loads, and run takes the engine from the config file as well as the flag. doctor's browser check names that version when it passes. A launch that fails for another reason is reported as such instead of as a missing browser. doctor also applies guardrails.blockedRequests to its preflight fence, and the starter config from `buttonmash init` shows a commented rule. --- src/cli-program.ts | 20 ++++++++++++++++---- src/doctor.ts | 28 ++++++++++++++++++++++++---- src/session/browser.ts | 19 +++++++++++++++++++ test/cli.test.ts | 27 +++++++++++++++++++++++++-- 4 files changed, 84 insertions(+), 10 deletions(-) diff --git a/src/cli-program.ts b/src/cli-program.ts index d31f832..b211354 100644 --- a/src/cli-program.ts +++ b/src/cli-program.ts @@ -14,7 +14,12 @@ import { runDoctor } from './doctor'; import { runButtonmash } from './explorer/runner'; import { writeReports } from './report'; import { captureAuth } from './session/auth'; -import type { Engine } from './session/browser'; +import { + browserInstallCommand, + isMissingBrowser, + playwrightVersion, + type Engine, +} from './session/browser'; import { version } from './version'; interface RunOpts { @@ -183,6 +188,8 @@ async function doRun( opts: RunOpts, replayed: Partial = {}, ): Promise { + // The config file can choose the engine too, so the hint below reads it once loaded. + let engine: Engine = opts.browser ?? 'chromium'; try { if (opts.failOn && !(opts.failOn in SEVERITY_ORDER)) { throw new ConfigError(`--fail-on must be one of: ${Object.keys(SEVERITY_ORDER).join(', ')}`); @@ -194,6 +201,7 @@ async function doRun( // config file's lists rather than replacing them. append: { routes: opts.route, allowedOrigins: opts.allowOrigin }, }); + engine = cfg.browser; const { result, outDir } = await runButtonmash(cfg); await writeReports(result, outDir, cfg); printSummary(result, outDir, cfg.report.formats.includes('html')); @@ -202,9 +210,11 @@ async function doRun( const message = (err as Error).message ?? String(err); if (err instanceof ConfigError || err instanceof BaselineError) { logger.error(message); - } else if (/Executable doesn't exist|playwright install|browserType\.launch/i.test(message)) { - logger.error('The browser is not installed.'); - logger.info(`Run: npx playwright install --with-deps ${opts.browser ?? 'chromium'}`); + } else if (isMissingBrowser(message)) { + logger.error(`${engine} is not installed for Playwright ${playwrightVersion}.`); + logger.info(`Run: ${browserInstallCommand(engine)}`); + } else if (/browserType\.launch/.test(message)) { + logger.error(`${engine} could not start: ${message.split('\n')[0]}`); } else { logger.error(`buttonmash crashed: ${(err as Error).stack ?? message}`); } @@ -423,6 +433,8 @@ export default defineConfig({ // Refuse to run if LIVE Stripe/Braintree keys are detected. Use test mode! billing: { mode: 'refuse' }, // dryRun: true, // read-only: explore without submitting/mutating + // Refuse requests by HTTP method, path (regex), or both. Reads still load. + // blockedRequests: [{ method: 'DELETE' }, { method: 'POST', path: '^/api/admin/' }], // Controls whose names only look destructive (regex), e.g. a canvas "Reset zoom". // destructive: { safeNames: ['^reset zoom$'] }, }, diff --git a/src/doctor.ts b/src/doctor.ts index f621f58..1c21047 100644 --- a/src/doctor.ts +++ b/src/doctor.ts @@ -13,10 +13,21 @@ import { combineRegexes, compileRegexes } from './core/regex'; import { SignalRecorder } from './detectors/recorder'; import { inspectRequestForLiveMode, scanTextForLiveMode } from './guardrails/billing'; import { DANGEROUS_PATH_RE } from './guardrails/destructive'; -import { attachPageFence, installContextFence, isAllowedOrigin } from './guardrails/fence'; +import { + attachPageFence, + compileRequestRules, + installContextFence, + isAllowedOrigin, +} from './guardrails/fence'; import { redactString } from './guardrails/secrets'; import { performScriptedLogin, validateStorageState } from './session/auth'; -import { createDeterministicContext, launchBrowser } from './session/browser'; +import { + browserInstallCommand, + createDeterministicContext, + isMissingBrowser, + launchBrowser, + playwrightVersion, +} from './session/browser'; import { version } from './version'; export type DoctorStatus = 'pass' | 'warn' | 'fail'; @@ -111,9 +122,17 @@ export async function runDoctor(cfg: ResolvedConfig): Promise { browser = await launchBrowser(cfg.browser, true, { vetRedirects: cfg.guardrails.vetRedirects, }); - check(checks, 'browser', 'pass', `${cfg.browser} launched successfully`); + check(checks, 'browser', 'pass', `${cfg.browser} launched (Playwright ${playwrightVersion})`); } catch (err) { - check(checks, 'browser', 'fail', `${cfg.browser} could not launch: ${(err as Error).message}`); + const message = (err as Error).message; + check( + checks, + 'browser', + 'fail', + isMissingBrowser(message) + ? `${cfg.browser} is not installed for Playwright ${playwrightVersion}. Run: ${browserInstallCommand(cfg.browser)}` + : `${cfg.browser} could not launch: ${message}`, + ); return { ok: false, checks }; } @@ -144,6 +163,7 @@ export async function runDoctor(cfg: ResolvedConfig): Promise { const fenceOptions = { allowedOrigins: cfg.guardrails.allowedOrigins, blockedPathRe: combineRegexes(pathRegexes), + blockedRequests: compileRequestRules(cfg.guardrails.blockedRequests), blockMedia: cfg.guardrails.blockMedia, billingMode: cfg.guardrails.billing.mode, isBillingLatched: () => billingLatched, diff --git a/src/session/browser.ts b/src/session/browser.ts index c58e5d2..ca8bfa0 100644 --- a/src/session/browser.ts +++ b/src/session/browser.ts @@ -9,6 +9,8 @@ * real apps (polling, spinners, timeouts); the seed already reproduces the * monkey's own choices, which is what matters for replaying a bug. */ +import { createRequire } from 'node:module'; + import { chromium, firefox, webkit } from 'playwright'; import type { Browser, BrowserContext, Page } from 'playwright'; @@ -18,6 +20,23 @@ import type { ResolvedConfig } from '../config/load'; const ENGINES = { chromium, firefox, webkit } as const; export type Engine = keyof typeof ENGINES; +/** The Playwright this copy of buttonmash loads. A project that pins its own + * Playwright can hold two copies, and a bare `npx playwright install` then + * downloads browsers for the project's copy, not this one. */ +export const playwrightVersion: string = ( + createRequire(import.meta.url)('playwright/package.json') as { version: string } +).version; + +/** Installs the browser builds that {@link playwrightVersion} launches. */ +export function browserInstallCommand(engine: Engine): string { + return `npx playwright@${playwrightVersion} install --with-deps ${engine}`; +} + +/** True when a launch failed because the engine's browser build is missing. */ +export function isMissingBrowser(message: string): boolean { + return /Executable doesn't exist|playwright install/i.test(message); +} + export async function launchBrowser( engine: Engine, headless: boolean, diff --git a/test/cli.test.ts b/test/cli.test.ts index 84b7bb8..cdb84df 100644 --- a/test/cli.test.ts +++ b/test/cli.test.ts @@ -27,11 +27,11 @@ afterAll(() => { for (const directory of temporaryDirectories) rmSync(directory, { recursive: true, force: true }); }); -function run(args: string[], cwd = root) { +function run(args: string[], cwd = root, env: NodeJS.ProcessEnv = {}) { return spawnSync(process.execPath, [cli, ...args], { cwd, encoding: 'utf8', - env: { ...process.env, NO_COLOR: '1' }, + env: { ...process.env, NO_COLOR: '1', ...env }, }); } @@ -92,6 +92,29 @@ describe('CLI contract', () => { } }); + it('names the install command for its own Playwright when the browser is missing', () => { + const directory = mkdtempSync(join(tmpdir(), 'buttonmash-cli-')); + temporaryDirectories.push(directory); + // An empty browsers directory: every engine's build is missing. + const env = { PLAYWRIGHT_BROWSERS_PATH: directory }; + const { version: playwright } = JSON.parse( + readFileSync(join(root, 'node_modules', 'playwright', 'package.json'), 'utf8'), + ) as { version: string }; + const command = `npx playwright@${playwright} install --with-deps firefox`; + + const runResult = run(['run', 'http://127.0.0.1:9', '--browser', 'firefox'], directory, env); + expect(runResult.status).toBe(2); + expect(runResult.stderr).toContain(`firefox is not installed for Playwright ${playwright}`); + expect(runResult.stdout).toContain(command); + + const doctor = run(['doctor', 'http://127.0.0.1:9', '--browser', 'firefox'], directory, env); + expect(doctor.status).toBe(2); + expect(doctor.stdout).toContain( + `browser: firefox is not installed for Playwright ${playwright}`, + ); + expect(doctor.stdout).toContain(command); + }); + it('rejects an unknown auth --browser before creating or launching anything', () => { const directory = mkdtempSync(join(tmpdir(), 'buttonmash-cli-')); temporaryDirectories.push(directory); From 65d107a1ad0be899f5f513da087c683d0395775b Mon Sep 17 00:00:00 2001 From: cj-vana Date: Thu, 5 Nov 2026 12:42:17 -0700 Subject: [PATCH 5/8] docs: cover blockedRequests, fence findings and the Playwright range Documents the Playwright floor and the install command doctor prints, guardrails.blockedRequests and the fence category, and that discovery skips iframes a user can't reach. Pins the action example at v0.4.0. --- README.md | 40 ++++++++++++++++++++++++++++++++++------ 1 file changed, 34 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index 56ae20f..b0e96e1 100644 --- a/README.md +++ b/README.md @@ -83,7 +83,16 @@ npm install --save-dev buttonmash npx playwright install --with-deps chromium # one-time browser install ``` -Requires Node 20+. +Requires Node 20+. Playwright 1.65 no longer tests on Node 20, so prefer 22 or +newer. + +buttonmash runs on Playwright 1.64.1 or newer, and uses your project's copy +when that version fits. If your project pins an older Playwright, npm gives +buttonmash a copy of its own, and a bare `npx playwright install` then +downloads browsers for your copy instead. `buttonmash doctor` reports which +Playwright buttonmash loads, and when its browser is missing, `doctor` and +`run` print the command that installs it, such as +`npx playwright@1.64.1 install --with-deps chromium`. ## Quickstart @@ -140,14 +149,14 @@ jobs: steps: - uses: actions/checkout@v5 # start your app under test here (e.g. npm ci && npm run start &) and wait for it… - - uses: cj-vana/buttonmash@v0.3.1 + - uses: cj-vana/buttonmash@v0.4.0 with: target: http://localhost:3000 args: --seed ci --max-actions 800 ``` -The action runs the buttonmash release that matches its own tag (`@v0.3.1` -installs 0.3.1) and reads a committed `buttonmash.config.*` from the +The action runs the buttonmash release that matches its own tag (`@v0.4.0` +installs 0.4.0) and reads a committed `buttonmash.config.*` from the workspace. Its inputs: | Input | Default | What it does | @@ -259,7 +268,8 @@ Salesforce LWC, Ionic, Shoelace/Lit/Material Web) and **same-origin iframes** (embedded editors, wizards), so component-based apps aren't invisible to it. It also skips what a user couldn't reach: the contents of a closed `
`, inert subtrees, and, while a modal dialog is open, everything outside the top -modal. +modal. The same holds for an iframe: nothing inside it is offered when the +iframe is hidden, inert, or outside an open modal. It's built to survive messy real apps on long CI sweeps: it **recovers from renderer crashes** (recreates the page and continues, skipping the page that @@ -338,6 +348,10 @@ export default defineConfig({ billing: { mode: 'refuse' }, // refuse | warn | off // dryRun: true, // read-only: explore without submitting // vetRedirects: true, // check a page's first redirect before following it + // blockedRequests: [ // refuse by HTTP method, path (regex), or both + // { method: 'DELETE' }, + // { method: 'POST', path: '^/api/admin/' }, + // ], destructive: { enabled: true, extraVerbs: ['archivar'], @@ -405,7 +419,8 @@ loops, React dev warnings, HMR…) and **downgrades third-party `console.error`* errors stay high (`detectors.thirdPartyConsole: true` to opt in). State dedup is **structural** by default, so live counters/clocks don't explode the state space on dynamic apps. Requests buttonmash's own fence blocks (a web font under -`blockMedia`, a logout ping) are never reported as app errors, in any engine. A +`blockMedia`, a logout ping) are never reported as app errors, in any engine; +the logout ping shows up as an `info` fence finding instead (see Safety). A control another layer covers (a canvas, a stuck overlay) costs one timeout per page, not one per pick. And if CI cancels or times out mid-run (SIGINT or SIGTERM), a **partial report is still written** with exit code `2`, so you never @@ -425,6 +440,19 @@ buttonmash is built to break things without breaking *you*: then the fence checks each page's first redirect before it is followed (Chromium and Firefox), at the cost of fetching every page itself, which buffers it and drops its `Sec-Fetch-*` headers. +- **Fence writes by method.** `guardrails.blockedRequests` refuses requests by + HTTP method, path, or both, so `{ method: 'DELETE' }` stops every delete + while reads of the same path still load. `path` is a regex matched like a + `blockedPathPatterns` entry, and both parts must match when a rule has both. + A rule that refuses a GET also keeps the crawl and link clicks off its path. + Like path guards, rules never block scripts, styles, images, fonts or media. +- **Show what the fence blocked.** Each request the fence refuses, whether by a + path guard, a `blockedRequests` rule or another origin, becomes an `info` + finding in the `fence` category: one per route (one per origin for page + loads), with a count. At the default `failOn` it doesn't fail the run, but it + shows when the fence stopped something it shouldn't have. Fonts and media + dropped by `blockMedia` aren't reported, and a payment provider's pages are + left to the billing guard. - **Skip destructive controls.** Buttons/links matching a multilingual verb list (delete, pay, logout, cancel subscription, …), or pointing at dangerous paths (`/logout`, `/account/delete`, `/billing/cancel`), are detected and From f36bfae77e545016a25701b9170dc6805d185e24 Mon Sep 17 00:00:00 2001 From: cj-vana Date: Thu, 5 Nov 2026 12:48:36 -0700 Subject: [PATCH 6/8] release: prepare buttonmash 0.4.0 --- package-lock.json | 4 ++-- package.json | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/package-lock.json b/package-lock.json index d6e3853..6e5d20e 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "buttonmash", - "version": "0.3.1", + "version": "0.4.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "buttonmash", - "version": "0.3.1", + "version": "0.4.0", "license": "MIT", "dependencies": { "axe-core": "^4.10.2", diff --git a/package.json b/package.json index 761e767..8de5ded 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "buttonmash", - "version": "0.3.1", + "version": "0.4.0", "description": "A CI chaos monkey for web apps. It presses every button, mashes random keystrokes, tries to break your UI, and reports what it found. Safe by default.", "keywords": [ "chaos-monkey", From cc28e6199af7a45025a5bbe88ea4587b8361992e Mon Sep 17 00:00:00 2001 From: cj-vana Date: Thu, 5 Nov 2026 12:59:48 -0700 Subject: [PATCH 7/8] fix(fence): compare blockedRequests methods in upper case fetch() upper-cases only the standard methods (DELETE, GET, HEAD, OPTIONS, POST, PUT). Any other method goes out as the page wrote it, so `fetch(url, { method: 'patch' })` sends "patch", which a `{ method: 'PATCH' }` rule did not match, while many servers still route it as PATCH. The fence now upper-cases the request's method before comparing it with the rules. Found by an automated security review of the pushed branch. --- src/guardrails/fence.ts | 7 +++++-- test/fence-browser.test.ts | 9 +++++++++ 2 files changed, 14 insertions(+), 2 deletions(-) diff --git a/src/guardrails/fence.ts b/src/guardrails/fence.ts index 94c6684..a89c652 100644 --- a/src/guardrails/fence.ts +++ b/src/guardrails/fence.ts @@ -63,11 +63,14 @@ export function compileRequestRules( })); } -/** Index of the first rule that refuses `method` to `u`, or -1. */ +/** Index of the first rule that refuses `method` to `u`, or -1. The method is + * compared in upper case: fetch() upper-cases only the standard methods, so a + * page can send "patch", which servers commonly route as PATCH. */ export function matchRequestRule(rules: readonly RequestRule[], method: string, u: URL): number { + const sent = method.toUpperCase(); return rules.findIndex( (rule) => - (rule.method === undefined || rule.method === method) && + (rule.method === undefined || rule.method === sent) && (rule.path === null || isDangerousRoute(u, rule.path)), ); } diff --git a/test/fence-browser.test.ts b/test/fence-browser.test.ts index 7c40558..8f97bd2 100644 --- a/test/fence-browser.test.ts +++ b/test/fence-browser.test.ts @@ -232,6 +232,15 @@ describe('blockedRequests', () => { expect(fenceNotes()).toEqual([`DELETE ${base}/api/workspace (guardrails.blockedRequests[0])`]); }); + it('refuses a method the page sends in lower case', async () => { + // fetch() upper-cases only the standard methods, so this goes out as + // "patch", which servers commonly route as PATCH. + await setUp({ blockedRequests: compileRequestRules([{ method: 'PATCH' }]) }); + expect(await send('patch', '/api/workspace')).toBe('refused'); + expect(requested()).toEqual([]); + expect(fenceNotes()).toEqual([`patch ${base}/api/workspace (guardrails.blockedRequests[0])`]); + }); + it('needs both the method and the path when a rule has both', async () => { await setUp({ blockedRequests: compileRequestRules([{ method: 'POST', path: '^/api/admin/' }]), From 3a9739cde682964e41252ae6c5801786cc614163 Mon Sep 17 00:00:00 2001 From: cj-vana Date: Thu, 5 Nov 2026 13:04:27 -0700 Subject: [PATCH 8/8] fix(signals): ignore cancelled requests in Firefox and WebKit too A request cancelled before it finished is not a failed request. The requestfailed handler already ignored Chromium's net::ERR_ABORTED, but Firefox reports the same event as NS_BINDING_ABORTED and WebKit as "cancelled", so those engines turned it into a medium network finding. A hands-on Firefox run found one after a double-clicked link restarted its navigation. The new case in fence-noise aborts an in-flight fetch with an AbortController; before this change it failed on Firefox and WebKit and passed on Chromium. --- README.md | 4 +++- src/detectors/signals.ts | 11 ++++++++- test/fence-noise.test.ts | 48 +++++++++++++++++++++++++++++++++++++++- test/helpers/server.ts | 8 +++++++ 4 files changed, 68 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index b0e96e1..5505d79 100644 --- a/README.md +++ b/README.md @@ -420,7 +420,9 @@ errors stay high (`detectors.thirdPartyConsole: true` to opt in). State dedup is **structural** by default, so live counters/clocks don't explode the state space on dynamic apps. Requests buttonmash's own fence blocks (a web font under `blockMedia`, a logout ping) are never reported as app errors, in any engine; -the logout ping shows up as an `info` fence finding instead (see Safety). A +the logout ping shows up as an `info` fence finding instead (see Safety). +Neither is a request cancelled before it finished, such as a navigation a +double-click restarted or a fetch the page aborted. A control another layer covers (a canvas, a stuck overlay) costs one timeout per page, not one per pick. And if CI cancels or times out mid-run (SIGINT or SIGTERM), a **partial report is still written** with exit code `2`, so you never diff --git a/src/detectors/signals.ts b/src/detectors/signals.ts index 3334d34..11ebffd 100644 --- a/src/detectors/signals.ts +++ b/src/detectors/signals.ts @@ -119,7 +119,16 @@ export function attachSignalListeners(deps: SignalDeps): void { const errorText = req.failure()?.errorText ?? 'unknown'; // Ignore the navigations/resources WE aborted via the fence. if (fenced.has(req.url())) return; - if (/ERR_ABORTED|BLOCKED_BY_CLIENT|blockedbyclient/i.test(errorText)) return; + // A request cancelled before it finished (a restarted navigation, an + // aborted fetch) did not fail: Chromium net::ERR_ABORTED, Firefox + // NS_BINDING_ABORTED, WebKit "cancelled". + if ( + /ERR_ABORTED|NS_BINDING_ABORTED|^cancelled$|BLOCKED_BY_CLIENT|blockedbyclient/i.test( + errorText, + ) + ) { + return; + } if (!cfg.detectors.httpErrors) return; const line = `${req.method()} ${req.url()} — ${errorText}`; if (ignored(line)) return; diff --git a/test/fence-noise.test.ts b/test/fence-noise.test.ts index 34ccb97..c597600 100644 --- a/test/fence-noise.test.ts +++ b/test/fence-noise.test.ts @@ -14,8 +14,14 @@ import { mkdtempSync, rmSync } from 'node:fs'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; -import { buttonmash } from '../src/index'; +import { chromium, firefox, webkit } from 'playwright'; + +import { loadConfig } from '../src/config/load'; import type { RunResult } from '../src/core/types'; +import { SignalRecorder } from '../src/detectors/recorder'; +import { attachSignalListeners } from '../src/detectors/signals'; +import { FenceLog } from '../src/guardrails/fence'; +import { buttonmash } from '../src/index'; import type { Engine } from '../src/session/browser'; import { startServer, type TestServer } from './helpers/server'; @@ -68,3 +74,43 @@ describe(`requests the fence aborts (${browser})`, () => { expect(result.run.exitCode).toBe(0); }); }); + +describe(`requests cancelled before they finish (${browser})`, () => { + // A double-clicked link restarts its navigation and a page can abort its own + // fetch. Chromium calls that net::ERR_ABORTED, Firefox NS_BINDING_ABORTED, + // WebKit "cancelled"; none of them is a failed request. + it('are not reported as failed network requests', async () => { + const cfg = await loadConfig({ + ignoreConfigFile: true, + overrides: { target: server.url, browser, logLevel: 'silent' }, + }); + const instance = await { chromium, firefox, webkit }[browser].launch(); + try { + const page = await instance.newPage(); + const recorder = new SignalRecorder(); + const reported: string[] = []; + page.on('requestfailed', (req) => reported.push(req.failure()?.errorText ?? '')); + attachSignalListeners({ + page, + recorder, + cfg, + ignore: [], + customConsole: [], + onBillingLive: () => {}, + fenced: new FenceLog(), + }); + await page.goto(`${server.url}/fonts`); + await page.evaluate(async () => { + const controller = new AbortController(); + const pending = fetch('/slow', { signal: controller.signal }).catch(() => {}); + setTimeout(() => controller.abort(), 200); + await pending; + }); + await page.waitForTimeout(300); + expect(reported.length).toBeGreaterThan(0); + expect(recorder.signals.filter((s) => s.kind === 'requestfailed')).toEqual([]); + } finally { + await instance.close(); + } + }); +}); diff --git a/test/helpers/server.ts b/test/helpers/server.ts index 2e84db1..78a292c 100644 --- a/test/helpers/server.ts +++ b/test/helpers/server.ts @@ -98,6 +98,14 @@ export async function startServer(): Promise { ); return; } + // Answers late, so a page can cancel the request while it is in flight. + if (url === '/slow') { + setTimeout(() => { + res.writeHead(200, { 'content-type': 'text/plain' }); + res.end('late'); + }, 1_500); + return; + } res.writeHead(404, { 'content-type': 'text/plain' }); res.end('not found'); });