');
check("loaders run page, then layouts leaf → root", order.join(",") === "page,blog,root");
check("a layout without a default export is skipped", !order.includes("skipped"));
}
{
order.length = 0;
const res = await req("/blog/early");
const body = await text(res);
check("early streaming wraps the same layouts", body === '
early E
');
check("early streaming runs loaders page, then layouts leaf → root", order.join(",") === "page,blog,root");
}
{
// After an early shell a redirect is `location.replace(...)`: only http(s) targets.
const go = async (next) => text(await req(`/blog/go?next=${encodeURIComponent(next)}`));
check("early redirect follows a path", (await go("/about")).includes('location.replace("/about")'));
check("early redirect follows an https URL", (await go("https://ok.test/x")).includes('location.replace("https://ok.test/x")'));
for (const bad of ["javascript:alert(1)", "JavaScript:alert(1)", " javascript:alert(1)", "data:text/html,"]) {
const body = await go(bad);
check(`early redirect refuses ${JSON.stringify(bad)} (goes to /)`, body.includes('location.replace("/")') && !/javascript:|data:/i.test(body));
}
}
{
seenUrls.length = 0;
const res = await req("/p/hello", { routePath: "/blog/hello" });
check("routePath picks the route", res.status === 200 && (await text(res)).includes("
'));
check(
"the rendered slot file's CSS follows the page's, deduped",
body.startsWith('\n'),
);
check("the rendered slot file's page scripts are included", body.includes('src="/routes/@modal/g/[id].tsx/./m.ts"'));
const plain = await text(await get("/plain"));
check("the default renders where no slot route matches", plain.endsWith('
plain
none
'));
check("a default's CSS is asked for", cssCalls.includes("routes/@modal/default.tsx"));
const early = await text(await get("/g/early"));
check("early streaming renders slots too", early.includes('
early
Learly'));
// The owners of a file's chain are computed once per table: a filter on table.slots that runs
// again would see the replaced array.
const saved = slotTable.slots;
slotTable.slots = [{ ...saved[0], name: "other" }];
check("slot owners are cached per table and file", (await text(await get("/g/6"))).includes(' noSlots }, { method: "GET", url: new URL("http://x.test/g/5"), headers: {}, version: 1 });
check("without slots a layout gets an empty slots object", (await text(res)).endsWith("|
page 5
"));
}
// CSRF: unsafe-method cross-site requests to API and file routes get the same 403 as page
// actions (after middleware), unless the route exports `csrf = false`. GET / HEAD / OPTIONS pass.
{
let mwRuns = 0;
const csrfModules = {
"routes/_middleware.ts": { default: () => void mwRuns++ },
"routes/api/plain.ts": { GET: () => ({ ok: "get" }), POST: () => ({ ok: "post" }), PUT: () => ({}), PATCH: () => ({}), DELETE: () => ({}), OPTIONS: () => ({ ok: "options" }) },
"routes/api/strict.ts": { csrf: true, POST: () => ({ ok: "post" }) },
"routes/api/hook.ts": { csrf: false, POST: () => ({ ok: "hook" }) },
"routes/feed.xml.ts": { default: () => ({ headers: { "content-type": "application/xml" }, body: "" }) },
"routes/todos.tsx": { action: () => ({ ok: true }), default: () => h("p", null, "todos") },
};
const api = (file, lit, fileExt) => ({ file, segments: lit.split("/").filter(Boolean).map((l) => ({ lit: l })), dir: "/", isApi: true, fileExt });
const csrfTable = {
routes: [
api("routes/api/plain.ts", "/api/plain"),
api("routes/api/strict.ts", "/api/strict"),
api("routes/api/hook.ts", "/api/hook"),
api("routes/feed.xml.ts", "/feed.xml", "xml"),
{ file: "routes/todos.tsx", segments: [{ lit: "todos" }], dir: "/", isApi: false },
],
layouts: [],
middleware: [{ prefix: "", file: "routes/_middleware.ts" }],
};
const csrfEnv = { ...env, routeTable: async () => csrfTable, importModule: async (file) => csrfModules[file] };
const send = (method, path, headers = {}) =>
handleRequest(csrfEnv, {
method,
url: new URL(`http://app.test${path}`),
headers: { host: "app.test", ...headers },
readBody: async () => new Uint8Array(),
version: 1,
});
const evil = { origin: "https://evil.test" };
const action = await send("POST", "/todos", evil);
const rejected = await send("POST", "/api/plain", evil);
check("csrf: cross-site API POST is rejected (403)", rejected.status === 403);
check(
"csrf: the API rejection is the page action's response (status, headers, body)",
action.status === 403 && JSON.stringify([rejected.status, rejected.headers, rejected.body]) === JSON.stringify([action.status, action.headers, action.body]),
);
for (const m of ["PUT", "PATCH", "DELETE"]) check(`csrf: cross-site API ${m} is rejected (403)`, (await send(m, "/api/plain", evil)).status === 403);
check("csrf: Origin null is rejected (403)", (await send("POST", "/api/plain", { origin: "null" })).status === 403);
check("csrf: Sec-Fetch-Site cross-site without Origin is rejected (403)", (await send("POST", "/api/plain", { "sec-fetch-site": "cross-site" })).status === 403);
check("csrf: same-origin API POST is allowed", (await send("POST", "/api/plain", { origin: "http://app.test" })).status === 200);
check("csrf: Sec-Fetch-Site same-origin without Origin is allowed", (await send("POST", "/api/plain", { "sec-fetch-site": "same-origin" })).status === 200);
check("csrf: POST without Origin or Sec-Fetch-Site (curl, server) is allowed", (await send("POST", "/api/plain")).status === 200);
check("csrf: cross-site GET is unaffected", (await send("GET", "/api/plain", evil)).status === 200);
check("csrf: cross-site OPTIONS is unaffected", (await send("OPTIONS", "/api/plain", evil)).status === 200);
check("csrf: `csrf = true` still rejects (403)", (await send("POST", "/api/strict", evil)).status === 403);
check("csrf: `csrf = false` accepts a cross-site POST", (await send("POST", "/api/hook", evil)).status === 200);
check("csrf: a file route rejects a cross-site POST (403)", (await send("POST", "/feed.xml", evil)).status === 403);
check("csrf: a file route still answers a cross-site GET", (await send("GET", "/feed.xml", evil)).status === 200);
mwRuns = 0;
await send("POST", "/api/plain", evil);
check("csrf: middleware runs before the check, as for actions", mwRuns === 1);
}
// ctx.routePath, and the aliases removed in 0.20.0 (`export const middleware`, lowercase API
// method exports): each is an error naming the new form, not a silent change.
{
const seen = [];
const mods = {
"routes/photo/[id].tsx": { default: () => h("p", null, "photo") },
"routes/api/r.ts": { GET: (ctx) => ctx.json({ routePath: ctx.routePath }) },
"routes/api/lower.ts": { get: () => ({ ok: true }), POST: () => ({ ok: true }) },
"routes/old/_middleware.ts": { middleware: () => new Response("old", { status: 401 }) },
"routes/_middleware.ts": { default: (ctx) => void seen.push(ctx.routePath) },
};
const t = {
routes: [
{ file: "routes/photo/[id].tsx", segments: [{ lit: "photo" }, { param: "id" }], dir: "/photo", isApi: false },
{ file: "routes/api/r.ts", segments: [{ lit: "api" }, { lit: "r" }], dir: "/api", isApi: true },
{ file: "routes/api/lower.ts", segments: [{ lit: "api" }, { lit: "lower" }], dir: "/api", isApi: true },
],
layouts: [],
middleware: [
{ prefix: "", file: "routes/_middleware.ts" },
{ prefix: "/old", file: "routes/old/_middleware.ts" },
],
};
const errors = [];
const e = {
...env,
routeTable: async () => t,
importModule: async (file) => mods[file],
renderError: (err) => (errors.push(String(err?.message ?? err)), { status: 500, headers: {}, body: "error" }),
};
const go = (path, extra = {}) => handleRequest(e, { method: "GET", url: new URL(`http://x.test${path}`), headers: {}, version: 1, ...extra });
const r = await go("/app/api/r", { routePath: "/api/r" });
check("ctx.routePath is the routed path, without basePath", JSON.parse(r.body).routePath === "/api/r");
seen.length = 0;
await go("/photo/1");
check("ctx.routePath without a front is url.pathname", seen[0] === "/photo/1");
const { compileI18n } = await import("../packages/nowaki-runtime/server/i18n.mjs");
const i18nEnv = { ...e, i18n: compileI18n({ i18n: { locales: ["en", "ja"], defaultLocale: "en" }, basePath: "/app" }) };
seen.length = 0;
const ja = await handleRequest(i18nEnv, { method: "GET", url: new URL("http://x.test/app/ja/photo/1"), routePath: "/ja/photo/1", headers: {}, version: 1 });
check("ctx.routePath drops the locale prefix too", ja.status === 200 && seen[0] === "/photo/1");
errors.length = 0;
const old = await go("/old/x");
check("`export const middleware` is refused with an error", old.status === 500 && /export const middleware.*removed in 0\.20\.0.*export default/.test(errors.join(" ")));
errors.length = 0;
const lowerGet = await go("/api/lower");
const lowerPost = await go("/api/lower", { method: "POST" });
check(
"a lowercase API method export is refused for every method",
lowerGet.status === 500 && lowerPost.status === 500 && errors.length === 2 && errors.every((m) => /exports `get`.*uppercase \(`GET`\)/.test(m)),
);
}
{
// A CORS preflight (OPTIONS, from any site, unchecked for CSRF) never runs a page action.
order.length = 0;
const pre = await req("/blog/act", { method: "OPTIONS", headers: { origin: "http://evil.test", host: "x.test" } });
check("OPTIONS does not run the action", !order.includes("action") && pre.status !== 303);
const post = await req("/blog/act", { method: "POST", headers: { origin: "http://x.test", host: "x.test" } });
check("same-origin POST still runs the action", order.includes("action") && post.status === 303);
}
{
// Endpoint body caps hold for a streamed body with no Content-Length (a chunked POST on the
// node adapter), not only against the header: server functions 1 MiB, live events and the
// revalidate endpoint 64 KiB (the general 10 MiB form cap would otherwise apply).
const { Readable } = await import("node:stream");
let pulled = 0;
const stream = (bytes) => {
pulled = 0;
const chunk = Buffer.alloc(16 * 1024, 0x61);
let left = bytes;
return Readable.from((function* () {
while (left > 0) {
left -= chunk.length;
pulled += chunk.length;
yield chunk;
}
})());
};
const json = { "content-type": "application/json", "x-nowaki-rpc": "1", "x-nowaki-live": "1", authorization: "Bearer s3cret-for-handler-test" };
const post = (path, bytes, extraEnv = {}) =>
handleRequest({ ...env, ...extraEnv }, { method: "POST", url: new URL(`http://x.test${path}`), headers: { ...json, host: "x.test" }, req: stream(bytes), version: 1 });
const fn = await post("/__nowaki/fn", 3 * 1024 * 1024, { serverFunctions: { lookup: async () => null, importModule: async () => ({}) } });
check(`server function: a streamed 3 MiB body is refused at 1 MiB (413, read ${pulled >> 10} KiB)`, fn.status === 413 && pulled <= 1024 * 1024 + 64 * 1024);
const live = await post("/__nowaki/live-event", 1024 * 1024, { live: { lookup: async () => null } });
check(`live-event: a streamed 1 MiB body is refused at 64 KiB (413, read ${pulled >> 10} KiB)`, live.status === 413 && pulled <= 128 * 1024);
process.env.NOWAKI_REVALIDATE_SECRET = "s3cret-for-handler-test ";
const rv = await post("/__nowaki/revalidate", 1024 * 1024);
check(`revalidate: a streamed 1 MiB body is refused at 64 KiB (413; secret with trailing spaces still matches)`, rv.status === 413 && pulled <= 128 * 1024);
process.env.NOWAKI_REVALIDATE_SECRET = " ";
check("revalidate: a blank secret leaves the endpoint off (404)", (await post("/__nowaki/revalidate", 10)).status === 404);
delete process.env.NOWAKI_REVALIDATE_SECRET;
}
// Layout metadata (`title`, `lang`, `head`, `htmlAttrs` / `bodyAttrs`, `meta` objects and meta()
// functions): layouts root → leaf, then the page; the nearest module that sets `title` / `lang`
// wins, and within a module `meta.*` beats the plain export.
{
const { pageMeta } = await import("../packages/nowaki-runtime/server/document.mjs");
const metaCalls = [];
const lm = {
"routes/_layout.tsx": {
title: "Root",
lang: "en",
head: '',
meta: { description: "site", openGraph: { siteName: "Site" } },
htmlAttrs: { class: "root", lang: "xx" },
loader: () => "RD",
default: ({ children }) => h("div", null, children),
},
"routes/docs/_layout.tsx": {
title: "Docs export",
loader: (ctx) => `docs:${ctx.params.slug ?? "-"}`,
meta: ({ data, params, url }) => (metaCalls.push({ data, params, path: url.pathname }), { title: `Docs ${data}`, lang: "fr", htmlAttrs: { class: "docs" }, bodyAttrs: { "data-l": "docs" }, openGraph: { type: "article" } }),
default: ({ children }) => h("section", null, children),
},
"routes/broken/_layout.tsx": {
meta: () => {
throw new Error("layout meta failed");
},
default: ({ children }) => h("main", null, children),
},
"routes/index.tsx": { default: () => h("p", null, "home") },
"routes/docs/[slug].tsx": { default: () => h("p", null, "doc") },
"routes/docs/own.tsx": { title: "Own", lang: "de", htmlAttrs: { class: "page" }, meta: () => ({ description: "page" }), default: () => h("p", null, "own") },
"routes/docs/early.tsx": { streaming: "early", default: () => h("p", null, "early") },
"routes/broken/x.tsx": { default: () => h("p", null, "x") },
"routes/_404.tsx": { title: "Missing", default: () => h("p", null, "404") },
};
const lt = {
routes: [
{ file: "routes/index.tsx", segments: [], dir: "", isApi: false },
{ file: "routes/docs/own.tsx", segments: [{ lit: "docs" }, { lit: "own" }], dir: "/docs", isApi: false },
{ file: "routes/docs/early.tsx", segments: [{ lit: "docs" }, { lit: "early" }], dir: "/docs", isApi: false },
{ file: "routes/docs/[slug].tsx", segments: [{ lit: "docs" }, { param: "slug" }], dir: "/docs", isApi: false },
{ file: "routes/broken/x.tsx", segments: [{ lit: "broken" }, { lit: "x" }], dir: "/broken", isApi: false },
],
layouts: [
{ prefix: "", file: "routes/_layout.tsx" },
{ prefix: "/docs", file: "routes/docs/_layout.tsx" },
{ prefix: "/broken", file: "routes/broken/_layout.tsx" },
],
middleware: [],
notFound: "routes/_404.tsx",
};
const doc = ({ mod, body, meta }) => JSON.stringify({ ...pageMeta(meta, mod), body });
const menv = {
...env,
routeTable: async () => lt,
importModule: async (file) => lm[file],
renderDocument: doc,
renderShell: ({ mod, meta }) => ({ head: `${doc({ mod, body: "", meta })}\n`, tail: "" }),
onError: () => {},
};
const get = async (path) => {
const res = await handleRequest(menv, { method: "GET", url: new URL(`http://x.test${path}`), headers: {}, version: 1 });
const body = await text(res);
return { status: res.status, ...JSON.parse(body.split("\n")[0]) };
};
const home = await get("/");
check("layout meta: the root layout's title export is the fallback title", home.title === "Root");
check("layout meta: the root layout's lang export beats its htmlAttrs.lang", home.lang === "en" && !home.htmlAttrs.includes("lang="));
check("layout meta: a layout's head and meta object reach the page", home.head.includes('rel="icon"') && home.head.includes(''));
const d = await get("/docs/intro");
check("layout meta: a layout's meta() gets its loader's data, params and url", metaCalls.at(-1)?.data === "docs:intro" && metaCalls.at(-1)?.params.slug === "intro" && metaCalls.at(-1)?.path === "/docs/intro");
check("layout meta: the nearest layout's meta().title wins over its title export and the root's", d.title === "Docs docs:intro");
check("layout meta: the nearest layout's meta().lang wins", d.lang === "fr");
check("layout meta: meta() htmlAttrs / bodyAttrs merge after the layouts' exports", d.htmlAttrs.includes('class="root docs"') && d.bodyAttrs.includes('data-l="docs"'));
check("layout meta: meta() SEO fields merge over the root's (openGraph one level deep)", d.head.includes('og:type" content="article"') && d.head.includes('og:site_name" content="Site"') && d.head.includes('og:title" content="Docs docs:intro"'));
const own = await get("/docs/own");
check("layout meta: the page's title and lang win over every layout", own.title === "Own" && own.lang === "de");
check("layout meta: the page's htmlAttrs merge last", own.htmlAttrs.includes('class="root docs page"'));
check("layout meta: the page's meta() fields win over the layouts'", own.head.includes('content="page"') && !own.head.includes('content="site"'));
metaCalls.length = 0;
const early = await get("/docs/early");
check("layout meta: early streaming calls a layout's meta() before any loader (data undefined)", early.title === "Docs undefined" && metaCalls.length === 1 && metaCalls[0].data === undefined);
const broken = await get("/broken/x");
check("layout meta: a layout meta() that throws is skipped; the page renders", broken.status === 200 && broken.title === "Root" && broken.body.includes("
x
"));
const missing = await get("/nope");
check("layout meta: the 404 page's own title wins over the layouts'", missing.status === 404 && missing.title === "Missing" && missing.lang === "en");
}
if (failures) {
console.error(`${failures} failure(s)`);
process.exit(1);
}
console.log("handler: all checks passed");