@kiln-js/server 0.1.3 → 0.2.0

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 ADDED
@@ -0,0 +1,45 @@
1
+ # @kiln-js/server
2
+
3
+ [![npm](https://img.shields.io/npm/v/%40kiln-js%2Fserver)](https://www.npmjs.com/package/@kiln-js/server)
4
+ [![license](https://img.shields.io/npm/l/%40kiln-js%2Fserver)](LICENSE)
5
+
6
+ Part of the Kiln framework.
7
+
8
+ Part of [Kiln](https://github.com/kiln-js/kiln), a file-based server-side rendering framework for React and Vite.
9
+
10
+ ## Install
11
+
12
+ ```bash
13
+ bun add @kiln-js/server
14
+ ```
15
+
16
+ ## Usage
17
+
18
+ ```ts
19
+ import { createAppHandler, type KilnAssets } from "@kiln-js/server";
20
+
21
+ export function createHandler(assets: KilnAssets) {
22
+ return createAppHandler({
23
+ assets,
24
+ defaultTitle: "My app",
25
+ notFound: "<h1>Page not found</h1>",
26
+ });
27
+ }
28
+ ```
29
+
30
+ ## Runtime
31
+
32
+ Handlers use standard `Request` and `Response` objects, so the same code runs on Bun, Node, and edge runtimes.
33
+ The route table is provided by `@kiln-js/vite-plugin`.
34
+
35
+ ## Documentation
36
+
37
+ See the [Kiln repository](https://github.com/kiln-js/kiln) for the full API reference and guides.
38
+
39
+ ## Development
40
+
41
+ This repository is generated from the Kiln monorepo. Make changes there, then run `scripts/publish-repo.ps1` to publish them here. Report issues in this repository, and send pull requests to the monorepo.
42
+
43
+ ## License
44
+
45
+ MIT
package/dist/app.d.ts CHANGED
@@ -1,10 +1,13 @@
1
- import type { ApiRoute, KilnAssets, RouteEntry } from "./types";
1
+ import { type SecurityOptions } from "./security";
2
+ import type { ApiRoute, KilnAssets, RouteEntry, Specials } from "./types";
2
3
  export interface AppOptions {
3
4
  routes?: RouteEntry[];
4
5
  api?: ApiRoute[];
6
+ specials?: Specials;
5
7
  assets: KilnAssets;
6
8
  template?: string;
7
9
  notFound?: string;
8
10
  defaultTitle?: string;
11
+ security?: SecurityOptions;
9
12
  }
10
13
  export declare function createAppHandler(options: AppOptions): (request: Request) => Promise<Response>;
@@ -0,0 +1,3 @@
1
+ import { type Schema, type Validated } from "@kiln-js/core";
2
+ export declare function readBody(request: Request): Promise<Record<string, unknown>>;
3
+ export declare function parseForm<S extends Schema>(request: Request, schema: S): Promise<Validated<S>>;
package/dist/index.d.ts CHANGED
@@ -1,4 +1,9 @@
1
1
  export { createHandler } from "./render";
2
2
  export { createAppHandler, type AppOptions } from "./app";
3
3
  export { defaultTemplate } from "./template";
4
+ export { withSecurity, csrfToken, type SecurityOptions, type CorsOptions, type CsrfOptions } from "./security";
5
+ export { CsrfField } from "./security";
6
+ export { parseForm, readBody } from "./forms";
7
+ export { HttpError, notFound, forbidden, redirect, island, defer, Await } from "@kiln-js/core";
8
+ export type { Deferred } from "@kiln-js/core";
4
9
  export type * from "./types";
package/dist/index.js CHANGED
@@ -1,153 +1,245 @@
1
- // @bun
2
- // src/render.tsx
1
+ // packages/server/src/render.tsx
3
2
  import { renderToString } from "react-dom/server";
3
+ import { renderToReadableStream } from "react-dom/server.browser";
4
+ import {
5
+ compose,
6
+ HeadProvider,
7
+ HttpError,
8
+ IslandContext,
9
+ matchRoute as matchRoute2,
10
+ RouteProvider
11
+ } from "@kiln-js/core";
4
12
 
5
- // ../core/dist/index.js
6
- import { jsx } from "react/jsx-runtime";
7
- import { createContext, useContext } from "react";
8
- import { jsx as jsx2 } from "react/jsx-runtime";
9
- import { createContext as createContext2, useContext as useContext2, useEffect, useLayoutEffect } from "react";
10
- import { jsx as jsx3 } from "react/jsx-runtime";
11
- function matchRoute(routes, pathname) {
12
- const parts = pathname.split("/").filter(Boolean);
13
- for (const route of routes) {
14
- const segs = route.pattern.split("/").filter(Boolean);
15
- const params = {};
16
- let ok = true;
17
- let i = 0;
18
- for (const seg of segs) {
19
- if (seg.startsWith("*")) {
20
- params[seg.slice(1)] = parts.slice(i).map(decodeURIComponent).join("/");
21
- i = parts.length;
22
- break;
23
- }
24
- if (i >= parts.length) {
25
- ok = false;
26
- break;
27
- }
28
- if (seg.startsWith(":"))
29
- params[seg.slice(1)] = decodeURIComponent(parts[i]);
30
- else if (seg !== parts[i]) {
31
- ok = false;
32
- break;
33
- }
34
- i++;
35
- }
36
- if (ok && i === parts.length)
37
- return { route, params };
38
- }
39
- return null;
40
- }
41
- function compose(page, layouts) {
42
- let tree = page;
43
- for (const Layout of [...layouts].reverse())
44
- tree = /* @__PURE__ */ jsx(Layout, {
45
- children: tree
46
- });
47
- return tree;
48
- }
49
- var RouteContext = createContext({ pathname: "/", params: {} });
50
- function RouteProvider({ value, children }) {
51
- return /* @__PURE__ */ jsx2(RouteContext.Provider, {
52
- value,
53
- children
54
- });
55
- }
56
- var HeadContext = createContext2(null);
57
- function HeadProvider({ value, children }) {
58
- return /* @__PURE__ */ jsx3(HeadContext.Provider, {
59
- value,
60
- children
61
- });
62
- }
63
-
64
- // src/api.ts
13
+ // packages/server/src/api.ts
14
+ import { matchRoute } from "@kiln-js/core";
65
15
  var METHODS = ["GET", "POST", "PUT", "PATCH", "DELETE", "HEAD", "OPTIONS"];
66
16
  async function handleApi(request, pathname, routes) {
67
17
  const match = matchRoute(routes, pathname);
68
- if (!match)
69
- return null;
18
+ if (!match) return null;
70
19
  const mod = await match.route.load();
71
20
  const method = request.method.toUpperCase();
72
21
  let handler = mod[method];
73
- if (!handler && method === "HEAD")
74
- handler = mod.GET;
22
+ if (!handler && method === "HEAD") handler = mod.GET;
75
23
  if (typeof handler !== "function") {
76
24
  const allow = METHODS.filter((m) => typeof mod[m] === "function");
77
- return Response.json({ error: `Method ${method} not allowed` }, { status: 405, headers: { allow: allow.join(", ") } });
25
+ return Response.json(
26
+ { error: `Method ${method} not allowed` },
27
+ { status: 405, headers: { allow: allow.join(", ") } }
28
+ );
78
29
  }
79
30
  const ctx = { params: match.params, request };
80
31
  const result = await handler(ctx);
81
- if (result instanceof Response)
82
- return result;
83
- if (result === undefined)
84
- return new Response(null, { status: 204 });
32
+ if (result instanceof Response) return result;
33
+ if (result === void 0) return new Response(null, { status: 204 });
85
34
  return Response.json(result);
86
35
  }
87
36
 
88
- // src/render.tsx
89
- import { jsx as jsx4 } from "react/jsx-runtime";
90
- var htmlHeaders = { "content-type": "text/html; charset=utf-8" };
37
+ // packages/server/src/render.tsx
38
+ import { jsx } from "react/jsx-runtime";
39
+ var DATA_PATH = "/__kiln/data";
40
+ var HTML = "text/html; charset=utf-8";
41
+ var MARK_APP = "%%KILN_APP%%";
42
+ var MARK_TAIL = "%%KILN_TAIL%%";
91
43
  var serialize = (v) => JSON.stringify(v).replace(/</g, "\\u003c");
92
44
  var escapeHtml = (s) => s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
93
- function setTitle(template, title) {
94
- const tag = `<title>${escapeHtml(title)}</title>`;
95
- return /<title>[\s\S]*?<\/title>/i.test(template) ? template.replace(/<title>[\s\S]*?<\/title>/i, () => tag) : template.replace("</head>", () => `${tag}
96
- </head>`);
97
- }
45
+ var wantsJson = (request) => (request.headers.get("accept") ?? "").includes("application/json");
46
+ var isDev = () => globalThis.__KILN_DEV__ === true;
98
47
  function createHandler(ctx) {
99
48
  return async function handle(request) {
100
49
  const url = new URL(request.url);
101
- const routes = await ctx.manifest();
102
- if (url.pathname === "/__kiln/data") {
103
- const match = matchRoute(routes, url.searchParams.get("path") ?? "/");
104
- if (!match?.route.load)
105
- return Response.json(null);
106
- const mod = await match.route.load();
107
- const data = mod.loader ? await mod.loader({ params: match.params, request }) : null;
108
- return Response.json(data ?? null);
109
- }
110
- if (ctx.api) {
111
- const apiResponse = await handleApi(request, url.pathname, await ctx.api());
112
- if (apiResponse)
113
- return apiResponse;
114
- }
115
- const match = matchRoute(routes, url.pathname);
116
- if (!match) {
117
- return new Response(await ctx.notFound(), { status: 404, headers: htmlHeaders });
50
+ try {
51
+ return await dispatch(request, url, ctx);
52
+ } catch (err) {
53
+ if (err instanceof HttpError) return httpErrorResponse(err, request, url, ctx);
54
+ throw err;
118
55
  }
119
- const page = await renderRoute(match.route, match.params, request, url.pathname, ctx);
120
- return new Response(page, { status: 200, headers: htmlHeaders });
121
56
  };
122
57
  }
123
- async function renderRoute(route, params, request, pathname, ctx) {
124
- const mod = route.load ? await route.load() : null;
58
+ async function dispatch(request, url, ctx) {
59
+ const routes = await ctx.manifest();
60
+ const specials = await loadSpecials(ctx);
61
+ if (url.pathname === DATA_PATH) return dataResponse(request, url, routes);
62
+ if (ctx.api) {
63
+ const apiResponse = await handleApi(request, url.pathname, await ctx.api());
64
+ if (apiResponse) return apiResponse;
65
+ }
66
+ const match = matchRoute2(routes, url.pathname);
67
+ if (!match) return notFoundResponse(request, url, ctx, specials);
68
+ const mod = match.route.load ? await match.route.load() : null;
69
+ if (request.method === "POST") return actionResponse(request, url, match.params, mod);
70
+ if (request.method !== "GET" && request.method !== "HEAD") {
71
+ return new Response("Method Not Allowed", { status: 405, headers: { allow: "GET, HEAD, POST" } });
72
+ }
73
+ try {
74
+ return await pageResponse(match.route, match.params, request, url, ctx, mod);
75
+ } catch (err) {
76
+ return errorPageOr(err, request, url, ctx, specials);
77
+ }
78
+ }
79
+ async function loadSpecials(ctx) {
80
+ return ctx.specials ? ctx.specials() : { errors: [], notFounds: [] };
81
+ }
82
+ function pickSpecial(list, pathname) {
83
+ return matchRoute2(list, pathname)?.route ?? null;
84
+ }
85
+ async function dataResponse(request, url, routes) {
86
+ const target = new URL(url.searchParams.get("path") ?? "/", url.origin);
87
+ const match = matchRoute2(routes, target.pathname);
88
+ if (!match?.route.load) return Response.json(null);
89
+ const mod = await match.route.load();
90
+ if (!mod.loader) return Response.json(null);
91
+ const targetRequest = new Request(target, { method: "GET", headers: request.headers });
92
+ const data = await mod.loader({ params: match.params, request: targetRequest });
93
+ if (data instanceof Response) {
94
+ const location = data.headers.get("location");
95
+ if (location && data.status >= 300 && data.status < 400) return Response.json({ redirect: location });
96
+ return data;
97
+ }
98
+ return Response.json(data ?? null);
99
+ }
100
+ async function pageResponse(route, params, request, url, ctx, mod) {
125
101
  const data = mod?.loader ? await mod.loader({ params, request }) : null;
102
+ if (data instanceof Response) return data;
103
+ const [template, assets] = await Promise.all([ctx.template(), ctx.assets()]);
104
+ const head = {};
105
+ const islands = /* @__PURE__ */ new Set();
106
+ const fallbackTitle = ctx.defaultTitle ?? "Kiln App";
107
+ if (route.mode === "server" && mod) {
108
+ return streamPage({ route, mod, params, data, request, url, head, islands, template, assets, fallbackTitle });
109
+ }
110
+ const appHtml = route.mode !== "client" && mod ? renderToString(await buildTree(route, mod, params, data, url, head, islands)) : "";
111
+ const page = assemble(template, assets, {
112
+ appHtml,
113
+ title: head.title ?? fallbackTitle,
114
+ tail: hydrationTail(route, data, islands.size > 0, assets)
115
+ });
116
+ const headers = new Headers({ "content-type": HTML });
117
+ applyCachePolicy(headers, mod, request);
118
+ return new Response(request.method === "HEAD" ? null : page, { status: 200, headers });
119
+ }
120
+ async function buildTree(route, mod, params, data, url, head, islands) {
121
+ const layouts = await Promise.all(route.layouts.map((l) => l().then((m) => m.default)));
122
+ const Page = mod.default;
123
+ return /* @__PURE__ */ jsx(IslandContext.Provider, { value: islands, children: /* @__PURE__ */ jsx(HeadProvider, { value: head, children: /* @__PURE__ */ jsx(RouteProvider, { value: { pathname: url.pathname, params }, children: compose(/* @__PURE__ */ jsx(Page, { params, data }), layouts) }) }) });
124
+ }
125
+ async function streamPage(p) {
126
+ const shell = await renderToReadableStream(
127
+ await buildTree(p.route, p.mod, p.params, p.data, p.url, p.head, p.islands),
128
+ { onError: (err) => console.error("[kiln] streaming error", err) }
129
+ );
130
+ const doc = assemble(p.template, p.assets, {
131
+ appHtml: MARK_APP,
132
+ title: p.head.title ?? p.fallbackTitle,
133
+ tail: MARK_TAIL
134
+ });
135
+ const [before, after] = doc.split(MARK_APP);
136
+ const encoder = new TextEncoder();
137
+ const body = new ReadableStream({
138
+ async start(controller) {
139
+ try {
140
+ controller.enqueue(encoder.encode(before));
141
+ const reader = shell.getReader();
142
+ for (; ; ) {
143
+ const { done, value } = await reader.read();
144
+ if (done) break;
145
+ controller.enqueue(value);
146
+ }
147
+ const tail = hydrationTail(p.route, p.data, p.islands.size > 0, p.assets);
148
+ controller.enqueue(encoder.encode(after.replace(MARK_TAIL, () => tail)));
149
+ controller.close();
150
+ } catch (err) {
151
+ controller.error(err);
152
+ }
153
+ }
154
+ });
155
+ const headers = new Headers({ "content-type": HTML });
156
+ applyCachePolicy(headers, p.mod, p.request);
157
+ return new Response(body, { status: 200, headers });
158
+ }
159
+ function assemble(template, assets, parts) {
160
+ const withHead = template.replace("<!--kiln-head-->", () => assets.head);
161
+ const withApp = withHead.replace("<!--kiln-app-->", () => parts.appHtml);
162
+ const withTail = withApp.replace("<!--kiln-data-->", () => parts.tail);
163
+ return setTitle(withTail, parts.title);
164
+ }
165
+ function setTitle(template, title) {
166
+ const tag = `<title>${escapeHtml(title)}</title>`;
167
+ return /<title>[\s\S]*?<\/title>/i.test(template) ? template.replace(/<title>[\s\S]*?<\/title>/i, () => tag) : template.replace("</head>", () => `${tag}
168
+ </head>`);
169
+ }
170
+ function hydrationTail(route, data, islands, assets) {
171
+ if (route.mode === "server" && !islands) return "";
172
+ const payload = {
173
+ mode: route.mode,
174
+ pattern: route.pattern,
175
+ data: route.mode === "universal" ? data : null,
176
+ islands
177
+ };
178
+ return `<script>window.__KILN__ = ${serialize(payload)};</script><script type="module" src="${assets.entry}"></script>`;
179
+ }
180
+ function applyCachePolicy(headers, mod, request) {
181
+ if (!mod || typeof mod.revalidate !== "number") return;
182
+ headers.set("vary", "Cookie");
183
+ if (request.headers.has("cookie")) {
184
+ headers.set("cache-control", "private, no-store");
185
+ return;
186
+ }
187
+ const seconds = Math.max(0, Math.floor(mod.revalidate));
188
+ headers.set("cache-control", `public, s-maxage=${seconds}, stale-while-revalidate=${seconds * 10}`);
189
+ }
190
+ async function actionResponse(request, url, params, mod) {
191
+ if (!mod?.action) return new Response("Method Not Allowed", { status: 405, headers: { allow: "GET, HEAD" } });
192
+ const origin = request.headers.get("origin");
193
+ if (origin && origin !== url.origin) return new Response("Forbidden", { status: 403 });
194
+ const result = await mod.action({ params, request });
195
+ if (result instanceof Response) return result;
196
+ if (wantsJson(request)) return Response.json(result ?? { ok: true });
197
+ return new Response(null, { status: 303, headers: { location: url.pathname } });
198
+ }
199
+ async function renderSpecial(special, props, status, request, url, ctx) {
200
+ const mod = await special.load();
201
+ const layouts = await Promise.all(special.layouts.map((l) => l().then((m) => m.default)));
126
202
  const head = {};
127
- let appHtml = "";
128
- if (route.mode !== "client" && mod) {
129
- const layouts = await Promise.all(route.layouts.map((l) => l().then((m) => m.default)));
130
- const Page = mod.default;
131
- appHtml = renderToString(/* @__PURE__ */ jsx4(HeadProvider, {
132
- value: head,
133
- children: /* @__PURE__ */ jsx4(RouteProvider, {
134
- value: { pathname, params },
135
- children: compose(/* @__PURE__ */ jsx4(Page, {
136
- params,
137
- data
138
- }), layouts)
139
- })
140
- }));
203
+ const Page = mod.default;
204
+ const appHtml = renderToString(
205
+ /* @__PURE__ */ jsx(HeadProvider, { value: head, children: /* @__PURE__ */ jsx(RouteProvider, { value: { pathname: url.pathname, params: {} }, children: compose(/* @__PURE__ */ jsx(Page, { ...props }), layouts) }) })
206
+ );
207
+ const page = assemble(await ctx.template(), await ctx.assets(), {
208
+ appHtml,
209
+ title: head.title ?? ctx.defaultTitle ?? "Kiln App",
210
+ tail: ""
211
+ });
212
+ return new Response(request.method === "HEAD" ? null : page, {
213
+ status,
214
+ headers: { "content-type": HTML, "cache-control": "no-store" }
215
+ });
216
+ }
217
+ async function notFoundResponse(request, url, ctx, specials) {
218
+ const special = pickSpecial(specials.notFounds, url.pathname);
219
+ if (special) return renderSpecial(special, {}, 404, request, url, ctx);
220
+ return new Response(await ctx.notFound(), { status: 404, headers: { "content-type": HTML } });
221
+ }
222
+ async function errorPageOr(err, request, url, ctx, specials) {
223
+ if (err instanceof HttpError || isDev()) throw err;
224
+ const special = pickSpecial(specials.errors, url.pathname);
225
+ if (!special) throw err;
226
+ const requestId = Math.random().toString(36).slice(2, 10);
227
+ console.error(`[kiln] ${request.method} ${url.pathname} [${requestId}]`, err);
228
+ return renderSpecial(special, { status: 500, error: { message: "Internal Server Error", requestId } }, 500, request, url, ctx);
229
+ }
230
+ async function httpErrorResponse(err, request, url, ctx) {
231
+ if (url.pathname.startsWith("/api/") || wantsJson(request)) {
232
+ return Response.json({ error: err.message }, { status: err.status });
141
233
  }
142
- const template = await ctx.template();
143
- const assets = await ctx.assets();
144
- const title = head.title ?? ctx.defaultTitle ?? "Kiln App";
145
- const boot = `window.__KILN__ = ${serialize({ mode: route.mode, pattern: route.pattern, data })};`;
146
- const script = route.mode === "server" ? "" : `<script type="module" src="${assets.entry}"></script>`;
147
- const page = template.replace("<!--kiln-head-->", () => assets.head).replace("<!--kiln-app-->", () => appHtml).replace("<!--kiln-data-->", () => `<script>${boot}</script>${script}`);
148
- return setTitle(page, title);
149
- }
150
- // src/template.ts
234
+ if (err.status === 404) return notFoundResponse(request, url, ctx, await loadSpecials(ctx));
235
+ const body = `<!doctype html><meta charset="utf-8"><title>${err.status}</title><h1>${err.status}</h1><p>${escapeHtml(err.message)}</p>`;
236
+ return new Response(request.method === "HEAD" ? null : body, {
237
+ status: err.status,
238
+ headers: { "content-type": HTML, "cache-control": "no-store" }
239
+ });
240
+ }
241
+
242
+ // packages/server/src/template.ts
151
243
  var defaultTemplate = `<!doctype html>
152
244
  <html lang="en">
153
245
  <head>
@@ -162,28 +254,198 @@ var defaultTemplate = `<!doctype html>
162
254
  </body>
163
255
  </html>`;
164
256
 
165
- // src/app.ts
166
- function injectedRoutes() {
167
- const routes = globalThis.__KILN_ROUTES__;
168
- if (!routes) {
169
- throw new Error("No routes found. Pass createAppHandler({ routes, assets }) or run through the Kiln plugin.");
257
+ // packages/server/src/security.tsx
258
+ import { jsx as jsx2 } from "react/jsx-runtime";
259
+ var CSRF_COOKIE = "kiln_csrf";
260
+ var UNSAFE = /* @__PURE__ */ new Set(["POST", "PUT", "PATCH", "DELETE"]);
261
+ var issued = /* @__PURE__ */ new WeakMap();
262
+ function readCookie(request, name) {
263
+ for (const part of (request.headers.get("cookie") ?? "").split(";")) {
264
+ const [key, ...rest] = part.trim().split("=");
265
+ if (key === name) return rest.join("=");
170
266
  }
171
- return routes;
267
+ return null;
268
+ }
269
+ function randomToken() {
270
+ const bytes = crypto.getRandomValues(new Uint8Array(32));
271
+ let s = "";
272
+ for (const b of bytes) s += String.fromCharCode(b);
273
+ return btoa(s).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
274
+ }
275
+ function csrfToken(request) {
276
+ const existing = issued.get(request) ?? readCookie(request, CSRF_COOKIE);
277
+ if (existing) {
278
+ issued.set(request, existing);
279
+ return existing;
280
+ }
281
+ const fresh = randomToken();
282
+ issued.set(request, fresh);
283
+ return fresh;
284
+ }
285
+ function safeEqual(a, b) {
286
+ if (a.length !== b.length) return false;
287
+ let diff = 0;
288
+ for (let i = 0; i < a.length; i++) diff |= a.charCodeAt(i) ^ b.charCodeAt(i);
289
+ return diff === 0;
290
+ }
291
+ async function csrfValid(request, url) {
292
+ const origin = request.headers.get("origin");
293
+ if (origin && origin !== url.origin) return false;
294
+ const cookie = readCookie(request, CSRF_COOKIE);
295
+ if (!cookie) return false;
296
+ let sent = request.headers.get("x-csrf-token");
297
+ if (!sent && /form/.test(request.headers.get("content-type") ?? "")) {
298
+ const form = await request.clone().formData().catch(() => null);
299
+ sent = form?.get("_csrf") ?? null;
300
+ }
301
+ return !!sent && safeEqual(sent, cookie);
302
+ }
303
+ function normalizeCors(opts) {
304
+ return {
305
+ origins: opts.origins ?? "*",
306
+ methods: opts.methods ?? ["GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"],
307
+ headers: opts.headers,
308
+ credentials: opts.credentials ?? false,
309
+ maxAge: opts.maxAge ?? 600,
310
+ paths: opts.paths ?? ["/api/"]
311
+ };
312
+ }
313
+ function originAllowed(origin, cors) {
314
+ const o = cors.origins;
315
+ if (o === "*") return true;
316
+ if (typeof o === "function") return o(origin);
317
+ return o.includes(origin);
318
+ }
319
+ function corsHeaders(request, cors) {
320
+ const origin = request.headers.get("origin");
321
+ if (!origin || !originAllowed(origin, cors)) return {};
322
+ const allowOrigin = cors.origins === "*" && !cors.credentials ? "*" : origin;
323
+ const headers = {
324
+ "access-control-allow-origin": allowOrigin,
325
+ vary: "Origin"
326
+ };
327
+ if (cors.credentials) headers["access-control-allow-credentials"] = "true";
328
+ return headers;
172
329
  }
330
+ function preflight(request, cors) {
331
+ const headers = corsHeaders(request, cors);
332
+ if (!("access-control-allow-origin" in headers)) return new Response(null, { status: 403 });
333
+ return new Response(null, {
334
+ status: 204,
335
+ headers: {
336
+ ...headers,
337
+ "access-control-allow-methods": cors.methods.join(", "),
338
+ "access-control-allow-headers": cors.headers?.join(", ") ?? request.headers.get("access-control-request-headers") ?? "content-type",
339
+ "access-control-max-age": String(cors.maxAge)
340
+ }
341
+ });
342
+ }
343
+ function withHeaders(response, change) {
344
+ const headers = new Headers(response.headers);
345
+ change(headers);
346
+ return new Response(response.body, { status: response.status, statusText: response.statusText, headers });
347
+ }
348
+ function withSecurity(handler, options) {
349
+ const cors = options.cors ? normalizeCors(options.cors === true ? {} : options.cors) : null;
350
+ const csrf = options.csrf ? { exempt: (options.csrf === true ? {} : options.csrf).exempt ?? [] } : null;
351
+ return async (request) => {
352
+ const url = new URL(request.url);
353
+ const corsPath = cors !== null && cors.paths.some((p) => url.pathname.startsWith(p));
354
+ if (cors && corsPath && request.method === "OPTIONS" && request.headers.has("access-control-request-method")) {
355
+ return preflight(request, cors);
356
+ }
357
+ if (csrf && UNSAFE.has(request.method) && !csrf.exempt.some((p) => url.pathname.startsWith(p))) {
358
+ if (!await csrfValid(request, url)) {
359
+ return new Response("Forbidden: missing or invalid CSRF token", { status: 403 });
360
+ }
361
+ }
362
+ let response = await handler(request);
363
+ if (csrf && issued.has(request) && !readCookie(request, CSRF_COOKIE)) {
364
+ const token = issued.get(request);
365
+ const secure = new URL(request.url).protocol === "https:" ? "; Secure" : "";
366
+ response = withHeaders(
367
+ response,
368
+ (h) => h.append("set-cookie", `${CSRF_COOKIE}=${token}; Path=/; HttpOnly; SameSite=Lax${secure}`)
369
+ );
370
+ }
371
+ if (cors && corsPath) {
372
+ const headers = corsHeaders(request, cors);
373
+ if (Object.keys(headers).length > 0) {
374
+ response = withHeaders(response, (h) => {
375
+ for (const [key, value] of Object.entries(headers)) {
376
+ if (key === "vary") h.append(key, value);
377
+ else h.set(key, value);
378
+ }
379
+ if (cors.credentials) h.set("access-control-allow-credentials", "true");
380
+ });
381
+ }
382
+ }
383
+ return response;
384
+ };
385
+ }
386
+ function CsrfField({ token }) {
387
+ return /* @__PURE__ */ jsx2("input", { type: "hidden", name: "_csrf", value: token });
388
+ }
389
+
390
+ // packages/server/src/app.ts
391
+ var injected = (key) => globalThis[key];
173
392
  function createAppHandler(options) {
174
- const routes = options.routes ?? injectedRoutes();
175
- const api = options.api ?? globalThis.__KILN_API__ ?? [];
176
- return createHandler({
393
+ const routes = options.routes ?? injected("__KILN_ROUTES__");
394
+ if (!routes) {
395
+ throw new Error("No routes found. Pass createAppHandler({ routes, assets }) or run through the Kiln plugin.");
396
+ }
397
+ const api = options.api ?? injected("__KILN_API__") ?? [];
398
+ const specials = options.specials ?? injected("__KILN_SPECIALS__") ?? { errors: [], notFounds: [] };
399
+ const handler = createHandler({
177
400
  manifest: async () => routes,
178
401
  api: async () => api,
402
+ specials: async () => specials,
179
403
  template: async () => options.template ?? defaultTemplate,
180
404
  assets: async () => options.assets,
181
405
  notFound: async () => options.notFound ?? "<h1>404: Not found</h1>",
182
406
  defaultTitle: options.defaultTitle ?? "Kiln App"
183
407
  });
408
+ return withSecurity(handler, options.security ?? {});
409
+ }
410
+
411
+ // packages/server/src/forms.ts
412
+ import { validate } from "@kiln-js/core";
413
+ async function readBody(request) {
414
+ const type = request.headers.get("content-type") ?? "";
415
+ if (type.includes("application/json")) {
416
+ const json = await request.json().catch(() => null);
417
+ return typeof json === "object" && json !== null ? json : {};
418
+ }
419
+ if (type.includes("multipart/form-data") || type.includes("application/x-www-form-urlencoded")) {
420
+ const form = await request.formData();
421
+ const out = {};
422
+ for (const [key, value] of form.entries()) {
423
+ if (typeof value === "string") out[key] = value;
424
+ }
425
+ return out;
426
+ }
427
+ return {};
428
+ }
429
+ async function parseForm(request, schema) {
430
+ return validate(schema, await readBody(request));
184
431
  }
432
+
433
+ // packages/server/src/index.ts
434
+ import { HttpError as HttpError2, notFound, forbidden, redirect, island, defer, Await } from "@kiln-js/core";
185
435
  export {
436
+ Await,
437
+ CsrfField,
438
+ HttpError2 as HttpError,
186
439
  createAppHandler,
187
440
  createHandler,
188
- defaultTemplate
441
+ csrfToken,
442
+ defaultTemplate,
443
+ defer,
444
+ forbidden,
445
+ island,
446
+ notFound,
447
+ parseForm,
448
+ readBody,
449
+ redirect,
450
+ withSecurity
189
451
  };
@@ -0,0 +1,20 @@
1
+ export interface CorsOptions {
2
+ origins?: "*" | string[] | ((origin: string) => boolean);
3
+ methods?: string[];
4
+ headers?: string[];
5
+ credentials?: boolean;
6
+ maxAge?: number;
7
+ paths?: string[];
8
+ }
9
+ export interface CsrfOptions {
10
+ exempt?: string[];
11
+ }
12
+ export interface SecurityOptions {
13
+ cors?: CorsOptions | false | any;
14
+ csrf?: CsrfOptions | boolean;
15
+ }
16
+ export declare function csrfToken(request: Request): string;
17
+ export declare function withSecurity(handler: (request: Request) => Promise<Response>, options: SecurityOptions): (request: Request) => Promise<Response>;
18
+ export declare function CsrfField({ token }: {
19
+ token: string;
20
+ }): import("react").JSX.Element;
package/dist/types.d.ts CHANGED
@@ -4,9 +4,12 @@ export interface LoaderContext {
4
4
  params: Record<string, string>;
5
5
  request: Request;
6
6
  }
7
+ export type ActionContext = LoaderContext;
7
8
  export interface PageModule {
8
9
  default: ComponentType<any>;
9
10
  loader?: (ctx: LoaderContext) => unknown;
11
+ action?: (ctx: ActionContext) => unknown;
12
+ revalidate?: number;
10
13
  }
11
14
  export interface LayoutModule {
12
15
  default: ComponentType<any>;
@@ -17,6 +20,17 @@ export interface RouteEntry {
17
20
  load: (() => Promise<PageModule>) | null;
18
21
  layouts: (() => Promise<LayoutModule>)[];
19
22
  }
23
+ export interface SpecialRoute {
24
+ pattern: string;
25
+ load: () => Promise<{
26
+ default: ComponentType<any>;
27
+ }>;
28
+ layouts: (() => Promise<LayoutModule>)[];
29
+ }
30
+ export interface Specials {
31
+ errors: SpecialRoute[];
32
+ notFounds: SpecialRoute[];
33
+ }
20
34
  export interface ApiContext {
21
35
  params: Record<string, string>;
22
36
  request: Request;
@@ -35,6 +49,7 @@ export interface KilnAssets {
35
49
  export interface KilnContext {
36
50
  manifest(): Promise<RouteEntry[]>;
37
51
  api?(): Promise<ApiRoute[]>;
52
+ specials?(): Promise<Specials>;
38
53
  template(): Promise<string>;
39
54
  assets(): Promise<KilnAssets>;
40
55
  notFound(): Promise<string>;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kiln-js/server",
3
- "version": "0.1.3",
3
+ "version": "0.2.0",
4
4
  "type": "module",
5
5
  "exports": {
6
6
  ".": {
@@ -17,7 +17,7 @@
17
17
  "typecheck": "tsc -p tsconfig.json --noEmit"
18
18
  },
19
19
  "dependencies": {
20
- "@kiln-js/core": "^0.1.3"
20
+ "@kiln-js/core": "^0.2.0"
21
21
  },
22
22
  "peerDependencies": {
23
23
  "react": "\u003e=18",