@dokebi/web 0.2.0 → 0.4.1

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,58 @@
1
+ /*
2
+ * Fastify's default schema compilers, built on first use (D-0070 §5).
3
+ *
4
+ * `fastify()` builds its validator compiler (@fastify/ajv-compiler: Ajv, its JTD and draft-07
5
+ * vocabularies) and its serializer compiler (fast-json-stringify) in the constructor, whether or
6
+ * not any route has a schema: about 15 ms of every start, the largest single cost after the JSON
7
+ * Schema check of dokebi.yaml was removed. Here the same two factories are handed to Fastify as
8
+ * `schemaController.compilersFactory` and loaded the first time a route needs one — the same
9
+ * packages, resolved from Fastify's own folder, called with the same arguments.
10
+ *
11
+ * Fastify treats any given `buildValidator` as a custom compiler and then skips one default
12
+ * behaviour: lower-casing the property names of `headers` schemas. These are the default
13
+ * compilers, so the server's flag is put back to "default" right after construction (Fastify's
14
+ * internal schema controller; fastify is pinned, and a web test checks that a header schema with
15
+ * an upper-case name still validates and that Ajv stays unloaded until a schema route exists).
16
+ * Extensions that set their own `schemaController` keep it untouched.
17
+ */
18
+ const { createRequire } = process.getBuiltinModule('node:module');
19
+ const fromWeb = createRequire(import.meta.url);
20
+ /** Requires a package the way Fastify itself does (its dependencies, not this plugin's). */
21
+ const fromFastify = createRequire(fromWeb.resolve('fastify'));
22
+ /** A fresh controller option for one Fastify instance (each instance has its own pools). */
23
+ export function lazyCompilers() {
24
+ const buildValidator = once('@fastify/ajv-compiler');
25
+ const buildSerializer = once('@fastify/fast-json-stringify-compiler');
26
+ const compilersFactory = {
27
+ buildValidator: (schemas, options) => buildValidator()(schemas, options),
28
+ buildSerializer: (schemas, options) => buildSerializer()(schemas, options),
29
+ };
30
+ return { compilersFactory };
31
+ }
32
+ /** The builder a Fastify compiler package exports, made on the first call and kept. */
33
+ function once(name) {
34
+ let builder;
35
+ return () => {
36
+ if (!builder)
37
+ builder = fromFastify(name)();
38
+ return builder;
39
+ };
40
+ }
41
+ /**
42
+ * After `fastify()`: when the server uses `controller` (not an extension's own), mark its compilers
43
+ * as the defaults again so header schemas keep Fastify's case-insensitive names.
44
+ */
45
+ export function restoreDefaultCompilers(server, given, controller) {
46
+ if (given !== controller)
47
+ return false;
48
+ const { kSchemaController } = fromFastify('./lib/symbols.js');
49
+ const schemas = kSchemaController === undefined
50
+ ? undefined
51
+ : server[kSchemaController];
52
+ if (!schemas || typeof schemas.isCustomValidatorCompiler !== 'boolean')
53
+ // Only a Fastify other than the pinned one gets here; never leave headers schemas changed.
54
+ throw new Error('Fastify schema controller not found: @dokebi/web needs the fastify version it pins');
55
+ schemas.isCustomValidatorCompiler = false;
56
+ schemas.isCustomSerializerCompiler = false;
57
+ return true;
58
+ }
@@ -0,0 +1,4 @@
1
+ import type { WebApi } from './index.js';
2
+ export declare const provider: import("@dokebi/core").ProviderDescriptor<WebApi>;
3
+ /** Required: created from @dokebi/web when no `dokebi-web` plugin is registered. */
4
+ export declare const dependency: import("@dokebi/core").PluginDependency<WebApi>;
@@ -0,0 +1,14 @@
1
+ import { defineProvider } from '@dokebi/core';
2
+ /*
3
+ * The one place dokebi-web states its name, package and range (D-0063 §6). Plugins and user code
4
+ * that always install @dokebi/web import `dependency` from '@dokebi/web/dependency' (a small
5
+ * module: it does not load Fastify).
6
+ */
7
+ export const provider = defineProvider({
8
+ name: 'dokebi-web',
9
+ version: '^0.4.0',
10
+ packageName: '@dokebi/web',
11
+ load: () => import('./index.js'),
12
+ });
13
+ /** Required: created from @dokebi/web when no `dokebi-web` plugin is registered. */
14
+ export const dependency = provider.dependency;
@@ -0,0 +1,40 @@
1
+ import { DokebiError, type DokebiErrorOptions } from '@dokebi/core';
2
+ import { type WebFieldError } from './responses.js';
3
+ /** Codes of the errors this plugin throws or answers with (`WebError`, `plugin: 'dokebi-web'`). */
4
+ export type WebErrorCode = 'INVALID_ENTRY' | 'INVALID_ROUTE' | 'INVALID_HOOK' | 'INVALID_ARGUMENT' | 'INVALID_EXTENSION_RESULT' | 'FROZEN' | 'CLOSED' | 'FORM_BODY_DISABLED' | 'FORM_BODY_TOO_MANY_FIELDS' | 'SEAL_PROVIDER_MISSING' | 'SEAL_PROVIDER_INVALID' | 'SEAL_REQUIRED' | 'SEAL_BODY_REFUSED' | 'SEAL_BODY_NOT_JSON' | 'SEAL_STREAM_UNSUPPORTED' | 'VALIDATION_FAILED' | 'NOT_FOUND';
5
+ /**
6
+ * Errors of @dokebi/web; compare `code`, not the class (another installed copy may throw).
7
+ * Request errors carry the HTTP `status` dokebi-web answers with, and a `hint` for the client.
8
+ */
9
+ export declare class WebError extends DokebiError<WebErrorCode> {
10
+ constructor(code: WebErrorCode, message?: string, options?: DokebiErrorOptions);
11
+ }
12
+ /** The refused fields of `validationError`: `{ field: message }` or `[{ field, message }]`. */
13
+ export type WebValidationInput = Readonly<Record<string, string>> | readonly {
14
+ readonly field: string;
15
+ readonly message: string;
16
+ }[];
17
+ /** Options of `validationError`: the message and hint of the answer, and extra `data`. */
18
+ export interface WebValidationOptions {
19
+ readonly message?: string;
20
+ readonly hint?: string;
21
+ readonly data?: Readonly<Record<string, unknown>>;
22
+ }
23
+ /**
24
+ * A 422 VALIDATION_FAILED `WebError` with its `fields` (D-0074 §2): what `validationError`
25
+ * returns. dokebi-web answers it like a refused route schema: `fields` and `errors` in the body,
26
+ * a validation redirect for Inertia (with @dokebi/template-inertia and a session).
27
+ */
28
+ export declare class WebValidationError extends WebError {
29
+ readonly fields: readonly WebFieldError[];
30
+ /** `{ field: first message }`, the shape of Inertia's `useForm().errors`. */
31
+ readonly errors: Readonly<Record<string, string>>;
32
+ constructor(fields: readonly WebFieldError[], options?: WebValidationOptions);
33
+ }
34
+ /**
35
+ * The error to throw when the handler's own check refuses fields:
36
+ * `throw validationError({ name: 'Already taken' })`. Clients get exactly what a refused route
37
+ * schema gives them: 422 `{ error: 'VALIDATION_FAILED', message, hint, fields, errors }`
38
+ * (D-0074 §2). Bad input (no field, a non-string message) throws INVALID_ARGUMENT.
39
+ */
40
+ export declare function validationError(input: WebValidationInput, options?: WebValidationOptions): WebValidationError;
package/dist/errors.js ADDED
@@ -0,0 +1,106 @@
1
+ import { DokebiError } from '@dokebi/core';
2
+ import { errorsByField, VALIDATION_HINT } from './responses.js';
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
+ const FIX = {
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.',
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
+ INVALID_ARGUMENT: 'Pass a function: web.sealRequests((request) => boolean).',
9
+ 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.',
10
+ FROZEN: 'Add routes, Fastify plugins, constraints and seal settings during setup, before start.',
11
+ CLOSED: 'Call web.track() only while the application runs.',
12
+ FORM_BODY_DISABLED: FORM_FIX,
13
+ FORM_BODY_TOO_MANY_FIELDS: 'Send fewer form fields, or raise formMaxFields under dokebi-web in dokebi.yaml (1..10000).',
14
+ SEAL_PROVIDER_MISSING: 'Register the dokebi-seal plugin (npx dokebi add @dokebi/seal), or remove seal: true from the domains and routes.',
15
+ SEAL_PROVIDER_INVALID: 'Register one seal codec provider (the dokebi-seal plugin) with { contentType, forRequest }.',
16
+ 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
+ SEAL_BODY_REFUSED: 'Seal request bodies with @dokebi/seal for this host and path, once, within sealDriftMs of the server clock.',
18
+ SEAL_BODY_NOT_JSON: 'A sealed request body must be JSON text before sealing.',
19
+ 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
+ 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 app (dokebi-app domains), a module route only under its mount prefix.',
22
+ };
23
+ const HINT = {
24
+ FORM_BODY_DISABLED: 'This address does not accept HTML form posts. Send JSON instead.',
25
+ FORM_BODY_TOO_MANY_FIELDS: 'The form has too many fields.',
26
+ SEAL_REQUIRED: 'This address only accepts sealed requests. Reload the page and try again.',
27
+ SEAL_BODY_REFUSED: 'The request could not be opened. Reload the page and try again.',
28
+ SEAL_BODY_NOT_JSON: 'The request could not be read. Reload the page and try again.',
29
+ VALIDATION_FAILED: VALIDATION_HINT,
30
+ NOT_FOUND: 'The page or resource does not exist.',
31
+ };
32
+ const STATUS = {
33
+ FORM_BODY_DISABLED: 415,
34
+ FORM_BODY_TOO_MANY_FIELDS: 413,
35
+ SEAL_REQUIRED: 415,
36
+ SEAL_BODY_REFUSED: 400,
37
+ SEAL_BODY_NOT_JSON: 400,
38
+ SEAL_STREAM_UNSUPPORTED: 500,
39
+ VALIDATION_FAILED: 422,
40
+ NOT_FOUND: 404,
41
+ };
42
+ /**
43
+ * Errors of @dokebi/web; compare `code`, not the class (another installed copy may throw).
44
+ * Request errors carry the HTTP `status` dokebi-web answers with, and a `hint` for the client.
45
+ */
46
+ export class WebError extends DokebiError {
47
+ constructor(code, message = `Web: ${code}`, options = {}) {
48
+ super(code, message, {
49
+ plugin: 'dokebi-web',
50
+ fix: FIX[code],
51
+ ...(HINT[code] === undefined ? {} : { hint: HINT[code] }),
52
+ ...(STATUS[code] === undefined ? {} : { status: STATUS[code] }),
53
+ ...options,
54
+ });
55
+ this.name = 'WebError';
56
+ }
57
+ }
58
+ /**
59
+ * A 422 VALIDATION_FAILED `WebError` with its `fields` (D-0074 §2): what `validationError`
60
+ * returns. dokebi-web answers it like a refused route schema: `fields` and `errors` in the body,
61
+ * a validation redirect for Inertia (with @dokebi/template-inertia and a session).
62
+ */
63
+ export class WebValidationError extends WebError {
64
+ fields;
65
+ /** `{ field: first message }`, the shape of Inertia's `useForm().errors`. */
66
+ errors;
67
+ constructor(fields, options = {}) {
68
+ super('VALIDATION_FAILED', options.message ??
69
+ `Invalid fields: ${[...new Set(fields.map((item) => item.field))].join(', ')}`, {
70
+ ...(options.hint === undefined ? {} : { hint: options.hint }),
71
+ ...(options.data === undefined ? {} : { data: options.data }),
72
+ });
73
+ this.fields = Object.freeze(fields.map((item) => Object.freeze({ ...item })));
74
+ this.errors = Object.freeze(errorsByField(this.fields));
75
+ }
76
+ }
77
+ /** A field name or message dokebi-web accepts: 1 to 200, and up to 1000 characters. */
78
+ function fieldText(value, max) {
79
+ return typeof value === 'string' && value.length > 0 && value.length <= max;
80
+ }
81
+ /**
82
+ * The error to throw when the handler's own check refuses fields:
83
+ * `throw validationError({ name: 'Already taken' })`. Clients get exactly what a refused route
84
+ * schema gives them: 422 `{ error: 'VALIDATION_FAILED', message, hint, fields, errors }`
85
+ * (D-0074 §2). Bad input (no field, a non-string message) throws INVALID_ARGUMENT.
86
+ */
87
+ export function validationError(input, options = {}) {
88
+ const list = Array.isArray(input)
89
+ ? input.map((item) => ({
90
+ field: item?.field,
91
+ message: item?.message,
92
+ }))
93
+ : input !== null && typeof input === 'object'
94
+ ? Object.entries(input).map(([field, message]) => ({
95
+ field,
96
+ message,
97
+ }))
98
+ : [];
99
+ if (!list.length ||
100
+ list.length > 1000 ||
101
+ list.some((item) => !fieldText(item.field, 200) || !fieldText(item.message, 1000)))
102
+ throw new WebError('INVALID_ARGUMENT', 'validationError() takes { field: message } or [{ field, message }] with at least one field', {
103
+ fix: "throw validationError({ name: 'Already taken' }) — field names of 1 to 200 characters, messages of 1 to 1000.",
104
+ });
105
+ return new WebValidationError(list, options);
106
+ }
@@ -0,0 +1,95 @@
1
+ import type { SecureServerOptions } from 'node:http2';
2
+ import type { ServerOptions } from 'node:https';
3
+ import type { FastifyRequest, FastifyServerOptions } from 'fastify';
4
+ /**
5
+ * Fastify creation options (`Fastify(options)`): HTTPS, HTTP/2, `serverFactory`, a query string
6
+ * parser, router settings and the like, over the ones dokebi-web derives from dokebi.yaml.
7
+ */
8
+ export type WebFastifyOptions = FastifyServerOptions & {
9
+ readonly https?: ServerOptions | SecureServerOptions | null;
10
+ readonly http2?: boolean;
11
+ readonly http2SessionTimeout?: number;
12
+ };
13
+ /**
14
+ * An error response body. `error` is the code; `message`, `hint` and `data` go to clients;
15
+ * `fix` and `details` only outside production (dokebi-web removes them in production, whatever
16
+ * a hook returns).
17
+ */
18
+ export interface WebErrorBody {
19
+ readonly error: string;
20
+ readonly message?: string;
21
+ readonly hint?: string;
22
+ readonly data?: Readonly<Record<string, unknown>>;
23
+ readonly fix?: string;
24
+ readonly details?: unknown;
25
+ readonly [field: string]: unknown;
26
+ }
27
+ /** The status and body of an error response. */
28
+ export interface WebErrorAnswer {
29
+ /** 400 to 599. */
30
+ readonly status: number;
31
+ readonly body: WebErrorBody;
32
+ }
33
+ /** What `errorBody` is told about one failed request. */
34
+ export interface WebErrorContext {
35
+ readonly request: FastifyRequest;
36
+ /** The answer dokebi-web would send (D-0063 §1 mapping). */
37
+ readonly answer: WebErrorAnswer;
38
+ /** True in production (or with `developmentErrors: false`): `fix` and `details` are dropped. */
39
+ readonly production: boolean;
40
+ }
41
+ /** Why a request is refused before it reaches a route. */
42
+ export type WebUnavailableReason = 'STARTING' | 'NOT_READY' | 'DRAINING';
43
+ /** The refusal of a request while the app is not ready or is draining. */
44
+ export interface WebUnavailableAnswer {
45
+ /** 400 to 599 (503 by default). */
46
+ readonly status: number;
47
+ /** Extra response headers (for example `retry-after`); `connection: close` is always set. */
48
+ readonly headers?: Readonly<Record<string, string>>;
49
+ /** Sent as JSON. */
50
+ readonly body: unknown;
51
+ }
52
+ /** What `unavailable` is told about one refused request. */
53
+ export interface WebUnavailableContext {
54
+ readonly request: FastifyRequest;
55
+ readonly reason: WebUnavailableReason;
56
+ /** The default refusal: 503 `{ error: 'SERVICE_UNAVAILABLE', reason }`. */
57
+ readonly answer: WebUnavailableAnswer;
58
+ }
59
+ /** The hooks the plugin calls, as plain methods (internal: the runtime's view of a subclass). */
60
+ export interface WebHooks {
61
+ fastifyOptions(defaults: WebFastifyOptions): WebFastifyOptions;
62
+ errorBody(error: unknown, context: WebErrorContext): WebErrorAnswer;
63
+ unavailable(context: WebUnavailableContext): WebUnavailableAnswer;
64
+ }
65
+ declare const WebExtension_base: import("@dokebi/core").ExtensionRoot;
66
+ /**
67
+ * Subclass this in `src/infra/web/extension.ts` (`export default class AppWeb extends
68
+ * WebExtension {}`) and override only the hooks you need, with `protected override`. Each
69
+ * default keeps the plugin's own behaviour; an empty subclass changes nothing and costs nothing
70
+ * per request. Hooks run with their inputs only: no constructor parameters, hooks never call
71
+ * each other, and all three are synchronous.
72
+ */
73
+ export declare class WebExtension extends WebExtension_base {
74
+ /**
75
+ * The Fastify creation options: return `defaults` with your changes (`https`, `http2`,
76
+ * `serverFactory`, `routerOptions`, …). Called once at setup. `return503OnClosing` and
77
+ * `forceCloseConnections` belong to the drain contract and may not change. Default: `defaults`.
78
+ */
79
+ protected fastifyOptions(defaults: WebFastifyOptions): WebFastifyOptions;
80
+ /**
81
+ * The status and body of an error response (a thrown error, a Fastify 4xx). Called per failed
82
+ * request; return `context.answer` changed or your own. In production dokebi-web drops `fix`,
83
+ * `details` and `stack` from what you return. Default: `context.answer`.
84
+ */
85
+ protected errorBody(error: unknown, context: WebErrorContext): WebErrorAnswer;
86
+ /**
87
+ * The refusal of a request before start, while health is not ready, or while draining
88
+ * (status, headers such as `retry-after`, body). It only shapes the refusal: the request is
89
+ * refused either way, so drain stays correct. Default: `context.answer`.
90
+ */
91
+ protected unavailable(context: WebUnavailableContext): WebUnavailableAnswer;
92
+ }
93
+ /** The plugin's handle on a subclass instance (not exported from the package). */
94
+ export declare function webHooks(extension: WebExtension): WebHooks;
95
+ export {};
@@ -0,0 +1,52 @@
1
+ import { defineExtension } from '@dokebi/core';
2
+ let bridge;
3
+ /**
4
+ * Subclass this in `src/infra/web/extension.ts` (`export default class AppWeb extends
5
+ * WebExtension {}`) and override only the hooks you need, with `protected override`. Each
6
+ * default keeps the plugin's own behaviour; an empty subclass changes nothing and costs nothing
7
+ * per request. Hooks run with their inputs only: no constructor parameters, hooks never call
8
+ * each other, and all three are synchronous.
9
+ */
10
+ export class WebExtension extends defineExtension({
11
+ plugin: 'dokebi-web',
12
+ api: 1,
13
+ hooks: ['fastifyOptions', 'errorBody', 'unavailable'],
14
+ file: 'src/infra/web/extension.ts',
15
+ }) {
16
+ static {
17
+ bridge = (extension) => Object.freeze({
18
+ fastifyOptions: (defaults) => extension.fastifyOptions(defaults),
19
+ errorBody: (error, context) => extension.errorBody(error, context),
20
+ unavailable: (context) => extension.unavailable(context),
21
+ });
22
+ }
23
+ /**
24
+ * The Fastify creation options: return `defaults` with your changes (`https`, `http2`,
25
+ * `serverFactory`, `routerOptions`, …). Called once at setup. `return503OnClosing` and
26
+ * `forceCloseConnections` belong to the drain contract and may not change. Default: `defaults`.
27
+ */
28
+ fastifyOptions(defaults) {
29
+ return defaults;
30
+ }
31
+ /**
32
+ * The status and body of an error response (a thrown error, a Fastify 4xx). Called per failed
33
+ * request; return `context.answer` changed or your own. In production dokebi-web drops `fix`,
34
+ * `details` and `stack` from what you return. Default: `context.answer`.
35
+ */
36
+ errorBody(error, context) {
37
+ void error;
38
+ return context.answer;
39
+ }
40
+ /**
41
+ * The refusal of a request before start, while health is not ready, or while draining
42
+ * (status, headers such as `retry-after`, body). It only shapes the refusal: the request is
43
+ * refused either way, so drain stays correct. Default: `context.answer`.
44
+ */
45
+ unavailable(context) {
46
+ return context.answer;
47
+ }
48
+ }
49
+ /** The plugin's handle on a subclass instance (not exported from the package). */
50
+ export function webHooks(extension) {
51
+ return bridge(extension);
52
+ }
@@ -0,0 +1,34 @@
1
+ import type { WebErrorBody } from './extension.js';
2
+ /** What the form helpers read of a request (a Fastify request has it). */
3
+ export interface WebFormRequest {
4
+ readonly method: string;
5
+ readonly url: string;
6
+ readonly headers: Readonly<Record<string, string | string[] | undefined>>;
7
+ readonly body?: unknown;
8
+ }
9
+ /** One value of the old input: the body's top-level scalars. */
10
+ export type WebFormValue = string | number | boolean | null;
11
+ /**
12
+ * True when the request body is an HTML form submission (`application/x-www-form-urlencoded`
13
+ * or `multipart/form-data`), as a browser sends a `<form method="post">`.
14
+ */
15
+ export declare function isFormSubmission(headers: Readonly<Record<string, string | string[] | undefined>>): boolean;
16
+ /**
17
+ * 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
+ * Otherwise `fallback` for a POST, PUT, PATCH or DELETE (template-inertia passes `/`), or
20
+ * undefined. A GET or HEAD whose referer is missing or is itself has no way back: a redirect to
21
+ * itself would be refused again, forever.
22
+ */
23
+ export declare function formBackTarget(request: WebFormRequest, host: string, fallback?: string): string | undefined;
24
+ /**
25
+ * The old input of a refused form (D-0074 §3): the body's top-level strings, numbers, booleans
26
+ * 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.
28
+ */
29
+ export declare function formOldInput(body: unknown): Record<string, WebFormValue> | undefined;
30
+ /**
31
+ * The `errors` (`{ field: message }`) of a validation answer — a refused route schema or
32
+ * `validationError()` (422 `VALIDATION_FAILED`) — or undefined for any other error body.
33
+ */
34
+ export declare function formFieldErrors(body: WebErrorBody): Record<string, string> | undefined;
package/dist/forms.js ADDED
@@ -0,0 +1,82 @@
1
+ /** Field names whose values never go into the session as old input. */
2
+ const SECRET_FIELD = /pass(?:word|wd|phrase)?|secret|token|api[_-]?key|card|cvc|cvv|otp|pin$/i;
3
+ /** Old input kept at most (as JSON text): a larger body is not flashed. */
4
+ const OLD_MAX = 8192;
5
+ /** A Referer longer than this is not followed. */
6
+ const REFERER_MAX = 4096;
7
+ /** Body types of an HTML form submission. */
8
+ const FORM_TYPES = new Set(['application/x-www-form-urlencoded', 'multipart/form-data']);
9
+ /**
10
+ * True when the request body is an HTML form submission (`application/x-www-form-urlencoded`
11
+ * or `multipart/form-data`), as a browser sends a `<form method="post">`.
12
+ */
13
+ export function isFormSubmission(headers) {
14
+ const value = headers['content-type'];
15
+ const type = Array.isArray(value) ? value[0] : value;
16
+ if (type === undefined)
17
+ return false;
18
+ return FORM_TYPES.has(type.split(';', 1)[0]?.trim().toLowerCase() ?? '');
19
+ }
20
+ /**
21
+ * 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
+ * Otherwise `fallback` for a POST, PUT, PATCH or DELETE (template-inertia passes `/`), or
24
+ * undefined. A GET or HEAD whose referer is missing or is itself has no way back: a redirect to
25
+ * itself would be refused again, forever.
26
+ */
27
+ export function formBackTarget(request, host, fallback) {
28
+ const read = ['GET', 'HEAD'].includes(request.method);
29
+ const value = request.headers.referer;
30
+ const referer = Array.isArray(value) ? value[0] : value;
31
+ if (typeof referer === 'string' && referer.length <= REFERER_MAX && URL.canParse(referer)) {
32
+ const url = new URL(referer);
33
+ if ((url.protocol === 'http:' || url.protocol === 'https:') &&
34
+ url.host.toLowerCase() === host.toLowerCase()) {
35
+ const target = url.pathname + url.search;
36
+ if (!(read && target === request.url))
37
+ return target;
38
+ }
39
+ }
40
+ return read ? undefined : fallback;
41
+ }
42
+ /**
43
+ * The old input of a refused form (D-0074 §3): the body's top-level strings, numbers, booleans
44
+ * 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.
46
+ */
47
+ export function formOldInput(body) {
48
+ if (body === null || typeof body !== 'object' || Array.isArray(body))
49
+ return undefined;
50
+ const old = {};
51
+ let kept = 0;
52
+ for (const [key, value] of Object.entries(body)) {
53
+ if (key === '__proto__' || SECRET_FIELD.test(key))
54
+ continue;
55
+ if (value === null ||
56
+ typeof value === 'boolean' ||
57
+ (typeof value === 'number' && Number.isFinite(value)) ||
58
+ typeof value === 'string') {
59
+ old[key] = value;
60
+ kept++;
61
+ }
62
+ }
63
+ if (!kept || JSON.stringify(old).length > OLD_MAX)
64
+ return undefined;
65
+ return old;
66
+ }
67
+ /**
68
+ * The `errors` (`{ field: message }`) of a validation answer — a refused route schema or
69
+ * `validationError()` (422 `VALIDATION_FAILED`) — or undefined for any other error body.
70
+ */
71
+ export function formFieldErrors(body) {
72
+ if (body.error !== 'VALIDATION_FAILED')
73
+ return undefined;
74
+ const errors = body.errors;
75
+ if (errors === null || typeof errors !== 'object' || Array.isArray(errors))
76
+ return undefined;
77
+ const result = {};
78
+ for (const [field, message] of Object.entries(errors))
79
+ if (field !== '__proto__' && typeof message === 'string')
80
+ result[field] = message;
81
+ return result;
82
+ }
package/dist/index.d.ts CHANGED
@@ -1,6 +1,12 @@
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 WebErrorResponder } from './responses.js';
3
4
  import { type WebSealCodecProvider, type WebSealer, type WebSealSetting } from './seal.js';
