@dokebi/web 0.2.0 → 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 +189 -51
- package/README.md +49 -47
- 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 +22 -6
- package/dist/index.js +725 -306
- 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 +10 -9
- package/dist/seal.js +23 -53
- package/options.schema.json +53 -17
- package/package.json +43 -13
- package/templates/extension.ts +14 -0
package/dist/index.js
CHANGED
|
@@ -1,173 +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';
|
|
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';
|
|
7
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';
|
|
8
19
|
export { SEALED_PATH_HEADER, } from './seal.js';
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
super(`Web: ${code}`);
|
|
13
|
-
this.code = code;
|
|
14
|
-
this.name = 'WebError';
|
|
15
|
-
}
|
|
16
|
-
}
|
|
17
|
-
/** IPv4-mapped IPv6 (`::ffff:127.0.0.1`) compares as plain IPv4. */
|
|
18
|
-
const plainAddress = (address) => address.replace(/^::ffff:(?=\d+\.\d+\.\d+\.\d+$)/, '');
|
|
19
|
-
function trustProxy(input) {
|
|
20
|
-
if (input === undefined)
|
|
21
|
-
return Object.freeze([]);
|
|
22
|
-
if (!Array.isArray(input) ||
|
|
23
|
-
input.length > 64 ||
|
|
24
|
-
!input.every((item) => typeof item === 'string' && isIP(item)))
|
|
25
|
-
throw new WebError('INVALID_OPTIONS');
|
|
26
|
-
return Object.freeze([...new Set(input.map((item) => plainAddress(item)))]);
|
|
27
|
-
}
|
|
28
|
-
const DEFAULT_HEALTH_ROUTES = Object.freeze({
|
|
29
|
-
live: '/health/live',
|
|
30
|
-
ready: '/health/ready',
|
|
31
|
-
});
|
|
32
|
-
/** Copies own string-keyed data properties; Proxies and accessors are rejected unevaluated. */
|
|
33
|
-
function dataRecord(input, keys) {
|
|
34
|
-
if (!input ||
|
|
35
|
-
typeof input !== 'object' ||
|
|
36
|
-
Array.isArray(input) ||
|
|
37
|
-
types.isProxy(input) ||
|
|
38
|
-
![Object.prototype, null].includes(Object.getPrototypeOf(input)))
|
|
39
|
-
return undefined;
|
|
40
|
-
const result = Object.create(null);
|
|
41
|
-
for (const key of Reflect.ownKeys(input)) {
|
|
42
|
-
const descriptor = Object.getOwnPropertyDescriptor(input, key);
|
|
43
|
-
if (typeof key !== 'string' || !descriptor || !('value' in descriptor) || !keys.includes(key))
|
|
44
|
-
return undefined;
|
|
45
|
-
result[key] = descriptor.value;
|
|
46
|
-
}
|
|
47
|
-
return result;
|
|
48
|
-
}
|
|
49
|
-
const ROUTE_PATH = /^\/[^?#\s]{0,2047}$/;
|
|
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';
|
|
50
23
|
/**
|
|
51
|
-
*
|
|
52
|
-
*
|
|
53
|
-
*
|
|
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.
|
|
54
27
|
*/
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
text = `NonError: ${String(current)}`; // not serialisable (cycle, BigInt): its string form
|
|
70
|
-
}
|
|
71
|
-
}
|
|
72
|
-
parts.push(depth ? `Caused by: ${text}` : text);
|
|
73
|
-
current = current instanceof Error ? current.cause : undefined;
|
|
74
|
-
}
|
|
75
|
-
const text = parts.join('\n').replace(/\/\/[^\s/@]*@/g, '//***@');
|
|
76
|
-
return text.length > 16_384
|
|
77
|
-
? `${text.slice(0, 16_384)}… [truncated ${text.length - 16_384} characters]`
|
|
78
|
-
: text;
|
|
79
|
-
}
|
|
80
|
-
/** How often a repeating error of the same kind is logged; repeats in between are counted. */
|
|
81
|
-
const REPEAT_INTERVAL_MS = 10_000;
|
|
82
|
-
/**
|
|
83
|
-
* Counts repeats of the same error key so a hot path logs it once per interval (D-0047). The
|
|
84
|
-
* first occurrence is logged; later ones inside the interval are only counted and reported with
|
|
85
|
-
* the next logged occurrence of that key.
|
|
86
|
-
*/
|
|
87
|
-
class Repeats {
|
|
88
|
-
#keys = new Map();
|
|
89
|
-
/** The repeats to report with this occurrence, or undefined when it is only counted. */
|
|
90
|
-
take(key, now = Date.now()) {
|
|
91
|
-
const entry = this.#keys.get(key);
|
|
92
|
-
if (entry && now < entry.until) {
|
|
93
|
-
entry.repeated++;
|
|
94
|
-
return undefined;
|
|
95
|
-
}
|
|
96
|
-
if (!entry && this.#keys.size >= 256)
|
|
97
|
-
this.#keys.clear();
|
|
98
|
-
this.#keys.set(key, { until: now + REPEAT_INTERVAL_MS, repeated: 0 });
|
|
99
|
-
return entry?.repeated ?? 0;
|
|
100
|
-
}
|
|
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
|
+
});
|
|
101
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';
|
|
102
46
|
/**
|
|
103
47
|
* How long a draining node:cluster worker stays up after it stops listening: enough for any
|
|
104
48
|
* connection the primary was already handing it to be answered "not accepted" and passed on.
|
|
105
49
|
*/
|
|
106
50
|
const CLOSE_GRACE_MS = 100;
|
|
107
|
-
|
|
108
|
-
if (input === undefined)
|
|
109
|
-
return DEFAULT_HEALTH_ROUTES;
|
|
110
|
-
if (input === false)
|
|
111
|
-
return false;
|
|
112
|
-
const value = dataRecord(input, ['live', 'ready']);
|
|
113
|
-
if (!value)
|
|
114
|
-
throw new WebError('INVALID_OPTIONS');
|
|
115
|
-
const live = value.live === undefined ? DEFAULT_HEALTH_ROUTES.live : value.live;
|
|
116
|
-
const ready = value.ready === undefined ? DEFAULT_HEALTH_ROUTES.ready : value.ready;
|
|
117
|
-
if (typeof live !== 'string' ||
|
|
118
|
-
typeof ready !== 'string' ||
|
|
119
|
-
!ROUTE_PATH.test(live) ||
|
|
120
|
-
!ROUTE_PATH.test(ready) ||
|
|
121
|
-
live === ready)
|
|
122
|
-
throw new WebError('INVALID_OPTIONS');
|
|
123
|
-
return Object.freeze({ live, ready });
|
|
124
|
-
}
|
|
125
|
-
function normalize(input) {
|
|
126
|
-
const value = dataRecord(input, [
|
|
127
|
-
'host',
|
|
128
|
-
'port',
|
|
129
|
-
'bodyLimit',
|
|
130
|
-
'requestTimeout',
|
|
131
|
-
'healthRoutes',
|
|
132
|
-
'trustProxy',
|
|
133
|
-
'sealDriftMs',
|
|
134
|
-
'sealExclude',
|
|
135
|
-
]);
|
|
136
|
-
if (!value)
|
|
137
|
-
throw new WebError('INVALID_OPTIONS');
|
|
138
|
-
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, sealDriftMs = value.sealDriftMs === undefined ? 60000 : value.sealDriftMs, exclude = sealExclude(value.sealExclude);
|
|
139
|
-
if (typeof host !== 'string' ||
|
|
140
|
-
!host ||
|
|
141
|
-
host.length > 253 ||
|
|
142
|
-
typeof port !== 'number' ||
|
|
143
|
-
!Number.isInteger(port) ||
|
|
144
|
-
port < 0 ||
|
|
145
|
-
port > 65535 ||
|
|
146
|
-
typeof bodyLimit !== 'number' ||
|
|
147
|
-
!Number.isSafeInteger(bodyLimit) ||
|
|
148
|
-
bodyLimit < 1 ||
|
|
149
|
-
bodyLimit > 67108864 ||
|
|
150
|
-
typeof requestTimeout !== 'number' ||
|
|
151
|
-
!Number.isSafeInteger(requestTimeout) ||
|
|
152
|
-
requestTimeout < 1 ||
|
|
153
|
-
requestTimeout > 2147483647 ||
|
|
154
|
-
typeof sealDriftMs !== 'number' ||
|
|
155
|
-
!Number.isSafeInteger(sealDriftMs) ||
|
|
156
|
-
sealDriftMs < 1000 ||
|
|
157
|
-
sealDriftMs > 600000 ||
|
|
158
|
-
!exclude)
|
|
159
|
-
throw new WebError('INVALID_OPTIONS');
|
|
160
|
-
return {
|
|
161
|
-
host,
|
|
162
|
-
port,
|
|
163
|
-
bodyLimit,
|
|
164
|
-
requestTimeout,
|
|
165
|
-
healthRoutes: healthRoutes(value.healthRoutes),
|
|
166
|
-
trustProxy: trustProxy(value.trustProxy),
|
|
167
|
-
sealDriftMs,
|
|
168
|
-
sealExclude: exclude,
|
|
169
|
-
};
|
|
170
|
-
}
|
|
51
|
+
const injectPoint = definePoint('dokebi-testing:inject');
|
|
171
52
|
const hooks = new Map([
|
|
172
53
|
['onRequest', 2],
|
|
173
54
|
['preParsing', 3],
|
|
@@ -180,80 +61,232 @@ const hooks = new Map([
|
|
|
180
61
|
['onTimeout', 2],
|
|
181
62
|
['onRequestAbort', 1],
|
|
182
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
|
+
}
|
|
183
153
|
class WebOwner {
|
|
184
154
|
context;
|
|
185
155
|
options;
|
|
186
156
|
server;
|
|
187
|
-
|
|
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
|
+
};
|
|
188
168
|
#wrapped = new WeakSet();
|
|
189
169
|
#closed = false;
|
|
190
170
|
#frozen = false;
|
|
191
171
|
#draining = false;
|
|
192
172
|
#address;
|
|
193
173
|
#sealing;
|
|
174
|
+
/** Error responders, the last added first (D-0074). */
|
|
175
|
+
#responders = [];
|
|
194
176
|
api;
|
|
195
|
-
|
|
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) {
|
|
196
185
|
this.context = context;
|
|
197
186
|
this.options = options;
|
|
198
|
-
|
|
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 = {
|
|
199
196
|
logger: false,
|
|
200
|
-
bodyLimit: options.
|
|
201
|
-
requestTimeout: options.
|
|
202
|
-
|
|
203
|
-
|
|
197
|
+
bodyLimit: options.maxBodyBytes,
|
|
198
|
+
requestTimeout: options.requestTimeoutMs,
|
|
199
|
+
schemaController,
|
|
200
|
+
...PINNED,
|
|
204
201
|
...(options.trustProxy.length ? { trustProxy: [...options.trustProxy] } : {}),
|
|
205
|
-
}
|
|
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);
|
|
206
208
|
const owner = this;
|
|
207
|
-
|
|
209
|
+
logger.log('debug', 'Web server configured', {
|
|
208
210
|
host: options.host,
|
|
209
211
|
port: options.port,
|
|
210
|
-
bodyLimit: options.
|
|
211
|
-
requestTimeout: options.
|
|
212
|
+
bodyLimit: options.maxBodyBytes,
|
|
213
|
+
requestTimeout: options.requestTimeoutMs,
|
|
212
214
|
healthRoutes: options.healthRoutes ? { ...options.healthRoutes } : false,
|
|
213
215
|
trustProxy: options.trustProxy.length,
|
|
214
216
|
sealDriftMs: options.sealDriftMs,
|
|
215
217
|
sealExclude: options.sealExclude.length,
|
|
218
|
+
formBody: options.formBody,
|
|
219
|
+
formMaxFields: options.formMaxFields,
|
|
220
|
+
errorBodies: this.#production ? 'production' : 'development',
|
|
216
221
|
health: health !== undefined,
|
|
217
|
-
|
|
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() }),
|
|
218
228
|
});
|
|
219
229
|
const failures = new Repeats();
|
|
220
|
-
this.server.setErrorHandler((error, request, reply) =>
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
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
|
+
});
|
|
237
254
|
}
|
|
238
|
-
else
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
route: request.routeOptions.url ?? 'unmatched',
|
|
243
|
-
error: errorText(error),
|
|
244
|
-
errorCode: error?.code,
|
|
255
|
+
else
|
|
256
|
+
logger.log('warn', 'Verify token ignored: unexpected format', {
|
|
257
|
+
code: 'VERIFY_TOKEN_INVALID',
|
|
258
|
+
variable: VERIFY_TOKEN_ENV,
|
|
245
259
|
});
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
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) => {
|
|
251
284
|
if (request.routeOptions.config.dokebiHealth === true)
|
|
252
|
-
return;
|
|
285
|
+
return done();
|
|
253
286
|
// A draining node:cluster worker no longer listens; a request still arriving on one of its
|
|
254
287
|
// open keep-alive connections is served and that connection then closes, so the client's
|
|
255
288
|
// next request goes to another worker instead of seeing 503 (D-0036).
|
|
256
|
-
const servesWhileDraining = this.#draining &&
|
|
289
|
+
const servesWhileDraining = this.#draining && worker;
|
|
257
290
|
if (servesWhileDraining)
|
|
258
291
|
reply.header('connection', 'close');
|
|
259
292
|
const reason = this.#draining
|
|
@@ -266,53 +299,25 @@ class WebOwner {
|
|
|
266
299
|
? 'NOT_READY'
|
|
267
300
|
: undefined;
|
|
268
301
|
if (reason) {
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
context.logger.log('debug', 'HTTP request refused', {
|
|
272
|
-
reason,
|
|
273
|
-
method: request.method,
|
|
274
|
-
url: request.url.split('?', 1)[0]?.slice(0, 200),
|
|
275
|
-
});
|
|
276
|
-
return reply
|
|
277
|
-
.code(503)
|
|
278
|
-
.header('connection', 'close')
|
|
279
|
-
.send({ error: 'SERVICE_UNAVAILABLE', reason });
|
|
302
|
+
this.#refuse(request, reply, reason);
|
|
303
|
+
return;
|
|
280
304
|
}
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
reply.raw.off('close', finish);
|
|
288
|
-
release();
|
|
289
|
-
if (this.#draining && cluster.isWorker)
|
|
290
|
-
this.server.server.closeIdleConnections();
|
|
291
|
-
};
|
|
292
|
-
reply.raw.once('finish', finish);
|
|
293
|
-
reply.raw.once('close', finish);
|
|
294
|
-
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);
|
|
295
311
|
});
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
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)
|
|
300
317
|
reply.header('connection', 'close');
|
|
301
|
-
|
|
302
|
-
});
|
|
303
|
-
// D-0062: the seal slot. Both hooks do nothing until something asks for sealing.
|
|
304
|
-
const sealing = new WebSealing(context.logger, { driftMs: options.sealDriftMs, exclude: options.sealExclude }, (request) => this.api.requestHost(request), errorText);
|
|
305
|
-
this.#sealing = sealing;
|
|
306
|
-
this.server.addHook('onRequest', async (request, reply) => {
|
|
307
|
-
if (!sealing.provider)
|
|
308
|
-
return;
|
|
309
|
-
return sealing.onRequest(request, reply);
|
|
310
|
-
});
|
|
311
|
-
this.server.addHook('onSend', async (request, reply, payload) => {
|
|
312
|
-
if (!sealing.provider)
|
|
313
|
-
return payload;
|
|
314
|
-
return sealing.onSend(request, reply, payload);
|
|
318
|
+
done(null, sealing.provider ? sealing.onSend(request, reply, payload) : payload);
|
|
315
319
|
});
|
|
320
|
+
this.#formBody(options);
|
|
316
321
|
this.server.addHook('onRoute', (route) => {
|
|
317
322
|
// `seal` on a route given to Fastify directly (a register() scope, @dokebi/router mount)
|
|
318
323
|
// becomes `config.dokebiSeal` too, so every way of adding a route can opt out (D-0062).
|
|
@@ -329,8 +334,19 @@ class WebOwner {
|
|
|
329
334
|
if (config?.dokebiHealth === true)
|
|
330
335
|
return;
|
|
331
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.
|
|
332
340
|
route.handler = function (request, reply) {
|
|
333
|
-
|
|
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;
|
|
334
350
|
};
|
|
335
351
|
const fields = route;
|
|
336
352
|
for (const name of hooks.keys()) {
|
|
@@ -398,7 +414,7 @@ class WebOwner {
|
|
|
398
414
|
this.#assertMutable();
|
|
399
415
|
sealing.setProvider(provider);
|
|
400
416
|
// Registered on the root before any plugin scope exists, so every route inherits it.
|
|
401
|
-
this.server.addContentTypeParser(provider.contentType, { parseAs: 'string', bodyLimit: options.
|
|
417
|
+
this.server.addContentTypeParser(provider.contentType, { parseAs: 'string', bodyLimit: options.maxBodyBytes }, (request, body) => sealing.parse(request, String(body)));
|
|
402
418
|
},
|
|
403
419
|
sealRequests: (predicate) => {
|
|
404
420
|
this.#assertMutable();
|
|
@@ -408,22 +424,75 @@ class WebOwner {
|
|
|
408
424
|
get sealing() {
|
|
409
425
|
return sealing.provider !== undefined;
|
|
410
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
|
+
},
|
|
411
438
|
});
|
|
412
439
|
}
|
|
413
440
|
#assertMutable() {
|
|
414
441
|
if (this.#frozen || this.#closed)
|
|
415
442
|
throw new WebError('FROZEN');
|
|
416
443
|
}
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
//
|
|
420
|
-
|
|
421
|
-
|
|
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
|
+
});
|
|
422
474
|
}
|
|
423
475
|
track(work) {
|
|
424
476
|
if (this.#closed)
|
|
425
477
|
return Promise.reject(new WebError('CLOSED'));
|
|
426
|
-
|
|
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;
|
|
427
496
|
}
|
|
428
497
|
#hook(name, fn) {
|
|
429
498
|
const count = hooks.get(name);
|
|
@@ -433,6 +502,9 @@ class WebOwner {
|
|
|
433
502
|
(fn.length === count + 1 || (name === 'onRequestAbort' && fn.length !== 1))) {
|
|
434
503
|
throw new TypeError('Async Fastify hooks must not accept a done callback');
|
|
435
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;
|
|
436
508
|
const owner = this;
|
|
437
509
|
function invoke(instance, args) {
|
|
438
510
|
return owner.track(() => new Promise((resolve, reject) => {
|
|
@@ -485,6 +557,30 @@ class WebOwner {
|
|
|
485
557
|
this.#wrapped.add(wrapped);
|
|
486
558
|
return wrapped;
|
|
487
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
|
+
}
|
|
488
584
|
async start() {
|
|
489
585
|
this.#frozen = true;
|
|
490
586
|
const started = performance.now();
|
|
@@ -498,16 +594,35 @@ class WebOwner {
|
|
|
498
594
|
// node:cluster shares the port: the primary hands connections to a worker as soon as it
|
|
499
595
|
// listens, so a worker listens only once the whole application is ready (`ready`, D-0034).
|
|
500
596
|
// A single process listens here and answers 503 until then (health checks see it start).
|
|
501
|
-
if (!
|
|
597
|
+
if (!this.#worker)
|
|
502
598
|
await this.listen();
|
|
503
599
|
}
|
|
600
|
+
/** Listens unless this process does not serve (`runtime.serving` false, D-0063 §4). */
|
|
504
601
|
async listen() {
|
|
505
602
|
if (this.#address !== undefined)
|
|
506
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
|
+
}
|
|
507
612
|
const started = performance.now();
|
|
508
613
|
this.#address = await this.server.listen({ host: this.options.host, port: this.options.port });
|
|
509
|
-
|
|
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', {
|
|
510
623
|
address: this.#address,
|
|
624
|
+
urls: urls.length ? urls : [this.#address],
|
|
625
|
+
host: this.options.host,
|
|
511
626
|
ms: Math.round(performance.now() - started),
|
|
512
627
|
});
|
|
513
628
|
}
|
|
@@ -517,8 +632,8 @@ class WebOwner {
|
|
|
517
632
|
const started = performance.now();
|
|
518
633
|
const logger = this.context.logger;
|
|
519
634
|
logger.log('debug', 'Web drain started', {
|
|
520
|
-
pending: this.#
|
|
521
|
-
clusterWorker:
|
|
635
|
+
pending: this.#inflight,
|
|
636
|
+
clusterWorker: this.#worker,
|
|
522
637
|
});
|
|
523
638
|
// The node:cluster primary keeps handing new connections to a worker while it listens, so a
|
|
524
639
|
// draining worker stops listening first; new connections go to the other workers. A single
|
|
@@ -532,7 +647,7 @@ class WebOwner {
|
|
|
532
647
|
// keep-alive connections at once, racing clients that are just reusing them. Those
|
|
533
648
|
// connections stay; their next request is served with `Connection: close`.
|
|
534
649
|
let grace;
|
|
535
|
-
if (
|
|
650
|
+
if (this.#worker && this.server.server.listening) {
|
|
536
651
|
Server.prototype.close.call(this.server.server);
|
|
537
652
|
grace = delay(CLOSE_GRACE_MS);
|
|
538
653
|
logger.log('debug', 'Web worker stopped listening', { graceMs: CLOSE_GRACE_MS });
|
|
@@ -545,18 +660,19 @@ class WebOwner {
|
|
|
545
660
|
signal.addEventListener('abort', () => resolve(), { once: true, signal: listening.signal });
|
|
546
661
|
});
|
|
547
662
|
try {
|
|
548
|
-
while (this.#
|
|
549
|
-
await Promise.race([
|
|
663
|
+
while (this.#inflight > 0) {
|
|
664
|
+
await Promise.race([this.#whenIdle(), aborted]);
|
|
550
665
|
if (signal.aborted) {
|
|
551
666
|
// Deadline or forced stop: cut the remaining connections; core records the timeout.
|
|
552
667
|
logger.log('debug', 'Web drain cut connections', {
|
|
553
|
-
pending: this.#
|
|
668
|
+
pending: this.#inflight,
|
|
554
669
|
ms: Math.round(performance.now() - started),
|
|
555
670
|
});
|
|
556
671
|
this.server.server.closeAllConnections();
|
|
557
672
|
return;
|
|
558
673
|
}
|
|
559
|
-
// 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.
|
|
560
676
|
await immediate();
|
|
561
677
|
}
|
|
562
678
|
if (grace)
|
|
@@ -567,6 +683,255 @@ class WebOwner {
|
|
|
567
683
|
listening.abort();
|
|
568
684
|
}
|
|
569
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
|
+
}
|
|
570
935
|
async close() {
|
|
571
936
|
this.#closed = true;
|
|
572
937
|
const started = performance.now();
|
|
@@ -576,66 +941,122 @@ class WebOwner {
|
|
|
576
941
|
});
|
|
577
942
|
}
|
|
578
943
|
}
|
|
944
|
+
const NO_EXTENSION = Object.freeze({
|
|
945
|
+
hooks: undefined,
|
|
946
|
+
overridden: new Set(),
|
|
947
|
+
});
|
|
579
948
|
const HEALTH = 'dokebi-health';
|
|
580
|
-
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
|
+
}
|
|
581
953
|
function requirement(value) {
|
|
582
954
|
if (value === null || typeof value !== 'object')
|
|
583
|
-
throw
|
|
955
|
+
throw invalidEntry('Invalid web requirement');
|
|
584
956
|
if (typeof value.setup === 'function')
|
|
585
957
|
return dependencyOf(value);
|
|
586
958
|
if (typeof value.name !== 'string')
|
|
587
|
-
throw
|
|
959
|
+
throw invalidEntry('Invalid web requirement');
|
|
588
960
|
return value;
|
|
589
961
|
}
|
|
590
|
-
|
|
591
|
-
|
|
592
|
-
|
|
593
|
-
|
|
594
|
-
|
|
595
|
-
|
|
596
|
-
|
|
597
|
-
|
|
598
|
-
|
|
599
|
-
|
|
600
|
-
|
|
601
|
-
|
|
602
|
-
|
|
603
|
-
|
|
604
|
-
|
|
605
|
-
|
|
606
|
-
|
|
607
|
-
|
|
608
|
-
|
|
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
|
+
});
|
|
609
1033
|
}
|
|
610
|
-
if (list === undefined)
|
|
611
|
-
return { requires: [] };
|
|
612
|
-
if (!Array.isArray(list) || list.length > 256)
|
|
613
|
-
throw new TypeError('Invalid web requires');
|
|
614
|
-
const requires = list.map(requirement);
|
|
615
|
-
const names = new Set(requires.map((dependency) => dependency.name));
|
|
616
|
-
if (names.size !== requires.length || names.has('dokebi-web'))
|
|
617
|
-
throw new TypeError('Duplicate web requirement');
|
|
618
|
-
return { requires };
|
|
619
1034
|
}
|
|
620
1035
|
class WebRuntime {
|
|
621
1036
|
options;
|
|
1037
|
+
extension;
|
|
622
1038
|
health;
|
|
623
1039
|
#owner;
|
|
624
|
-
constructor(options, health) {
|
|
1040
|
+
constructor(options, extension, health) {
|
|
625
1041
|
this.options = options;
|
|
1042
|
+
this.extension = extension;
|
|
626
1043
|
this.health = health;
|
|
627
1044
|
}
|
|
628
1045
|
setup(context) {
|
|
629
|
-
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));
|
|
630
1047
|
this.#owner = owner;
|
|
631
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
|
+
}));
|
|
632
1053
|
return owner.api;
|
|
633
1054
|
}
|
|
634
1055
|
start() {
|
|
635
1056
|
return this.#owner?.start();
|
|
636
1057
|
}
|
|
637
1058
|
ready() {
|
|
638
|
-
return
|
|
1059
|
+
return this.#owner?.worker ? this.#owner.listen() : undefined;
|
|
639
1060
|
}
|
|
640
1061
|
drain(context) {
|
|
641
1062
|
return this.#owner?.drain(context.drainSignal);
|
|
@@ -643,24 +1064,22 @@ class WebRuntime {
|
|
|
643
1064
|
}
|
|
644
1065
|
export const createPlugin = definePlugin({
|
|
645
1066
|
name: 'dokebi-web',
|
|
646
|
-
version: '0.
|
|
647
|
-
core: '^0.
|
|
648
|
-
options:
|
|
649
|
-
entry:
|
|
1067
|
+
version: '0.4.0',
|
|
1068
|
+
core: '^0.4.0',
|
|
1069
|
+
options: declaration,
|
|
1070
|
+
entry: (input) => new WebEntryInput(input),
|
|
1071
|
+
contributes: [injectPoint],
|
|
650
1072
|
// A required dokebi-health in entry.requires replaces the optional link.
|
|
651
1073
|
dependencies: ({ entry }) => {
|
|
1074
|
+
// The extension is created here, once: a broken subclass fails the factory call.
|
|
1075
|
+
entry?.extension();
|
|
652
1076
|
const requires = entry?.requires ?? [];
|
|
653
1077
|
return requires.some((dependency) => dependency.name === HEALTH)
|
|
654
1078
|
? requires
|
|
655
1079
|
: [...requires, health];
|
|
656
1080
|
},
|
|
657
|
-
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) ??
|
|
658
1082
|
health)),
|
|
659
1083
|
});
|
|
660
|
-
/** Declares dokebi-web as a required provider
|
|
661
|
-
export
|
|
662
|
-
name: 'dokebi-web',
|
|
663
|
-
packageName: '@dokebi/web',
|
|
664
|
-
version: '^0.2.0',
|
|
665
|
-
load: () => import('./index.js'),
|
|
666
|
-
});
|
|
1084
|
+
/** Declares dokebi-web as a required provider (also `@dokebi/web/dependency`, D-0063 §6). */
|
|
1085
|
+
export { dependency } from './dependency.js';
|