@sigil-dev/grimoire 0.9.5 → 0.9.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -116,7 +116,7 @@ export async function scanRoutes(
116
116
  }
117
117
  }
118
118
 
119
- for await (const file of glob.scan(routesDir)) {
119
+ for await (const file of glob.scan({ cwd: routesDir, dot: true })) {
120
120
  const filePath = join(routesDir, file);
121
121
  const name = basename(file).replace(/\.(tsx?|jsx?)$/, "");
122
122
  const { pattern, params, optionalParams, restParams, paramMatchers } =
@@ -282,15 +282,27 @@ export async function startCoordinator(options: CoordinatorOptions) {
282
282
  const serialized =
283
283
  (await runSerializeLocals(plugins, locals)) ??
284
284
  defaultSerialize(locals, secret);
285
+ const forwardHeaders: Record<string, string> = {
286
+ ...Object.fromEntries(req.headers),
287
+ "X-Grimoire-Locals": serialized,
288
+ "X-Grimoire-Internal": secret,
289
+ };
290
+ // Bun's fetch() to 127.0.0.1 drops the cookie header when it arrives
291
+ // via Object.fromEntries (lowercase "cookie"). Re-set it explicitly
292
+ // under the canonical "Cookie" name so the worker receives it.
293
+ const cookieHeader = req.headers.get("cookie");
294
+ if (cookieHeader) {
295
+ forwardHeaders["Cookie"] = cookieHeader;
296
+ }
285
297
  return fetch(chosen.internalUrl + url.pathname + url.search, {
286
298
  method: req.method,
287
- headers: {
288
- //@ts-expect-error shut up
289
- ...Object.fromEntries(req.headers),
290
- "X-Grimoire-Locals": serialized,
291
- "X-Grimoire-Internal": secret,
292
- },
299
+ headers: forwardHeaders,
293
300
  body: req.body,
301
+ // never follow worker redirects: a 303 from a form action must
302
+ // reach the client verbatim (Set-Cookie + Location), otherwise
303
+ // the coordinator silently swallows the session cookie and
304
+ // returns the redirect target's HTML as a 200.
305
+ redirect: "manual",
294
306
  });
295
307
  },
296
308
  websocket: {
@@ -327,7 +339,7 @@ export async function startCoordinator(options: CoordinatorOptions) {
327
339
  stopping = true;
328
340
  await runHook(plugins, "onStop", "shutdown");
329
341
  for (const w of liveWorkers) w.process.kill();
330
- server.stop();
342
+ server.stop(true);
331
343
  };
332
344
 
333
345
  const restartAll = () =>
@@ -464,15 +464,18 @@ export async function createServer(config: GrimoireConfig = {}) {
464
464
 
465
465
  const handler = mod[evt.request.method];
466
466
  if (!handler) {
467
- return new Response("Method Not Allowed", { status: 405 });
467
+ return new Response("Method Not Allowed", { status: 405 });
468
468
  }
469
469
  return handler({
470
470
  request: evt.request,
471
471
  params: matched.params,
472
472
  url: evt.url,
473
473
  locals: evt.locals,
474
+ fetch: patchedFetch,
475
+ cookies,
476
+ setHeaders: (headers) => Object.assign(setHeadersMap, headers),
474
477
  });
475
- }
478
+ }
476
479
 
477
480
  // form actions (+page.server.ts)
478
481
  if (
@@ -602,10 +605,15 @@ export async function createServer(config: GrimoireConfig = {}) {
602
605
  data: undefined,
603
606
  })) ?? html;
604
607
  }
608
+ // Carry the original headers over. Rebuilding with a fixed set
609
+ // dropped Vary and the _csrf Set-Cookie, so any onRouteRender
610
+ // plugin silently broke form actions and cache correctness.
611
+ const headers = new Headers(response.headers);
612
+ headers.set("Content-Type", "text/html");
605
613
  return new Response(html, {
606
614
  status: response.status,
607
615
  statusText: response.statusText,
608
- headers: { "Content-Type": "text/html" },
616
+ headers,
609
617
  });
610
618
  }
611
619
 