5
+ export { validationError, WebError, type WebErrorCode, WebValidationError, type WebValidationInput, type WebValidationOptions, } from './errors.js';
6
+ 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';
8
+ export { options, type WebOptions } from './options.js';
9
+ export { errorFormat, type WebErrorFormat, type WebErrorResponder, type WebErrorResponse, type WebFieldError, } from './responses.js';
4
10
  export { SEALED_PATH_HEADER, type WebSealCodec, type WebSealCodecProvider, type WebSealer, type WebSealRequest, type WebSealSetting, } from './seal.js';
5
11
  export type WebRoute<T extends RouteGenericInterface = RouteGenericInterface> = RouteOptions<RawServerDefault, RawRequestDefaultExpression<RawServerDefault>, RawReplyDefaultExpression<RawServerDefault>, T> & {
6
12
  /**
@@ -47,6 +53,14 @@ export interface WebApi {
47
53
  sealOf(request: FastifyRequest): WebSealer | undefined;
48
54
  /** True once a seal codec is registered. */
49
55
  readonly sealing: boolean;
56
+ /**
57
+ * Adds an error responder (D-0074): before dokebi-web writes an error answer (a thrown error,
58
+ * a refused schema, an unknown route), responders are asked, the last added first, and one
59
+ * may write the answer itself (dokebi-app: the app's `errors/<status>.ejs`; template-inertia:
60
+ * the validation redirect and the error page). Setup only. Not asked for the 503 refusals
61
+ * before ready and while draining.
62
+ */
63
+ errorResponder(responder: WebErrorResponder): void;
50
64
  }
