@dokebi/web 0.4.0 → 0.4.2

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.2
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) and the path stays on it (0.4.2: `//other.host/…`, `/\other.host` and their encoded forms such as `/%2F%2F…` are refused, so the target never resolves to another origin), 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`):
@@ -171,6 +182,7 @@ Do not answer validation with your own `reply.code(422).send(…)`: template-ine
171
182
  | `SEAL_PROVIDER_INVALID` | the provider has the wrong shape or was registered twice |
172
183
  | `SEAL_REQUIRED` | 415, a plain body on a sealed request (answered in plain text) |
173
184
  | `SEAL_BODY_REFUSED` | 400, a sealed body could not be opened (the reason is only in the warn log) |
185
+ | `SEAL_BUSY` | 503, the seal provider's replay nonce store is full of live nonces (fail closed, [D-0075](https://git.nyx-zone.com/dokebi/framework/-/blob/main/docs/decisions/D-0075-replay-capacity.md)); retryable, warn `SEAL_BODY_REFUSED` with `reason: capacity` |
174
186
  | `SEAL_BODY_NOT_JSON` | 400, the opened body is not JSON |
175
187
  | `SEAL_STREAM_UNSUPPORTED` | 500, JSON for a sealed request was sent as a stream (error log) |
176
188
  | `VALIDATION_FAILED` | 422, a refused body or query string schema, or `validationError()`; `fields` and `errors` in the body |
package/README.md CHANGED
@@ -1,4 +1,4 @@
1
- # @dokebi/web 0.4.0
1
+ # @dokebi/web 0.4.2
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
 
@@ -71,7 +71,7 @@ Plugins with an entry file are left out of the generated code's manifest depende
71
71
  web owns the **slot** that seals HTTP data of seal hosts (@dokebi/app `domains.<host>.seal: true`) and of `seal: true` routes. @dokebi/seal fills in the algorithm with `sealCodec(provider)` (this package never imports seal). See [D-0062](https://git.nyx-zone.com/dokebi/framework/-/blob/main/docs/decisions/D-0062-http-seal.md).
72
72
 
73
73
  - The decision (once per request): health → plain, route `seal: false` → plain, `seal: true` or `seal(request)` → sealed, a `sealExclude` prefix (`/` boundary) → plain, any `sealRequests(predicate)` true → sealed. `seal` becomes `config.dokebiSeal` whether given to `route()`, a Fastify `register` scope or a router `mount`.
74
- - Bodies of sealed requests: when the content type is the provider's `contentType` (`application/vnd.dokebi-seal`), the parser opens it and puts the JSON into `request.body` (drift, replay and tampering are 400, with the reason only in warn `SEAL_BODY_REFUSED`). A body that is neither sealed nor `multipart/form-data` gets `415 { error: 'SEAL_REQUIRED', fix }` **before the parser** (warn `SEAL_REQUIRED`, once per route every 10 seconds).
74
+ - Bodies of sealed requests: when the content type is the provider's `contentType` (`application/vnd.dokebi-seal`), the parser opens it and puts the JSON into `request.body` (drift, replay and tampering are 400, with the reason only in warn `SEAL_BODY_REFUSED`; a full replay nonce store is a retryable 503 `SEAL_BUSY`, D-0075). A body that is neither sealed nor `multipart/form-data` gets `415 { error: 'SEAL_REQUIRED', fix }` **before the parser** (warn `SEAL_REQUIRED`, once per route every 10 seconds).
75
75
  - JSON responses of sealed requests (`application/json`, `+json`, 4xx and 5xx included) are sealed in `onSend` and get `Content-Type: application/vnd.dokebi-seal` and `x-dokebi-sealed-path` (the path used for sealing; the final path after redirects). HTML, file and hijacked responses stay as they are. Streamed JSON cannot be sealed and becomes a 500 (plain text is never sent).
76
76
  - Code that writes its own body (the Inertia first page, SSE) gets `{ path, encode }` from `sealOf(request)`.
77
77
  - When something wants sealing (a registered decision or a sealed route) but no provider exists, start fails with `SEAL_PROVIDER_MISSING`.
package/dist/errors.d.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  import { DokebiError, type DokebiErrorOptions } from '@dokebi/core';
2
2
  import { type WebFieldError } from './responses.js';
3
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';
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_BUSY' | 'SEAL_BODY_NOT_JSON' | 'SEAL_STREAM_UNSUPPORTED' | 'VALIDATION_FAILED' | 'NOT_FOUND';
5
5
  /**
6
6
  * Errors of @dokebi/web; compare `code`, not the class (another installed copy may throw).
7
7
  * Request errors carry the HTTP `status` dokebi-web answers with, and a `hint` for the client.
package/dist/errors.js CHANGED
@@ -15,6 +15,7 @@ const FIX = {
15
15
  SEAL_PROVIDER_INVALID: 'Register one seal codec provider (the dokebi-seal plugin) with { contentType, forRequest }.',
16
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
17
  SEAL_BODY_REFUSED: 'Seal request bodies with @dokebi/seal for this host and path, once, within sealDriftMs of the server clock.',
18
+ 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): register @dokebi/websocket-hub with mode: cluster (Redis), or lower sealDriftMs.',
18
19
  SEAL_BODY_NOT_JSON: 'A sealed request body must be JSON text before sealing.',
19
20
  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
21
  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.',
@@ -25,6 +26,7 @@ const HINT = {
25
26
  FORM_BODY_TOO_MANY_FIELDS: 'The form has too many fields.',
26
27
  SEAL_REQUIRED: 'This address only accepts sealed requests. Reload the page and try again.',
27
28
  SEAL_BODY_REFUSED: 'The request could not be opened. Reload the page and try again.',
29
+ SEAL_BUSY: 'The server is busy. Try again in a moment.',
28
30
  SEAL_BODY_NOT_JSON: 'The request could not be read. Reload the page and try again.',
29
31
  VALIDATION_FAILED: VALIDATION_HINT,
30
32
  NOT_FOUND: 'The page or resource does not exist.',
@@ -34,6 +36,7 @@ const STATUS = {
34
36
  FORM_BODY_TOO_MANY_FIELDS: 413,
35
37
  SEAL_REQUIRED: 415,
36
38
  SEAL_BODY_REFUSED: 400,
39
+ SEAL_BUSY: 503,
37
40
  SEAL_BODY_NOT_JSON: 400,
38
41
  SEAL_STREAM_UNSUPPORTED: 500,
39
42
  VALIDATION_FAILED: 422,
@@ -0,0 +1,35 @@
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) and the
19
+ * path stays on it (`//other.host/…`, `/\other.host` and their encoded forms are refused, so the
20
+ * answer never reads as another host). Otherwise `fallback` for a POST, PUT, PATCH or DELETE
21
+ * (template-inertia passes `/`), or undefined. A GET or HEAD whose referer is missing or is itself has no way back: a redirect to
22
+ * itself would be refused again, forever.
23
+ */
24
+ export declare function formBackTarget(request: WebFormRequest, host: string, fallback?: string): string | undefined;
25
+ /**
26
+ * The old input of a refused form (D-0074 §3): the body's top-level strings, numbers, booleans
27
+ * and nulls, without password-like fields (`password`, `token`, `secret`, `api_key`, `card`,
28
+ * `cvc`, `otp`, `pin`…); undefined when nothing is left or it is larger than 8 KB as JSON.
29
+ */
30
+ export declare function formOldInput(body: unknown): Record<string, WebFormValue> | undefined;
31
+ /**
32
+ * The `errors` (`{ field: message }`) of a validation answer — a refused route schema or
33
+ * `validationError()` (422 `VALIDATION_FAILED`) — or undefined for any other error body.
34
+ */
35
+ export declare function formFieldErrors(body: WebErrorBody): Record<string, string> | undefined;
package/dist/forms.js ADDED
@@ -0,0 +1,100 @@
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) and the
23
+ * path stays on it (`//other.host/…`, `/\other.host` and their encoded forms are refused, so the
24
+ * answer never reads as another host). Otherwise `fallback` for a POST, PUT, PATCH or DELETE
25
+ * (template-inertia passes `/`), or undefined. A GET or HEAD whose referer is missing or is itself has no way back: a redirect to
26
+ * itself would be refused again, forever.
27
+ */
28
+ export function formBackTarget(request, host, fallback) {
29
+ const read = ['GET', 'HEAD'].includes(request.method);
30
+ const value = request.headers.referer;
31
+ const referer = Array.isArray(value) ? value[0] : value;
32
+ if (typeof referer === 'string' && referer.length <= REFERER_MAX && URL.canParse(referer)) {
33
+ const url = new URL(referer);
34
+ if ((url.protocol === 'http:' || url.protocol === 'https:') &&
35
+ url.host.toLowerCase() === host.toLowerCase()) {
36
+ const target = url.pathname + url.search;
37
+ if (sameOrigin(target, url.origin) && !(read && target === request.url))
38
+ return target;
39
+ }
40
+ }
41
+ return read ? undefined : fallback;
42
+ }
43
+ /**
44
+ * A path a browser or a proxy could read as another host: `//host` (scheme-relative), `/\host`
45
+ * and their percent-encoded forms (`/%2F…`, `/%5C…`). The URL parser turns `\` and `/./` into
46
+ * `/`, so a same-host Referer such as `https://app.test//outside.test/x` has such a path.
47
+ */
48
+ const HOST_LIKE_PATH = /^\/(?:[/\\]|%2f|%5c)/i;
49
+ /**
50
+ * True when `target` (a path and query of a Referer whose origin is `origin`) is a redirect
51
+ * target that stays on `origin`: it is not host-like and resolves against `origin` to `origin`
52
+ * with the same path and query (ISSUE-0006 A02, an open redirect through `//host` paths).
53
+ */
54
+ function sameOrigin(target, origin) {
55
+ if (!target.startsWith('/') || HOST_LIKE_PATH.test(target))
56
+ return false;
57
+ const resolved = new URL(target, origin);
58
+ return resolved.origin === origin && resolved.pathname + resolved.search === target;
59
+ }
60
+ /**
61
+ * The old input of a refused form (D-0074 §3): the body's top-level strings, numbers, booleans
62
+ * and nulls, without password-like fields (`password`, `token`, `secret`, `api_key`, `card`,
63
+ * `cvc`, `otp`, `pin`…); undefined when nothing is left or it is larger than 8 KB as JSON.
64
+ */
65
+ export function formOldInput(body) {
66
+ if (body === null || typeof body !== 'object' || Array.isArray(body))
67
+ return undefined;
68
+ const old = {};
69
+ let kept = 0;
70
+ for (const [key, value] of Object.entries(body)) {
71
+ if (key === '__proto__' || SECRET_FIELD.test(key))
72
+ continue;
73
+ if (value === null ||
74
+ typeof value === 'boolean' ||
75
+ (typeof value === 'number' && Number.isFinite(value)) ||
76
+ typeof value === 'string') {
77
+ old[key] = value;
78
+ kept++;
79
+ }
80
+ }
81
+ if (!kept || JSON.stringify(old).length > OLD_MAX)
82
+ return undefined;
83
+ return old;
84
+ }
85
+ /**
86
+ * The `errors` (`{ field: message }`) of a validation answer — a refused route schema or
87
+ * `validationError()` (422 `VALIDATION_FAILED`) — or undefined for any other error body.
88
+ */
89
+ export function formFieldErrors(body) {
90
+ if (body.error !== 'VALIDATION_FAILED')
91
+ return undefined;
92
+ const errors = body.errors;
93
+ if (errors === null || typeof errors !== 'object' || Array.isArray(errors))
94
+ return undefined;
95
+ const result = {};
96
+ for (const [field, message] of Object.entries(errors))
97
+ if (field !== '__proto__' && typeof message === 'string')
98
+ result[field] = message;
99
+ return result;
100
+ }
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.2',
1068
1069
  core: '^0.4.0',
1069
1070
  options: declaration,
1070
1071
  entry: (input) => new WebEntryInput(input),
package/dist/seal.js CHANGED
@@ -219,6 +219,12 @@ export class WebSealing {
219
219
  ...(repeated ? { repeated } : {}),
220
220
  });
221
221
  this.#plain.add(request);
222
+ // A full replay nonce store (D-0075, fail closed) is the server's state, not the body's:
223
+ // 503, so the client may retry. It says nothing about drift or replay.
224
+ if (reason === 'capacity')
225
+ throw new WebError('SEAL_BUSY', 'Sealed request body refused: server busy', {
226
+ cause: error,
227
+ });
222
228
  throw new WebError('SEAL_BODY_REFUSED', 'Sealed request body refused', { cause: error });
223
229
  }
224
230
  if (plain === '')
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dokebi/web",
3
- "version": "0.4.0",
3
+ "version": "0.4.2",
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",