@dokebi/web 0.4.3 → 0.4.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/AI.md CHANGED
@@ -142,6 +142,7 @@ http.route({ method: 'POST', url: '/import', handler: async (request, reply) =>
142
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
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
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: { requestIdleMs } })` | (0.4.5) the longest gap without a byte of this route's body, in whole ms (1..2147483647): a large upload is never cut while bytes keep arriving, a stalled one is 408 `REQUEST_TIMEOUT` one gap after its last byte. With `requestTimeoutMs` too, that still bounds the whole body. Progress is the connection's bytes read (HTTP/2: the session's). A route with it lifts Node's own whole-request bound to the largest timer (web's per-request timers still apply to every route). Checked at start (`INVALID_ROUTE_CONFIG`) |
145
146
  | `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
147
  | `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
148
  | `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 |
@@ -223,6 +224,8 @@ A tunnel or proxy that forwards to this app usually connects from this machine a
223
224
  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
225
  3. **Nothing else**: the tunnel's HTTP Host Header may stay `localhost`; no change on the tunnel side is needed.
225
226
 
227
+ A request Node's HTTP parser refuses gets a bare 400 (408 for a request timeout, 431 for headers too large) before any route, so the request log never shows it. web logs it as `WEB_CLIENT_ERROR` (`error` the parser's code such as `HPE_CLOSED_CONNECTION` or `HPE_INVALID_METHOD`, `reason`, `bytesParsed`, `status`, `remote`; never the request bytes): at **warn** with a `fix` when the peer is in `trustProxy` (your own proxy sent it: its configuration), once per peer, code and `logRepeatWindowMs` with `repeated`; at debug for any other peer. `HPE_CLOSED_CONNECTION` from a proxy means it sent a request on a connection the app had answered with `Connection: close`: send `Connection ""` upstream for keep-alive (as `dokebi deploy proxy --nginx` writes it).
228
+
226
229
  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).
227
230
 
228
231
  ## 3. Start and request blocking