@@ -649,22 +657,24 @@ export async function createServer(config: GrimoireConfig = {}) {
649
657
 
650
658
  const setCookieHeaders = cookies.toHeaders();
651
659
  if (
652
- setCookieHeaders.length > 0 ||
653
- Object.keys(setHeadersMap).length > 0
660
+ !response ||
661
+ (setCookieHeaders.length === 0 &&
662
+ Object.keys(setHeadersMap).length === 0)
654
663
  ) {
655
- const headers = new Headers(response.headers);
656
- for (const [k, v] of Object.entries(setHeadersMap)) {
657
- headers.set(k, v);
658
- }
659
- for (const sc of setCookieHeaders) {
660
- headers.append("Set-Cookie", sc);
661
- }
662
- response = new Response(response.body, {
663
- status: response.status,
664
- statusText: response.statusText,
665
- headers,
666
- });
664
+ return response;
665
+ }
666
+ const headers = new Headers(response.headers);
667
+ for (const [k, v] of Object.entries(setHeadersMap)) {
668
+ headers.set(k, v);
667
669
  }
670
+ for (const sc of setCookieHeaders) {
671
+ headers.append("Set-Cookie", sc);
672
+ }
673
+ response = new Response(response.body, {
674
+ status: response.status,
675
+ statusText: response.statusText,
676
+ headers,
677
+ });
668
678
 
669
679
  return response;
670
680
  });
@@ -700,7 +710,9 @@ export async function createServer(config: GrimoireConfig = {}) {
700
710
  if (stopping) return;
701
711
  stopping = true;
702
712
  await runHook(plugins, "onStop", "shutdown");
703
- server.stop();
713
+ // stop(true), not stop(): the graceful form waits for open connections,
714
+ // and a dev HMR websocket never closes on its own, so shutdown hangs.
715
+ server.stop(true);
704
716
  process.exit(0);
705
717
  };
706
718
  process.on("SIGINT", handleShutdown);
@@ -0,0 +1,61 @@
1
+ import { beforeEach, describe, expect, test } from "bun:test";
2
+ import { ensureCsrf, onSubmitEnsureCsrf } from "../src/client/csrf.ts";
3
+
4
+ // The root test/preload.ts installs happy-dom globals; this package's
5
+ // compiler options have no DOM lib, so reach them untyped.
6
+ const { window, document, Event } = globalThis as any;
7
+
8
+ window.location.href = "http://localhost/";
9
+
10
+ const token = (form: any) =>
11
+ form.querySelector('input[name="_csrf"]')?.value ?? null;
12
+
13
+ beforeEach(() => {
14
+ document.cookie = "_csrf=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/";
15
+ document.body.innerHTML = "";
16
+ });
17
+
18
+ describe("client CSRF", () => {
19
+ test("a client-rendered form gets the cookie's token", () => {
20
+ document.cookie = "_csrf=abc123; path=/";
21
+ const form = document.createElement("form") as any;
22
+ form.setAttribute("method", "post");
23
+ ensureCsrf(form);
24
+ expect(token(form)).toBe("abc123");
25
+ expect(form.querySelectorAll('input[name="_csrf"]').length).toBe(1);
26
+ expect(form.firstElementChild.hasAttribute("data-grimoire-csrf")).toBe(
27
+ true,
28
+ );
29
+ });
30
+
31
+ test("a stale SSR token is replaced, not duplicated", () => {
32
+ document.cookie = "_csrf=fresh; path=/";
33
+ document.body.innerHTML = `<form method="post"><input type="hidden" name="_csrf" value="stale" data-grimoire-csrf></form>`;
34
+ const form = document.querySelector("form") as any;
35
+ ensureCsrf(form);
36
+ expect(token(form)).toBe("fresh");
37
+ expect(form.querySelectorAll('input[name="_csrf"]').length).toBe(1);
38
+ });
39
+
40
+ test("no cookie, no change", () => {
41
+ const form = document.createElement("form") as any;
42
+ ensureCsrf(form);
43
+ expect(token(form)).toBeNull();
44
+ });
45
+
46
+ test("the submit listener only touches POST forms", () => {
47
+ document.cookie = "_csrf=tok; path=/";
48
+ document.body.innerHTML = `<form method="post" id="p"></form><form id="g"></form>`;
49
+ document.addEventListener("submit", onSubmitEnsureCsrf as any, true);
50
+ for (const id of ["p", "g"]) {
51
+ document
52
+ .getElementById(id)!
53
+ .dispatchEvent(
54
+ new Event("submit", { bubbles: true, cancelable: true }),
55
+ );
56
+ }
57
+ document.removeEventListener("submit", onSubmitEnsureCsrf as any, true);
58
+ expect(token(document.getElementById("p"))).toBe("tok");
59
+ expect(token(document.getElementById("g"))).toBeNull();
60
+ });
61
+ });
@@ -205,6 +205,77 @@ describe("hover prefetch", () => {
205
205
  });
206
206
  });
207
207
 
