@dokebi/web 0.4.1 → 0.4.3

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.
Files changed (46) hide show
  1. package/AI.md +248 -38
  2. package/README.md +32 -11
  3. package/dist/app-routes.d.ts +20 -0
  4. package/dist/app-routes.js +137 -0
  5. package/dist/before-hijack.d.ts +24 -0
  6. package/dist/before-hijack.js +73 -0
  7. package/dist/body.d.ts +14 -0
  8. package/dist/body.js +30 -0
  9. package/dist/cluster-ready.d.ts +67 -0
  10. package/dist/cluster-ready.js +123 -0
  11. package/dist/compilers.d.ts +16 -0
  12. package/dist/compilers.js +25 -0
  13. package/dist/compression.d.ts +40 -0
  14. package/dist/compression.js +435 -0
  15. package/dist/connections.d.ts +44 -0
  16. package/dist/connections.js +282 -0
  17. package/dist/define-errors.d.ts +76 -0
  18. package/dist/define-errors.js +161 -0
  19. package/dist/describe.d.ts +37 -0
  20. package/dist/describe.js +96 -0
  21. package/dist/errors.d.ts +1 -1
  22. package/dist/errors.js +26 -2
  23. package/dist/forms.d.ts +27 -10
  24. package/dist/forms.js +75 -17
  25. package/dist/index.d.ts +134 -4
  26. package/dist/index.js +1518 -91
  27. package/dist/options.d.ts +56 -0
  28. package/dist/options.js +320 -1
  29. package/dist/points.d.ts +159 -0
  30. package/dist/points.js +162 -1
  31. package/dist/responses.d.ts +31 -6
  32. package/dist/responses.js +68 -6
  33. package/dist/route-config.d.ts +38 -0
  34. package/dist/route-config.js +222 -0
  35. package/dist/route-hooks.d.ts +75 -0
  36. package/dist/route-hooks.js +118 -0
  37. package/dist/route-table.d.ts +55 -0
  38. package/dist/route-table.js +142 -0
  39. package/dist/seal.d.ts +49 -1
  40. package/dist/seal.js +261 -20
  41. package/dist/security-headers.d.ts +121 -0
  42. package/dist/security-headers.js +298 -0
  43. package/dist/transient-log.d.ts +42 -0
  44. package/dist/transient-log.js +95 -0
  45. package/options.schema.json +488 -1
  46. package/package.json +22 -9
package/dist/points.js CHANGED
@@ -1,5 +1,166 @@
1
- import { definePoint } from '@dokebi/core';
1
+ import { DokebiError, definePoint, option as o, } from '@dokebi/core';
2
+ export { BEFORE_HIJACK, beforeHijackSteps, runBeforeHijack, } from './before-hijack.js';
2
3
  /** `dokebi-web:view-engine`: template engines an app can render with. */
3
4
  export const viewEngines = definePoint('dokebi-web:view-engine');
4
5
  /** `dokebi-web:realtime`: realtime transports an app can mount routes on. */
5
6
  export const realtime = definePoint('dokebi-web:realtime');
