@sigil-dev/grimoire 0.9.3 → 0.9.4

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.
@@ -247,3 +247,108 @@ export const websocket = {
247
247
  expect(body.kind).toBe("http");
248
248
  });
249
249
  });
250
+
251
+ describe("Server — named form actions (?/name)", () => {
252
+ let server: { stop: () => void };
253
+ let csrfToken = "";
254
+ const base = "http://localhost:3006";
255
+
256
+ beforeAll(async () => {
257
+ await mkdir(join(tmpDir, "form"), { recursive: true });
258
+ await writeFile(
259
+ join(tmpDir, "form", "+page.tsx"),
260
+ 'export default () => "<h1>form</h1>";',
261
+ );
262
+ await writeFile(
263
+ join(tmpDir, "form", "+page.server.ts"),
264
+ [
265
+ "export async function create(action) {",
266
+ " return {",
267
+ " __fail: true,",
268
+ " status: 400,",
269
+ " data: {",
270
+ ' ok: false,',
271
+ ' hasCookies: typeof action.cookies?.get === "function",',
272
+ ' method: action.request.method,',
273
+ " },",
274
+ " };",
275
+ "}",
276
+ "export async function POST() {",
277
+ ' return { redirect: "/done" };',
278
+ "}",
279
+ ].join("\n"),
280
+ );
281
+
282
+ server = await createServer({
283
+ port: 3006,
284
+ routes: tmpDir,
285
+ _skipBuild: true,
286
+ });
287
+ // SSR render sets the _csrf cookie
288
+ const res = await fetch(`${base}/form`);
289
+ const setCookie = res.headers.get("set-cookie") ?? "";
290
+ csrfToken = /_csrf=([a-f0-9]+)/.exec(setCookie)?.[1] ?? "";
291
+ });
292
+
293
+ afterAll(() => server.stop());
294
+
295
+ test("POST ?/create invokes the named export with cookies", async () => {
296
+ const res = await fetch(`${base}/form?/create`, {
297
+ method: "POST",
298
+ headers: {
299
+ "Content-Type": "application/x-www-form-urlencoded",
300
+ Cookie: `_csrf=${csrfToken}`,
301
+ },
302
+ body: `x=1&_csrf=${csrfToken}`,
303
+ });
304
+ expect(res.status).toBe(400);
305
+ // shape asserted below — typed to satisfy strict unknown-returning json()
306
+ const json = (await res.json()) as { fail: boolean; data: { hasCookies: boolean; method: string } };
307
+ expect(json.fail).toBe(true);
308
+ expect(json.data.hasCookies).toBe(true);
309
+ expect(json.data.method).toBe("POST");
310
+ });
311
+
312
+ test("unknown named action returns 404", async () => {
313
+ const res = await fetch(`${base}/form?/nope`, {
314
+ method: "POST",
315
+ headers: {
316
+ "Content-Type": "application/x-www-form-urlencoded",
317
+ Cookie: `_csrf=${csrfToken}`,
318
+ },
319
+ body: `x=1&_csrf=${csrfToken}`,
320
+ });
321
+ expect(res.status).toBe(404);
322
+ });
323
+
324
+ test("GET named action is allowed (no CSRF needed)", async () => {
325
+ const res = await fetch(`${base}/form?/create`);
326
+ expect(res.status).toBe(400);
327
+ // shape asserted below — typed to satisfy strict unknown-returning json()
328
+ const json = (await res.json()) as { fail: boolean; data: { hasCookies: boolean; method: string } };
329
+ expect(json.data.method).toBe("GET");
330
+ });
331
+
332
+ test("POST named action without CSRF token is forbidden", async () => {
333
+ const res = await fetch(`${base}/form?/create`, {
334
+ method: "POST",
335
+ headers: { "Content-Type": "application/x-www-form-urlencoded" },
336
+ body: "x=1",
337
+ });
338
+ expect(res.status).toBe(403);
339
+ });
340
+
341
+ test("method dispatch without query key is unchanged", async () => {
342
+ const res = await fetch(`${base}/form`, {
343
+ method: "POST",
344
+ headers: {
345
+ "Content-Type": "application/x-www-form-urlencoded",
346
+ Cookie: `_csrf=${csrfToken}`,
347
+ },
348
+ body: `x=1&_csrf=${csrfToken}`,
349
+ redirect: "manual",
350
+ });
351
+ expect(res.status).toBe(303);
352
+ expect(res.headers.get("location")).toBe("/done");
353
+ });
354
+ });
@@ -1,5 +1,10 @@
1
- import { describe, expect, test } from "bun:test";
1
+ import { afterAll, beforeAll, describe, expect, test } from "bun:test";
2
+ import { mkdir, rm, writeFile } from "node:fs/promises";
3
+ import { tmpdir } from "node:os";
4
+ import { join } from "node:path";
2
5
  import { renderRoute } from "../src/rendering";
