// App-layer security regression suite against examples/hello (no browser). Run by // scripts/ci/e2e-dev.sh, e2e-prod.sh and e2e-adapters.sh against a running server: // node scripts/security-e2e.mjs dev // node scripts/security-e2e.mjs prod // node scripts/security-e2e.mjs headers [label] // node scripts/security-e2e.mjs headers-worker // dev and prod: RPC CSRF and limits, server function hardening, cross-site writes to actions, API // and file routes, multipart limits, sessions (cross-site writes rejected, forged cookies), // default security headers, config redirects (open redirects, CRLF, the internal // x-nowaki-route-path header), CSWSH, forged live state and the live-event POST gate. // Dev only: arbitrary file read (@fs, ssr-module, .env, credential files, virtual-module `..`) // and the HMR socket. Prod only: generic 500s, ISR isolation, CDN cache headers and query-flood // collapsing, /_nowaki/* path traversal. // headers / headers-worker: the internal-header sweep and the raw-HTML nonce check against any // server or the Cloudflare Worker's fetch handler (which also runs the session and revalidate // checks). import http from "node:http"; const [mode, base, appRoot] = process.argv.slice(2); let fails = 0; const check = (label, cond) => { console.log(`${cond ? "ok " : "FAIL"} ${label}`); if (!cond) fails++; }; const sleep = (ms) => new Promise((r) => setTimeout(r, ms)); const statusOf = async (url, opts) => (await fetch(url, opts)).status; // GET that sends the path verbatim (fetch normalizes `..`, so use raw http). function rawGet(b, path) { const u = new URL(b); return new Promise((resolve) => { const req = http.request( { host: u.hostname, port: u.port, path, method: "GET" }, (res) => { res.resume(); resolve(res.statusCode); }, ); req.on("error", () => resolve(0)); req.end(); }); } // Attempts a WebSocket upgrade. 101=upgraded, 403 etc.=rejected. Origin can be set freely. function wsUpgrade(b, path, origin) { const u = new URL(b); return new Promise((resolve) => { const req = http.request({ host: u.hostname, port: u.port, path, method: "GET", headers: { Connection: "Upgrade", Upgrade: "websocket", "Sec-WebSocket-Key": "AAAAAAAAAAAAAAAAAAAAAA==", "Sec-WebSocket-Version": "13", Origin: origin, }, }); req.on("upgrade", (_res, socket) => { socket.destroy(); resolve(101); }); req.on("response", (res) => { res.resume(); resolve(res.statusCode); }); req.on("error", () => resolve(0)); req.end(); }); } // Client-sent x-forwarded-host is dropped by the Rust front (no NOWAKI_TRUST_PROXY), so it can // neither spoof the RPC same-origin check nor break a genuine same-origin call. async function forwardedHostIgnored(b) { const call = (h) => fetch(`${b}/__nowaki/fn`, { method: "POST", headers: { "content-type": "application/json", "x-nowaki-rpc": "1", ...h }, body: JSON.stringify({ id: "6c90d7dc921a9a3f", args: [] }), }).then((r) => r.status); check("RPC forged x-forwarded-host can't spoof the origin check (403)", (await call({ origin: "http://evil.test", "x-forwarded-host": "evil.test" })) === 403); check("RPC same-origin call unaffected by a client x-forwarded-host (200)", (await call({ origin: b, "x-forwarded-host": "evil.test" })) === 200); } // Server functions: Standard Schema validation (addTodo), body/argument limits, and no internal // error details in production (brokenTodo throws "db password is hunter2"). async function serverFnHardening(b, m) { const rpc = async (body) => { const r = await fetch(`${b}/__nowaki/fn`, { method: "POST", headers: { "content-type": "application/json", "x-nowaki-rpc": "1" }, body: typeof body === "string" ? body : JSON.stringify(body), }); let data = null; try { data = await r.json(); } catch {} return { status: r.status, data }; }; const bad = await rpc({ id: "675f80133a1699f8", args: [""] }); check("serverFn rejects invalid input (400 + issues)", bad.status === 400 && bad.data?.error === "Invalid input" && bad.data?.data?.issues?.length === 1); const good = await rpc({ id: "675f80133a1699f8", args: [" schema-ok "] }); check("serverFn passes the validated value", good.status === 200 && good.data?.result?.includes("schema-ok")); const broken = await rpc({ id: "96224074eee5e982", args: [] }); if (m === "prod") { check("prod: unexpected server function error is generic (500, no message)", broken.status === 500 && broken.data?.error === "Internal Server Error"); } else { check("dev: unexpected server function error keeps its message", broken.status === 500 && /hunter2/.test(broken.data?.error ?? "")); } for (const id of ["__proto__", "constructor", "toString"]) { check(`server function id ${id} is not in the allowlist (404)`, (await rpc({ id, args: [] })).status === 404); } check("server function argument count limit (400)", (await rpc({ id: "6c90d7dc921a9a3f", args: Array(17).fill(0) })).status === 400); check("server function body size limit (413)", (await rpc(JSON.stringify({ id: "6c90d7dc921a9a3f", args: ["x".repeat(1100 * 1024)] }))).status === 413); } async function multipartFormGuards(b) { const { FORM_BODY_LIMIT } = await import("../packages/nowaki-runtime/server/multipart.mjs"); const boundary = "nowakie2e"; const body = `--${boundary}\r\nContent-Disposition: form-data; name="note"\r\n\r\nhi\r\n--${boundary}\r\nContent-Disposition: form-data; name="file"; filename="t.txt"\r\nContent-Type: text/plain\r\n\r\nok\r\n--${boundary}--\r\n`; const ok = await fetch(`${b}/api/upload`, { method: "POST", headers: { "content-type": `multipart/form-data; boundary=${boundary}`, origin: b }, body, }); const json = await ok.json().catch(() => ({})); check("multipart upload round trip (file + field)", ok.status === 200 && json.hasFile && json.name === "t.txt" && json.field === "hi"); // fetch refuses a Content-Length / body length mismatch (undici); use raw http like the limits in // context.mjs expect (oversized Content-Length rejected before the body is read). const huge = await raw(b, "/api/upload", { method: "POST", headers: { "content-type": `multipart/form-data; boundary=${boundary}`, "content-length": String(FORM_BODY_LIMIT + 1), origin: b, }, body: "", timeoutMs: 5000, }); check("multipart Content-Length over limit (413)", huge.status === 413); const bad = await fetch(`${b}/api/upload`, { method: "POST", headers: { "content-type": "multipart/form-data; boundary=missing", origin: b }, body: "not multipart", }); check("multipart malformed body (400)", bad.status === 400); } // Page actions and API / file routes reject cross-site non-GET requests by default. async function crossSiteWritesRejected(b) { const send = (path, h) => fetch(`${b}${path}`, { method: "POST", redirect: "manual", headers: { "content-type": "application/x-www-form-urlencoded", ...h }, body: "text=csrf-check", }).then((r) => r.status); check("action: cross-site Origin rejected (403)", (await send("/todos", { origin: "http://evil.test" })) === 403); check("action: Origin null rejected (403)", (await send("/todos", { origin: "null" })) === 403); check("action: Sec-Fetch-Site cross-site rejected (403)", (await send("/todos", { "sec-fetch-site": "cross-site" })) === 403); check("action: same-origin POST allowed", (await send("/todos", { origin: b })) === 302); check("action: POST without Origin (non-browser) allowed", (await send("/todos", {})) === 302); // API routes (the default since 0.19.3): the same rule and the same 403 as actions; // `csrf = false` opts out. const api = (path, h, method = "POST") => fetch(`${b}${path}`, { method, redirect: "manual", headers: method === "GET" ? h : { "content-type": "application/json", ...h }, body: method === "GET" ? undefined : "{}", }); const action = await fetch(`${b}/todos`, { method: "POST", redirect: "manual", headers: { "content-type": "application/x-www-form-urlencoded", origin: "http://evil.test" }, body: "text=csrf-check", }); const rejected = await api("/api/echo", { origin: "http://evil.test" }); const actionBody = await action.text(); const rejectedBody = await rejected.text(); check("API: cross-site Origin rejected (403)", rejected.status === 403); check("API: the rejection matches the action's (status, content-type, body)", rejected.status === action.status && rejectedBody === actionBody && rejected.headers.get("content-type") === action.headers.get("content-type")); check("API: Origin null rejected (403)", (await api("/api/echo", { origin: "null" })).status === 403); check("API: Sec-Fetch-Site cross-site without Origin rejected (403)", (await api("/api/echo", { "sec-fetch-site": "cross-site" })).status === 403); check("API: DELETE cross-site rejected (403, before the 405)", (await api("/api/echo", { origin: "http://evil.test" }, "DELETE")).status === 403); check("API: default handler (any method) rejects cross-site POST (403)", (await api("/api/hello", { origin: "http://evil.test" })).status === 403); check("API: same-origin POST allowed", (await api("/api/echo", { origin: b })).status === 200); check("API: Sec-Fetch-Site same-origin without Origin allowed", (await api("/api/echo", { "sec-fetch-site": "same-origin" })).status === 200); check("API: POST without Origin (non-browser) allowed", (await api("/api/echo", {})).status === 200); check("API: cross-site GET unaffected", (await api("/api/echo", { origin: "http://evil.test" }, "GET")).status === 200); check("API with `csrf = false`: cross-site POST allowed", (await api("/api/webhook", { origin: "http://evil.test" })).status === 200); check("file route: cross-site POST rejected (403)", (await api("/feed.xml", { origin: "http://evil.test" })).status === 403); } // Sessions (routes/api/session.ts): a cross-site POST carrying a valid session cookie sees an empty, // read-only session and can't write; a forged or tampered cookie reads as empty. async function sessionGuards(b) { const post = (body, h = {}) => fetch(`${b}/api/session`, { method: "POST", headers: { "content-type": "application/x-www-form-urlencoded", origin: b, ...h }, body, }); const login = await post("op=login&user=alice"); const setCookie = login.headers.get("set-cookie") ?? ""; const cookie = setCookie.split(";")[0]; check("session: same-site login sets an HttpOnly SameSite=Lax cookie", /^hello_session=v1\./.test(cookie) && /HttpOnly/.test(setCookie) && /SameSite=Lax/.test(setCookie)); const me = await (await fetch(`${b}/api/session`, { headers: { cookie } })).json(); check("session: the cookie reads back", me.user === "alice"); const evil = await post("op=login&user=mallory", { cookie, origin: "http://evil.test" }); check("session: cross-site POST to the API is rejected (403, no cookie)", evil.status === 403 && !evil.headers.get("set-cookie")); const still = await (await fetch(`${b}/api/session`, { headers: { cookie } })).json(); check("session: the victim's session is unchanged", still.user === "alice"); const value = cookie.slice(cookie.indexOf("=") + 1); const flipped = value.slice(0, 12) + (value[12] === "A" ? "B" : "A") + value.slice(13); const tampered = await (await fetch(`${b}/api/session`, { headers: { cookie: `hello_session=${flipped}` } })).json(); check("session: a tampered cookie reads as empty", tampered.user === null); const forged = await (await fetch(`${b}/api/session`, { headers: { cookie: "hello_session=v1.eyJkIjp7InVzZXIiOiJhZG1pbiJ9fQ" } })).json(); check("session: a forged cookie reads as empty", forged.user === null); } // POST /__nowaki/revalidate: 404 while NOWAKI_REVALIDATE_SECRET is unset (or blank), then only the // exact bearer secret, JSON only, no-store. `setSecret(value | undefined)` sets it for the server. async function revalidateGate(b, setSecret) { const post = (auth, ct = "application/json") => fetch(`${b}/__nowaki/revalidate`, { method: "POST", headers: { "content-type": ct, ...(auth ? { authorization: `Bearer ${auth}` } : {}) }, body: JSON.stringify({ paths: ["/isr"] }), }); const secret = "e2e-revalidate-secret-0123456789abcdef"; setSecret(undefined); check("revalidate: 404 while NOWAKI_REVALIDATE_SECRET is unset", (await post(secret)).status === 404); setSecret(" "); check("revalidate: 404 with a blank secret", (await post("")).status === 404); setSecret(secret); check("revalidate: wrong secret 401", (await post("x" + secret.slice(1))).status === 401); check("revalidate: a prefix of the secret 401", (await post(secret.slice(0, -1))).status === 401); check("revalidate: no Authorization 401", (await post(null)).status === 401); check("revalidate: text/plain 415", (await post(secret, "text/plain")).status === 415); const ok = await post(secret); check("revalidate: the secret purges (200, no-store)", ok.status === 200 && /no-store/.test(ok.headers.get("cache-control") || "")); setSecret(undefined); } // Default security headers on each of `paths`: pages and 404s in both modes, plus ISR hits and a // static asset in prod. async function securityHeadersPresent(b, paths) { for (const p of paths) { const h = (await fetch(`${b}${p}`)).headers; check(`security headers on ${p}`, h.get("x-content-type-options") === "nosniff" && h.get("x-frame-options") === "SAMEORIGIN" && h.get("referrer-policy") === "strict-origin-when-cross-origin" && h.get("cross-origin-opener-policy") === "same-origin" && /frame-ancestors 'self'/.test(h.get("content-security-policy") || "")); } } // A forged live join gets no patch (rejected by signature verification). The global WebSocket // connects without Origin (ws_origin_ok allows it), so this tests the signature alone. async function liveForgeryRejected(b) { const html = await (await fetch(`${b}/live`)).text(); const tag = html.match(/]*>/)?.[0]; if (!tag) return false; const attr = (n) => tag.match(new RegExp(`${n}="([^"]*)"`))?.[1]; const nid = attr("nid"); const name = attr("name"); const wsUrl = b.replace(/^http/, "ws") + "/__nowaki/live"; return await new Promise((resolve) => { const ws = new WebSocket(wsUrl); let gotPatch = false; ws.addEventListener("open", () => { ws.send(JSON.stringify({ type: "join", islands: [{ nid, name, state: { count: 9999 }, sig: "FORGED" }], })); setTimeout(() => ws.send(JSON.stringify({ type: "event", nid, handler: "inc" })), 120); }); ws.addEventListener("message", (e) => { try { if (JSON.parse(e.data).type === "patch") gotPatch = true; } catch {} }); setTimeout(() => { ws.close(); resolve(!gotPatch); }, 900); }); } // POST /__nowaki/live-event (the WS fallback) keeps the RPC-style CSRF gate, a body cap, and // signature verification before any handler. async function liveEventGate(b) { const tag = (await (await fetch(`${b}/live`)).text()).match(/]*>/)?.[0] ?? ""; const attr = (n) => tag.match(new RegExp(`${n}="([^"]*)"`))?.[1]; const ev = { name: attr("name"), state: JSON.parse((attr("state") ?? "{}").replace(/"/g, '"')), sig: attr("sig"), handler: "inc" }; const post = (h, body = ev) => fetch(`${b}/__nowaki/live-event`, { method: "POST", headers: Object.fromEntries( Object.entries({ "content-type": "application/json", "x-nowaki-live": "1", ...h }).filter(([, v]) => v !== null), ), body: typeof body === "string" ? body : JSON.stringify(body), }); const ok = await post({ origin: b }); const okBody = ok.status === 200 ? await ok.json() : {}; check("live-event same-origin POST applies the event (live: 1, new sig)", /live:\s*1/.test(okBody.html ?? "") && okBody.state?.count === 1 && okBody.sig && okBody.sig !== ev.sig); check("live-event cross-site Origin rejected (403)", (await post({ origin: "http://evil.test" })).status === 403); check("live-event Sec-Fetch-Site cross-site rejected (403)", (await post({ "sec-fetch-site": "cross-site" })).status === 403); check("live-event missing x-nowaki-live rejected (403)", (await post({ "x-nowaki-live": null })).status === 403); check("live-event text/plain rejected (415)", (await post({ "content-type": "text/plain" })).status === 415); const forged = await post({}, { ...ev, state: { count: 9999 }, sig: "FORGED" }); const forgedText = await forged.text(); check(`live-event forged signature gets no html (${forged.status})`, forged.status === 403 && !forgedText.includes("html")); check("live-event oversized body rejected (413)", (await post({}, { ...ev, payload: "x".repeat(70 * 1024) })).status === 413); // The POST runs in its own request: live.authorize sees the request's real cookies. const admin = (cookie) => fetch(`${b}/__nowaki/live-event`, { method: "POST", headers: { "content-type": "application/json", "x-nowaki-live": "1", ...(cookie ? { cookie } : {}) }, body: JSON.stringify({ ...ev, handler: "adminReset" }), }); const denied = await admin(null); check(`live-event: live.authorize refuses without the role cookie (${denied.status})`, denied.status === 403 && (await denied.json()).error === "forbidden"); check("live-event: live.authorize allows with role=admin", (await admin("role=admin")).status === 200); // The sidecar's internal render hook has no CSRF gate, so the Rust front must not proxy it. const internal = await fetch(`${b}/__nowaki/live-render`, { method: "POST", headers: { "content-type": "text/plain" }, body: JSON.stringify(ev) }); check(`internal /__nowaki/live-render not reachable (${internal.status})`, internal.status === 404); } // Raw request (path sent verbatim): { status, headers, body }. function raw(b, path, { method = "GET", headers = {}, body, timeoutMs } = {}) { const u = new URL(b); return new Promise((resolve) => { let settled = false; const finish = (value) => { if (settled) return; settled = true; resolve(value); }; const req = http.request({ host: u.hostname, port: u.port, path, method, headers }, (res) => { let text = ""; res.setEncoding("utf8"); res.on("data", (c) => (text += c)); res.on("end", () => finish({ status: res.statusCode, headers: res.headers, body: text })); }); req.on("error", () => finish({ status: 0, headers: {}, body: "" })); if (timeoutMs) req.setTimeout(timeoutMs, () => { req.destroy(); finish({ status: 0, headers: {}, body: "" }); }); if (body !== undefined) req.write(body); req.end(); }); } // nowaki.config redirects in examples/hello (`/old-docs/[...rest]` → `/[...rest]`, `/go/[to]` → // `/[to]`, rewrite `/p/[slug]` → `/blog/[slug]`): a capture can't make the Location leave the site // or add a header, redirects carry the security headers, and a client can't pick the route // through the internal x-nowaki-route-path header. async function configRoutingSafe(b) { const offSite = (loc) => loc === undefined || /^\/\/|^\/\\|^[a-z][a-z0-9+.-]*:/i.test(loc); for (const [p, want] of [ ["/old-docs//evil.com", "/evil.com"], ["/old-docs/%2F%2Fevil.com", "/%2F%2Fevil.com"], ["/old-docs/%5Cevil.com", "/%5Cevil.com"], ["/go/%2F%2Fevil.com", "/%2F%2Fevil.com"], ["/go/%5C%5Cevil.com", "/%5C%5Cevil.com"], ["/go/https:%2F%2Fevil.com", "/https%3A%2F%2Fevil.com"], ["/go/..", "/%2E%2E"], ]) { const r = await raw(b, p); check(`redirect ${p} stays on the site (${r.status} → ${r.headers.location})`, r.status >= 300 && r.status < 400 && r.headers.location === want && !offSite(r.headers.location)); } // A raw backslash may be refused outright; if it's redirected, the target must stay on the site. const bs = await raw(b, "/old-docs/\\evil.com"); check(`redirect /old-docs/\\evil.com stays on the site (${bs.status} → ${bs.headers.location})`, bs.status >= 400 || !offSite(bs.headers.location)); const crlf = await raw(b, "/go/a%0D%0ASet-Cookie:%20pwned=1"); check("encoded CRLF in a capture stays encoded (no injected header)", crlf.status === 307 && crlf.headers.location === "/a%0D%0ASet-Cookie%3A%20pwned%3D1" && !crlf.headers["set-cookie"]); const q = await raw(b, "/old-docs/guide?x=1"); check(`redirect keeps the query and carries the security headers (${q.headers.location})`, q.status === 308 && q.headers.location === "/guide?x=1" && q.headers["x-content-type-options"] === "nosniff" && q.headers["x-frame-options"] === "SAMEORIGIN"); const rw = await raw(b, "/p/hello"); check("rewrite renders the destination route", rw.status === 200 && rw.body.includes("Post: hello")); const forged = await raw(b, "/about", { headers: { "x-nowaki-route-path": "/env" } }); check("client x-nowaki-route-path can't pick the route", forged.status === 200 && !forged.body.includes("token length") && forged.body.includes("