7
+ /** `dokebi-web:view-data`: values plugins add to every rendered page (EJS data, Inertia props). */
8
+ export const viewData = definePoint('dokebi-web:view-data');
9
+ /** `dokebi-web:error-translator`: what an unhandled error means, asked before the 500 (D-0093). */
10
+ export const errorTranslators = definePoint('dokebi-web:error-translator');
11
+ const VIEW_DATA_KEY = /^[A-Za-z_$][A-Za-z0-9_$]{0,63}$/;
12
+ /**
13
+ * Checks the contributions of `dokebi-web:view-data` for one collector (dokebi-app for EJS,
14
+ * template-inertia for props): a valid key and a `value` function each, no key twice and none of
15
+ * the collector's own `reserved` keys. Throws VIEW_DATA_CONFLICT (a setup error) otherwise.
16
+ */
17
+ export function collectViewData(contributions, collector) {
18
+ const entries = new Map();
19
+ for (const { plugin, value: contribution } of contributions) {
20
+ const { key, value } = (contribution ?? {});
21
+ const refuse = (message, fix) => {
22
+ throw new DokebiError('VIEW_DATA_CONFLICT', message, { plugin: collector.plugin, fix });
23
+ };
24
+ if (typeof key !== 'string' || !VIEW_DATA_KEY.test(key) || typeof value !== 'function')
25
+ refuse(`${plugin} contributed invalid view data`, `Contribute { key: 'name', value: (request) => value } to dokebi-web:view-data (${plugin}).`);
26
+ const name = key;
27
+ if (collector.reserved.includes(name))
28
+ refuse(`View data key ${name} of ${plugin} is ${collector.plugin}'s own`, `Use another key in ${plugin}: ${collector.reserved.join(', ')} are set by ${collector.plugin}.`);
29
+ const taken = entries.get(name);
30
+ if (taken)
31
+ refuse(`View data key ${name} is contributed by both ${taken.plugin} and ${plugin}`, `Register only one of ${taken.plugin} and ${plugin}, or give one of them another key.`);
32
+ entries.set(name, { plugin, source: contribution });
33
+ }
34
+ const list = [...entries];
35
+ return Object.freeze({
36
+ keys: Object.freeze(list.map(([key]) => key)),
37
+ values: async (request) => {
38
+ const values = await Promise.all(list.map(([, entry]) => entry.source.value(request)));
39
+ const result = {};
40
+ list.forEach(([key], index) => {
41
+ result[key] = values[index];
42
+ });
43
+ return result;
44
+ },
45
+ });
46
+ }
47
+ /** An app name, as @dokebi/app defines it (D-0132: the `app` of a route or a plugin option). */
48
+ export const APP_NAME = /^[a-z][a-z0-9-]{0,31}$/;
49
+ /** App names of one route or option at most. */
50
+ export const APP_NAMES_MAX = 64;
51
+ /**
52
+ * The shared `app` option of a plugin that adds routes (D-0132): `app: mcp` or
53
+ * `app: [studio, admin]`, the apps of @dokebi/app whose hosts answer the plugin's routes. Leave
54
+ * it out and the routes answer on every host. Put it in the plugin's `defineOptions` shape
55
+ * (`app: appOption('The apps whose hosts answer /mcp …')`) and pass the value as the `app` of
56
+ * each route; dokebi-web does the rest at boot.
57
+ */
58
+ export function appOption(description) {
59
+ return o.union([
60
+ o.string({ pattern: APP_NAME }),
61
+ o.array(o.string({ pattern: APP_NAME }), {
62
+ minItems: 1,
63
+ maxItems: APP_NAMES_MAX,
64
+ uniqueItems: true,
65
+ }),
66
+ ], { description });
67
+ }
68
+ /**
69
+ * Where `url` lands for routes bound to `apps` (D-0132): plugins that publish their own URLs
70
+ * (an OAuth issuer, a resource URI) check them at boot. `ok` when nothing is bound, there is
71
+ * no routing yet, or an app is unknown (the binding itself refuses that).
72
+ */
73
+ export function appUrlMatch(routing, url, apps) {
74
+ // An unknown app name is the binding's error (ROUTE_APP_UNKNOWN), reported when the route is added.
75
+ if (routing === undefined ||
76
+ apps === undefined ||
77
+ apps.some((app) => !routing.names.includes(app)))
78
+ return { kind: 'ok' };
79
+ const raw = new URL(url).hostname.toLowerCase();
80
+ const host = raw.endsWith('.') ? raw.slice(0, -1) : raw;
81
+ const owner = routing.domainApp(host);
82
+ if (owner === undefined)
83
+ return { kind: 'unconfigured', host, fallback: routing.fallback };
84
+ return apps.includes(owner) ? { kind: 'ok' } : { kind: 'other-app', host, app: owner };
85
+ }
86
+ // ── Route ids of the routes a plugin adds itself (D-0142) ──
87
+ /** A route id (D-0077 A): `API-12`, `posts.index`, `mcp.endpoint`. */
88
+ export const ROUTE_ID = /^[A-Za-z][A-Za-z0-9._-]{0,63}$/;
89
+ /**
90
+ * The owner mark on the `config` of a route a plugin adds itself (D-0142), a registered symbol:
91
+ * a plugin that does not import this module (@dokebi/seal, @dokebi/mail) writes
92
+ * `Symbol.for('dokebi-web:route-owner')` and means the same. Its value is a `WebRouteOwner`.
93
+ * dokebi-web reads it at onRoute: `web.routes()` and describe name the plugin, and the duplicate
94
+ * route id check names both owners. A symbol key is no config key (never checked or listed).
95
+ */
96
+ export const ROUTE_OWNER = Symbol.for('dokebi-web:route-owner');
97
+ /** `dokebi-mcp` → `mcp`: the namespace of a plugin's default route ids (D-0142). */
98
+ export function routeNamespace(plugin) {
99
+ return plugin.startsWith('dokebi-') ? plugin.slice('dokebi-'.length) : plugin;
100
+ }
101
+ const ROUTE_KEY = /^[a-z][A-Za-z0-9]{0,31}$/;
102
+ // A route id is never a secret, however its key is named (`token` of an OAuth server).
103
+ const routeIdNode = (description) => o.string({ pattern: ROUTE_ID, description, plain: true });
104
+ /**
105
+ * The shared `routeIds` option of a plugin that adds routes itself (D-0142): one optional key per
106
+ * route role, whose value replaces the default id `<namespace>.<key>` of those routes
107
+ * (`options.dokebi-mcp.routeIds: { endpoint: ai.mcp }`). Other keys are refused like any unknown
108
+ * option, and values follow the rule of a route `config.id`. `routes` says, per key, which
109
+ * routes it names. Put it in the plugin's `defineOptions` shape as `routeIds` and pass the value
110
+ * to `pluginRouteIds`.
111
+ */
112
+ export function routeIdsOption(plugin, routes) {
113
+ const namespace = routeNamespace(plugin);
114
+ const keys = Object.keys(routes);
115
+ for (const key of keys)
116
+ if (!ROUTE_KEY.test(key))
117
+ throw new DokebiError('INVALID_ARGUMENT', `Route key ${key} of ${plugin} is not allowed`, {
118
+ plugin: 'dokebi-web',
119
+ fix: 'Name a route key in camelCase: a lower case letter, then letters and digits (1-32).',
120
+ });
121
+ const shape = Object.fromEntries(keys.map((key) => [key, routeIdNode(`Id of ${routes[key]}; default ${namespace}.${key}`)]));
122
+ return o.object(shape, {
123
+ description: `Ids of the routes ${plugin} adds (D-0142), by route key: ${keys
124
+ .map((key) => `${key} (default ${namespace}.${key})`)
125
+ .join(', ')}. An id is 1-64 letters, digits, '.', '_' or '-' starting with a letter; an id another route of the same app has fails the start (DUPLICATE_ROUTE_ID)`,
126
+ });
127
+ }
128
+ /**
129
+ * Resolves the ids of a plugin's own routes (D-0142). `overrides` is the parsed `routeIds`
130
+ * option; a key outside `keys` is INVALID_ARGUMENT (the option schema already refuses it). The
131
+ * ids are checked by dokebi-web at start like every route id (INVALID_ROUTE_CONFIG,
132
+ * DUPLICATE_ROUTE_ID), so a plugin never checks them itself.
133
+ */
134
+ export function pluginRouteIds(plugin, keys, overrides) {
135
+ const namespace = routeNamespace(plugin);
136
+ const unknownKey = (key) => {
137
+ throw new DokebiError('INVALID_ARGUMENT', `${plugin} has no route key ${key}`, {
138
+ plugin: 'dokebi-web',
139
+ fix: `Use one of ${keys.join(', ')} in options.${plugin}.routeIds.`,
140
+ });
141
+ };
142
+ for (const key of Object.keys(overrides ?? {}))
143
+ if (!keys.includes(key))
144
+ unknownKey(key);
145
+ const ids = Object.freeze(Object.fromEntries(keys.map((key) => [key, overrides?.[key] ?? `${namespace}.${key}`])));
146
+ const owners = new Map(keys.map((key) => [key, Object.freeze({ plugin, key })]));
147
+ return Object.freeze({
148
+ ids,
149
+ config(key, extra) {
150
+ const owner = owners.get(key) ?? unknownKey(String(key));
151
+ return { ...(extra ?? {}), id: ids[key], [ROUTE_OWNER]: owner };
152
+ },
153
+ });
154
+ }
155
+ /** The owner mark of a route config, when it carries a valid one (read by dokebi-web). */
156
+ export function routeOwnerOf(config) {
157
+ if (config === null || typeof config !== 'object')
158
+ return undefined;
159
+ const owner = config[ROUTE_OWNER];
160
+ if (owner === null || typeof owner !== 'object')
161
+ return undefined;
162
+ const { plugin, key } = owner;
163
+ return typeof plugin === 'string' && plugin !== '' && typeof key === 'string' && key !== ''
164
+ ? { plugin, key }
165
+ : undefined;
166
+ }
@@ -24,7 +24,10 @@ export interface WebErrorResponse {
24
24
  readonly format: WebErrorFormat;
25
25
  /** True in production (or with `developmentErrors: false`). */
26
26
  readonly production: boolean;
27
- /** The request is sealed (a seal host, D-0062): only JSON leaves, sealed by dokebi-web. */
27
+ /**
28
+ * The request is sealed (a seal host, D-0062): every JSON answer leaves sealed (dokebi-web
29
+ * seals it). `format` is `html` for a page navigation or a sealed form of such a request.
30
+ */
28
31
  readonly sealed: boolean;
29
32
  }
