@dokebi/web 0.4.2 → 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 -39
  2. package/README.md +31 -10
  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 +24 -3
  23. package/dist/forms.d.ts +23 -7
  24. package/dist/forms.js +53 -13
  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 +259 -24
  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
@@ -0,0 +1,118 @@
1
+ // Per-route hooks of other plugins (D-0076 §3.8): dokebi-auth protects only the routes that need
2
+ // it. A global Fastify hook would run on every request of every route, and it could not see which
3
+ // app a route belongs to (the dokebi-app host constraint is not part of `request.routeOptions`).
4
+ // So dokebi-web, whose onRoute hook sees every route (it is on the root before any other plugin
5
+ // adds one), asks each registered plugin once per route what to add: a preValidation hook for that
6
+ // route alone and/or values under symbol keys in its config. Routes added before the plugin's
7
+ // setup are offered when it registers, so the setup order does not matter for the hook (Fastify
8
+ // reads route hooks at ready); their config was already copied into the route context, so those
9
+ // cannot take `data` (`configFixed`). Health routes are never offered. Nothing runs per request
10
+ // for routes a plugin leaves alone.
11
+ import { WebError } from './errors.js';
12
+ /**
13
+ * The observers of one route under this key of its config, an array every route gets from
14
+ * dokebi-web's onRoute (before Fastify copies the config), so hooks registered later still add
15
+ * to it. Read per request through the route context.
16
+ */
17
+ export const COMPLETED = Symbol('dokebi-web.completed');
18
+ const EMPTY = Object.freeze({});
19
+ function invalid(plugin, what) {
20
+ return new WebError('INVALID_ARGUMENT', `The route hook of ${plugin} returned ${what}`, {
21
+ fix: `Return undefined or { preValidation?: async (request, reply) => …, onResponse?: (request, reply, done) => …, completed?: (request, reply, elapsedMs) => …, data?: { [symbol]: value } } from the route hook of ${plugin}.`,
22
+ });
23
+ }
24
+ export class RouteHooks {
25
+ #hooks = [];
26
+ /** Routes seen so far, offered to hooks registered later; dropped at start. */
27
+ #seen = [];
28
+ #wrapResponse;
29
+ constructor(wrapResponse) {
30
+ this.#wrapResponse = wrapResponse;
31
+ }
32
+ get size() {
33
+ return this.#hooks.length;
34
+ }
35
+ /** True once a hook gave some route a `completed` observer (final at start). */
36
+ get completing() {
37
+ return this.#completing;
38
+ }
39
+ #completing = false;
40
+ add(definition) {
41
+ const { plugin, route } = (definition ?? {});
42
+ if (typeof plugin !== 'string' || plugin === '' || typeof route !== 'function')
43
+ throw new WebError('INVALID_ARGUMENT', 'A route hook needs plugin and route', {
44
+ fix: "Pass { plugin: 'dokebi-…', route: (route) => ({ preValidation }) | undefined }.",
45
+ });
46
+ const hook = Object.freeze({ plugin, route: route.bind(definition) });
47
+ this.#hooks.push(hook);
48
+ let offered = 0;
49
+ for (const fields of this.#seen ?? []) {
50
+ this.#apply(hook, fields, true);
51
+ offered++;
52
+ }
53
+ return offered;
54
+ }
55
+ /** From onRoute: every registered hook decides for this route, and later ones will too. */
56
+ offer(fields) {
57
+ // A fresh list per route: Fastify's HEAD twin starts from a copy of the GET's config.
58
+ fields.config = { ...fields.config, [COMPLETED]: [] };
59
+ this.#seen?.push(fields);
60
+ for (const hook of this.#hooks)
61
+ this.#apply(hook, fields, false);
62
+ }
63
+ /** At start every route is known to the hooks there are: the list is not needed any more. */
64
+ close() {
65
+ this.#seen = undefined;
66
+ }
67
+ #apply(hook, fields, configFixed) {
68
+ const method = fields.method;
69
+ const info = Object.freeze({
70
+ method: Array.isArray(method) ? method.join(',') : String(method),
71
+ url: String(fields.url ?? fields.path ?? ''),
72
+ config: fields.config ?? EMPTY,
73
+ constraints: fields.constraints ?? EMPTY,
74
+ configFixed,
75
+ });
76
+ const addition = hook.route(info);
77
+ if (addition === undefined)
78
+ return;
79
+ if (addition === null || typeof addition !== 'object')
80
+ throw invalid(hook.plugin, 'a non-object');
81
+ const { preValidation, onResponse, completed, data } = addition;
82
+ if (preValidation !== undefined && typeof preValidation !== 'function')
83
+ throw invalid(hook.plugin, 'a preValidation that is not a function');
84
+ if (onResponse !== undefined && typeof onResponse !== 'function')
85
+ throw invalid(hook.plugin, 'an onResponse that is not a function');
86
+ if (completed !== undefined && typeof completed !== 'function')
87
+ throw invalid(hook.plugin, 'a completed that is not a function');
88
+ if (data !== undefined) {
89
+ if (data === null || typeof data !== 'object' || Object.keys(data).length > 0)
90
+ throw invalid(hook.plugin, 'data that is not an object of symbol keys');
91
+ if (configFixed)
92
+ throw invalid(hook.plugin, 'data for a route whose config is fixed');
93
+ // Fastify copies the route config into the route context after every onRoute hook
94
+ // (symbol keys included), so the values are there per request without a lookup.
95
+ fields.config = { ...fields.config, ...data };
96
+ }
97
+ if (completed) {
98
+ // The same list the route context holds (Fastify copies the config shallowly).
99
+ fields.config[COMPLETED].push(completed);
100
+ this.#completing = true;
101
+ }
102
+ if (onResponse) {
103
+ const existing = fields.onResponse;
104
+ const response = this.#wrapResponse(onResponse);
105
+ fields.onResponse =
106
+ existing === undefined
107
+ ? response
108
+ : [...(Array.isArray(existing) ? existing : [existing]), response];
109
+ }
110
+ if (preValidation) {
111
+ const existing = fields.preValidation;
112
+ fields.preValidation =
113
+ existing === undefined
114
+ ? preValidation
115
+ : [preValidation, ...(Array.isArray(existing) ? existing : [existing])];
116
+ }
117
+ }
118
+ }
@@ -0,0 +1,55 @@
1
+ /** One route as `web.routes()` lists it (D-0077 A). */
2
+ export interface WebRouteEntry {
3
+ /** The method, or several joined by commas (`GET`, `GET,POST`), as in `WebRouteInfo`. */
4
+ readonly method: string;
5
+ /** The full path with the scope prefix (`/admin/posts/:id`). */
6
+ readonly url: string;
7
+ /** The route's `config.id`, when it has one. */
8
+ readonly id?: string;
9
+ /**
10
+ * The route's constraints as text (`{ dokebiApp: 'admin' }` for a route of an app, a RegExp
11
+ * `host` as its source `/…/`); `{}` when it has none.
12
+ */
13
+ readonly constraints: Readonly<Record<string, string>>;
14
+ /** The string keys of its `config` (`id`, `auth`, `csrf`, `dokebiSeal`, …), without `url`/`method`. */
15
+ readonly configKeys: readonly string[];
16
+ /** The plugin that added the route itself (D-0142: `POST /mcp` is `dokebi-mcp`'s). */
17
+ readonly plugin?: string;
18
+ }
19
+ /** A route id on more than one route of the same app (`DUPLICATE_ROUTE_ID`). */
20
+ export interface WebDuplicateRouteId {
21
+ readonly id: string;
22
+ /**
23
+ * `GET /a`, `POST /b` (with ` [dokebiApp=admin]` when the routes are constrained). When a
24
+ * plugin's own route is among them (D-0142) each names its owner: `POST /mcp (dokebi-mcp
25
+ * routeIds.endpoint)`, `GET /x [dokebiApp=mcp] (application)`.
26
+ */
27
+ readonly routes: readonly string[];
28
+ /** The plugin routes among them as `<plugin> routeIds.<key>` (D-0142); absent when none. */
29
+ readonly owners?: readonly string[];
30
+ }
31
+ /**
32
+ * What describe mode (D-0077 B) keeps besides an entry: the route's schema and its config values,
33
+ * in the order of `routes()`. Never recorded outside describe mode.
34
+ */
35
+ export interface RouteDetails {
36
+ readonly schema: unknown;
37
+ readonly config: Readonly<Record<string, unknown>>;
38
+ }
39
+ export declare class RouteTable {
40
+ #private;
41
+ /** `details`: also keep each route's schema and config values (describe mode, D-0077 B). */
42
+ constructor(details?: boolean);
43
+ /** Called from onRoute for every route (start-up cost only). */
44
+ record(method: string | readonly string[], url: string, config: unknown, constraints: unknown, schema?: unknown): void;
45
+ /** Describe mode: the schema and config values of `routes()[i]`; undefined otherwise. */
46
+ details(): readonly RouteDetails[] | undefined;
47
+ /** The routes recorded so far, frozen; the same array until another route is added. */
48
+ routes(): readonly WebRouteEntry[];
49
+ /**
50
+ * Ids on more than one route of the same constraints (one app, or the routes outside apps).
51
+ * Two registrations with the same method, path (a trailing slash aside) and constraints are one
52
+ * route. The same id in two apps is allowed: a module mounted in both apps is one route.
53
+ */
54
+ duplicateIds(): WebDuplicateRouteId[];
55
+ }
@@ -0,0 +1,142 @@
1
+ // Every route dokebi-web saw (D-0077 A): what `web.routes()` gives other plugins (the route list
2
+ // of `dokebi describe`), and the duplicate route id check at start. Recorded from onRoute, so it
3
+ // costs one small object per route at start-up and nothing per request. The HEAD route Fastify
4
+ // adds to every GET is left out: it is the GET route, not a route of the app. A route a plugin
5
+ // adds itself carries its owner (D-0142, `ROUTE_OWNER`): listed as `plugin` and named by the
6
+ // duplicate check.
7
+ import { routeOwnerOf } from './points.js';
8
+ const NO_CONSTRAINTS = Object.freeze({});
9
+ /** Keys Fastify writes into every route config itself. */
10
+ const FASTIFY_KEYS = new Set(['url', 'method']);
11
+ function constraintsOf(value) {
12
+ if (value === null || typeof value !== 'object')
13
+ return NO_CONSTRAINTS;
14
+ const entries = Object.entries(value);
15
+ if (entries.length === 0)
16
+ return NO_CONSTRAINTS;
17
+ return Object.freeze(Object.fromEntries(entries.map(([key, item]) => [key, String(item)])));
18
+ }
19
+ /** The constraints as one comparable key (sorted names). */
20
+ function constraintsKey(constraints) {
21
+ return Object.keys(constraints)
22
+ .sort()
23
+ .map((key) => `${key}=${constraints[key]}`)
24
+ .join('&');
25
+ }
26
+ /** `/board/` and `/board` are one route (dokebi-app answers a prefixed root with both). */
27
+ function samePath(url) {
28
+ return url.length > 1 && url.endsWith('/') ? url.slice(0, -1) : url;
29
+ }
30
+ export class RouteTable {
31
+ #entries = [];
32
+ /** The owner mark of each entry (D-0142), undefined for a route no plugin marked. */
33
+ #owners = [];
34
+ /** Describe mode only: one item per entry. */
35
+ #details;
36
+ /** `details`: also keep each route's schema and config values (describe mode, D-0077 B). */
37
+ constructor(details = false) {
38
+ this.#details = details ? [] : undefined;
39
+ }
40
+ /** `url \0 constraints` of every GET route: the HEAD twin Fastify adds comes right after. */
41
+ #gets = new Set();
42
+ #frozen;
43
+ /** Called from onRoute for every route (start-up cost only). */
44
+ record(method, url, config, constraints, schema) {
45
+ const methods = Array.isArray(method) ? method.map(String) : [String(method)];
46
+ const fixed = constraintsOf(constraints);
47
+ const place = `${url}\u0000${constraintsKey(fixed)}`;
48
+ if (methods.length === 1 && methods[0] === 'HEAD' && this.#gets.has(place))
49
+ return;
50
+ if (methods.includes('GET'))
51
+ this.#gets.add(place);
52
+ const values = config !== null && typeof config === 'object' ? config : {};
53
+ const id = values.id;
54
+ const owner = routeOwnerOf(values);
55
+ this.#entries.push(Object.freeze({
56
+ method: methods.join(','),
57
+ url,
58
+ ...(typeof id === 'string' ? { id } : {}),
59
+ constraints: fixed,
60
+ configKeys: Object.freeze(Object.keys(values).filter((key) => !FASTIFY_KEYS.has(key))),
61
+ ...(owner === undefined ? {} : { plugin: owner.plugin }),
62
+ }));
63
+ this.#owners.push(owner);
64
+ this.#details?.push({ schema, config: values });
65
+ this.#frozen = undefined;
66
+ }
67
+ /** Describe mode: the schema and config values of `routes()[i]`; undefined otherwise. */
68
+ details() {
69
+ return this.#details;
70
+ }
71
+ /** The routes recorded so far, frozen; the same array until another route is added. */
72
+ routes() {
73
+ this.#frozen ??= Object.freeze([...this.#entries]);
74
+ return this.#frozen;
75
+ }
76
+ /**
77
+ * Ids on more than one route of the same constraints (one app, or the routes outside apps).
78
+ * Two registrations with the same method, path (a trailing slash aside) and constraints are one
79
+ * route. The same id in two apps is allowed: a module mounted in both apps is one route.
80
+ */
81
+ duplicateIds() {
82
+ const groups = new Map();
83
+ /** Per id: the plugin routes without constraints (they answer on every host). */
84
+ const everywhere = new Map();
85
+ this.#entries.forEach((entry, index) => {
86
+ if (entry.id === undefined)
87
+ return;
88
+ const where = constraintsKey(entry.constraints);
89
+ const group = `${entry.id}\u0000${where}`;
90
+ let routes = groups.get(group);
91
+ if (!routes) {
92
+ routes = new Map();
93
+ groups.set(group, routes);
94
+ }
95
+ const method = entry.method.split(',').sort().join(',');
96
+ const same = `${method} ${samePath(entry.url)}`;
97
+ const owner = this.#owners[index];
98
+ const seen = {
99
+ text: `${entry.method} ${entry.url}${where ? ` [${where}]` : ''}`,
100
+ owner: owner === undefined ? undefined : `${owner.plugin} routeIds.${owner.key}`,
101
+ };
102
+ if (!routes.has(same))
103
+ routes.set(same, seen);
104
+ if (owner !== undefined && where === '') {
105
+ let list = everywhere.get(entry.id);
106
+ if (!list) {
107
+ list = new Map();
108
+ everywhere.set(entry.id, list);
109
+ }
110
+ // Marked apart: the same method and path of an app is another route than this one.
111
+ list.set(`\u0000${same}`, seen);
112
+ }
113
+ });
114
+ // D-0142: a plugin route bound to no app answers on every host, so its id is taken in every
115
+ // app: it joins each constrained group of the same id.
116
+ if (everywhere.size)
117
+ for (const [group, routes] of groups) {
118
+ const cut = group.indexOf('\u0000');
119
+ if (cut === group.length - 1)
120
+ continue;
121
+ for (const [same, seen] of everywhere.get(group.slice(0, cut)) ?? [])
122
+ routes.set(same, seen);
123
+ }
124
+ const duplicates = [];
125
+ for (const [group, routes] of groups) {
126
+ if (routes.size < 2)
127
+ continue;
128
+ const list = [...routes.values()];
129
+ const owners = list.flatMap((seen) => (seen.owner === undefined ? [] : [seen.owner]));
130
+ // One route key of one plugin over several routes (its asset files, one copy per app) is
131
+ // one role: the plugin gives it one id on purpose.
132
+ if (owners.length === list.length && new Set(owners).size === 1)
133
+ continue;
134
+ duplicates.push(Object.freeze({
135
+ id: group.slice(0, group.indexOf('\u0000')),
136
+ routes: Object.freeze(list.map((seen) => owners.length ? `${seen.text} (${seen.owner ?? 'application'})` : seen.text)),
137
+ ...(owners.length ? { owners: Object.freeze([...new Set(owners)]) } : {}),
138
+ }));
139
+ }
140
+ return duplicates;
141
+ }
142
+ }
package/dist/seal.d.ts CHANGED
@@ -36,8 +36,23 @@ export interface WebSealer {
36
36
  }
