@jini-ai/http-kit 0.7.3-next.2 → 0.7.3-next.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +49 -0
- package/dist/adapter-request.d.ts +101 -0
- package/dist/adapter-request.js +100 -0
- package/dist/adapter.d.ts +31 -7
- package/dist/adapter.js +291 -43
- package/dist/deferred-body.d.ts +14 -0
- package/dist/deferred-body.js +85 -0
- package/dist/dev-proxy.d.ts +76 -0
- package/dist/dev-proxy.js +244 -0
- package/dist/index.d.ts +3 -1
- package/dist/index.js +2 -0
- package/dist/node-bridge.d.ts +11 -1
- package/dist/node-bridge.js +59 -11
- package/dist/rate-limit.d.ts +2 -14
- package/dist/raw-route.d.ts +35 -0
- package/dist/raw-route.js +279 -0
- package/dist/reporter-internal-error.d.ts +19 -0
- package/dist/reporter-internal-error.js +34 -0
- package/dist/request-id.d.ts +9 -0
- package/dist/request-id.js +21 -0
- package/dist/request.d.ts +8 -3
- package/dist/request.js +17 -2
- package/dist/types.d.ts +129 -6
- package/package.json +18 -6
|
@@ -0,0 +1,244 @@
|
|
|
1
|
+
import { Agent as HttpAgent, request as httpRequest } from "node:http";
|
|
2
|
+
import { Agent as HttpsAgent, request as httpsRequest } from "node:https";
|
|
3
|
+
/**
|
|
4
|
+
* @file Proxies `<basePath>/*` to a frontend dev server (the host passes its URL as `devProxyUrl`;
|
|
5
|
+
* this module reads no environment) so the browser never leaves this server's own origin — replacing
|
|
6
|
+
* the 302-redirect dev-proxy mode a host's static-asset registration used to run.
|
|
7
|
+
*
|
|
8
|
+
* The redirect existed because a straight proxy has one hard problem: Vite's HMR client opens a
|
|
9
|
+
* WebSocket, and an ordinary HTTP reverse proxy only ever sees `request` events, not the `upgrade`
|
|
10
|
+
* event a WebSocket handshake arrives as. A redirect sidestepped that by putting the browser
|
|
11
|
+
* directly on Vite's own origin, where its WS client needs no help. This module solves the problem
|
|
12
|
+
* instead of avoiding it: {@link createDevProxyRequestHandler} forwards ordinary requests, and
|
|
13
|
+
* {@link createDevProxyUpgradeListener} forwards the `upgrade` event so HMR keeps working through a
|
|
14
|
+
* same-origin proxy. Verified against the installed Vite (7.3.6) source: with no `server.hmr.path`
|
|
15
|
+
* override, its HMR client computes the socket URL as `<page origin><config.base>` — i.e. exactly
|
|
16
|
+
* `/admin/` on whichever origin served the page — and its server-side `shouldHandle` gate matches
|
|
17
|
+
* upgrades by that same base path, so proxying `/admin/*` (including the bare-path fix below) is
|
|
18
|
+
* sufficient; no separate HMR-specific route is needed.
|
|
19
|
+
*/
|
|
20
|
+
/**
|
|
21
|
+
* A TLS agent scoped to ONE dev-only upstream: Vite's own mkcert-issued certificate is
|
|
22
|
+
* locally-trusted in the OS/browser store but not in Node's separate bundled CA list — the same gap
|
|
23
|
+
* a Vite config's own `/api` proxy entries hit and fix with `secure: false`. Scoped to
|
|
24
|
+
* this module's own outbound connections only; `NODE_TLS_REJECT_UNAUTHORIZED` is never touched, so
|
|
25
|
+
* every other TLS connection this process makes (including real calls to third-party provider APIs)
|
|
26
|
+
* keeps full certificate verification. `keepAlive` reuses one TLS connection across the many small
|
|
27
|
+
* ESM module requests a Vite dev page issues, rather than a fresh handshake per file.
|
|
28
|
+
*/
|
|
29
|
+
function createDevUpstreamHttpsAgent() {
|
|
30
|
+
return new HttpsAgent({ rejectUnauthorized: false, keepAlive: true });
|
|
31
|
+
}
|
|
32
|
+
/** Plain-HTTP counterpart for a boot with dev TLS disabled — kept for parity, not certificate-related. */
|
|
33
|
+
function createDevUpstreamHttpAgent() {
|
|
34
|
+
return new HttpAgent({ keepAlive: true });
|
|
35
|
+
}
|
|
36
|
+
/**
|
|
37
|
+
* Rewrites a bare `/admin` request to `/admin/` before it reaches Vite. Vite's `base: "/admin/"`
|
|
38
|
+
* only falls through to `index.html` on an exact base match, trailing slash included — a bare
|
|
39
|
+
* `/admin` 404s at Vite itself. Mirrors the identical fix the redirect branch this module replaces
|
|
40
|
+
* used to apply (`req.path === "/admin" ? "/admin/" : req.originalUrl`), rewritten to work directly
|
|
41
|
+
* off a raw URL string so the same helper serves both the request proxy (which has `req.originalUrl`)
|
|
42
|
+
* and the upgrade proxy (which only has the raw `req.url`).
|
|
43
|
+
*
|
|
44
|
+
* @param url - the incoming request's full path + query string.
|
|
45
|
+
* @param basePath - the mount path the dev server serves under, without a trailing slash (e.g. `/admin`).
|
|
46
|
+
* @complexity O(n) in `url`'s length (one indexOf, one slice).
|
|
47
|
+
*/
|
|
48
|
+
export function resolveDevProxyPath({ url, basePath }, _optional = {}) {
|
|
49
|
+
const queryIndex = url.indexOf("?");
|
|
50
|
+
const pathname = queryIndex === -1 ? url : url.slice(0, queryIndex);
|
|
51
|
+
if (pathname !== basePath)
|
|
52
|
+
return url;
|
|
53
|
+
return `${basePath}/${queryIndex === -1 ? "" : url.slice(queryIndex)}`;
|
|
54
|
+
}
|
|
55
|
+
/**
|
|
56
|
+
* Hop-by-hop header names (RFC 7230 §6.1, plus `keep-alive`/`proxy-connection` which real servers
|
|
57
|
+
* still send even though the RFC only names it as an example): meaningful only between this proxy
|
|
58
|
+
* and the ONE upstream connection that produced them, never valid to relay verbatim to the actual
|
|
59
|
+
* client on the other side of a proxy. Forwarding `connection` in particular used to merely be
|
|
60
|
+
* sloppy under an HTTP/1.1-only client — under an HTTP/2 client (now possible: {@link
|
|
61
|
+
* createDevProxyRequestHandler}'s `res` may be an HTTP/2 compat response once `index.ts`'s
|
|
62
|
+
* listener negotiates `h2`) it is a hard failure: Node's http2 compatibility layer throws
|
|
63
|
+
* `ERR_HTTP2_INVALID_CONNECTION_HEADER` the moment a `connection` header reaches `writeHead()`, and
|
|
64
|
+
* Vite's own Node HTTP/1.1 server sets `Connection: keep-alive` on its responses by default — so
|
|
65
|
+
* every proxied `/admin/*` response carried this header before the filter below was added.
|
|
66
|
+
*/
|
|
67
|
+
const HOP_BY_HOP_RESPONSE_HEADERS = new Set(["connection", "keep-alive", "proxy-connection", "transfer-encoding", "upgrade", "proxy-authenticate", "proxy-authorization", "trailer"]);
|
|
68
|
+
/**
|
|
69
|
+
* Drops hop-by-hop headers (see {@link HOP_BY_HOP_RESPONSE_HEADERS}) from an upstream response
|
|
70
|
+
* before it is relayed to the actual client. Node's `IncomingMessage.headers` keys are already
|
|
71
|
+
* lower-cased, so a plain `Set` lookup is enough — no case-folding needed here.
|
|
72
|
+
*
|
|
73
|
+
* @complexity O(n) in the number of response headers.
|
|
74
|
+
*/
|
|
75
|
+
export function stripHopByHopHeaders({ headers }, _optional = {}) {
|
|
76
|
+
const filtered = {};
|
|
77
|
+
for (const [name, value] of Object.entries(headers)) {
|
|
78
|
+
if (HOP_BY_HOP_RESPONSE_HEADERS.has(name))
|
|
79
|
+
continue;
|
|
80
|
+
filtered[name] = value;
|
|
81
|
+
}
|
|
82
|
+
return filtered;
|
|
83
|
+
}
|
|
84
|
+
/** @complexity O(1). */
|
|
85
|
+
function resolveDevProxyUpstream({ devProxyUrl, basePath }, _optional = {}) {
|
|
86
|
+
const target = new URL(devProxyUrl);
|
|
87
|
+
const isHttps = target.protocol === "https:";
|
|
88
|
+
return {
|
|
89
|
+
basePath,
|
|
90
|
+
target,
|
|
91
|
+
requestFn: isHttps ? httpsRequest : httpRequest,
|
|
92
|
+
// One agent per proxy instance (not module state): the keep-alive pool lives and dies with its proxy.
|
|
93
|
+
agent: isHttps ? createDevUpstreamHttpsAgent() : createDevUpstreamHttpAgent(),
|
|
94
|
+
};
|
|
95
|
+
}
|
|
96
|
+
/** Shared request options both the ordinary and upgrade proxies send. */
|
|
97
|
+
function buildProxyRequestOptions(upstream, req) {
|
|
98
|
+
return {
|
|
99
|
+
hostname: upstream.target.hostname,
|
|
100
|
+
port: upstream.target.port,
|
|
101
|
+
// Host is rewritten to the upstream's own — Vite's dev server allowlists request hosts
|
|
102
|
+
// (`server.allowedHosts`) and this keeps that check, and any base-URL logic Vite derives from
|
|
103
|
+
// the Host header, seeing exactly what it would see when hit directly.
|
|
104
|
+
headers: { ...req.headers, host: upstream.target.host },
|
|
105
|
+
path: resolveDevProxyPath({ url: req.url, basePath: upstream.basePath }),
|
|
106
|
+
method: req.method,
|
|
107
|
+
agent: upstream.agent,
|
|
108
|
+
};
|
|
109
|
+
}
|
|
110
|
+
/**
|
|
111
|
+
* Builds the Node request listener that proxies ordinary (non-WebSocket) `/admin/*` requests to Vite.
|
|
112
|
+
* It speaks `IncomingMessage`/`ServerResponse` only, so any host (an Express `app.all`, a bare
|
|
113
|
+
* `http.createServer`) can mount it.
|
|
114
|
+
*
|
|
115
|
+
* Streams both directions rather than buffering: `req` is piped straight into the upstream request,
|
|
116
|
+
* and the upstream response is piped straight into `res`, so this scales to Vite's large module
|
|
117
|
+
* bundles and source maps without holding them in memory.
|
|
118
|
+
*
|
|
119
|
+
* @param required.writeFailure - REQUIRED: the host's reply for an unreachable upstream (called only
|
|
120
|
+
* while `res.headersSent` is false; after the head went out the response is destroyed instead).
|
|
121
|
+
* @complexity O(1) setup per request; the actual byte volume is bounded by whatever Vite serves.
|
|
122
|
+
*/
|
|
123
|
+
export function createDevProxyRequestHandler({ devProxyUrl, basePath, writeFailure }, _optional = {}) {
|
|
124
|
+
const upstream = resolveDevProxyUpstream({ devProxyUrl, basePath });
|
|
125
|
+
return (req, res) => {
|
|
126
|
+
const proxyReq = upstream.requestFn(buildProxyRequestOptions(upstream, { method: req.method, headers: req.headers, url: req.url ?? "" }), (proxyRes) => {
|
|
127
|
+
// A client-side `IncomingMessage` handed to a `request()` response callback always carries the
|
|
128
|
+
// parsed status line, so `statusCode` is set here (it is only optional on the server-side type).
|
|
129
|
+
if (proxyRes.statusCode === undefined) {
|
|
130
|
+
proxyRes.resume();
|
|
131
|
+
proxyReq.destroy(new Error("admin dev proxy response has no status code"));
|
|
132
|
+
return;
|
|
133
|
+
}
|
|
134
|
+
res.writeHead(proxyRes.statusCode, stripHopByHopHeaders({ headers: proxyRes.headers }));
|
|
135
|
+
proxyRes.pipe(res);
|
|
136
|
+
});
|
|
137
|
+
proxyReq.on("error", (error) => {
|
|
138
|
+
if (res.headersSent) {
|
|
139
|
+
res.destroy();
|
|
140
|
+
return;
|
|
141
|
+
}
|
|
142
|
+
writeFailure({ res, error, target: upstream.target });
|
|
143
|
+
});
|
|
144
|
+
req.pipe(proxyReq);
|
|
145
|
+
};
|
|
146
|
+
}
|
|
147
|
+
/** Formats an upstream upgrade response's raw headers back into wire format for the client socket.
|
|
148
|
+
* The `upgrade` event only fires for a parsed `101` response, so its status code and reason phrase
|
|
149
|
+
* (possibly empty, never absent) are always present on the client-side `IncomingMessage`. */
|
|
150
|
+
function formatUpgradeResponseHead({ statusCode, statusMessage, rawHeaders }, _optional = {}) {
|
|
151
|
+
let headerLines = "";
|
|
152
|
+
for (let i = 0; i < rawHeaders.length; i += 2) {
|
|
153
|
+
headerLines += `${rawHeaders[i]}: ${rawHeaders[i + 1]}\r\n`;
|
|
154
|
+
}
|
|
155
|
+
return `HTTP/1.1 ${statusCode} ${statusMessage}\r\n${headerLines}\r\n`;
|
|
156
|
+
}
|
|
157
|
+
/**
|
|
158
|
+
* Makes `victim` go away once `terminator` does, in either direction — call it once per direction to
|
|
159
|
+
* get full cross-destroy between two spliced sockets.
|
|
160
|
+
*
|
|
161
|
+
* Listens for `end` as well as `close`/`error`, which is the part easy to get wrong: `http.Server`
|
|
162
|
+
* (and this proxy's own outbound `http.request`) sets `allowHalfOpen: true` on its sockets, so a
|
|
163
|
+
* plain graceful disconnect (the common case — a browser tab closing, `curl` exiting) only ever
|
|
164
|
+
* delivers `end`, never `close`, to the OTHER side. `.destroy()` is idempotent (a no-op past the
|
|
165
|
+
* first call), so listening for all three and calling it from each is safe even when more than one
|
|
166
|
+
* fires for the same disconnect.
|
|
167
|
+
*
|
|
168
|
+
* Confirmed live: without the `end` listener specifically, a real test of this exact tunnel hung
|
|
169
|
+
* forever on teardown — the peer socket sat there fully disconnected but never noticed.
|
|
170
|
+
*/
|
|
171
|
+
function destroyOnTermination(terminator, victim) {
|
|
172
|
+
const destroyVictim = () => victim.destroy();
|
|
173
|
+
terminator.on("end", destroyVictim);
|
|
174
|
+
terminator.on("close", destroyVictim);
|
|
175
|
+
terminator.on("error", destroyVictim);
|
|
176
|
+
}
|
|
177
|
+
/**
|
|
178
|
+
* Pipes one client `upgrade` request through to the matching upstream connection, splicing the two
|
|
179
|
+
* raw sockets together for the rest of the connection's life. This is the piece an ordinary HTTP
|
|
180
|
+
* reverse proxy does not provide for free — `req`/`res` proxying only ever sees `request` events,
|
|
181
|
+
* never `upgrade` — and it is what makes Vite's HMR WebSocket survive a same-origin `/admin/*` proxy.
|
|
182
|
+
*
|
|
183
|
+
* Any bytes the client sent immediately after its handshake (`head`) are forwarded on to the
|
|
184
|
+
* upstream socket, and any the upstream sent immediately after its 101 response (`proxyHead`) are
|
|
185
|
+
* forwarded on to the client socket, before the bidirectional pipe takes over — both are empty in
|
|
186
|
+
* the overwhelmingly common case (a clean WebSocket handshake with no immediately-following frame)
|
|
187
|
+
* but dropping them silently would corrupt the stream on the rare case they are not.
|
|
188
|
+
*
|
|
189
|
+
* @complexity O(1) setup; the connection then runs as a plain byte pipe for its lifetime.
|
|
190
|
+
*/
|
|
191
|
+
function proxyDevUpgrade({ upstream, req, url, clientSocket, head }, _optional = {}) {
|
|
192
|
+
const proxyReq = upstream.requestFn(buildProxyRequestOptions(upstream, { method: req.method, headers: req.headers, url }));
|
|
193
|
+
proxyReq.on("upgrade", (proxyRes, proxySocket, proxyHead) => {
|
|
194
|
+
if (proxyRes.statusCode === undefined || proxyRes.statusMessage === undefined) {
|
|
195
|
+
proxySocket.destroy();
|
|
196
|
+
clientSocket.destroy(new Error("admin dev proxy upgrade response has no status line"));
|
|
197
|
+
return;
|
|
198
|
+
}
|
|
199
|
+
clientSocket.write(formatUpgradeResponseHead({ statusCode: proxyRes.statusCode, statusMessage: proxyRes.statusMessage, rawHeaders: proxyRes.rawHeaders }));
|
|
200
|
+
if (proxyHead.length > 0)
|
|
201
|
+
clientSocket.write(proxyHead);
|
|
202
|
+
if (head.length > 0)
|
|
203
|
+
proxySocket.write(head);
|
|
204
|
+
proxySocket.pipe(clientSocket);
|
|
205
|
+
clientSocket.pipe(proxySocket);
|
|
206
|
+
// Neither `.pipe()` above nor a graceful half-close tears down the OTHER socket on its own (see
|
|
207
|
+
// `destroyOnTermination`'s own doc) — without this, one side going away leaves the other leg of
|
|
208
|
+
// the tunnel, a real TCP socket held open to Vite or to the browser, dangling forever.
|
|
209
|
+
destroyOnTermination(proxySocket, clientSocket);
|
|
210
|
+
destroyOnTermination(clientSocket, proxySocket);
|
|
211
|
+
});
|
|
212
|
+
proxyReq.on("error", () => clientSocket.destroy());
|
|
213
|
+
clientSocket.on("error", () => proxyReq.destroy());
|
|
214
|
+
proxyReq.end();
|
|
215
|
+
}
|
|
216
|
+
/** The URL of an `upgrade` request this proxy claims (a present URL under `basePath`), else `undefined`. @complexity O(1). */
|
|
217
|
+
function claimedUpgradeUrl({ req, basePath }, _optional = {}) {
|
|
218
|
+
return req.url?.startsWith(basePath) === true ? req.url : undefined;
|
|
219
|
+
}
|
|
220
|
+
/**
|
|
221
|
+
* Builds the `upgrade` listener that makes Vite's HMR WebSocket work through the dev proxy — see
|
|
222
|
+
* this file's module doc for why an ordinary request proxy cannot provide this on its own.
|
|
223
|
+
*
|
|
224
|
+
* The host attaches the returned listener to the actual `http.Server`/`https.Server` instance (not
|
|
225
|
+
* the Express `app`): `upgrade` is a socket-level server event Express's own request routing never
|
|
226
|
+
* sees. Whether to attach it at all (dev-proxy URL configured, not a packaged build) is the host's
|
|
227
|
+
* decision — this module reads no environment.
|
|
228
|
+
*
|
|
229
|
+
* Only claims upgrade requests whose path starts with `basePath`; anything else is left alone (no
|
|
230
|
+
* `socket.destroy()`) so a future unrelated `upgrade` listener on the same server is not pre-empted.
|
|
231
|
+
*
|
|
232
|
+
* @complexity O(1) setup; the listener is O(1) per upgrade request.
|
|
233
|
+
*/
|
|
234
|
+
export function createDevProxyUpgradeListener({ devProxyUrl, basePath }, _optional = {}) {
|
|
235
|
+
const upstream = resolveDevProxyUpstream({ devProxyUrl, basePath });
|
|
236
|
+
return (req, socket, head) => {
|
|
237
|
+
// Only `<basePath>*` upgrades are claimed, so the URL is known to be present past this check.
|
|
238
|
+
const url = claimedUpgradeUrl({ req, basePath });
|
|
239
|
+
if (url === undefined)
|
|
240
|
+
return;
|
|
241
|
+
proxyDevUpgrade({ upstream, req, url, clientSocket: socket, head });
|
|
242
|
+
};
|
|
243
|
+
}
|
|
244
|
+
//# sourceMappingURL=dev-proxy.js.map
|
package/dist/index.d.ts
CHANGED
|
@@ -9,10 +9,12 @@
|
|
|
9
9
|
* owns sending. See the capability owners for raw-stream uploads, bodyless cleanup, attachment
|
|
10
10
|
* rejection mapping and host-owned claim/cleanup lifecycle rather than duplicating those rules here.
|
|
11
11
|
*/
|
|
12
|
-
export type { JsonRouteSpec, JsonRoutePorts } from './types.js';
|
|
12
|
+
export type { JsonRouteSpec, JsonRoutePorts, RawRouteSpec, RouteMountOptions, RouteRequestOptIns, RouteDepsSource } from './types.js';
|
|
13
13
|
export { defineJsonRoute, mountJsonRoute } from './adapter.js';
|
|
14
|
+
export { defineRawRoute, mountRawRoute } from './raw-route.js';
|
|
14
15
|
export type { RouteInternalErrorContext, RouteInternalErrorSink } from './internal-error.js';
|
|
15
16
|
export { reportRouteInternalError } from './internal-error.js';
|
|
17
|
+
export { createReporterRouteInternalError } from './reporter-internal-error.js';
|
|
16
18
|
export type { InstallRouteRegistrationGuardOptions, RouteRegistration } from './route-registration-guard.js';
|
|
17
19
|
export { getRouteRegistrationInventory, guardedRouteKey, installRouteRegistrationGuard, recordRouteRegistrations, } from './route-registration-guard.js';
|
|
18
20
|
export type { CreateSseChannelOptions, SseChannel } from './sse.js';
|
package/dist/index.js
CHANGED
|
@@ -1,5 +1,7 @@
|
|
|
1
1
|
export { defineJsonRoute, mountJsonRoute } from './adapter.js';
|
|
2
|
+
export { defineRawRoute, mountRawRoute } from './raw-route.js';
|
|
2
3
|
export { reportRouteInternalError } from './internal-error.js';
|
|
4
|
+
export { createReporterRouteInternalError } from './reporter-internal-error.js';
|
|
3
5
|
export { getRouteRegistrationInventory, guardedRouteKey, installRouteRegistrationGuard, recordRouteRegistrations, } from './route-registration-guard.js';
|
|
4
6
|
export { createSseChannel, requestedAfterCursor, sendRawApiError } from './sse.js';
|
|
5
7
|
export { mountPackHttp } from './pack-http.js';
|
package/dist/node-bridge.d.ts
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import type { IncomingMessage, ServerResponse } from 'node:http';
|
|
2
2
|
import { type SecretRedactionPattern } from '@jini-ai/core';
|
|
3
3
|
import { type Server } from '@jini-ai/core/contracts/server';
|
|
4
|
+
import { type ErrorReporter } from '@jini-ai/core/errors/reporter';
|
|
4
5
|
/** Optional per-request hints from a host framework that already touched the request. */
|
|
5
6
|
export interface NodeDispatchOptions {
|
|
6
7
|
/** Hand unmatched requests (`next()`) and handler failures (`next(error)`) to the host. */
|
|
@@ -43,6 +44,14 @@ export interface NodeDispatcherOptions {
|
|
|
43
44
|
* host passes its own API key shape). Ignored when `onUnhandledError` is given: that sink owns redaction.
|
|
44
45
|
*/
|
|
45
46
|
readonly redactionPatterns?: readonly SecretRedactionPattern[];
|
|
47
|
+
/**
|
|
48
|
+
* The host's error reporter. When given, it is the one reference source: an unhandled failure is
|
|
49
|
+
* recorded once (one host record, one tracker report) and the plain-words 500 shows its ERR- ID, so
|
|
50
|
+
* `onUnhandledError` and `redactionPatterns` are ignored (the reporter owns redaction). Only
|
|
51
|
+
* `record` is used, with no tracker: a route behind the bridge that is already traced (a reporter-mode
|
|
52
|
+
* JSON route) owns its own `http.route` operation, and the bridge never opens a second one around it.
|
|
53
|
+
*/
|
|
54
|
+
readonly reporter?: Pick<ErrorReporter, 'record'>;
|
|
46
55
|
/**
|
|
47
56
|
* For a host that replaces Express routes with route lists and must keep answering what Express
|
|
48
57
|
* answered. Paths match as Express 4 matches by default (fixed segments ignore letter case, one
|
|
@@ -102,7 +111,8 @@ export declare function sendWebResponse({ response, res }: {
|
|
|
102
111
|
* Creates a dispatcher with an empty route table.
|
|
103
112
|
* @param optional.onUnhandledError - Where a handler failure goes when no `next` was given, with the reference its 500 shows (default: redacted, to stderr).
|
|
104
113
|
* @param optional.redactionPatterns - Host key shapes the default stderr sink also masks.
|
|
114
|
+
* @param optional.reporter - The host's error reporter; its ERR- IDs replace the 12-hex references (see {@link NodeDispatcherOptions}).
|
|
105
115
|
* @param optional.expressCompatible - Keep Express's answers for path spellings, a bad percent-escape and OPTIONS (see {@link NodeDispatcherOptions}).
|
|
106
116
|
*/
|
|
107
|
-
export declare function createNodeDispatcher(_required?: Record<string, never>, { onUnhandledError, redactionPatterns, expressCompatible }?: NodeDispatcherOptions): NodeDispatcher;
|
|
117
|
+
export declare function createNodeDispatcher(_required?: Record<string, never>, { onUnhandledError, redactionPatterns, expressCompatible, reporter }?: NodeDispatcherOptions): NodeDispatcher;
|
|
108
118
|
//# sourceMappingURL=node-bridge.d.ts.map
|
package/dist/node-bridge.js
CHANGED
|
@@ -10,6 +10,7 @@ import { Readable } from 'node:stream';
|
|
|
10
10
|
import { inspect } from 'node:util';
|
|
11
11
|
import { redactSecrets } from '@jini-ai/core';
|
|
12
12
|
import { createRouteTable } from '@jini-ai/core/contracts/server';
|
|
13
|
+
import { UNAVAILABLE_ERROR_ID } from '@jini-ai/core/errors/reporter';
|
|
13
14
|
/**
|
|
14
15
|
* How many times longer a JSON text can get when it is parsed and printed again
|
|
15
16
|
* (`JSON.stringify(JSON.parse(text))`), which is what {@link consumedBody} does to a body an upstream
|
|
@@ -173,6 +174,22 @@ async function pipeBody({ body, out }) {
|
|
|
173
174
|
reader.releaseLock();
|
|
174
175
|
}
|
|
175
176
|
}
|
|
177
|
+
/**
|
|
178
|
+
* Adds a response's `Vary` fields to any a middleware or a route's static headers already set, as Express
|
|
179
|
+
* `res.vary` does: a replacement would drop e.g. a CORS `Origin` and let a cache serve one origin's answer
|
|
180
|
+
* to another. Field names are de-duplicated case-insensitively and `*` absorbs everything.
|
|
181
|
+
* @complexity O(n) in the number of field names.
|
|
182
|
+
*/
|
|
183
|
+
function appendVary({ out, value }, _optional = {}) {
|
|
184
|
+
const existing = out.getHeader('vary');
|
|
185
|
+
const fields = [];
|
|
186
|
+
for (const field of `${existing === undefined ? '' : String(existing)},${value}`.split(',')) {
|
|
187
|
+
const name = field.trim();
|
|
188
|
+
if (name && !fields.some((seen) => seen.toLowerCase() === name.toLowerCase()))
|
|
189
|
+
fields.push(name);
|
|
190
|
+
}
|
|
191
|
+
out.setHeader('vary', fields.includes('*') ? '*' : fields.join(', '));
|
|
192
|
+
}
|
|
176
193
|
/**
|
|
177
194
|
* Writes a web `Response` to a Node `ServerResponse`: status, headers (each `Set-Cookie` on its own line), then the
|
|
178
195
|
* body with backpressure, headers flushed before the first chunk so a stream reaches the client before its first event.
|
|
@@ -187,7 +204,11 @@ export async function sendWebResponse({ response, res }, { headOnly = false } =
|
|
|
187
204
|
// Set-Cookie cannot be comma-joined (cookie dates contain commas), so each one gets its own line.
|
|
188
205
|
const cookies = response.headers.getSetCookie();
|
|
189
206
|
response.headers.forEach((value, name) => {
|
|
190
|
-
if (name
|
|
207
|
+
if (name === 'set-cookie')
|
|
208
|
+
return;
|
|
209
|
+
if (name === 'vary')
|
|
210
|
+
appendVary({ out, value });
|
|
211
|
+
else
|
|
191
212
|
out.setHeader(name, value);
|
|
192
213
|
});
|
|
193
214
|
for (const cookie of cookies)
|
|
@@ -255,8 +276,31 @@ function containedSink(sink) {
|
|
|
255
276
|
function internalErrorResponse(reference) {
|
|
256
277
|
return plainText({ status: 500, text: `The server could not finish this request. Reference: ${reference}. Try again; if it keeps failing, send this reference to the site's owner.` });
|
|
257
278
|
}
|
|
279
|
+
/**
|
|
280
|
+
* Picks the reference source once, at creation: the reporter's ERR- incident ID when one is wired,
|
|
281
|
+
* else today's 12-hex reference through the contained sink. Never both, so a failure has one ID.
|
|
282
|
+
*/
|
|
283
|
+
function incidentSource({ reporter, onUnhandledError, redactionPatterns }) {
|
|
284
|
+
if (reporter)
|
|
285
|
+
return ({ error, step }) => recordWithReporter({ reporter, error, step });
|
|
286
|
+
const sink = containedSink(onUnhandledError ?? stderrSink(redactionPatterns));
|
|
287
|
+
return ({ error }) => {
|
|
288
|
+
const reference = newErrorReference();
|
|
289
|
+
sink({ error, reference });
|
|
290
|
+
return reference;
|
|
291
|
+
};
|
|
292
|
+
}
|
|
293
|
+
/** The reporter promises never to throw; this guard keeps a broken one from rejecting `handle()`, and the caller still gets the stand-in ID. */
|
|
294
|
+
function recordWithReporter({ reporter, error, step }) {
|
|
295
|
+
try {
|
|
296
|
+
return reporter.record({ error, step, operation: 'http.route' }).errorId;
|
|
297
|
+
}
|
|
298
|
+
catch {
|
|
299
|
+
return UNAVAILABLE_ERROR_ID;
|
|
300
|
+
}
|
|
301
|
+
}
|
|
258
302
|
/** Calls the matched route and writes its answer; a handler failure goes to `next(error)` or a plain 500. */
|
|
259
|
-
async function serveRoute({ incoming, out, method, options,
|
|
303
|
+
async function serveRoute({ incoming, out, method, options, reportIncident }, { url, match }) {
|
|
260
304
|
// A client that hangs up aborts `request.signal`, which is how a handler or stream notices.
|
|
261
305
|
// Observe response close: request close can fire when a POST body finishes while its response is still streaming. A normally finished response does not abort the signal.
|
|
262
306
|
const abort = new AbortController();
|
|
@@ -271,12 +315,14 @@ async function serveRoute({ incoming, out, method, options, onUnhandledError },
|
|
|
271
315
|
}
|
|
272
316
|
catch (error) {
|
|
273
317
|
out.off('close', onClose);
|
|
318
|
+
// Before any head went out the host's own error handler owns this failure, so it is handed over
|
|
319
|
+
// unrecorded: recording here as well would give one failure two incidents.
|
|
274
320
|
if (options.next) {
|
|
275
321
|
options.next(error);
|
|
276
322
|
return;
|
|
277
323
|
}
|
|
278
|
-
|
|
279
|
-
|
|
324
|
+
// No host handler: the bridge owns both the record and the one plain-words reply that shows its reference.
|
|
325
|
+
const reference = reportIncident({ error, step: 'Handle request' });
|
|
280
326
|
await sendWebResponse({ response: internalErrorResponse(reference), res: out })
|
|
281
327
|
.catch(() => { out.destroy(); });
|
|
282
328
|
return;
|
|
@@ -286,8 +332,9 @@ async function serveRoute({ incoming, out, method, options, onUnhandledError },
|
|
|
286
332
|
}
|
|
287
333
|
catch (error) {
|
|
288
334
|
// Headers are already on the wire, so no error page can follow: cut the connection so the
|
|
289
|
-
// client sees a failed response instead of a silently truncated one.
|
|
290
|
-
|
|
335
|
+
// client sees a failed response instead of a silently truncated one. The bridge owns this write,
|
|
336
|
+
// so it records the failure itself, once.
|
|
337
|
+
reportIncident({ error, step: 'Write response' });
|
|
291
338
|
out.destroy();
|
|
292
339
|
}
|
|
293
340
|
finally {
|
|
@@ -319,11 +366,12 @@ function expressAnswer({ dispatch, match }) {
|
|
|
319
366
|
* Creates a dispatcher with an empty route table.
|
|
320
367
|
* @param optional.onUnhandledError - Where a handler failure goes when no `next` was given, with the reference its 500 shows (default: redacted, to stderr).
|
|
321
368
|
* @param optional.redactionPatterns - Host key shapes the default stderr sink also masks.
|
|
369
|
+
* @param optional.reporter - The host's error reporter; its ERR- IDs replace the 12-hex references (see {@link NodeDispatcherOptions}).
|
|
322
370
|
* @param optional.expressCompatible - Keep Express's answers for path spellings, a bad percent-escape and OPTIONS (see {@link NodeDispatcherOptions}).
|
|
323
371
|
*/
|
|
324
|
-
export function createNodeDispatcher(_required = {}, { onUnhandledError, redactionPatterns = [], expressCompatible = false } = {}) {
|
|
372
|
+
export function createNodeDispatcher(_required = {}, { onUnhandledError, redactionPatterns = [], expressCompatible = false, reporter } = {}) {
|
|
325
373
|
const table = createRouteTable({}, { lenientPaths: expressCompatible });
|
|
326
|
-
const
|
|
374
|
+
const reportIncident = incidentSource({ reporter, onUnhandledError, redactionPatterns });
|
|
327
375
|
const dispatch = async (dispatchArgs) => {
|
|
328
376
|
const target = requestTarget({ incoming: dispatchArgs.incoming, origin: dispatchArgs.options.origin });
|
|
329
377
|
const match = target ? table.match({ method: dispatchArgs.method, pathname: target.pathname }) : null;
|
|
@@ -341,10 +389,10 @@ export function createNodeDispatcher(_required = {}, { onUnhandledError, redacti
|
|
|
341
389
|
server: { route: (route) => table.route(route) },
|
|
342
390
|
handle({ incoming, out }, options = {}) {
|
|
343
391
|
// The promise never rejects (the Express adapter discards it): anything left is reported and
|
|
344
|
-
// the connection cut. `
|
|
345
|
-
return dispatch({ incoming, out, method: incoming.method ?? 'GET', options,
|
|
392
|
+
// the connection cut. `reportIncident` is contained, and the cut runs even if it were not.
|
|
393
|
+
return dispatch({ incoming, out, method: incoming.method ?? 'GET', options, reportIncident, expressCompatible }).catch((error) => {
|
|
346
394
|
try {
|
|
347
|
-
|
|
395
|
+
reportIncident({ error, step: 'Serve request' });
|
|
348
396
|
}
|
|
349
397
|
finally {
|
|
350
398
|
out.destroy();
|
package/dist/rate-limit.d.ts
CHANGED
|
@@ -1,13 +1,9 @@
|
|
|
1
1
|
/** Fixed-window counting over a host-owned clock and counter store. */
|
|
2
2
|
import type { Clock } from '@jini-ai/core/primitives';
|
|
3
3
|
import type { RateLimiter } from '@jini-ai/core/contracts/server';
|
|
4
|
+
import type { ClientIpSource, RateLimitProfile } from '@jini-ai/core/contracts/site/http-kit-rate-limit';
|
|
4
5
|
export type { Clock } from '@jini-ai/core/primitives';
|
|
5
|
-
|
|
6
|
-
export interface RateLimitProfile {
|
|
7
|
-
readonly windowSeconds: number;
|
|
8
|
-
readonly max: number;
|
|
9
|
-
readonly burst: number;
|
|
10
|
-
}
|
|
6
|
+
export type { ClientIpSource, RateLimitProfile } from '@jini-ai/core/contracts/site/http-kit-rate-limit';
|
|
11
7
|
export interface CounterWindow {
|
|
12
8
|
readonly windowStartMs: number;
|
|
13
9
|
readonly count: number;
|
|
@@ -57,14 +53,6 @@ export declare function createRateLimiter({ profile, clock, store }: {
|
|
|
57
53
|
key: string;
|
|
58
54
|
}, optional: Record<string, never>) => number | Promise<number>;
|
|
59
55
|
}): RateLimiter;
|
|
60
|
-
/** Structural request shape; transport/framework trust configuration stays outside. */
|
|
61
|
-
export interface ClientIpSource {
|
|
62
|
-
readonly socket: {
|
|
63
|
-
readonly remoteAddress?: string;
|
|
64
|
-
};
|
|
65
|
-
readonly headers: Record<string, string | string[] | undefined>;
|
|
66
|
-
readonly ip?: string;
|
|
67
|
-
}
|
|
68
56
|
/**
|
|
69
57
|
* Host trust policy. A fallback may use framework-resolved `source.ip` only
|
|
70
58
|
* when the host has configured that framework's proxy trust appropriately.
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Non-JSON routes (HTML, streams, uploads, downloads, a redirect that sets cookies) on the same gates
|
|
3
|
+
* and host ports as `mountJsonRoute`: the handler answers with a web `Response`, which is written back
|
|
4
|
+
* through the node bridge's writer. Mounted with `app[method](path, handler)`, never `app.use`, so a
|
|
5
|
+
* host's route-table inventory sees exactly one route per spec, as it does for a JSON spec.
|
|
6
|
+
*/
|
|
7
|
+
import type { Express } from 'express';
|
|
8
|
+
import { type RouteHostContext } from '@jini-ai/core/contracts/server';
|
|
9
|
+
import type { RawRouteSpec, RouteMountOptions, RouteDepsSource } from './types.js';
|
|
10
|
+
/** The optional fields of a raw spec, settable in `defineRawRoute`'s second argument. */
|
|
11
|
+
type RawRouteOptionalKey = 'requireSameOrigin' | 'maxBodyBytes' | 'ports' | 'readHeaders' | 'requestFacts' | 'responseHeaders' | 'admittedResponseHeaders' | 'bufferedReply';
|
|
12
|
+
/**
|
|
13
|
+
* Combines required route fields and optional settings into a fresh raw spec, pinning its generic
|
|
14
|
+
* parameters at the definition site. Optional settings take precedence; neither argument is mutated.
|
|
15
|
+
* @complexity O(1).
|
|
16
|
+
*/
|
|
17
|
+
export declare function defineRawRoute<Deps, Context = undefined>(requiredArgs: Omit<RawRouteSpec<Deps, Context>, RawRouteOptionalKey>, optionalArgs?: Pick<RawRouteSpec<Deps, Context>, RawRouteOptionalKey>): RawRouteSpec<Deps, Context>;
|
|
18
|
+
/**
|
|
19
|
+
* Mounts one raw spec. Gates run in `mountJsonRoute`'s order — static response headers, body cap,
|
|
20
|
+
* workspace (then `admittedResponseHeaders`), same-origin, authenticate — then `handle`, whose `raw.readBody` reads the request body only
|
|
21
|
+
* when called (so a route that defers its body never reads an unauthorized one); a thrown error takes the same `onError` /
|
|
22
|
+
* SEC-005 path. The returned `Response` is written with its status, every header (each `Set-Cookie`
|
|
23
|
+
* on its own line) and its body: none ends the answer, a stream is piped and cancelled when the
|
|
24
|
+
* client leaves, and `handle`'s `signal` aborts on that same disconnect.
|
|
25
|
+
* `optional.bodyParsers` are registered between the path and the handler of this one route (`RouteMountOptions`).
|
|
26
|
+
* @throws At mount, when the spec opts into `requestFacts` without the host's resolver port.
|
|
27
|
+
* @complexity O(1) setup; per request, the gates, the host ports, `handle` and the body copy.
|
|
28
|
+
*/
|
|
29
|
+
export declare function mountRawRoute<Deps, Context = undefined>(required: {
|
|
30
|
+
readonly app: Express;
|
|
31
|
+
readonly spec: RawRouteSpec<Deps, Context>;
|
|
32
|
+
readonly adapter?: RouteHostContext;
|
|
33
|
+
} & RouteDepsSource<Deps>, optional?: RouteMountOptions<Deps>): void;
|
|
34
|
+
export {};
|
|
35
|
+
//# sourceMappingURL=raw-route.d.ts.map
|