About

")); const forged404 = await raw(b, "/nope-404", { headers: { "x-nowaki-route-path": "/about" } }); check("client x-nowaki-route-path can't turn a 404 into a page", forged404.status === 404); } if (mode === "dev") { const enc = encodeURIComponent; // Arbitrary file read surface (canonicalize, allowed roots, deny list, transformable gates). // `outside` exists outside every allowed root, so "blocked" means 403 rather than 404. const outside = process.platform === "win32" ? "C:/Windows/win.ini" : "/etc/passwd"; const fsUrl = (p) => `${base}/@fs/${p.replace(/\\/g, "/").replace(/^\//, "")}`; check(`@fs arbitrary read blocked (${outside} → 403)`, (await statusOf(fsUrl(outside))) === 403); check("@fs .env blocked (403)", (await statusOf(fsUrl(`${appRoot}/.env`))) === 403); // Credential files under the app root (Wrangler's .dev.vars, registry tokens): never served. { const fs = await import("node:fs"); const nodePath = await import("node:path"); for (const name of [".dev.vars", ".npmrc"]) { const file = nodePath.join(appRoot, name); if (fs.existsSync(file)) continue; fs.writeFileSync(file, "TOKEN=security-e2e-credential\n"); try { const viaFs = await fetch(fsUrl(file)); const viaRoot = await fetch(`${base}/${name}`); check(`@fs ${name} blocked (403)`, viaFs.status === 403); check(`${name} not served by the dev fallback`, !(await viaRoot.text()).includes("security-e2e-credential")); } finally { fs.rmSync(file, { force: true }); } } } check(`ssr-module arbitrary read blocked (${outside} → 403)`, (await statusOf(`${base}/__nowaki/ssr-module?path=${enc(outside)}`)) === 403); check("ssr-module .env blocked (403)", (await statusOf(`${base}/__nowaki/ssr-module?path=${enc(appRoot + "/.env")}`)) === 403); check("ssr-module legit module still served (200)", (await statusOf(`${base}/__nowaki/ssr-module?path=${enc(appRoot + "/routes/index.tsx")}`)) === 200); const envRes = await fetch(`${base}/.env`); const envBody = await envRes.text(); check(".env not served via dev fallback (no secret leaked)", envRes.status !== 200 && !envBody.includes("SESSION_SECRET")); check("virtual-module traversal rejected (.. → 404)", (await rawGet(base, "/__nowaki_virtual__/../../../../../../../etc/hosts")) === 404); // HMR is dev-only. check("CSWSH /__nowaki/hmr cross-origin upgrade rejected (403)", (await wsUpgrade(base, "/__nowaki/hmr", "http://evil.test")) === 403); } // Internal headers never reach a client, on every server: no `x-nowaki-*` response header outside // CLIENT_HEADERS, and no `Set-Cookie` next to a shared-cacheable `Cache-Control` (`public` / // `s-maxage`). `req(path, init)` returns a Response (fetch against a server, or a Worker's fetch // handler called in-process). Each request is also sent with forged internal headers, which must // not be echoed back or turn the answer into a shared one. // CLIENT_HEADERS: the documented x-nowaki-cache, x-nowaki-slot (the intercepting-route fragment // the client router reads; private, no-store), and x-nowaki-mw (set by examples/hello's own // _middleware). const CLIENT_HEADERS = new Set(["x-nowaki-cache", "x-nowaki-slot", "x-nowaki-mw"]); async function internalHeaderSweep(req, label, origin) { const forged = { "x-nowaki-vary": "cookie", "x-nowaki-purge": "/", "x-nowaki-tags": "t", "x-nowaki-route": "/admin", "x-nowaki-route-path": "/secret" }; const form = { "content-type": "application/x-www-form-urlencoded", origin }; const json = { "content-type": "application/json", origin }; const cases = [ ["/"], ["/"], ["/about"], ["/isr"], ["/isr"], ["/isr?cb=1"], ["/isr-tagged"], ["/isr-tagged"], ["/vary", { headers: { "accept-language": "de" } }], ["/vary", { headers: { "accept-language": "de" } }], ["/isr-cookie", { headers: { cookie: "user=alice" } }], ["/isr-sets-cookie"], ["/isr-sets-cookie"], ["/stream"], ["/stream-early"], ["/live"], ["/raw-html"], ["/env"], ["/feed.xml"], ["/og/intro.png"], ["/robots.txt"], ["/nope"], ["/boom?boom=1"], ["/old-docs/intro"], ["/p/hello"], ["/photos/1"], ["/photos/1", { headers: { "x-nowaki-intercept": "/photos/@modal" } }], ["/api/hello"], ["/api/echo", { method: "POST", headers: json, body: "{}" }], ["/api/session"], ["/api/session", { method: "POST", headers: form, body: "op=login&user=sweep" }], ["/api/session", { method: "POST", headers: { ...form, origin: "http://evil.test" }, body: "op=inc" }], ["/todos", { method: "POST", headers: { ...form, origin: "http://evil.test" }, body: "text=x" }], ["/__nowaki/health"], ["/__nowaki/boundaries"], ["/__nowaki/fn", { method: "POST", headers: { ...json, "x-nowaki-rpc": "1" }, body: '{"id":"nope","args":[]}' }], ["/__nowaki/revalidate", { method: "POST", headers: { ...json, authorization: "Bearer wrong" }, body: '{"paths":["/"]}' }], ["/__nowaki/live-event", { method: "POST", headers: { ...json, "x-nowaki-live": "1" }, body: "{}" }], ]; const home = await (await req("/")).text(); const asset = home.match(/\/_nowaki\/[A-Za-z0-9_.-]+\.js/)?.[0]; if (asset) cases.push([asset]); let leaks = []; let shared = []; for (const [p, init = {}] of cases) { for (const extra of [{}, forged]) { const r = await req(p, { redirect: "manual", ...init, headers: { ...(init.headers || {}), ...extra } }); await r.arrayBuffer().catch(() => {}); for (const [k] of r.headers) { if (k.toLowerCase().startsWith("x-nowaki-") && !CLIENT_HEADERS.has(k.toLowerCase())) leaks.push(`${p} ${k}`); } const cc = r.headers.get("cache-control") || ""; if (r.headers.get("set-cookie") && /public|s-maxage/i.test(cc)) shared.push(`${p} (${cc})`); } } leaks = [...new Set(leaks)]; shared = [...new Set(shared)]; check(`${label}: no internal x-nowaki-* response header (${cases.length} requests x2)${leaks.length ? ` leaked: ${leaks.join(", ")}` : ""}`, leaks.length === 0); check(`${label}: no Set-Cookie on a shared-cacheable response${shared.length ? ` (${shared.join(", ")})` : ""}`, shared.length === 0); await rawHtmlNonce(req, label); } // Under NOWAKI_CSP (when the server sends a nonce policy): raw HTML in a page (routes/raw-html.tsx, // as if from a CMS) gets no nonce on its inline