37
37
  /** Response header naming the path a sealed response was sealed with (after a redirect it is the final one). */
38
38
  export declare const SEALED_PATH_HEADER = "x-dokebi-sealed-path";
39
+ /**
40
+ * Response header of a redirect answered to a sealed form (`x-dokebi-form: 1`, D-0092 §1.2): the
41
+ * 3xx becomes 204 with the `Location` here, and the forms module navigates to it.
42
+ */
43
+ export declare const SEALED_LOCATION_HEADER = "x-dokebi-location";
44
+ /**
45
+ * On a refusal this layer already recorded (the warn `SEAL_BODY_REFUSED`, once per window): the
46
+ * error answer writes no record of its own.
47
+ */
48
+ export declare const RECORDED: unique symbol;
39
49
  /** The media type of a Content-Type value: lower case, without parameters. */
40
50
  export declare function mediaType(value: unknown): string;
51
+ /**
52
+ * Ends a body stream an onSend step replaces: Fastify sends the new payload and never touches the
53
+ * old one, so a file stream kept its descriptor open for the life of the process.
54
+ */
55
+ export declare function discardPayload(payload: unknown, logger: Logger): void;
41
56
  /** `/a/b?c` → `/a/b`. */
42
57
  export declare function pathOf(url: string): string;
43
58
  /** `sealExclude` (validated by the options): prefixes without trailing slashes, unique. */