6
+ import { matchRoute } from "../src/routing/router";
7
+ import { scanRoutes } from "../src/routing/scanner";
3
8
 
4
9
  function makeMatched(path: string, filePath: string, params = {}) {
5
10
  return {
@@ -122,4 +127,116 @@ describe("Streaming SSR", () => {
122
127
  expect(json.pattern).toBe("/nav");
123
128
  expect(json.data).toBeDefined();
124
129
  });
130
+
131
+ test("state JSON escapes </script> in data (XSS)", async () => {
132
+ const evil = "</script><script>alert(1)</script>";
133
+ const src = [
134
+ "export const load = async () => ({ evil })",
135
+ "const evil = " + JSON.stringify(evil),
136
+ 'export default () => "<div>ok</div>"',
137
+ ].join(";\n");
138
+ const matched = makeMatched(
139
+ "/xss",
140
+ `data:text/javascript,${encodeURIComponent(src)}`,
141
+ );
142
+
143
+ const res = await renderRoute(matched, new Request("http://localhost/xss"));
144
+ const html = await res.text();
145
+
146
+ const tagStart = html.indexOf('<script id="__grimoire_state__"');
147
+ expect(tagStart).toBeGreaterThan(-1);
148
+ const payloadStart = html.indexOf(">", tagStart) + 1;
149
+ const payloadEnd = html.indexOf("</script>", payloadStart);
150
+ const payload = html.slice(payloadStart, payloadEnd);
151
+
152
+ // no literal closing tag inside the JSON payload
153
+ expect(payload).not.toContain("</script>");
154
+ // `<` escaped as \u003c — JSON.parse decodes it back
155
+ expect(payload).toContain("\\u003c/script");
156
+ const parsed = JSON.parse(payload);
157
+ expect(parsed.data.evil).toBe(evil);
158
+ });
159
+ });
160
+
161
+ describe("streamed promises (deferred data)", () => {
162
+ let root: string;
163
+
164
+ beforeAll(async () => {
165
+ root = join(tmpdir(), `grimoire-defer-${Date.now()}`);
166
+ await mkdir(root, { recursive: true });
167
+ });
168
+
169
+ afterAll(async () => {
170
+ await rm(root, { recursive: true });
171
+ });
172
+
173
+ async function readChunks(res: Response): Promise<string[]> {
174
+ const reader = res.body!.getReader();
175
+ const chunks: string[] = [];
176
+ while (true) {
177
+ const { done, value } = await reader.read();
178
+ if (done) break;
179
+ chunks.push(String(value));
180
+ }
181
+ return chunks;
182
+ }
183
+
184
+ async function setup(name: string, serverSrc: string): Promise<string[]> {
185
+ // unique dir per test — Bun caches modules by resolved path
186
+ const dir = join(root, name);
187
+ await mkdir(dir, { recursive: true });
188
+ await writeFile(join(dir, "+page.server.ts"), serverSrc);
189
+ await writeFile(
190
+ join(dir, "+page.tsx"),
191
+ 'export default function P({ data }) { return <div>{data.fast}{String(data.slow)}{String(data.boom)}</div>; }',
192
+ );
193
+ const tree = await scanRoutes(dir);
194
+ const matched = matchRoute(tree, new URL("http://localhost/"));
195
+ const res = await renderRoute(matched!, new Request("http://localhost/"));
196
+ return readChunks(res);
197
+ }
198
+
199
+ test("slow promise flushes after the document shell", async () => {
200
+ const chunks = await setup(
201
+ "slow",
202
+ [
203
+ "export async function load() {",
204
+ " return {",
205
+ ' fast: "now",',
206
+ ' slow: new Promise((r) => setTimeout(() => r("late"), 30)),',
207
+ " };",
208
+ "}",
209
+ ].join("\n"),
210
+ );
211
+ const all = chunks.join("");
212
+
213
+ // state payload marks the field as deferred
214
+ expect(all).toContain('"__deferred":"gd-0"');
215
+ // the shell flushed before the promise settled
216
+ const shell = chunks.find((c) => c.includes("__grimoire_state__"))!;
217
+ expect(shell).not.toContain('"late"');
218
+ // a later chunk carries the self-contained patch script
219
+ const late = chunks.find((c) => c.includes("grimoire:deferred"));
220
+ expect(late).toBeDefined();
221
+ expect(late).toContain('"late"');
222
+ expect(late).toContain("__grimoire_state__");
223
+ expect(late).toContain('data["slow"]');
224
+ });
225
+
226
+ test("rejected promise emits error detail and null value", async () => {
227
+ const all = (
228
+ await setup(
229
+ "reject",
230
+ [
231
+ "export async function load() {",
232
+ " const boom = Promise.reject(new Error('nope'));",
233
+ " boom.catch(() => {});",
234
+ " return { boom };",
235
+ "}",
236
+ ].join("\n"),
237
+ )
238
+ ).join("");
239
+ expect(all).toContain("error:true");
240
+ expect(all).toContain('data["boom"]');
241
+ });
125
242
  });
