@dokebi/web 0.1.2 → 0.4.0
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 +191 -45
- package/README.md +59 -33
- package/dist/compilers.d.ts +9 -0
- package/dist/compilers.js +58 -0
- package/dist/dependency.d.ts +4 -0
- package/dist/dependency.js +14 -0
- package/dist/errors.d.ts +40 -0
- package/dist/errors.js +106 -0
- package/dist/extension.d.ts +95 -0
- package/dist/extension.js +52 -0
- package/dist/index.d.ts +50 -8
- package/dist/index.js +766 -285
- package/dist/install.d.ts +25 -0
- package/dist/install.js +23 -0
- package/dist/options.d.ts +19 -0
- package/dist/options.js +92 -0
- package/dist/points.d.ts +53 -0
- package/dist/points.js +5 -0
- package/dist/responses.d.ts +80 -0
- package/dist/responses.js +246 -0
- package/dist/seal.d.ts +83 -0
- package/dist/seal.js +273 -0
- package/options.schema.json +68 -14
- package/package.json +43 -13
- package/templates/extension.ts +14 -0
package/dist/index.js
CHANGED
|
@@ -1,162 +1,54 @@
|
|
|
1
|
-
import
|
|
2
|
-
import {
|
|
1
|
+
import { createHmac } from 'node:crypto';
|
|
2
|
+
import { Server } from 'node:net';
|
|
3
|
+
import { parse as parseQuery } from 'node:querystring';
|
|
3
4
|
import { setTimeout as delay, setImmediate as immediate } from 'node:timers/promises';
|
|
4
5
|
import { types } from 'node:util';
|
|
5
|
-
import { definePlugin, dependencyOf,
|
|
6
|
+
import { createExtension, definePlugin, definePoint, dependencyOf, EXTENSION_BRAND, optionalDependency, } from '@dokebi/core';
|
|
7
|
+
import { diagnostics } from '@dokebi/core/libraries';
|
|
6
8
|
import Fastify, {} from 'fastify';
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
}
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
input.length > 64 ||
|
|
22
|
-
!input.every((item) => typeof item === 'string' && isIP(item)))
|
|
23
|
-
throw new WebError('INVALID_OPTIONS');
|
|
24
|
-
return Object.freeze([...new Set(input.map((item) => plainAddress(item)))]);
|
|
25
|
-
}
|
|
26
|
-
const DEFAULT_HEALTH_ROUTES = Object.freeze({
|
|
27
|
-
live: '/health/live',
|
|
28
|
-
ready: '/health/ready',
|
|
29
|
-
});
|
|
30
|
-
/** Copies own string-keyed data properties; Proxies and accessors are rejected unevaluated. */
|
|
31
|
-
function dataRecord(input, keys) {
|
|
32
|
-
if (!input ||
|
|
33
|
-
typeof input !== 'object' ||
|
|
34
|
-
Array.isArray(input) ||
|
|
35
|
-
types.isProxy(input) ||
|
|
36
|
-
![Object.prototype, null].includes(Object.getPrototypeOf(input)))
|
|
37
|
-
return undefined;
|
|
38
|
-
const result = Object.create(null);
|
|
39
|
-
for (const key of Reflect.ownKeys(input)) {
|
|
40
|
-
const descriptor = Object.getOwnPropertyDescriptor(input, key);
|
|
41
|
-
if (typeof key !== 'string' || !descriptor || !('value' in descriptor) || !keys.includes(key))
|
|
42
|
-
return undefined;
|
|
43
|
-
result[key] = descriptor.value;
|
|
44
|
-
}
|
|
45
|
-
return result;
|
|
46
|
-
}
|
|
47
|
-
const ROUTE_PATH = /^\/[^?#\s]{0,2047}$/;
|
|
9
|
+
import { lazyCompilers, restoreDefaultCompilers } from './compilers.js';
|
|
10
|
+
import { WebError } from './errors.js';
|
|
11
|
+
import { WebExtension, webHooks, } from './extension.js';
|
|
12
|
+
import { options as declaration } from './options.js';
|
|
13
|
+
import { errorAnswer, errorFormat, errorPage, productionBody, sendableDetails, validAnswer, } from './responses.js';
|
|
14
|
+
import { checkSealSetting, sealExclude, WebSealing, } from './seal.js';
|
|
15
|
+
export { validationError, WebError, WebValidationError, } from './errors.js';
|
|
16
|
+
export { WebExtension, } from './extension.js';
|
|
17
|
+
export { options } from './options.js';
|
|
18
|
+
export { errorFormat, } from './responses.js';
|
|
19
|
+
export { SEALED_PATH_HEADER, } from './seal.js';
|
|
20
|
+
/** Set by `dokebi verify` on the app it starts (D-0065 §11); the header echoes it. */
|
|
21
|
+
const VERIFY_TOKEN_ENV = 'DOKEBI_VERIFY_TOKEN';
|
|
22
|
+
const VERIFY_HEADER = 'x-dokebi-verify';
|
|
48
23
|
/**
|
|
49
|
-
*
|
|
50
|
-
*
|
|
51
|
-
*
|
|
24
|
+
* Set by `dokebi start` on the app (D-0073): a request with a challenge in this header gets
|
|
25
|
+
* HMAC-SHA256(token, challenge) back in it, so `dokebi stop` and `status` can prove a recorded pid
|
|
26
|
+
* is this app where `ps` is unavailable. The token itself never goes on the wire.
|
|
52
27
|
*/
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
text = `NonError: ${String(current)}`; // not serialisable (cycle, BigInt): its string form
|
|
68
|
-
}
|
|
69
|
-
}
|
|
70
|
-
parts.push(depth ? `Caused by: ${text}` : text);
|
|
71
|
-
current = current instanceof Error ? current.cause : undefined;
|
|
72
|
-
}
|
|
73
|
-
const text = parts.join('\n').replace(/\/\/[^\s/@]*@/g, '//***@');
|
|
74
|
-
return text.length > 16_384
|
|
75
|
-
? `${text.slice(0, 16_384)}… [truncated ${text.length - 16_384} characters]`
|
|
76
|
-
: text;
|
|
77
|
-
}
|
|
78
|
-
/** How often a repeating error of the same kind is logged; repeats in between are counted. */
|
|
79
|
-
const REPEAT_INTERVAL_MS = 10_000;
|
|
80
|
-
/**
|
|
81
|
-
* Counts repeats of the same error key so a hot path logs it once per interval (D-0047). The
|
|
82
|
-
* first occurrence is logged; later ones inside the interval are only counted and reported with
|
|
83
|
-
* the next logged occurrence of that key.
|
|
84
|
-
*/
|
|
85
|
-
class Repeats {
|
|
86
|
-
#keys = new Map();
|
|
87
|
-
/** The repeats to report with this occurrence, or undefined when it is only counted. */
|
|
88
|
-
take(key, now = Date.now()) {
|
|
89
|
-
const entry = this.#keys.get(key);
|
|
90
|
-
if (entry && now < entry.until) {
|
|
91
|
-
entry.repeated++;
|
|
92
|
-
return undefined;
|
|
93
|
-
}
|
|
94
|
-
if (!entry && this.#keys.size >= 256)
|
|
95
|
-
this.#keys.clear();
|
|
96
|
-
this.#keys.set(key, { until: now + REPEAT_INTERVAL_MS, repeated: 0 });
|
|
97
|
-
return entry?.repeated ?? 0;
|
|
98
|
-
}
|
|
28
|
+
const INSTANCE_TOKEN_ENV = 'DOKEBI_INSTANCE_TOKEN';
|
|
29
|
+
const INSTANCE_HEADER = 'x-dokebi-instance';
|
|
30
|
+
const INSTANCE_TOKEN = /^[A-Za-z0-9_-]{16,128}$/;
|
|
31
|
+
const INSTANCE_CHALLENGE = /^[A-Za-z0-9_-]{16,128}$/;
|
|
32
|
+
const { describeError, Repeats } = diagnostics;
|
|
33
|
+
const EXTENSION_FILE = 'src/infra/web/extension.ts';
|
|
34
|
+
/** IPv4-mapped IPv6 (`::ffff:127.0.0.1`) compares as plain IPv4. */
|
|
35
|
+
const plainAddress = (address) => address.replace(/^::ffff:(?=\d+\.\d+\.\d+\.\d+$)/, '');
|
|
36
|
+
function settings(parsed) {
|
|
37
|
+
return Object.freeze({
|
|
38
|
+
...parsed,
|
|
39
|
+
trustProxy: Object.freeze([...new Set(parsed.trustProxy.map(plainAddress))]),
|
|
40
|
+
sealExclude: sealExclude(parsed.sealExclude),
|
|
41
|
+
});
|
|
99
42
|
}
|
|
43
|
+
/** Fastify creation options that belong to the drain contract (D-0023, D-0036). */
|
|
44
|
+
const PINNED = Object.freeze({ return503OnClosing: true, forceCloseConnections: 'idle' });
|
|
45
|
+
const FORM_TYPE = 'application/x-www-form-urlencoded';
|
|
100
46
|
/**
|
|
101
47
|
* How long a draining node:cluster worker stays up after it stops listening: enough for any
|
|
102
48
|
* connection the primary was already handing it to be answered "not accepted" and passed on.
|
|
103
49
|
*/
|
|
104
50
|
const CLOSE_GRACE_MS = 100;
|
|
105
|
-
|
|
106
|
-
if (input === undefined)
|
|
107
|
-
return DEFAULT_HEALTH_ROUTES;
|
|
108
|
-
if (input === false)
|
|
109
|
-
return false;
|
|
110
|
-
const value = dataRecord(input, ['live', 'ready']);
|
|
111
|
-
if (!value)
|
|
112
|
-
throw new WebError('INVALID_OPTIONS');
|
|
113
|
-
const live = value.live === undefined ? DEFAULT_HEALTH_ROUTES.live : value.live;
|
|
114
|
-
const ready = value.ready === undefined ? DEFAULT_HEALTH_ROUTES.ready : value.ready;
|
|
115
|
-
if (typeof live !== 'string' ||
|
|
116
|
-
typeof ready !== 'string' ||
|
|
117
|
-
!ROUTE_PATH.test(live) ||
|
|
118
|
-
!ROUTE_PATH.test(ready) ||
|
|
119
|
-
live === ready)
|
|
120
|
-
throw new WebError('INVALID_OPTIONS');
|
|
121
|
-
return Object.freeze({ live, ready });
|
|
122
|
-
}
|
|
123
|
-
function normalize(input) {
|
|
124
|
-
const value = dataRecord(input, [
|
|
125
|
-
'host',
|
|
126
|
-
'port',
|
|
127
|
-
'bodyLimit',
|
|
128
|
-
'requestTimeout',
|
|
129
|
-
'healthRoutes',
|
|
130
|
-
'trustProxy',
|
|
131
|
-
]);
|
|
132
|
-
if (!value)
|
|
133
|
-
throw new WebError('INVALID_OPTIONS');
|
|
134
|
-
const host = value.host === undefined ? '127.0.0.1' : value.host, port = value.port === undefined ? 0 : value.port, bodyLimit = value.bodyLimit === undefined ? 1048576 : value.bodyLimit, requestTimeout = value.requestTimeout === undefined ? 30000 : value.requestTimeout;
|
|
135
|
-
if (typeof host !== 'string' ||
|
|
136
|
-
!host ||
|
|
137
|
-
host.length > 253 ||
|
|
138
|
-
typeof port !== 'number' ||
|
|
139
|
-
!Number.isInteger(port) ||
|
|
140
|
-
port < 0 ||
|
|
141
|
-
port > 65535 ||
|
|
142
|
-
typeof bodyLimit !== 'number' ||
|
|
143
|
-
!Number.isSafeInteger(bodyLimit) ||
|
|
144
|
-
bodyLimit < 1 ||
|
|
145
|
-
bodyLimit > 67108864 ||
|
|
146
|
-
typeof requestTimeout !== 'number' ||
|
|
147
|
-
!Number.isSafeInteger(requestTimeout) ||
|
|
148
|
-
requestTimeout < 1 ||
|
|
149
|
-
requestTimeout > 2147483647)
|
|
150
|
-
throw new WebError('INVALID_OPTIONS');
|
|
151
|
-
return {
|
|
152
|
-
host,
|
|
153
|
-
port,
|
|
154
|
-
bodyLimit,
|
|
155
|
-
requestTimeout,
|
|
156
|
-
healthRoutes: healthRoutes(value.healthRoutes),
|
|
157
|
-
trustProxy: trustProxy(value.trustProxy),
|
|
158
|
-
};
|
|
159
|
-
}
|
|
51
|
+
const injectPoint = definePoint('dokebi-testing:inject');
|
|
160
52
|
const hooks = new Map([
|
|
161
53
|
['onRequest', 2],
|
|
162
54
|
['preParsing', 3],
|
|
@@ -169,77 +61,232 @@ const hooks = new Map([
|
|
|
169
61
|
['onTimeout', 2],
|
|
170
62
|
['onRequestAbort', 1],
|
|
171
63
|
]);
|
|
64
|
+
/**
|
|
65
|
+
* Hooks that may run after the response is finished or the client is gone, so the request's own
|
|
66
|
+
* hold no longer covers them: only these are wrapped for drain tracking (D-0068). Request-phase
|
|
67
|
+
* hooks (onRequest … onSend) always run while the request is held.
|
|
68
|
+
*/
|
|
69
|
+
const RESPONSE_HOOKS = new Set(['onResponse', 'onError', 'onTimeout', 'onRequestAbort']);
|
|
70
|
+
/** Per-response marks on the raw ServerResponse (no per-request object, D-0068). */
|
|
71
|
+
const REPLY = Symbol('dokebi.web.reply');
|
|
72
|
+
const HANDLER = Symbol('dokebi.web.handler');
|
|
73
|
+
const SENDING = Symbol('dokebi.web.sending');
|
|
74
|
+
const ABORTED = Symbol('dokebi.web.aborted');
|
|
75
|
+
function thenable(value) {
|
|
76
|
+
return (value !== null &&
|
|
77
|
+
(typeof value === 'object' || typeof value === 'function') &&
|
|
78
|
+
typeof value.then === 'function');
|
|
79
|
+
}
|
|
80
|
+
/**
|
|
81
|
+
* A request whose client went away before its response was written (rare). The request stays
|
|
82
|
+
* held until Fastify's chain for it ends: it writes the response head (an error or a late
|
|
83
|
+
* reply), pipes a stream into it, or the handler settled and nothing is being sent. Until then
|
|
84
|
+
* hooks and the handler of that request may still be running (D-0023: a disconnect alone never
|
|
85
|
+
* ends work).
|
|
86
|
+
*/
|
|
87
|
+
class AbortedResponse {
|
|
88
|
+
response;
|
|
89
|
+
release;
|
|
90
|
+
#released = false;
|
|
91
|
+
constructor(response, release) {
|
|
92
|
+
this.response = response;
|
|
93
|
+
this.release = release;
|
|
94
|
+
const watch = this;
|
|
95
|
+
const writeHead = response.writeHead;
|
|
96
|
+
const end = response.end;
|
|
97
|
+
// Instance properties of this one response only; the prototype is untouched.
|
|
98
|
+
response.writeHead = function (...args) {
|
|
99
|
+
watch.done('write');
|
|
100
|
+
return writeHead.apply(this, args);
|
|
101
|
+
};
|
|
102
|
+
response.end = function (...args) {
|
|
103
|
+
watch.done('end');
|
|
104
|
+
return end.apply(this, args);
|
|
105
|
+
};
|
|
106
|
+
response.once('pipe', () => watch.done('pipe'));
|
|
107
|
+
const handler = response[HANDLER];
|
|
108
|
+
if (handler !== undefined)
|
|
109
|
+
this.handler(handler);
|
|
110
|
+
}
|
|
111
|
+
/** The route handler was reached (now or before the client left). */
|
|
112
|
+
handler(result) {
|
|
113
|
+
const settled = () => {
|
|
114
|
+
// Fastify sends a resolved value in the same turn; nothing started sending by the next
|
|
115
|
+
// macrotask means it never will (an undefined result after the client left).
|
|
116
|
+
setImmediate(() => {
|
|
117
|
+
if (!this.response[SENDING])
|
|
118
|
+
this.done('handler');
|
|
119
|
+
});
|
|
120
|
+
};
|
|
121
|
+
if (thenable(result))
|
|
122
|
+
result.then(settled, settled);
|
|
123
|
+
else
|
|
124
|
+
settled();
|
|
125
|
+
}
|
|
126
|
+
done(reason) {
|
|
127
|
+
if (this.#released)
|
|
128
|
+
return;
|
|
129
|
+
this.#released = true;
|
|
130
|
+
this.release(reason);
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
/** The message of the built-in 503 page per refusal reason. */
|
|
134
|
+
const UNAVAILABLE = {
|
|
135
|
+
STARTING: 'The application is starting. Try again in a moment.',
|
|
136
|
+
NOT_READY: 'The application is not ready. Try again in a moment.',
|
|
137
|
+
DRAINING: 'The application is restarting. Try again in a moment.',
|
|
138
|
+
};
|
|
139
|
+
/** A usable `unavailable` result: a 4xx/5xx status, string headers, synchronous. */
|
|
140
|
+
function validRefusal(value) {
|
|
141
|
+
if (value === null || typeof value !== 'object' || 'then' in value)
|
|
142
|
+
return false;
|
|
143
|
+
const { status, headers } = value;
|
|
144
|
+
return (typeof status === 'number' &&
|
|
145
|
+
Number.isInteger(status) &&
|
|
146
|
+
status >= 400 &&
|
|
147
|
+
status <= 599 &&
|
|
148
|
+
(headers === undefined ||
|
|
149
|
+
(headers !== null &&
|
|
150
|
+
typeof headers === 'object' &&
|
|
151
|
+
Object.values(headers).every((item) => typeof item === 'string'))));
|
|
152
|
+
}
|
|
172
153
|
class WebOwner {
|
|
173
154
|
context;
|
|
174
155
|
options;
|
|
175
156
|
server;
|
|
176
|
-
|
|
157
|
+
/** Requests, handlers, response-phase hooks and track() work still running. */
|
|
158
|
+
#inflight = 0;
|
|
159
|
+
/** Resolved when #inflight reaches 0; only created while draining waits. */
|
|
160
|
+
#idle;
|
|
161
|
+
#release = () => {
|
|
162
|
+
if (--this.#inflight === 0 && this.#idle) {
|
|
163
|
+
const { resolve } = this.#idle;
|
|
164
|
+
this.#idle = undefined;
|
|
165
|
+
resolve();
|
|
166
|
+
}
|
|
167
|
+
};
|
|
177
168
|
#wrapped = new WeakSet();
|
|
178
169
|
#closed = false;
|
|
179
170
|
#frozen = false;
|
|
180
171
|
#draining = false;
|
|
181
172
|
#address;
|
|
173
|
+
#sealing;
|
|
174
|
+
/** Error responders, the last added first (D-0074). */
|
|
175
|
+
#responders = [];
|
|
182
176
|
api;
|
|
183
|
-
|
|
177
|
+
/** A node:cluster worker (D-0063 `context.runtime`): it listens from `ready` and drains first. */
|
|
178
|
+
#worker;
|
|
179
|
+
/** Error bodies without `fix`, `details` and 5xx messages (D-0063 §1). */
|
|
180
|
+
#production;
|
|
181
|
+
#hooks;
|
|
182
|
+
#overridden;
|
|
183
|
+
#https;
|
|
184
|
+
constructor(context, options, extension, health) {
|
|
184
185
|
this.context = context;
|
|
185
186
|
this.options = options;
|
|
186
|
-
|
|
187
|
+
const logger = context.logger;
|
|
188
|
+
const runtime = context.runtime ?? context.app.runtime;
|
|
189
|
+
this.#worker = runtime.role === 'worker';
|
|
190
|
+
this.#production = process.env.NODE_ENV === 'production' || !options.developmentErrors;
|
|
191
|
+
this.#hooks = extension.hooks;
|
|
192
|
+
this.#overridden = extension.overridden;
|
|
193
|
+
// Fastify's schema compilers are loaded when a route first needs one (compilers.ts).
|
|
194
|
+
const schemaController = lazyCompilers();
|
|
195
|
+
const defaults = {
|
|
187
196
|
logger: false,
|
|
188
|
-
bodyLimit: options.
|
|
189
|
-
requestTimeout: options.
|
|
190
|
-
|
|
191
|
-
|
|
197
|
+
bodyLimit: options.maxBodyBytes,
|
|
198
|
+
requestTimeout: options.requestTimeoutMs,
|
|
199
|
+
schemaController,
|
|
200
|
+
...PINNED,
|
|
192
201
|
...(options.trustProxy.length ? { trustProxy: [...options.trustProxy] } : {}),
|
|
193
|
-
}
|
|
202
|
+
};
|
|
203
|
+
const created = this.#fastifyOptions(defaults);
|
|
204
|
+
this.#https = Boolean(created.https);
|
|
205
|
+
// HTTPS and HTTP/2 change only the raw server type; the API is typed for the default one.
|
|
206
|
+
this.server = Fastify(created);
|
|
207
|
+
const lazySchemas = restoreDefaultCompilers(this.server, created.schemaController, schemaController);
|
|
194
208
|
const owner = this;
|
|
195
|
-
|
|
209
|
+
logger.log('debug', 'Web server configured', {
|
|
196
210
|
host: options.host,
|
|
197
211
|
port: options.port,
|
|
198
|
-
bodyLimit: options.
|
|
199
|
-
requestTimeout: options.
|
|
212
|
+
bodyLimit: options.maxBodyBytes,
|
|
213
|
+
requestTimeout: options.requestTimeoutMs,
|
|
200
214
|
healthRoutes: options.healthRoutes ? { ...options.healthRoutes } : false,
|
|
201
215
|
trustProxy: options.trustProxy.length,
|
|
216
|
+
sealDriftMs: options.sealDriftMs,
|
|
217
|
+
sealExclude: options.sealExclude.length,
|
|
218
|
+
formBody: options.formBody,
|
|
219
|
+
formMaxFields: options.formMaxFields,
|
|
220
|
+
errorBodies: this.#production ? 'production' : 'development',
|
|
202
221
|
health: health !== undefined,
|
|
203
|
-
|
|
222
|
+
// `lazy`: Fastify's default compilers, loaded on the first schema route (D-0070 §5).
|
|
223
|
+
schemaCompilers: lazySchemas ? 'lazy' : 'extension',
|
|
224
|
+
role: runtime.role,
|
|
225
|
+
serving: runtime.serving,
|
|
226
|
+
extension: [...this.#overridden],
|
|
227
|
+
...(created === defaults ? {} : { fastifyOptions: Object.keys(created).sort() }),
|
|
204
228
|
});
|
|
205
229
|
const failures = new Repeats();
|
|
206
|
-
this.server.setErrorHandler((error, request, reply) =>
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
230
|
+
this.server.setErrorHandler((error, request, reply) => this.#fail(error, request, reply, failures));
|
|
231
|
+
// An unknown route answers like any other error (D-0074): the same body, format and
|
|
232
|
+
// responders (an app's errors/404.ejs), not Fastify's own `{ message, error, statusCode }`.
|
|
233
|
+
this.server.setNotFoundHandler((request, reply) => this.#fail(new WebError('NOT_FOUND', `No route for ${request.method} ${request.url.split('?', 1)[0]?.slice(0, 200)}`), request, reply, failures));
|
|
234
|
+
// D-0062: the seal slot. Its hook steps do nothing until something asks for sealing.
|
|
235
|
+
const sealing = new WebSealing(logger, { driftMs: options.sealDriftMs, exclude: options.sealExclude }, (request) => this.api.requestHost(request));
|
|
236
|
+
this.#sealing = sealing;
|
|
237
|
+
// A request is held from here until its response closes (D-0068): one counter and one shared
|
|
238
|
+
// listener, no Promise or closure per request. Callback style: no Promise per hook either.
|
|
239
|
+
const closed = function () {
|
|
240
|
+
owner.#responseClosed(this);
|
|
241
|
+
};
|
|
242
|
+
const worker = this.#worker;
|
|
243
|
+
// `dokebi verify` (D-0065 §11) starts the app with a random token and accepts only answers
|
|
244
|
+
// that echo it, so another project's server on the same port is not taken for this app.
|
|
245
|
+
// Without the variable (every normal start) no hook exists: nothing per request.
|
|
246
|
+
const verifyToken = process.env[VERIFY_TOKEN_ENV];
|
|
247
|
+
if (verifyToken !== undefined) {
|
|
248
|
+
if (/^[A-Za-z0-9_-]{8,128}$/.test(verifyToken)) {
|
|
249
|
+
logger.log('debug', 'Verify instance header enabled', { header: VERIFY_HEADER });
|
|
250
|
+
this.server.addHook('onRequest', (_request, reply, done) => {
|
|
251
|
+
reply.header(VERIFY_HEADER, verifyToken);
|
|
252
|
+
done();
|
|
253
|
+
});
|
|
223
254
|
}
|
|
224
|
-
else
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
route: request.routeOptions.url ?? 'unmatched',
|
|
229
|
-
error: errorText(error),
|
|
230
|
-
errorCode: error?.code,
|
|
255
|
+
else
|
|
256
|
+
logger.log('warn', 'Verify token ignored: unexpected format', {
|
|
257
|
+
code: 'VERIFY_TOKEN_INVALID',
|
|
258
|
+
variable: VERIFY_TOKEN_ENV,
|
|
231
259
|
});
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
260
|
+
}
|
|
261
|
+
// `dokebi start` (D-0073): answer the instance challenge before anything else runs (no route,
|
|
262
|
+
// no app code). Without the variable (dev, tests, other process managers) no hook exists.
|
|
263
|
+
const instanceToken = process.env[INSTANCE_TOKEN_ENV];
|
|
264
|
+
if (instanceToken !== undefined) {
|
|
265
|
+
if (INSTANCE_TOKEN.test(instanceToken)) {
|
|
266
|
+
logger.log('debug', 'Instance challenge enabled', { header: INSTANCE_HEADER });
|
|
267
|
+
this.server.addHook('onRequest', (request, reply, done) => {
|
|
268
|
+
const challenge = request.headers[INSTANCE_HEADER];
|
|
269
|
+
if (typeof challenge !== 'string' || !INSTANCE_CHALLENGE.test(challenge))
|
|
270
|
+
return done();
|
|
271
|
+
reply
|
|
272
|
+
.header(INSTANCE_HEADER, createHmac('sha256', instanceToken).update(challenge).digest('base64url'))
|
|
273
|
+
.code(204)
|
|
274
|
+
.send();
|
|
275
|
+
});
|
|
276
|
+
}
|
|
277
|
+
else
|
|
278
|
+
logger.log('warn', 'Instance token ignored: unexpected format', {
|
|
279
|
+
code: 'INSTANCE_TOKEN_INVALID',
|
|
280
|
+
variable: INSTANCE_TOKEN_ENV,
|
|
281
|
+
});
|
|
282
|
+
}
|
|
283
|
+
this.server.addHook('onRequest', (request, reply, done) => {
|
|
237
284
|
if (request.routeOptions.config.dokebiHealth === true)
|
|
238
|
-
return;
|
|
285
|
+
return done();
|
|
239
286
|
// A draining node:cluster worker no longer listens; a request still arriving on one of its
|
|
240
287
|
// open keep-alive connections is served and that connection then closes, so the client's
|
|
241
288
|
// next request goes to another worker instead of seeing 503 (D-0036).
|
|
242
|
-
const servesWhileDraining = this.#draining &&
|
|
289
|
+
const servesWhileDraining = this.#draining && worker;
|
|
243
290
|
if (servesWhileDraining)
|
|
244
291
|
reply.header('connection', 'close');
|
|
245
292
|
const reason = this.#draining
|
|
@@ -252,46 +299,54 @@ class WebOwner {
|
|
|
252
299
|
? 'NOT_READY'
|
|
253
300
|
: undefined;
|
|
254
301
|
if (reason) {
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
context.logger.log('debug', 'HTTP request refused', {
|
|
258
|
-
reason,
|
|
259
|
-
method: request.method,
|
|
260
|
-
url: request.url.split('?', 1)[0]?.slice(0, 200),
|
|
261
|
-
});
|
|
262
|
-
return reply
|
|
263
|
-
.code(503)
|
|
264
|
-
.header('connection', 'close')
|
|
265
|
-
.send({ error: 'SERVICE_UNAVAILABLE', reason });
|
|
302
|
+
this.#refuse(request, reply, reason);
|
|
303
|
+
return;
|
|
266
304
|
}
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
reply.raw.off('close', finish);
|
|
274
|
-
release();
|
|
275
|
-
if (this.#draining && cluster.isWorker)
|
|
276
|
-
this.server.server.closeIdleConnections();
|
|
277
|
-
};
|
|
278
|
-
reply.raw.once('finish', finish);
|
|
279
|
-
reply.raw.once('close', finish);
|
|
280
|
-
this.#watch(done);
|
|
305
|
+
const raw = reply.raw;
|
|
306
|
+
this.#inflight++;
|
|
307
|
+
raw[REPLY] = reply;
|
|
308
|
+
raw.on('close', closed);
|
|
309
|
+
// A sealed request with a plain body is answered 415 here, before any parser (D-0062).
|
|
310
|
+
done(sealing.provider ? sealing.refusePlain(request) : undefined);
|
|
281
311
|
});
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
312
|
+
this.server.addHook('onSend', (request, reply, payload, done) => {
|
|
313
|
+
reply.raw[SENDING] = true;
|
|
314
|
+
// Responses already under way when a cluster worker starts draining close their
|
|
315
|
+
// connection too, instead of leaving it idle for the client to reuse (D-0036).
|
|
316
|
+
if (this.#draining && worker)
|
|
286
317
|
reply.header('connection', 'close');
|
|
287
|
-
|
|
318
|
+
done(null, sealing.provider ? sealing.onSend(request, reply, payload) : payload);
|
|
288
319
|
});
|
|
320
|
+
this.#formBody(options);
|
|
289
321
|
this.server.addHook('onRoute', (route) => {
|
|
290
|
-
|
|
322
|
+
// `seal` on a route given to Fastify directly (a register() scope, @dokebi/router mount)
|
|
323
|
+
// becomes `config.dokebiSeal` too, so every way of adding a route can opt out (D-0062).
|
|
324
|
+
const options = route;
|
|
325
|
+
if (options.seal !== undefined) {
|
|
326
|
+
options.config = {
|
|
327
|
+
...route.config,
|
|
328
|
+
dokebiSeal: checkSealSetting(options.seal),
|
|
329
|
+
};
|
|
330
|
+
delete options.seal;
|
|
331
|
+
}
|
|
332
|
+
const config = route.config;
|
|
333
|
+
sealing.route(checkSealSetting(config?.dokebiSeal));
|
|
334
|
+
if (config?.dokebiHealth === true)
|
|
291
335
|
return;
|
|
292
336
|
const original = route.handler;
|
|
337
|
+
// The handler is held until its Promise settles, also after an early reply.send() and
|
|
338
|
+
// after the client left (D-0023). The request itself is already held by onRequest, so
|
|
339
|
+
// this is the only tracking a handler gets: one reaction on the Promise it returns.
|
|
293
340
|
route.handler = function (request, reply) {
|
|
294
|
-
|
|
341
|
+
const result = original.call(this, request, reply);
|
|
342
|
+
const raw = reply.raw;
|
|
343
|
+
raw[HANDLER] = result;
|
|
344
|
+
if (thenable(result)) {
|
|
345
|
+
owner.#inflight++;
|
|
346
|
+
result.then(owner.#release, owner.#release);
|
|
347
|
+
}
|
|
348
|
+
raw[ABORTED]?.handler(result);
|
|
349
|
+
return result;
|
|
295
350
|
};
|
|
296
351
|
const fields = route;
|
|
297
352
|
for (const name of hooks.keys()) {
|
|
@@ -324,7 +379,14 @@ class WebOwner {
|
|
|
324
379
|
},
|
|
325
380
|
route: (route) => {
|
|
326
381
|
this.#assertMutable();
|
|
327
|
-
|
|
382
|
+
const { seal, ...rest } = route;
|
|
383
|
+
if (seal === undefined)
|
|
384
|
+
this.server.route(rest);
|
|
385
|
+
else
|
|
386
|
+
this.server.route({
|
|
387
|
+
...rest,
|
|
388
|
+
config: { ...rest.config, dokebiSeal: checkSealSetting(seal) },
|
|
389
|
+
});
|
|
328
390
|
},
|
|
329
391
|
register: (plugin, options) => {
|
|
330
392
|
this.#assertMutable();
|
|
@@ -348,22 +410,89 @@ class WebOwner {
|
|
|
348
410
|
.trim()
|
|
349
411
|
.toLowerCase();
|
|
350
412
|
},
|
|
413
|
+
sealCodec: (provider) => {
|
|
414
|
+
this.#assertMutable();
|
|
415
|
+
sealing.setProvider(provider);
|
|
416
|
+
// Registered on the root before any plugin scope exists, so every route inherits it.
|
|
417
|
+
this.server.addContentTypeParser(provider.contentType, { parseAs: 'string', bodyLimit: options.maxBodyBytes }, (request, body) => sealing.parse(request, String(body)));
|
|
418
|
+
},
|
|
419
|
+
sealRequests: (predicate) => {
|
|
420
|
+
this.#assertMutable();
|
|
421
|
+
sealing.addPredicate(predicate);
|
|
422
|
+
},
|
|
423
|
+
sealOf: (request) => sealing.sealOf(request),
|
|
424
|
+
get sealing() {
|
|
425
|
+
return sealing.provider !== undefined;
|
|
426
|
+
},
|
|
427
|
+
errorResponder: (responder) => {
|
|
428
|
+
this.#assertMutable();
|
|
429
|
+
if (typeof responder !== 'function')
|
|
430
|
+
throw new WebError('INVALID_ARGUMENT', 'An error responder must be a function', {
|
|
431
|
+
fix: 'Pass a function: web.errorResponder((response) => boolean | Promise<boolean>).',
|
|
432
|
+
});
|
|
433
|
+
this.#responders.unshift(responder);
|
|
434
|
+
logger.log('debug', 'Web error responder registered', {
|
|
435
|
+
responders: this.#responders.length,
|
|
436
|
+
});
|
|
437
|
+
},
|
|
351
438
|
});
|
|
352
439
|
}
|
|
353
440
|
#assertMutable() {
|
|
354
441
|
if (this.#frozen || this.#closed)
|
|
355
442
|
throw new WebError('FROZEN');
|
|
356
443
|
}
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
//
|
|
360
|
-
|
|
361
|
-
|
|
444
|
+
/** The shared 'close' listener of every held response (`this` is the response). */
|
|
445
|
+
#responseClosed(response) {
|
|
446
|
+
// 'close' fires once per response, so the listener is not removed (one call saved).
|
|
447
|
+
if (this.#draining && this.#worker)
|
|
448
|
+
this.server.server.closeIdleConnections();
|
|
449
|
+
const reply = response[REPLY];
|
|
450
|
+
// Written (finished, or at least its head: the rest needs no user code) or hijacked: done.
|
|
451
|
+
if (response.writableFinished || response.headersSent || reply === undefined || reply.sent) {
|
|
452
|
+
this.#release();
|
|
453
|
+
return;
|
|
454
|
+
}
|
|
455
|
+
// The client left before the response was written. Hooks or the handler of this request may
|
|
456
|
+
// still run; hold it until Fastify's chain for it ends (D-0023).
|
|
457
|
+
const logger = this.context.logger;
|
|
458
|
+
if (logger.isEnabled('debug'))
|
|
459
|
+
logger.log('debug', 'HTTP client left before the response', {
|
|
460
|
+
method: reply.request.method,
|
|
461
|
+
route: reply.request.routeOptions.url ?? 'unmatched',
|
|
462
|
+
handler: response[HANDLER] !== undefined,
|
|
463
|
+
sending: response[SENDING] === true,
|
|
464
|
+
});
|
|
465
|
+
response[ABORTED] = new AbortedResponse(response, (reason) => {
|
|
466
|
+
if (logger.isEnabled('debug'))
|
|
467
|
+
logger.log('debug', 'HTTP request without client finished', {
|
|
468
|
+
method: reply.request.method,
|
|
469
|
+
route: reply.request.routeOptions.url ?? 'unmatched',
|
|
470
|
+
reason,
|
|
471
|
+
});
|
|
472
|
+
this.#release();
|
|
473
|
+
});
|
|
362
474
|
}
|
|
363
475
|
track(work) {
|
|
364
476
|
if (this.#closed)
|
|
365
477
|
return Promise.reject(new WebError('CLOSED'));
|
|
366
|
-
|
|
478
|
+
this.#inflight++;
|
|
479
|
+
const promise = Promise.resolve().then(work);
|
|
480
|
+
// Bookkeeping only: the caller holds the same promise and sees its rejection (D-0047).
|
|
481
|
+
void promise.then(this.#release, this.#release);
|
|
482
|
+
return promise;
|
|
483
|
+
}
|
|
484
|
+
/** Resolves once nothing is held (immediately when nothing is). */
|
|
485
|
+
#whenIdle() {
|
|
486
|
+
if (this.#inflight === 0)
|
|
487
|
+
return Promise.resolve();
|
|
488
|
+
if (!this.#idle) {
|
|
489
|
+
let resolve;
|
|
490
|
+
const promise = new Promise((done) => {
|
|
491
|
+
resolve = done;
|
|
492
|
+
});
|
|
493
|
+
this.#idle = { promise, resolve };
|
|
494
|
+
}
|
|
495
|
+
return this.#idle.promise;
|
|
367
496
|
}
|
|
368
497
|
#hook(name, fn) {
|
|
369
498
|
const count = hooks.get(name);
|
|
@@ -373,6 +502,9 @@ class WebOwner {
|
|
|
373
502
|
(fn.length === count + 1 || (name === 'onRequestAbort' && fn.length !== 1))) {
|
|
374
503
|
throw new TypeError('Async Fastify hooks must not accept a done callback');
|
|
375
504
|
}
|
|
505
|
+
// Request-phase hooks run while their request is held: no wrapper, no cost (D-0068).
|
|
506
|
+
if (!RESPONSE_HOOKS.has(name))
|
|
507
|
+
return fn;
|
|
376
508
|
const owner = this;
|
|
377
509
|
function invoke(instance, args) {
|
|
378
510
|
return owner.track(() => new Promise((resolve, reject) => {
|
|
@@ -425,10 +557,36 @@ class WebOwner {
|
|
|
425
557
|
this.#wrapped.add(wrapped);
|
|
426
558
|
return wrapped;
|
|
427
559
|
}
|
|
560
|
+
/** The urlencoded body parser, or its refusal when `formBody` is off (D-0068). */
|
|
561
|
+
#formBody(options) {
|
|
562
|
+
if (!options.formBody) {
|
|
563
|
+
// Refused before the body is read: nothing is buffered for a request that gets 415.
|
|
564
|
+
this.server.addContentTypeParser(FORM_TYPE, (_request, _payload, done) => {
|
|
565
|
+
done(new WebError('FORM_BODY_DISABLED', 'Form bodies are not enabled'), undefined);
|
|
566
|
+
});
|
|
567
|
+
return;
|
|
568
|
+
}
|
|
569
|
+
const max = options.formMaxFields;
|
|
570
|
+
this.server.addContentTypeParser(FORM_TYPE, { parseAs: 'string', bodyLimit: options.maxBodyBytes }, (_request, body, done) => {
|
|
571
|
+
const text = body;
|
|
572
|
+
// Counted before parsing: refused, never cut (querystring's maxKeys drops the rest).
|
|
573
|
+
let fields = text.length ? 1 : 0;
|
|
574
|
+
for (let at = text.indexOf('&'); at !== -1; at = text.indexOf('&', at + 1))
|
|
575
|
+
if (++fields > max) {
|
|
576
|
+
done(new WebError('FORM_BODY_TOO_MANY_FIELDS', `A form body may carry at most ${max} fields`, { data: { maxFields: max } }), undefined);
|
|
577
|
+
return;
|
|
578
|
+
}
|
|
579
|
+
// node:querystring: decodes + and %XX, repeats become arrays, and the result has a null
|
|
580
|
+
// prototype (`__proto__` is an ordinary key, nothing is polluted).
|
|
581
|
+
done(null, parseQuery(text, '&', '=', { maxKeys: 0 }));
|
|
582
|
+
});
|
|
583
|
+
}
|
|
428
584
|
async start() {
|
|
429
585
|
this.#frozen = true;
|
|
430
586
|
const started = performance.now();
|
|
431
587
|
await this.server.ready();
|
|
588
|
+
// After every setup (routes and the seal provider are all known): fail closed (D-0062).
|
|
589
|
+
this.#sealing.check();
|
|
432
590
|
this.context.logger.log('debug', 'Web routes frozen', {
|
|
433
591
|
ms: Math.round(performance.now() - started),
|
|
434
592
|
});
|
|
@@ -436,16 +594,35 @@ class WebOwner {
|
|
|
436
594
|
// node:cluster shares the port: the primary hands connections to a worker as soon as it
|
|
437
595
|
// listens, so a worker listens only once the whole application is ready (`ready`, D-0034).
|
|
438
596
|
// A single process listens here and answers 503 until then (health checks see it start).
|
|
439
|
-
if (!
|
|
597
|
+
if (!this.#worker)
|
|
440
598
|
await this.listen();
|
|
441
599
|
}
|
|
600
|
+
/** Listens unless this process does not serve (`runtime.serving` false, D-0063 §4). */
|
|
442
601
|
async listen() {
|
|
443
602
|
if (this.#address !== undefined)
|
|
444
603
|
return;
|
|
604
|
+
const runtime = this.context.runtime ?? this.context.app.runtime;
|
|
605
|
+
if (!runtime.serving) {
|
|
606
|
+
this.context.logger.log('debug', 'Web server not listening', {
|
|
607
|
+
role: runtime.role,
|
|
608
|
+
serving: false,
|
|
609
|
+
});
|
|
610
|
+
return;
|
|
611
|
+
}
|
|
445
612
|
const started = performance.now();
|
|
446
613
|
this.#address = await this.server.listen({ host: this.options.host, port: this.options.port });
|
|
447
|
-
|
|
614
|
+
// info, with every bound address: `dokebi start` reads it to show where the app answers.
|
|
615
|
+
// `localhost` binds both 127.0.0.1 and ::1, so there can be more than one.
|
|
616
|
+
const scheme = this.#https ? 'https' : 'http';
|
|
617
|
+
const urls = this.server
|
|
618
|
+
.addresses()
|
|
619
|
+
.map((bound) => bound.family === 'IPv6' || bound.family === 6
|
|
620
|
+
? `${scheme}://[${bound.address}]:${bound.port}`
|
|
621
|
+
: `${scheme}://${bound.address}:${bound.port}`);
|
|
622
|
+
this.context.logger.log('info', 'Web server listening', {
|
|
448
623
|
address: this.#address,
|
|
624
|
+
urls: urls.length ? urls : [this.#address],
|
|
625
|
+
host: this.options.host,
|
|
449
626
|
ms: Math.round(performance.now() - started),
|
|
450
627
|
});
|
|
451
628
|
}
|
|
@@ -455,8 +632,8 @@ class WebOwner {
|
|
|
455
632
|
const started = performance.now();
|
|
456
633
|
const logger = this.context.logger;
|
|
457
634
|
logger.log('debug', 'Web drain started', {
|
|
458
|
-
pending: this.#
|
|
459
|
-
clusterWorker:
|
|
635
|
+
pending: this.#inflight,
|
|
636
|
+
clusterWorker: this.#worker,
|
|
460
637
|
});
|
|
461
638
|
// The node:cluster primary keeps handing new connections to a worker while it listens, so a
|
|
462
639
|
// draining worker stops listening first; new connections go to the other workers. A single
|
|
@@ -470,7 +647,7 @@ class WebOwner {
|
|
|
470
647
|
// keep-alive connections at once, racing clients that are just reusing them. Those
|
|
471
648
|
// connections stay; their next request is served with `Connection: close`.
|
|
472
649
|
let grace;
|
|
473
|
-
if (
|
|
650
|
+
if (this.#worker && this.server.server.listening) {
|
|
474
651
|
Server.prototype.close.call(this.server.server);
|
|
475
652
|
grace = delay(CLOSE_GRACE_MS);
|
|
476
653
|
logger.log('debug', 'Web worker stopped listening', { graceMs: CLOSE_GRACE_MS });
|
|
@@ -483,18 +660,19 @@ class WebOwner {
|
|
|
483
660
|
signal.addEventListener('abort', () => resolve(), { once: true, signal: listening.signal });
|
|
484
661
|
});
|
|
485
662
|
try {
|
|
486
|
-
while (this.#
|
|
487
|
-
await Promise.race([
|
|
663
|
+
while (this.#inflight > 0) {
|
|
664
|
+
await Promise.race([this.#whenIdle(), aborted]);
|
|
488
665
|
if (signal.aborted) {
|
|
489
666
|
// Deadline or forced stop: cut the remaining connections; core records the timeout.
|
|
490
667
|
logger.log('debug', 'Web drain cut connections', {
|
|
491
|
-
pending: this.#
|
|
668
|
+
pending: this.#inflight,
|
|
492
669
|
ms: Math.round(performance.now() - started),
|
|
493
670
|
});
|
|
494
671
|
this.server.server.closeAllConnections();
|
|
495
672
|
return;
|
|
496
673
|
}
|
|
497
|
-
// Fastify
|
|
674
|
+
// Fastify starts the next step of a request (the next hook, onResponse after 'finish')
|
|
675
|
+
// right after the previous one settles; look again once those have had their turn.
|
|
498
676
|
await immediate();
|
|
499
677
|
}
|
|
500
678
|
if (grace)
|
|
@@ -505,6 +683,255 @@ class WebOwner {
|
|
|
505
683
|
listening.abort();
|
|
506
684
|
}
|
|
507
685
|
}
|
|
686
|
+
get worker() {
|
|
687
|
+
return this.#worker;
|
|
688
|
+
}
|
|
689
|
+
/** Fastify creation options: the extension's `fastifyOptions`, checked (D-0064 §9). */
|
|
690
|
+
#fastifyOptions(defaults) {
|
|
691
|
+
if (!this.#hooks || !this.#overridden.has('fastifyOptions'))
|
|
692
|
+
return defaults;
|
|
693
|
+
const result = this.#hooks.fastifyOptions(Object.freeze({ ...defaults }));
|
|
694
|
+
const plain = result !== null &&
|
|
695
|
+
typeof result === 'object' &&
|
|
696
|
+
!types.isProxy(result) &&
|
|
697
|
+
[Object.prototype, null].includes(Object.getPrototypeOf(result)) &&
|
|
698
|
+
!('then' in result);
|
|
699
|
+
const fields = (plain ? result : {});
|
|
700
|
+
const changed = Object.keys(PINNED).filter((key) => Object.hasOwn(fields, key) && fields[key] !== PINNED[key]);
|
|
701
|
+
if (!plain ||
|
|
702
|
+
changed.length ||
|
|
703
|
+
(fields.serverFactory !== undefined && typeof fields.serverFactory !== 'function'))
|
|
704
|
+
throw new WebError('INVALID_EXTENSION_RESULT', 'fastifyOptions() must return a plain object of Fastify options', {
|
|
705
|
+
fix: `Return { ...defaults, … } from fastifyOptions() in ${EXTENSION_FILE}, synchronously; return503OnClosing and forceCloseConnections belong to the drain contract.`,
|
|
706
|
+
data: { hook: 'fastifyOptions', ...(changed.length ? { pinned: changed } : {}) },
|
|
707
|
+
});
|
|
708
|
+
return { ...fields, ...PINNED };
|
|
709
|
+
}
|
|
710
|
+
/**
|
|
711
|
+
* The error handler: D-0063 §1 mapping, the `errorBody` hook, logging, then the error responders
|
|
712
|
+
* or the built-in JSON or HTML answer (D-0074). Synchronous while no responder is registered.
|
|
713
|
+
*/
|
|
714
|
+
#fail(error, request, reply, failures) {
|
|
715
|
+
const logger = this.context.logger;
|
|
716
|
+
const production = this.#production;
|
|
717
|
+
let answer = errorAnswer(error, production, (details) => this.#details(details));
|
|
718
|
+
// The route pattern, not the requested URL: no query values in the log (D-0047).
|
|
719
|
+
const route = request.routeOptions.url ?? 'unmatched';
|
|
720
|
+
const own = error?.code;
|
|
721
|
+
const code = typeof own === 'string' ? own : answer.body.error;
|
|
722
|
+
if (answer.status >= 500) {
|
|
723
|
+
const name = error instanceof Error ? error.name : typeof error;
|
|
724
|
+
const repeated = failures.take(`${request.method} ${route} ${name} ${code}`);
|
|
725
|
+
if (repeated !== undefined)
|
|
726
|
+
logger.log('error', 'HTTP request failed', {
|
|
727
|
+
code: 'WEB_REQUEST_FAILED',
|
|
728
|
+
requestId: request.id,
|
|
729
|
+
method: request.method,
|
|
730
|
+
route,
|
|
731
|
+
status: answer.status,
|
|
732
|
+
errorCode: code,
|
|
733
|
+
error: describeError(error),
|
|
734
|
+
...(repeated ? { repeated } : {}),
|
|
735
|
+
});
|
|
736
|
+
}
|
|
737
|
+
else if (error instanceof WebError && error.code === 'FORM_BODY_DISABLED') {
|
|
738
|
+
// A disabled form body is a setup mistake worth seeing once per interval.
|
|
739
|
+
const repeated = failures.take(`${error.code} ${request.method} ${route}`);
|
|
740
|
+
if (repeated !== undefined)
|
|
741
|
+
logger.log('warn', 'HTTP form body refused', {
|
|
742
|
+
code: error.code,
|
|
743
|
+
method: request.method,
|
|
744
|
+
route,
|
|
745
|
+
fix: error.fix,
|
|
746
|
+
...(repeated ? { repeated } : {}),
|
|
747
|
+
});
|
|
748
|
+
}
|
|
749
|
+
else if (logger.isEnabled('debug'))
|
|
750
|
+
logger.log('debug', 'HTTP request rejected', {
|
|
751
|
+
status: answer.status,
|
|
752
|
+
method: request.method,
|
|
753
|
+
route,
|
|
754
|
+
error: describeError(error),
|
|
755
|
+
errorCode: code,
|
|
756
|
+
});
|
|
757
|
+
if (this.#hooks && this.#overridden.has('errorBody')) {
|
|
758
|
+
try {
|
|
759
|
+
const changed = this.#hooks.errorBody(error, { request, answer, production });
|
|
760
|
+
if (!validAnswer(changed))
|
|
761
|
+
throw new WebError('INVALID_EXTENSION_RESULT', 'errorBody() returned no answer', {
|
|
762
|
+
data: { hook: 'errorBody' },
|
|
763
|
+
});
|
|
764
|
+
answer = changed;
|
|
765
|
+
}
|
|
766
|
+
catch (failure) {
|
|
767
|
+
const repeated = failures.take(`errorBody ${route}`);
|
|
768
|
+
if (repeated !== undefined)
|
|
769
|
+
logger.log('error', 'Web errorBody hook failed', {
|
|
770
|
+
code: 'WEB_EXTENSION_FAILED',
|
|
771
|
+
method: request.method,
|
|
772
|
+
route,
|
|
773
|
+
fix: `Return { status, body: { error, … } } from errorBody() in ${EXTENSION_FILE}.`,
|
|
774
|
+
error: describeError(failure),
|
|
775
|
+
...(repeated ? { repeated } : {}),
|
|
776
|
+
});
|
|
777
|
+
}
|
|
778
|
+
}
|
|
779
|
+
const body = production ? productionBody(answer.body) : answer.body;
|
|
780
|
+
// D-0074 §1: JSON for scripts (Inertia, fetch, XHR, APIs, sealed requests), a small page for
|
|
781
|
+
// a browser navigation or an HTML form post.
|
|
782
|
+
const sealed = this.#sealing.sealOf(request) !== undefined;
|
|
783
|
+
const format = errorFormat(request.headers, sealed);
|
|
784
|
+
reply.code(answer.status);
|
|
785
|
+
if (!this.#responders.length) {
|
|
786
|
+
this.#send(reply, answer.status, body, format);
|
|
787
|
+
return undefined;
|
|
788
|
+
}
|
|
789
|
+
return this.#respond({ request, reply, error, status: answer.status, body, format, production, sealed }, route, failures);
|
|
790
|
+
}
|
|
791
|
+
/** The built-in answer: the body as JSON, or its small HTML page. */
|
|
792
|
+
#send(reply, status, body, format) {
|
|
793
|
+
reply.code(status);
|
|
794
|
+
if (format === 'html')
|
|
795
|
+
reply.type('text/html; charset=utf-8').send(errorPage(status, body));
|
|
796
|
+
else
|
|
797
|
+
reply.type('application/json; charset=utf-8').send(body);
|
|
798
|
+
}
|
|
799
|
+
/** Asks the error responders (D-0074); the built-in answer when none wrote one or one failed. */
|
|
800
|
+
async #respond(response, route, failures) {
|
|
801
|
+
const { request, reply } = response;
|
|
802
|
+
const logger = this.context.logger;
|
|
803
|
+
// `reply.sent` stays false until the response has ended (async onSend hooks such as the
|
|
804
|
+
// session's run first), so whether a responder sent is seen on this reply's own `send`
|
|
805
|
+
// (redirect() and view helpers call it too). Error answers only: no cost on other requests.
|
|
806
|
+
let sent = false;
|
|
807
|
+
const send = reply.send;
|
|
808
|
+
reply.send = function (...args) {
|
|
809
|
+
sent = true;
|
|
810
|
+
return send.apply(this, args);
|
|
811
|
+
};
|
|
812
|
+
for (const [index, responder] of this.#responders.entries()) {
|
|
813
|
+
try {
|
|
814
|
+
if ((await responder(response)) === true) {
|
|
815
|
+
if (sent || reply.sent)
|
|
816
|
+
return reply;
|
|
817
|
+
throw new WebError('INVALID_EXTENSION_RESULT', 'An error responder returned true without sending an answer');
|
|
818
|
+
}
|
|
819
|
+
if (sent || reply.sent)
|
|
820
|
+
return reply;
|
|
821
|
+
}
|
|
822
|
+
catch (failure) {
|
|
823
|
+
const repeated = failures.take(`responder ${index} ${route}`);
|
|
824
|
+
if (repeated !== undefined)
|
|
825
|
+
logger.log('error', 'Web error responder failed', {
|
|
826
|
+
code: 'WEB_ERROR_RESPONDER_FAILED',
|
|
827
|
+
method: request.method,
|
|
828
|
+
route,
|
|
829
|
+
status: response.status,
|
|
830
|
+
errorCode: response.body.error,
|
|
831
|
+
fix: 'The built-in error answer was sent instead; fix the error view or page (see error).',
|
|
832
|
+
error: describeError(failure),
|
|
833
|
+
...(repeated ? { repeated } : {}),
|
|
834
|
+
});
|
|
835
|
+
if (sent || reply.sent)
|
|
836
|
+
return reply;
|
|
837
|
+
break;
|
|
838
|
+
}
|
|
839
|
+
}
|
|
840
|
+
// Headers a failed responder may have set (a view's type) are replaced by the built-in answer.
|
|
841
|
+
this.#send(reply, response.status, response.body, response.format);
|
|
842
|
+
return reply;
|
|
843
|
+
}
|
|
844
|
+
/** `details` for a development body; one that is not JSON (a cycle, a BigInt) is left out. */
|
|
845
|
+
#details(details) {
|
|
846
|
+
try {
|
|
847
|
+
return sendableDetails(details);
|
|
848
|
+
}
|
|
849
|
+
catch (error) {
|
|
850
|
+
if (this.context.logger.isEnabled('debug'))
|
|
851
|
+
this.context.logger.log('debug', 'Web error details not sent', {
|
|
852
|
+
reason: 'not-json',
|
|
853
|
+
error: describeError(error),
|
|
854
|
+
});
|
|
855
|
+
return undefined;
|
|
856
|
+
}
|
|
857
|
+
}
|
|
858
|
+
/** The 503 of a request refused before start, while not ready or while draining. */
|
|
859
|
+
#refuse(request, reply, reason) {
|
|
860
|
+
const logger = this.context.logger;
|
|
861
|
+
// Why a request was turned away: drain, start not finished, or health not ready.
|
|
862
|
+
if (logger.isEnabled('debug'))
|
|
863
|
+
logger.log('debug', 'HTTP request refused', {
|
|
864
|
+
reason,
|
|
865
|
+
method: request.method,
|
|
866
|
+
url: request.url.split('?', 1)[0]?.slice(0, 200),
|
|
867
|
+
});
|
|
868
|
+
// D-0074 §1: a browser navigation gets a small page, every script JSON; sealed requests stay
|
|
869
|
+
// JSON (the route is known in onRequest, so the seal decision is too).
|
|
870
|
+
const html = errorFormat(request.headers, this.#sealing.sealOf(request) !== undefined) === 'html';
|
|
871
|
+
if (!this.#hooks || !this.#overridden.has('unavailable')) {
|
|
872
|
+
reply.code(503).header('connection', 'close');
|
|
873
|
+
if (html)
|
|
874
|
+
reply
|
|
875
|
+
.type('text/html; charset=utf-8')
|
|
876
|
+
.send(errorPage(503, { error: 'SERVICE_UNAVAILABLE', message: UNAVAILABLE[reason] }));
|
|
877
|
+
else
|
|
878
|
+
reply.send({ error: 'SERVICE_UNAVAILABLE', reason });
|
|
879
|
+
return;
|
|
880
|
+
}
|
|
881
|
+
const answer = {
|
|
882
|
+
status: 503,
|
|
883
|
+
body: { error: 'SERVICE_UNAVAILABLE', reason },
|
|
884
|
+
};
|
|
885
|
+
let chosen = answer;
|
|
886
|
+
try {
|
|
887
|
+
const result = this.#hooks.unavailable({ request, reason, answer });
|
|
888
|
+
if (!validRefusal(result))
|
|
889
|
+
throw new WebError('INVALID_EXTENSION_RESULT', 'unavailable() returned no answer', {
|
|
890
|
+
data: { hook: 'unavailable' },
|
|
891
|
+
});
|
|
892
|
+
chosen = result;
|
|
893
|
+
}
|
|
894
|
+
catch (failure) {
|
|
895
|
+
logger.log('error', 'Web unavailable hook failed', {
|
|
896
|
+
code: 'WEB_EXTENSION_FAILED',
|
|
897
|
+
reason,
|
|
898
|
+
fix: `Return { status, headers?, body } synchronously from unavailable() in ${EXTENSION_FILE}.`,
|
|
899
|
+
error: describeError(failure),
|
|
900
|
+
});
|
|
901
|
+
}
|
|
902
|
+
reply.code(chosen.status);
|
|
903
|
+
for (const [name, value] of Object.entries(chosen.headers ?? {}))
|
|
904
|
+
reply.header(name, value);
|
|
905
|
+
// The request is refused either way: the connection closes, as without the hook.
|
|
906
|
+
reply.header('connection', 'close');
|
|
907
|
+
const body = chosen.body;
|
|
908
|
+
// A page only for a body of the error shape; anything else the hook chose stays JSON.
|
|
909
|
+
if (html && body !== null && typeof body === 'object' && typeof body.error === 'string')
|
|
910
|
+
reply
|
|
911
|
+
.type('text/html; charset=utf-8')
|
|
912
|
+
.send(errorPage(chosen.status, this.#production
|
|
913
|
+
? productionBody(body)
|
|
914
|
+
: body));
|
|
915
|
+
else
|
|
916
|
+
reply.send(chosen.body);
|
|
917
|
+
}
|
|
918
|
+
/** `@dokebi/core/testing` inject (D-0063 §7): a request through Fastify, without a socket. */
|
|
919
|
+
async inject(request) {
|
|
920
|
+
const response = await this.server.inject({
|
|
921
|
+
method: (request.method ?? 'GET'),
|
|
922
|
+
url: request.url,
|
|
923
|
+
...(request.headers ? { headers: { ...request.headers } } : {}),
|
|
924
|
+
...(request.payload === undefined
|
|
925
|
+
? {}
|
|
926
|
+
: { payload: request.payload }),
|
|
927
|
+
});
|
|
928
|
+
return Object.freeze({
|
|
929
|
+
statusCode: response.statusCode,
|
|
930
|
+
headers: Object.freeze({ ...response.headers }),
|
|
931
|
+
body: response.body,
|
|
932
|
+
json: () => JSON.parse(response.body),
|
|
933
|
+
});
|
|
934
|
+
}
|
|
508
935
|
async close() {
|
|
509
936
|
this.#closed = true;
|
|
510
937
|
const started = performance.now();
|
|
@@ -514,66 +941,122 @@ class WebOwner {
|
|
|
514
941
|
});
|
|
515
942
|
}
|
|
516
943
|
}
|
|
944
|
+
const NO_EXTENSION = Object.freeze({
|
|
945
|
+
hooks: undefined,
|
|
946
|
+
overridden: new Set(),
|
|
947
|
+
});
|
|
517
948
|
const HEALTH = 'dokebi-health';
|
|
518
|
-
const health = optionalDependency({ name: HEALTH, version: '^0.
|
|
949
|
+
const health = optionalDependency({ name: HEALTH, version: '^0.4.0' });
|
|
950
|
+
function invalidEntry(message, fix) {
|
|
951
|
+
return new WebError('INVALID_ENTRY', message, fix === undefined ? {} : { fix });
|
|
952
|
+
}
|
|
519
953
|
function requirement(value) {
|
|
520
954
|
if (value === null || typeof value !== 'object')
|
|
521
|
-
throw
|
|
955
|
+
throw invalidEntry('Invalid web requirement');
|
|
522
956
|
if (typeof value.setup === 'function')
|
|
523
957
|
return dependencyOf(value);
|
|
524
958
|
if (typeof value.name !== 'string')
|
|
525
|
-
throw
|
|
959
|
+
throw invalidEntry('Invalid web requirement');
|
|
526
960
|
return value;
|
|
527
961
|
}
|
|
528
|
-
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
|
|
532
|
-
|
|
533
|
-
|
|
534
|
-
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
|
|
546
|
-
|
|
962
|
+
function brandedForWeb(value) {
|
|
963
|
+
if (typeof value !== 'function')
|
|
964
|
+
return false;
|
|
965
|
+
const declaration = value[EXTENSION_BRAND];
|
|
966
|
+
return declaration?.plugin === 'dokebi-web';
|
|
967
|
+
}
|
|
968
|
+
/**
|
|
969
|
+
* The entry as given: `requires` is checked at once, the extension class is created lazily,
|
|
970
|
+
* once, when the factory derives dependencies (so INVALID_EXTENSION leaves the factory call).
|
|
971
|
+
*/
|
|
972
|
+
class WebEntryInput {
|
|
973
|
+
requires;
|
|
974
|
+
#extension;
|
|
975
|
+
#resolved;
|
|
976
|
+
constructor(input) {
|
|
977
|
+
if (input === undefined || typeof input === 'function') {
|
|
978
|
+
this.requires = [];
|
|
979
|
+
this.#extension = input;
|
|
980
|
+
return;
|
|
981
|
+
}
|
|
982
|
+
if (input === null ||
|
|
983
|
+
typeof input !== 'object' ||
|
|
984
|
+
Array.isArray(input) ||
|
|
985
|
+
types.isProxy(input) ||
|
|
986
|
+
![Object.prototype, null].includes(Object.getPrototypeOf(input)))
|
|
987
|
+
throw invalidEntry('Invalid web entry');
|
|
988
|
+
let list;
|
|
989
|
+
let extension;
|
|
990
|
+
for (const key of Reflect.ownKeys(input)) {
|
|
991
|
+
// Module namespaces carry Symbol.toStringTag; only string exports are entry fields.
|
|
992
|
+
if (typeof key !== 'string')
|
|
993
|
+
continue;
|
|
994
|
+
const descriptor = Object.getOwnPropertyDescriptor(input, key);
|
|
995
|
+
if (!descriptor || !('value' in descriptor))
|
|
996
|
+
throw invalidEntry('Invalid web entry');
|
|
997
|
+
if (key === 'requires')
|
|
998
|
+
list = descriptor.value;
|
|
999
|
+
else if (key === 'default')
|
|
1000
|
+
extension = descriptor.value;
|
|
1001
|
+
else if (brandedForWeb(descriptor.value))
|
|
1002
|
+
throw invalidEntry('The web extension class must be the default export', `Write export default class … extends WebExtension in ${EXTENSION_FILE} (found the named export ${key}).`);
|
|
1003
|
+
else
|
|
1004
|
+
throw invalidEntry('Invalid web entry');
|
|
1005
|
+
}
|
|
1006
|
+
this.#extension = extension;
|
|
1007
|
+
if (list === undefined) {
|
|
1008
|
+
this.requires = [];
|
|
1009
|
+
return;
|
|
1010
|
+
}
|
|
1011
|
+
if (!Array.isArray(list) || list.length > 256)
|
|
1012
|
+
throw invalidEntry('Invalid web requires');
|
|
1013
|
+
const requires = list.map(requirement);
|
|
1014
|
+
const names = new Set(requires.map((dependency) => dependency.name));
|
|
1015
|
+
if (names.size !== requires.length || names.has('dokebi-web'))
|
|
1016
|
+
throw invalidEntry('Duplicate web requirement');
|
|
1017
|
+
this.requires = Object.freeze(requires);
|
|
1018
|
+
}
|
|
1019
|
+
extension() {
|
|
1020
|
+
this.#resolved ??= this.#resolve();
|
|
1021
|
+
return this.#resolved;
|
|
1022
|
+
}
|
|
1023
|
+
#resolve() {
|
|
1024
|
+
if (this.#extension === undefined)
|
|
1025
|
+
return NO_EXTENSION;
|
|
1026
|
+
const created = createExtension(this.#extension, WebExtension);
|
|
1027
|
+
if (!created.overridden.length)
|
|
1028
|
+
return NO_EXTENSION;
|
|
1029
|
+
return Object.freeze({
|
|
1030
|
+
hooks: webHooks(created.instance),
|
|
1031
|
+
overridden: new Set(created.overridden),
|
|
1032
|
+
});
|
|
547
1033
|
}
|
|
548
|
-
if (list === undefined)
|
|
549
|
-
return { requires: [] };
|
|
550
|
-
if (!Array.isArray(list) || list.length > 256)
|
|
551
|
-
throw new TypeError('Invalid web requires');
|
|
552
|
-
const requires = list.map(requirement);
|
|
553
|
-
const names = new Set(requires.map((dependency) => dependency.name));
|
|
554
|
-
if (names.size !== requires.length || names.has('dokebi-web'))
|
|
555
|
-
throw new TypeError('Duplicate web requirement');
|
|
556
|
-
return { requires };
|
|
557
1034
|
}
|
|
558
1035
|
class WebRuntime {
|
|
559
1036
|
options;
|
|
1037
|
+
extension;
|
|
560
1038
|
health;
|
|
561
1039
|
#owner;
|
|
562
|
-
constructor(options, health) {
|
|
1040
|
+
constructor(options, extension, health) {
|
|
563
1041
|
this.options = options;
|
|
1042
|
+
this.extension = extension;
|
|
564
1043
|
this.health = health;
|
|
565
1044
|
}
|
|
566
1045
|
setup(context) {
|
|
567
|
-
const owner = new WebOwner(context, this.options, context.getOptionalDependency(this.health));
|
|
1046
|
+
const owner = new WebOwner(context, this.options, this.extension, context.getOptionalDependency(this.health));
|
|
568
1047
|
this.#owner = owner;
|
|
569
1048
|
context.defer(() => owner.close());
|
|
1049
|
+
// D-0063 §7: `inject` of @dokebi/core/testing goes through this server, without a socket.
|
|
1050
|
+
context.contribute(injectPoint, Object.freeze({
|
|
1051
|
+
inject: (request) => owner.inject(request),
|
|
1052
|
+
}));
|
|
570
1053
|
return owner.api;
|
|
571
1054
|
}
|
|
572
1055
|
start() {
|
|
573
1056
|
return this.#owner?.start();
|
|
574
1057
|
}
|
|
575
1058
|
ready() {
|
|
576
|
-
return
|
|
1059
|
+
return this.#owner?.worker ? this.#owner.listen() : undefined;
|
|
577
1060
|
}
|
|
578
1061
|
drain(context) {
|
|
579
1062
|
return this.#owner?.drain(context.drainSignal);
|
|
@@ -581,24 +1064,22 @@ class WebRuntime {
|
|
|
581
1064
|
}
|
|
582
1065
|
export const createPlugin = definePlugin({
|
|
583
1066
|
name: 'dokebi-web',
|
|
584
|
-
version: '0.
|
|
585
|
-
core: '^0.
|
|
586
|
-
options:
|
|
587
|
-
entry:
|
|
1067
|
+
version: '0.4.0',
|
|
1068
|
+
core: '^0.4.0',
|
|
1069
|
+
options: declaration,
|
|
1070
|
+
entry: (input) => new WebEntryInput(input),
|
|
1071
|
+
contributes: [injectPoint],
|
|
588
1072
|
// A required dokebi-health in entry.requires replaces the optional link.
|
|
589
1073
|
dependencies: ({ entry }) => {
|
|
1074
|
+
// The extension is created here, once: a broken subclass fails the factory call.
|
|
1075
|
+
entry?.extension();
|
|
590
1076
|
const requires = entry?.requires ?? [];
|
|
591
1077
|
return requires.some((dependency) => dependency.name === HEALTH)
|
|
592
1078
|
? requires
|
|
593
1079
|
: [...requires, health];
|
|
594
1080
|
},
|
|
595
|
-
instance: ({ options, dependencies }) => new WebRuntime(options, (dependencies.find((dependency) => dependency.name === HEALTH) ??
|
|
1081
|
+
instance: ({ options, entry, dependencies }) => new WebRuntime(settings(options), entry?.extension() ?? NO_EXTENSION, (dependencies.find((dependency) => dependency.name === HEALTH) ??
|
|
596
1082
|
health)),
|
|
597
1083
|
});
|
|
598
|
-
/** Declares dokebi-web as a required provider
|
|
599
|
-
export
|
|
600
|
-
name: 'dokebi-web',
|
|
601
|
-
packageName: '@dokebi/web',
|
|
602
|
-
version: '^0.1.0',
|
|
603
|
-
load: () => import('./index.js'),
|
|
604
|
-
});
|
|
1084
|
+
/** Declares dokebi-web as a required provider (also `@dokebi/web/dependency`, D-0063 §6). */
|
|
1085
|
+
export { dependency } from './dependency.js';
|