30
33
  /**
@@ -64,13 +67,35 @@ export declare function validAnswer(value: unknown): value is WebErrorAnswer;
64
67
  */
65
68
  export declare function prefersHtml(accept: string | undefined): boolean;
66
69
  /**
67
- * JSON or HTML for an error answer (D-0074 §1). JSON for every script: an Inertia request
70
+ * The request header the seal forms module (`@dokebi/seal/forms`) sends with a sealed form
71
+ * submission, value `1` (D-0092 §1.2). The request is a form post: its errors follow the HTML
72
+ * form flow, and its sealed body has the shape of a parsed urlencoded body.
73
+ */
74
+ export declare const FORM_SUBMISSION_HEADER = "x-dokebi-form";
75
+ /** The request header `sealedFetch` sends on a seal host: a script, never a page navigation. */
76
+ export declare const SEALED_FETCH_HEADER = "x-dokebi-sealed";
77
+ /** True when the request carries the seal forms marker `x-dokebi-form: 1`. */
78
+ export declare function sealedFormMarker(headers: Readonly<Record<string, string | string[] | undefined>>): boolean;
79
+ /**
80
+ * JSON or HTML for an error answer (D-0074 §1, D-0092 §1). HTML for a sealed form submission
81
+ * (`x-dokebi-form: 1`: the HTML form flow). JSON for every script: an Inertia request
68
82
  * (`X-Inertia`), `X-Requested-With: XMLHttpRequest`, `Authorization: Bearer …`, a JSON request
69
- * body (a script sent it), a sealed request (D-0062: only sealed JSON leaves), or `Accept`
70
- * preferring JSON. HTML only for what is left when `Accept` prefers HTML: a browser navigation
71
- * or an HTML form post.
83
+ * body (a script sent it), or `Accept` preferring JSON. A sealed request (`sealed`, D-0062) is
84
+ * JSON too unless it is what a browser sends for a page (`method` GET or HEAD without a body, or
85
+ * a native form post; no `x-dokebi-sealed`, `Sec-Fetch-Mode` absent or `navigate`): HTML is not
86
+ * sealed, every JSON answer of a sealed request is. Without `method` a sealed request is JSON.
87
+ * HTML only for what is left when `Accept` prefers HTML: a browser navigation or a form post.
88
+ * Whether a body follows comes from the headers here (Content-Length, Transfer-Encoding).
89
+ */
90
+ export declare function errorFormat(headers: Readonly<Record<string, string | string[] | undefined>>, sealed?: boolean, method?: string): WebErrorFormat;
91
+ /**
92
+ * `errorFormat` of a request (the rule dokebi-web answers its own errors with): its headers and
93
+ * method, and whether it carries a body from the request itself — an HTTP/2 request needs no
94
+ * Content-Length, so its headers alone do not say it (audit r4 step 2). For a plugin that writes
95
+ * its own error answers (dokebi-auth's sign-in refusals). `sealed`: `web.sealOf(request) !==
96
+ * undefined`.
72
97
  */
