@sigil-dev/grimoire 0.9.17 → 0.9.19

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/README.md CHANGED
@@ -1,174 +1,83 @@
1
1
  # @sigil-dev/grimoire
2
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
3
+ The full-stack framework for [Sigil](https://sigil.cane1712.dev): file-based routes, server `load` functions, form actions that work without JavaScript, streaming SSR, WebSockets and a plugin system. If you know SvelteKit, most of it will feel familiar.
7
4
 
8
5
  ```sh
9
6
  bun i -g @sigil-dev/cli
10
- sigil create
7
+ sigil create my-app && cd my-app && sigil dev
11
8
  ```
12
9
 
13
- ## Route files
14
-
15
- Place files in /src/routes.
10
+ ## Routes
16
11
 
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) |
12
+ Files in `src/routes` are pages and endpoints:
26
13
 
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`.
14
+ | File | What it is |
15
+ | --- | --- |
16
+ | `+page.tsx` | A page (`about.tsx` and `about/index.tsx` work too) |
17
+ | `+page.server.ts` | Its `load` and form actions, server only |
18
+ | `+layout.tsx`, `+layout.server.ts` | A layout and its data |
19
+ | `+server.ts` | An endpoint: `GET`, `POST`, … return a `Response` |
20
+ | `+error.tsx` | The error page for everything below it |
21
+ | `hooks.server.ts` | Per-request middleware, at the project root |
29
22
 
30
- ## Loading data
23
+ `[slug]` is a parameter, `[[...rest]]` an optional catch-all.
31
24
 
32
25
  ```ts
33
26
  // src/routes/posts/[slug]/+page.server.ts
34
- import { error } from "@sigil-dev/grimoire";
35
- import type { TypedLoadContext } from "@sigil-dev/grimoire";
27
+ import { error, fail, redirect } from "@sigil-dev/grimoire";
36
28
 
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 }
29
+ export async function load({ params }) {
30
+ const post = await db.posts.findFirst({ where: { slug: params.slug } });
31
+ if (!post) throw error(404, "Post not found");
32
+ return { post }; // the page's `data` prop
41
33
  }
42
- ```
43
-
44
- The return value is passed as the `data` prop to the matching `+page.tsx` component.
45
-
46
- ## Form actions
47
34
 
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");
35
+ export async function comment({ request, locals }) {
36
+ const form = await request.formData(); // a <form method="POST" action="?/comment">
37
+ if (!form.get("body")) return fail(400, { error: "Say something" }); // the page's `form` prop
38
+ await saveComment(form, locals.user);
39
+ throw redirect(303, "/posts");
59
40
  }
60
41
  ```
61
42
 
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
43
  ```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 });
44
+ // src/routes/posts/[slug]/+page.tsx
45
+ export default function Post({ data, form }) {
46
+ return (
47
+ <article>
48
+ <h1>{data.post.title}</h1>
49
+ <form method="POST" action="?/comment">
50
+ <textarea name="body" />
51
+ {form?.error && <p>{form.error}</p>}
52
+ <button>Comment</button>
53
+ </form>
54
+ </article>
55
+ );
113
56
  }
114
57
  ```
115
58
 
