@dokebi/web 0.1.2 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,25 @@
1
+ interface InstallContext {
2
+ readonly options?: Readonly<Record<string, unknown>>;
3
+ /** On upgrade: the entry the project already has. */
4
+ readonly installation?: {
5
+ readonly entry?: string;
6
+ };
7
+ }
8
+ interface Template {
9
+ readonly source: string;
10
+ readonly target: string;
11
+ }
12
+ export declare function planInstall(_context: InstallContext): {
13
+ requires: string[];
14
+ entry: Template;
15
+ };
16
+ /**
17
+ * A project that already has an entry keeps it (the CLI refuses to move one): an older
18
+ * `src/infra/web/requires.ts` may add `export default class … extends WebExtension` itself.
19
+ * A project without one gets the new entry.
20
+ */
21
+ export declare function planUpgrade(context: InstallContext): {
22
+ requires: string[];
23
+ entry: Template;
24
+ };
25
+ export {};
@@ -0,0 +1,23 @@
1
+ // Install lifecycle module (`dokebi.installModule`). It runs isolated in the CLI, so it imports
2
+ // nothing and only reads the plain context it is given.
3
+ /** The user-owned entry (D-0064 §9): `requires` and an empty WebExtension subclass. */
4
+ const ENTRY = Object.freeze({
5
+ source: 'templates/extension.ts',
6
+ target: 'src/infra/web/extension.ts',
7
+ });
8
+ /** The entry of projects made before 0.4.0 (requires only); an upgrade keeps it where it is. */
9
+ const LEGACY_ENTRY_SOURCE = 'templates/web.ts';
10
+ export function planInstall(_context) {
11
+ return { requires: [], entry: ENTRY };
12
+ }
13
+ /**
14
+ * A project that already has an entry keeps it (the CLI refuses to move one): an older
15
+ * `src/infra/web/requires.ts` may add `export default class … extends WebExtension` itself.
16
+ * A project without one gets the new entry.
17
+ */
18
+ export function planUpgrade(context) {
19
+ const current = context.installation?.entry;
20
+ if (current === undefined || current === ENTRY.target)
21
+ return { requires: [], entry: ENTRY };
22
+ return { requires: [], entry: { source: LEGACY_ENTRY_SOURCE, target: current } };
23
+ }
@@ -0,0 +1,19 @@
1
+ import { type OptionsOf } from '@dokebi/core';
2
+ export declare const options: import("@dokebi/core").OptionsDeclaration<{
3
+ readonly developmentErrors: boolean;
4
+ readonly formBody: boolean;
5
+ readonly formMaxFields: number;
6
+ readonly healthRoutes: false | {
7
+ readonly live: string;
8
+ readonly ready: string;
9
+ };
10
+ readonly host: string;
11
+ readonly maxBodyBytes: number;
12
+ readonly port: number;
13
+ readonly requestTimeoutMs: number;
14
+ readonly sealDriftMs: number;
15
+ readonly sealExclude: readonly string[];
16
+ readonly trustProxy: readonly string[];
17
+ }>;
18
+ /** The parsed options of dokebi-web (`options.dokebi-web`). */
19
+ export type WebOptions = OptionsOf<typeof options>;
@@ -0,0 +1,92 @@
1
+ import { isIP } from 'node:net';
2
+ import { defineOptions, option as o } from '@dokebi/core';
3
+ /*
4
+ * Options of dokebi-web (D-0063 §3): one declaration is the parser and, at build time,
5
+ * options.schema.json. The rules are the hand parser's before wave B; what the old schema did
6
+ * not say (an address must be an IP, live and ready must differ) is declared here too.
7
+ */
8
+ /** A route path: `/` and up to 2047 characters without query, fragment or white space. */
9
+ const ROUTE_PATH = '^/[^?#\\s]{0,2047}$';
10
+ export const options = defineOptions({
11
+ host: o.string({
12
+ minLength: 1,
13
+ maxLength: 253,
14
+ default: '127.0.0.1',
15
+ description: 'Address to listen on; 0.0.0.0 accepts other machines (put a proxy in front).',
16
+ }),
17
+ port: o.integer({
18
+ minimum: 0,
19
+ maximum: 65535,
20
+ default: 0,
21
+ description: 'Port to listen on; 0 picks a free one.',
22
+ }),
23
+ maxBodyBytes: o.integer({
24
+ minimum: 1,
25
+ maximum: 67108864,
26
+ default: 1048576,
27
+ description: 'Largest request body in bytes.',
28
+ }),
29
+ bodyLimit: o.alias('maxBodyBytes'),
30
+ requestTimeoutMs: o.integer({
31
+ minimum: 1,
32
+ maximum: 2147483647,
33
+ default: 30000,
34
+ description: 'Time to receive a whole request in ms (not a limit on the work it starts).',
35
+ }),
36
+ requestTimeout: o.alias('requestTimeoutMs'),
37
+ healthRoutes: o.union([
38
+ o.literal(false),
39
+ o.object({
40
+ live: o.string({ pattern: ROUTE_PATH, default: '/health/live' }),
41
+ ready: o.string({ pattern: ROUTE_PATH, default: '/health/ready' }),
42
+ }, {
43
+ checks: [
44
+ {
45
+ path: 'ready',
46
+ message: 'must differ from live',
47
+ test: (routes) => routes.live !== routes.ready,
48
+ },
49
+ ],
50
+ }),
51
+ ], {
52
+ default: { live: '/health/live', ready: '/health/ready' },
53
+ description: 'Liveness and readiness routes (answered before ready and while draining); false registers none.',
54
+ }),
55
+ trustProxy: o.array(o.string({
56
+ minLength: 2,
57
+ maxLength: 45,
58
+ description: 'IPv4 or IPv6 address',
59
+ refine: [{ test: (value) => isIP(value) !== 0, message: 'must be an IP address' }],
60
+ }), {
61
+ maxItems: 64,
62
+ uniqueItems: true,
63
+ default: [],
64
+ description: 'Proxy addresses whose X-Forwarded-Host/For/Proto are trusted, e.g. [127.0.0.1, ::1] for a local tunnel',
65
+ }),
66
+ sealDriftMs: o.integer({
67
+ minimum: 1000,
68
+ maximum: 600000,
69
+ default: 60000,
70
+ description: 'Seal hosts (D-0062): accepted clock difference of a sealed request body in ms; replay nonces are kept twice as long',
71
+ }),
72
+ sealExclude: o.array(o.string({ pattern: ROUTE_PATH }), {
73
+ maxItems: 64,
74
+ uniqueItems: true,
75
+ default: [],
76
+ description: 'Seal hosts (D-0062): path prefixes that stay plain (webhooks, server-to-server), matched at a / boundary',
77
+ }),
78
+ formBody: o.boolean({
79
+ default: false,
80
+ description: 'Parse HTML form bodies (application/x-www-form-urlencoded) into request.body (D-0068). Off: such a request gets 415 FORM_BODY_DISABLED. Seal hosts still refuse them (415 SEAL_REQUIRED)',
81
+ }),
82
+ formMaxFields: o.integer({
83
+ minimum: 1,
84
+ maximum: 10000,
85
+ default: 1000,
86
+ description: 'Most fields one form body may carry; more is 413 FORM_BODY_TOO_MANY_FIELDS (maxBodyBytes also applies)',
87
+ }),
88
+ developmentErrors: o.boolean({
89
+ default: true,
90
+ description: 'Outside production (NODE_ENV is not production) error bodies also carry fix and details (D-0063). false: never, as in production. hint and data are always sent.',
91
+ }),
92
+ });
@@ -0,0 +1,53 @@
1
+ import type { FastifyRequest } from 'fastify';
2
+ /**
3
+ * A view engine (`dokebi-web:view-engine`): template-ejs contributes `{ name: 'ejs' }`,
4
+ * template-inertia `{ name: 'inertia' }`. `scope` gives the renderer of one app or module; the
5
+ * input and the renderer are the engine's own types (method syntax keeps them assignable here).
6
+ */
7
+ export interface WebViewEngine<TInput = unknown, TRenderer = unknown> {
8
+ /** The engine name an app chooses (`ejs`, `inertia`). */
9
+ readonly name: string;
10
+ /** The renderer for one app or module. Call during setup. */
11
+ scope(input: TInput): Promise<TRenderer>;
12
+ }
13
+ /**
14
+ * Where a realtime route of an app or module is mounted: what the transport adds to the route.
15
+ * dokebi-app makes one per route (prefix, domain constraint and namespace rule, D-0061).
16
+ */
17
+ export interface WebRealtimeScope {
18
+ /** The full path of the route (the mount prefix already joined). */
19
+ readonly path: string;
20
+ /** Route constraints added over the route's own (for example the app's host constraint). */
21
+ readonly constraints: Readonly<Record<string, unknown>>;
22
+ /**
23
+ * The identity the transport keeps for an authenticated client: the namespace-prefixed tenant,
24
+ * or undefined to refuse the client (401).
25
+ */
26
+ identity<T extends {
27
+ readonly tenant: string;
28
+ readonly namespace?: string;
29
+ }>(identity: T): T | undefined;
30
+ /**
31
+ * Requests whose connections are sealed besides the route's own `seal` (dokebi-app: a host
32
+ * with `seal: true`, D-0059 §4); absent when no host of the app seals. A transport that writes
33
+ * through dokebi-web (SSE) is sealed by `web.sealOf` and may ignore it.
34
+ */
35
+ readonly seal?: (request: FastifyRequest) => boolean;
36
+ }
37
+ /**
38
+ * A realtime transport (`dokebi-web:realtime`): websocket contributes `{ kind: 'websocket' }`,
39
+ * sse `{ kind: 'sse' }`. `mount` registers one route during setup; `handle` gives the operations
40
+ * on one namespace (the tenants `<namespace>:<tenant>`).
41
+ */
42
+ export interface WebRealtimeTransport<TRoute = unknown, THandle = unknown> {
43
+ /** The transport kind (`websocket`, `sse`). */
44
+ readonly kind: string;
45
+ /** Registers a route of an app or module under `scope`. Call during setup. */
46
+ mount(route: TRoute, scope: WebRealtimeScope): void;
47
+ /** The operations on one namespace. */
48
+ handle(namespace: string): THandle;
49
+ }
50
+ /** `dokebi-web:view-engine`: template engines an app can render with. */
51
+ export declare const viewEngines: import("@dokebi/core").ContributionPoint<WebViewEngine<unknown, unknown>>;
52
+ /** `dokebi-web:realtime`: realtime transports an app can mount routes on. */
53
+ export declare const realtime: import("@dokebi/core").ContributionPoint<WebRealtimeTransport<unknown, unknown>>;
package/dist/points.js ADDED
@@ -0,0 +1,5 @@
1
+ import { definePoint } from '@dokebi/core';
2
+ /** `dokebi-web:view-engine`: template engines an app can render with. */
3
+ export const viewEngines = definePoint('dokebi-web:view-engine');
4
+ /** `dokebi-web:realtime`: realtime transports an app can mount routes on. */
5
+ export const realtime = definePoint('dokebi-web:realtime');
@@ -0,0 +1,80 @@
1
+ import { DokebiError } from '@dokebi/core';
2
+ import type { FastifyReply, FastifyRequest } from 'fastify';
3
+ import type { WebErrorAnswer, WebErrorBody } from './extension.js';
4
+ /** One refused field of a validation error (D-0074 §2). */
5
+ export interface WebFieldError {
6
+ /** `name`, `address.city`, `items.0.name`; a query string field is `query.page`. */
7
+ readonly field: string;
8
+ readonly message: string;
9
+ }
10
+ /** Whether an error answer is JSON or an HTML page (D-0074 §1). */
11
+ export type WebErrorFormat = 'json' | 'html';
12
+ /**
13
+ * One error answer about to be written, handed to the error responders (`WebApi.errorResponder`).
14
+ * `status` and `body` are final: the `errorBody` hook ran and a production body is already cut.
15
+ */
16
+ export interface WebErrorResponse {
17
+ readonly request: FastifyRequest;
18
+ readonly reply: FastifyReply;
19
+ /** What was thrown (a `WebError` NOT_FOUND for an unknown route). */
20
+ readonly error: unknown;
21
+ readonly status: number;
22
+ readonly body: WebErrorBody;
23
+ /** What dokebi-web would send: JSON for scripts (Inertia, fetch, XHR, APIs), HTML for pages. */
24
+ readonly format: WebErrorFormat;
25
+ /** True in production (or with `developmentErrors: false`). */
26
+ readonly production: boolean;
27
+ /** The request is sealed (a seal host, D-0062): only JSON leaves, sealed by dokebi-web. */
28
+ readonly sealed: boolean;
29
+ }
30
+ /**
31
+ * Writes an error answer itself (an app's error view, an Inertia error page, a validation
32
+ * redirect) and resolves to true, or resolves to false to leave it to the next responder and
33
+ * finally to dokebi-web. A responder that throws is logged and dokebi-web answers instead.
34
+ */
35
+ export type WebErrorResponder = (response: WebErrorResponse) => boolean | Promise<boolean>;
36
+ /** The code of a refused schema check and of `validationError()`. */
37
+ export declare const VALIDATION_FAILED = "VALIDATION_FAILED";
38
+ /** The hint of every validation answer. */
39
+ export declare const VALIDATION_HINT = "Some fields are not valid. Correct them and try again.";
40
+ /**
41
+ * The fields of a Fastify schema validation error (Ajv errors in `validation`, the part of the
42
+ * request in `validationContext`), or undefined when it is not one.
43
+ */
44
+ export declare function schemaFields(error: unknown): WebFieldError[] | undefined;
45
+ /** The fields of a `validationError()` (of any installed copy: matched by code and shape). */
46
+ export declare function ownFields(error: unknown): readonly WebFieldError[] | undefined;
47
+ /** `{ field: first message }`: the shape of Inertia's `useForm().errors` (and Laravel's). */
48
+ export declare function errorsByField(fields: readonly WebFieldError[]): Record<string, string>;
49
+ /** A Dokebi error by shape: the class of this core, or the same fields naming a plugin. */
50
+ export declare function dokebiError(error: unknown): DokebiError | undefined;
51
+ /** A Fastify 4xx `statusCode` of a thrown value, if any. */
52
+ export declare function clientStatus(error: unknown): number | undefined;
53
+ /** `details` as it may be sent: JSON-serialisable and at most 16 KB, otherwise undefined. */
54
+ export declare function sendableDetails(details: unknown): unknown;
55
+ /** The default answer for a caught value; `production` hides `fix`, `details` and 5xx messages. */
56
+ export declare function errorAnswer(error: unknown, production: boolean, details: (value: unknown) => unknown): WebErrorAnswer;
57
+ /** Drops `fix`, `details` and `stack` from a production body (a hook may have added them). */
58
+ export declare function productionBody(body: WebErrorBody): WebErrorBody;
59
+ /** A plain object whose own data is a usable answer (`errorBody` result). */
60
+ export declare function validAnswer(value: unknown): value is WebErrorAnswer;
61
+ /**
62
+ * True when `Accept` asks for HTML before JSON: it lists text/html, and application/json not
63
+ * earlier. `fetch()` sends `*\/*`: JSON. One input of `errorFormat`, not the whole rule.
64
+ */
65
+ export declare function prefersHtml(accept: string | undefined): boolean;
66
+ /**
67
+ * JSON or HTML for an error answer (D-0074 §1). JSON for every script: an Inertia request
68
+ * (`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.
72
+ */
73
+ export declare function errorFormat(headers: Readonly<Record<string, string | string[] | undefined>>, sealed?: boolean): WebErrorFormat;
74
+ /** The `fields` of a body that are well formed (a hook may have returned anything). */
75
+ export declare function bodyFields(body: WebErrorBody): WebFieldError[];
76
+ /**
77
+ * A small HTML page of an error body: code, message, hint, the refused fields and (development
78
+ * only) fix.
79
+ */
80
+ export declare function errorPage(status: number, body: WebErrorBody): string;
@@ -0,0 +1,246 @@
1
+ import { DokebiError, isDokebiError } from '@dokebi/core';
2
+ // Not `import … from 'node:http'`: the ESM facade of node:http reads every export, and its lazy
3
+ // WebSocket/fetch getters load undici — about 9 ms of every start (D-0070 §5). Fastify already
4
+ // loaded node:http through require, so this costs nothing.
5
+ const { STATUS_CODES } = process.getBuiltinModule('node:http');
6
+ /** The code of a refused schema check and of `validationError()`. */
7
+ export const VALIDATION_FAILED = 'VALIDATION_FAILED';
8
+ /** The hint of every validation answer. */
9
+ export const VALIDATION_HINT = 'Some fields are not valid. Correct them and try again.';
10
+ /**
11
+ * The parts of a request whose schema refusal is a validation error (422), and the prefix of
12
+ * their fields: the data a user typed (a form body, a search query). A refused `params` or
13
+ * `headers` schema stays 400 INVALID_REQUEST: the address or the client is wrong, not a field.
14
+ */
15
+ const CONTEXT_PREFIX = { body: '', querystring: 'query.' };
16
+ /** The field of a part that is wrong as a whole (the body is not an object, …). */
17
+ const ROOT_FIELD = { body: '_body', querystring: 'query' };
18
+ /** `/items/0/name` (a JSON pointer) → `items.0.name`. */
19
+ function pointerPath(pointer) {
20
+ if (!pointer)
21
+ return '';
22
+ return pointer
23
+ .split('/')
24
+ .slice(1)
25
+ .map((part) => part.replace(/~1/g, '/').replace(/~0/g, '~'))
26
+ .join('.');
27
+ }
28
+ /**
29
+ * The fields of a Fastify schema validation error (Ajv errors in `validation`, the part of the
30
+ * request in `validationContext`), or undefined when it is not one.
31
+ */
32
+ export function schemaFields(error) {
33
+ if (error === null || typeof error !== 'object')
34
+ return undefined;
35
+ const { validation, validationContext } = error;
36
+ if (!Array.isArray(validation) || !validation.length)
37
+ return undefined;
38
+ const context = typeof validationContext === 'string' ? validationContext : 'body';
39
+ const prefix = Object.hasOwn(CONTEXT_PREFIX, context) ? CONTEXT_PREFIX[context] : undefined;
40
+ if (prefix === undefined)
41
+ return undefined;
42
+ const fields = [];
43
+ for (const item of validation) {
44
+ if (item === null || typeof item !== 'object')
45
+ continue;
46
+ const { instancePath, keyword, params, message } = item;
47
+ let path = pointerPath(typeof instancePath === 'string' ? instancePath : '');
48
+ let text = typeof message === 'string' ? message : 'is not valid';
49
+ const missing = params?.missingProperty;
50
+ const extra = params?.additionalProperty;
51
+ if (keyword === 'required' && typeof missing === 'string') {
52
+ path = path ? `${path}.${missing}` : missing;
53
+ text = 'is required';
54
+ }
55
+ else if (keyword === 'additionalProperties' && typeof extra === 'string') {
56
+ path = path ? `${path}.${extra}` : extra;
57
+ text = 'is not allowed';
58
+ }
59
+ fields.push({ field: path ? prefix + path : ROOT_FIELD[context], message: text });
60
+ }
61
+ return fields.length ? fields : undefined;
62
+ }
63
+ /** The fields of a `validationError()` (of any installed copy: matched by code and shape). */
64
+ export function ownFields(error) {
65
+ if (error === null || typeof error !== 'object')
66
+ return undefined;
67
+ const { code, fields } = error;
68
+ return code === VALIDATION_FAILED && Array.isArray(fields)
69
+ ? fields
70
+ : undefined;
71
+ }
72
+ /** `{ field: first message }`: the shape of Inertia's `useForm().errors` (and Laravel's). */
73
+ export function errorsByField(fields) {
74
+ const errors = {};
75
+ for (const { field, message } of fields)
76
+ if (!Object.hasOwn(errors, field))
77
+ errors[field] = message;
78
+ return errors;
79
+ }
80
+ /** Fields that never leave a production body, whatever an extension hook returned. */
81
+ const DEVELOPER_FIELDS = ['fix', 'details', 'stack'];
82
+ /** Largest `details` sent in a development body (as JSON text). */
83
+ const DETAILS_MAX = 16_384;
84
+ /** A Dokebi error by shape: the class of this core, or the same fields naming a plugin. */
85
+ export function dokebiError(error) {
86
+ if (error instanceof DokebiError)
87
+ return error;
88
+ return isDokebiError(error) && typeof error.plugin === 'string'
89
+ ? error
90
+ : undefined;
91
+ }
92
+ /** A Fastify 4xx `statusCode` of a thrown value, if any. */
93
+ export function clientStatus(error) {
94
+ const code = error !== null && typeof error === 'object' && 'statusCode' in error
95
+ ? error.statusCode
96
+ : undefined;
97
+ return typeof code === 'number' && Number.isInteger(code) && code >= 400 && code < 500
98
+ ? code
99
+ : undefined;
100
+ }
101
+ /** `details` as it may be sent: JSON-serialisable and at most 16 KB, otherwise undefined. */
102
+ export function sendableDetails(details) {
103
+ if (details === undefined)
104
+ return undefined;
105
+ const text = JSON.stringify(details); // throws on a cycle or a BigInt: the caller logs it
106
+ return text === undefined || text.length > DETAILS_MAX ? undefined : JSON.parse(text);
107
+ }
108
+ /** The default answer for a caught value; `production` hides `fix`, `details` and 5xx messages. */
109
+ export function errorAnswer(error, production, details) {
110
+ const known = dokebiError(error);
111
+ if (known) {
112
+ const status = known.status ?? clientStatus(error) ?? 500;
113
+ const body = {
114
+ error: known.code,
115
+ message: production && status >= 500 ? (STATUS_CODES[status] ?? 'Server Error') : known.message,
116
+ };
117
+ if (known.hint !== undefined)
118
+ body.hint = known.hint;
119
+ if (known.data !== undefined)
120
+ body.data = known.data;
121
+ const fields = ownFields(known);
122
+ if (fields) {
123
+ body.fields = fields.map(({ field, message }) => ({ field, message }));
124
+ body.errors = errorsByField(fields);
125
+ }
126
+ if (!production) {
127
+ if (known.fix !== undefined)
128
+ body.fix = known.fix;
129
+ const sent = details(known.details);
130
+ if (sent !== undefined)
131
+ body.details = sent;
132
+ }
133
+ return { status, body: body };
134
+ }
135
+ const status = clientStatus(error);
136
+ if (status === undefined)
137
+ return { status: 500, body: { error: 'INTERNAL_SERVER_ERROR' } };
138
+ // A route's JSON schema refused a well-formed request: 422 with the fields (D-0074 §2). The
139
+ // field messages are the point of the answer, so production keeps them.
140
+ const fields = schemaFields(error);
141
+ if (fields)
142
+ return {
143
+ status: 422,
144
+ body: {
145
+ error: VALIDATION_FAILED,
146
+ message: `Invalid fields: ${[...new Set(fields.map((item) => item.field))].join(', ')}`,
147
+ hint: VALIDATION_HINT,
148
+ fields,
149
+ errors: errorsByField(fields),
150
+ },
151
+ };
152
+ // Fastify's own message (bad JSON, media type, size) helps while developing; hidden in production.
153
+ const message = !production && error instanceof Error ? error.message : undefined;
154
+ return {
155
+ status,
156
+ body: message ? { error: 'INVALID_REQUEST', message } : { error: 'INVALID_REQUEST' },
157
+ };
158
+ }
159
+ /** Drops `fix`, `details` and `stack` from a production body (a hook may have added them). */
160
+ export function productionBody(body) {
161
+ if (!DEVELOPER_FIELDS.some((field) => Object.hasOwn(body, field)))
162
+ return body;
163
+ const copy = { ...body };
164
+ for (const field of DEVELOPER_FIELDS)
165
+ delete copy[field];
166
+ return copy;
167
+ }
168
+ /** A plain object whose own data is a usable answer (`errorBody` result). */
169
+ export function validAnswer(value) {
170
+ if (value === null || typeof value !== 'object' || 'then' in value)
171
+ return false;
172
+ const { status, body } = value;
173
+ return (typeof status === 'number' &&
174
+ Number.isInteger(status) &&
175
+ status >= 400 &&
176
+ status <= 599 &&
177
+ body !== null &&
178
+ typeof body === 'object' &&
179
+ !Array.isArray(body) &&
180
+ typeof body.error === 'string');
181
+ }
182
+ /**
183
+ * True when `Accept` asks for HTML before JSON: it lists text/html, and application/json not
184
+ * earlier. `fetch()` sends `*\/*`: JSON. One input of `errorFormat`, not the whole rule.
185
+ */
186
+ export function prefersHtml(accept) {
187
+ if (accept === undefined)
188
+ return false;
189
+ const html = accept.indexOf('text/html');
190
+ if (html === -1)
191
+ return false;
192
+ const json = accept.indexOf('application/json');
193
+ return json === -1 || html < json;
194
+ }
195
+ /** A JSON media type: `application/json`, `application/problem+json`, … */
196
+ const JSON_TYPE = /^application\/(?:[a-z0-9.+-]+\+)?json$/;
197
+ function headerValue(value) {
198
+ return Array.isArray(value) ? value[0] : value;
199
+ }
200
+ /**
201
+ * JSON or HTML for an error answer (D-0074 §1). JSON for every script: an Inertia request
202
+ * (`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.
206
+ */
207
+ export function errorFormat(headers, sealed = false) {
208
+ if (sealed || headers['x-inertia'] !== undefined)
209
+ return 'json';
210
+ const requestedWith = headerValue(headers['x-requested-with']);
211
+ if (requestedWith !== undefined && requestedWith.toLowerCase() === 'xmlhttprequest')
212
+ return 'json';
213
+ const authorization = headerValue(headers.authorization);
214
+ if (authorization !== undefined && /^bearer\s/i.test(authorization))
215
+ return 'json';
216
+ const type = headerValue(headers['content-type']);
217
+ if (type !== undefined && JSON_TYPE.test(type.split(';', 1)[0]?.trim().toLowerCase() ?? ''))
218
+ return 'json';
219
+ return prefersHtml(headerValue(headers.accept)) ? 'html' : 'json';
220
+ }
221
+ function escapeHtml(text) {
222
+ return text.replace(/[&<>"']/g, (character) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' })[character] ??
223
+ character);
224
+ }
225
+ /** The `fields` of a body that are well formed (a hook may have returned anything). */
226
+ export function bodyFields(body) {
227
+ return Array.isArray(body.fields)
228
+ ? body.fields.filter((item) => item !== null &&
229
+ typeof item === 'object' &&
230
+ typeof item.field === 'string' &&
231
+ typeof item.message === 'string')
232
+ : [];
233
+ }
234
+ /**
235
+ * A small HTML page of an error body: code, message, hint, the refused fields and (development
236
+ * only) fix.
237
+ */
238
+ export function errorPage(status, body) {
239
+ const title = `${status} ${STATUS_CODES[status] ?? 'Error'}`;
240
+ const text = (value) => (typeof value === 'string' ? escapeHtml(value) : '');
241
+ const fields = bodyFields(body);
242
+ const list = fields.length
243
+ ? `<ul>${fields.map((item) => `<li><code>${text(item.field)}</code> ${text(item.message)}</li>`).join('')}</ul>`
244
+ : '';
245
+ return `<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>${escapeHtml(title)}</title></head><body><h1>${escapeHtml(title)}</h1><p><code>${text(body.error)}</code>${body.message ? ` ${text(body.message)}` : ''}</p>${body.hint ? `<p>${text(body.hint)}</p>` : ''}${list}${body.fix ? `<pre>${text(body.fix)}</pre>` : ''}</body></html>`;
246
+ }
package/dist/seal.d.ts ADDED
@@ -0,0 +1,83 @@
1
+ import type { Logger } from '@dokebi/core';
2
+ import type { FastifyReply, FastifyRequest } from 'fastify';
3
+ import { WebError } from './errors.js';
4
+ /** A route's own seal setting: true seals it on every host, false keeps it plain on seal hosts. */
5
+ export type WebSealSetting = boolean | ((request: FastifyRequest) => boolean);
6
+ /** What a codec provider is told about one sealed request. */
7
+ export interface WebSealRequest {
8
+ /** The request host without port, lower case (`requestHost`, so trustProxy applies). */
9
+ readonly host: string;
10
+ /** The request path as the browser sent it, without the query. */
11
+ readonly path: string;
12
+ readonly userAgent: string;
13
+ /** Accepted clock difference of a sealed body (`sealDriftMs`). */
14
+ readonly driftMs: number;
15
+ }
16
+ /** Seals and opens the bodies of one request. Its errors never reach the client. */
17
+ export interface WebSealCodec {
18
+ /** Opens a sealed request body; rejects (with a `reason` such as `drift` or `replay`) to refuse it. */
19
+ decode(body: string): Promise<string>;
20
+ /** Seals one response text (`E:<ts>:<base64>`). */
21
+ encode(text: string): string;
22
+ }
23
+ /** The shape the dokebi-seal plugin provides (structural; never imported). */
24
+ export interface WebSealCodecProvider {
25
+ /** Media type of sealed bodies, both ways (for example `application/vnd.dokebi-seal`). */
26
+ readonly contentType: string;
27
+ /** The codec of one request. Replay nonces are the provider's (the hub's `nonces()`). */
28
+ forRequest(request: WebSealRequest): WebSealCodec;
29
+ }
30
+ /** The sealing of one sealed request, for code that writes its own body (Inertia page, SSE). */
31
+ export interface WebSealer {
32
+ /** The path the request was sealed with (the key input), also sent as `x-dokebi-sealed-path`. */
33
+ readonly path: string;
34
+ /** Seals one text with this request's key. */
35
+ encode(text: string): string;
36
+ }
37
+ /** Response header naming the path a sealed response was sealed with (after a redirect it is the final one). */
38
+ export declare const SEALED_PATH_HEADER = "x-dokebi-sealed-path";
39
+ /** The media type of a Content-Type value: lower case, without parameters. */
40
+ export declare function mediaType(value: unknown): string;
41
+ /** `/a/b?c` → `/a/b`. */
42
+ export declare function pathOf(url: string): string;
43
+ /** `sealExclude` (validated by the options): prefixes without trailing slashes, unique. */
44
+ export declare function sealExclude(input: readonly string[]): readonly string[];
45
+ export declare function checkSealSetting(value: unknown): WebSealSetting | undefined;
46
+ export interface SealingOptions {
47
+ readonly driftMs: number;
48
+ readonly exclude: readonly string[];
49
+ }
50
+ /**
51
+ * The seal slot of one web server. Requests are sealed by their route (`seal`) or by a
52
+ * registered predicate (dokebi-app: hosts with `seal: true`); health routes, `seal: false`
53
+ * routes and `sealExclude` prefixes stay plain. A sealed request's body must be sealed (or
54
+ * multipart), and its JSON responses are sealed on the way out.
55
+ */
56
+ export declare class WebSealing {
57
+ #private;
58
+ readonly logger: Logger;
59
+ readonly options: SealingOptions;
60
+ readonly requestHost: (request: FastifyRequest) => string;
61
+ constructor(logger: Logger, options: SealingOptions, requestHost: (request: FastifyRequest) => string);
62
+ get provider(): WebSealCodecProvider | undefined;
63
+ /** True when anything may be sealed: a predicate or a sealing route. */
64
+ get wanted(): boolean;
65
+ setProvider(provider: WebSealCodecProvider): void;
66
+ addPredicate(predicate: (request: FastifyRequest) => boolean): void;
67
+ /** Counts a route whose own setting may seal it (for the missing provider check). */
68
+ route(setting: WebSealSetting | undefined): void;
69
+ /** Fail closed at start: something wants sealing but no provider will seal it. */
70
+ check(): void;
71
+ /** The sealer of a request, decided once; undefined for a plain request. */
72
+ sealOf(request: FastifyRequest): WebSealer | undefined;
73
+ /**
74
+ * onRequest: decides the request and refuses a plain body on a sealed one: the 415 error to
75
+ * answer with (sent plain), or undefined. Synchronous: dokebi-web calls it from its
76
+ * callback-style hook and passes the error to `done`, so the error mapping answers it.
77
+ */
78
+ refusePlain(request: FastifyRequest): WebError | undefined;
79
+ /** The body parser of the sealed media type: opens, then parses JSON. Refusals are 400. */
80
+ parse(request: FastifyRequest, body: string): Promise<unknown>;
81
+ /** onSend: seals the JSON response of a sealed request (other types pass unchanged). */
82
+ onSend(request: FastifyRequest, reply: FastifyReply, payload: unknown): unknown;
83
+ }