73
- export declare function errorFormat(headers: Readonly<Record<string, string | string[] | undefined>>, sealed?: boolean): WebErrorFormat;
98
+ export declare function requestErrorFormat(request: FastifyRequest, sealed?: boolean): WebErrorFormat;
74
99
  /** The `fields` of a body that are well formed (a hook may have returned anything). */
75
100
  export declare function bodyFields(body: WebErrorBody): WebFieldError[];
76
101
  /**
package/dist/responses.js CHANGED
@@ -1,4 +1,5 @@
1
1
  import { DokebiError, isDokebiError } from '@dokebi/core';
2
+ import { bodyFollows } from './body.js';
2
3
  // Not `import … from 'node:http'`: the ESM facade of node:http reads every export, and its lazy
3
4
  // WebSocket/fetch getters load undici — about 9 ms of every start (D-0070 §5). Fastify already
4
5
  // loaded node:http through require, so this costs nothing.
@@ -194,18 +195,79 @@ export function prefersHtml(accept) {
194
195
  }
195
196
  /** A JSON media type: `application/json`, `application/problem+json`, … */
196
197
  const JSON_TYPE = /^application\/(?:[a-z0-9.+-]+\+)?json$/;
198
+ /** Body types a browser sends for a `<form method="post">` without script. */
199
+ const NATIVE_FORM_TYPES = new Set(['application/x-www-form-urlencoded', 'multipart/form-data']);
197
200
  function headerValue(value) {
198
201
  return Array.isArray(value) ? value[0] : value;
199
202
  }
200
203
  /**
201
- * JSON or HTML for an error answer (D-0074 §1). JSON for every script: an Inertia request
204
+ * The request header the seal forms module (`@dokebi/seal/forms`) sends with a sealed form
205
+ * submission, value `1` (D-0092 §1.2). The request is a form post: its errors follow the HTML
206
+ * form flow, and its sealed body has the shape of a parsed urlencoded body.
207
+ */
208
+ export const FORM_SUBMISSION_HEADER = 'x-dokebi-form';
209
+ /** The request header `sealedFetch` sends on a seal host: a script, never a page navigation. */
210
+ export const SEALED_FETCH_HEADER = 'x-dokebi-sealed';
211
+ /** True when the request carries the seal forms marker `x-dokebi-form: 1`. */
212
+ export function sealedFormMarker(headers) {
213
+ return headerValue(headers[FORM_SUBMISSION_HEADER]) === '1';
214
+ }
215
+ /** A request carries a body when it says so (Content-Length above 0 or Transfer-Encoding). */
216
+ function carriesBody(headers) {
217
+ if (headers['transfer-encoding'] !== undefined)
218
+ return true;
219
+ const length = headerValue(headers['content-length']);
220
+ return length !== undefined && length !== '0';
221
+ }
222
+ /**
223
+ * What a browser itself sends when it loads a page (D-0092 §1.1): a GET or HEAD without a body,
224
+ * or a native `<form method="post">` body (urlencoded or multipart, a page without its seal
225
+ * script), and no script marker (`x-dokebi-sealed`, a `Sec-Fetch-Mode` other than `navigate`).
226
+ * The remaining script markers and `Accept` are checked by `errorFormat` for every request.
227
+ */
228
+ function browserLoad(headers, method, body) {
229
+ if (headers[SEALED_FETCH_HEADER] !== undefined)
230
+ return false;
231
+ const mode = headerValue(headers['sec-fetch-mode']);
232
+ if (mode !== undefined && mode.toLowerCase() !== 'navigate')
233
+ return false;
234
+ if (method === 'GET' || method === 'HEAD')
235
+ return !(body ?? carriesBody(headers));
236
+ if (method !== 'POST')
237
+ return false;
238
+ const type = headerValue(headers['content-type']);
239
+ return (type !== undefined && NATIVE_FORM_TYPES.has(type.split(';', 1)[0]?.trim().toLowerCase() ?? ''));
240
+ }
241
+ /**
242
+ * JSON or HTML for an error answer (D-0074 §1, D-0092 §1). HTML for a sealed form submission
243
+ * (`x-dokebi-form: 1`: the HTML form flow). JSON for every script: an Inertia request
202
244
  * (`X-Inertia`), `X-Requested-With: XMLHttpRequest`, `Authorization: Bearer …`, a JSON request
203
- * body (a script sent it), a sealed request (D-0062: only sealed JSON leaves), or `Accept`
204
- * preferring JSON. HTML only for what is left when `Accept` prefers HTML: a browser navigation
205
- * or an HTML form post.
245
+ * body (a script sent it), or `Accept` preferring JSON. A sealed request (`sealed`, D-0062) is
246
+ * JSON too unless it is what a browser sends for a page (`method` GET or HEAD without a body, or
247
+ * a native form post; no `x-dokebi-sealed`, `Sec-Fetch-Mode` absent or `navigate`): HTML is not
248
+ * sealed, every JSON answer of a sealed request is. Without `method` a sealed request is JSON.
249
+ * HTML only for what is left when `Accept` prefers HTML: a browser navigation or a form post.
250
+ * Whether a body follows comes from the headers here (Content-Length, Transfer-Encoding).
251
+ */
252
+ export function errorFormat(headers, sealed = false, method) {
253
+ return formatOf(headers, sealed, method, undefined);
254
+ }
255
+ /**
256
+ * `errorFormat` of a request (the rule dokebi-web answers its own errors with): its headers and
257
+ * method, and whether it carries a body from the request itself — an HTTP/2 request needs no
258
+ * Content-Length, so its headers alone do not say it (audit r4 step 2). For a plugin that writes
259
+ * its own error answers (dokebi-auth's sign-in refusals). `sealed`: `web.sealOf(request) !==
260
+ * undefined`.
206
261
  */