@@ -80,5 +80,8 @@ function route(filePath: string, path: string): RouteFile {
80
80
  clientPath: filePath,
81
81
  type: "page",
82
82
  paramNames: [],
83
+ optionalParamNames: [],
84
+ restParamNames: [],
85
+ paramMatchers: {},
83
86
  };
84
87
  }
@@ -81,6 +81,13 @@ describe("buildParams", () => {
81
81
  const result = buildParams(["slug"]);
82
82
  expect(result).toContain("slug: string;");
83
83
  });
84
+
85
+ test("optional params are typed string | undefined", () => {
86
+ const result = buildParams(["slug"], ["lang"], ["rest"]);
87
+ expect(result).toContain("slug: string;");
88
+ expect(result).toContain("lang: string | undefined;");
89
+ expect(result).toContain("rest: string;");
90
+ });
84
91
  });
85
92
 
86
93
  // ---------------------------------------------------------------------------
@@ -94,7 +101,9 @@ function makeRouteFile(
94
101
  path: "/",
95
102
  clientPath: "/src/routes/+page.tsx",
96
103
  paramNames: [],
104
+ optionalParamNames: [],
97
105
  restParamNames: [],
106
+ paramMatchers: {},
98
107
  ...overrides,
99
108
  };
100
109
  }
@@ -109,6 +118,7 @@ describe("groupByDirectory", () => {
109
118
  layouts: [],
110
119
  servers: [],
111
120
  errors: [],
121
+ paramMatcherFiles: [],
112
122
  };
113
123
  const groups = groupByDirectory(tree);
114
124
  expect(groups.size).toBe(0);
@@ -131,6 +141,7 @@ describe("groupByDirectory", () => {
131
141
  layouts: [],
132
142
  servers: [],
133
143
  errors: [],
144
+ paramMatcherFiles: [],
134
145
  };
135
146
  const groups = groupByDirectory(tree);
136
147
  expect(groups.size).toBe(1);
@@ -152,6 +163,7 @@ describe("groupByDirectory", () => {
152
163
  ],
153
164
  servers: [],
154
165
  errors: [],
166
+ paramMatcherFiles: [],
155
167
  };
156
168
  const groups = groupByDirectory(tree);
157
169
  expect(groups.size).toBe(1);
@@ -171,6 +183,7 @@ describe("groupByDirectory", () => {
171
183
  }),
172
184
  ],
173
185
  errors: [],
186
+ paramMatcherFiles: [],
174
187
  };
175
188
  const groups = groupByDirectory(tree);
176
189
  expect(groups.size).toBe(1);
@@ -211,6 +224,7 @@ describe("groupByDirectory", () => {
211
224
  layouts: [],
212
225
  servers: [],
213
226
  errors: [],
227
+ paramMatcherFiles: [],
214
228
  };
215
229
  const groups = groupByDirectory(tree);
216
230
  const group = groups.values().next().value!;
@@ -229,6 +243,7 @@ describe("groupByDirectory", () => {
229
243
  layouts: [],
230
244
  servers: [],
231
245
  errors: [],
246
+ paramMatcherFiles: [],
232
247
  };
233
248
  const groups = groupByDirectory(tree);
234
249
  expect(groups.size).toBe(1);