@dokebi/web 0.4.2 → 0.4.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. package/AI.md +248 -39
  2. package/README.md +31 -10
  3. package/dist/app-routes.d.ts +20 -0
  4. package/dist/app-routes.js +137 -0
  5. package/dist/before-hijack.d.ts +24 -0
  6. package/dist/before-hijack.js +73 -0
  7. package/dist/body.d.ts +14 -0
  8. package/dist/body.js +30 -0
  9. package/dist/cluster-ready.d.ts +67 -0
  10. package/dist/cluster-ready.js +123 -0
  11. package/dist/compilers.d.ts +16 -0
  12. package/dist/compilers.js +25 -0
  13. package/dist/compression.d.ts +40 -0
  14. package/dist/compression.js +435 -0
  15. package/dist/connections.d.ts +44 -0
  16. package/dist/connections.js +282 -0
  17. package/dist/define-errors.d.ts +76 -0
  18. package/dist/define-errors.js +161 -0
  19. package/dist/describe.d.ts +37 -0
  20. package/dist/describe.js +96 -0
  21. package/dist/errors.d.ts +1 -1
  22. package/dist/errors.js +24 -3
  23. package/dist/forms.d.ts +23 -7
  24. package/dist/forms.js +53 -13
  25. package/dist/index.d.ts +134 -4
  26. package/dist/index.js +1518 -91
  27. package/dist/options.d.ts +56 -0
  28. package/dist/options.js +320 -1
  29. package/dist/points.d.ts +159 -0
  30. package/dist/points.js +162 -1
  31. package/dist/responses.d.ts +31 -6
  32. package/dist/responses.js +68 -6
  33. package/dist/route-config.d.ts +38 -0
  34. package/dist/route-config.js +222 -0
  35. package/dist/route-hooks.d.ts +75 -0
  36. package/dist/route-hooks.js +118 -0
  37. package/dist/route-table.d.ts +55 -0
  38. package/dist/route-table.js +142 -0
  39. package/dist/seal.d.ts +49 -1
  40. package/dist/seal.js +259 -24
  41. package/dist/security-headers.d.ts +121 -0
  42. package/dist/security-headers.js +298 -0
  43. package/dist/transient-log.d.ts +42 -0
  44. package/dist/transient-log.js +95 -0
  45. package/options.schema.json +488 -1
  46. package/package.json +22 -9
package/AI.md CHANGED
@@ -1,4 +1,4 @@
1
- # AI guide — @dokebi/web 0.4.2
1
+ # AI guide — @dokebi/web
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
 
@@ -17,12 +17,27 @@ dokebi-web:
17
17
  maxBodyBytes: 1048576 # 1 B..64 MiB (named bodyLimit before 0.4.0)
18
18
  requestTimeoutMs: 30000 # limit for receiving a request, not for running the work (named requestTimeout before 0.4.0)
19
19
  healthRoutes: { live: /health/live, ready: /health/ready } # false registers none
20
+ routeIds: { healthLive: ops.live } # D-0142: route ids of the health routes (default web.healthLive, web.healthReady)
20
21
  trustProxy: [127.0.0.1, "::1"] # exact IPs only, up to 64
21
22
  sealDriftMs: 60000 # seal hosts (D-0062): allowed ts drift of sealed bodies
22
23
  sealExclude: [/webhooks] # path prefixes that stay plain on seal hosts
23
24
  formBody: true # HTML forms (application/x-www-form-urlencoded) into request.body; default false
24
25
  formMaxFields: 1000 # field limit per form, 1..10000; above it 413 FORM_BODY_TOO_MANY_FIELDS
25
26
  developmentErrors: true # outside production (NODE_ENV=production) error bodies also carry fix and details; false always answers like production