package/dist/index.d.ts CHANGED
@@ -55,6 +55,12 @@ declare module 'fastify' {
55
55
  * is 408 REQUEST_TIMEOUT. Checked at start (INVALID_ROUTE_CONFIG).
56
56
  */
57
57
  requestTimeoutMs?: number;
58
+ /**
59
+ * The longest gap without a byte of this route's request body, in ms: a large upload is never
60
+ * cut while it keeps arriving (with `requestTimeoutMs` too, that bounds the whole body).
61
+ * Past it the answer is 408 REQUEST_TIMEOUT. Checked at start (INVALID_ROUTE_CONFIG).
62
+ */
63
+ requestIdleMs?: number;
58
64
  /**
59
65
  * Security headers of this route (D-0149): `false` sends none (an answer embedded by other
60
66
  * sites on purpose), an object changes some (`{ frameOptions: false, contentSecurityPolicy:
package/dist/index.js CHANGED
@@ -128,6 +128,13 @@ const ERROR_PASS = Symbol('dokebi.web.errorPass');
128
128
  const BODY_TIMER = Symbol('dokebi.web.bodyTimer');
129
129
  /** On the raw request whose body did not arrive in time (answered 408 or cut). */
130
130
  const TIMED_OUT = Symbol('dokebi.web.timedOut');
131
+ /** On a raw request of a route with `config.requestIdleMs`: what its idle timer compares. */
132
+ const BODY_IDLE = Symbol('dokebi.web.bodyIdle');
133
+ /** Bytes the request's connection has read (HTTP/2: the session's socket). */
134
+ function bytesRead(raw) {
135
+ const value = raw.socket?.bytesRead;
136
+ return typeof value === 'number' ? value : 0;
137
+ }
131
138
  /** The error of a body that did not arrive in time: the 408 answer, and what its reader gets. */
132
139
  function bodyTimeout(ms) {
133
140
  return new WebError('REQUEST_TIMEOUT', `The request body did not arrive within ${ms} ms`, {
@@ -413,6 +420,40 @@ class WebOwner {
413
420
  http2: created.http2 === true,
414
421
  logger,
415
422
  });
423
+ // A request Node's HTTP parser refuses (a malformed line, data after `Connection: close`, a
424
+ // header block too large, a request timeout) gets Fastify's bare 400/408/431 before any route,
425
+ // and Fastify records it only at trace. From a peer in trustProxy (the deployment's own
426
+ // proxy) that is a configuration fault to fix: a warning, once per window, peer and code.
427
+ // From any other peer it is debug: an internet client may send anything. The request bytes
428
+ // (`rawPacket`) can hold tokens and are never logged. Prepended: Fastify's own listener
429
+ // answers and destroys the socket, after which its peer address is gone.
430
+ const clientErrors = new Repeats({ intervalMs: options.logRepeatWindowMs });
431
+ this.server.server.prependListener('clientError', (error, socket) => {
432
+ if (error.code === 'ECONNRESET' || socket.destroyed)
433
+ return;
434
+ const peer = plainAddress(socket.remoteAddress ?? '?');
435
+ const proxy = options.trustProxy.includes(peer);
436
+ if (!proxy && !logger.isEnabled('debug'))
437
+ return;
438
+ const code = typeof error.code === 'string' ? error.code : 'UNKNOWN';
439
+ const repeated = proxy ? clientErrors.take(`${peer} ${code}`) : 0;
440
+ if (repeated === undefined)
441
+ return;
442
+ logger.log(proxy ? 'warn' : 'debug', 'A request was refused before any route', {
443
+ code: 'WEB_CLIENT_ERROR',
444
+ error: code,
445
+ ...(typeof error.reason === 'string' ? { reason: error.reason.slice(0, 200) } : {}),
446
+ ...(typeof error.bytesParsed === 'number' ? { bytesParsed: error.bytesParsed } : {}),
447
+ status: code === 'ERR_HTTP_REQUEST_TIMEOUT' ? 408 : code === 'HPE_HEADER_OVERFLOW' ? 431 : 400,
448
+ remote: peer,
449
+ ...(proxy
450
+ ? {
451
+ fix: 'The peer is your proxy (trustProxy): check what it sends upstream. HPE_CLOSED_CONNECTION: it reused a connection the app answered with close (send Connection "" upstream with keepalive, as deploy proxy --nginx writes it).',
452
+ }
453
+ : {}),
454
+ ...(repeated ? { repeated } : {}),
455
+ });
456
+ });
416
457
  const lazySchemas = restoreDefaultCompilers(this.server, created.schemaController, schemaController);
417
458
  const owner = this;
418
459
  logger.log('debug', 'Web server configured', {
@@ -717,14 +758,25 @@ class WebOwner {
717
758
  }
718
759
  // A route's own requestTimeoutMs (an upload route): its first onRequest step times the body
719
760
  // again with it (the global hook ran first, with the dokebi-web option). Checked at start.
720
- const bodyMs = config?.requestTimeoutMs;
721
- if (typeof bodyMs === 'number' && Number.isSafeInteger(bodyMs) && bodyMs >= 1) {
722
- // Node's own request timeout is set past the longest body time at start.
723
- if (bodyMs <= MAX_TIMEOUT_MS)
724
- owner.#longestBodyMs = Math.max(owner.#longestBodyMs, bodyMs);
761
+ // requestIdleMs instead bounds the gaps between bytes (requestTimeoutMs, when set too, the
762
+ // whole body).
763
+ const timing = config;
764
+ const whole = (value) => typeof value === 'number' && Number.isSafeInteger(value) && value >= 1;
765
+ const bodyMs = timing?.requestTimeoutMs;
766
+ const idleMs = timing?.requestIdleMs;
767
+ if (whole(bodyMs) || whole(idleMs)) {
768
+ // Node's own request timeout is set past the longest body time at start (an idle route
769
+ // has no longest time: Node's whole-request bound becomes the largest timer).
770
+ const longest = whole(idleMs)
771
+ ? whole(bodyMs)
772
+ ? bodyMs
773
+ : MAX_TIMEOUT_MS
774
+ : bodyMs;
775
+ if (longest <= MAX_TIMEOUT_MS)
776
+ owner.#longestBodyMs = Math.max(owner.#longestBodyMs, longest);
725
777
  const retime = (request, reply, done) => {
726
778
  if (request.raw[BODY_TIMER] !== undefined)
727
- owner.#timeBody(request, reply, bodyMs);
779
+ owner.#timeBody(request, reply, whole(idleMs) ? idleMs : bodyMs, whole(idleMs) ? (whole(bodyMs) ? bodyMs : undefined) : undefined, whole(idleMs));
728
780
  done();
729
781
  };
730
782
  const fields = route;
@@ -1079,13 +1131,20 @@ class WebOwner {
1079
1131
  this.#release();
1080
1132
  });
1081
1133
  }
1082
- /** The timer of a body that is arriving: `ms` from now (re-armed by a route's own setting). */
1083
- #timeBody(request, reply, ms) {
1134
+ /**
1135
+ * The timer of a body that is arriving: `ms` from now (re-armed by a route's own setting).
1136
+ * `idle`: `ms` is the longest gap without a byte (config.requestIdleMs): the timer re-arms while
1137
+ * the connection keeps reading, up to `wholeMs` when the route bounds the whole body too.
1138
+ */
1139
+ #timeBody(request, reply, ms, wholeMs, idle = false) {
1084
1140
  const raw = request.raw;
1085
1141
  if (raw[BODY_TIMER] === undefined)
1086
1142
  raw.once('end', clearBodyTimer);
1087
1143
  else
1088
1144
  clearTimeout(raw[BODY_TIMER]);
1145
+ raw[BODY_IDLE] = idle
1146
+ ? { bytes: bytesRead(raw), started: performance.now(), wholeMs }
1147
+ : undefined;
1089
1148
  const timer = setTimeout(this.#bodyTimedOut, ms, request, reply, ms);
1090
1149
  timer.unref();
1091
1150
  raw[BODY_TIMER] = timer;
@@ -1100,6 +1159,19 @@ class WebOwner {
1100
1159
  raw[BODY_TIMER] = undefined;
1101
1160
  if (raw.complete || raw.destroyed)
1102
1161
  return;
1162
+ const idle = raw[BODY_IDLE];
1163
+ if (idle !== undefined) {
1164
+ const bytes = bytesRead(raw);
1165
+ const within = idle.wholeMs === undefined || performance.now() - idle.started < idle.wholeMs;
1166
+ // Bytes arrived since the timer was armed: the body is still coming, wait another gap.
1167
+ if (bytes > idle.bytes && within) {
1168
+ idle.bytes = bytes;
1169
+ const timer = setTimeout(this.#bodyTimedOut, ms, request, reply, ms);
1170
+ timer.unref();
1171
+ raw[BODY_TIMER] = timer;
1172
+ return;
1173
+ }
1174
+ }
1103
1175
  raw[TIMED_OUT] = ms;
1104
1176
  const answered = reply.sent || reply.raw.headersSent;
1105
1177
  if (this.context.logger.isEnabled('debug'))
@@ -2424,7 +2496,7 @@ class WebRuntime {
2424
2496
  }
2425
2497
  export const createPlugin = definePlugin({
2426
2498
  name: 'dokebi-web',
2427
- version: '0.4.3',
2499
+ version: '0.4.5',
2428
2500
  core: '^0.4.2',
2429
2501
  options: declaration,
2430
2502
  entry: (input) => new WebEntryInput(input),
@@ -28,7 +28,7 @@ export declare function routeIdProblem(value: unknown): string | undefined;
28
28
  export declare const MAX_TIMEOUT_MS = 2147483647;
29
29
  export declare class RouteConfigKeys {
30
30
  #private;
31
- /** Keys declared by other plugins (dokebi-web's own six not counted). */
31
+ /** Keys declared by other plugins (dokebi-web's own seven not counted). */
32
32
  get size(): number;
33
33
  add(definition: WebRouteConfigKey): void;
34
34
  /** Called from onRoute for every route (start-up cost only). */
@@ -70,6 +70,17 @@ const REQUEST_TIMEOUT_KEY = Object.freeze({
70
70
  ? undefined
71
71
  : `must be whole milliseconds from 1 to ${MAX_TIMEOUT_MS} (the time this route's body may take to arrive), not ${value === null ? 'null' : typeof value === 'number' ? value : typeof value}`,
72
72
  });
73
+ /**
74
+ * `config.requestIdleMs` (2026-11-07): this route's body may take any time while bytes keep
75
+ * arriving; a gap of this many ms without a byte is 408 (a large upload over a slow link).
76
+ */
77
+ const REQUEST_IDLE_KEY = Object.freeze({
78
+ key: 'requestIdleMs',
79
+ plugin: 'dokebi-web',
80
+ check: (value) => typeof value === 'number' && Number.isInteger(value) && value >= 1 && value <= MAX_TIMEOUT_MS
81
+ ? undefined
82
+ : `must be whole milliseconds from 1 to ${MAX_TIMEOUT_MS} (the longest gap without a byte of this route's body), not ${value === null ? 'null' : typeof value === 'number' ? value : typeof value}`,
83
+ });
73
84
  /**
74
85
  * Options of `web.route()` itself that read like route config keys. The per-route switches
75
86
  * `overload`, `readiness`, `compress`, `securityHeaders` and `requestTimeoutMs` live in `config`;
@@ -89,11 +100,12 @@ export class RouteConfigKeys {
89
100
  ['overload', OVERLOAD_KEY],
90
101
  ['readiness', READINESS_KEY],
91
102
  ['requestTimeoutMs', REQUEST_TIMEOUT_KEY],
103
+ ['requestIdleMs', REQUEST_IDLE_KEY],
92
104
  ]);
93
105
  #routes = [];
94
- /** Keys declared by other plugins (dokebi-web's own six not counted). */
106
+ /** Keys declared by other plugins (dokebi-web's own seven not counted). */
95
107
  get size() {
96
- return this.#keys.size - 6;
108
+ return this.#keys.size - 7;
97
109
  }
98
110
  add(definition) {
99
111
  const { key, plugin, check, routes } = (definition ?? {});
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dokebi/web",
3
- "version": "0.4.3",
3
+ "version": "0.4.5",
4
4
  "description": "Fastify 5 HTTP server owned by a Dokebi app: 503 before ready, health routes, drain and cluster handover.",
5
5
  "keywords": [
6
6
  "dokebi",