@kiln-js/server 0.1.4 → 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/dist/app.d.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import { type SecurityOptions } from "./security";
1
2
  import type { ApiRoute, KilnAssets, RouteEntry, Specials } from "./types";
2
3
  export interface AppOptions {
3
4
  routes?: RouteEntry[];
@@ -7,5 +8,6 @@ export interface AppOptions {
7
8
  template?: string;
8
9
  notFound?: string;
9
10
  defaultTitle?: string;
11
+ security?: SecurityOptions;
10
12
  }
11
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,6 +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";
4
7
  export { HttpError, notFound, forbidden, redirect, island, defer, Await } from "@kiln-js/core";
5
8
  export type { Deferred } from "@kiln-js/core";
6
9
  export type * from "./types";
package/dist/index.js CHANGED
@@ -254,6 +254,139 @@ var defaultTemplate = `<!doctype html>
254
254
  </body>
255
255
  </html>`;
256
256
 
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("=");
266
+ }
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;
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
+
257
390
  // packages/server/src/app.ts
258
391
  var injected = (key) => globalThis[key];
259
392
  function createAppHandler(options) {
@@ -263,7 +396,7 @@ function createAppHandler(options) {
263
396
  }
264
397
  const api = options.api ?? injected("__KILN_API__") ?? [];
265
398
  const specials = options.specials ?? injected("__KILN_SPECIALS__") ?? { errors: [], notFounds: [] };
266
- return createHandler({
399
+ const handler = createHandler({
267
400
  manifest: async () => routes,
268
401
  api: async () => api,
269
402
  specials: async () => specials,
@@ -272,19 +405,47 @@ function createAppHandler(options) {
272
405
  notFound: async () => options.notFound ?? "<h1>404: Not found</h1>",
273
406
  defaultTitle: options.defaultTitle ?? "Kiln App"
274
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));
275
431
  }
276
432
 
277
433
  // packages/server/src/index.ts
278
434
  import { HttpError as HttpError2, notFound, forbidden, redirect, island, defer, Await } from "@kiln-js/core";
279
435
  export {
280
436
  Await,
437
+ CsrfField,
281
438
  HttpError2 as HttpError,
282
439
  createAppHandler,
283
440
  createHandler,
441
+ csrfToken,
284
442
  defaultTemplate,
285
443
  defer,
286
444
  forbidden,
287
445
  island,
288
446
  notFound,
289
- redirect
447
+ parseForm,
448
+ readBody,
449
+ redirect,
450
+ withSecurity
290
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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kiln-js/server",
3
- "version": "0.1.4",
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.5"
20
+ "@kiln-js/core": "^0.2.0"
21
21
  },
22
22
  "peerDependencies": {
23
23
  "react": "\u003e=18",