27
+ transientLogWindowMs: 10000 # retryable 503s: the first of each code and route per window in full, the rest counted (D-0113)
28
+ transientLogMaxKeys: 256 # code and route pairs one window logs in full
29
+ transientLogLevel: error # or warn: level of those records and their summaries (500s stay at error)
30
+ compression: # D-0125: br or gzip by Accept-Encoding (on by default)
31
+ enabled: true # false: a front proxy compresses
32
+ thresholdBytes: 1024 # smaller bodies go out as they are
33
+ brotliQuality: 4 # 0..11
34
+ gzipLevel: 6 # 1..9
35
+ encodings: [br, gzip] # offered codings; the first wins a q-value tie
36
+ securityHeaders: # D-0149: on by default (§2.4)
37
+ contentSecurityPolicy: { directives: { img-src: ["'self'", https://cdn.example.com] } } # changes to the default policy
38
+ strictTransportSecurity: { maxAgeSec: 31536000 } # HTTPS answers only
39
+ overload: # D-0150: shed load before the event loop stalls (§2.5)
40
+ maxEventLoopDelayMs: 200 # default; 0 turns a check off
26
41
  ```
27
42
 
28
43
  | Key | Type | Default | Description |
@@ -31,35 +46,77 @@ dokebi-web:
31
46
  | `port` | integer | 0 | 0..65535; 0 picks an ephemeral port |
32
47
  | `maxBodyBytes` | integer | 1048576 | request body limit, 1 B..64 MiB |
33
48
  | `bodyLimit` | integer | — | deprecated name of `maxBodyBytes` (D-0071): warns `OPTION_DEPRECATED`; setting both is `INVALID_OPTIONS` |
34
- | `requestTimeoutMs` | integer | 30000 | time to receive a request, 1..2147483647 ms; not a limit on the work |
49
+ | `maxRouteBodyBytes` | integer 1..1073741824 | 67108864 | the largest `bodyLimit` one route may declare for itself (64 MiB; at least `maxBodyBytes`); a larger one fails the start with `INVALID_ROUTE` ([D-0122](https://git.nyx-zone.com/dokebi/framework/-/blob/main/docs/decisions/D-0122-studio-terminal-needs.md), below) |
50
+ | `linger.ms` | integer | 5000 | after an answer sent before the request body was read (an early 403, 413 or 415), how long the connection still reads and drops what the client keeps sending, so it reads the answer instead of a connection reset (lingering close, as nginx's `lingering_close`); 0..60000, 0 closes at once. HTTP/1 only: on HTTP/2 the answered stream ends by itself and its session stays (no `connection` header is set there, RFC 9113 §8.2.2) |
51
+ | `linger.maxBytes` | integer | 16777216 | at most this many bytes of such a body are read and dropped; past it the connection closes at once |
52
+ | `binaryBody` | boolean | false | parse `application/octet-stream` bodies into `request.body` as a `Buffer`, within the route's `bodyLimit` or `maxBodyBytes` (D-0122); off: such a request gets 415 as before |
53
+ | `requestTimeoutMs` | integer | 30000 | time to receive a request, 1..2147483647 ms; not a limit on the work. A body that has not arrived this long after its headers is answered **408 `REQUEST_TIMEOUT`** (the connection closes; over HTTP/2 the stream ends with RST_STREAM NO_ERROR after the answer; a reader still waiting for it, such as a multipart file stream, fails), whether a parser or the handler reads it, over HTTP/1 and HTTP/2 (with or without Content-Length). A route that takes long uploads sets its own: `config: { requestTimeoutMs: 600000 }`. The headers stay under Node's own check (every 30 s, a bare 408): at start web sets its `headersTimeout` to the smaller of `requestTimeoutMs` and Node's 60 s, and its whole-request bound past the longest body time, so a route's own longer time is never cut by Node (debug `Web request timeouts`) |
35
54
  | `requestTimeout` | integer | — | deprecated name of `requestTimeoutMs` (D-0071) |
36
55
  | `healthRoutes` | `{ live?, ready? }` or `false` | `{ live: /health/live, ready: /health/ready }` | missing keys use the default path; paths start with `/`, have no `?`, `#` or spaces, and differ; `false` registers neither |
37
- | `trustProxy` | string[] | `[]` | exact IPv4/IPv6 proxy addresses (up to 64) whose `X-Forwarded-*` headers are trusted |
56
+ | `routeIds` | `{ healthLive?, healthReady? }` | — (`web.healthLive`, `web.healthReady`) | the route ids of the health routes ([D-0142](https://git.nyx-zone.com/dokebi/framework/-/blob/main/docs/decisions/D-0142-plugin-route-ids.md), §2.2): each value replaces one default id, by the rule of `config.id`; other keys are refused |
57
+ | `trustProxy` | string[] | `[]` | exact IPv4/IPv6 proxy addresses (up to 64) whose `X-Forwarded-*` headers are trusted. A tunnel or proxy on this machine (Cloudflare Tunnel, ngrok): `[127.0.0.1, "::1"]` (§2.6); without it a forwarded host is ignored and warned `WEB_FORWARDED_HOST_IGNORED` |
38
58
  | `sealDriftMs` | integer | 60000 | allowed timestamp drift of sealed bodies, 1000..600000; nonces are kept twice as long |
39
59
  | `sealExclude` | string[] | `[]` | path prefixes (with a `/` boundary) that stay plain on seal hosts, up to 64 |
60
+ | `unknownFields` | `remove` or `refuse` | `remove` | fields a route schema does not allow (`additionalProperties: false`) in a body, query string or params: `remove` drops them silently before the handler (Fastify's Ajv `removeAdditional`, the request is accepted); `refuse` answers an extra body or query field **422 `VALIDATION_FAILED`** with each one in `fields` (`{ field: 'extra', message: 'is not allowed' }`, a query field as `query.extra`), and an extra path parameter 400 `INVALID_REQUEST` like every refused `params` schema (the address is wrong, not a field) |
40
61
  | `formBody` | boolean | false | parse `application/x-www-form-urlencoded` bodies |
41
62
  | `formMaxFields` | integer | 1000 | field limit per form, 1..10000 |
42
- | `developmentErrors` | boolean | true | outside production, error bodies carry `fix` and `details`; false answers like production everywhere |
43
-
44
- **To accept HTML forms set `formBody: true`** (off by default, D-0068). While off, a form request gets 415 `{ error: 'FORM_BODY_DISABLED', fix }` before the handler, and the `fix` and a warn log (`HTTP form body refused`, `code: FORM_BODY_DISABLED`, once per route every 10 seconds) name this option. When on, the body is decoded with `node:querystring` into `request.body`: an object without a prototype, repeated names become arrays, `+` and `%XX` are decoded, and `maxBodyBytes` applies. It is off by default because a form POST is a request other sites can send without a preflight (a CORS simple request): cookie-authenticated apps keep the session cookie `SameSite=Lax` (the @dokebi/session default) or `Strict`, or check a CSRF token. Seal hosts still refuse forms with 415 `SEAL_REQUIRED` when it is on (§3.1).
63
+ | `developmentErrors` (reloadable) | boolean | true | outside production, error bodies carry `fix` and `details`; false answers like production everywhere |
64
+ | `transientLogWindowMs` (reloadable) | integer | 10000 | window of the retryable 503 log, 1000..3600000 ms ([D-0113](https://git.nyx-zone.com/dokebi/framework/-/blob/main/docs/decisions/D-0113-overload-log-and-storage-wait.md), below) |
65
+ | `transientLogMaxKeys` (reloadable) | integer | 256 | error code and route pairs one window logs in full, 1..65536; past it new pairs are only counted (`overflow: true`) |
66
+ | `transientLogLevel` (reloadable) | `error` or `warn` | `error` | level of the retryable 503 records and their `WEB_TRANSIENT_REPEATED` summaries; 500s stay at `error` |
67
+ | `logRepeatWindowMs` | integer 1000..3600000 | `10000` | window of every other repeated log (D-0047): a 500 of the same route, error name and code, a refused form body, a refused or failed sealed body, a failed response hook, translator or responder is logged in full once per window, and the next record says how many were held back (`repeated`). Raise it when a known defect floods the log; the counts stay exact |
68
+ | `formOldInputMaxChars` | integer 256..1048576 | `8192` | the largest old input (as JSON text) a refused form goes back with; a larger body goes back without it, so the user retypes everything. Raise it for long text areas (the old input travels in the session flash: keep it below the session store's `maxBytes`) |
69
+ | `formRefererMaxLength` | integer 256..65536 | `4096` | the longest `Referer` a refused form goes back to; a longer one is not followed (a POST goes to its fallback). Raise it for pages with long query strings |
70
+ | `drainGraceMs` (reloadable) | integer 0..60000 | `100` | how long a draining node:cluster worker stays up after it stops listening, so a connection the primary was already handing it is answered "not accepted" and passed on (D-0036). Raise it on a loaded host where the primary is slow to notice |
71
+ | `unavailableRetryAfterMs` (reloadable) | integer 1000..600000 | `5000` | `Retry-After` (rounded up to seconds) of the 503 `SERVICE_UNAVAILABLE` refusals: before the app is ready, while a required health check is not (a Redis or database outage makes every worker unready) and while it drains; the default is the 5 s of a lost Redis connection (dokebi-redis `unavailableRetryAfterMs`), the usual cause. The `unavailable` hook gets it in `answer.headers` and decides its own |
72
+ | `drainIdleMs` (reloadable) | integer 0..60000 | `2000` | how long a draining node:cluster worker keeps its idle keep-alive connections open (§4): a request a client sends on one is served with `Connection: close` (it was lost to a closed socket before, `ECONNRESET`, and a POST is never resent); the drain goes on as soon as none is left, the ones still idle then are closed. Never past the drain deadline: the wait ends 100 ms before core's `drainDeadline` (`shutdown.drainTimeoutMs`, 20 s by default), so it never causes `DRAIN_TIMEOUT`. Raise it for clients that pause longer between requests |
73
+ | `sealRetryAfterMs` | integer 1..60000 | `1000` | `Retry-After` of the 503s `SEAL_BUSY` and `SEAL_NONCE_STORE_UNAVAILABLE` (and of `SEAL_NONCES_LOST`), unless the seal codec names its own wait (`retryAfterMs`) |
74
+ | `compression.enabled` | boolean | `true` | compress responses with br or gzip when the client accepts it ([D-0125](https://git.nyx-zone.com/dokebi/framework/-/blob/main/docs/decisions/D-0125-response-compression.md), below); `false` sends every body as the handler wrote it (a front proxy that compresses) |
75
+ | `compression.thresholdBytes` | integer 0..1048576 | `1024` | the smallest body that is compressed; a smaller one, or a stream whose `Content-Length` is smaller, goes out as it is (and without `Vary`) |
76
+ | `compression.brotliQuality` | integer 0..11 | `4` | brotli quality; 4 is about gzip 6's size at under half its CPU. 10 and 11 are far too slow for answers made per request |
77
+ | `compression.gzipLevel` | integer 1..9 | `6` | gzip level |
78
+ | `compression.encodings` | `br` and/or `gzip`, 1..2, unique | `[br, gzip]` | the codings offered, in the order that wins when the client gives them the same q-value |
79
+ | `compression.maxBufferBytes` | integer 1024..67108864 | `1048576` | the largest buffered body compressed in one call and sent with `Content-Length`; a larger one is compressed as a stream (chunked), so its compressed copy is never held whole |
80
+ | `compression.maxPending` | integer 1..4096 | `64` | compressions under way at once (one-shot jobs and streams); past it answers go out uncompressed and warn `WEB_COMPRESSION_BUSY` (once per `logRepeatWindowMs`) instead of queueing more CPU work |
81
+ | `securityHeaders.enabled` | boolean | `true` | security headers on every answer ([D-0149](https://git.nyx-zone.com/dokebi/framework/-/blob/main/docs/decisions/D-0149-security-headers.md), §2.4); `false` sends none (a front proxy sets them) |
82
+ | `securityHeaders.contentSecurityPolicy` (reloadable) | `{ directives?, reportOnly? }` or `false` | `{ directives: {}, reportOnly: false }` | the CSP of HTML documents: `directives` changes the default policy by directive (a list of sources replaces it, `[]` is a directive without sources, `false` removes it); `reportOnly: true` sends `Content-Security-Policy-Report-Only`; `false` sends none |
83
+ | `securityHeaders.strictTransportSecurity` (reloadable) | `{ maxAgeSec?, includeSubDomains?, preload? }` or `false` | `{ maxAgeSec: 31536000, includeSubDomains: true, preload: false }` | HSTS on answers to HTTPS requests only (TLS here, or `X-Forwarded-Proto: https` from a `trustProxy` address) |
84
+ | `securityHeaders.frameOptions` (reloadable) | `DENY` · `SAMEORIGIN` · `false` | `SAMEORIGIN` | `X-Frame-Options` of HTML documents |
85
+ | `securityHeaders.referrerPolicy` (reloadable) | a Referrer-Policy value or `false` | `strict-origin-when-cross-origin` | `Referrer-Policy` of HTML documents |
86
+ | `securityHeaders.crossOriginOpenerPolicy` (reloadable) | `same-origin` · `same-origin-allow-popups` · `unsafe-none` · `false` | `same-origin-allow-popups` | `Cross-Origin-Opener-Policy` of HTML documents over HTTPS (a payment or sign-in popup the page opens stays connected) |
87
+ | `securityHeaders.crossOriginResourcePolicy` (reloadable) | `same-origin` · `same-site` · `cross-origin` · `false` | `same-site` | `Cross-Origin-Resource-Policy` of HTML documents |
88
+ | `securityHeaders.contentTypeOptions` (reloadable) | boolean | `true` | `X-Content-Type-Options: nosniff` on every answer |
89
+ | `overload.enabled` | boolean | `true` | shed load ([D-0150](https://git.nyx-zone.com/dokebi/framework/-/blob/main/docs/decisions/D-0150-overload-protection.md), §2.5): above a limit below, requests get 503 `OVERLOADED` with `Retry-After` before any handler runs; `false`: never |
90
+ | `overload.maxEventLoopDelayMs` (reloadable) | integer 0..600000 | `200` | mean event loop delay of the last sample above which requests are refused (a saturated but healthy loop measured 11 ms (at most 24 ms)); `0`: not checked |
91
+ | `overload.maxEventLoopUtilization` (reloadable) | number 0..1 | `0` | event loop utilization of the last sample above which requests are refused; `0`: not checked |
92
+ | `overload.maxHeapUsedBytes` (reloadable) | integer | `0` | V8 heap used above which requests are refused; `0`: not checked |
93
+ | `overload.maxRssBytes` (reloadable) | integer | `0` | resident set size above which requests are refused; `0`: not checked |
94
+ | `overload.sampleIntervalMs` | integer 10..60000 | `1000` | how often the event loop and memory are sampled |
95
+ | `overload.retryAfterMs` (reloadable) | integer 1000..600000 | `2000` | `Retry-After` of the 503 answers (rounded up to seconds) |
96
+
97
+ **To accept HTML forms set `formBody: true`** (off by default, D-0068). While off, a form request gets 415 `{ error: 'FORM_BODY_DISABLED', fix }` before the handler, and the `fix` and a warn log (`HTTP form body refused`, `code: FORM_BODY_DISABLED`, once per route every 10 seconds) name this option. When on, the body is decoded with `node:querystring` into `request.body`: an object without a prototype, repeated names become arrays, `+` and `%XX` are decoded, and `maxBodyBytes` applies. It is off by default because a form POST is a request other sites can send without a preflight (a CORS simple request): cookie-authenticated apps keep the session cookie `SameSite=Lax` (the @dokebi/session default) or `Strict`, or check a CSRF token. Seal hosts still refuse a plain form body with 415 `SEAL_REQUIRED` when it is on; their forms are sent sealed by `@dokebi/seal/forms` and are form bodies too (`formBody` and `formMaxFields` apply, §3.1).
98
+
99
+ **Per-route body limits and binary bodies** (D-0122). A route may declare its own `bodyLimit` (bytes, Fastify's route option) above or below `maxBodyBytes`, up to `maxRouteBodyBytes`: `web.route({ method: 'POST', url: '/term/outputs/chunks', bodyLimit: 4 * 1024 * 1024, handler })` (also through @dokebi/router route options). Exceeding it is 413 **early**: a `Content-Length` over the limit is refused before a byte is read, and a body without one (chunked) is cut off as soon as it passes the limit, so at most the limit is buffered; the connection is closed after the 413 (a client still sending may see that as a reset). With `binaryBody: true` an `application/octet-stream` body arrives as one `Buffer` in `request.body` (read through the same limit); give raw upload routes a `bodyLimit` that fits them and keep `maxBodyBytes` small for the rest. For files larger than memory should hold, stream them with `receiveUpload` of @dokebi/storage instead. Seal hosts refuse a plain binary body with 415 `SEAL_REQUIRED` unless the route sets `seal: false` (or its path is in `sealExclude`). It is off by default so that an app which registers its own `application/octet-stream` parser keeps it (Fastify refuses a second parser for one type).
100
+
101
+ **Response compression** (0.4.3, D-0125). A response body is compressed with `br` or `gzip` when all of these hold: the request's `Accept-Encoding` accepts one of `compression.encodings` (q-values, `*`, `identity` and `x-gzip` are read as RFC 9110 says; equal q-values go to the first of `encodings`; no header means identity); the body is at least `thresholdBytes`; its type is text (`text/*` except `text/event-stream`), JSON (`application/json`, `*+json`: Inertia visits and API answers), JavaScript, XML (`*+xml`), SVG or wasm; the status is not 1xx, 204, 206 or 304; and nothing opts out: a `Content-Encoding` already set, `Cache-Control: no-transform`, a `Content-Range`, the route's `config: { compress: false }`, or `skipCompression(reply)` for one response. Images other than SVG, archives, video, fonts, `application/octet-stream` (storage downloads) and sealed bodies (`application/vnd.dokebi-seal`, a ciphertext) are never compressed. A compressed answer gets `Content-Encoding`, `Vary: Accept-Encoding` (added to an existing `Vary`), a `Content-Length` of the compressed bytes (buffered bodies) or none (streams, HEAD), a strong `ETag` turned weak (`W/"…"`) and no `Accept-Ranges`. A candidate sent as identity (the client accepts no coding) still gets `Vary: Accept-Encoding`. HEAD gets the headers a GET would get and no body. Streams (`reply.send(readable)`) are piped through a zlib stream with backpressure and flushed per chunk, so a slow stream's parts arrive as they are written. SSE is never compressed: @dokebi/sse writes its stream itself (hijacked), and a `text/event-stream` sent through `reply.send` is left alone, since compression would hold events back until a flush. The work runs on the libuv thread pool (zlib's asynchronous calls), not the event loop; while the server drains, or when `maxPending` compressions are under way, answers go out uncompressed. Compression is the last `onSend` step of every route (after seal, session, i18n and the app's own hooks), so it sees the final body; an unknown route's answer (an app's 404 page) is compressed too. A failed compression logs error `WEB_COMPRESSION_FAILED` (`method`, `route`, `encoding`, the full `error`; once per `logRepeatWindowMs`): a buffered body then goes out uncompressed, a failing stream is cut. Turn it off (`compression.enabled: false`) when a front proxy compresses.
45
102
 
46
103
  `dokebi verify` starts the app with `DOKEBI_VERIFY_TOKEN` (random), and only when that variable is set does this plugin add the header `x-dokebi-verify: <token>` to every response. verify counts only answers with the right header, so another app on the same port is never mistaken for yours (D-0065 §11). Without the variable (normal runs and production) the hook does not exist. A malformed value is ignored with warn `VERIFY_TOKEN_INVALID`.
47
104
 
48
105
  `dokebi start` gives the app a random per-start `DOKEBI_INSTANCE_TOKEN` (D-0073). While that variable is set, a request carrying a challenge in the header `x-dokebi-instance` (16–128 characters of `A-Za-z0-9_-`) is answered at once with `204` and `x-dokebi-instance: <base64url HMAC-SHA256(token, challenge)>`; no route or app code runs, and the token itself never goes on the wire. Requests without that header are served as usual. `dokebi stop` and `status` use it to prove a recorded pid is this app where `ps` is blocked. A malformed token is ignored with warn `INSTANCE_TOKEN_INVALID`; without the variable no hook exists.
49
106
 
50
- Fastify construction options such as HTTPS, HTTP/2, `serverFactory` or the query-string parser are not dokebi.yaml options; give them through the extension hook `fastifyOptions` (§8). Usually TLS ends at a front proxy.
107
+ Fastify construction options such as HTTPS, HTTP/2, `serverFactory` or the query-string parser are not dokebi.yaml options; give them through the extension hook `fastifyOptions` (§8). HTTP/2 works over TLS (`https` with `http2: true`, `allowHTTP1` too) and as h2c (`http2: true` alone; Fastify refuses `forceCloseConnections: 'idle'` there, so dokebi-web sets it to `false` for h2c and ends connections itself). Usually TLS ends at a front proxy. A `serverFactory` returns a server Fastify does not configure: it keeps Node's own `keepAliveTimeout` (5 s, not Fastify's 72 s, so a front proxy that keeps connections longer gets resets) and `requestTimeout` (300 s instead of `requestTimeoutMs`; web's own body timer still applies `requestTimeoutMs`). Set those on the server you create, and only use a factory for a server Fastify cannot make; response headers belong in handlers, hooks or `securityHeaders` (§2.4), never in a factory (R8 Codex T3 wrapped every request in its own `http.createServer` to add two headers).
51
108
 
52
109
  ## 2. Usage
53
110
 
54
111
  Usually @dokebi/app, module and router build routes on top of web. To use it directly:
55
112
 
56
113
  ```ts snippet
57
- import cors from '@fastify/cors';
114
+ import multipart from '@fastify/multipart';
58
115
  import { dependency as web } from '@dokebi/web';
59
116
  // put web into dependencies/requires, then in setup:
60
117
  const http = context.getDependency(web);
61
118
  http.route({ method: 'GET', url: '/ping', handler: async () => ({ ok: true }) });
62
- http.register(cors, { origin: ['https://a.com'] }); // Fastify plugin (options required; {} when none)
119
+ http.register(multipart, {}); // a Fastify plugin (options required; {} when none). CORS is @dokebi/cors
63
120
  http.route({ method: 'POST', url: '/import', handler: async (request, reply) => {
64
121
  void http.track(() => importLater(request.body)); // work that outlives the response joins the drain via track
65
122
  return reply.code(202).send({ accepted: true });
@@ -72,31 +129,125 @@ http.route({ method: 'POST', url: '/import', handler: async (request, reply) =>
72
129
  | `register(plugin, options)` | a Fastify async or callback plugin (scope, decorators and hooks kept). Setup only |
73
130
  | `constraint(strategy)` | adds a route constraint strategy (`dokebiApp` of @dokebi/app). Setup only, before the routes that use it |
74
131
  | `track(() => work)` | makes drain wait for work whose lifetime differs from the HTTP response |
75
- | `requestHost(request)` | the request host under the trusted-proxy rules (lower case, port kept) |
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
- | `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 |
132
+ | `requestHost(request)` | the request host under the trusted-proxy rules (lower case, port kept): `X-Forwarded-Host` from a `trustProxy` address, else `Host`, over HTTP/2 `:authority` (an HTTP/2 client sends no Host) |
133
+ | `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). An option of the route itself, beside `method` and `url` — **not** `config.seal` (the per-route switches `overload`, `readiness`, `compress` live in `config`; `seal` does not): `config: { seal: false }` fails the start with `INVALID_ROUTE_CONFIG` and says where it belongs |
134
+ | `route({ ..., app })` | binds the route to apps of @dokebi/app (§2.1, D-0132): `app: 'mcp'` or `app: ['studio', 'admin']`; only those apps' hosts answer it, every other host gets the 404 of an unknown route. Unset: every host |
135
+ | `appRouting(routing)` · `apps` | the app routing slot (D-0132): @dokebi/app fills it in its setup (constraint, app names, host map; `WebAppRouting`); `apps` is it, or undefined without @dokebi/app. Final at boot, so plugins read it inside their `register()` scopes. You do not call `appRouting` yourself |
136
+ | `requestApps(resolver)` · `appOf(request)` · `resolvesApps` | which app a request belongs to (D-0181): @dokebi/app registers the resolver (the app of the host, setup only); a plugin that answers per app (dokebi-i18n's app layers) asks `appOf(request)` (undefined: no app, an unknown host, or no resolver). `resolvesApps`: a resolver is registered (final after every setup) |
137
+ | `sealCodec(provider)` · `sealRequests(predicate)` · `sealOf(request)` · `sealing` · `sealWanted` | the HTTP seal slot (D-0062). @dokebi/seal provides the codec and @dokebi/app registers the decision; you rarely call them yourself. `sealing`: a codec is registered; `sealWanted` (0.4.3): a predicate or a route with `seal` asks for sealing (final after every setup) |
138
+ | `formLimits` | `{ oldInputMaxChars, refererMaxLength }` of these options (`formOldInputMaxChars`, `formRefererMaxLength`, D-0114): pass it to `formOldInput` and `formBackTarget` (@dokebi/app and template-inertia do) |
78
139
  | `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 |
140
+ | `routeConfig({ key, plugin, check, routes? })` | declares a route `config` key this plugin reads (D-0076 §5, for example `auth`, `csrf`). Setup only. At start every route's value goes through `check(value) → string \| undefined` (a sentence when wrong), and a key in another case or at most two edits away from a declared key (`csfr`) is a likely typo; either fails the start with `INVALID_ROUTE_CONFIG` (`details.problems`, error log `WEB_ROUTE_CONFIG_INVALID`). When nothing is wrong, the optional `routes(list)` is called once with every route that sets the key (`{ method, url, value }`, `WebRouteConfigUse`; the HEAD twin of a GET left out), so the plugin can report them (@dokebi/csrf logs the routes with `csrf: false`). The plugin reads the value per request from `request.routeOptions.config[key]`. Keys of other Fastify plugins (`rateLimit`) are left alone |
141
+ | `routeHook({ plugin, route })` | asks `route(info)` once per route what to add to that route only (D-0076 §3.8; dokebi-auth's route protection). `info` is `{ method, url, config, constraints, configFixed }` (`constraints.dokebiApp` names a dokebi-app app); return `undefined` (the route is left untouched: no cost per request) or `{ preValidation?, onResponse?, completed?, data? }`: an async preValidation hook that runs for that route only (after the body is parsed, before schema validation), a response observer (`onResponse` or the cheaper `completed`, below), and values under symbol keys merged into the route's config (`request.routeOptions.config[symbol]`). Routes added before the call are offered when it is made (`configFixed: true`: their config was already copied, so only `preValidation`/`onResponse`/`completed`); health routes are never offered. Setup only; a malformed result is `INVALID_ARGUMENT` |
142
+ | `contentSecurityPolicy({ plugin, directives })` | adds CSP sources for the pages of a plugin (D-0149, §2.4): `{ plugin: 'dokebi-seal', directives: { 'script-src': ["'wasm-unsafe-eval'"] } }`, appended to each directive. Setup only; a malformed one is `INVALID_ARGUMENT` |
143
+ | `route({ ..., config: { securityHeaders } })` · `route({ ..., config: { overload: false } })` · `route({ ..., config: { readiness: false } })` | per route: `securityHeaders: false` or the settings to change (D-0149, §2.4); `overload: false` serves the route while the server sheds load (D-0150, §2.5); `readiness: false` serves it while a required dependency is down and while the app drains (§3). Checked at start (`INVALID_ROUTE_CONFIG`) |
144
+ | `route({ ..., config: { requestTimeoutMs } })` | this route's time to receive its body after the headers, in whole ms (1..2147483647), instead of the `requestTimeoutMs` option: give upload routes the time their largest file needs on a slow link. Checked at start (`INVALID_ROUTE_CONFIG`); past it 408 `REQUEST_TIMEOUT` (`data.timeoutMs`) |
145
+ | `route({ ..., config: { compress: false } })` · `skipCompression(reply)` | keep a route's answers, or one response, uncompressed (D-0125): a page that reflects request input next to a secret of its own (§7, BREACH). `compress` must be a boolean (otherwise `INVALID_ROUTE_CONFIG` at start); `skipCompression` returns the reply and is called before `send` |
146
+ | `route({ ..., config: { id: 'API-12' } })` | the route's id (D-0077): 1 to 64 letters, digits, `.`, `_` or `-`, starting with a letter. dokebi-web owns the key: a wrong value or a misspelt key (`ID`) fails the start with `INVALID_ROUTE_CONFIG`, and the same id on two routes of one app (the same constraints) fails it with `DUPLICATE_ROUTE_ID` (`details.duplicates`, error log `WEB_ROUTE_ID_DUPLICATE`). One route registered twice counts once: the HEAD twin of a GET, and a path with and without its trailing slash (dokebi-app answers a module root both ways). The same id in two apps (other constraint values) is allowed: a module mounted in both apps is one route of the design. The handler reads it as `request.routeOptions.config.id` (typed `id?: string`; route config stays open to other keys) |
147
+ | `routes()` | every route added so far (D-0077), frozen: `[{ method, url, id?, constraints, configKeys }]` (`WebRouteEntry`: `method` like `GET` or `GET,POST`, `url` with the scope prefix, `constraints` as text such as `{ dokebiApp: 'admin' }`, `configKeys` the names of its config keys without `url`/`method`). The HEAD twin Fastify adds to a GET is left out; health routes are in it (`configKeys: ['dokebiHealth']`). The same array is returned until another route is added (no copy per call). Complete once the server is ready (after start, or `ready()`), when the routes of Fastify plugin scopes exist too |
79
148
  | `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
149
 
81
150
  - `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
151
  - `@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.
152
+ - `viewData` (`dokebi-web:view-data`, D-0076 §5) carries values a plugin adds to every rendered page: contribute `{ key, value(request) }` (list the point under `contributes`). @dokebi/app puts it in the EJS data of every app page and error view (`data.<key>`: after `sealed` and the flash, before the app's `shared` and the page data, so those win), template-inertia in the shared props (before the entry's `shared` and the page props). `value` runs only when a page renders (JSON routes never call it) and may return a Promise. `collectViewData(contributions, { plugin, reserved })` is the collectors' check: a key twice, a key the collector sets itself (app: `sealed`, `seal`, `errors`, `old`, `flash`; template-inertia: `errors`, `flash`) or an invalid entry refuses the setup with `VIEW_DATA_CONFLICT` (`plugin` is the collector).
153
+ - `errorTranslators` (`dokebi-web:error-translator`, D-0093) is collected by web itself: contribute `{ translate(error, request) }` (type `WebErrorTranslator`; list the point under `contributes`, and core sets the contributor up before web). An error that would answer 500 is offered to every contribution in setup order: an uncoded error (`INTERNAL_SERVER_ERROR`, no Fastify 4xx), and a Dokebi error answering 500, thrown in a handler or any hook: a plugin's coded failure around a driver error (dokebi-auth's HOOK_FAILED of a `findById` on a full pool, dokebi-session's STORE_FAILED over a full Redis connection), or a plugin's own error its translator knows (a bare @dokebi/redis `QUEUE_FULL`, D-0102); for these only a translation answering 5xx counts. The first `DokebiError` returned answers instead, through the normal path of §6 (its status and code, JSON or HTML, `errorBody`, the error responders, sealed JSON). `translate` is synchronous, returns undefined to pass, puts the thrown value in the result's `cause` and no driver text, values or names in its message, hint or data; a numeric `data.retryAfterMs` also sets `Retry-After` (seconds, rounded up). @dokebi/db contributes one from its adapters' `classifyError` (`DB_CONFLICT` 409, `DB_INVALID_DATA` 422, `DB_TIMEOUT`/`DB_BUSY`/`DB_UNAVAILABLE` 503, db AI.md §4.1); @dokebi/redis one for its transient errors (`REDIS_BUSY`/`REDIS_TIMEOUT`/`REDIS_UNAVAILABLE` 503, redis AI.md §4). A contribution without a `translate` function fails the setup with `INVALID_ERROR_TRANSLATOR`; a translator that throws or returns anything else is logged and skipped (§6).
154
+ - `@dokebi/web/points` also has the shared pieces of app binding (D-0132, §2.1): `appOption(description)` (the `app` option of a plugin that adds routes, for `defineOptions`), `appUrlMatch(routing, url, apps)` (whether a URL a plugin publishes is a domain of the apps that serve it), `APP_NAME`, `APP_NAMES_MAX` and the types `WebAppSetting`, `WebAppRouting`, `WebAppUrlMatch` (also exported from the root, with `appNames`).
155
+ - **Before-hijack steps** (D-0089, `@dokebi/web/points`, also from the root): a hijacked reply (an SSE stream, a WebSocket upgrade) runs no `onSend`, so plugins that finish work there (@dokebi/session saves the session and writes its cookie, @dokebi/auth its cookies) also push a step onto `beforeHijackSteps(scope)` (one list per server, under `BEFORE_HIJACK` = `Symbol.for('dokebi.web.beforeHijack')`, shared by name), and a transport calls `runBeforeHijack(request, reply, timeoutMs, timeoutError)` before it writes its own head: `undefined` when nothing is to be waited for (no Promise, no timer), else a Promise of the number of steps waited for, rejecting with the first failure or `timeoutError()` (`WebBeforeHijackStep`: `(request, reply) => PromiseLike<void> | undefined`).
83
156
  - 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`), 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.
157
+ - Other exports: `options` (the `defineOptions` declaration) and `WebOptions`, `WebError`, `validationError` and `WebValidationError` (§6), `errorFormat` and `requestErrorFormat` (§6) and the responder types (`WebErrorResponder`, `WebErrorResponse`, `WebErrorFormat`, `WebFieldError`), the form helpers `isFormSubmission`, `formFieldErrors`, `formOldInput`, `formBackTarget` and their types `WebFormRequest`, `WebFormValue` (0.4.1, §6), `WebRouteConfigKey` and `WebRouteConfigUse` (0.4.3), `WebRouteEntry` and `WebDuplicateRouteId` (0.4.3, D-0077), `defineErrors`, `errorCatalog`, `ERROR_CATALOG` and their types `ErrorDefinition`, `ErrorCatalogEntry`, `DefinedError`, `DefinedErrors`, `DefinedErrorOptions` (0.4.3, §6), `skipCompression` and the types `WebCompressionEncoding`, `WebCompressionOptions` (0.4.3, D-0125), `WebExtension` and its types, `SEALED_PATH_HEADER` (`x-dokebi-sealed-path`), `SEALED_LOCATION_HEADER` (`x-dokebi-location`), `FORM_SUBMISSION_HEADER` (`x-dokebi-form`) and `SEALED_FETCH_HEADER` (`x-dokebi-sealed`) (0.4.3, D-0092) and the seal types.
158
+
159
+ ### 2.1 Routes bound to apps (D-0132)
160
+
161
+ In a project with several apps (@dokebi/app, chosen by host), a route a plugin or a module adds directly on web answers on **every host** unless it says otherwise. `app` says which apps' hosts answer it:
162
+
163
+ ```ts snippet
164
+ http.route({ method: 'POST', url: '/hooks/billing', app: 'api', handler }); // api's hosts only
165
+ http.register(async (scope) => {
166
+ scope.route({ method: 'GET', url: '/status', app: ['studio', 'admin'], handler }); // in a scope too
167
+ }, {});
168
+ ```
169
+
170
+ - It becomes the host constraint of app routes (`dokebiApp`), so the route behaves like an app route of those apps: their domains (dev hosts `<app>.<project>.localhost` are domains too), a forwarded host behind `trustProxy`, and `unknownDomain` (a host no domain names is answered by that app, its bound routes included). On every other host the answer is **the 404 of an unknown route** (the app's 404 page or JSON `NOT_FOUND`), never 403: nothing tells the endpoint exists there.
171
+ - Bound at boot (`server.ready()`), after every setup, so the order of plugins does not matter; `routes()` lists the constraint (`{ dokebiApp: 'mcp' }`, a list as `studio,admin`). A route of another app at the same method and path on one app fails the start (`ROUTE_APP_CONFLICT`).
172
+ - **Plugins that add routes** take the same option name: `<plugin>.app` in dokebi.yaml (`dokebi-mcp.app: mcp`, `dokebi-oauth.app: studio`), declared with `appOption(description)` of `@dokebi/web/points` and passed as the `app` of each route. A plugin that publishes its own URLs (an OAuth issuer, a resource URI) checks them at boot with `appUrlMatch(http.apps, url, apps)`: `other-app` (the host is a domain of another app: clients would reach a 404) should fail its start, `unconfigured` (no domain names the host: a proxy may map it) should warn.
173
+ - Without @dokebi/app a bound route fails the start with `ROUTE_APP_UNAVAILABLE` (fail closed: ignoring the binding would put the endpoint on every host); a name that is not an app fails it with `ROUTE_APP_UNKNOWN` (`data.apps` lists the apps); a bad value (not a name, an empty or repeated list) is `INVALID_ROUTE` at the call. An app no domain points at (and not the `unknownDomain` target) is warned once: `ROUTE_APP_UNREACHABLE`.
174
+ - Health routes are never bound (load balancers probe any host). Debug logs: `Web app routing registered` (`constraint`, `apps`, `fallback`), per bound route `Web route bound to apps` (`route`, `apps`).
175
+
176
+ ### 2.2 Ids of the routes plugins add (D-0142)
177
+
178
+ Every route a plugin adds itself has a route id like an app route's `config.id`, with no configuration: `/mcp` is `mcp.endpoint`, `/oauth/token` is `oauth.token`, the health routes are `web.healthLive` and `web.healthReady`. The id is `<namespace>.<key>`: the namespace is the plugin id without `dokebi-` (`dokebi-template-inertia` → `template-inertia`), the key names the route's role. One key may cover several routes of one role (the six files of `/dokebi/seal/`, a GET and a POST of `/oauth/authorize`, one copy per app); they share the id on purpose. So an audit hook reads `request.routeOptions.config.id` for every request, a route hook sees `info.config.id`, and `routes()` and `dokebi describe` (`routes[].id`) show it, with `plugin` naming the owner (`routes[].plugin`; absent on the app's own routes).
179
+
180
+ - **Override**: `options.<plugin>.routeIds.<key>` replaces one id (`dokebi-mcp.routeIds: { endpoint: ai.mcp }`), when it collides with an app route or a naming policy wants another. Keys other than the plugin's route keys are refused (`INVALID_PLUGIN_OPTIONS`, `is not an allowed option`), and values follow the `config.id` rule. Each plugin's AI.md lists its keys.
181
+ - **Same checks as app routes**: the ids go through the same start-up checks (`INVALID_ROUTE_CONFIG`, `DUPLICATE_ROUTE_ID`). An app route that takes a plugin route's id fails the start, and the message names both owners: `Route id oauth.token is on more than one route: POST /tokens [dokebiApp=studio] (application), POST /oauth/token [dokebiApp=studio] (dokebi-oauth routeIds.token)`, with a `fix` naming the option. A plugin route bound to no app (no `app` option) answers on every host, so its id is taken in every app. Two keys of one plugin set to one id are a duplicate too.
182
+ - **Logs**: the error and rejection logs of dokebi-web (`HTTP request rejected` at debug, `WEB_REQUEST_FAILED`, `WEB_ERROR_TRANSLATED`, `FORM_BODY_DISABLED`) carry `routeId` (the id, or `null`) next to `route`, and the plugins' own refusal logs carry it as well (`MCP origin refused`, `OAuth token refused`, …).
183
+ - **For a plugin author**: declare `routeIds: routeIdsOption('<plugin>', { <key>: '<which routes>' })` in `defineOptions` and give each route `config: pluginRouteIds('<plugin>', keys, options.routeIds).config(key, { ...config })`, both from `@dokebi/web/points`. The config carries the id and the owner mark `ROUTE_OWNER` (`Symbol.for('dokebi-web:route-owner')` → `{ plugin, key }`; a symbol key, so no config key is added). A plugin that does not import @dokebi/web (@dokebi/seal, @dokebi/mail) writes the same symbol and the same option shape. Also exported: `ROUTE_ID` (the id rule) and `routeNamespace(plugin)`.
184
+
185
+ ### 2.3 Files from a folder
186
+
187
+ Serving an operator's folder (update feeds, installers) is [@dokebi/static](https://git.nyx-zone.com/dokebi/framework/-/blob/main/plugins/dokebi-static/AI.md) ([D-0147](https://git.nyx-zone.com/dokebi/framework/-/blob/main/docs/decisions/D-0147-static-plugin.md)): `options.dokebi-static.mounts.<name>`, on @fastify/static. dokebi-web itself has no `files` option or `files()` method (the D-0146 mounts of the unpublished 0.4.3 moved there).
188
+
189
+ ### 2.4 Security headers (D-0149)
190
+
191
+ On by default, with no configuration. Every answer gets `X-Content-Type-Options: nosniff`, and an answer to an HTTPS request (TLS here, or `X-Forwarded-Proto: https` from a `trustProxy` address) `Strict-Transport-Security: max-age=31536000; includeSubDomains`; never over plain HTTP. An HTML document (`Content-Type: text/html…`) also gets:
192
+
193
+ | Header | Default |
194
+ |---|---|
195
+ | `Content-Security-Policy` | `default-src 'self'; base-uri 'self'; object-src 'none'; frame-ancestors 'self'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline' https:; img-src 'self' data: blob: https:; font-src 'self' data: https:; connect-src 'self'` |
196
+ | `X-Frame-Options` | `SAMEORIGIN` |
197
+ | `Referrer-Policy` | `strict-origin-when-cross-origin` |
198
+ | `Cross-Origin-Opener-Policy` | `same-origin-allow-popups`, over HTTPS only (browsers ignore it on plain HTTP and log a console error) |
199
+ | `Cross-Origin-Resource-Policy` | `same-site` |
200
+
201
+ - **A header already set is kept**: a handler or a plugin that sets its own (`reply.header('content-security-policy', …)`) wins. That is how the sandboxing CSP of @dokebi/storage and @dokebi/image downloads, @dokebi/static files, the development mail inbox (@dokebi/mail) and the OAuth consent page (`frame-ancestors 'none'`) stay as they are.
202
+ - **Plugins add the sources they need** with `web.contentSecurityPolicy({ plugin, directives })` (setup only; appended to the directive, a directive that is not set starts from `default-src`): @dokebi/seal adds `'wasm-unsafe-eval'` to `script-src` (its browser client compiles WebAssembly), @dokebi/template-inertia in development `ws://*:* wss://*:*` to `connect-src` (the Vite HMR socket on its own port). `'unsafe-inline'` in `script-src` is in the default for the seal import map that @dokebi/app writes into EJS pages, inline scripts of your EJS pages and inline scripts a Vite framework plugin adds in development; remove it (`directives: { script-src: ["'self'", "'wasm-unsafe-eval'"] }`) when your pages have none.
203
+ - **Change it in dokebi.yaml** (`securityHeaders.*`, the table of §1): a CDN in `img-src`, `report-only` while you tighten the policy, `frameOptions: DENY`.
204
+ - **Per route**: `config: { securityHeaders: false }` sends none (a page other sites embed on purpose); `config: { securityHeaders: { frameOptions: false, contentSecurityPolicy: { directives: { 'frame-ancestors': ['https://partner.example'] } } } }` changes some (the same keys as the options except `enabled`; `strictTransportSecurity` takes only `false`). Checked at start (`INVALID_ROUTE_CONFIG`). Hijacked answers (SSE streams, WebSocket upgrades, the Vite dev proxy) are written outside Fastify and get none.
205
+ - Cost: the values are built once per route; a JSON answer gets one header. Measured on the hello JSON route: 0.99 of Fastify alone, where `@fastify/helmet` (a dozen headers on every answer, its middleware built per request) answered at 0.71 (D-0149 §0, §2).
206
+
207
+ ### 2.5 Overload protection (D-0150)
208
+
209
+ On by default. [@fastify/under-pressure](https://github.com/fastify/under-pressure) samples the event loop delay, event loop utilization, heap and RSS every `overload.sampleIntervalMs` (1 s); while the last sample is above a limit (`overload.maxEventLoopDelayMs` 200 by default, the others off), every request is answered **503 `OVERLOADED`** with `Retry-After` (`retryAfterMs`, 2 s) and `Cache-Control: no-store` before any handler, auth hook or body parser runs: the error shape for scripts (`{ error: 'OVERLOADED', message, hint, data: { reason, retryAfterMs } }`), a small page for a browser navigation. `reason` is `eventLoopDelay`, `eventLoopUtilization`, `heapUsedBytes` or `rssBytes`.
210
+
211
+ - **Served anyway**: the health routes, and routes with `config: { overload: false }` (a metrics scrape, an operator's status page). Checked at start (`INVALID_ROUTE_CONFIG`). Never turn it off on an API route that takes load: its callers then queue behind a stalled worker instead of getting a 503 they can retry (AI-M37). `dokebi check` reports `overload: false` as `overload-off`; a metrics route keeps it with `// dokebi-check: allow overload-off <reason>`.
212
+ - **Logs** (D-0113): the first refusal of each route per `transientLogWindowMs`, at `transientLogLevel` (`WEB_OVERLOADED`: `method`, `route`, `routeId`, `reason`, `value`, `limit`, `fix`), the rest counted into `WEB_TRANSIENT_REPEATED`; the start and the end of an overload at debug. No log per refused request.
213
+ - **Why 200 ms**: a saturated but healthy loop (hello JSON at 256 connections) measured a mean delay of 11 ms (at most 24 ms); a CPU-bound route (20 ms per request, 100 connections) 252 ms, with a p99 latency of 8.5 s and health checks waiting 0.8 s. With the default, the served requests answered in under 5 ms at p99, health in 4 ms, and the rest got 503 at once (D-0150 §2, §4). Raise it for work that blocks the loop on purpose; `0` turns a check off, `enabled: false` all of them.
214
+ - Under pressure the server sheds whole sample intervals: throughput of a CPU-bound route drops (it served about 65% of what it could), latency and health stay bounded. Add capacity, or move the work to @dokebi/worker or @dokebi/job.
215
+ - Cost while calm: one field read per request (measured: no difference on hello JSON).
216
+ - **Reload** (D-0154): the limits and `retryAfterMs` reload; a reload that sets a limit above 0 when protection was not on at start (`enabled: false`, or every limit 0) is refused with `OVERLOAD_RESTART_REQUIRED` (`plugin: 'dokebi-web'`; the sampler starts with the server): restart instead.
217
+
218
+ ### 2.6 Behind a tunnel or reverse proxy (Cloudflare Tunnel, ngrok, nginx)
219
+
220
+ A tunnel or proxy that forwards to this app usually connects from this machine and passes the browser's host in `X-Forwarded-Host` (Cloudflare Tunnel with its HTTP Host Header set to `localhost` sends `Host: localhost`, `X-Forwarded-Host: studio.example.com`, from `127.0.0.1`). Do these three things:
221
+
222
+ 1. **`trustProxy`**: the proxy's address as this app sees it. A tunnel on the same machine: `trustProxy: [127.0.0.1, "::1"]`. Only then `requestHost()` is the browser's host; otherwise it is `localhost`, and web warns `WEB_FORWARDED_HOST_IGNORED` (`remote`, `forwardedHost`, `fix`) once per peer and `logRepeatWindowMs` (only for loopback and private peers).
223
+ 2. **The public host is a known host**: an @dokebi/app domain (`options.dokebi-app.domains`), and in development also `options.dokebi-template-inertia.devHosts`.
224
+ 3. **Nothing else**: the tunnel's HTTP Host Header may stay `localhost`; no change on the tunnel side is needed.
225
+
226
+ What goes wrong without step 1: the app is chosen by `localhost` (the public host is not matched), and on a seal host the first Inertia page does not decrypt in the browser — the seal key uses the host, `requestHost()` on the server and the address bar on the browser, and they must be the same. Check: `web.requestHost(request)` must equal the host in the browser's address bar. Development HMR goes through the page's own origin, so it works through the tunnel too (@dokebi/template-inertia AI.md §5.1).
85
227
 
86
228
  ## 3. Start and request blocking
87
229
 
88
230
  - web listens in its start, after every setup. **A cluster worker (`context.runtime.role === 'worker'`) listens in the core `ready` hook** (D-0034), so only workers whose whole app is ready get connections. With `runtime.serving` false it never listens (D-0063 §4).
89
- - Until the app has started and health is ready, business requests get 503 `{ error: 'SERVICE_UNAVAILABLE', reason }` (reason `STARTING`, `NOT_READY` or `DRAINING`); a browser page (§6 format rule) gets the same as a small HTML page. The status, headers (`retry-after` and so on) and body can be changed with the extension hook `unavailable` (§8); a hook body of the error shape (`{ error, … }`) is still drawn as a page for a browser. The request is refused either way, so drain stays correct. Error responders are not asked for these refusals (the app is starting or draining).
90
- - Health routes: live 200/503, ready 200/503 (app state and the health checks). `dokebi-health` is an optional dependency: when registered it is connected automatically, otherwise only the app state counts. Health is per app, not a cluster-wide aggregate.
231
+ - Until the app has started and health is ready, business requests get 503 `{ error: 'SERVICE_UNAVAILABLE', reason }` (reason `STARTING`, `NOT_READY` or `DRAINING`; `DRAINING` from the moment the app stops, also while plugins that depend on web — sse, websocket — drain before web, and a cluster worker serves those requests with `Connection: close` instead, as in its own drain) with `Retry-After` (`unavailableRetryAfterMs`, 5 s) and `Connection: close` (HTTP/1: the retry opens a new connection, which a cluster primary or a load balancer may give to a ready worker; with the Retry-After a client pays that handshake once per wait); a browser page (§6 format rule) gets the same as a small HTML page. The status, headers (`retry-after` and so on) and body can be changed with the extension hook `unavailable` (§8); a hook body of the error shape (`{ error, … }`) is still drawn as a page for a browser. The request is refused either way, so drain stays correct. Error responders are not asked for these refusals (the app is starting or draining).
232
+ - **`config.readiness: false` (M51)**: a route served while a required health check is down (the 503 `NOT_READY` above) and while the app drains (`DRAINING`), like the health routes, so a metrics scrape or a status page answers during a database or Redis outage, when it is needed most. It is tracked like any request (the drain waits for it) and still refused before the app runs (`STARTING`) and once the plugins clean up. A boolean, checked at start (`INVALID_ROUTE_CONFIG`). The browser files of @dokebi/template-inertia (`/build/*`, the built files and the dev modules), @dokebi/seal (`/dokebi/seal/*`) and @dokebi/static mounts (an app's `public/` too) carry it, so such a page also opens anew during the outage. Never on an API route: its handler would run against the missing dependency (`npx dokebi check` reports `readiness-off` as an error without `// dokebi-check: allow readiness-off <reason>` on the line before it).
233
+ - Health routes: live 200/503, ready 200/503 (app state and the health checks). `dokebi-health` is an optional dependency: when registered it is connected automatically, otherwise only the app state counts. Body: `{ ready }`.
234
+ - **Ready of a cluster ([D-0164](https://git.nyx-zone.com/dokebi/framework/-/blob/main/docs/decisions/D-0164-cluster-wide-readiness.md)).** In a `@dokebi/cluster` worker the ready route answers for **every worker**: they share one port and a load balancer sees them as one target, so one ready worker must not say 200 while another still refuses requests with 503 `NOT_READY` (a database that came back reaches each worker's check at its own time). A worker that is not ready itself answers 503 `{ ready: false }` at once; a ready one asks the others through the cluster (500 ms) and answers 200 only when each is ready, with `{ ready, workers: { total, ready: [slots], notReady: [slots] } }`. Left out: a draining worker (it no longer listens) and one without web. A worker that does not answer in time counts as not ready. While the cluster starts or stops, 503 with `reason: 'GATHER_UNAVAILABLE'`; when the cluster cannot ask (`GATHER_BUSY` and the like) the worker answers for itself with `reason` and warns `WEB_READY_GATHER_FAILED` once per `logRepeatWindowMs`. Concurrent probes of one worker share one question. A plain `node:cluster` worker without `@dokebi/cluster` answers for itself. `live` stays per worker. `health.ready` and the 503 `NOT_READY` refusals stay per worker too: a ready worker serves.
91
235
 
92
236
  ### 3.1 HTTP on seal hosts (D-0062)
93
237
 
94
- With @dokebi/seal and @dokebi/app, requests to a seal host behave like this: JSON responses (4xx included) go out as an `E:<ts>:<b64>` body with `Content-Type: application/vnd.dokebi-seal` and `x-dokebi-sealed-path`, and request bodies must be sealed. Plain JSON, urlencoded and text bodies get **415 `SEAL_REQUIRED`** before the handler (multipart uploads pass). Browsers use `sealedFetch` and `sealInertia` of `@dokebi/seal/http`. Routes that cannot be sealed, such as webhooks, opt out with `seal: false` or `sealExclude`. HTML responses (EJS) stay as they are. Asking for sealing without a provider fails the start with `SEAL_PROVIDER_MISSING`. Sealing is obfuscation and replay protection; confidentiality comes from TLS.
238
+ With @dokebi/seal and @dokebi/app, requests to a seal host behave like this: JSON responses (4xx included) go out as an `E:<ts>:<b64>` body with `Content-Type: application/vnd.dokebi-seal` and `x-dokebi-sealed-path`, and request bodies must be sealed. Plain JSON, urlencoded and text bodies get **415 `SEAL_REQUIRED`** before the handler (multipart uploads pass). Browsers use `sealedFetch` and `sealInertia` of `@dokebi/seal/http`. Routes that cannot be sealed, such as webhooks, opt out with `seal: false` or `sealExclude`. HTML responses (EJS) stay as they are.
239
+
240
+ **EJS pages and forms on a seal host (0.4.3, [D-0092](https://git.nyx-zone.com/dokebi/framework/-/blob/main/docs/decisions/D-0092-ejs-seal-default-view-layout.md) §1).** Page navigations are plain; forms and REST are sealed:
241
+
242
+ - **A page navigation is HTML, its errors too.** A GET or HEAD without a body whose `Accept` prefers HTML and that carries no script marker (`X-Inertia`, `X-Requested-With`, Bearer, `x-dokebi-sealed`, a `Sec-Fetch-Mode` other than `navigate`) is answered like on a plain host: the page, and an error as the HTML page (an app's `errors/<status>.ejs`, an Inertia `errorPage`, else web's small page). Every JSON answer of a sealed request stays sealed.
243
+ - **A sealed form** is a request with `x-dokebi-form: 1` (sent by `@dokebi/seal/forms`). Its sealed body must open to the shape the urlencoded parser gives — an object of strings, a repeated name an array of two or more strings, at most `formMaxFields` values — and the handler gets it as such an object without a prototype (`formBody` off: 415 `FORM_BODY_DISABLED`; another shape, a marker other than `1`, or the marker on a body that is neither sealed nor multipart: 400 `FORM_BODY_INVALID`). `isFormSubmission` is true for it, so its errors take the HTML form flow: a 422 (or a 4xx with `data.formErrors`) goes back with `errors` and `old` (@dokebi/app with a session), any other error is the HTML error page. With files the module sends multipart with the same marker.
244
+ - **Redirects of a sealed form are told, not followed**: a 3xx answer to `x-dokebi-form: 1` leaves as **204 with `x-dokebi-location: <target>`** (and `Cache-Control: no-store`), and the forms module navigates there. The browser's fetch would otherwise follow the redirect itself — render the next page and take its session flash for an answer it throws away, and fail on another origin. Success redirects of handlers and the form-back redirect both go this way.
245
+ - **A native form post** (urlencoded, a page without its seal script or without JavaScript) is still refused with 415 `SEAL_REQUIRED`, now with fixed words (`This page needs its seal script to send forms`, hint `Reload the page and send the form again.`): an HTML page for a browser navigation, the JSON 415 for a script. Asking for sealing without a provider fails the start with `SEAL_PROVIDER_MISSING`. Sealing is obfuscation and replay protection; confidentiality comes from TLS.
95
246
 
96
247
  ## 4. Shutdown (drain)
97
248
 
98
- - Single process: new requests get 503, and drain waits for responses in progress, handler Promises (including the part that continues after the response was sent), request hooks, after-response hooks (`onResponse`, `onError`, `onTimeout`, `onRequestAbort`) and `track` work. When a client disconnects first, drain still waits for that request's hooks and handler (D-0023). Requests are counted without a Promise each (D-0068). When the core drain deadline (default 20 s) passes or on `stop({ force: true })`, remaining connections are cut and drain returns (core records `DRAIN_TIMEOUT`). After every drain succeeded, cleanup calls `Fastify.close` (onClose runs).
99
- - Cluster worker (D-0036): the listen socket closes first so the primary sends new connections to other workers; requests on open keep-alive connections are served and then closed with `Connection: close`. The worker stays up at least 100 ms. A request sent at the moment an idle keep-alive connection closes can get `ECONNRESET` (inherent to HTTP); non-browser clients retry an idempotent request on a reused socket once.
249
+ - Single process: new requests get 503, and drain waits for responses in progress, handler Promises (including the part that continues after the response was sent), request hooks, after-response hooks (`onResponse`, `onError`, `onTimeout`, `onRequestAbort`) and `track` work. When a client disconnects first, drain still waits for that request's hooks and handler (D-0023). Requests are counted without a Promise each (D-0068). When the core drain deadline (default 20 s) passes or on `stop({ force: true })`, remaining connections are cut and drain returns (core records `DRAIN_TIMEOUT`). After every drain succeeded, cleanup calls `Fastify.close` (onClose runs). Cleanup first ends every connection that answers no request: idle keep-alive connections, a connection on which no request ever arrived (a browser's preconnect, the spare connection an HTTP client opens after it aborted a request), one whose next request is still arriving, a TLS connection before its handshake, and an HTTP/2 session without streams, including one whose client never sent its preface. Node's own sweep leaves these, and `server.close()` waited for them until `headersTimeout` or for ever, past the cleanup deadline (`CLEANUP_TIMEOUT`). A response still under way is left to finish and its connection is ended once it has; an HTTP/2 session with streams under way gets GOAWAY and ends after them; an upgraded connection (WebSocket) is left to its plugin; a connection accepted after cleanup began is ended at once. Connections are judged from public server events only (`connection`, `secureConnection`, `session`, `request` and the response's `close`, `upgrade`): per connection one Set entry and one shared listener (plus one Map entry behind TLS or HTTP/2), per HTTP/1 request one property write (the connection's newest response), per HTTP/2 request a counter on the session and one shared listener. Measured against the previous reads of Node's private fields: no difference on the empty-route benchmark (web/fastify 0.933 against 0.931, three alternating rounds each). At the drain deadline the same tracking cuts every connection but upgraded ones (HTTP/2 servers have no `closeAllConnections`), and a draining cluster worker sends GOAWAY to its HTTP/2 sessions.
250
+ - Cluster worker (D-0036): the listen socket closes first so the primary sends new connections to other workers, and HTTP/2 sessions are told GOAWAY. HTTP/1 has no such signal: a keep-alive connection the server answered with `Keep-Alive: timeout=…` may carry the client's next request at any moment, and closing it then loses that request (`ECONNRESET`; Node's agent never resends, undici only idempotent methods — the M50 review lost 2 of 588 paced POSTs per 10 replacements). So the open connections stay up to `drainIdleMs` (2 s): a request on one is served with `Connection: close` and the client's next one opens a connection to another worker; the wait ends as soon as no connection is left. Then the connections still idle are closed (once, `closeIdleConnections`, which leaves a connection whose next request has begun to arrive), and a response still under way closes its connection when it ends; after that only the ending response's own connection is looked at, so a drain costs O(connections) ([D-0107](https://git.nyx-zone.com/dokebi/framework/-/blob/main/docs/decisions/D-0107-stream-and-render-bounds.md) §1). The worker stays up at least `drainGraceMs` (100 ms). What stays: a client that stays idle longer than `drainIdleMs` and sends its request at the very moment the connection closes can still see `ECONNRESET` (no HTTP/1 server can prevent that); a client that pauses longer than 2 s between requests needs a larger `drainIdleMs`, or a retry of the requests it can repeat.
100
251
 
101
252
  ## 5. Ownership rules (important)
102
253
 
@@ -117,13 +268,16 @@ With @dokebi/seal and @dokebi/app, requests to a seal host behave like this: JSO
117
268
  | `throw validationError({ name: 'Already taken' })` from a handler (D-0074) | 422 | the same shape (`fields`, `errors`) |
118
269
  | an unknown route (D-0074) | 404 | `{ error: 'NOT_FOUND', message, hint }` |
119
270
  | any other 4xx (malformed JSON, media type, size, a `params` or `headers` schema) | Fastify's value | `{ error: 'INVALID_REQUEST' }` (plus Fastify's `message` in development) |
271
+ | an error a `dokebi-web:error-translator` contribution translates (D-0093: a driver error with @dokebi/db, also inside a Dokebi error answering 500 such as dokebi-auth's HOOK_FAILED; D-0102: a transient @dokebi/redis error, bare or under session's STORE_FAILED) | the translated error's `status` | the translated error's `{ error: code, message, hint?, data? }`; `Retry-After` from `data.retryAfterMs` |
120
272
  | anything else (unknown errors, errno and so on) | 500 | `{ error: 'INTERNAL_SERVER_ERROR' }` |
121
273
 
122
274
  - **Production** (`NODE_ENV=production` or `developmentErrors: false`) never carries `fix`, `details` or stacks, and a 5xx `message` becomes a generic sentence (`Internal Server Error`, `Service Unavailable` and so on). `code`, `hint`, `data`, `fields` and `errors` are sent in production too. **Development** also sends `fix` and `details` (when they fit in 16 KB of JSON).
123
275
  - The body is a flat object extending the old `{ error: '<CODE>' }` shape (`error` is the code). Clients branch on `body.error`.
124
276
  - The extension hook `errorBody` can change status and body (§8). In production web removes `fix`, `details` and `stack` whatever the hook returns.
125
277
 
126
- **Validation errors (D-0074).** A field is the property path without `body/`: `name`, `address.city`, `items.0.name`; a missing property is named itself (`required` → `name`: `is required`); a query string field is `query.page`; a body that is wrong as a whole is `_body`. Fastify stops at the first failing rule (Ajv `allErrors: false`, its safe default), so a schema answer usually names one field. Refuse input in handler code the same way, so clients see one shape:
278
+ **Route schemas.** Fastify's Ajv compiles them with union types allowed (`type: ['string', 'null']`, `type: ['string', 'number', 'boolean']`). What Ajv's strict mode still reports while a schema compiles (a `properties` without `type: 'object'`, an unknown format) is logged as warn `WEB_SCHEMA_WARNING` (`warning`: Ajv's text with the schema path; `WEB_SCHEMA_ERROR` at error, `WEB_SCHEMA_MESSAGE` at debug), never printed to the console. An extension that sets its own `ajv` option in `fastifyOptions` replaces both.
279
+
280
+ **Validation errors (D-0074).** A field is the property path without `body/`: `name`, `address.city`, `items.0.name`; a missing property is named itself (`required` → `name`: `is required`); a query string field is `query.page`; a body that is wrong as a whole is `_body`. Fastify stops at the first failing rule (Ajv `allErrors: false`, its safe default), so a schema answer usually names one field. **`additionalProperties: false` does not refuse by default**: Fastify's Ajv removes the extra fields (`removeAdditional`) and the request goes on without them. To refuse them, set `unknownFields: refuse` under dokebi-web: then an extra field is a 422 `VALIDATION_FAILED` like any refused field (`extra` `is not allowed`). Ajv also coerces types (`coerceTypes: 'array'`: `"5"` for an integer becomes 5) and fills `default` values. Refuse input in handler code the same way, so clients see one shape:
127
281
 
128
282
  ```ts snippet
129
283
  import { validationError } from '@dokebi/web';
@@ -133,10 +287,37 @@ if (await users.exists(body.name)) throw validationError({ name: 'This name is t
133
287
 
134
288
  Do not answer validation with your own `reply.code(422).send(…)`: template-inertia only turns a `VALIDATION_FAILED` answer into the Inertia validation redirect. `fields` keeps every message in order; `errors` is the first message per field (the shape of Inertia `useForm().errors`).
135
289
 
136
- **JSON or HTML (D-0074, `errorFormat(headers, sealed)`).** One rule for every error answer (thrown errors, refused schemas, unknown routes, 413/415 bodies, seal errors, the 503 refusals):
290
+ **App error codes in one list (D-0077, `defineErrors`).** Declare the codes an app answers with once, in `src/shared/errors.ts`, and throw them by name; never write a code as a string in a route (`npx dokebi check` warns `unknown-error-code`):
291
+
292
+ ```ts
293
+ import { defineErrors } from '@dokebi/web';
294
+
295
+ export const errors = defineErrors({
296
+ POST_NOT_FOUND: { status: 404, message: 'The post does not exist', hint: 'Check the address.' },
297
+ POST_LOCKED: { status: 409, message: 'The post is being edited' },
298
+ });
299
+ ```
300
+
301
+ ```ts snippet
302
+ import { errors } from '../../shared/errors.ts';
303
+ throw errors.POST_NOT_FOUND({ data: { id } }); // 404 { error: 'POST_NOT_FOUND', message, hint, data }
304
+ throw errors.POST_LOCKED({ message: 'Post 7 is being edited', cause });
305
+ if (error.code === errors.POST_LOCKED.code) { /* … */ }
306
+ ```
307
+
308
+ - A code is a D-0063 code (upper case letters, digits and `_`, starting with a letter, at most 64), `status` an integer from 400 to 599, `message` one line of fixed English (at most 500 characters, trimmed), `hint` optional, one line, `intended` optional: `true` declares a refusal the app makes on purpose (a report budget, a quota it enforces), status 503 only, thrown with `data: { retryAfterMs }`. dokebi-web logs such an error at warn and counts its repeats per window (`WEB_TRANSIENT_REPEATED` at warn) instead of logging it at error: it is the app working as designed. Every other 503 keeps the D-0113 rule (`transientLogLevel`, default error) and a 500 is always logged at error. Any other field, an empty list, more than 1000 codes, `intended` on a status other than 503 or `VALIDATION_FAILED` (refused fields use `validationError`) throws `INVALID_ARGUMENT` when the module loads.
309
+ - `errors.CODE(options?)` returns a `DokebiError` with the code, status, message and hint and `plugin: 'app'`; options are `data` (sent to the client), `details` (development only), `cause` and a one-off `message` (one line). Each factory also has `code` and `status`. The result and every factory are frozen.
310
+ - The list is on the result under `Symbol.for('dokebi.errors.v1')` (`ERROR_CATALOG`): a frozen `[{ code, status, message, hint?, intended? }]` in declaration order. An error of an intended code carries `Symbol.for('dokebi.errors.intended.v1')` (`INTENDED_REFUSAL`) set to true. `errorCatalog(value)` returns it from a `defineErrors` result or from a module namespace that exports one (`errorCatalog(await import('./src/shared/errors.ts'))`; several exported lists are joined in export order, a code once), else undefined. Tools read it this way (`dokebi describe`); another installed copy of @dokebi/web reads it too.
311
+
312
+ **An error raised while an error answer is sent (audit r4 step 2).** An `onSend` step can fail on the error answer itself — @dokebi/session saving a flash on a 422 while its Redis is down. That second error is answered by dokebi-web like the first (translated: here the 503 with `Retry-After` of dokebi-redis's translator, in the same JSON or HTML format, logged once), never in Fastify's own `{ statusCode, code, error, message }` shape. If the answer to that second error fails too, nothing is left to answer with: the connection ends (over HTTP/2 the stream only) and error `WEB_ERROR_ANSWER_FAILED` (`route`, `status`, `fix`, `error`) is logged once per route and window.
137
313
 
138
- - **JSON** when any of: `X-Inertia` is present; `X-Requested-With: XMLHttpRequest`; `Authorization: Bearer …`; the request body is JSON (`Content-Type` `application/json` or `+json`: a script sent it); the request is sealed (D-0062: only sealed JSON leaves a seal host); `Accept` prefers JSON or is `*/*` (`fetch()`).
139
- - **HTML** (a small page with the code, message, hint, the refused fields and, in development, `fix`) only otherwise and only when `Accept` prefers `text/html`: a browser navigation or an HTML form post.
314
+ **An error answer is not the resource (audit 2026-10-24).** Before a thrown error is answered, the headers a handler set for the resource it was about to send go: `ETag`, `Last-Modified`, `Expires`, `Content-Disposition`, `Accept-Ranges` and `Content-Range` (a 416 keeps its `bytes */<size>`), and the answer is `Cache-Control: no-store`. Kept, a 404 went out cached for a year as `immutable` with the resource's ETag (the next `If-None-Match` answered 304 to the error). Protective headers (`X-Content-Type-Options`, a CSP) stay. An error responder runs after and may set its own caching on the reply (`errorBody` only returns the answer's status and body). web's own error answers are English (the small page says `<html lang="en">`, coded errors carry fixed English messages), so they go out with `Content-Language: en`, whatever language was negotiated for the request before (@dokebi/i18n sets it in `onRequest`): the built-in JSON and HTML answers of thrown errors, unknown routes and the 503 refusals. A body the `errorBody` hook wrote, and an app's error view or Inertia page sent by a responder, keep the header they have. HTTP/2 answers never carry a `connection` header (Fastify's 413 and body parse errors set one; web removes it, RFC 9113 §8.2.2).
315
+
316
+ **JSON or HTML (D-0074, D-0092, `errorFormat(headers, sealed, method?)`, `requestErrorFormat(request, sealed?)`).** One rule for every error answer (thrown errors, refused schemas, unknown routes, 413/415 bodies, seal errors, the 503 refusals). `errorFormat`, given only headers, reads whether a body follows from `Content-Length` and `Transfer-Encoding`; an HTTP/2 request needs neither, so a plugin that writes its own error answers calls `requestErrorFormat(request, web.sealOf(request) !== undefined)`, which asks the request itself (over HTTP/2 its HEADERS frame), as dokebi-web does for its own:
317
+
318
+ - **HTML** for a sealed form (`x-dokebi-form: 1`): the HTML form flow, whatever it accepts.
319
+ - **JSON** when any of: `X-Inertia` is present; the request is sealed (D-0062) and is not what a browser sends for a page (a GET or HEAD without a body, or a native urlencoded or multipart form post; no `x-dokebi-sealed`, `Sec-Fetch-Mode` absent or `navigate`) — without `method` a sealed request is always JSON; `X-Requested-With: XMLHttpRequest`; `Authorization: Bearer …`; the request body is JSON (`Content-Type` `application/json` or `+json`: a script sent it); `Accept` prefers JSON or is `*/*` (`fetch()`).
320
+ - **HTML** (a small page with the code, message, hint, the refused fields and, in development, `fix`) only otherwise and only when `Accept` prefers `text/html`: a browser navigation or an HTML form post. HTML is never sealed; every JSON answer of a sealed request is.
140
321
 
141
322
  | Client \ error | 404 route | 400 bad JSON | 413 | 415 form off | 422 schema | 422 `validationError` | 401/403 | 500 | 503 refused |
142
323
  |---|---|---|---|---|---|---|---|---|---|
@@ -147,7 +328,11 @@ Do not answer validation with your own `reply.code(422).send(…)`: template-ine
147
328
  | Bearer API | JSON | – | – | – | JSON (query) | JSON | JSON | JSON | JSON |
148
329
  | Inertia visit (GET, `X-Inertia`) | JSON | – | – | – | JSON | JSON | JSON | JSON | JSON |
149
330
  | Inertia POST | JSON | JSON | JSON | – | JSON | JSON | JSON | JSON | JSON |
150
- | sealed request (seal host) | JSON (sealed) | – | JSON (sealed) | 415 `SEAL_REQUIRED` JSON (plain) | JSON (sealed) | JSON (sealed) | JSON (sealed) | JSON (sealed) | JSON (sealed) |
331
+ | sealed request (seal host, Inertia) | JSON (sealed) | – | JSON (sealed) | 415 `SEAL_REQUIRED` JSON (plain) | JSON (sealed) | JSON (sealed) | JSON (sealed) | JSON (sealed) | JSON (sealed) |
332
+ | sealed navigation (GET, `Accept: text/html`, seal host) | HTML | – | – | – | HTML (query) | HTML | HTML | HTML | HTML |
333
+ | sealed form (`x-dokebi-form: 1`) | HTML | – | HTML | HTML | HTML | HTML | HTML | HTML | HTML |
334
+ | `sealedFetch` (`x-dokebi-sealed`, even with `Accept: text/html`) | JSON (sealed) | – | – | – | JSON (sealed) | JSON (sealed) | JSON (sealed) | JSON (sealed) | JSON (sealed) |
335
+ | native form post on a seal host | – | – | – | 415 `SEAL_REQUIRED` HTML | – | – | – | – | – |
151
336
 
152
337
  (`–`: 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
338
 
@@ -157,10 +342,10 @@ Do not answer validation with your own `reply.code(422).send(…)`: template-ine
157
342
 
158
343
  | Function | Returns |
159
344
  |---|---|
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) |
345
+ | `isFormSubmission(headers)` | true for a body of `application/x-www-form-urlencoded` or `multipart/form-data` (a browser `<form method="post">`), and since 0.4.3 for a sealed form (`x-dokebi-form: 1`, D-0092) |
346
+ | `formFieldErrors(body)` | the `errors` (`{ field: message }`) of a 422 `VALIDATION_FAILED` body; for another error body, its `data.formErrors` when that is a non-empty `{ field: message }` record of strings (0.4.3, D-0076 §2.5: how any error asks for the form redirect; `_form` is the key of an error about the whole form); else undefined. Responders go back only for a 4xx |
347
+ | `formOldInput(body, limits?)` | the request body's top-level strings, numbers, booleans and nulls without password-like fields (`password`, `token`, `secret`, `api_key`, `card`, `cvc`, `otp`, `pin`, and since 0.4.3 `csrf`/`xsrf` fields and every name core's one secret rule masks, `redaction.isSecretField` of `@dokebi/core/libraries`: `pwd`, `privateKey`, `credentials`, `sessionId`, `jwt`, `authorization`…); undefined when nothing is left or it is over `limits.oldInputMaxChars` (8 KB) as JSON. Pass `web.formLimits` as `limits` so the options apply |
348
+ | `formBackTarget(request, host, fallback?, limits?)` | 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
349
 
165
350
  dokebi-web knows no session: the caller flashes `errors` and `old` and answers `reply.redirect(target, 303)`.
166
351
 
@@ -170,34 +355,54 @@ dokebi-web knows no session: the caller flashes `errors` and `old` and answers `
170
355
  | Code | When |
171
356
  |---|---|
172
357
  | `INVALID_ENTRY` | the entry module exports something other than `requires` and `default`, or exports the extension class under a name (the cause of `INVALID_PLUGIN_INPUT`) |
173
- | `INVALID_ROUTE` | a route's `seal` is neither boolean nor function |
358
+ | `INVALID_ROUTE` | a route's `seal` is neither boolean nor function, its `bodyLimit` is above `maxRouteBodyBytes` (D-0122; `data.bodyLimit`, `data.maxRouteBodyBytes`), or its `app` is not an app name or a list of 1 to 64 distinct names, or comes with the `dokebiApp` constraint it sets (D-0132) |
174
359
  | `INVALID_HOOK` | an async Fastify hook takes the done argument |
175
- | `INVALID_ARGUMENT` | `sealRequests` or `errorResponder` got something other than a function, or `validationError` got no field or a non-string message |
360
+ | `INVALID_ARGUMENT` | `sealRequests` or `errorResponder` got something other than a function, `routeConfig` got an invalid or taken key (`id` is dokebi-web's own), `routeHook` got no plugin or function or its `route` returned a malformed addition, `validationError` got no field or a non-string message, `defineErrors` got a wrong definition, or an `errors.CODE()` call got wrong options |
361
+ | `INVALID_ROUTE_CONFIG` | start: a route `config` value a plugin declared with `routeConfig` is wrong, a `config.id` is not an id, or a key looks like a misspelled declared key; every problem is in `details.problems` |
362
+ | `DUPLICATE_ROUTE_ID` | start: one `config.id` is on two routes of one app; `details.duplicates` lists `{ id, routes }`, and `owners` when a plugin's own route is one of them (D-0142, §2.2: each route then names its owner, and `fix` names the `routeIds` option) |
363
+ | `INVALID_ERROR_TRANSLATOR` | setup: a `dokebi-web:error-translator` contribution has no `translate` function (`data.translator` names the plugin); at request time the logged cause of `WEB_ERROR_TRANSLATOR_FAILED` when a translator returns something other than a Dokebi error or undefined |
176
364
  | `INVALID_EXTENSION_RESULT` | an extension hook returned the wrong shape (`fastifyOptions` fails setup; `errorBody` and `unavailable` fall back to the default answer plus error log `WEB_EXTENSION_FAILED`) |
177
- | `FROZEN` | `route`, `register`, `constraint`, `errorResponder` or a seal setting after setup |
365
+ | `FROZEN` | `route`, `register`, `constraint`, `appRouting`, `errorResponder`, `routeConfig`, `routeHook` or a seal setting after setup |
178
366
  | `CLOSED` | `track` after close |
179
367
  | `FORM_BODY_DISABLED` | 415, form bodies are off (`fix` says how to turn them on; warn log) |
180
- | `FORM_BODY_TOO_MANY_FIELDS` | 413, `data.maxFields` |
368
+ | `FORM_BODY_TOO_MANY_FIELDS` | 413, `data.maxFields` (a sealed form too) |
369
+ | `FORM_BODY_INVALID` | 400, a sealed form (`x-dokebi-form`) whose marker is not `1`, whose body is neither sealed nor multipart, or whose opened body is not an object of strings and string arrays (`data.field` names the wrong field) (0.4.3, D-0092) |
181
370
  | `SEAL_PROVIDER_MISSING` | start: sealing is wanted but there is no provider |
182
371
  | `SEAL_PROVIDER_INVALID` | the provider has the wrong shape or was registered twice |
183
- | `SEAL_REQUIRED` | 415, a plain body on a sealed request (answered in plain text) |
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` |
372
+ | `SEAL_REQUIRED` | 415, a plain body on a sealed request (answered in plain text; a urlencoded body says `This page needs its seal script to send forms`, an HTML page for a browser) |
373
+ | `SEAL_BODY_REFUSED` | 400, a sealed body proven bad: no prefix, plain, drift, replay or it does not open (the reason is only in the warn log). Never retried |
374
+ | `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: `Retry-After` from `sealRetryAfterMs` (1 s), `data: { retryable: true, retryAfterMs }`. One record: the store's own `NONCE_STORE_FULL` (dokebi-seal's in-process store and websocket-hub's local store: `max`, `live`, `repeated`, `fix`, once per their `logRepeatWindowMs`); for any other store web's warn `SEAL_BUSY` at the same level (`reason: capacity`, `route`, `fix`: raise dokebi-seal `nonces.max`), once per route per `logRepeatWindowMs`, the rest counted as `repeated`. A capacity refusal, not a fault ([D-0075](https://git.nyx-zone.com/dokebi/framework/-/blob/main/docs/decisions/D-0075-replay-capacity.md) §4): warn, whichever store is plugged in. Never `WEB_REQUEST_FAILED` |
375
+ | `SEAL_NONCE_STORE_UNAVAILABLE` | 503, the seal provider could not check the body: its replay nonce store failed or was too slow (Redis down, its pending-command limit, a timeout), or the codec failed without a client reason ([D-0096](https://git.nyx-zone.com/dokebi/framework/-/blob/main/docs/decisions/D-0096-seal-shared-nonces.md) §2). Refused (fail closed), never answered as the client's fault; retryable like `SEAL_BUSY` (`Retry-After`, `data`), with the codec's `retryAfterMs` when it names one (dokebi-seal: the wait of the @dokebi/redis error behind it, so one Redis outage answers one Retry-After from every plugin), else `sealRetryAfterMs`; one record: for dokebi-seal's shared stores (Redis, the hub) its own error `SEAL_NONCE_STORE_UNAVAILABLE` (driver, timeout, the whole cause; once per its `logRepeatWindowMs`) and none from web; for any other codec failure (no known reason) web's error `WEB_REQUEST_FAILED` with the whole cause (the first per route and window at `transientLogLevel`) |
376
+ | `SEAL_NONCES_LOST` | 503, the seal provider's replay nonce store lost its nonces (a new process with in-process nonces, a Redis restart without persistence, a FLUSHALL) and the body was stamped before that (dokebi-seal reason `nonces-lost`, AI.md §5.3 of @dokebi/seal). Refused, but the server's state: retryable, `Retry-After` from the codec's `retryAfterMs` (the rest of the window; `sealRetryAfterMs` when it gives none), `data: { retryable: true, retryAfterMs }`, warn `SEAL_BODY_REFUSED` with `reason: nonces-lost` (once per route per `logRepeatWindowMs`, the rest counted) and no `WEB_REQUEST_FAILED`: an expected state after a store loss has its one record. A second copy of the same body is `SEAL_BODY_REFUSED` (a replay) |
186
377
  | `SEAL_BODY_NOT_JSON` | 400, the opened body is not JSON |
187
378
  | `SEAL_STREAM_UNSUPPORTED` | 500, JSON for a sealed request was sent as a stream (error log) |
188
379
  | `VALIDATION_FAILED` | 422, a refused body or query string schema, or `validationError()`; `fields` and `errors` in the body |
189
- | `NOT_FOUND` | 404, no route for the method and path |
380
+ | `NOT_FOUND` | 404, no route for the method and path (on this host: an app route or a route bound to other apps is not there, D-0132) |
381
+ | `REQUEST_TIMEOUT` | 408, the request body did not arrive within `requestTimeoutMs` (or the route's `config.requestTimeoutMs`) after its headers (`data.timeoutMs`); debug `HTTP request body timed out` (`code: WEB_REQUEST_TIMEOUT`); the handler that then fails reading the body is not logged as a failure |
382
+ | `OVERLOADED` | 503, the server sheds load (D-0150, §2.5): the last sample of the event loop or memory is above an `overload.*` limit; `Retry-After` from `overload.retryAfterMs`, `data: { reason, retryAfterMs }`, warn or error `WEB_OVERLOADED` (D-0113) |
383
+ | `ROUTE_APP_UNAVAILABLE` | start: a route is bound to apps (`app`, a plugin's `<plugin>.app`) but no app routing is registered (@dokebi/app missing; `data.route`, `data.apps`) (D-0132) |
384
+ | `ROUTE_APP_UNKNOWN` | start: a route is bound to a name that is not an app (`data.app`, `data.apps`) (D-0132) |
385
+ | `ROUTE_APP_CONFLICT` | start: two routes with the same method and path answer on one app (`data.route`, `data.app`) (D-0132) |
386
+ | `VIEW_DATA_CONFLICT` | setup of a collector (@dokebi/app, template-inertia): two plugins contribute one `dokebi-web:view-data` key, a key is the collector's own, or a contribution is not `{ key, value }` (thrown by `collectViewData`) |
387
+
388
+ Option errors are core `INVALID_PLUGIN_OPTIONS` (cause `INVALID_OPTIONS` with paths such as `trustProxy[0]` in `details.issues`). A 500 leaves the `error` log `HTTP request failed` (`code: WEB_REQUEST_FAILED`, `requestId`, `method`, `route` (the route pattern, no query), `status`, `errorCode`, `error` (name, full message, stack and `Caused by:` causes; only URL credentials are removed as `//***@`, cut above 16 KB)). The same route and error is logged once per `logRepeatWindowMs` (10 seconds) and the count in between appears as `repeated` in the next record (D-0047). A 4xx is debug `HTTP request rejected` (`status`, `route`, the full `error` text, `errorCode`). A translated error (D-0093), whatever its status, is the `error` log `HTTP request error translated` (`code: WEB_ERROR_TRANSLATED`, `requestId`, `method`, `route`, `status`, `errorCode`, `translator` (the plugin), `error`: the translated error with the thrown value as its `Caused by:`), once per route, code and 10 seconds with `repeated` like the 500 log, which it replaces. **Retryable 503s under a burst ([D-0113](https://git.nyx-zone.com/dokebi/framework/-/blob/main/docs/decisions/D-0113-overload-log-and-storage-wait.md)).** A translated error that answers 503, and a coded error that answers 503 with `data.retryAfterMs` (`Retry-After`), is an expected refusal: a burst of them must not write a full stack per request (AI-M25: 193,466 records, about 200 MB in 65 s, rotated every other log out). The first one of each status, error code, method and route in a window of `transientLogWindowMs` is logged in full as above (`WEB_ERROR_TRANSLATED` or `WEB_REQUEST_FAILED`, at `transientLogLevel`; not the seal refusals whose own layer writes their one record: `SEAL_NONCES_LOST`, `SEAL_BUSY`, and `SEAL_NONCE_STORE_UNAVAILABLE` of dokebi-seal's shared stores (see the error code table)); the rest are counted, and when the window ends, or when the server closes, one line per pair gives the exact count: `HTTP transient errors repeated` (`code: WEB_TRANSIENT_REPEATED`, `method`, `route`, `status`, `errorCode`, `translator` when translated, `repeated` (the ones after the logged first), `windowMs`). The next window logs its first one in full again. Past `transientLogMaxKeys` pairs in one window, new pairs are only counted, in one `WEB_TRANSIENT_REPEATED` line with `overflow: true`, `repeated`, `maxKeys` and a `fix`. Every other 5xx (a 500, a 503 without `Retry-After`) and a translated 4xx keep the rule above. A translator that throws or returns something else is the `error` log `Web error translator failed` (`code: WEB_ERROR_TRANSLATOR_FAILED`, `route`, `translator`, `fix`, `error`), once per translator, route and interval; the next translator, finally the 500 answer, takes the error. If you register your own error handler, its security is your responsibility.
190
389
 
191
- Option errors are core `INVALID_PLUGIN_OPTIONS` (cause `INVALID_OPTIONS` with paths such as `trustProxy[0]` in `details.issues`). A 500 leaves the `error` log `HTTP request failed` (`code: WEB_REQUEST_FAILED`, `requestId`, `method`, `route` (the route pattern, no query), `status`, `errorCode`, `error` (name, full message, stack and `Caused by:` causes; only URL credentials are removed as `//***@`, cut above 16 KB)). The same route and error is logged once per 10 seconds and the count in between appears as `repeated` in the next record (D-0047). A 4xx is debug `HTTP request rejected` (`status`, `route`, the full `error` text, `errorCode`). If you register your own error handler, its security is your responsibility.
390
+ **A handler that fails after its answer was sent** (an async handler that awaits more work after `reply.send()`, or a hijacked stream) cannot be answered any more: Fastify only tells its own logger, which is off without @dokebi/logger. web logs it at error as `HTTP handler failed after its answer was sent` (`code: WEB_HANDLER_FAILED_AFTER_SEND`, `requestId`, `method`, `route`, `routeId`, `status` (the answer already sent), `errorCode` when the error has one, `fix`, `error`), once per route and error per `logRepeatWindowMs` with `repeated`. With @dokebi/logger's request log (`options.logging.requests`) Fastify's own error record says it instead. Catch errors of such work yourself, or run it with `track()` or a job.
192
391
 
193
- The info log `Web server listening` (`address`, `urls` (every bound address; `localhost` means 127.0.0.1 and ::1), `host`, `ms`) is what `dokebi start` reads to show the address. Debug logs (`DOKEBI_LOG_LEVEL=debug`): `Web server configured` (options, only the number of trustProxy entries, and `schemaCompilers`: `lazy` loads Fastify's default validation and serialization compilers when the first route with a schema appears — about 15 ms faster startup with the same behaviour, header schema names still case-insensitive; `extension` when the extension's `fastifyOptions` supplies a `schemaController`, D-0070), `Web routes frozen`, `Web drain started` (`pending`: requests, handlers, hooks and track work in progress at that moment), `Web worker stopped listening`, `Web drain cut connections`, `Web drain finished`, `Web server closed`; per request `HTTP request refused` (reason, method and path without the query; built only when debug is on), and when a client leaves before the response `HTTP client left before the response` and `HTTP request without client finished`.
392
+ An `onResponse` observer failure is logged at error level as `HTTP response hook failed` (`code: WEB_RESPONSE_HOOK_FAILED`, `route`, `repeated`, full `error` with causes). Failures are limited to one log per route per `logRepeatWindowMs`. Synchronous callbacks avoid intermediate Promises; asynchronous completion still holds drain. A duplicate callback cannot advance the remaining hooks or release the hold twice.
393
+
394
+
395
+ **Fastify's records with @dokebi/logger (D-0151).** Without it Fastify logs nothing (`logger: false`). With @dokebi/logger wired (an optional dependency, met by name) and its `options.logging.requests` true (the default), web gives Fastify a `loggerInstance` that writes through this plugin's context logger, so Fastify's records and Dokebi's are one stream with the same JSON line, redaction, targets and the `dokebi-web` level: one info record per finished request, `HTTP request completed` (`code: WEB_REQUEST_COMPLETED`, `requestId`, `method`, `path` without the query string, `route` (the pattern), `status`, `responseTimeMs`), error `HTTP request errored` for a response that failed while being sent (codes in the AI.md of @dokebi/logger, section 5), and Fastify's own warnings; its `incoming request` record is left out and `Server listening at …` and `Route … not found` go to debug. Request headers, cookies and query values never reach a record. Quiet it with `options.logging.plugins: { dokebi-web: warn }` or `options.logging.requests: false`. An extension's `fastifyOptions` can still replace `loggerInstance`. The debug log `Web server configured` has `requestLog` (true when this is on).
396
+
397
+ The info log `Web server listening` (`address`, `urls` (every bound address; `localhost` means 127.0.0.1 and ::1), `host`, `ms`) is what `dokebi start` reads to show the address. Debug logs (`DOKEBI_LOG_LEVEL=debug`): `Web server configured` (options, only the number of trustProxy entries, and `schemaCompilers`: `lazy` loads Fastify's default validation and serialization compilers when the first route with a schema appears — about 15 ms faster startup with the same behaviour, header schema names still case-insensitive; `extension` when the extension's `fastifyOptions` supplies a `schemaController`, D-0070), `Web route body limit` (`method`, `url`, `bodyLimit` of a route that declares one, D-0122), `Web routes frozen`, `Web route ids checked` (`routes`, `ids`), in a `@dokebi/cluster` worker `Web readiness answers for the cluster` (`slot`, `workers`) and per ready probe that finds workers not ready `Cluster readiness: workers not ready` (`notReady`, `reasons` of those that did not answer) (D-0164), per request (D-0125) `Web response compressed` (`encoding`, `bytes`, `compressed`, `ms`), `Web response stream compressed` (`encoding`, `bytes`, `ms`), `Web response stream compression ended early` (the client left) and `Web compression skipped` (`reason`: `draining` or `not-smaller`), `Web drain started` (`pending`: requests, handlers, hooks and track work in progress at that moment), `Web worker stopped listening`, `Web drain cut connections` (`pending`, `cut`, `ms`), `Web drain told HTTP/2 sessions to go away` (`sessions`), `Web drain closed idle connections` (`pending`, `open`: connections still open when the idle wait ended, `idleMs`), `Web drain finished`, `Web close ended connections without a request` (`ended`, `kept`: connections with a response under way or upgraded), `Web close ended a connection after its response` (`remote`), `Web connection ended: the server is closing` (`remote`), `Web server closed` (`ms`, `endedConnections`); per request (D-0092) `Sealed form body opened` (`method`, `route`, `fields`) and `Sealed form redirect told` (`status`, `target` without the query); per request `HTTP request refused` (reason, method and path without the query; built only when debug is on), and when a client leaves before the response `HTTP client left before the response` and `HTTP request without client finished`.
194
398
 
195
399
  ## 7. Cautions
196
400
 
197
- - Behind a proxy, list **only the proxy addresses** in `trustProxy`; never trust Host or X-Forwarded-* headers yourself, use `requestHost(request)`.
198
- - Authentication, rate limiting, CORS and security headers are Fastify plugins the app chooses (none are built in).
401
+ - Behind a proxy or tunnel, list **only the proxy addresses** in `trustProxy` (§2.6); never trust Host or X-Forwarded-* headers yourself, use `requestHost(request)`.
402
+ - Security headers (§2.4) and overload protection (§2.5) are built in and on. CORS is [@dokebi/cors](https://git.nyx-zone.com/dokebi/framework/-/blob/main/docs/decisions/D-0148-cors.md) (`npx dokebi add @dokebi/cors`); authentication is @dokebi/auth, rate limiting @dokebi/rate-limit. Do not register @fastify/cors, @fastify/helmet or @fastify/under-pressure yourself: the first duplicates @dokebi/cors, the others what web already does.
199
403
  - `requestTimeoutMs` is not a limit on the work. Send long work to job.
200
404
  - Do not treat the end of a response or a client disconnect as the work being done.
405
+ - **Compression and secrets (BREACH, D-0125).** Over HTTPS an attacker who can make a victim's browser send requests and can see response sizes may guess a secret that a compressed page shows next to text the attacker controls (a query echoed into the page). Framework tokens are safe: @dokebi/csrf masks its token anew on every render, session ids travel in cookies (headers are not compressed), and sealed bodies are ciphertexts that are not compressed. For your own secrets that a page shows together with reflected input (an API key on a search results page), set `config: { compress: false }` on that route or call `skipCompression(reply)`.
201
406
 
202
407
  ## 8. Extension (D-0064 §9)
203
408
 
@@ -236,3 +441,7 @@ export default class AppWeb extends WebExtension {
236
441
  - The extension surface (hook signatures and their types) is fingerprinted in `scripts/release/extensions.json`.
237
442
 
238
443
  References: `examples/29-extension` (errorBody, unavailable), `examples/22-web` (API and HTML), `examples/12-cluster` and `24-template-inertia --cluster` (rolling replacement), `examples/21-db` (DB and drain), `examples/25-playground`, D-0034, D-0036, D-0062, D-0068, D-0071.
444
+
445
+ `routeHook` can return `onResponse(request, reply, done)`: a callback hook appended after existing response hooks, including on routes registered earlier. Call `done` once. The response has completed and cannot be changed; `reply.elapsedTime` is milliseconds. Routes left untouched receive no hook.
446
+
447
+ An observer that only reads the finished response returns `completed(request, reply, elapsedMs)` instead (type `WebRouteCompleted`): called synchronously once the response was written, from web's own response tracking, so the route gets no Fastify `onResponse` hook (Fastify adds response listeners and runs its hook chain on every request of a route that has one). Not called when the client left before the response was written (before its head or in its body). `elapsedMs` runs from the request's first `onRequest` step to the response's close. Several observers run in the order their route hooks were registered; a throw is logged at error level as `HTTP response hook failed` (`WEB_RESPONSE_HOOK_FAILED`, counted per route per `logRepeatWindowMs`) and the next observer still runs. Works on routes registered earlier, like `onResponse`. `@dokebi/metrics` uses it for bounded response collection (measured 2026-10-31: `web-metrics/web` 0.943 with `onResponse`, 0.972 with `completed`).