208
+ describe("popstate — query string", () => {
209
+ // popstate fires navigate() from an event listener, so there is no promise
210
+ // to await at the call site. afterNavigate is the router's own completion
211
+ // signal; a fixed sleep would be both slower and racy.
212
+ function onNavigated(): Promise<void> {
213
+ const { promise, resolve } = Promise.withResolvers<void>();
214
+ router.afterNavigate(() => resolve());
215
+ return promise;
216
+ }
217
+
218
+ // Back used to refetch the bare pathname, so a query-driven page rendered
219
+ // unfiltered data while the address bar still showed the query.
220
+ test("back to a query URL refetches with the query intact", async () => {
221
+ const root = document.createElement("div");
222
+ root.id = "grimoire-root";
223
+ document.body.appendChild(root);
224
+ window.history.pushState(null, "", "/");
225
+ router.initRouter(
226
+ {
227
+ "/list": () => document.createElement("div"),
228
+ "/other": () => document.createElement("div"),
229
+ },
230
+ [],
231
+ );
232
+ const shim = captureFetch();
233
+ try {
234
+ await router.navigate("/list?q=fireball&page=2");
235
+ await router.navigate("/other");
236
+ shim.calls.length = 0;
237
+
238
+ // the browser moves history itself, then fires popstate
239
+ const navigated = onNavigated();
240
+ window.history.pushState(null, "", "/list?q=fireball&page=2");
241
+ window.dispatchEvent(new Event("popstate"));
242
+ await navigated;
243
+
244
+ expect(shim.calls.map((c) => c.input)).toEqual([
245
+ "/list?q=fireball&page=2",
246
+ ]);
247
+ } finally {
248
+ router.afterNavigate(() => {});
249
+ shim.restore();
250
+ root.remove();
251
+ }
252
+ });
253
+
254
+ test("a popstate that only changes the query still refetches", async () => {
255
+ const root = document.createElement("div");
256
+ root.id = "grimoire-root";
257
+ document.body.appendChild(root);
258
+ window.history.pushState(null, "", "/");
259
+ router.initRouter({ "/list": () => document.createElement("div") }, []);
260
+ const shim = captureFetch();
261
+ try {
262
+ await router.navigate("/list?page=2");
263
+ shim.calls.length = 0;
264
+
265
+ const navigated = onNavigated();
266
+ window.history.pushState(null, "", "/list?page=1");
267
+ window.dispatchEvent(new Event("popstate"));
268
+ await navigated;
269
+
270
+ expect(shim.calls.map((c) => c.input)).toEqual(["/list?page=1"]);
271
+ } finally {
272
+ router.afterNavigate(() => {});
273
+ shim.restore();
274
+ root.remove();
275
+ }
276
+ });
277
+ });
278
+
208
279
  describe("enhance — named action URLs", () => {
209
280
  test("action starting with ?/ submits to the current pathname", async () => {
210
281
  // earlier navigate() tests moved history — reset to a clean path
@@ -128,6 +128,45 @@ describe("Streaming SSR", () => {
128
128
  expect(json.data).toBeDefined();
129
129
  });
130
130
 
131
+ // The JSON payload and the HTML document share one URL and are picked by a
132
+ // request header. Without Vary any cache may serve the JSON to a plain
133
+ // document request, which rendered the raw state object as the page.
134
+ test("navigation JSON declares Vary on the navigate header", async () => {
135
+ const matched = makeMatched(
136
+ "/nav-vary",
137
+ "data:text/javascript,export default (p) => '<div>nav</div>'",
138
+ );
139
+
140
+ const res = await renderRoute(
141
+ matched,
142
+ new Request("http://localhost/nav-vary", {
143
+ headers: { "x-grimoire-navigate": "1" },
144
+ }),
145
+ );
146
+
147
+ expect(res.headers.get("content-type")).toContain("application/json");
148
+ expect(res.headers.get("vary")?.toLowerCase()).toContain(
149
+ "x-grimoire-navigate",
150
+ );
151
+ });
152
+
153
+ test("HTML document declares Vary on the navigate header", async () => {
154
+ const matched = makeMatched(
155
+ "/doc-vary",
156
+ "data:text/javascript,export default (p) => '<div>doc</div>'",
157
+ );
158
+
159
+ const res = await renderRoute(
160
+ matched,
161
+ new Request("http://localhost/doc-vary"),
162
+ );
163
+
164
+ expect(res.headers.get("content-type")).toContain("text/html");
165
+ expect(res.headers.get("vary")?.toLowerCase()).toContain(
166
+ "x-grimoire-navigate",
167
+ );
168
+ });
169
+
131
170
  test("state JSON escapes </script> in data (XSS)", async () => {
132
171
  const evil = "</script><script>alert(1)</script>";
133
172
  const src = [