116
- ## Layouts
59
+ Every form post carries a CSRF token; Grimoire adds it to rendered forms for you.
117
60
 
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
- ```
61
+ ## Batteries
131
62
 
132
- ## Hooks (middleware)
63
+ These are separate packages, so an app only carries what it uses:
133
64
 
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
- ```
65
+ - [`@sigil-dev/tome`](https://www.npmjs.com/package/@sigil-dev/tome): schema, typed queries, validation and migrations
66
+ - [`@sigil-dev/auth`](https://www.npmjs.com/package/@sigil-dev/auth): sign-up, sign-in, sessions and OAuth
67
+ - [`@sigil-dev/plugin-sql`](https://www.npmjs.com/package/@sigil-dev/plugin-sql): the database connection
68
+ - [`@sigil-dev/plugin-jobs`](https://www.npmjs.com/package/@sigil-dev/plugin-jobs): background jobs and schedules
69
+ - `plugin-health`, `plugin-sentry`, `plugin-namepool`: health checks, error tracking, worker names
143
70
 
144
71
  ## Configuration
145
72
 
146
73
  ```ts
74
+ // sigil.config.ts
147
75
  import { defineConfig } from "@sigil-dev/grimoire";
148
76
 
149
77
  export default defineConfig({
150
- port: 3000,
151
- host: "localhost",
152
- routes: "src/routes", // default
153
- plugins: [],
78
+ port: 3000,
79
+ plugins: [],
154
80
  });
155
81
  ```
156
82
 
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.
83
+ **Docs:** [sigil.cane1712.dev/docs](https://sigil.cane1712.dev/docs). Start with the [tutorial](https://sigil.cane1712.dev/docs/tutorial), or go to [routing](https://sigil.cane1712.dev/docs/reference/routing), [loading](https://sigil.cane1712.dev/docs/reference/loading), [actions](https://sigil.cane1712.dev/docs/reference/actions), [hooks](https://sigil.cane1712.dev/docs/reference/hooks) and [deploying](https://sigil.cane1712.dev/docs/guides/deploying).
package/index.ts CHANGED
@@ -18,6 +18,13 @@ export type {
18
18
  RequestEvent,
19
19
  ResolveFunction,
20
20
  } from "./src/server/hooks";
21
+ export {
22
+ type CachedFn,
23
+ type CachedOptions,
24
+ cached,
25
+ cachedBy,
26
+ } from "./src/server/cached";
27
+ export { clientAddress } from "./src/server/client-address";
21
28
  export { createHooks, sequence } from "./src/server/hooks";
22
29
  export type {
23
30
  BuiltinWorkerMode,
package/package.json CHANGED
@@ -1,10 +1,17 @@
1
1
  {
2
2
  "name": "@sigil-dev/grimoire",
3
- "description": "Full stack web framework using Sigil",
3
+ "description": "Full-stack framework for Sigil on Bun: file routes, SSR, load functions, form actions, hooks and plugins",
4
+ "license": "MIT",
5
+ "homepage": "https://sigil.cane1712.dev/docs",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://git.cane1712.dev/sigil/sigil.git",
9
+ "directory": "packages/grimoire"
10
+ },
4
11
  "module": "index.ts",
5
12
  "type": "module",
6
13
  "private": false,
7
- "version": "0.9.17",
14
+ "version": "0.9.19",
8
15
  "exports": {
9
16
  ".": "./index.ts",
10
17
  "./server": "./server.ts",
@@ -23,8 +30,8 @@
23
30
  "test": "bun test"
24
31
  },
25
32
  "dependencies": {
26
- "@sigil-dev/compiler": "0.9.17",
27
- "@sigil-dev/runtime": "0.9.17",
33
+ "@sigil-dev/compiler": "0.9.19",
34
+ "@sigil-dev/runtime": "0.9.19",
28
35
  "vite": "^8.0.16"
29
36
  },
30
37
  "peerDependencies": {
@@ -24,7 +24,10 @@ export interface EnhanceOptions {
24
24
  * action returned.
25
25
  */
26
26
  onSuccess?: (result: { redirect: string; data?: unknown }) => void;
27
- /** Called when server returns fail() with validation data */
27
+ /**
28
+ * Called when the action returns fail(). The page has already been shown
29
+ * again with that data as its `form` prop, so most forms need no handler.
30
+ */
28
31
  onFail?: (data: Record<string, unknown>) => void;
29
32
  /** Called on network or unexpected errors, and for error() */
30
33
  onError?: (error: Error) => void;
@@ -114,13 +117,29 @@ export function enhance(
114
117
 
115
118
  const json = (await res.json()) as Outcome | Record<string, unknown>;
116
119
  if ("fail" in json && json.fail) {
117
- onFail?.((json as { data: Record<string, unknown> }).data);
120
+ const data = (json as { data: Record<string, unknown> }).data;
121
+ // the page that posted shows the failure as its `form` prop, as
122
+ // it would after a submission without JavaScript
123
+ if (
124
+ new URL(url, window.location.href).pathname ===
125
+ window.location.pathname
126
+ ) {
127
+ await (
128
+ globalThis as {
129
+ __grimoire_form__?: (form: unknown) => Promise<void>;
130
+ }
131
+ ).__grimoire_form__?.(data);
132
+ }
133
+ onFail?.(data);
118
134
  return;
119
135
  }
120
136
  if ("error" in json && json.error) {
121
137
  throw new Error(String((json as { message?: unknown }).message));
122
138
  }
123
- if (json.type === "success" || json.type === "redirect") {
139
+ if (
140
+ "type" in json &&
141
+ (json.type === "success" || json.type === "redirect")
142
+ ) {
124
143
  const outcome = json as { location: string; data?: unknown };
125
144
  if (reset) form.reset();
126
145
  onSuccess?.({ redirect: outcome.location, data: outcome.data });
@@ -82,6 +82,17 @@ let beforeNavigateCb: ((url: URL) => boolean | undefined) | null = null;
82
82
  let onNavigateCb: ((url: URL) => void) | null = null;
83
83
  let afterNavigateCb: ((url: URL) => void) | null = null;
84
84
 
85
+ /**
86
+ * Shows the page again with an enhanced form's failure as its `form` prop,
87
+ * which is what a submission without JavaScript gets from the server. The
88
+ * same page code then works either way.
89
+ */
90
+ export function showActionFailure(form: unknown): Promise<void> {
91
+ if (!lastState) return Promise.resolve();
92
+ lastState = { ...lastState, form };
93
+ return hmrRerender();
94
+ }
95
+
85
96
  export async function hmrRerender(): Promise<void> {
86
97
  if (!lastState) {
87
98
  location.reload();
@@ -372,10 +383,12 @@ let lastState: {
372
383
  layoutData: any[];
373
384
  params: any;
374
385
  pattern: string;
386
+ /** What the page's last failed action passed to fail(); cleared by navigation. */
387
+ form?: unknown;
375
388
  } | null = null;
376
389
 
377
390
  function buildRouteTree(state: typeof lastState, Page: PageComponent): any {
378
- const { data, layoutData, params, pattern } = state!;
391
+ const { data, layoutData, params, pattern, form } = state!;
379
392
  if (!Page) throw new Error(`no component for pattern ${pattern}`);
380
393
 
381
394
  const matchedLayouts = layoutList
@@ -388,7 +401,7 @@ function buildRouteTree(state: typeof lastState, Page: PageComponent): any {
388
401
  .sort((a, b) => a.path.length - b.path.length);
389
402
 
390
403
  let renderFn = () => {
391
- const pageNode = Page({ data, params });
404
+ const pageNode = Page({ data, params, form });
392
405
  const pageDiv = document.createElement("div");
393
406
  pageDiv.id = "grimoire-page";
394
407
  pageDiv.appendChild(pageNode);
@@ -700,11 +713,13 @@ export function initRouter(
700
713
  __grimoire_routes__?: Record<string, RouteEntry>;
701
714
  __grimoire_rerender__?: () => Promise<void>;
702
715
  __grimoire_navigate__?: (path: string, replace?: boolean) => void;
716
+ __grimoire_form__?: (form: unknown) => Promise<void>;
703
717
  __grimoire_hmr__?: HmrControl;
704
718
  };
705
719
  globals.__grimoire_routes__ = routeMap;
706
720
  globals.__grimoire_rerender__ = hmrRerender;
707
721
  globals.__grimoire_hmr__ = hmrControl;
722
+ globals.__grimoire_form__ = showActionFailure;
708
723
  globals.__grimoire_navigate__ = (path, replace) =>
709
724
  navigate(path, replace ?? false);
710
725
 
@@ -717,6 +732,7 @@ export function initRouter(
717
732
  layoutData: state.layoutData,
718
733
  params: state.params,
719
734
  pattern: state.pattern,
735
+ form: state.form,
720
736
  };
721
737
  if (Array.isArray(state.deps)) {
722
738
  setDeps(state.pattern, state.deps);
@@ -1,31 +1,30 @@
1
1
  import { mkdirSync } from "node:fs";
2
2
  import { join } from "node:path";
3
3
  import { log } from "../logger/instance";
4
+ import { clientDir } from "../server/client-dir";
4
5
 
5
6
  const logger = log.scope("runtime-bundle");
6
7
 
7
8
  export async function ensureRuntimeBundle(projectRoot: string): Promise<void> {
8
- const outDir = join(projectRoot, "public/__grimoire__");
9
+ const outDir = clientDir(projectRoot);
9
10
  mkdirSync(outDir, { recursive: true });
10
11
 
11
- // runtime
12
- const runtimeOut = join(outDir, "runtime.js");
13
- if (!(await Bun.file(runtimeOut).exists())) {
14
- logger.debug("bundling runtime...");
15
- const result = await Bun.build({
16
- entrypoints: [
17
- join(projectRoot, "node_modules/@sigil-dev/runtime/index.ts"),
18
- ],
19
- outdir: outDir,
20
- naming: "runtime.js",
21
- target: "browser",
22
- format: "esm",
23
- minify: false,
24
- });
25
- if (!result.success)
26
- logger.error("[sigil hmr] runtime bundle failed:", result.logs);
27
- else logger.debug("[sigil hmr] runtime bundled");
28
- }
12
+ // runtime: rebuilt on every start, since an existing file says nothing
13
+ // about whether @sigil-dev/runtime changed under it. It takes a few ms.
14
+ logger.debug("bundling runtime...");
15
+ const result = await Bun.build({
16
+ entrypoints: [
17
+ join(projectRoot, "node_modules/@sigil-dev/runtime/index.ts"),
18
+ ],
19
+ outdir: outDir,
20
+ naming: "runtime.js",
21
+ target: "browser",
22
+ format: "esm",
23
+ minify: false,
24
+ });
25
+ if (!result.success)
26
+ logger.error("[sigil hmr] runtime bundle failed:", result.logs);
27
+ else logger.debug("[sigil hmr] runtime bundled");
29
28
 
30
29
  // grimoire client
31
30
  const grimClientOut = join(outDir, "grimoire-client.js");
@@ -55,7 +55,7 @@ function formatData(data: unknown): string {
55
55
  const entries = Object.entries(data as Record<string, unknown>);
56
56
  const isFlat = entries.every(([, v]) => typeof v !== "object" || v === null);
57
57
  if (isFlat) {
58
- return ` ${entries.map(([k, v]) => `${colors.dim(`${k}=`)}${v}`).join(" ")}`;
58
+ return ` ${entries.map(([k, v]) => `${c.dim}${k}=${c.reset}${v}`).join(" ")}`;
59
59
  }
60
60
  // nested — indent but don't pretty-print the whole thing
61
61
  return `\n ${JSON.stringify(data).replace(/,/g, ", ")}`;
@@ -10,6 +10,7 @@ import type { RouteFile } from "../routing/scanner";
10
10
  import { isErrorResult } from "../sentinels/error.ts";
11
11
  import { isRedirectResult } from "../sentinels/redirect.ts";
12
12
  import { runWithContext } from "../server/context";
13
+ import { clientAddressOf } from "../server/client-address";
13
14
  import { runHook } from "../server/plugins";
14
15
  import type { GrimoirePlugin, LoadContext, Route } from "../types";
15
16
  import { collectHead, initHead } from "./head";
@@ -287,6 +288,7 @@ export async function renderRoute(
287
288
  url: new URL(req.url),
288
289
  locals,
289
290
  fetch: patchedFetch ?? globalThis.fetch,
291
+ getClientAddress: () => clientAddressOf(req),
290
292
  // no layouts have loaded yet — parent() is empty until the loop runs
291
293
  parent: async () => ({}),
292
294
  };
@@ -12,6 +12,7 @@
12
12
  */
13
13
  import { existsSync, readFileSync } from "node:fs";
14
14
  import { join } from "node:path";
15
+ import { clientDir } from "../server/client-dir";
15
16
 
16
17
  interface ChunkGraph {
17
18
  /** route pattern → chunk id */
@@ -53,7 +54,7 @@ export function parseChunkGraph(source: string): ChunkGraph | null {
53
54
 
54
55
  function load(): ChunkGraph | null {
55
56
  if (graph !== undefined) return graph;
56
- const file = join(process.cwd(), "public", "__grimoire__", "hydrate.js");
57
+ const file = join(clientDir(), "hydrate.js");
57
58
  graph = existsSync(file) ? parseChunkGraph(readFileSync(file, "utf-8")) : null;
58
59
  return graph;
59
60
  }
@@ -7,6 +7,7 @@ import { scanRoutes } from "../routing/scanner";
7
7
  import { transformRoutes } from "../routing/transform-routes";
8
8
  import { generateTypes } from "../typegen";
9
9
  import type { BuildResult, GrimoireConfig, GrimoirePlugin } from "../types";
10
+ import { clientDir, pruneClientDir, resetClientDir } from "./client-dir";
10
11
  import { runHook } from "./plugins";
11
12
  import { projectAliases, resolverPlugin } from "./resolver";
12
13
 
@@ -60,12 +61,12 @@ export async function rebuildClient(
60
61
  ),
61
62
  ]);
62
63
 
63
- const publicDir = join(process.cwd(), "public/__grimoire__");
64
+ const bundleDir = clientDir();
64
65
 
65
66
  const [hydrateResult, domResult] = await Promise.all([
66
67
  Bun.build({
67
68
  entrypoints: [join(import.meta.dir, "../rendering/hydrate.ts")],
68
- outdir: publicDir,
69
+ outdir: bundleDir,
69
70
  // report failures in result.logs instead of throwing past them
70
71
  throw: false,
71
72
  // lazy route entries in the manifest use dynamic import()
@@ -78,7 +79,7 @@ export async function rebuildClient(
78
79
  }),
79
80
  Bun.build({
80
81
  entrypoints: [join(import.meta.dir, "../client/index.ts")],
81
- outdir: publicDir,
82
+ outdir: bundleDir,
82
83
  // report failures in result.logs instead of throwing past them
83
84
  throw: false,
84
85
  splitting: true,
@@ -90,13 +91,18 @@ export async function rebuildClient(
90
91
  }),
91
92
  ]);
92
93
 
94
+ const outputs = [...hydrateResult.outputs, ...domResult.outputs].map(
95
+ (o) => o.path,
96
+ );
97
+ const success = hydrateResult.success && domResult.success;
98
+ // a failed build keeps the last good bundle in place
99
+ if (success) await pruneClientDir(outputs);
100
+
93
101
  return {
94
102
  tree,
95
103
  result: {
96
- success: hydrateResult.success && domResult.success,
97
- outputs: [...hydrateResult.outputs, ...domResult.outputs].map(
98
- (o) => o.path,
99
- ),
104
+ success,
105
+ outputs,
100
106
  errors: [...hydrateResult.logs, ...domResult.logs].map(String),
101
107
  },
102
108
  };
@@ -158,7 +164,8 @@ export async function buildProject(
158
164
  ]);
159
165
 
160
166
  const bundleStrategy = config.bundleStrategy ?? "split";
161
- const publicDir = join(process.cwd(), "public/__grimoire__");
167
+ const bundleDir = clientDir();
168
+ await resetClientDir();
162
169
 
163
170
  if (bundleStrategy === "single") {
164
171
  const singleResult = await Bun.build({
@@ -166,7 +173,7 @@ export async function buildProject(
166
173
  join(import.meta.dir, "../rendering/hydrate.ts"),
167
174
  join(import.meta.dir, "../client/index.ts"),
168
175
  ],
169
- outdir: publicDir,
176
+ outdir: bundleDir,
170
177
  // report failures in result.logs instead of throwing past them
171
178
  throw: false,
172
179
  // lazy route entries in the manifest use dynamic import()
@@ -197,7 +204,7 @@ export async function buildProject(
197
204
  const [hydrateResult, domResult] = await Promise.all([
198
205
  Bun.build({
199
206
  entrypoints: [join(import.meta.dir, "../rendering/hydrate.ts")],
200
- outdir: publicDir,
207
+ outdir: bundleDir,
201
208
  // report failures in result.logs instead of throwing past them
202
209
  throw: false,
203
210
  // lazy route entries in the manifest use dynamic import()
@@ -210,7 +217,7 @@ export async function buildProject(
210
217
  }),
211
218
  Bun.build({
212
219
  entrypoints: [join(import.meta.dir, "../client/index.ts")],
213
- outdir: publicDir,
220
+ outdir: bundleDir,
214
221
  // report failures in result.logs instead of throwing past them
215
222
  throw: false,
216
223
  splitting: true,
@@ -0,0 +1,82 @@
1
+ import type { Server } from "bun";
2
+
3
+ /**
4
+ * The visitor's address, as the coordinator saw it, on a request it forwards
5
+ * to a worker. A client's own copy of the header is dropped by the
6
+ * coordinator, and a worker only accepts requests that carry its secret, so
7
+ * inside a worker the value can be trusted.
8
+ */
9
+ export const CLIENT_ADDRESS_HEADER = "x-grimoire-client-address";
10
+
11
+ const isWorker = () => Boolean(process.env.GRIMOIRE_INTERNAL_SECRET);
12
+
13
+ /** Loopback and private ranges: where a reverse proxy on the same machine or network connects from. */
14
+ function isPrivate(ip: string): boolean {
15
+ const v4 = ip.startsWith("::ffff:") ? ip.slice(7) : ip;
16
+ if (/^(127\.|10\.|192\.168\.|169\.254\.)/.test(v4)) return true;
17
+ const m = /^172\.(\d+)\./.exec(v4);
18
+ if (m && Number(m[1]) >= 16 && Number(m[1]) <= 31) return true;
19
+ const v6 = ip.toLowerCase();
20
+ return (
21
+ v6 === "::1" ||
22
+ v6.startsWith("fc") ||
23
+ v6.startsWith("fd") ||
24
+ v6.startsWith("fe80:")
25
+ );
26
+ }
27
+
28
+ /**
29
+ * Who sent the request, given the address of the connection it came over.
30
+ *
31
+ * A connection from a private address is a reverse proxy (Caddy, nginx, a
32
+ * load balancer, Docker's network), and the visitor is the last entry it
33
+ * appended to X-Forwarded-For. Earlier entries came from the client and can
34
+ * say anything. A connection from a public address is the visitor itself, so
35
+ * any X-Forwarded-For it sends is ignored rather than believed.
36
+ */
37
+ export function resolveClientAddress(
38
+ req: Request,
39
+ peer: string | undefined,
40
+ ): string {
41
+ if (!peer) return "unknown";
42
+ if (!isPrivate(peer)) return peer;
43
+ const forwarded = req.headers
44
+ .get("x-forwarded-for")
45
+ ?.split(",")
46
+ .map((s) => s.trim())
47
+ .filter(Boolean);
48
+ return forwarded?.at(-1) ?? req.headers.get("x-real-ip")?.trim() ?? peer;
49
+ }
50
+
51
+ /**
52
+ * The visitor's IP address. Under `sigil start` it is what the coordinator
53
+ * worked out; otherwise it is read from the connection the same way.
54
+ */
55
+ export function clientAddress(
56
+ req: Request,
57
+ server: Server<unknown> | null,
58
+ ): string {
59
+ if (isWorker()) {
60
+ return req.headers.get(CLIENT_ADDRESS_HEADER) ?? "unknown";
61
+ }
62
+ return resolveClientAddress(req, server?.requestIP(req)?.address);
63
+ }
64
+
65
+ const lookups = new WeakMap<Request, () => string>();
66
+
67
+ /** Remembers how to find the address of a request, so every context built for it can offer one. */
68
+ export function trackClientAddress(
69
+ req: Request,
70
+ server: Server<unknown> | null,
71
+ ): void {
72
+ let address: string | undefined;
73
+ lookups.set(req, () => {
74
+ address ??= clientAddress(req, server);
75
+ return address;
76
+ });
77
+ }
78
+
79
+ /** The address of a request the server is handling. */
80
+ export function clientAddressOf(req: Request): string {
81
+ return lookups.get(req)?.() ?? "unknown";
82
+ }