@@ -46,7 +61,28 @@ export declare function checkSealSetting(value: unknown): WebSealSetting | undef
46
61
  export interface SealingOptions {
47
62
  readonly driftMs: number;
48
63
  readonly exclude: readonly string[];
64
+ /** `formBody`: sealed form bodies (`x-dokebi-form: 1`) are form bodies too (D-0068, D-0092). */
65
+ readonly formBody: boolean;
66
+ /** `formMaxFields`: most values one sealed form body may carry. */
67
+ readonly formMaxFields: number;
68
+ /** `sealRetryAfterMs`: the Retry-After of SEAL_BUSY and SEAL_NONCE_STORE_UNAVAILABLE (D-0114). */
69
+ readonly retryAfterMs?: number;
70
+ /** `logRepeatWindowMs`: the window of the repeated seal refusal logs (D-0114). */
71
+ readonly logRepeatWindowMs?: number;
49
72
  }
73
+ /**
74
+ * The refusal of a request that carries the seal forms marker (`x-dokebi-form`) wrongly, or
75
+ * undefined: the value must be `1`, and a body must be sealed (`sealedType`, the provider's
76
+ * media type) or multipart (a file upload of a sealed form). A body-less request with the marker
77
+ * passes (a redirect a proxy answered, followed by the browser). `body`: `bodyFollows(request)`.
78
+ */
79
+ export declare function formMarkerRefusal(headers: FastifyRequest['headers'], sealedType: string | undefined, body: boolean): WebError | undefined;
80
+ /**
81
+ * The opened body of a sealed form (D-0092 §1.3), checked to have the shape the urlencoded parser
82
+ * gives — an object of strings, a repeated name an array of strings — and returned like it: an
83
+ * object without a prototype (`__proto__` is an ordinary key), at most `maxFields` values.
84
+ */
85
+ export declare function sealedFormBody(value: unknown, maxFields: number): Record<string, string | string[]>;
50
86
  /**
51
87
  * The seal slot of one web server. Requests are sealed by their route (`seal`) or by a
52
88
  * registered predicate (dokebi-app: hosts with `seal: true`); health routes, `seal: false`
@@ -76,8 +112,20 @@ export declare class WebSealing {
76
112
  * callback-style hook and passes the error to `done`, so the error mapping answers it.
77
113
  */