207
- export function errorFormat(headers, sealed = false) {
208
- if (sealed || headers['x-inertia'] !== undefined)
262
+ export function requestErrorFormat(request, sealed = false) {
263
+ return formatOf(request.headers, sealed, request.method, bodyFollows(request));
264
+ }
265
+ function formatOf(headers, sealed, method, body) {
266
+ if (sealedFormMarker(headers))
267
+ return 'html';
268
+ if (headers['x-inertia'] !== undefined)
269
+ return 'json';
270
+ if (sealed && !browserLoad(headers, method, body))
209
271
  return 'json';
210
272
  const requestedWith = headerValue(headers['x-requested-with']);
211
273
  if (requestedWith !== undefined && requestedWith.toLowerCase() === 'xmlhttprequest')
@@ -0,0 +1,38 @@
1
+ /** A route `config` key a plugin reads (`web.routeConfig`, D-0076 §5). */
2
+ export interface WebRouteConfigKey {
3
+ /** The key under a route's `config`, for example `auth`. */
4
+ readonly key: string;
5
+ /** The plugin that reads it, named in errors. */
6
+ readonly plugin: string;
7
+ /** Checks one route's value at start: a sentence that says what is wrong, or undefined. */
8
+ check(value: unknown): string | undefined;
9
+ /**
10
+ * Optional: called once at start, when no route config problem was found, with every route
11
+ * that sets the key (the HEAD route Fastify adds to a GET left out), so the plugin can report
12
+ * them (dokebi-csrf logs the routes with `csrf: false`). Not called when the start fails.
13
+ */
14
+ routes?(routes: readonly WebRouteConfigUse[]): void;
15
+ }
16
+ /** One route that sets a declared key, as `WebRouteConfigKey.routes` receives it. */
17
+ export interface WebRouteConfigUse {
18
+ /** `GET`, `POST`, … (several joined with commas). */
19
+ readonly method: string;
20
+ /** The route pattern, for example `/posts/:id`. */
21
+ readonly url: string;
22
+ /** The route's value of the key. */
23
+ readonly value: unknown;
24
+ }
25
+ /** The problem of a route `config.id` value, or undefined when it is a valid id. */
26
+ export declare function routeIdProblem(value: unknown): string | undefined;
27
+ /** `config.requestTimeoutMs`: this route's time to receive its body, in ms (an upload route). */
28
+ export declare const MAX_TIMEOUT_MS = 2147483647;
29
+ export declare class RouteConfigKeys {
30
+ #private;
31
+ /** Keys declared by other plugins (dokebi-web's own six not counted). */
32
+ get size(): number;
33
+ add(definition: WebRouteConfigKey): void;
34
+ /** Called from onRoute for every route (start-up cost only). */
35
+ record(method: string | readonly string[], url: string, config: unknown): void;
36
+ /** Problems of every recorded route, one sentence each; the record is dropped afterwards. */
37
+ check(): string[];
38
+ }
@@ -0,0 +1,222 @@
1
+ // Route `config` keys other plugins read (D-0076 §5): dokebi-auth reads `config.auth`, dokebi-csrf
2
+ // `config.csrf`. Those plugins set up after dokebi-web (they depend on it), so they register the
3
+ // key on a slot like the error responders instead of a contribution point dokebi-web would collect
4
+ // (that would need them to set up first: a cycle). Every route is recorded when it is added; the
5
+ // values and near-miss names (`csfr`) are checked once at start, after Fastify is ready, so a typo
6
+ // fails the start instead of silently leaving a route unprotected. Nothing runs per request.
7
+ // `config.id` (D-0077 A), `config.compress` (D-0125), `config.securityHeaders` (D-0149) and
8
+ // `config.overload` (D-0150) are dokebi-web's own keys, declared here from the start.
9
+ import { WebError } from './errors.js';
10
+ import { ROUTE_ID } from './points.js';
11
+ import { securityHeadersProblem } from './security-headers.js';
12
+ /** Keys of dokebi-web itself and of Fastify (`url`, `method` are filled in by Fastify). */
13
+ const OWN_KEYS = new Set(['dokebiHealth', 'dokebiSeal', 'url', 'method']);
14
+ const KEY = /^[A-Za-z][A-Za-z0-9]{1,63}$/;
15
+ /** The problem of a route `config.id` value, or undefined when it is a valid id. */
16
+ export function routeIdProblem(value) {
17
+ if (typeof value === 'string' && ROUTE_ID.test(value))
18
+ return undefined;
19
+ const shown = typeof value === 'string'
20
+ ? JSON.stringify(value.length > 70 ? `${value.slice(0, 67)}...` : value)
21
+ : `a ${value === null ? 'null' : typeof value}`;
22
+ return `must be a string of 1 to 64 letters, digits, '.', '_' or '-' that starts with a letter (for example 'API-12'), not ${shown}`;
23
+ }
24
+ /** `config.id`: owned by dokebi-web itself, checked and typo-matched like a plugin key. */
25
+ const ID_KEY = Object.freeze({
26
+ key: 'id',
27
+ plugin: 'dokebi-web',
28
+ check: routeIdProblem,
29
+ });
30
+ /** `config.compress` (D-0125): `false` keeps a route's answers uncompressed. Read at onRoute. */
31
+ const COMPRESS_KEY = Object.freeze({
32
+ key: 'compress',
33
+ plugin: 'dokebi-web',
34
+ check: (value) => typeof value === 'boolean'
35
+ ? undefined
36
+ : `must be true or false (false: this route's answers are never compressed), not ${value === null ? 'null' : typeof value}`,
37
+ });
38
+ /** `config.securityHeaders` (D-0149): `false` or the settings to change on this route. */
39
+ const SECURITY_KEY = Object.freeze({
40
+ key: 'securityHeaders',
41
+ plugin: 'dokebi-web',
42
+ check: securityHeadersProblem,
43
+ });
44
+ /** `config.overload` (D-0150): `false` serves the route while the server sheds load. */
45
+ const OVERLOAD_KEY = Object.freeze({
46
+ key: 'overload',
47
+ plugin: 'dokebi-web',
48
+ check: (value) => typeof value === 'boolean'
49
+ ? undefined
50
+ : `must be true or false (false: served while the server sheds load), not ${value === null ? 'null' : typeof value}`,
51
+ });
52
+ /**
53
+ * `config.readiness` (M51): `false` serves the route while a required dependency is down
54
+ * (NOT_READY) and while the app drains, like the health routes: a metrics scrape or a status
55
+ * page is needed most then. It is still refused before the app runs (STARTING).
56
+ */
57
+ const READINESS_KEY = Object.freeze({
58
+ key: 'readiness',
59
+ plugin: 'dokebi-web',
60
+ check: (value) => typeof value === 'boolean'
61
+ ? undefined
62
+ : `must be true or false (false: served while not ready and while draining), not ${value === null ? 'null' : typeof value}`,
63
+ });
64
+ /** `config.requestTimeoutMs`: this route's time to receive its body, in ms (an upload route). */
65
+ export const MAX_TIMEOUT_MS = 2_147_483_647;
66
+ const REQUEST_TIMEOUT_KEY = Object.freeze({
67
+ key: 'requestTimeoutMs',
68
+ plugin: 'dokebi-web',
69
+ check: (value) => typeof value === 'number' && Number.isInteger(value) && value >= 1 && value <= MAX_TIMEOUT_MS
70
+ ? undefined
71
+ : `must be whole milliseconds from 1 to ${MAX_TIMEOUT_MS} (the time this route's body may take to arrive), not ${value === null ? 'null' : typeof value === 'number' ? value : typeof value}`,
72
+ });
73
+ /**
74
+ * Options of `web.route()` itself that read like route config keys. The per-route switches
75
+ * `overload`, `readiness`, `compress`, `securityHeaders` and `requestTimeoutMs` live in `config`;
76
+ * these do not, and in `config` nothing reads them.
77
+ */
78
+ const ROUTE_OPTIONS_NOT_CONFIG = new Map([
79
+ [
80
+ 'seal',
81
+ '`seal` is an option of the route itself, beside method and url: route({ method, url, seal: false, handler }) (D-0062)',
82
+ ],
83
+ ]);
84
+ export class RouteConfigKeys {
85
+ #keys = new Map([
86
+ ['id', ID_KEY],
87
+ ['compress', COMPRESS_KEY],
88
+ ['securityHeaders', SECURITY_KEY],
89
+ ['overload', OVERLOAD_KEY],
90
+ ['readiness', READINESS_KEY],
91
+ ['requestTimeoutMs', REQUEST_TIMEOUT_KEY],
92
+ ]);
93
+ #routes = [];
94
+ /** Keys declared by other plugins (dokebi-web's own six not counted). */
95
+ get size() {
96
+ return this.#keys.size - 6;
97
+ }
98
+ add(definition) {
99
+ const { key, plugin, check, routes } = (definition ?? {});
100
+ if (typeof key !== 'string' || !KEY.test(key) || OWN_KEYS.has(key))
101
+ throw new WebError('INVALID_ARGUMENT', `Route config key ${String(key)} is not allowed`, {
102
+ fix: 'Name the key with letters and digits (2-64, starting with a letter), not dokebiHealth, dokebiSeal, url or method.',
103
+ });
104
+ if (typeof plugin !== 'string' ||
105
+ plugin === '' ||
106
+ typeof check !== 'function' ||
107
+ (routes !== undefined && typeof routes !== 'function'))
108
+ throw new WebError('INVALID_ARGUMENT', 'A route config key needs plugin and check', {
109
+ fix: "Pass { key, plugin: 'dokebi-…', check: (value) => string | undefined, routes?: (routes) => void }.",
110
+ });
111
+ const taken = this.#keys.get(key);
112
+ if (taken)
113
+ throw new WebError('INVALID_ARGUMENT', `Route config key ${key} is already read by ${taken.plugin}`, { fix: `Use another key for ${plugin}: two plugins cannot read one route config key.` });
114
+ this.#keys.set(key, Object.freeze({ key, plugin, check, ...(routes === undefined ? {} : { routes }) }));
115
+ }
116
+ /** Called from onRoute for every route (start-up cost only). */
117
+ record(method, url, config) {
118
+ if (config === null || typeof config !== 'object')
119
+ return;
120
+ const names = Object.keys(config).filter((name) => !OWN_KEYS.has(name));
121
+ if (names.length === 0)
122
+ return;
123
+ this.#routes.push({
124
+ method: Array.isArray(method) ? method.join(',') : String(method),
125
+ url,
126
+ config: config,
127
+ });
128
+ }
129
+ /** Problems of every recorded route, one sentence each; the record is dropped afterwards. */
130
+ check() {
131
+ const problems = [];
132
+ // Fastify adds a HEAD route with the same config to every GET route: said once, for GET.
133
+ const said = new Set();
134
+ const keys = [...this.#keys.keys()];
135
+ const add = (route, rest) => {
136
+ const same = `${route.url}\u0000${rest}`;
137
+ if (route.method === 'HEAD' && said.has(same))
138
+ return;
139
+ said.add(same);
140
+ problems.push(`${route.method} ${route.url}: ${rest}`);
141
+ };
142
+ const gets = new Set(this.#routes
143
+ .filter((route) => route.method.split(',').includes('GET'))
144
+ .map((route) => route.url));
145
+ const uses = new Map();
146
+ for (const route of this.#routes)
147
+ for (const [name, value] of Object.entries(route.config)) {
148
+ if (OWN_KEYS.has(name))
149
+ continue;
150
+ const where = `config.${name}`;
151
+ const known = this.#keys.get(name);
152
+ if (known) {
153
+ let problem;
154
+ try {
155
+ problem = known.check(value);
156
+ }
157
+ catch (error) {
158
+ problem = `the check of ${known.plugin} failed: ${error instanceof Error ? error.message : String(error)}`;
159
+ }
160
+ if (problem !== undefined)
161
+ add(route, `${where} (${known.plugin}): ${problem}`);
162
+ else if (known.routes && !(route.method === 'HEAD' && gets.has(route.url))) {
163
+ let list = uses.get(name);
164
+ if (!list) {
165
+ list = [];
166
+ uses.set(name, list);
167
+ }
168
+ list.push(Object.freeze({ method: route.method, url: route.url, value }));
169
+ }
170
+ continue;
171
+ }
172
+ // A route option written into config (2026-10-28: `config: { seal: false }` was ignored
173
+ // without a word, so the answer stayed sealed): said with where it belongs.
174
+ const option = ROUTE_OPTIONS_NOT_CONFIG.get(name);
175
+ if (option) {
176
+ add(route, `${where} is not read: ${option}`);
177
+ continue;
178
+ }
179
+ const near = keys.find((key) => close(name, key));
180
+ if (near)
181
+ add(route, `${where} is not a known key; did you mean config.${near}?`);
182
+ }
183
+ this.#routes = [];
184
+ if (problems.length)
185
+ return problems;
186
+ for (const [name, list] of uses) {
187
+ const known = this.#keys.get(name);
188
+ try {
189
+ known.routes?.(Object.freeze(list));
190
+ }
191
+ catch (error) {
192
+ problems.push(`the routes callback of ${known.plugin} for config.${name} failed: ${error instanceof Error ? error.message : String(error)}`);
193
+ }
194
+ }
195
+ return problems;
196
+ }
197
+ }
198
+ /** Same key in another case, or at most two edits away (keys of 4+ letters): a likely typo. */
199
+ function close(name, key) {
200
+ const a = name.toLowerCase();
201
+ const b = key.toLowerCase();
202
+ if (a === b)
203
+ return true;
204
+ if (Math.min(a.length, b.length) < 4 || Math.abs(a.length - b.length) > 2)
205
+ return false;
206
+ return distance(a, b) <= 2;
207
+ }
208
+ /** Optimal string alignment distance (Levenshtein with adjacent swaps). */
209
+ function distance(a, b) {
210
+ const rows = Array.from({ length: a.length + 1 }, (_, i) => Array.from({ length: b.length + 1 }, (_, j) => (i === 0 ? j : j === 0 ? i : 0)));
211
+ for (let i = 1; i <= a.length; i++)
212
+ for (let j = 1; j <= b.length; j++) {
213
+ const row = rows[i];
214
+ const above = rows[i - 1];
215
+ const cost = a[i - 1] === b[j - 1] ? 0 : 1;
216
+ let best = Math.min(above[j] + 1, row[j - 1] + 1, above[j - 1] + cost);
217
+ if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1])
218
+ best = Math.min(best, rows[i - 2][j - 2] + 1);
219
+ row[j] = best;
220
+ }
221
+ return rows[a.length][b.length];
222
+ }
@@ -0,0 +1,75 @@
1
+ import type { FastifyReply, FastifyRequest } from 'fastify';
2
+ /** A route as a route hook sees it, once, when it is added. */
3
+ export interface WebRouteInfo {
4
+ /** The method, or several joined by commas (`GET`, `HEAD`, `GET,POST`). */
5
+ readonly method: string;
6
+ /** The full path with the scope prefix. */
7
+ readonly url: string;
8
+ /** The route's `config` (`{}` when it has none). */
9
+ readonly config: Readonly<Record<string, unknown>>;
10
+ /** The route's constraints (`{ dokebiApp: 'admin' }` for a route of an app, `{}` otherwise). */
11
+ readonly constraints: Readonly<Record<string, unknown>>;
12
+ /**
13
+ * True for a route added before the hook was registered: Fastify has already copied its config,
14
+ * so `data` cannot be added (a preValidation hook still can).
15
+ */
16
+ readonly configFixed: boolean;
17
+ }
18
+ /** An async preValidation hook for one route; return `reply` after sending an answer. */
19
+ export type WebRoutePreValidation = (request: FastifyRequest, reply: FastifyReply) => Promise<unknown>;
20
+ /** Runs after a response completes. Call done exactly once; the response cannot be changed. */
21
+ export type WebRouteOnResponse = (request: FastifyRequest, reply: FastifyReply, done: (error?: Error) => void) => void;
22
+ /**
23
+ * Observes a response of this route once it was written (not when the client left before that):
24
+ * synchronous, after every hook, from dokebi-web's own response tracking — no Fastify hook, so it
25
+ * costs a request about one call. `elapsedMs` runs from the request's first onRequest step to the
26
+ * response's close. A throw is logged, never answered (the response is gone).
27
+ */
28
+ export type WebRouteCompleted = (request: FastifyRequest, reply: FastifyReply, elapsedMs: number) => void;
29
+ /**
30
+ * The observers of one route under this key of its config, an array every route gets from
31
+ * dokebi-web's onRoute (before Fastify copies the config), so hooks registered later still add
32
+ * to it. Read per request through the route context.
33
+ */
34
+ export declare const COMPLETED: unique symbol;
35
+ /** What a route hook adds to one route. */
36
+ export interface WebRouteAddition {
37
+ /**
38
+ * Runs for this route only, in Fastify's preValidation phase: after the body is parsed and the
39
+ * global preValidation hooks, before the route's own hooks and schema validation.
40
+ */
41
+ readonly preValidation?: WebRoutePreValidation;
42
+ /** Appended after existing response hooks; also works on earlier registered routes. */
43
+ readonly onResponse?: WebRouteOnResponse;
44
+ /**
45
+ * Called after this route's response was written; also works on earlier registered routes.
46
+ * Cheaper than `onResponse` for an observer that only reads the reply (metrics).
47
+ */
48
+ readonly completed?: WebRouteCompleted;
49
+ /**
50
+ * Values merged into the route's config under symbol keys (`request.routeOptions.config[key]`).
51
+ * Not for a route whose `configFixed` is true.
52
+ */
53
+ readonly data?: Readonly<Record<symbol, unknown>>;
54
+ }
55
+ /** A plugin's per-route decision (`web.routeHook`, D-0076 §3.8). */
56
+ export interface WebRouteHook {
57
+ /** The plugin, named in errors. */
58
+ readonly plugin: string;
59
+ /** Called once per route when it is added (earlier routes when this is registered). */
60
+ route(route: WebRouteInfo): WebRouteAddition | undefined;
61
+ }
62
+ type RouteFields = Record<string | symbol, unknown>;
63
+ export declare class RouteHooks {
64
+ #private;
65
+ constructor(wrapResponse: (hook: WebRouteOnResponse) => WebRouteOnResponse);
66
+ get size(): number;
67
+ /** True once a hook gave some route a `completed` observer (final at start). */
68
+ get completing(): boolean;
69
+ add(definition: WebRouteHook): number;
70
+ /** From onRoute: every registered hook decides for this route, and later ones will too. */
71
+ offer(fields: RouteFields): void;
72
+ /** At start every route is known to the hooks there are: the list is not needed any more. */
73
+ close(): void;
74
+ }
75
+ export {};