@jini-ai/http-kit 0.7.1 → 0.7.3-next.1
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/CHANGELOG.md +2 -2
- package/README.md +6 -6
- package/dist/adapter.d.ts +7 -50
- package/dist/adapter.js +12 -54
- package/dist/api-security-middleware.d.ts +0 -16
- package/dist/api-security-middleware.js +2 -18
- package/dist/index.d.ts +10 -15
- package/dist/index.js +7 -10
- package/dist/internal-error.d.ts +42 -0
- package/dist/internal-error.js +48 -0
- package/dist/local-daemon-request.d.ts +11 -4
- package/dist/local-daemon-request.js +1 -28
- package/dist/middleware.d.ts +1 -0
- package/dist/middleware.js +1 -0
- package/dist/node-bridge.d.ts +108 -0
- package/dist/node-bridge.js +356 -0
- package/dist/observability.d.ts +3 -14
- package/dist/origin.d.ts +13 -30
- package/dist/origin.js +13 -13
- package/dist/range.d.ts +53 -0
- package/dist/range.js +93 -0
- package/dist/rate-limit.d.ts +1 -13
- package/dist/rate-limit.js +5 -2
- package/dist/request.d.ts +2 -13
- package/dist/request.js +0 -13
- package/dist/response.d.ts +8 -7
- package/dist/response.js +0 -36
- package/dist/route-registration-guard.d.ts +14 -0
- package/dist/route-registration-guard.js +17 -0
- package/dist/run-credentials.d.ts +73 -0
- package/dist/run-credentials.js +71 -0
- package/dist/settings/contracts.d.ts +49 -0
- package/dist/settings/contracts.js +2 -0
- package/dist/settings/http-request.d.ts +36 -0
- package/dist/settings/http-request.js +50 -0
- package/dist/settings/http.d.ts +10 -0
- package/dist/settings/http.js +216 -0
- package/dist/settings/index.d.ts +4 -0
- package/dist/settings/index.js +3 -0
- package/dist/settings/shared.d.ts +16 -0
- package/dist/settings/shared.js +16 -0
- package/dist/settings/stream.d.ts +25 -0
- package/dist/settings/stream.js +180 -0
- package/dist/sse.d.ts +1 -15
- package/dist/sse.js +77 -72
- package/dist/trust-proxy.d.ts +36 -0
- package/dist/trust-proxy.js +45 -0
- package/dist/types.d.ts +4 -52
- package/dist/types.js +1 -4
- package/package.json +24 -14
- package/dist/raw-sse.d.ts +0 -49
- package/dist/raw-sse.js +0 -92
- package/dist/verified-origin/configured-origin.d.ts +0 -37
- package/dist/verified-origin/configured-origin.js +0 -99
- package/dist/verified-origin/index.d.ts +0 -7
- package/dist/verified-origin/index.js +0 -6
- package/dist/verified-origin/loopback-host.d.ts +0 -9
- package/dist/verified-origin/loopback-host.js +0 -17
- package/dist/verified-origin/origin.d.ts +0 -64
- package/dist/verified-origin/origin.js +0 -162
- package/dist/verified-origin/ports.d.ts +0 -38
- package/dist/verified-origin/ports.js +0 -2
- package/dist/verified-origin/repo.memory.d.ts +0 -32
- package/dist/verified-origin/repo.memory.js +0 -34
- package/dist/verified-origin/site-path.d.ts +0 -113
- package/dist/verified-origin/site-path.js +0 -188
- package/dist/verified-origin/types.d.ts +0 -33
- package/dist/verified-origin/types.js +0 -30
- package/dist/verified-origin.d.ts +0 -2
- package/dist/verified-origin.js +0 -2
package/dist/sse.js
CHANGED
|
@@ -1,14 +1,5 @@
|
|
|
1
|
+
import { DEFAULT_MAX_QUEUED_SSE_EVENTS } from '@jini-ai/core/contracts/server';
|
|
1
2
|
import { createApiErrorResponse } from '@jini-ai/protocol';
|
|
2
|
-
/**
|
|
3
|
-
* Cap on events queued for one client — covers both a pre-header replay
|
|
4
|
-
* burst and any backlog built up while `res.write` reports backpressure
|
|
5
|
-
* (`write() === false`, awaiting `'drain'`). A stalled or malicious client
|
|
6
|
-
* would otherwise let an unbounded producer grow this array without limit
|
|
7
|
-
* (SEC-006, carried forward from `runs.ts`'s original constant). Once
|
|
8
|
-
* exceeded, the connection is dropped rather than accepting unbounded
|
|
9
|
-
* memory growth.
|
|
10
|
-
*/
|
|
11
|
-
export const DEFAULT_MAX_QUEUED_SSE_EVENTS = 1000;
|
|
12
3
|
/** Default wire format: `id: <cursor>\nevent: <kind>\ndata: <json>\n\n`, matching the SSE spec's field syntax. */
|
|
13
4
|
function defaultFormatEvent(event) {
|
|
14
5
|
return `id: ${event.opaqueCursor}\nevent: ${event.kind}\ndata: ${JSON.stringify(event)}\n\n`;
|
|
@@ -43,19 +34,46 @@ function defaultFormatEvent(event) {
|
|
|
43
34
|
export function createSseChannel({ res }, options = {}) {
|
|
44
35
|
const maxQueuedEvents = options.maxQueuedEvents ?? DEFAULT_MAX_QUEUED_SSE_EVENTS;
|
|
45
36
|
const formatEvent = options.formatEvent ?? (({ event }) => defaultFormatEvent(event));
|
|
46
|
-
const
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
const
|
|
37
|
+
const state = {
|
|
38
|
+
queue: [], flowing: false, writable: true, closed: false, ending: false, closeCallbacks: [],
|
|
39
|
+
};
|
|
40
|
+
const { markClosed, finish, end } = createSseLifecycle(res, state);
|
|
41
|
+
const isTerminalEvent = (event) => options.isEndEvent?.({ event });
|
|
42
|
+
const pump = createSsePump(res, state, { formatEvent, options, finish, end, isTerminalEvent });
|
|
43
|
+
const { enqueue, open } = createSseProducer(res, state, { maxQueuedEvents, finish, pump });
|
|
44
|
+
res.on('drain', () => {
|
|
45
|
+
state.writable = true;
|
|
46
|
+
pump();
|
|
47
|
+
});
|
|
48
|
+
// The client disconnecting only marks the channel closed — it must not itself call `res.end()`
|
|
49
|
+
// (see `end()`'s doc for why calling it a second time would be safe anyway, but a route that
|
|
50
|
+
// still wants to send a *non-SSE* response — e.g. a JSON error — after discovering a subscribe
|
|
51
|
+
// failed needs `isClosed()` to be observable without the response having been touched yet).
|
|
52
|
+
res.on('close', markClosed);
|
|
53
|
+
const onClose = ({ callback }) => {
|
|
54
|
+
if (state.closed) {
|
|
55
|
+
callback();
|
|
56
|
+
return;
|
|
57
|
+
}
|
|
58
|
+
state.closeCallbacks.push(callback);
|
|
59
|
+
};
|
|
60
|
+
return {
|
|
61
|
+
enqueue,
|
|
62
|
+
open,
|
|
63
|
+
isClosed: () => state.closed,
|
|
64
|
+
end,
|
|
65
|
+
abandon: markClosed,
|
|
66
|
+
onClose,
|
|
67
|
+
};
|
|
68
|
+
}
|
|
69
|
+
function createSseLifecycle(res, state) {
|
|
52
70
|
const markClosed = () => {
|
|
53
|
-
if (closed)
|
|
71
|
+
if (state.closed)
|
|
54
72
|
return;
|
|
55
|
-
closed = true;
|
|
73
|
+
state.closed = true;
|
|
56
74
|
// Copy first: a callback that itself calls `onClose` during this loop must not be invoked
|
|
57
75
|
// twice or mutate the array being iterated.
|
|
58
|
-
const callbacks = closeCallbacks.splice(0, closeCallbacks.length);
|
|
76
|
+
const callbacks = state.closeCallbacks.splice(0, state.closeCallbacks.length);
|
|
59
77
|
for (const callback of callbacks)
|
|
60
78
|
callback();
|
|
61
79
|
};
|
|
@@ -67,86 +85,73 @@ export function createSseChannel({ res }, options = {}) {
|
|
|
67
85
|
};
|
|
68
86
|
/** Stop production now; an open backlog finishes on drain. O(1) excluding close callbacks. */
|
|
69
87
|
const end = () => {
|
|
70
|
-
if (closed)
|
|
88
|
+
if (state.closed)
|
|
71
89
|
return;
|
|
72
|
-
ending = true;
|
|
73
|
-
if (flowing && queue.length > 0)
|
|
90
|
+
state.ending = true;
|
|
91
|
+
if (state.flowing && state.queue.length > 0)
|
|
74
92
|
return;
|
|
75
93
|
finish();
|
|
76
94
|
};
|
|
95
|
+
return { markClosed, finish, end };
|
|
96
|
+
}
|
|
97
|
+
function createSsePump(res, state, { formatEvent, options, finish, end, isTerminalEvent }) {
|
|
77
98
|
const pump = () => {
|
|
78
|
-
if (!flowing || closed)
|
|
99
|
+
if (!state.flowing || state.closed)
|
|
79
100
|
return;
|
|
80
|
-
while (writable && queue.length > 0) {
|
|
81
|
-
|
|
82
|
-
let wroteOk;
|
|
83
|
-
try {
|
|
84
|
-
wroteOk = res.write(formatEvent({ event }));
|
|
85
|
-
}
|
|
86
|
-
catch (error) {
|
|
87
|
-
// A dead/broken transport must never throw back through whatever is producing events —
|
|
88
|
-
// stop this channel only.
|
|
89
|
-
options.onWriteError?.({ error });
|
|
90
|
-
finish();
|
|
101
|
+
while (state.writable && state.queue.length > 0) {
|
|
102
|
+
if (!writeNextSseEvent(res, state, { formatEvent, options, finish, isTerminalEvent }))
|
|
91
103
|
return;
|
|
92
|
-
}
|
|
93
|
-
if (wroteOk === false)
|
|
94
|
-
writable = false;
|
|
95
|
-
if (isTerminalEvent(event)) {
|
|
96
|
-
finish();
|
|
97
|
-
return;
|
|
98
|
-
}
|
|
99
104
|
}
|
|
100
|
-
if (ending)
|
|
105
|
+
if (state.ending)
|
|
101
106
|
end();
|
|
102
107
|
};
|
|
103
|
-
|
|
108
|
+
return pump;
|
|
109
|
+
}
|
|
110
|
+
function writeNextSseEvent(res, state, { formatEvent, options, finish, isTerminalEvent }) {
|
|
111
|
+
const event = state.queue.shift();
|
|
112
|
+
let wroteOk;
|
|
113
|
+
try {
|
|
114
|
+
wroteOk = res.write(formatEvent({ event }));
|
|
115
|
+
}
|
|
116
|
+
catch (error) {
|
|
117
|
+
// A dead/broken transport must never throw back through whatever is producing events —
|
|
118
|
+
// stop this channel only.
|
|
119
|
+
options.onWriteError?.({ error });
|
|
120
|
+
finish();
|
|
121
|
+
return false;
|
|
122
|
+
}
|
|
123
|
+
if (wroteOk === false)
|
|
124
|
+
state.writable = false;
|
|
125
|
+
if (isTerminalEvent(event)) {
|
|
126
|
+
finish();
|
|
127
|
+
return false;
|
|
128
|
+
}
|
|
129
|
+
return true;
|
|
130
|
+
}
|
|
131
|
+
function createSseProducer(res, state, { maxQueuedEvents, finish, pump }) {
|
|
104
132
|
const enqueue = ({ event }) => {
|
|
105
|
-
if (closed || ending)
|
|
133
|
+
if (state.closed || state.ending)
|
|
106
134
|
return;
|
|
107
|
-
if (queue.length >= maxQueuedEvents) {
|
|
135
|
+
if (state.queue.length >= maxQueuedEvents) {
|
|
108
136
|
// Slow/stalled consumer — disconnect rather than grow memory without bound.
|
|
109
137
|
finish();
|
|
110
138
|
return;
|
|
111
139
|
}
|
|
112
|
-
queue.push(event);
|
|
140
|
+
state.queue.push(event);
|
|
113
141
|
pump();
|
|
114
142
|
};
|
|
115
143
|
const open = () => {
|
|
116
|
-
if (closed || flowing)
|
|
144
|
+
if (state.closed || state.flowing)
|
|
117
145
|
return;
|
|
118
146
|
res.statusCode = 200;
|
|
119
147
|
res.setHeader('Content-Type', 'text/event-stream; charset=utf-8');
|
|
120
148
|
res.setHeader('Cache-Control', 'no-cache, no-transform');
|
|
121
149
|
res.setHeader('Connection', 'keep-alive');
|
|
122
150
|
res.flushHeaders();
|
|
123
|
-
flowing = true;
|
|
151
|
+
state.flowing = true;
|
|
124
152
|
pump();
|
|
125
153
|
};
|
|
126
|
-
|
|
127
|
-
writable = true;
|
|
128
|
-
pump();
|
|
129
|
-
});
|
|
130
|
-
// The client disconnecting only marks the channel closed — it must not itself call `res.end()`
|
|
131
|
-
// (see `end()`'s doc for why calling it a second time would be safe anyway, but a route that
|
|
132
|
-
// still wants to send a *non-SSE* response — e.g. a JSON error — after discovering a subscribe
|
|
133
|
-
// failed needs `isClosed()` to be observable without the response having been touched yet).
|
|
134
|
-
res.on('close', markClosed);
|
|
135
|
-
const onClose = ({ callback }) => {
|
|
136
|
-
if (closed) {
|
|
137
|
-
callback();
|
|
138
|
-
return;
|
|
139
|
-
}
|
|
140
|
-
closeCallbacks.push(callback);
|
|
141
|
-
};
|
|
142
|
-
return {
|
|
143
|
-
enqueue,
|
|
144
|
-
open,
|
|
145
|
-
isClosed: () => closed,
|
|
146
|
-
end,
|
|
147
|
-
abandon: markClosed,
|
|
148
|
-
onClose,
|
|
149
|
-
};
|
|
154
|
+
return { enqueue, open };
|
|
150
155
|
}
|
|
151
156
|
/** Reads a reconnect cursor from the standard `Last-Event-ID` header, falling back to an `afterCursor` query parameter. Shared by any SSE route that supports reconnect replay (the header takes precedence since it is what browsers set automatically on `EventSource` reconnect). */
|
|
152
157
|
export function requestedAfterCursor(req) {
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @file The `trust proxy` decision for a server behind a platform edge, without any server framework.
|
|
3
|
+
*
|
|
4
|
+
* Without it, every visitor behind a platform edge shares the edge's IP: per-IP rate limits become
|
|
5
|
+
* one global bucket and stored source IPs are the proxy's. Trusting X-Forwarded-For everywhere would
|
|
6
|
+
* be worse — a direct client could name any IP it likes. So it is trusted for exactly the hops a
|
|
7
|
+
* known platform puts in front of the app, and never when running locally or directly.
|
|
8
|
+
*
|
|
9
|
+
* With a hop count of N, the server takes the Nth address from the RIGHT of X-Forwarded-For — the
|
|
10
|
+
* one the outermost trusted proxy appended — so whatever the client wrote to the left is ignored.
|
|
11
|
+
*/
|
|
12
|
+
/** `false`, a hop count, or an address/subnet list (e.g. `"loopback, 10.0.0.0/8"`). */
|
|
13
|
+
export type TrustProxySetting = false | number | string;
|
|
14
|
+
/**
|
|
15
|
+
* Decide `trust proxy`.
|
|
16
|
+
*
|
|
17
|
+
* - `override` wins when non-empty: `false`/`0`/`off`/`no` -> trust none; an integer -> that many
|
|
18
|
+
* hops; anything else -> an address/subnet list. `true` is refused: it trusts every
|
|
19
|
+
* X-Forwarded-For entry, so any client could spoof its IP.
|
|
20
|
+
* - Otherwise the platform's declared hop count (`platformHops`, read only in this case).
|
|
21
|
+
* - Otherwise `false`: the socket peer is the client.
|
|
22
|
+
*
|
|
23
|
+
* @param required.override The operator's raw setting (e.g. an env value), or undefined.
|
|
24
|
+
* @param optional.platformHops Lazily reads the matched platform's hop count.
|
|
25
|
+
* @param optional.overrideName Names the setting in the refusal message. @param optional.serverLabel Names the server there.
|
|
26
|
+
* @throws Error when `override` is `true`.
|
|
27
|
+
* @complexity O(1) plus `platformHops`.
|
|
28
|
+
*/
|
|
29
|
+
export declare function resolveTrustProxySetting({ override }: {
|
|
30
|
+
override: string | undefined;
|
|
31
|
+
}, { platformHops, overrideName, serverLabel }?: {
|
|
32
|
+
platformHops?: () => number | undefined;
|
|
33
|
+
overrideName?: string;
|
|
34
|
+
serverLabel?: string;
|
|
35
|
+
}): TrustProxySetting;
|
|
36
|
+
//# sourceMappingURL=trust-proxy.d.ts.map
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @file The `trust proxy` decision for a server behind a platform edge, without any server framework.
|
|
3
|
+
*
|
|
4
|
+
* Without it, every visitor behind a platform edge shares the edge's IP: per-IP rate limits become
|
|
5
|
+
* one global bucket and stored source IPs are the proxy's. Trusting X-Forwarded-For everywhere would
|
|
6
|
+
* be worse — a direct client could name any IP it likes. So it is trusted for exactly the hops a
|
|
7
|
+
* known platform puts in front of the app, and never when running locally or directly.
|
|
8
|
+
*
|
|
9
|
+
* With a hop count of N, the server takes the Nth address from the RIGHT of X-Forwarded-For — the
|
|
10
|
+
* one the outermost trusted proxy appended — so whatever the client wrote to the left is ignored.
|
|
11
|
+
*/
|
|
12
|
+
/**
|
|
13
|
+
* Decide `trust proxy`.
|
|
14
|
+
*
|
|
15
|
+
* - `override` wins when non-empty: `false`/`0`/`off`/`no` -> trust none; an integer -> that many
|
|
16
|
+
* hops; anything else -> an address/subnet list. `true` is refused: it trusts every
|
|
17
|
+
* X-Forwarded-For entry, so any client could spoof its IP.
|
|
18
|
+
* - Otherwise the platform's declared hop count (`platformHops`, read only in this case).
|
|
19
|
+
* - Otherwise `false`: the socket peer is the client.
|
|
20
|
+
*
|
|
21
|
+
* @param required.override The operator's raw setting (e.g. an env value), or undefined.
|
|
22
|
+
* @param optional.platformHops Lazily reads the matched platform's hop count.
|
|
23
|
+
* @param optional.overrideName Names the setting in the refusal message. @param optional.serverLabel Names the server there.
|
|
24
|
+
* @throws Error when `override` is `true`.
|
|
25
|
+
* @complexity O(1) plus `platformHops`.
|
|
26
|
+
*/
|
|
27
|
+
export function resolveTrustProxySetting({ override }, { platformHops, overrideName = 'TRUST_PROXY', serverLabel = 'this server' } = {}) {
|
|
28
|
+
const value = override?.trim() ?? '';
|
|
29
|
+
if (value !== '')
|
|
30
|
+
return parseOverride({ value }, { overrideName, serverLabel });
|
|
31
|
+
return platformHops?.() ?? false;
|
|
32
|
+
}
|
|
33
|
+
/** The non-empty operator setting as `false`, a hop count or an address list; refuses `true`. */
|
|
34
|
+
function parseOverride({ value }, { overrideName, serverLabel }) {
|
|
35
|
+
const lower = value.toLowerCase();
|
|
36
|
+
if (lower === 'true') {
|
|
37
|
+
throw new Error(`${overrideName}="true" would trust X-Forwarded-For from any client. Set the number of proxy hops in front of ${serverLabel} (e.g. 1), or a list of proxy addresses/subnets.`);
|
|
38
|
+
}
|
|
39
|
+
if (['false', '0', 'off', 'no'].includes(lower))
|
|
40
|
+
return false;
|
|
41
|
+
if (/^\d+$/.test(value))
|
|
42
|
+
return Number(value);
|
|
43
|
+
return value;
|
|
44
|
+
}
|
|
45
|
+
//# sourceMappingURL=trust-proxy.js.map
|
package/dist/types.d.ts
CHANGED
|
@@ -1,58 +1,10 @@
|
|
|
1
1
|
/**
|
|
2
|
-
*
|
|
3
|
-
* (`
|
|
4
|
-
*
|
|
2
|
+
* Express-bound route-spec shapes (`JsonRoutePorts`, `JsonRouteSpec`) consumed by `mountJsonRoute`.
|
|
3
|
+
* The framework-free vocabulary (`Result`, `Handler`, `InputParser`, …) lives in
|
|
4
|
+
* `@jini-ai/core/contracts/server`.
|
|
5
5
|
*/
|
|
6
|
-
import type {
|
|
7
|
-
import type { ApiError } from '@jini-ai/protocol';
|
|
6
|
+
import type { Handler, HttpMethod, InputParser, RouteInputContext } from '@jini-ai/core/contracts/server';
|
|
8
7
|
import type { Response } from 'express';
|
|
9
|
-
/**
|
|
10
|
-
* A discriminated success/failure envelope used throughout the module in place of throwing.
|
|
11
|
-
* Route parsing, handling, and origin checks all resolve to a `Result` so the Adapter can fold
|
|
12
|
-
* every failure mode into one error-handling pipeline.
|
|
13
|
-
*/
|
|
14
|
-
export type Result<T, E = ApiError> = CoreResult<T, E>;
|
|
15
|
-
/** Builds a successful `Result` carrying `value`. */
|
|
16
|
-
export declare const ok: <T, E = ApiError>({ value }: {
|
|
17
|
-
readonly value: T;
|
|
18
|
-
}, _optional?: Record<string, never>) => Result<T, E>;
|
|
19
|
-
/** Builds a failed `Result` carrying `error`. */
|
|
20
|
-
export declare const err: <T = never, E = ApiError>({ error }: {
|
|
21
|
-
readonly error: E;
|
|
22
|
-
}, _optional?: Record<string, never>) => Result<T, E>;
|
|
23
|
-
/**
|
|
24
|
-
* The normalized shape of a raw HTTP request handed to a route's `parse` function: body, query,
|
|
25
|
-
* and params, decoupled from any framework `Request` type so parsers are unit-testable without
|
|
26
|
-
* a real server.
|
|
27
|
-
*/
|
|
28
|
-
export interface RouteInputContext {
|
|
29
|
-
body: unknown;
|
|
30
|
-
query: Record<string, unknown>;
|
|
31
|
-
params: Record<string, string>;
|
|
32
|
-
}
|
|
33
|
-
/** Parses a `RouteInputContext` into a typed `Input`, or fails with an `ApiError`. */
|
|
34
|
-
export type InputParser<Input> = (raw: RouteInputContext) => Result<Input>;
|
|
35
|
-
/**
|
|
36
|
-
* Handles a parsed `Input` (plus injected `Deps`) and produces a `Result<Output>`.
|
|
37
|
-
*
|
|
38
|
-
* `signal` is optional and additive: it aborts if the underlying HTTP request's connection drops
|
|
39
|
-
* before the Adapter has written a response (see `mountJsonRoute` in `adapter.ts`) — handlers read it from their optional arguments when they perform cancellable work.
|
|
40
|
-
*/
|
|
41
|
-
export type Handler<Input, Output, Deps, Context = undefined> = (requiredArgs: {
|
|
42
|
-
readonly input: Input;
|
|
43
|
-
readonly deps: Deps;
|
|
44
|
-
readonly context?: Context | undefined;
|
|
45
|
-
readonly authorize?: JsonRouteAuthorize;
|
|
46
|
-
}, optionalArgs?: {
|
|
47
|
-
readonly signal?: AbortSignal | undefined;
|
|
48
|
-
}) => Promise<Result<Output>> | Result<Output>;
|
|
49
|
-
/** HTTP verbs the Adapter can mount a `JsonRouteSpec` under. */
|
|
50
|
-
export type HttpMethod = 'get' | 'post' | 'put' | 'delete' | 'patch';
|
|
51
|
-
/** Explicit authorization remains at the route's chosen point, preserving validation precedence. */
|
|
52
|
-
export type JsonRouteAuthorize = (requiredArgs: {
|
|
53
|
-
readonly permission: string;
|
|
54
|
-
readonly entityType: string;
|
|
55
|
-
}, optionalArgs?: Record<string, never>) => Promise<void>;
|
|
56
8
|
/** Host-owned workspace, authentication/authorization and exception policy.
|
|
57
9
|
* Guards throw on rejection; the error port owns their wire envelope. Without an error port the
|
|
58
10
|
* adapter retains its caller-safe-error and SEC-005 redaction policy. Authentication can await
|
package/dist/types.js
CHANGED
|
@@ -1,5 +1,2 @@
|
|
|
1
|
-
|
|
2
|
-
export const ok = ({ value }, _optional = {}) => ({ ok: true, value });
|
|
3
|
-
/** Builds a failed `Result` carrying `error`. */
|
|
4
|
-
export const err = ({ error }, _optional = {}) => ({ ok: false, error });
|
|
1
|
+
export {};
|
|
5
2
|
//# sourceMappingURL=types.js.map
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@jini-ai/http-kit",
|
|
3
|
-
"version": "0.7.1",
|
|
3
|
+
"version": "0.7.3-next.1",
|
|
4
4
|
"description": "Generic Express transport primitives, request parsing, response serialization, origin guards and route-pack mounting.",
|
|
5
5
|
"license": "Apache-2.0",
|
|
6
6
|
"repository": {
|
|
@@ -15,9 +15,11 @@
|
|
|
15
15
|
".": "node",
|
|
16
16
|
"./rate-limit": "node",
|
|
17
17
|
"./middleware": "node",
|
|
18
|
-
"./
|
|
18
|
+
"./settings": "node",
|
|
19
19
|
"./observability": "node",
|
|
20
|
-
"./html-response": "node"
|
|
20
|
+
"./html-response": "node",
|
|
21
|
+
"./range": "universal",
|
|
22
|
+
"./node-bridge": "node"
|
|
21
23
|
},
|
|
22
24
|
"runtime": "node"
|
|
23
25
|
},
|
|
@@ -36,16 +38,16 @@
|
|
|
36
38
|
"import": "./dist/rate-limit.js",
|
|
37
39
|
"default": "./dist/rate-limit.js"
|
|
38
40
|
},
|
|
41
|
+
"./settings": {
|
|
42
|
+
"types": "./dist/settings/index.d.ts",
|
|
43
|
+
"import": "./dist/settings/index.js",
|
|
44
|
+
"default": "./dist/settings/index.js"
|
|
45
|
+
},
|
|
39
46
|
"./middleware": {
|
|
40
47
|
"types": "./dist/middleware.d.ts",
|
|
41
48
|
"import": "./dist/middleware.js",
|
|
42
49
|
"default": "./dist/middleware.js"
|
|
43
50
|
},
|
|
44
|
-
"./verified-origin": {
|
|
45
|
-
"types": "./dist/verified-origin.d.ts",
|
|
46
|
-
"import": "./dist/verified-origin.js",
|
|
47
|
-
"default": "./dist/verified-origin.js"
|
|
48
|
-
},
|
|
49
51
|
"./observability": {
|
|
50
52
|
"types": "./dist/observability.d.ts",
|
|
51
53
|
"import": "./dist/observability.js",
|
|
@@ -55,6 +57,16 @@
|
|
|
55
57
|
"types": "./dist/html-response.d.ts",
|
|
56
58
|
"import": "./dist/html-response.js",
|
|
57
59
|
"default": "./dist/html-response.js"
|
|
60
|
+
},
|
|
61
|
+
"./range": {
|
|
62
|
+
"types": "./dist/range.d.ts",
|
|
63
|
+
"import": "./dist/range.js",
|
|
64
|
+
"default": "./dist/range.js"
|
|
65
|
+
},
|
|
66
|
+
"./node-bridge": {
|
|
67
|
+
"types": "./dist/node-bridge.d.ts",
|
|
68
|
+
"import": "./dist/node-bridge.js",
|
|
69
|
+
"default": "./dist/node-bridge.js"
|
|
58
70
|
}
|
|
59
71
|
},
|
|
60
72
|
"files": [
|
|
@@ -77,14 +89,12 @@
|
|
|
77
89
|
"@types/express": "^4.17.21",
|
|
78
90
|
"@vitest/coverage-v8": "^2.1.9",
|
|
79
91
|
"express": "^4.21.0",
|
|
80
|
-
"@jini-ai/
|
|
81
|
-
"@jini-ai/protocol": "0.7.1"
|
|
82
|
-
"@jini-ai/core": "0.7.1"
|
|
92
|
+
"@jini-ai/core": "0.7.3-next.1",
|
|
93
|
+
"@jini-ai/protocol": "0.7.3-next.1"
|
|
83
94
|
},
|
|
84
95
|
"dependencies": {
|
|
85
|
-
"@jini-ai/
|
|
86
|
-
"@jini-ai/
|
|
87
|
-
"@jini-ai/platform": "^0.7.1"
|
|
96
|
+
"@jini-ai/protocol": "^0.7.3-next.1",
|
|
97
|
+
"@jini-ai/core": "^0.7.3-next.1"
|
|
88
98
|
},
|
|
89
99
|
"scripts": {
|
|
90
100
|
"build": "tsc -p tsconfig.json",
|
package/dist/raw-sse.d.ts
DELETED
|
@@ -1,49 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* @module sse
|
|
3
|
-
*
|
|
4
|
-
* A Server-Sent Events primitive typed only against `node:http`'s `IncomingMessage`/
|
|
5
|
-
* `ServerResponse` — Express's `req`/`res` already satisfy these directly (`Response` extends
|
|
6
|
-
* `http.ServerResponse`), so `frontend-sessions.ts`'s `handleFrontendSessionStream` hands them
|
|
7
|
-
* straight through with no adapter of its own.
|
|
8
|
-
*/
|
|
9
|
-
import type { IncomingMessage, ServerResponse } from 'node:http';
|
|
10
|
-
/**
|
|
11
|
-
* Cap on messages buffered for one client while its socket reports backpressure. Mirrors
|
|
12
|
-
* `sse.ts`'s `DEFAULT_MAX_QUEUED_SSE_EVENTS` (SEC-006) — the two SSE primitives in this package
|
|
13
|
-
* should not disagree about how much a stalled consumer may cost the server. Once exceeded the
|
|
14
|
-
* connection is dropped rather than growing memory without bound.
|
|
15
|
-
*/
|
|
16
|
-
export declare const DEFAULT_MAX_QUEUED_SSE_MESSAGES = 1000;
|
|
17
|
-
export interface CreateSseResponseOptions {
|
|
18
|
-
/** Milliseconds between keepalive ping comment lines, sent to keep an idle connection from being closed by an intermediary/timeout. Defaults to 15000. */
|
|
19
|
-
readonly keepAliveMs?: number;
|
|
20
|
-
/** Invoked exactly once, the first time this connection closes for any reason (an explicit `close()` call, or the client disconnecting) — the caller's seam for its own cleanup (e.g. unsubscribing from an event source). */
|
|
21
|
-
readonly onClose?: () => void;
|
|
22
|
-
/** Buffered-message ceiling before the connection is dropped. Defaults to {@link DEFAULT_MAX_QUEUED_SSE_MESSAGES}. */
|
|
23
|
-
readonly maxQueuedMessages?: number;
|
|
24
|
-
}
|
|
25
|
-
export interface SseConnection {
|
|
26
|
-
/** Writes one SSE `data:` event, JSON-serializing `data`. A no-op once the connection has closed. */
|
|
27
|
-
send({ data }: {
|
|
28
|
-
readonly data: unknown;
|
|
29
|
-
}, _optional?: Record<string, never>): void;
|
|
30
|
-
/** Closes the connection: stops the keepalive interval and ends the response. Idempotent — safe to call more than once, or after the client has already disconnected. */
|
|
31
|
-
close(): void;
|
|
32
|
-
/** `true` once this connection has closed, whether via an explicit `close()` call or the client disconnecting. */
|
|
33
|
-
readonly closed: boolean;
|
|
34
|
-
}
|
|
35
|
-
/**
|
|
36
|
-
* Opens `res` as a Server-Sent Events stream: writes the `text/event-stream` response headers
|
|
37
|
-
* immediately, arms a keepalive interval, and wires client-disconnect detection.
|
|
38
|
-
*
|
|
39
|
-
* @param req - The raw request (Express's `Request` already satisfies this).
|
|
40
|
-
* @param res - The raw response (Express's `Response` already satisfies this).
|
|
41
|
-
* @returns An `SseConnection` the caller pushes events through and closes when done.
|
|
42
|
-
* @complexity O(1) to open; `send` is O(1) plus `JSON.stringify`'s cost in the payload's size.
|
|
43
|
-
* @overallScore 100/100
|
|
44
|
-
*/
|
|
45
|
-
export declare function createSseResponse({ req, res }: {
|
|
46
|
-
readonly req: IncomingMessage;
|
|
47
|
-
readonly res: ServerResponse;
|
|
48
|
-
}, options?: CreateSseResponseOptions): SseConnection;
|
|
49
|
-
//# sourceMappingURL=raw-sse.d.ts.map
|
package/dist/raw-sse.js
DELETED
|
@@ -1,92 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Cap on messages buffered for one client while its socket reports backpressure. Mirrors
|
|
3
|
-
* `sse.ts`'s `DEFAULT_MAX_QUEUED_SSE_EVENTS` (SEC-006) — the two SSE primitives in this package
|
|
4
|
-
* should not disagree about how much a stalled consumer may cost the server. Once exceeded the
|
|
5
|
-
* connection is dropped rather than growing memory without bound.
|
|
6
|
-
*/
|
|
7
|
-
export const DEFAULT_MAX_QUEUED_SSE_MESSAGES = 1000;
|
|
8
|
-
/**
|
|
9
|
-
* Opens `res` as a Server-Sent Events stream: writes the `text/event-stream` response headers
|
|
10
|
-
* immediately, arms a keepalive interval, and wires client-disconnect detection.
|
|
11
|
-
*
|
|
12
|
-
* @param req - The raw request (Express's `Request` already satisfies this).
|
|
13
|
-
* @param res - The raw response (Express's `Response` already satisfies this).
|
|
14
|
-
* @returns An `SseConnection` the caller pushes events through and closes when done.
|
|
15
|
-
* @complexity O(1) to open; `send` is O(1) plus `JSON.stringify`'s cost in the payload's size.
|
|
16
|
-
* @overallScore 100/100
|
|
17
|
-
*/
|
|
18
|
-
export function createSseResponse({ req, res }, options = {}) {
|
|
19
|
-
let closed = false;
|
|
20
|
-
const maxQueuedMessages = options.maxQueuedMessages ?? DEFAULT_MAX_QUEUED_SSE_MESSAGES;
|
|
21
|
-
// Frames held back because the socket reported backpressure, flushed on `'drain'`. Every write
|
|
22
|
-
// this connection makes — events and keepalive pings alike — goes through this queue, so there is
|
|
23
|
-
// no second path that could bypass the bound.
|
|
24
|
-
const queue = [];
|
|
25
|
-
let writable = true;
|
|
26
|
-
res.writeHead(200, {
|
|
27
|
-
'Content-Type': 'text/event-stream',
|
|
28
|
-
'Cache-Control': 'no-cache, no-transform',
|
|
29
|
-
Connection: 'keep-alive',
|
|
30
|
-
});
|
|
31
|
-
/**
|
|
32
|
-
* Writes as much of the queue as the socket will accept. `res.write()` returning `false` means
|
|
33
|
-
* Node has buffered the frame internally and wants no more until `'drain'` — ignoring that (as
|
|
34
|
-
* this primitive used to) lets a client that simply stops reading accumulate the entire output of
|
|
35
|
-
* a run in memory, which is a denial of service reachable by anyone who can open a stream.
|
|
36
|
-
*/
|
|
37
|
-
function pump() {
|
|
38
|
-
while (!closed && writable && queue.length > 0) {
|
|
39
|
-
const frame = queue.shift();
|
|
40
|
-
if (res.write(frame) === false)
|
|
41
|
-
writable = false;
|
|
42
|
-
}
|
|
43
|
-
}
|
|
44
|
-
/**
|
|
45
|
-
* Queues one frame, dropping the connection if the backlog has outgrown its bound. Disconnecting
|
|
46
|
-
* a stalled client is the deliberate choice over either growing without limit or silently
|
|
47
|
-
* discarding frames — a consumer that missed events in the middle of a stream cannot tell, while
|
|
48
|
-
* a closed stream is an observable signal it can reconnect from.
|
|
49
|
-
*/
|
|
50
|
-
function enqueue(frame) {
|
|
51
|
-
if (closed)
|
|
52
|
-
return;
|
|
53
|
-
if (queue.length >= maxQueuedMessages) {
|
|
54
|
-
close();
|
|
55
|
-
return;
|
|
56
|
-
}
|
|
57
|
-
queue.push(frame);
|
|
58
|
-
pump();
|
|
59
|
-
}
|
|
60
|
-
const keepAliveMs = options.keepAliveMs ?? 15_000;
|
|
61
|
-
const keepAliveTimer = setInterval(() => {
|
|
62
|
-
enqueue(': ping\n\n');
|
|
63
|
-
}, keepAliveMs);
|
|
64
|
-
keepAliveTimer.unref?.();
|
|
65
|
-
function close() {
|
|
66
|
-
if (closed)
|
|
67
|
-
return;
|
|
68
|
-
closed = true;
|
|
69
|
-
queue.length = 0;
|
|
70
|
-
clearInterval(keepAliveTimer);
|
|
71
|
-
options.onClose?.();
|
|
72
|
-
res.end();
|
|
73
|
-
}
|
|
74
|
-
res.on('drain', () => {
|
|
75
|
-
writable = true;
|
|
76
|
-
pump();
|
|
77
|
-
});
|
|
78
|
-
// A request's `'close'` can fire when a POST body finishes arriving while its response is still
|
|
79
|
-
// streaming. Observe the response instead so request completion cannot tear down a live stream.
|
|
80
|
-
// `raw-sse.test.ts` pins both lifecycles; its real-socket cases also verify client disconnects.
|
|
81
|
-
res.on('close', close);
|
|
82
|
-
return {
|
|
83
|
-
send({ data }) {
|
|
84
|
-
enqueue(`data: ${JSON.stringify(data)}\n\n`);
|
|
85
|
-
},
|
|
86
|
-
close,
|
|
87
|
-
get closed() {
|
|
88
|
-
return closed;
|
|
89
|
-
},
|
|
90
|
-
};
|
|
91
|
-
}
|
|
92
|
-
//# sourceMappingURL=raw-sse.js.map
|
|
@@ -1,37 +0,0 @@
|
|
|
1
|
-
import { type VerifiedOrigin } from "./types.js";
|
|
2
|
-
/** Operator declaration is evidence of configured trust, not DNS or ownership proof. */
|
|
3
|
-
export interface ConfiguredOriginRequired {
|
|
4
|
-
env: Readonly<Record<string, string | undefined>>;
|
|
5
|
-
envVarName: string;
|
|
6
|
-
clock: {
|
|
7
|
-
nowIso(): string;
|
|
8
|
-
};
|
|
9
|
-
warn: (message: string) => void;
|
|
10
|
-
}
|
|
11
|
-
/** Accept a caller-named operator declaration or return undefined with a refusal warning.
|
|
12
|
-
* No ambient environment lookup. The injected clock stamps accepted evidence only.
|
|
13
|
-
* @complexity O(configured URL length) time/space; no network or storage effects.
|
|
14
|
-
* @example resolveConfiguredOrigin({ env, envVarName: "APP_PUBLIC_URL", clock, warn });
|
|
15
|
-
*/
|
|
16
|
-
export declare function resolveConfiguredOrigin(required: ConfiguredOriginRequired): VerifiedOrigin | undefined;
|
|
17
|
-
export type OriginBootPlan = {
|
|
18
|
-
kind: "configured";
|
|
19
|
-
origin: VerifiedOrigin;
|
|
20
|
-
} | {
|
|
21
|
-
kind: "dev-seed";
|
|
22
|
-
} | {
|
|
23
|
-
kind: "none";
|
|
24
|
-
};
|
|
25
|
-
export interface OriginBootRequired extends ConfiguredOriginRequired {
|
|
26
|
-
/** The host decides whether this runtime may seed a development capability. */
|
|
27
|
-
allowDevSeed: () => boolean;
|
|
28
|
-
missingOriginWarning: string;
|
|
29
|
-
}
|
|
30
|
-
/** Pure boot decision; registration effects and runtime selection stay in the host. */
|
|
31
|
-
/** Choose configured evidence, an allowed development seed, or no registration.
|
|
32
|
-
* Warnings use caller-supplied policy; registration effects remain host-owned.
|
|
33
|
-
* @complexity O(configured URL length) time/space.
|
|
34
|
-
* @example planOriginBoot({ env, envVarName, clock, warn, allowDevSeed, missingOriginWarning });
|
|
35
|
-
*/
|
|
36
|
-
export declare function planOriginBoot(required: OriginBootRequired): OriginBootPlan;
|
|
37
|
-
//# sourceMappingURL=configured-origin.d.ts.map
|