78
114
  refusePlain(request: FastifyRequest): WebError | undefined;
79
- /** The body parser of the sealed media type: opens, then parses JSON. Refusals are 400. */
115
+ /**
116
+ * The body parser of the sealed media type: opens, then parses JSON. A body proven bad (no
117
+ * prefix, plain, drift, replay, does not open) is 400; a body the server could not check (a full
118
+ * nonce store, a failing or slow store, any failure without a known client reason) is a
119
+ * retryable 503 (D-0075, D-0096 §2), never a client error.
120
+ */
80
121
  parse(request: FastifyRequest, body: string): Promise<unknown>;
81
122
  /** onSend: seals the JSON response of a sealed request (other types pass unchanged). */
82
123
  onSend(request: FastifyRequest, reply: FastifyReply, payload: unknown): unknown;
83
124
  }
125
+ /**
126
+ * onSend of a redirect answered to a sealed form (D-0092 §1.2): 204 with the target in
127
+ * `x-dokebi-location` instead of the 3xx, so the browser's fetch does not follow it (it would
128
+ * render the next page — and take its session flash — for an answer the forms module throws
129
+ * away, and a redirect to another origin would fail as a CORS request). Returns the payload.
130
+ */
131
+ export declare function sealedFormRedirect(request: FastifyRequest, reply: FastifyReply, logger: Logger, payload?: unknown): string;