@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.
- package/.grimoire/_routes.ts +4 -0
- package/README.md +174 -174
- package/package.json +3 -3
- package/public/__grimoire__/client.js +55 -0
- package/public/__grimoire__/hydrate.js +63 -0
- package/src/client/csrf.ts +47 -0
- package/src/client/enhance.ts +5 -0
- package/src/client/router.ts +622 -551
- package/src/rendering/hydrate.ts +159 -159
- package/src/rendering/index.ts +599 -577
- package/src/routing/scanner.ts +1 -1
- package/src/server/coordinator.ts +19 -7
- package/src/server/index.ts +30 -18
- package/test/client-csrf.test.ts +61 -0
- package/test/client-router.test.ts +71 -0
- package/test/streaming.test.ts +39 -0
package/README.md
CHANGED
|
@@ -1,174 +1,174 @@
|
|
|
1
|
-
# @sigil-dev/grimoire
|
|
2
|
-
|
|
3
|
-
Full-stack server framework for [Sigil](https://git.cane1712.dev/sigil/sigil).
|
|
4
|
-
Heavily inspired by SvelteKit. Most of [its documentation](https://svelte.dev/docs/kit/introduction) applies here
|
|
5
|
-
|
|
6
|
-
## Quick start
|
|
7
|
-
|
|
8
|
-
```sh
|
|
9
|
-
bun i -g @sigil-dev/cli
|
|
10
|
-
sigil create
|
|
11
|
-
```
|
|
12
|
-
|
|
13
|
-
## Route files
|
|
14
|
-
|
|
15
|
-
Place files in /src/routes.
|
|
16
|
-
|
|
17
|
-
| File | Purpose |
|
|
18
|
-
|---|---|
|
|
19
|
-
| `+page.tsx | index.tsx | routeName.tsx` | Page |
|
|
20
|
-
| `+page.server.ts` | Server data passed to page / form actions |
|
|
21
|
-
| `+layout.tsx` | Page layout |
|
|
22
|
-
| `+layout.server.ts` | Layout-level `load` |
|
|
23
|
-
| `+server.ts` | API route (raw `Request → Response`) |
|
|
24
|
-
| `+error.tsx` | Error boundary page |
|
|
25
|
-
| `hooks.index.ts` | Global request middleware (project root) |
|
|
26
|
-
|
|
27
|
-
`/routes/about/index.tsx`, `/routes/about/+page.tsx` and `/routes/about.tsx` all work and all do the same thing.
|
|
28
|
-
For path parameters use square brackets. `src/routes/posts/[slug]/+page.tsx` → `/posts/:slug`.
|
|
29
|
-
|
|
30
|
-
## Loading data
|
|
31
|
-
|
|
32
|
-
```ts
|
|
33
|
-
// src/routes/posts/[slug]/+page.server.ts
|
|
34
|
-
import { error } from "@sigil-dev/grimoire";
|
|
35
|
-
import type { TypedLoadContext } from "@sigil-dev/grimoire";
|
|
36
|
-
|
|
37
|
-
export async function load({ params }: TypedLoadContext<{ slug: string }>) {
|
|
38
|
-
const post = await db.posts.findBySlug(params.slug);
|
|
39
|
-
if (!post) throw error(404, "Post not found");
|
|
40
|
-
return { post }; // → page receives { data: { post }, params }
|
|
41
|
-
}
|
|
42
|
-
```
|
|
43
|
-
|
|
44
|
-
The return value is passed as the `data` prop to the matching `+page.tsx` component.
|
|
45
|
-
|
|
46
|
-
## Form actions
|
|
47
|
-
|
|
48
|
-
Export HTTP method handlers alongside `load`:
|
|
49
|
-
|
|
50
|
-
```ts
|
|
51
|
-
// src/routes/login/+page.server.ts
|
|
52
|
-
import { fail, redirect } from "@sigil-dev/grimoire";
|
|
53
|
-
|
|
54
|
-
export async function POST({ request }) {
|
|
55
|
-
const data = await request.formData();
|
|
56
|
-
const user = await auth.login(data.get("email"), data.get("password"));
|
|
57
|
-
if (!user) return fail(400, { error: "Invalid credentials" });
|
|
58
|
-
throw redirect(303, "/dashboard");
|
|
59
|
-
}
|
|
60
|
-
```
|
|
61
|
-
|
|
62
|
-
Use `enhance` with the `use` prop on the client for fetch-based submission without a full page reload:
|
|
63
|
-
> This is jank and will likely be reworked.
|
|
64
|
-
|
|
65
|
-
```tsx
|
|
66
|
-
// src/routes/login/+page.tsx
|
|
67
|
-
import { enhance } from "@sigil-dev/grimoire/client";
|
|
68
|
-
|
|
69
|
-
export default function LoginPage() {
|
|
70
|
-
const errors = $state({});
|
|
71
|
-
|
|
72
|
-
return (
|
|
73
|
-
<form use={[enhance, { onFail: (data) => errors.set(data) }]}>
|
|
74
|
-
<input name="email" />
|
|
75
|
-
<input name="password" type="password" />
|
|
76
|
-
<button>Log in</button>
|
|
77
|
-
</form>
|
|
78
|
-
);
|
|
79
|
-
}
|
|
80
|
-
```
|
|
81
|
-
|
|
82
|
-
## Error handling
|
|
83
|
-
|
|
84
|
-
`error(status, message)` can be thrown from any `load` function or action. Grimoire renders the closest `+error.tsx` if one exists, otherwise falls back to a plain-text response.
|
|
85
|
-
|
|
86
|
-
```tsx
|
|
87
|
-
// src/routes/+error.tsx
|
|
88
|
-
export default function ErrorPage({ status, message }: { status: number; message: string }) {
|
|
89
|
-
return (
|
|
90
|
-
<html>
|
|
91
|
-
<body>
|
|
92
|
-
<h1>{status}</h1>
|
|
93
|
-
<p>{message}</p>
|
|
94
|
-
</body>
|
|
95
|
-
</html>
|
|
96
|
-
);
|
|
97
|
-
}
|
|
98
|
-
```
|
|
99
|
-
|
|
100
|
-
## API routes
|
|
101
|
-
|
|
102
|
-
```ts
|
|
103
|
-
// src/routes/api/items/+server.ts
|
|
104
|
-
export async function GET({ url }) {
|
|
105
|
-
const items = await db.items.list();
|
|
106
|
-
return Response.json(items);
|
|
107
|
-
}
|
|
108
|
-
|
|
109
|
-
export async function POST({ request }) {
|
|
110
|
-
const body = await request.json();
|
|
111
|
-
const item = await db.items.create(body);
|
|
112
|
-
return Response.json(item, { status: 201 });
|
|
113
|
-
}
|
|
114
|
-
```
|
|
115
|
-
|
|
116
|
-
## Layouts
|
|
117
|
-
|
|
118
|
-
```tsx
|
|
119
|
-
// src/routes/+layout.tsx
|
|
120
|
-
import { Head } from "@sigil-dev/grimoire";
|
|
121
|
-
|
|
122
|
-
export default function Layout({ children }) {
|
|
123
|
-
return (
|
|
124
|
-
<html>
|
|
125
|
-
<Head><title>My App</title></Head>
|
|
126
|
-
<body>{children}</body>
|
|
127
|
-
</html>
|
|
128
|
-
);
|
|
129
|
-
}
|
|
130
|
-
```
|
|
131
|
-
|
|
132
|
-
## Hooks (middleware)
|
|
133
|
-
|
|
134
|
-
```ts
|
|
135
|
-
// hooks.index.ts (project root)
|
|
136
|
-
import type { Handle } from "@sigil-dev/grimoire/hooks";
|
|
137
|
-
|
|
138
|
-
export const handle: Handle = async ({ event, resolve }) => {
|
|
139
|
-
event.locals.user = await getUser(event.request);
|
|
140
|
-
return resolve(event);
|
|
141
|
-
};
|
|
142
|
-
```
|
|
143
|
-
|
|
144
|
-
## Configuration
|
|
145
|
-
|
|
146
|
-
```ts
|
|
147
|
-
import { defineConfig } from "@sigil-dev/grimoire";
|
|
148
|
-
|
|
149
|
-
export default defineConfig({
|
|
150
|
-
port: 3000,
|
|
151
|
-
host: "localhost",
|
|
152
|
-
routes: "src/routes", // default
|
|
153
|
-
plugins: [],
|
|
154
|
-
});
|
|
155
|
-
```
|
|
156
|
-
|
|
157
|
-
## Helpers
|
|
158
|
-
|
|
159
|
-
| Import | Description |
|
|
160
|
-
|---|---|
|
|
161
|
-
| `error(status, message)` | Throw an HTTP error from `load` or an action |
|
|
162
|
-
| `fail(status, data)` | Return validation errors from an action |
|
|
163
|
-
| `redirect(status, location)` | Throw a redirect from `load` or an action |
|
|
164
|
-
| `sequence(...handles)` | Compose multiple `Handle` middleware functions |
|
|
165
|
-
|
|
166
|
-
## Security headers
|
|
167
|
-
|
|
168
|
-
```ts
|
|
169
|
-
import { securityHeaders } from "@sigil-dev/grimoire/headers";
|
|
170
|
-
|
|
171
|
-
// use as a Handle in hooks.index.ts, or compose with sequence()
|
|
172
|
-
```
|
|
173
|
-
|
|
174
|
-
`securityHeaders()` returns a `Handle` that sets CSP, HSTS, X-Frame-Options, and related headers on every response.
|
|
1
|
+
# @sigil-dev/grimoire
|
|
2
|
+
|
|
3
|
+
Full-stack server framework for [Sigil](https://git.cane1712.dev/sigil/sigil).
|
|
4
|
+
Heavily inspired by SvelteKit. Most of [its documentation](https://svelte.dev/docs/kit/introduction) applies here
|
|
5
|
+
|
|
6
|
+
## Quick start
|
|
7
|
+
|
|
8
|
+
```sh
|
|
9
|
+
bun i -g @sigil-dev/cli
|
|
10
|
+
sigil create
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
## Route files
|
|
14
|
+
|
|
15
|
+
Place files in /src/routes.
|
|
16
|
+
|
|
17
|
+
| File | Purpose |
|
|
18
|
+
|---|---|
|
|
19
|
+
| `+page.tsx | index.tsx | routeName.tsx` | Page |
|
|
20
|
+
| `+page.server.ts` | Server data passed to page / form actions |
|
|
21
|
+
| `+layout.tsx` | Page layout |
|
|
22
|
+
| `+layout.server.ts` | Layout-level `load` |
|
|
23
|
+
| `+server.ts` | API route (raw `Request → Response`) |
|
|
24
|
+
| `+error.tsx` | Error boundary page |
|
|
25
|
+
| `hooks.index.ts` | Global request middleware (project root) |
|
|
26
|
+
|
|
27
|
+
`/routes/about/index.tsx`, `/routes/about/+page.tsx` and `/routes/about.tsx` all work and all do the same thing.
|
|
28
|
+
For path parameters use square brackets. `src/routes/posts/[slug]/+page.tsx` → `/posts/:slug`.
|
|
29
|
+
|
|
30
|
+
## Loading data
|
|
31
|
+
|
|
32
|
+
```ts
|
|
33
|
+
// src/routes/posts/[slug]/+page.server.ts
|
|
34
|
+
import { error } from "@sigil-dev/grimoire";
|
|
35
|
+
import type { TypedLoadContext } from "@sigil-dev/grimoire";
|
|
36
|
+
|
|
37
|
+
export async function load({ params }: TypedLoadContext<{ slug: string }>) {
|
|
38
|
+
const post = await db.posts.findBySlug(params.slug);
|
|
39
|
+
if (!post) throw error(404, "Post not found");
|
|
40
|
+
return { post }; // → page receives { data: { post }, params }
|
|
41
|
+
}
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
The return value is passed as the `data` prop to the matching `+page.tsx` component.
|
|
45
|
+
|
|
46
|
+
## Form actions
|
|
47
|
+
|
|
48
|
+
Export HTTP method handlers alongside `load`:
|
|
49
|
+
|
|
50
|
+
```ts
|
|
51
|
+
// src/routes/login/+page.server.ts
|
|
52
|
+
import { fail, redirect } from "@sigil-dev/grimoire";
|
|
53
|
+
|
|
54
|
+
export async function POST({ request }) {
|
|
55
|
+
const data = await request.formData();
|
|
56
|
+
const user = await auth.login(data.get("email"), data.get("password"));
|
|
57
|
+
if (!user) return fail(400, { error: "Invalid credentials" });
|
|
58
|
+
throw redirect(303, "/dashboard");
|
|
59
|
+
}
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
Use `enhance` with the `use` prop on the client for fetch-based submission without a full page reload:
|
|
63
|
+
> This is jank and will likely be reworked.
|
|
64
|
+
|
|
65
|
+
```tsx
|
|
66
|
+
// src/routes/login/+page.tsx
|
|
67
|
+
import { enhance } from "@sigil-dev/grimoire/client";
|
|
68
|
+
|
|
69
|
+
export default function LoginPage() {
|
|
70
|
+
const errors = $state({});
|
|
71
|
+
|
|
72
|
+
return (
|
|
73
|
+
<form use={[enhance, { onFail: (data) => errors.set(data) }]}>
|
|
74
|
+
<input name="email" />
|
|
75
|
+
<input name="password" type="password" />
|
|
76
|
+
<button>Log in</button>
|
|
77
|
+
</form>
|
|
78
|
+
);
|
|
79
|
+
}
|
|
80
|
+
```
|
|
81
|
+
|
|
82
|
+
## Error handling
|
|
83
|
+
|
|
84
|
+
`error(status, message)` can be thrown from any `load` function or action. Grimoire renders the closest `+error.tsx` if one exists, otherwise falls back to a plain-text response.
|
|
85
|
+
|
|
86
|
+
```tsx
|
|
87
|
+
// src/routes/+error.tsx
|
|
88
|
+
export default function ErrorPage({ status, message }: { status: number; message: string }) {
|
|
89
|
+
return (
|
|
90
|
+
<html>
|
|
91
|
+
<body>
|
|
92
|
+
<h1>{status}</h1>
|
|
93
|
+
<p>{message}</p>
|
|
94
|
+
</body>
|
|
95
|
+
</html>
|
|
96
|
+
);
|
|
97
|
+
}
|
|
98
|
+
```
|
|
99
|
+
|
|
100
|
+
## API routes
|
|
101
|
+
|
|
102
|
+
```ts
|
|
103
|
+
// src/routes/api/items/+server.ts
|
|
104
|
+
export async function GET({ url }) {
|
|
105
|
+
const items = await db.items.list();
|
|
106
|
+
return Response.json(items);
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
export async function POST({ request }) {
|
|
110
|
+
const body = await request.json();
|
|
111
|
+
const item = await db.items.create(body);
|
|
112
|
+
return Response.json(item, { status: 201 });
|
|
113
|
+
}
|
|
114
|
+
```
|
|
115
|
+
|
|
116
|
+
## Layouts
|
|
117
|
+
|
|
118
|
+
```tsx
|
|
119
|
+
// src/routes/+layout.tsx
|
|
120
|
+
import { Head } from "@sigil-dev/grimoire";
|
|
121
|
+
|
|
122
|
+
export default function Layout({ children }) {
|
|
123
|
+
return (
|
|
124
|
+
<html>
|
|
125
|
+
<Head><title>My App</title></Head>
|
|
126
|
+
<body>{children}</body>
|
|
127
|
+
</html>
|
|
128
|
+
);
|
|
129
|
+
}
|
|
130
|
+
```
|
|
131
|
+
|
|
132
|
+
## Hooks (middleware)
|
|
133
|
+
|
|
134
|
+
```ts
|
|
135
|
+
// hooks.index.ts (project root)
|
|
136
|
+
import type { Handle } from "@sigil-dev/grimoire/hooks";
|
|
137
|
+
|
|
138
|
+
export const handle: Handle = async ({ event, resolve }) => {
|
|
139
|
+
event.locals.user = await getUser(event.request);
|
|
140
|
+
return resolve(event);
|
|
141
|
+
};
|
|
142
|
+
```
|
|
143
|
+
|
|
144
|
+
## Configuration
|
|
145
|
+
|
|
146
|
+
```ts
|
|
147
|
+
import { defineConfig } from "@sigil-dev/grimoire";
|
|
148
|
+
|
|
149
|
+
export default defineConfig({
|
|
150
|
+
port: 3000,
|
|
151
|
+
host: "localhost",
|
|
152
|
+
routes: "src/routes", // default
|
|
153
|
+
plugins: [],
|
|
154
|
+
});
|
|
155
|
+
```
|
|
156
|
+
|
|
157
|
+
## Helpers
|
|
158
|
+
|
|
159
|
+
| Import | Description |
|
|
160
|
+
|---|---|
|
|
161
|
+
| `error(status, message)` | Throw an HTTP error from `load` or an action |
|
|
162
|
+
| `fail(status, data)` | Return validation errors from an action |
|
|
163
|
+
| `redirect(status, location)` | Throw a redirect from `load` or an action |
|
|
164
|
+
| `sequence(...handles)` | Compose multiple `Handle` middleware functions |
|
|
165
|
+
|
|
166
|
+
## Security headers
|
|
167
|
+
|
|
168
|
+
```ts
|
|
169
|
+
import { securityHeaders } from "@sigil-dev/grimoire/headers";
|
|
170
|
+
|
|
171
|
+
// use as a Handle in hooks.index.ts, or compose with sequence()
|
|
172
|
+
```
|
|
173
|
+
|
|
174
|
+
`securityHeaders()` returns a `Handle` that sets CSP, HSTS, X-Frame-Options, and related headers on every response.
|
package/package.json
CHANGED
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
"module": "index.ts",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"private": false,
|
|
7
|
-
"version": "0.9.
|
|
7
|
+
"version": "0.9.7",
|
|
8
8
|
"exports": {
|
|
9
9
|
".": "./index.ts",
|
|
10
10
|
"./server": "./server.ts",
|
|
@@ -23,8 +23,8 @@
|
|
|
23
23
|
"test": "bun test"
|
|
24
24
|
},
|
|
25
25
|
"dependencies": {
|
|
26
|
-
"@sigil-dev/compiler": "0.9.
|
|
27
|
-
"@sigil-dev/runtime": "0.9.
|
|
26
|
+
"@sigil-dev/compiler": "0.9.7",
|
|
27
|
+
"@sigil-dev/runtime": "0.9.7",
|
|
28
28
|
"vite": "^8.0.16"
|
|
29
29
|
},
|
|
30
30
|
"peerDependencies": {
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
// .grimoire/_routes.ts
|
|
2
|
+
var routes = {};
|
|
3
|
+
|
|
4
|
+
// src/client-router.ts
|
|
5
|
+
var routeMap = {};
|
|
6
|
+
async function navigate(path) {
|
|
7
|
+
const res = await fetch(path, { headers: { "x-grimoire-navigate": "1" } });
|
|
8
|
+
const json = await res.json();
|
|
9
|
+
console.log("navigate response:", json);
|
|
10
|
+
const { data, params, pattern, head } = json;
|
|
11
|
+
const Page = routeMap[pattern];
|
|
12
|
+
if (!Page) {
|
|
13
|
+
window.location.href = path;
|
|
14
|
+
return;
|
|
15
|
+
}
|
|
16
|
+
const node = Page({ ...data, params });
|
|
17
|
+
const slot = document.getElementById("grimoire-page");
|
|
18
|
+
if (!slot)
|
|
19
|
+
return;
|
|
20
|
+
slot.replaceChildren(node);
|
|
21
|
+
updateHead(head);
|
|
22
|
+
history.pushState({}, "", path);
|
|
23
|
+
window.scrollTo(0, 0);
|
|
24
|
+
}
|
|
25
|
+
function initRouter(routes2) {
|
|
26
|
+
routeMap = routes2;
|
|
27
|
+
document.addEventListener("click", handleClick);
|
|
28
|
+
window.addEventListener("popstate", () => navigate(location.pathname));
|
|
29
|
+
}
|
|
30
|
+
function updateHead(headHtml) {
|
|
31
|
+
document.querySelectorAll("[data-grimoire-head]").forEach((el) => el.remove());
|
|
32
|
+
if (!headHtml)
|
|
33
|
+
return;
|
|
34
|
+
const tmp = document.createElement("head");
|
|
35
|
+
tmp.innerHTML = headHtml;
|
|
36
|
+
for (const el of Array.from(tmp.children)) {
|
|
37
|
+
el.dataset.grimoireHead = "1";
|
|
38
|
+
document.head.appendChild(el);
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
function handleClick(e) {
|
|
42
|
+
const a = e.target.closest("a");
|
|
43
|
+
if (!a)
|
|
44
|
+
return;
|
|
45
|
+
const href = a.getAttribute("href");
|
|
46
|
+
if (!href)
|
|
47
|
+
return;
|
|
48
|
+
if (/^(https?:\/\/|\/\/|#|mailto:|tel:)/.test(href))
|
|
49
|
+
return;
|
|
50
|
+
e.preventDefault();
|
|
51
|
+
navigate(href);
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
// src/client.ts
|
|
55
|
+
initRouter(routes);
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
// .grimoire/_routes.ts
|
|
2
|
+
var routes = {};
|
|
3
|
+
|
|
4
|
+
// src/client-router.ts
|
|
5
|
+
var routeMap = {};
|
|
6
|
+
async function navigate(path) {
|
|
7
|
+
const res = await fetch(path, { headers: { "x-grimoire-navigate": "1" } });
|
|
8
|
+
const json = await res.json();
|
|
9
|
+
console.log("navigate response:", json);
|
|
10
|
+
const { data, params, pattern, head } = json;
|
|
11
|
+
const Page = routeMap[pattern];
|
|
12
|
+
if (!Page) {
|
|
13
|
+
window.location.href = path;
|
|
14
|
+
return;
|
|
15
|
+
}
|
|
16
|
+
const node = Page({ ...data, params });
|
|
17
|
+
const slot = document.getElementById("grimoire-page");
|
|
18
|
+
if (!slot)
|
|
19
|
+
return;
|
|
20
|
+
slot.replaceChildren(node);
|
|
21
|
+
updateHead(head);
|
|
22
|
+
history.pushState({}, "", path);
|
|
23
|
+
window.scrollTo(0, 0);
|
|
24
|
+
}
|
|
25
|
+
function initRouter(routes2) {
|
|
26
|
+
routeMap = routes2;
|
|
27
|
+
document.addEventListener("click", handleClick);
|
|
28
|
+
window.addEventListener("popstate", () => navigate(location.pathname));
|
|
29
|
+
}
|
|
30
|
+
function updateHead(headHtml) {
|
|
31
|
+
document.querySelectorAll("[data-grimoire-head]").forEach((el) => el.remove());
|
|
32
|
+
if (!headHtml)
|
|
33
|
+
return;
|
|
34
|
+
const tmp = document.createElement("head");
|
|
35
|
+
tmp.innerHTML = headHtml;
|
|
36
|
+
for (const el of Array.from(tmp.children)) {
|
|
37
|
+
el.dataset.grimoireHead = "1";
|
|
38
|
+
document.head.appendChild(el);
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
function handleClick(e) {
|
|
42
|
+
const a = e.target.closest("a");
|
|
43
|
+
if (!a)
|
|
44
|
+
return;
|
|
45
|
+
const href = a.getAttribute("href");
|
|
46
|
+
if (!href)
|
|
47
|
+
return;
|
|
48
|
+
if (/^(https?:\/\/|\/\/|#|mailto:|tel:)/.test(href))
|
|
49
|
+
return;
|
|
50
|
+
e.preventDefault();
|
|
51
|
+
navigate(href);
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
// src/hydrate.ts
|
|
55
|
+
var stateEl = document.getElementById("__grimoire_state__");
|
|
56
|
+
if (stateEl) {
|
|
57
|
+
const state = JSON.parse(stateEl.textContent);
|
|
58
|
+
const Page = routes[state.pattern];
|
|
59
|
+
if (Page) {
|
|
60
|
+
Page({ ...state.data, params: state.params });
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
initRouter(routes);
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* CSRF for forms the browser rendered.
|
|
3
|
+
*
|
|
4
|
+
* The server double-submits a token: the `_csrf` cookie, plus a hidden input
|
|
5
|
+
* it injects into every <form> in the SSR HTML (rendering/index.ts). A page
|
|
6
|
+
* reached by client-side navigation is rendered in the browser, so its forms
|
|
7
|
+
* never got that input and every POST from them was refused with 403.
|
|
8
|
+
*
|
|
9
|
+
* ensureCsrf copies the cookie's current token into a form just before it
|
|
10
|
+
* submits. Always overwriting the value also fixes forms that did get an input
|
|
11
|
+
* but are stale: a page opened later in another tab rotates the cookie.
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
export const CSRF_FIELD = "_csrf";
|
|
15
|
+
|
|
16
|
+
function cookieToken(): string | null {
|
|
17
|
+
const m = /(?:^|;\s*)_csrf=([^;]+)/.exec(document.cookie);
|
|
18
|
+
return m ? decodeURIComponent(m[1]) : null;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export function ensureCsrf(form: HTMLFormElement): void {
|
|
22
|
+
const token = cookieToken();
|
|
23
|
+
if (!token) return;
|
|
24
|
+
let input = form.querySelector<HTMLInputElement>(
|
|
25
|
+
`input[name="${CSRF_FIELD}"]`,
|
|
26
|
+
);
|
|
27
|
+
if (!input) {
|
|
28
|
+
input = document.createElement("input");
|
|
29
|
+
input.type = "hidden";
|
|
30
|
+
input.name = CSRF_FIELD;
|
|
31
|
+
input.setAttribute("data-grimoire-csrf", "");
|
|
32
|
+
form.prepend(input);
|
|
33
|
+
}
|
|
34
|
+
input.value = token;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* Native (non-enhanced) POST forms: a capture listener on the document runs
|
|
39
|
+
* before any handler on the form itself, so the token is in place for both
|
|
40
|
+
* the browser's own submission and anything that reads FormData.
|
|
41
|
+
*/
|
|
42
|
+
export function onSubmitEnsureCsrf(e: Event): void {
|
|
43
|
+
const form = e.target as HTMLFormElement | null;
|
|
44
|
+
if (form?.tagName !== "FORM") return;
|
|
45
|
+
if ((form.getAttribute("method") ?? "get").toLowerCase() !== "post") return;
|
|
46
|
+
ensureCsrf(form);
|
|
47
|
+
}
|
package/src/client/enhance.ts
CHANGED
|
@@ -13,6 +13,8 @@
|
|
|
13
13
|
* ...
|
|
14
14
|
* </form>
|
|
15
15
|
*/
|
|
16
|
+
import { ensureCsrf } from "./csrf.ts";
|
|
17
|
+
|
|
16
18
|
export interface EnhanceOptions {
|
|
17
19
|
/** URL to submit to (defaults to form's action) */
|
|
18
20
|
action?: string;
|
|
@@ -41,6 +43,9 @@ export function enhance(
|
|
|
41
43
|
async function handleSubmit(e: Event) {
|
|
42
44
|
e.preventDefault();
|
|
43
45
|
|
|
46
|
+
// client-rendered forms have no SSR-injected token; the server's CSRF
|
|
47
|
+
// check covers fetch submissions too
|
|
48
|
+
ensureCsrf(form);
|
|
44
49
|
const formData = new FormData(form);
|
|
45
50
|
const resolved =
|
|
46
51
|
action ?? form.getAttribute("action") ?? window.location.pathname;
|