51
65
  export interface WebRequestLike {
52
66
  readonly headers: Readonly<Record<string, string | string[] | undefined>>;
@@ -56,20 +70,23 @@ export interface WebRequestLike {
56
70
  }
57
71
  /** A Fastify constraint strategy; see Fastify `addConstraintStrategy`. */
58
72
  export type WebConstraintStrategy = Parameters<FastifyInstance['addConstraintStrategy']>[0];
59
- export declare class WebError extends Error {
60
- readonly code: 'INVALID_OPTIONS' | 'FROZEN' | 'CLOSED';
61
- constructor(code: 'INVALID_OPTIONS' | 'FROZEN' | 'CLOSED');
62
- }
63
73
  export interface WebHealthRoutes {
64
74
  readonly live: string;
65
75
  readonly ready: string;
66
76
  }
67
77
  /** Plugin instances or descriptors that must outlive Fastify close (native onClose users). */
68
78
  export type WebRequirement = Plugin<unknown> | PluginDependency;
79
+ /**
80
+ * The user entry module (`src/infra/web/extension.ts`; projects from before 0.4.0 keep
81
+ * `src/infra/web/requires.ts`), or the extension class itself.
82
+ */
69
83
  export interface WebEntry {
84
+ /** Plugins Fastify `onClose` hooks still use: they are cleaned up after the server closed. */
70
85
  readonly requires?: readonly WebRequirement[];
86
+ /** `export default class AppWeb extends WebExtension {}` (D-0064). */
87
+ readonly default?: unknown;
71
88
  }
72
89
  export declare const createPlugin: import("@dokebi/core").PluginFactory<WebApi>;
73
- /** Declares dokebi-web as a required provider; it is created from this package when absent. */
74
- export declare const dependency: PluginDependency<WebApi>;
75
90
  export type { RouteGenericInterface } from 'fastify';
91
+ /** Declares dokebi-web as a required provider (also `@dokebi/web/dependency`, D-0063 §6). */
92
+ export { dependency } from './dependency.js';