@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.
- package/AI.md +248 -38
- package/README.md +32 -11
- package/dist/app-routes.d.ts +20 -0
- package/dist/app-routes.js +137 -0
- package/dist/before-hijack.d.ts +24 -0
- package/dist/before-hijack.js +73 -0
- package/dist/body.d.ts +14 -0
- package/dist/body.js +30 -0
- package/dist/cluster-ready.d.ts +67 -0
- package/dist/cluster-ready.js +123 -0
- package/dist/compilers.d.ts +16 -0
- package/dist/compilers.js +25 -0
- package/dist/compression.d.ts +40 -0
- package/dist/compression.js +435 -0
- package/dist/connections.d.ts +44 -0
- package/dist/connections.js +282 -0
- package/dist/define-errors.d.ts +76 -0
- package/dist/define-errors.js +161 -0
- package/dist/describe.d.ts +37 -0
- package/dist/describe.js +96 -0
- package/dist/errors.d.ts +1 -1
- package/dist/errors.js +26 -2
- package/dist/forms.d.ts +27 -10
- package/dist/forms.js +75 -17
- package/dist/index.d.ts +134 -4
- package/dist/index.js +1518 -91
- package/dist/options.d.ts +56 -0
- package/dist/options.js +320 -1
- package/dist/points.d.ts +159 -0
- package/dist/points.js +162 -1
- package/dist/responses.d.ts +31 -6
- package/dist/responses.js +68 -6
- package/dist/route-config.d.ts +38 -0
- package/dist/route-config.js +222 -0
- package/dist/route-hooks.d.ts +75 -0
- package/dist/route-hooks.js +118 -0
- package/dist/route-table.d.ts +55 -0
- package/dist/route-table.js +142 -0
- package/dist/seal.d.ts +49 -1
- package/dist/seal.js +261 -20
- package/dist/security-headers.d.ts +121 -0
- package/dist/security-headers.js +298 -0
- package/dist/transient-log.d.ts +42 -0
- package/dist/transient-log.js +95 -0
- package/options.schema.json +488 -1
- package/package.json +22 -9
package/dist/errors.js
CHANGED
|
@@ -3,41 +3,65 @@ import { errorsByField, VALIDATION_HINT } from './responses.js';
|
|
|
3
3
|
const FORM_FIX = 'HTML form bodies (application/x-www-form-urlencoded) are off: set `formBody: true` under dokebi-web in dokebi.yaml, or send JSON. A form post is a cross-site "simple" request: keep the session cookie SameSite=Lax (the @dokebi/session default) or Strict, or check a CSRF token.';
|
|
4
4
|
const FIX = {
|
|
5
5
|
INVALID_ENTRY: 'The web entry (src/infra/web/extension.ts) exports `requires` (plugins Fastify onClose hooks use) and, optionally, `export default class AppWeb extends WebExtension {}`.',
|
|
6
|
-
INVALID_ROUTE: 'Give a route `seal` as true, false or a function of the request.',
|
|
6
|
+
INVALID_ROUTE: 'Give a route `seal` as true, false or a function of the request, a `bodyLimit` of whole bytes up to maxRouteBodyBytes, and `app` as an app name or a list of them.',
|
|
7
7
|
INVALID_HOOK: 'An async Fastify hook must not take the done callback: drop the last parameter, or make the hook a plain function that calls done.',
|
|
8
8
|
INVALID_ARGUMENT: 'Pass a function: web.sealRequests((request) => boolean).',
|
|
9
|
+
INVALID_ROUTE_CONFIG: 'Correct the route `config` values listed in `details.problems` (a plugin such as dokebi-auth or dokebi-csrf reads them; its AI.md lists the allowed values), or rename a misspelled key.',
|
|
10
|
+
DUPLICATE_ROUTE_ID: 'Give each route of an app its own `config.id` (details.duplicates lists the id and its routes), or drop the id from one of them. The same id may repeat in two apps (a module mounted in both), not inside one.',
|
|
9
11
|
INVALID_EXTENSION_RESULT: 'Return what the WebExtension hook documents (src/infra/web/extension.ts): fastifyOptions → a plain object without return503OnClosing/forceCloseConnections, errorBody → { status, body } or undefined, unavailable → { status, headers?, body? } or undefined, synchronously.',
|
|
12
|
+
INVALID_ERROR_TRANSLATOR: 'Contribute { translate(error, request) } to dokebi-web:error-translator (@dokebi/web/points): translate returns a DokebiError (with the error as its cause) or undefined, synchronously, and never throws (details: data.translator).',
|
|
10
13
|
FROZEN: 'Add routes, Fastify plugins, constraints and seal settings during setup, before start.',
|
|
11
14
|
CLOSED: 'Call web.track() only while the application runs.',
|
|
12
15
|
FORM_BODY_DISABLED: FORM_FIX,
|
|
13
16
|
FORM_BODY_TOO_MANY_FIELDS: 'Send fewer form fields, or raise formMaxFields under dokebi-web in dokebi.yaml (1..10000).',
|
|
17
|
+
FORM_BODY_INVALID: 'Send sealed forms with the @dokebi/seal/forms module (D-0092): x-dokebi-form is 1, the body is sealed (or multipart for files) and opens to an object whose values are strings, or arrays of strings for a repeated name.',
|
|
14
18
|
SEAL_PROVIDER_MISSING: 'Register the dokebi-seal plugin (npx dokebi add @dokebi/seal), or remove seal: true from the domains and routes.',
|
|
15
19
|
SEAL_PROVIDER_INVALID: 'Register one seal codec provider (the dokebi-seal plugin) with { contentType, forRequest }.',
|
|
16
20
|
SEAL_REQUIRED: 'This route is sealed (a seal host): send the body sealed with @dokebi/seal (sealedFetch, or the Inertia bridge sealInertia). File uploads use multipart/form-data; webhooks and server-to-server routes set seal: false or are listed in dokebi-web sealExclude.',
|
|
17
21
|
SEAL_BODY_REFUSED: 'Seal request bodies with @dokebi/seal for this host and path, once, within sealDriftMs of the server clock.',
|
|
22
|
+
SEAL_BUSY: 'The one-time nonce store of the seal provider is full of live nonces, so sealed bodies are refused until some expire (fail closed, D-0075): share the nonces in Redis (dokebi-seal nonces.driver: redis, or @dokebi/websocket-hub with mode: cluster), raise dokebi-seal nonces.max, or lower sealDriftMs.',
|
|
23
|
+
SEAL_NONCE_STORE_UNAVAILABLE: 'The seal provider could not check the body: its replay nonce store failed or did not answer in time (Redis down, its pending-command limit reached, a hub outage). The body is refused, not let through (fail closed); this is the server, not the client, so the answer is a retryable 503 (D-0096). The error with the whole cause is logged once: SEAL_NONCE_STORE_UNAVAILABLE of dokebi-seal for its shared stores (Redis, the hub), else WEB_REQUEST_FAILED of dokebi-web; check the store connection and its limits (dokebi-redis maxPending, commandTimeoutMs, dokebi-seal nonces.timeoutMs).',
|
|
24
|
+
SEAL_NONCES_LOST: "The seal provider's replay nonce store lost its nonces (a new process with in-process nonces, a Redis restart without persistence, a FLUSHALL) and this body was stamped before that, so it cannot be checked and is refused; this is the server's state, so the answer is a retryable 503 whose Retry-After says when a body sealed anew passes. A second copy of the same body is 400 SEAL_BODY_REFUSED. Use a Redis with persistence for dokebi-seal nonces.",
|
|
18
25
|
SEAL_BODY_NOT_JSON: 'A sealed request body must be JSON text before sealing.',
|
|
19
26
|
SEAL_STREAM_UNSUPPORTED: 'Send JSON of a sealed request as a string, object or Buffer, not a stream (or set seal: false on the route).',
|
|
20
27
|
VALIDATION_FAILED: 'Correct the fields listed in `fields` (or `errors`): the route schema (schema.body, schema.querystring, schema.params) or the validationError() of the handler refused them.',
|
|
21
|
-
NOT_FOUND: 'Check the method and the path. An app route answers only on the hosts of its
|
|
28
|
+
NOT_FOUND: 'Check the method and the path. An app route, and a route bound to apps (`app`, a plugin option such as dokebi-mcp.app), answers only on the hosts of its apps (dokebi-app domains), a module route only under its mount prefix.',
|
|
29
|
+
ROUTE_APP_UNAVAILABLE: 'A route is bound to an app (`app` of the route, or the app option of the plugin that adds it, such as options.dokebi-mcp.app), but @dokebi/app is not registered: add it (npx dokebi add @dokebi/app) with domains for that app, or remove the app option so the route answers on every host.',
|
|
30
|
+
ROUTE_APP_UNKNOWN: 'Name an app of src/apps/<app> that dokebi-app defines (details.apps lists them) in the app option, or add the app (npx dokebi app add <name> --domain <host>).',
|
|
31
|
+
ROUTE_APP_CONFLICT: 'Two routes with the same method and path answer on one app: bind one of them to other apps (its app option), or move it to another path.',
|
|
32
|
+
REQUEST_TIMEOUT: 'The request body did not arrive within requestTimeoutMs of dokebi-web (data.timeoutMs) after its headers: a stalled or very slow client. For a route that takes long uploads give it config: { requestTimeoutMs } (or raise requestTimeoutMs under dokebi-web in dokebi.yaml).',
|
|
33
|
+
OVERLOADED: 'The server sheds load (D-0150): its event loop delay, event loop utilization, heap or RSS is above a dokebi-web overload limit (data.reason). Retry after Retry-After; for the operator: add capacity, find what blocks the event loop (the debug log of the overload state), or raise dokebi-web overload.* (0 turns one check off).',
|
|
22
34
|
};
|
|
23
35
|
const HINT = {
|
|
24
36
|
FORM_BODY_DISABLED: 'This address does not accept HTML form posts. Send JSON instead.',
|
|
25
37
|
FORM_BODY_TOO_MANY_FIELDS: 'The form has too many fields.',
|
|
38
|
+
FORM_BODY_INVALID: 'The form could not be read. Reload the page and try again.',
|
|
26
39
|
SEAL_REQUIRED: 'This address only accepts sealed requests. Reload the page and try again.',
|
|
27
40
|
SEAL_BODY_REFUSED: 'The request could not be opened. Reload the page and try again.',
|
|
41
|
+
SEAL_BUSY: 'The server is busy. Try again in a moment.',
|
|
42
|
+
SEAL_NONCE_STORE_UNAVAILABLE: 'The server is busy. Try again in a moment.',
|
|
43
|
+
SEAL_NONCES_LOST: 'The server is busy. Try again in a moment.',
|
|
28
44
|
SEAL_BODY_NOT_JSON: 'The request could not be read. Reload the page and try again.',
|
|
29
45
|
VALIDATION_FAILED: VALIDATION_HINT,
|
|
30
46
|
NOT_FOUND: 'The page or resource does not exist.',
|
|
47
|
+
OVERLOADED: 'The server is busy. Try again in a moment.',
|
|
48
|
+
REQUEST_TIMEOUT: 'The request took too long to arrive. Try again.',
|
|
31
49
|
};
|
|
32
50
|
const STATUS = {
|
|
33
51
|
FORM_BODY_DISABLED: 415,
|
|
34
52
|
FORM_BODY_TOO_MANY_FIELDS: 413,
|
|
53
|
+
FORM_BODY_INVALID: 400,
|
|
35
54
|
SEAL_REQUIRED: 415,
|
|
36
55
|
SEAL_BODY_REFUSED: 400,
|
|
56
|
+
SEAL_BUSY: 503,
|
|
57
|
+
SEAL_NONCE_STORE_UNAVAILABLE: 503,
|
|
58
|
+
SEAL_NONCES_LOST: 503,
|
|
37
59
|
SEAL_BODY_NOT_JSON: 400,
|
|
38
60
|
SEAL_STREAM_UNSUPPORTED: 500,
|
|
39
61
|
VALIDATION_FAILED: 422,
|
|
40
62
|
NOT_FOUND: 404,
|
|
63
|
+
OVERLOADED: 503,
|
|
64
|
+
REQUEST_TIMEOUT: 408,
|
|
41
65
|
};
|
|
42
66
|
/**
|
|
43
67
|
* Errors of @dokebi/web; compare `code`, not the class (another installed copy may throw).
|
package/dist/forms.d.ts
CHANGED
|
@@ -8,27 +8,44 @@ export interface WebFormRequest {
|
|
|
8
8
|
}
|
|
9
9
|
/** One value of the old input: the body's top-level scalars. */
|
|
10
10
|
export type WebFormValue = string | number | boolean | null;
|
|
11
|
+
/** The form limits of the web options (`formOldInputMaxChars`, `formRefererMaxLength`, D-0114). */
|
|
12
|
+
export interface WebFormLimits {
|
|
13
|
+
readonly oldInputMaxChars: number;
|
|
14
|
+
readonly refererMaxLength: number;
|
|
15
|
+
}
|
|
11
16
|
/**
|
|
12
|
-
* True when the request
|
|
13
|
-
* or `multipart/form-data
|
|
17
|
+
* True when the request is an HTML form submission: a body of
|
|
18
|
+
* `application/x-www-form-urlencoded` or `multipart/form-data`, as a browser sends a
|
|
19
|
+
* `<form method="post">`, or a sealed form of the seal forms module (`x-dokebi-form: 1`, D-0092
|
|
20
|
+
* §1.3), whose body dokebi-web checked to have the urlencoded shape.
|
|
14
21
|
*/
|
|
15
22
|
export declare function isFormSubmission(headers: Readonly<Record<string, string | string[] | undefined>>): boolean;
|
|
16
23
|
/**
|
|
17
24
|
* Where a refused form goes back (D-0074 §3): the path and query of the `Referer` when it is
|
|
18
|
-
* this host (`host` as `WebApi.requestHost` gives it; another origin is never followed)
|
|
19
|
-
*
|
|
20
|
-
*
|
|
25
|
+
* this host (`host` as `WebApi.requestHost` gives it; another origin is never followed) and the
|
|
26
|
+
* path stays on it (`//other.host/…`, `/\other.host` and their encoded forms are refused, so the
|
|
27
|
+
* answer never reads as another host). Otherwise `fallback` for a POST, PUT, PATCH or DELETE
|
|
28
|
+
* (template-inertia passes `/`), or undefined. A GET or HEAD whose referer is missing or is itself has no way back: a redirect to
|
|
21
29
|
* itself would be refused again, forever.
|
|
22
30
|
*/
|
|
23
|
-
export declare function formBackTarget(request: WebFormRequest, host: string, fallback?: string): string | undefined;
|
|
31
|
+
export declare function formBackTarget(request: WebFormRequest, host: string, fallback?: string, limits?: Partial<WebFormLimits>): string | undefined;
|
|
24
32
|
/**
|
|
25
33
|
* The old input of a refused form (D-0074 §3): the body's top-level strings, numbers, booleans
|
|
26
34
|
* and nulls, without password-like fields (`password`, `token`, `secret`, `api_key`, `card`,
|
|
27
|
-
* `cvc`, `otp`, `pin`…); undefined when nothing is left or it is larger than 8 KB as JSON.
|
|
35
|
+
* `cvc`, `otp`, `pin`…, and every name core's secret rule masks: `pwd`, `privateKey`, `jwt`…); undefined when nothing is left or it is larger than `limits.oldInputMaxChars` (8 KB) as JSON.
|
|
36
|
+
* Pass `web.formLimits` so the web options apply.
|
|
28
37
|
*/
|
|
29
|
-
export declare function formOldInput(body: unknown): Record<string, WebFormValue> | undefined;
|
|
38
|
+
export declare function formOldInput(body: unknown, limits?: Partial<WebFormLimits>): Record<string, WebFormValue> | undefined;
|
|
30
39
|
/**
|
|
31
|
-
* The `
|
|
32
|
-
*
|
|
40
|
+
* The `{ field: message }` errors a refused form goes back with, or undefined when the answer is
|
|
41
|
+
* not one a form goes back from:
|
|
42
|
+
*
|
|
43
|
+
* - a validation answer — a refused route schema or `validationError()` (422
|
|
44
|
+
* `VALIDATION_FAILED`) — gives its `errors`;
|
|
45
|
+
* - any other error whose `data.formErrors` is a `{ field: message }` record of strings gives
|
|
46
|
+
* those (D-0076 §2.5, 0.4.3): a plugin or a handler asks for the form redirect this way, for
|
|
47
|
+
* example dokebi-csrf's expired token `{ _form: 'The form expired. Please submit it again.' }`.
|
|
48
|
+
* `_form` is the key of an error about the whole form. Only 4xx answers go back: the callers
|
|
49
|
+
* (@dokebi/app, @dokebi/template-inertia) check the status.
|
|
33
50
|
*/
|
|
34
51
|
export declare function formFieldErrors(body: WebErrorBody): Record<string, string> | undefined;
|
package/dist/forms.js
CHANGED
|
@@ -1,5 +1,13 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
1
|
+
import { redaction } from '@dokebi/core/libraries';
|
|
2
|
+
import { sealedFormMarker } from './responses.js';
|
|
3
|
+
/**
|
|
4
|
+
* Field names whose values never go into the session as old input, besides every field core's one
|
|
5
|
+
* secret rule masks (`redaction.isSecretField`): form-only ones such as a card number or a CSRF
|
|
6
|
+
* token.
|
|
7
|
+
*/
|
|
8
|
+
const SECRET_FIELD = /pass(?:word|wd|phrase)?|secret|token|api[_-]?key|card|cvc|cvv|otp|csrf|xsrf|pin$/i;
|
|
9
|
+
/** At most this many form-level errors are read from `data.formErrors` (D-0076 §2.5). */
|
|
10
|
+
const FORM_ERRORS_MAX = 64;
|
|
3
11
|
/** Old input kept at most (as JSON text): a larger body is not flashed. */
|
|
4
12
|
const OLD_MAX = 8192;
|
|
5
13
|
/** A Referer longer than this is not followed. */
|
|
@@ -7,10 +15,14 @@ const REFERER_MAX = 4096;
|
|
|
7
15
|
/** Body types of an HTML form submission. */
|
|
8
16
|
const FORM_TYPES = new Set(['application/x-www-form-urlencoded', 'multipart/form-data']);
|
|
9
17
|
/**
|
|
10
|
-
* True when the request
|
|
11
|
-
* or `multipart/form-data
|
|
18
|
+
* True when the request is an HTML form submission: a body of
|
|
19
|
+
* `application/x-www-form-urlencoded` or `multipart/form-data`, as a browser sends a
|
|
20
|
+
* `<form method="post">`, or a sealed form of the seal forms module (`x-dokebi-form: 1`, D-0092
|
|
21
|
+
* §1.3), whose body dokebi-web checked to have the urlencoded shape.
|
|
12
22
|
*/
|
|
13
23
|
export function isFormSubmission(headers) {
|
|
24
|
+
if (sealedFormMarker(headers))
|
|
25
|
+
return true;
|
|
14
26
|
const value = headers['content-type'];
|
|
15
27
|
const type = Array.isArray(value) ? value[0] : value;
|
|
16
28
|
if (type === undefined)
|
|
@@ -19,38 +31,58 @@ export function isFormSubmission(headers) {
|
|
|
19
31
|
}
|
|
20
32
|
/**
|
|
21
33
|
* Where a refused form goes back (D-0074 §3): the path and query of the `Referer` when it is
|
|
22
|
-
* this host (`host` as `WebApi.requestHost` gives it; another origin is never followed)
|
|
23
|
-
*
|
|
24
|
-
*
|
|
34
|
+
* this host (`host` as `WebApi.requestHost` gives it; another origin is never followed) and the
|
|
35
|
+
* path stays on it (`//other.host/…`, `/\other.host` and their encoded forms are refused, so the
|
|
36
|
+
* answer never reads as another host). Otherwise `fallback` for a POST, PUT, PATCH or DELETE
|
|
37
|
+
* (template-inertia passes `/`), or undefined. A GET or HEAD whose referer is missing or is itself has no way back: a redirect to
|
|
25
38
|
* itself would be refused again, forever.
|
|
26
39
|
*/
|
|
27
|
-
export function formBackTarget(request, host, fallback) {
|
|
40
|
+
export function formBackTarget(request, host, fallback, limits) {
|
|
28
41
|
const read = ['GET', 'HEAD'].includes(request.method);
|
|
29
42
|
const value = request.headers.referer;
|
|
30
43
|
const referer = Array.isArray(value) ? value[0] : value;
|
|
31
|
-
|
|
44
|
+
const longest = limits?.refererMaxLength ?? REFERER_MAX;
|
|
45
|
+
if (typeof referer === 'string' && referer.length <= longest && URL.canParse(referer)) {
|
|
32
46
|
const url = new URL(referer);
|
|
33
47
|
if ((url.protocol === 'http:' || url.protocol === 'https:') &&
|
|
34
48
|
url.host.toLowerCase() === host.toLowerCase()) {
|
|
35
49
|
const target = url.pathname + url.search;
|
|
36
|
-
if (!(read && target === request.url))
|
|
50
|
+
if (sameOrigin(target, url.origin) && !(read && target === request.url))
|
|
37
51
|
return target;
|
|
38
52
|
}
|
|
39
53
|
}
|
|
40
54
|
return read ? undefined : fallback;
|
|
41
55
|
}
|
|
56
|
+
/**
|
|
57
|
+
* A path a browser or a proxy could read as another host: `//host` (scheme-relative), `/\host`
|
|
58
|
+
* and their percent-encoded forms (`/%2F…`, `/%5C…`). The URL parser turns `\` and `/./` into
|
|
59
|
+
* `/`, so a same-host Referer such as `https://app.test//outside.test/x` has such a path.
|
|
60
|
+
*/
|
|
61
|
+
const HOST_LIKE_PATH = /^\/(?:[/\\]|%2f|%5c)/i;
|
|
62
|
+
/**
|
|
63
|
+
* True when `target` (a path and query of a Referer whose origin is `origin`) is a redirect
|
|
64
|
+
* target that stays on `origin`: it is not host-like and resolves against `origin` to `origin`
|
|
65
|
+
* with the same path and query (ISSUE-0006 A02, an open redirect through `//host` paths).
|
|
66
|
+
*/
|
|
67
|
+
function sameOrigin(target, origin) {
|
|
68
|
+
if (!target.startsWith('/') || HOST_LIKE_PATH.test(target))
|
|
69
|
+
return false;
|
|
70
|
+
const resolved = new URL(target, origin);
|
|
71
|
+
return resolved.origin === origin && resolved.pathname + resolved.search === target;
|
|
72
|
+
}
|
|
42
73
|
/**
|
|
43
74
|
* The old input of a refused form (D-0074 §3): the body's top-level strings, numbers, booleans
|
|
44
75
|
* and nulls, without password-like fields (`password`, `token`, `secret`, `api_key`, `card`,
|
|
45
|
-
* `cvc`, `otp`, `pin`…); undefined when nothing is left or it is larger than 8 KB as JSON.
|
|
76
|
+
* `cvc`, `otp`, `pin`…, and every name core's secret rule masks: `pwd`, `privateKey`, `jwt`…); undefined when nothing is left or it is larger than `limits.oldInputMaxChars` (8 KB) as JSON.
|
|
77
|
+
* Pass `web.formLimits` so the web options apply.
|
|
46
78
|
*/
|
|
47
|
-
export function formOldInput(body) {
|
|
79
|
+
export function formOldInput(body, limits) {
|
|
48
80
|
if (body === null || typeof body !== 'object' || Array.isArray(body))
|
|
49
81
|
return undefined;
|
|
50
82
|
const old = {};
|
|
51
83
|
let kept = 0;
|
|
52
84
|
for (const [key, value] of Object.entries(body)) {
|
|
53
|
-
if (key === '__proto__' || SECRET_FIELD.test(key))
|
|
85
|
+
if (key === '__proto__' || SECRET_FIELD.test(key) || redaction.isSecretField(key, value))
|
|
54
86
|
continue;
|
|
55
87
|
if (value === null ||
|
|
56
88
|
typeof value === 'boolean' ||
|
|
@@ -60,17 +92,25 @@ export function formOldInput(body) {
|
|
|
60
92
|
kept++;
|
|
61
93
|
}
|
|
62
94
|
}
|
|
63
|
-
if (!kept || JSON.stringify(old).length > OLD_MAX)
|
|
95
|
+
if (!kept || JSON.stringify(old).length > (limits?.oldInputMaxChars ?? OLD_MAX))
|
|
64
96
|
return undefined;
|
|
65
97
|
return old;
|
|
66
98
|
}
|
|
67
99
|
/**
|
|
68
|
-
* The `
|
|
69
|
-
*
|
|
100
|
+
* The `{ field: message }` errors a refused form goes back with, or undefined when the answer is
|
|
101
|
+
* not one a form goes back from:
|
|
102
|
+
*
|
|
103
|
+
* - a validation answer — a refused route schema or `validationError()` (422
|
|
104
|
+
* `VALIDATION_FAILED`) — gives its `errors`;
|
|
105
|
+
* - any other error whose `data.formErrors` is a `{ field: message }` record of strings gives
|
|
106
|
+
* those (D-0076 §2.5, 0.4.3): a plugin or a handler asks for the form redirect this way, for
|
|
107
|
+
* example dokebi-csrf's expired token `{ _form: 'The form expired. Please submit it again.' }`.
|
|
108
|
+
* `_form` is the key of an error about the whole form. Only 4xx answers go back: the callers
|
|
109
|
+
* (@dokebi/app, @dokebi/template-inertia) check the status.
|
|
70
110
|
*/
|
|
71
111
|
export function formFieldErrors(body) {
|
|
72
112
|
if (body.error !== 'VALIDATION_FAILED')
|
|
73
|
-
return
|
|
113
|
+
return requestedFormErrors(body.data);
|
|
74
114
|
const errors = body.errors;
|
|
75
115
|
if (errors === null || typeof errors !== 'object' || Array.isArray(errors))
|
|
76
116
|
return undefined;
|
|
@@ -80,3 +120,21 @@ export function formFieldErrors(body) {
|
|
|
80
120
|
result[field] = message;
|
|
81
121
|
return result;
|
|
82
122
|
}
|
|
123
|
+
/** `data.formErrors` when it is a non-empty record of strings (at most 64 entries), else undefined. */
|
|
124
|
+
function requestedFormErrors(data) {
|
|
125
|
+
if (data === null || typeof data !== 'object' || Array.isArray(data))
|
|
126
|
+
return undefined;
|
|
127
|
+
const errors = data.formErrors;
|
|
128
|
+
if (errors === null || typeof errors !== 'object' || Array.isArray(errors))
|
|
129
|
+
return undefined;
|
|
130
|
+
const entries = Object.entries(errors);
|
|
131
|
+
if (entries.length === 0 || entries.length > FORM_ERRORS_MAX)
|
|
132
|
+
return undefined;
|
|
133
|
+
const result = {};
|
|
134
|
+
for (const [field, message] of entries) {
|
|
135
|
+
if (field === '__proto__' || typeof message !== 'string')
|
|
136
|
+
return undefined;
|
|
137
|
+
result[field] = message;
|
|
138
|
+
}
|
|
139
|
+
return result;
|
|
140
|
+
}
|
package/dist/index.d.ts
CHANGED
|
@@ -1,13 +1,75 @@
|
|
|
1
1
|
import { type Awaitable, type Plugin, type PluginDependency } from '@dokebi/core';
|
|
2
2
|
import { type FastifyInstance, type FastifyPluginAsync, type FastifyPluginCallback, type FastifyPluginOptions, type FastifyRegisterOptions, type FastifyRequest, type RawReplyDefaultExpression, type RawRequestDefaultExpression, type RawServerDefault, type RouteGenericInterface, type RouteOptions } from 'fastify';
|
|
3
|
+
import type { WebFormLimits } from './forms.js';
|
|
4
|
+
import { type WebAppRouting, type WebAppSetting } from './points.js';
|
|
3
5
|
import { type WebErrorResponder } from './responses.js';
|
|
6
|
+
import { type WebRouteConfigKey } from './route-config.js';
|
|
7
|
+
import { type WebRouteHook } from './route-hooks.js';
|
|
8
|
+
import { type WebRouteEntry } from './route-table.js';
|
|
4
9
|
import { type WebSealCodecProvider, type WebSealer, type WebSealSetting } from './seal.js';
|
|
10
|
+
import { type WebCspContribution, type WebSecurityHeadersRoute } from './security-headers.js';
|
|
11
|
+
export { appNames } from './app-routes.js';
|
|
12
|
+
export { BEFORE_HIJACK, beforeHijackSteps, runBeforeHijack, type WebBeforeHijackStep, } from './before-hijack.js';
|
|
13
|
+
export { skipCompression, type WebCompressionEncoding, type WebCompressionOptions, } from './compression.js';
|
|
14
|
+
export { type DefinedError, type DefinedErrorOptions, type DefinedErrors, defineErrors, ERROR_CATALOG, type ErrorCatalogEntry, type ErrorDefinition, errorCatalog, INTENDED_REFUSAL, } from './define-errors.js';
|
|
5
15
|
export { validationError, WebError, type WebErrorCode, WebValidationError, type WebValidationInput, type WebValidationOptions, } from './errors.js';
|
|
6
16
|
export { type WebErrorAnswer, type WebErrorBody, type WebErrorContext, WebExtension, type WebFastifyOptions, type WebUnavailableAnswer, type WebUnavailableContext, type WebUnavailableReason, } from './extension.js';
|
|
7
|
-
export { formBackTarget, formFieldErrors, formOldInput, isFormSubmission, type WebFormRequest, type WebFormValue, } from './forms.js';
|
|
17
|
+
export { formBackTarget, formFieldErrors, formOldInput, isFormSubmission, type WebFormLimits, type WebFormRequest, type WebFormValue, } from './forms.js';
|
|
8
18
|
export { options, type WebOptions } from './options.js';
|
|
9
|
-
export {
|
|
10
|
-
export {
|
|
19
|
+
export { APP_NAME, APP_NAMES_MAX, appOption, appUrlMatch, pluginRouteIds, ROUTE_ID, ROUTE_OWNER, routeIdsOption, routeNamespace, type WebAppRouting, type WebAppSetting, type WebAppUrlMatch, type WebPluginRouteIds, type WebRouteOwner, } from './points.js';
|
|
20
|
+
export { errorFormat, FORM_SUBMISSION_HEADER, requestErrorFormat, SEALED_FETCH_HEADER, type WebErrorFormat, type WebErrorResponder, type WebErrorResponse, type WebFieldError, } from './responses.js';
|
|
21
|
+
export type { WebRouteConfigKey, WebRouteConfigUse } from './route-config.js';
|
|
22
|
+
export type { WebRouteAddition, WebRouteCompleted, WebRouteHook, WebRouteInfo, WebRouteOnResponse, WebRoutePreValidation, } from './route-hooks.js';
|
|
23
|
+
export type { WebDuplicateRouteId, WebRouteEntry } from './route-table.js';
|
|
24
|
+
export { SEALED_LOCATION_HEADER, SEALED_PATH_HEADER, type WebSealCodec, type WebSealCodecProvider, type WebSealer, type WebSealRequest, type WebSealSetting, } from './seal.js';
|
|
25
|
+
export { DEFAULT_DIRECTIVES, type WebCspContribution, type WebSecurityHeadersRoute, } from './security-headers.js';
|
|
26
|
+
declare module 'fastify' {
|
|
27
|
+
interface FastifyContextConfig {
|
|
28
|
+
/**
|
|
29
|
+
* The route's id (D-0077 A), for example `'API-12'`: 1 to 64 letters, digits, `.`, `_` or
|
|
30
|
+
* `-`, starting with a letter. Checked at start (INVALID_ROUTE_CONFIG); the same id on two
|
|
31
|
+
* routes of one app fails the start (DUPLICATE_ROUTE_ID). Read it per request with
|
|
32
|
+
* `request.routeOptions.config.id`; `web.routes()` lists it.
|
|
33
|
+
*/
|
|
34
|
+
id?: string;
|
|
35
|
+
/**
|
|
36
|
+
* `false` keeps this route's answers uncompressed (D-0125), for example a page that reflects
|
|
37
|
+
* request input next to a secret of its own (BREACH). Unset or true: compressed by the
|
|
38
|
+
* dokebi-web `compression` options. Checked at start (INVALID_ROUTE_CONFIG).
|
|
39
|
+
*/
|
|
40
|
+
compress?: boolean;
|
|
41
|
+
/**
|
|
42
|
+
* `false` serves this route while the server sheds load (D-0150): a metrics scrape, a status
|
|
43
|
+
* page an operator needs. Health routes always are. Checked at start (INVALID_ROUTE_CONFIG).
|
|
44
|
+
*/
|
|
45
|
+
overload?: boolean;
|
|
46
|
+
/**
|
|
47
|
+
* `false` serves this route while a required dependency is down (NOT_READY) and while the
|
|
48
|
+
* app drains, like the health routes: a metrics scrape or a status page, needed most then
|
|
49
|
+
* (M51). Before the app runs it is refused as STARTING. Checked at start (INVALID_ROUTE_CONFIG).
|
|
50
|
+
*/
|
|
51
|
+
readiness?: boolean;
|
|
52
|
+
/**
|
|
53
|
+
* Time this route's request body may take to arrive after its headers, in ms, instead of the
|
|
54
|
+
* dokebi-web `requestTimeoutMs` (an upload route that takes long bodies). Past it the answer
|
|
55
|
+
* is 408 REQUEST_TIMEOUT. Checked at start (INVALID_ROUTE_CONFIG).
|
|
56
|
+
*/
|
|
57
|
+
requestTimeoutMs?: number;
|
|
58
|
+
/**
|
|
59
|
+
* Security headers of this route (D-0149): `false` sends none (an answer embedded by other
|
|
60
|
+
* sites on purpose), an object changes some (`{ frameOptions: false, contentSecurityPolicy:
|
|
61
|
+
* { directives: { 'frame-ancestors': ['https://partner.example'] } } }`). Checked at start
|
|
62
|
+
* (INVALID_ROUTE_CONFIG).
|
|
63
|
+
*/
|
|
64
|
+
securityHeaders?: false | WebSecurityHeadersRoute;
|
|
65
|
+
/**
|
|
66
|
+
* Route config stays open to other keys (a plugin's own, Fastify plugins'): declaring `id`
|
|
67
|
+
* must not turn every other key into a type error. Misspelt keys of declared ones (`csfr`,
|
|
68
|
+
* `ID`) fail the start instead (INVALID_ROUTE_CONFIG).
|
|
69
|
+
*/
|
|
70
|
+
[key: string]: unknown;
|
|
71
|
+
}
|
|
72
|
+
}
|
|
11
73
|
export type WebRoute<T extends RouteGenericInterface = RouteGenericInterface> = RouteOptions<RawServerDefault, RawRequestDefaultExpression<RawServerDefault>, RawReplyDefaultExpression<RawServerDefault>, T> & {
|
|
12
74
|
/**
|
|
13
75
|
* Sealing of this route (D-0062): `false` keeps it plain on a seal host (webhooks,
|
|
@@ -15,6 +77,14 @@ export type WebRoute<T extends RouteGenericInterface = RouteGenericInterface> =
|
|
|
15
77
|
* decides (dokebi-app `domains.<host>.seal`). Stored as `config.dokebiSeal`.
|
|
16
78
|
*/
|
|
17
79
|
readonly seal?: WebSealSetting;
|
|
80
|
+
/**
|
|
81
|
+
* The app or apps of @dokebi/app whose hosts answer this route (D-0132): `'mcp'` or
|
|
82
|
+
* `['studio', 'admin']`. Other hosts get the 404 of an unknown route. Unset: every host (as
|
|
83
|
+
* before). Becomes the `dokebiApp` constraint of app routes at boot; without @dokebi/app the
|
|
84
|
+
* start fails (ROUTE_APP_UNAVAILABLE), an unknown name too (ROUTE_APP_UNKNOWN). Also read on
|
|
85
|
+
* routes of `register()` scopes.
|
|
86
|
+
*/
|
|
87
|
+
readonly app?: WebAppSetting;
|
|
18
88
|
};
|
|
19
89
|
export interface WebHealth {
|
|
20
90
|
readonly ready: boolean;
|
|
@@ -33,7 +103,8 @@ export interface WebApi {
|
|
|
33
103
|
constraint(strategy: WebConstraintStrategy): void;
|
|
34
104
|
/**
|
|
35
105
|
* The host a client asked for: `X-Forwarded-Host` when the request comes from an address in
|
|
36
|
-
* `trustProxy`, otherwise `Host
|
|
106
|
+
* `trustProxy`, otherwise `Host` (over HTTP/2 `:authority`). Lower case, port kept. Takes a raw or
|
|
107
|
+
* Fastify request.
|
|
37
108
|
*/
|
|
38
109
|
requestHost(request: WebRequestLike): string;
|
|
39
110
|
/**
|
|
@@ -51,8 +122,28 @@ export interface WebApi {
|
|
|
51
122
|
* (the Inertia first page, SSE event data). JSON responses are sealed by dokebi-web itself.
|
|
52
123
|
*/
|
|
53
124
|
sealOf(request: FastifyRequest): WebSealer | undefined;
|
|
125
|
+
/**
|
|
126
|
+
* D-0181: tells which app a request belongs to (dokebi-app registers one: the app of its host).
|
|
127
|
+
* Setup only. Plugins that answer per app (dokebi-i18n's app layers) ask `appOf`.
|
|
128
|
+
*/
|
|
129
|
+
requestApps(resolver: (request: FastifyRequest) => string | undefined): void;
|
|
130
|
+
/** The app of a request, as the first `requestApps` resolver says; undefined without one. */
|
|
131
|
+
appOf(request: FastifyRequest): string | undefined;
|
|
132
|
+
/** True once a `requestApps` resolver is registered (final once every setup has run). */
|
|
133
|
+
readonly resolvesApps: boolean;
|
|
54
134
|
/** True once a seal codec is registered. */
|
|
55
135
|
readonly sealing: boolean;
|
|
136
|
+
/**
|
|
137
|
+
* True when something asks for sealing: a `sealRequests` predicate (dokebi-app registers one
|
|
138
|
+
* only for sealed domains) or a route whose `seal` is true or a function. Final once every
|
|
139
|
+
* setup has run (the seal plugin reads it in its start).
|
|
140
|
+
*/
|
|
141
|
+
readonly sealWanted: boolean;
|
|
142
|
+
/**
|
|
143
|
+
* The form limits of these options (`formOldInputMaxChars`, `formRefererMaxLength`, D-0114):
|
|
144
|
+
* pass them to `formOldInput` and `formBackTarget`.
|
|
145
|
+
*/
|
|
146
|
+
readonly formLimits: WebFormLimits;
|
|
56
147
|
/**
|
|
57
148
|
* Adds an error responder (D-0074): before dokebi-web writes an error answer (a thrown error,
|
|
58
149
|
* a refused schema, an unknown route), responders are asked, the last added first, and one
|
|
@@ -61,6 +152,45 @@ export interface WebApi {
|
|
|
61
152
|
* before ready and while draining.
|
|
62
153
|
*/
|
|
63
154
|
errorResponder(responder: WebErrorResponder): void;
|
|
155
|
+
/**
|
|
156
|
+
* Declares a route `config` key this plugin reads (D-0076 §5: `auth`, `csrf`). Setup only. At
|
|
157
|
+
* start every route's value goes through `check`, and a key two edits away from a declared one
|
|
158
|
+
* (`csfr`) is reported as a likely typo: either fails the start with INVALID_ROUTE_CONFIG. The
|
|
159
|
+
* plugin itself reads the value per request (`request.routeOptions.config[key]`).
|
|
160
|
+
*/
|
|
161
|
+
routeConfig(definition: WebRouteConfigKey): void;
|
|
162
|
+
/**
|
|
163
|
+
* Asks `route(info)` once for every route (D-0076 §3.8), including the routes added before this
|
|
164
|
+
* call, what to add to that route only: preValidation/onResponse hooks and/or config values under symbol
|
|
165
|
+
* keys. Routes it returns undefined for are left untouched (no cost on their requests). Health
|
|
166
|
+
* routes are never offered. Setup only.
|
|
167
|
+
*/
|
|
168
|
+
routeHook(definition: WebRouteHook): void;
|
|
169
|
+
/**
|
|
170
|
+
* Adds sources to the Content-Security-Policy of HTML documents (D-0149): @dokebi/seal adds
|
|
171
|
+
* `'wasm-unsafe-eval'` to script-src, template-inertia the Vite dev socket to connect-src.
|
|
172
|
+
* Appended to the directive (one not set starts from default-src). Setup only; a malformed
|
|
173
|
+
* contribution is INVALID_ARGUMENT.
|
|
174
|
+
*/
|
|
175
|
+
contentSecurityPolicy(contribution: WebCspContribution): void;
|
|
176
|
+
/**
|
|
177
|
+
* Every route added so far (D-0077 A): method, path, `config.id`, constraints and config key
|
|
178
|
+
* names, frozen (the same array until another route is added). The HEAD route Fastify adds to
|
|
179
|
+
* each GET is left out. Complete once the server is ready (after start, or `ready()`), when the
|
|
180
|
+
* routes of every registered Fastify plugin scope exist too. Cheap: no copy per call.
|
|
181
|
+
*/
|
|
182
|
+
routes(): readonly WebRouteEntry[];
|
|
183
|
+
/**
|
|
184
|
+
* Fills the app routing (D-0132): @dokebi/app calls it in its setup with its constraint and
|
|
185
|
+
* host map, so routes with `app` get the host constraint of app routes. Setup only, once.
|
|
186
|
+
*/
|
|
187
|
+
appRouting(routing: WebAppRouting): void;
|
|
188
|
+
/**
|
|
189
|
+
* The app routing @dokebi/app registered, or undefined (no @dokebi/app, or its setup has not
|
|
190
|
+
* run yet). Final at boot: plugins read it inside their `register()` scopes, for example to
|
|
191
|
+
* check that a URL they publish is a domain of the apps that serve it (`appUrlMatch`).
|
|
192
|
+
*/
|
|
193
|
+
readonly apps: WebAppRouting | undefined;
|
|
64
194
|
}
|
|
65
195
|
export interface WebRequestLike {
|
|
66
196
|
readonly headers: Readonly<Record<string, string | string[] | undefined>>;
|