@dokebi/web 0.4.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.
package/AI.md CHANGED
@@ -1,4 +1,4 @@
1
- # AI guide — @dokebi/web 0.4.0
1
+ # AI guide — @dokebi/web 0.4.1
2
2
 
3
3
  A plugin through which the app owns a Fastify 5 HTTP server. It blocks requests before the app is ready and while it shuts down (503), serves health routes, drains requests in progress, swaps cluster workers without downtime and handles trusted proxies. Routers, controllers, views and DBs are not required. Node >=24.0.0, core ^0.4.0. Details are in the [README](README.md).
4
4
 
@@ -75,13 +75,13 @@ http.route({ method: 'POST', url: '/import', handler: async (request, reply) =>
75
75
  | `requestHost(request)` | the request host under the trusted-proxy rules (lower case, port kept) |
76
76
  | `route({ ..., seal })` | `seal: false` stays plain even on a seal host (webhooks, server to server); `true` or a function seals on any host (D-0062) |
77
77
  | `sealCodec(provider)` · `sealRequests(predicate)` · `sealOf(request)` · `sealing` | the HTTP seal slot (D-0062). @dokebi/seal provides the codec and @dokebi/app registers the decision; you rarely call them yourself |
78
- | `errorResponder(responder)` | adds an error responder (D-0074, §6): asked before web writes an error answer, the last added first; `(response) => boolean \| Promise<boolean>`, true when it sent the answer itself. @dokebi/app (error views) and template-inertia (validation redirect, error page) use it. Setup only |
78
+ | `errorResponder(responder)` | adds an error responder (D-0074, §6): asked before web writes an error answer, the last added first; `(response) => boolean \| Promise<boolean>`, true when it sent the answer itself. @dokebi/app (HTML form redirect, error views) and template-inertia (validation redirect, error page) use it. Setup only |
79
79
  | `address` | the real address after listen (undefined before). In a cluster worker it is set after core `ready`, so other plugins read it in `ready`. A process with `runtime.serving` false (a migration tool and so on) never listens, so it stays undefined |
80
80
 
81
81
  - `dependency` of `@dokebi/web/dependency` (also exported from the root) is the provider descriptor for plugins and app code that always install web (D-0063 §6; a small module that does not load Fastify).
82
82
  - `@dokebi/web/points` exports the contribution points `viewEngines` (`dokebi-web:view-engine`) and `realtime` (`dokebi-web:realtime`) and their value types (`WebViewEngine`, `WebRealtimeTransport`, `WebRealtimeScope`): template-ejs and template-inertia contribute view engines, websocket and sse contribute realtime transports, and @dokebi/app collects them.
83
83
  - web also contributes Fastify `inject` to the `inject` slot of `@dokebi/core/testing` (`dokebi-testing:inject`), so `await inject('/health/live')` runs without a socket.
84
- - Other exports: `options` (the `defineOptions` declaration) and `WebOptions`, `WebError`, `validationError` and `WebValidationError` (§6), `errorFormat` and the responder types (`WebErrorResponder`, `WebErrorResponse`, `WebErrorFormat`, `WebFieldError`), `WebExtension` and its types, `SEALED_PATH_HEADER` (`x-dokebi-sealed-path`) and the seal types.
84
+ - Other exports: `options` (the `defineOptions` declaration) and `WebOptions`, `WebError`, `validationError` and `WebValidationError` (§6), `errorFormat` and the responder types (`WebErrorResponder`, `WebErrorResponse`, `WebErrorFormat`, `WebFieldError`), the form helpers `isFormSubmission`, `formFieldErrors`, `formOldInput`, `formBackTarget` and their types `WebFormRequest`, `WebFormValue` (0.4.1, §6), `WebExtension` and its types, `SEALED_PATH_HEADER` (`x-dokebi-sealed-path`) and the seal types.
85
85
 
86
86
  ## 3. Start and request blocking
87
87
 
@@ -149,9 +149,20 @@ Do not answer validation with your own `reply.code(422).send(…)`: template-ine
149
149
  | Inertia POST | JSON | JSON | JSON | – | JSON | JSON | JSON | JSON | JSON |
150
150
  | sealed request (seal host) | JSON (sealed) | – | JSON (sealed) | 415 `SEAL_REQUIRED` JSON (plain) | JSON (sealed) | JSON (sealed) | JSON (sealed) | JSON (sealed) | JSON (sealed) |
151
151
 
152
- (`–`: that client cannot send that request. The table is `tests/error-matrix.test.ts`.) With @dokebi/template-inertia an Inertia request refused with 422 goes back instead (303, `errors` in the session flash), and an app's error views or Inertia error page may draw the HTML answer: both through error responders.
152
+ (`–`: that client cannot send that request. The table is `tests/error-matrix.test.ts`.) With @dokebi/template-inertia an Inertia request refused with 422 goes back instead (303, `errors` in the session flash); with @dokebi/app 0.4.1 and @dokebi/session an HTML form post refused with 422 goes back the same way (`data.errors`, `data.old` in the app's views); and an app's error views or Inertia error page may draw the HTML answer: all through error responders.
153
153
 
154
- **Error responders (D-0074).** `web.errorResponder((response) => …)` (setup only) is asked before web writes an error answer, the last added first. `response` is `{ request, reply, error, status, body, format, production, sealed }` with the final status and body (after `errorBody`, production-cut). Return true after sending the answer yourself (`reply.redirect`, a rendered view), false to pass. A responder that throws (or returns true without sending) is logged once per route and interval as `error` `Web error responder failed` (`code: WEB_ERROR_RESPONDER_FAILED`, `status`, `errorCode`, `error`) and web sends its own answer. @dokebi/app answers an app's hosts with its error views; template-inertia does the validation redirect and the error page. Responders are not asked for the 503 refusals.
154
+ **Error responders (D-0074).** `web.errorResponder((response) => …)` (setup only) is asked before web writes an error answer, the last added first. `response` is `{ request, reply, error, status, body, format, production, sealed }` with the final status and body (after `errorBody`, production-cut). Return true after sending the answer yourself (`reply.redirect`, a rendered view), false to pass. A responder that throws (or returns true without sending) is logged once per route and interval as `error` `Web error responder failed` (`code: WEB_ERROR_RESPONDER_FAILED`, `status`, `errorCode`, `error`) and web sends its own answer. @dokebi/app answers an app's hosts with the HTML form redirect and its error views; template-inertia does the Inertia validation redirect and the error page. Responders are not asked for the 503 refusals.
155
+
156
+ **Form helpers (0.4.1, D-0074 addendum 1).** The pieces of the validation redirect, shared by template-inertia and @dokebi/app, for a responder of your own:
157
+
158
+ | Function | Returns |
159
+ |---|---|
160
+ | `isFormSubmission(headers)` | true for a body of `application/x-www-form-urlencoded` or `multipart/form-data` (a browser `<form method="post">`) |
161
+ | `formFieldErrors(body)` | the `errors` (`{ field: message }`) of a 422 `VALIDATION_FAILED` body, else undefined |
162
+ | `formOldInput(body)` | the request body's top-level strings, numbers, booleans and nulls without password-like fields (`password`, `token`, `secret`, `api_key`, `card`, `cvc`, `otp`, `pin`…); undefined when nothing is left or it is over 8 KB as JSON |
163
+ | `formBackTarget(request, host, fallback?)` | the path and query of the `Referer` when it is `host` (`web.requestHost(request)`; another origin is never followed), else `fallback` for a POST/PUT/PATCH/DELETE, else undefined; a GET or HEAD never goes back to itself (no redirect loop) |
164
+
165
+ dokebi-web knows no session: the caller flashes `errors` and `old` and answers `reply.redirect(target, 303)`.
155
166
 
156
167
  <!-- docs-check: complete-error-codes WebErrorCode -->
157
168
  `WebError` (`plugin: 'dokebi-web'`, always a `fix`; request errors also have `status` and `hint`):
package/README.md CHANGED
@@ -1,4 +1,4 @@
1
- # @dokebi/web 0.4.0
1
+ # @dokebi/web 0.4.1
2
2
 
3
3
  An optional package for Node >=24.0.0 and core ^0.4.0 (public on npm). It owns an HTTP server built on Fastify 5.12.7; DBs, routers, controllers and views are not required.
4
4
 
@@ -58,7 +58,7 @@ In a single process, drain refuses new requests with 503 and then waits for resp
58
58
 
59
59
  For native callback hooks, done or the normal end of the response marks the end of the work; async hooks are awaited until their returned Promise settles. Work that continues after the response, and async work in user raw streams, parsers, custom error handlers, timers or outside events, is not tracked automatically: wait for it with track or the owning plugin's drain. Do not mix async and done in a hook. `listen`/`close`, overwriting root hooks and bypassing the reserved `dokebiHealth` config are outside the extension contract.
60
60
 
61
- Error responses follow the D-0063 §1 mapping: a Dokebi error answers with its `status` and `{ error: code, message, hint?, data? }` (plus `fix` and `details` in development); an unknown error answers 500 `{ error: 'INTERNAL_SERVER_ERROR' }`. In production (`NODE_ENV=production` or `developmentErrors: false`) `fix` and `details` are left out and 5xx messages become generic sentences. One rule picks the format ([D-0074](https://git.nyx-zone.com/dokebi/framework/-/blob/main/docs/decisions/D-0074-error-responses.md)): Inertia requests, XHR, Bearer API clients, JSON request bodies, sealed requests and `fetch()` get JSON; only a browser page (a navigation, an HTML form post) gets the same content as a small HTML page. A refused body or query string schema is 422 `{ error: 'VALIDATION_FAILED', message, hint, fields: [{ field, message }], errors: { field: message } }`, and `throw validationError({ name: 'Already taken' })` from a handler gives the same answer; an unknown route is 404 `NOT_FOUND` in the same shape. Error responders (`web.errorResponder`) let @dokebi/app draw an app's error views and @dokebi/template-inertia answer Inertia requests (validation redirect, error page). A 500 leaves the error log `WEB_REQUEST_FAILED` (with the full error text). The table is in [AI.md](AI.md) §6. If you register your own error handler, its security is your responsibility. HTTP authentication, rate limiting, CORS and so on are Fastify plugins the app chooses.
61
+ Error responses follow the D-0063 §1 mapping: a Dokebi error answers with its `status` and `{ error: code, message, hint?, data? }` (plus `fix` and `details` in development); an unknown error answers 500 `{ error: 'INTERNAL_SERVER_ERROR' }`. In production (`NODE_ENV=production` or `developmentErrors: false`) `fix` and `details` are left out and 5xx messages become generic sentences. One rule picks the format ([D-0074](https://git.nyx-zone.com/dokebi/framework/-/blob/main/docs/decisions/D-0074-error-responses.md)): Inertia requests, XHR, Bearer API clients, JSON request bodies, sealed requests and `fetch()` get JSON; only a browser page (a navigation, an HTML form post) gets the same content as a small HTML page. A refused body or query string schema is 422 `{ error: 'VALIDATION_FAILED', message, hint, fields: [{ field, message }], errors: { field: message } }`, and `throw validationError({ name: 'Already taken' })` from a handler gives the same answer; an unknown route is 404 `NOT_FOUND` in the same shape. Error responders (`web.errorResponder`) let @dokebi/app draw an app's error views and send a refused HTML form back to its page, and @dokebi/template-inertia answer Inertia requests (validation redirect, error page). The pieces of that redirect are exported for your own responders (0.4.1): `isFormSubmission`, `formFieldErrors`, `formOldInput` and `formBackTarget` (AI.md §6). A 500 leaves the error log `WEB_REQUEST_FAILED` (with the full error text). The table is in [AI.md](AI.md) §6. If you register your own error handler, its security is your responsibility. HTTP authentication, rate limiting, CORS and so on are Fastify plugins the app chooses.
62
62
 
63
63
  ## Install and run
64
64
 
@@ -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
@@ -4,6 +4,7 @@ import { type WebErrorResponder } from './responses.js';
4
4
  import { type WebSealCodecProvider, type WebSealer, type WebSealSetting } from './seal.js';
5
5
  export { validationError, WebError, type WebErrorCode, WebValidationError, type WebValidationInput, type WebValidationOptions, } from './errors.js';
6
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';
7
8
  export { options, type WebOptions } from './options.js';
8
9
  export { errorFormat, type WebErrorFormat, type WebErrorResponder, type WebErrorResponse, type WebFieldError, } from './responses.js';
9
10
  export { SEALED_PATH_HEADER, type WebSealCodec, type WebSealCodecProvider, type WebSealer, type WebSealRequest, type WebSealSetting, } from './seal.js';
package/dist/index.js CHANGED
@@ -14,6 +14,7 @@ import { errorAnswer, errorFormat, errorPage, productionBody, sendableDetails, v
14
14
  import { checkSealSetting, sealExclude, WebSealing, } from './seal.js';
15
15
  export { validationError, WebError, WebValidationError, } from './errors.js';
16
16
  export { WebExtension, } from './extension.js';
17
+ export { formBackTarget, formFieldErrors, formOldInput, isFormSubmission, } from './forms.js';
17
18
  export { options } from './options.js';
18
19
  export { errorFormat, } from './responses.js';
19
20
  export { SEALED_PATH_HEADER, } from './seal.js';
@@ -1064,7 +1065,7 @@ class WebRuntime {
1064
1065
  }
1065
1066
  export const createPlugin = definePlugin({
1066
1067
  name: 'dokebi-web',
1067
- version: '0.4.0',
1068
+ version: '0.4.1',
1068
1069
  core: '^0.4.0',
1069
1070
  options: declaration,
1070
1071
  entry: (input) => new WebEntryInput(input),
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dokebi/web",
3
- "version": "0.4.0",
3
+ "version": "0.4.1",
4
4
  "description": "Fastify 5 HTTP server owned by a Dokebi app: 503 before ready, health routes, drain and cluster handover.",
5
5
  "keywords": [
6
6
  "dokebi",