@jini-ai/http-kit 0.3.7 → 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/CHANGELOG.md +171 -0
- package/README.md +71 -98
- package/dist/adapter.d.ts +13 -5
- package/dist/adapter.js +17 -15
- package/dist/api-security-middleware.d.ts +27 -17
- package/dist/api-security-middleware.js +27 -36
- package/dist/compat.d.ts +12 -17
- package/dist/compat.js +4 -12
- package/dist/db-ops.d.ts +3 -3
- package/dist/db-ops.js +3 -3
- package/dist/delegated-tools.d.ts +31 -78
- package/dist/delegated-tools.js +62 -101
- package/dist/index.d.ts +140 -59
- package/dist/index.js +12 -32
- package/dist/local-daemon-request.d.ts +18 -8
- package/dist/local-daemon-request.js +23 -32
- package/dist/memory.d.ts +1 -1
- package/dist/middleware.d.ts +20 -0
- package/dist/middleware.js +21 -0
- package/dist/observability.d.ts +29 -0
- package/dist/observability.js +22 -0
- package/dist/origin.d.ts +8 -6
- package/dist/origin.js +8 -5
- package/dist/pack-http.d.ts +12 -8
- package/dist/pack-http.js +3 -3
- package/dist/rate-limit.d.ts +97 -0
- package/dist/rate-limit.js +94 -0
- package/dist/raw-sse.d.ts +7 -2
- package/dist/raw-sse.js +6 -7
- package/dist/read-only-tools.d.ts +67 -0
- package/dist/read-only-tools.js +59 -0
- package/dist/remote-run-events.js +1 -1
- package/dist/request.d.ts +8 -2
- package/dist/request.js +4 -4
- package/dist/response.d.ts +16 -4
- package/dist/response.js +7 -5
- package/dist/route-registration-guard.d.ts +13 -5
- package/dist/route-registration-guard.js +6 -6
- package/dist/sse.d.ts +25 -9
- package/dist/sse.js +10 -10
- package/dist/tool-catalog.d.ts +3 -3
- package/dist/types.d.ts +15 -13
- package/dist/types.js +2 -2
- package/dist/verified-origin/configured-origin.d.ts +37 -0
- package/dist/verified-origin/configured-origin.js +112 -0
- package/dist/verified-origin/index.d.ts +6 -0
- package/dist/verified-origin/index.js +5 -0
- package/dist/verified-origin/origin.d.ts +65 -0
- package/dist/verified-origin/origin.js +151 -0
- package/dist/verified-origin/ports.d.ts +40 -0
- package/dist/verified-origin/ports.js +2 -0
- package/dist/verified-origin/repo.memory.d.ts +34 -0
- package/dist/verified-origin/repo.memory.js +34 -0
- package/dist/verified-origin/types.d.ts +33 -0
- package/dist/verified-origin/types.js +23 -0
- package/dist/verified-origin.d.ts +2 -0
- package/dist/verified-origin.js +2 -0
- package/package.json +36 -9
- package/dist/express/run-stream.d.ts +0 -15
- package/dist/express/run-stream.js +0 -11
- package/dist/express-index.d.ts +0 -32
- package/dist/express-index.js +0 -14
- package/dist/fastify/adapter.d.ts +0 -31
- package/dist/fastify/adapter.js +0 -64
- package/dist/fastify/agents.d.ts +0 -13
- package/dist/fastify/agents.js +0 -7
- package/dist/fastify/api-security-middleware.d.ts +0 -64
- package/dist/fastify/api-security-middleware.js +0 -139
- package/dist/fastify/compat.d.ts +0 -22
- package/dist/fastify/compat.js +0 -16
- package/dist/fastify/daemon-status.d.ts +0 -22
- package/dist/fastify/daemon-status.js +0 -9
- package/dist/fastify/host-tools.d.ts +0 -13
- package/dist/fastify/host-tools.js +0 -8
- package/dist/fastify/index.d.ts +0 -36
- package/dist/fastify/index.js +0 -18
- package/dist/fastify/local-daemon-request.d.ts +0 -43
- package/dist/fastify/local-daemon-request.js +0 -155
- package/dist/fastify/origin.d.ts +0 -21
- package/dist/fastify/origin.js +0 -14
- package/dist/fastify/request.d.ts +0 -20
- package/dist/fastify/request.js +0 -25
- package/dist/fastify/response.d.ts +0 -20
- package/dist/fastify/response.js +0 -41
- package/dist/fastify/route-registration-guard.d.ts +0 -70
- package/dist/fastify/route-registration-guard.js +0 -69
- package/dist/fastify/run-stream.d.ts +0 -18
- package/dist/fastify/run-stream.js +0 -10
- package/dist/fastify/runs.d.ts +0 -17
- package/dist/fastify/runs.js +0 -33
- package/dist/run-stream.d.ts +0 -60
- package/dist/run-stream.js +0 -108
package/dist/origin.js
CHANGED
|
@@ -1,14 +1,17 @@
|
|
|
1
1
|
import { createApiError } from '@jini-ai/protocol';
|
|
2
|
-
import { isLocalSameOrigin } from '
|
|
2
|
+
import { isLocalSameOrigin } from '@jini-ai/core';
|
|
3
3
|
import { err, ok } from './types.js';
|
|
4
4
|
/**
|
|
5
5
|
* Wraps `isLocalSameOrigin` so the HTTP Adapter can fold the origin decision into the same
|
|
6
6
|
* error-handling pipeline as parse/handle failures.
|
|
7
7
|
*/
|
|
8
|
-
export function guardSameOrigin(req, origin) {
|
|
9
|
-
|
|
10
|
-
|
|
8
|
+
export function guardSameOrigin({ req, origin }, _optional = {}) {
|
|
9
|
+
const { env, allowedOriginsEnvVar, webPortEnvVar, bindHostEnvVar } = origin;
|
|
10
|
+
if (isLocalSameOrigin({ req, port: origin.resolvedPortRef.current, env,
|
|
11
|
+
config: { allowedOriginsEnvVar, webPortEnvVar, bindHostEnvVar },
|
|
12
|
+
})) {
|
|
13
|
+
return ok({ value: undefined });
|
|
11
14
|
}
|
|
12
|
-
return err(createApiError('FORBIDDEN', 'cross-origin request rejected'));
|
|
15
|
+
return err({ error: createApiError({ code: 'FORBIDDEN', message: 'cross-origin request rejected' }) });
|
|
13
16
|
}
|
|
14
17
|
//# sourceMappingURL=origin.js.map
|
package/dist/pack-http.d.ts
CHANGED
|
@@ -1,30 +1,34 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* Route-pack registrar: mounts every composed pack's `http` registrar (`Pack.http`, typed
|
|
3
|
-
* `(app: unknown, services) => void` in `@jini-ai/core` so the kernel never depends on any one HTTP
|
|
3
|
+
* `({ app: unknown, services }) => void` in `@jini-ai/core` so the kernel never depends on any one HTTP
|
|
4
4
|
* framework) onto a concrete app instance. This is the piece of extraction-plan.md §3's
|
|
5
5
|
* "@jini-ai/http-kit — HTTP/SSE transport + route-pack registrar" that ties a `Daemon` composed by
|
|
6
|
-
* `createDaemon` to a real HTTP surface: a pack that declares an `http(app, services)` function
|
|
6
|
+
* `createDaemon` to a real HTTP surface: a pack that declares an `http({ app, services })` function
|
|
7
7
|
* gets called with the *same* app and the *same* services object `@jini-ai/cli` would receive via
|
|
8
8
|
* `Pack.cli` (extraction-plan.md §2.3). `app` is typed `unknown` here (mirroring `Pack.http`'s own
|
|
9
9
|
* signature) rather than a concrete Express app type, since this registrar itself never touches
|
|
10
|
-
* `app` beyond passing it straight through to each pack's own `http(app, services)`.
|
|
10
|
+
* `app` beyond passing it straight through to each pack's own `http({ app, services })`.
|
|
11
11
|
*
|
|
12
12
|
* Injecting an `ExecutionDelegate` for the tool-execution boundary (extraction-plan.md §2.5,
|
|
13
|
-
* §10 task 6) is explicitly out of scope here —
|
|
13
|
+
* §10 task 6) is explicitly out of scope here — this registrar does not construct a `ToolExecutor`.
|
|
14
14
|
* `mountPackHttp` only wires the transport-neutral pack composition already built in
|
|
15
|
-
* `@jini-ai/core`;
|
|
15
|
+
* `@jini-ai/core`; hosts supply their execution boundary independently of this registrar.
|
|
16
16
|
*
|
|
17
|
-
* **Note for pack authors:** a pack's own `http(app, services)` registrar receives the concrete
|
|
17
|
+
* **Note for pack authors:** a pack's own `http({ app, services })` registrar receives the concrete
|
|
18
18
|
* Express instance the caller assembled — write it against Express's own API, or (preferred) build
|
|
19
19
|
* it on `@jini-ai/http-kit`'s own `defineJsonRoute`/`mountJsonRoute`.
|
|
20
20
|
*/
|
|
21
21
|
import type { Daemon, Pack } from '@jini-ai/core';
|
|
22
22
|
type AnyPack = Pack<any, any, string>;
|
|
23
23
|
/**
|
|
24
|
-
* Calls `pack.http(app, services)` for every pack in `packs` that declares an `http` registrar,
|
|
24
|
+
* Calls `pack.http({ app, services })` for every pack in `packs` that declares an `http` registrar,
|
|
25
25
|
* passing the services object `createDaemon` already composed for that pack. Packs with no
|
|
26
26
|
* `http` registrar (e.g. a CLI-only or headless pack) are skipped.
|
|
27
27
|
*/
|
|
28
|
-
export declare function mountPackHttp<const Packs extends readonly AnyPack[]>(app
|
|
28
|
+
export declare function mountPackHttp<const Packs extends readonly AnyPack[]>({ app, packs, daemon }: {
|
|
29
|
+
readonly app: unknown;
|
|
30
|
+
readonly packs: Packs;
|
|
31
|
+
readonly daemon: Daemon<Packs>;
|
|
32
|
+
}, _optional?: Record<string, never>): void;
|
|
29
33
|
export {};
|
|
30
34
|
//# sourceMappingURL=pack-http.d.ts.map
|
package/dist/pack-http.js
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* Calls `pack.http(app, services)` for every pack in `packs` that declares an `http` registrar,
|
|
2
|
+
* Calls `pack.http({ app, services })` for every pack in `packs` that declares an `http` registrar,
|
|
3
3
|
* passing the services object `createDaemon` already composed for that pack. Packs with no
|
|
4
4
|
* `http` registrar (e.g. a CLI-only or headless pack) are skipped.
|
|
5
5
|
*/
|
|
6
|
-
export function mountPackHttp(app, packs, daemon) {
|
|
6
|
+
export function mountPackHttp({ app, packs, daemon }, _optional = {}) {
|
|
7
7
|
const services = daemon.services;
|
|
8
8
|
for (const pack of packs) {
|
|
9
|
-
pack.http?.(app, services[pack.name]);
|
|
9
|
+
pack.http?.({ app, services: services[pack.name] });
|
|
10
10
|
}
|
|
11
11
|
}
|
|
12
12
|
//# sourceMappingURL=pack-http.js.map
|
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
/** Fixed-window counting over a host-owned clock and counter store. */
|
|
2
|
+
import type { Clock } from '@jini-ai/core/primitives';
|
|
3
|
+
export type { Clock } from '@jini-ai/core/primitives';
|
|
4
|
+
/** Host-selected window and request budget; no product profiles live here. */
|
|
5
|
+
export interface RateLimitProfile {
|
|
6
|
+
readonly windowSeconds: number;
|
|
7
|
+
readonly max: number;
|
|
8
|
+
readonly burst: number;
|
|
9
|
+
}
|
|
10
|
+
export type RateLimitResult = {
|
|
11
|
+
allowed: true;
|
|
12
|
+
} | {
|
|
13
|
+
allowed: false;
|
|
14
|
+
retryAfterSeconds: number;
|
|
15
|
+
};
|
|
16
|
+
export interface CounterWindow {
|
|
17
|
+
readonly windowStartMs: number;
|
|
18
|
+
readonly count: number;
|
|
19
|
+
}
|
|
20
|
+
/**
|
|
21
|
+
* Async storage port. Dedicate one store to one limiter; checks are serialized
|
|
22
|
+
* within that limiter. Sharing a store across processes requires a different,
|
|
23
|
+
* atomic distributed algorithm. Stored values are replaced, never mutated.
|
|
24
|
+
*/
|
|
25
|
+
export interface CounterStore {
|
|
26
|
+
get(required: {
|
|
27
|
+
key: string;
|
|
28
|
+
}): Promise<CounterWindow | undefined>;
|
|
29
|
+
set(required: {
|
|
30
|
+
key: string;
|
|
31
|
+
state: CounterWindow;
|
|
32
|
+
}): Promise<void>;
|
|
33
|
+
delete(required: {
|
|
34
|
+
key: string;
|
|
35
|
+
}): Promise<void>;
|
|
36
|
+
entries(required: Record<string, never>): Promise<Iterable<readonly [string, CounterWindow]>>;
|
|
37
|
+
size(required: Record<string, never>): Promise<number>;
|
|
38
|
+
}
|
|
39
|
+
export interface RateLimiter {
|
|
40
|
+
/** Resolves the budget decision; rejects missing, non-string or empty keys with TypeError. */
|
|
41
|
+
check(required: {
|
|
42
|
+
key: string;
|
|
43
|
+
}): Promise<RateLimitResult>;
|
|
44
|
+
size(required: Record<string, never>): Promise<number>;
|
|
45
|
+
}
|
|
46
|
+
/**
|
|
47
|
+
* Creates an isolated in-memory CounterStore adapter.
|
|
48
|
+
* @param _required - No required configuration for this adapter.
|
|
49
|
+
* @returns A new store; construct one for each limiter.
|
|
50
|
+
*/
|
|
51
|
+
export declare function createMemoryCounterStore(_required: Record<string, never>, _optional?: Record<string, never>): CounterStore;
|
|
52
|
+
/**
|
|
53
|
+
* Builds a fixed-window limiter, preserving max+burst and ceil-to-second retry
|
|
54
|
+
* delays. Counter updates and periodic eviction run in arrival order across
|
|
55
|
+
* storage awaits. Rejected checks do not consume more of the budget.
|
|
56
|
+
* @param required - Host profile, clock and dedicated counter store.
|
|
57
|
+
* @returns An async limiter. Storage failures reject the caller's check.
|
|
58
|
+
* Invalid keys reject with TypeError before storage or queue state is touched.
|
|
59
|
+
* @example const result = await limiter.check({ key: clientIp });
|
|
60
|
+
*/
|
|
61
|
+
export declare function createRateLimiter({ profile, clock, store }: {
|
|
62
|
+
profile: RateLimitProfile;
|
|
63
|
+
clock: Clock;
|
|
64
|
+
store: CounterStore;
|
|
65
|
+
}, _optional?: Record<string, never>): RateLimiter;
|
|
66
|
+
/** Structural request shape; transport/framework trust configuration stays outside. */
|
|
67
|
+
export interface ClientIpSource {
|
|
68
|
+
readonly socket: {
|
|
69
|
+
readonly remoteAddress?: string;
|
|
70
|
+
};
|
|
71
|
+
readonly headers: Record<string, string | string[] | undefined>;
|
|
72
|
+
readonly ip?: string;
|
|
73
|
+
}
|
|
74
|
+
/**
|
|
75
|
+
* Host trust policy. A fallback may use framework-resolved `source.ip` only
|
|
76
|
+
* when the host has configured that framework's proxy trust appropriately.
|
|
77
|
+
*/
|
|
78
|
+
export interface ClientIpPolicy {
|
|
79
|
+
readonly unknownAddress: string;
|
|
80
|
+
isTrustedProxy(required: {
|
|
81
|
+
address: string;
|
|
82
|
+
}): boolean;
|
|
83
|
+
fallbackAddress(required: {
|
|
84
|
+
source: ClientIpSource;
|
|
85
|
+
socketPeer: string;
|
|
86
|
+
}): string;
|
|
87
|
+
}
|
|
88
|
+
/**
|
|
89
|
+
* Reads the first forwarded hop only when the immediate peer is trusted.
|
|
90
|
+
* @param required - Request source and explicit host trust/fallback policy.
|
|
91
|
+
* @returns The forwarded IP for a trusted peer, or the policy's fallback.
|
|
92
|
+
*/
|
|
93
|
+
export declare function resolveClientIp({ source, policy }: {
|
|
94
|
+
source: ClientIpSource;
|
|
95
|
+
policy: ClientIpPolicy;
|
|
96
|
+
}, _optional?: Record<string, never>): string;
|
|
97
|
+
//# sourceMappingURL=rate-limit.d.ts.map
|
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
/** Fixed-window counting over a host-owned clock and counter store. */
|
|
2
|
+
/**
|
|
3
|
+
* Creates an isolated in-memory CounterStore adapter.
|
|
4
|
+
* @param _required - No required configuration for this adapter.
|
|
5
|
+
* @returns A new store; construct one for each limiter.
|
|
6
|
+
*/
|
|
7
|
+
export function createMemoryCounterStore(_required, _optional = {}) {
|
|
8
|
+
const windows = new Map();
|
|
9
|
+
return {
|
|
10
|
+
get: async ({ key }) => windows.get(key),
|
|
11
|
+
set: async ({ key, state }) => { windows.set(key, { ...state }); },
|
|
12
|
+
delete: async ({ key }) => { windows.delete(key); },
|
|
13
|
+
entries: async () => windows.entries(),
|
|
14
|
+
size: async () => windows.size,
|
|
15
|
+
};
|
|
16
|
+
}
|
|
17
|
+
// An injected clock makes window boundaries deterministic without real-time sleeps; a fresh
|
|
18
|
+
// dedicated store keeps limiter instances isolated instead of sharing module-global counters.
|
|
19
|
+
/**
|
|
20
|
+
* Builds a fixed-window limiter, preserving max+burst and ceil-to-second retry
|
|
21
|
+
* delays. Counter updates and periodic eviction run in arrival order across
|
|
22
|
+
* storage awaits. Rejected checks do not consume more of the budget.
|
|
23
|
+
* @param required - Host profile, clock and dedicated counter store.
|
|
24
|
+
* @returns An async limiter. Storage failures reject the caller's check.
|
|
25
|
+
* Invalid keys reject with TypeError before storage or queue state is touched.
|
|
26
|
+
* @example const result = await limiter.check({ key: clientIp });
|
|
27
|
+
*/
|
|
28
|
+
export function createRateLimiter({ profile, clock, store }, _optional = {}) {
|
|
29
|
+
const windowMs = profile.windowSeconds * 1000;
|
|
30
|
+
const effectiveMax = profile.max + profile.burst;
|
|
31
|
+
let lastSweepMs = null;
|
|
32
|
+
let pending = Promise.resolve();
|
|
33
|
+
// Expiry sweeps prevent attacker-controlled keys (for example rotating anonymous source IPs)
|
|
34
|
+
// from accumulating forever. Work is O(tracked keys) only once per window; per-request full
|
|
35
|
+
// scans would replace a memory-exhaustion risk with linear request latency. Active key volume
|
|
36
|
+
// still determines memory use, and separate in-memory processes each retain their own budget.
|
|
37
|
+
async function consume(key) {
|
|
38
|
+
const nowMs = clock.nowMs();
|
|
39
|
+
if (lastSweepMs === null) {
|
|
40
|
+
lastSweepMs = nowMs;
|
|
41
|
+
}
|
|
42
|
+
else if (nowMs - lastSweepMs >= windowMs) {
|
|
43
|
+
// One scan per window, rather than one per request. Sweep cost is linear
|
|
44
|
+
// in tracked keys; expired entries behave exactly like missing entries.
|
|
45
|
+
for (const [expiredKey, state] of await store.entries({})) {
|
|
46
|
+
if (nowMs - state.windowStartMs >= windowMs)
|
|
47
|
+
await store.delete({ key: expiredKey });
|
|
48
|
+
}
|
|
49
|
+
lastSweepMs = nowMs;
|
|
50
|
+
}
|
|
51
|
+
const existing = await store.get({ key });
|
|
52
|
+
if (!existing || nowMs - existing.windowStartMs >= windowMs) {
|
|
53
|
+
await store.set({ key, state: { windowStartMs: nowMs, count: 1 } });
|
|
54
|
+
return { allowed: true };
|
|
55
|
+
}
|
|
56
|
+
if (existing.count < effectiveMax) {
|
|
57
|
+
await store.set({ key, state: { ...existing, count: existing.count + 1 } });
|
|
58
|
+
return { allowed: true };
|
|
59
|
+
}
|
|
60
|
+
const retryAfterSeconds = Math.max(1, Math.ceil((existing.windowStartMs + windowMs - nowMs) / 1000));
|
|
61
|
+
return { allowed: false, retryAfterSeconds };
|
|
62
|
+
}
|
|
63
|
+
return {
|
|
64
|
+
check: async (required) => {
|
|
65
|
+
const key = required?.key;
|
|
66
|
+
// Positional or missing keys must never merge unrelated clients into an undefined bucket.
|
|
67
|
+
if (typeof key !== "string" || key === "")
|
|
68
|
+
throw new TypeError("rate limit key must be a non-empty string");
|
|
69
|
+
const result = pending.then(() => consume(key));
|
|
70
|
+
// Only the queue's tail contains the failure. The caller still receives
|
|
71
|
+
// the rejection, and later checks can try the adapter again.
|
|
72
|
+
pending = result.then(() => undefined, () => undefined);
|
|
73
|
+
return result;
|
|
74
|
+
},
|
|
75
|
+
size: () => pending.then(() => store.size({})),
|
|
76
|
+
};
|
|
77
|
+
}
|
|
78
|
+
/**
|
|
79
|
+
* Reads the first forwarded hop only when the immediate peer is trusted.
|
|
80
|
+
* @param required - Request source and explicit host trust/fallback policy.
|
|
81
|
+
* @returns The forwarded IP for a trusted peer, or the policy's fallback.
|
|
82
|
+
*/
|
|
83
|
+
export function resolveClientIp({ source, policy }, _optional = {}) {
|
|
84
|
+
const socketPeer = source.socket?.remoteAddress ?? policy.unknownAddress;
|
|
85
|
+
if (policy.isTrustedProxy({ address: socketPeer })) {
|
|
86
|
+
const header = source.headers['x-forwarded-for'];
|
|
87
|
+
const value = Array.isArray(header) ? header[0] : header;
|
|
88
|
+
const firstHop = value?.split(',')[0]?.trim();
|
|
89
|
+
if (firstHop)
|
|
90
|
+
return firstHop;
|
|
91
|
+
}
|
|
92
|
+
return policy.fallbackAddress({ source, socketPeer });
|
|
93
|
+
}
|
|
94
|
+
//# sourceMappingURL=rate-limit.js.map
|
package/dist/raw-sse.d.ts
CHANGED
|
@@ -24,7 +24,9 @@ export interface CreateSseResponseOptions {
|
|
|
24
24
|
}
|
|
25
25
|
export interface SseConnection {
|
|
26
26
|
/** Writes one SSE `data:` event, JSON-serializing `data`. A no-op once the connection has closed. */
|
|
27
|
-
send(data
|
|
27
|
+
send({ data }: {
|
|
28
|
+
readonly data: unknown;
|
|
29
|
+
}, _optional?: Record<string, never>): void;
|
|
28
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. */
|
|
29
31
|
close(): void;
|
|
30
32
|
/** `true` once this connection has closed, whether via an explicit `close()` call or the client disconnecting. */
|
|
@@ -40,5 +42,8 @@ export interface SseConnection {
|
|
|
40
42
|
* @complexity O(1) to open; `send` is O(1) plus `JSON.stringify`'s cost in the payload's size.
|
|
41
43
|
* @overallScore 100/100
|
|
42
44
|
*/
|
|
43
|
-
export declare function createSseResponse(req
|
|
45
|
+
export declare function createSseResponse({ req, res }: {
|
|
46
|
+
readonly req: IncomingMessage;
|
|
47
|
+
readonly res: ServerResponse;
|
|
48
|
+
}, options?: CreateSseResponseOptions): SseConnection;
|
|
44
49
|
//# sourceMappingURL=raw-sse.d.ts.map
|
package/dist/raw-sse.js
CHANGED
|
@@ -15,7 +15,7 @@ export const DEFAULT_MAX_QUEUED_SSE_MESSAGES = 1000;
|
|
|
15
15
|
* @complexity O(1) to open; `send` is O(1) plus `JSON.stringify`'s cost in the payload's size.
|
|
16
16
|
* @overallScore 100/100
|
|
17
17
|
*/
|
|
18
|
-
export function createSseResponse(req, res, options = {}) {
|
|
18
|
+
export function createSseResponse({ req, res }, options = {}) {
|
|
19
19
|
let closed = false;
|
|
20
20
|
const maxQueuedMessages = options.maxQueuedMessages ?? DEFAULT_MAX_QUEUED_SSE_MESSAGES;
|
|
21
21
|
// Frames held back because the socket reported backpressure, flushed on `'drain'`. Every write
|
|
@@ -75,13 +75,12 @@ export function createSseResponse(req, res, options = {}) {
|
|
|
75
75
|
writable = true;
|
|
76
76
|
pump();
|
|
77
77
|
});
|
|
78
|
-
//
|
|
79
|
-
//
|
|
80
|
-
//
|
|
81
|
-
|
|
82
|
-
req.on('close', close);
|
|
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);
|
|
83
82
|
return {
|
|
84
|
-
send(data) {
|
|
83
|
+
send({ data }) {
|
|
85
84
|
enqueue(`data: ${JSON.stringify(data)}\n\n`);
|
|
86
85
|
},
|
|
87
86
|
close,
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
import { type Principal, type ToolRegistry } from '@jini-ai/core';
|
|
2
|
+
import type { ToolExecutor } from '@jini-ai/daemon';
|
|
3
|
+
export interface ReadOnlyConstrainedPrincipal extends Principal {
|
|
4
|
+
readonly toolAccess: 'read-only';
|
|
5
|
+
}
|
|
6
|
+
/** Required host wording; absent metadata is always a refusal. */
|
|
7
|
+
export interface ReadOnlyToolMessages {
|
|
8
|
+
readonly unverifiableMessage: string;
|
|
9
|
+
toolRefusalMessage(required: {
|
|
10
|
+
toolId: string;
|
|
11
|
+
}): string;
|
|
12
|
+
}
|
|
13
|
+
export interface IdGenerator {
|
|
14
|
+
newId(): string;
|
|
15
|
+
}
|
|
16
|
+
export interface ReadOnlyToolCheckRequired {
|
|
17
|
+
readonly toolId: string;
|
|
18
|
+
readonly registry: Pick<ToolRegistry, 'list'> | undefined;
|
|
19
|
+
readonly messages: ReadOnlyToolMessages;
|
|
20
|
+
}
|
|
21
|
+
export interface ReadOnlyToolConstraintRequired {
|
|
22
|
+
readonly inner: ToolExecutor;
|
|
23
|
+
readonly registry: Pick<ToolRegistry, 'list'> | undefined;
|
|
24
|
+
readonly idGenerator: IdGenerator;
|
|
25
|
+
readonly messages: ReadOnlyToolMessages;
|
|
26
|
+
}
|
|
27
|
+
/** @returns A copied, attenuated principal; its roles are unchanged. */
|
|
28
|
+
export declare function constrainPrincipalToReadOnlyTools({ principal }: {
|
|
29
|
+
principal: Principal;
|
|
30
|
+
}, _optional?: Record<string, never>): ReadOnlyConstrainedPrincipal;
|
|
31
|
+
/** @returns Whether attenuation survived the executor/decorator boundary. */
|
|
32
|
+
export declare function principalIsReadOnlyConstrained({ principal }: {
|
|
33
|
+
principal: Principal;
|
|
34
|
+
}, _optional?: Record<string, never>): boolean;
|
|
35
|
+
/** @returns Required host wording for an unknown or non-read-only tool. */
|
|
36
|
+
export declare function readOnlyToolRefusalMessage({ toolId, messages }: {
|
|
37
|
+
toolId: string;
|
|
38
|
+
messages: ReadOnlyToolMessages;
|
|
39
|
+
}, _optional?: Record<string, never>): string;
|
|
40
|
+
/**
|
|
41
|
+
* Single read-only registration decision, shared by routes and inner dispatch.
|
|
42
|
+
* @returns Null for an explicitly read-only registration, otherwise host refusal text.
|
|
43
|
+
*/
|
|
44
|
+
export declare function checkReadOnlyTool({ toolId, registry, messages }: ReadOnlyToolCheckRequired, _optional?: Record<string, never>): string | null;
|
|
45
|
+
/**
|
|
46
|
+
* Preflight for every dispatch, including a recovery tool the caller never named.
|
|
47
|
+
* @returns Null for unconstrained principals or safe reads; otherwise refusal text.
|
|
48
|
+
*/
|
|
49
|
+
export declare function refuseNonReadOnlyDispatch(required: ReadOnlyToolCheckRequired & {
|
|
50
|
+
readonly principal: Principal;
|
|
51
|
+
}, _optional?: Record<string, never>): string | null;
|
|
52
|
+
/** @returns Caller-formatted recovery refusal, preserving the original refusal verbatim as input. */
|
|
53
|
+
export declare function readOnlyRemedyRefusalMessage({ refusal, formatMessage }: {
|
|
54
|
+
refusal: string;
|
|
55
|
+
formatMessage: (required: {
|
|
56
|
+
refusal: string;
|
|
57
|
+
}) => string;
|
|
58
|
+
}, _optional?: Record<string, never>): string;
|
|
59
|
+
/**
|
|
60
|
+
* Gate every dispatch before its handler runs. Compose directly around the bare
|
|
61
|
+
* executor, beneath all decorators that can issue nested/recovery dispatches.
|
|
62
|
+
* Wrapping only a fully composed stack cannot intercept its inner references.
|
|
63
|
+
* @param required - Executor, registry, denial ID source and required host wording.
|
|
64
|
+
* @returns An executor using the existing kernel port's positional methods.
|
|
65
|
+
*/
|
|
66
|
+
export declare function withReadOnlyToolConstraint({ inner, registry, idGenerator, messages }: ReadOnlyToolConstraintRequired, _optional?: Record<string, never>): ToolExecutor;
|
|
67
|
+
//# sourceMappingURL=read-only-tools.d.ts.map
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
import { isReadOnlyTool } from '@jini-ai/core';
|
|
2
|
+
/** @returns A copied, attenuated principal; its roles are unchanged. */
|
|
3
|
+
export function constrainPrincipalToReadOnlyTools({ principal }, _optional = {}) {
|
|
4
|
+
return { ...principal, toolAccess: 'read-only' };
|
|
5
|
+
}
|
|
6
|
+
/** @returns Whether attenuation survived the executor/decorator boundary. */
|
|
7
|
+
export function principalIsReadOnlyConstrained({ principal }, _optional = {}) {
|
|
8
|
+
return principal.toolAccess === 'read-only';
|
|
9
|
+
}
|
|
10
|
+
/** @returns Required host wording for an unknown or non-read-only tool. */
|
|
11
|
+
export function readOnlyToolRefusalMessage({ toolId, messages }, _optional = {}) {
|
|
12
|
+
return messages.toolRefusalMessage({ toolId });
|
|
13
|
+
}
|
|
14
|
+
/**
|
|
15
|
+
* Single read-only registration decision, shared by routes and inner dispatch.
|
|
16
|
+
* @returns Null for an explicitly read-only registration, otherwise host refusal text.
|
|
17
|
+
*/
|
|
18
|
+
export function checkReadOnlyTool({ toolId, registry, messages }, _optional = {}) {
|
|
19
|
+
if (registry === undefined)
|
|
20
|
+
return messages.unverifiableMessage;
|
|
21
|
+
const descriptor = registry.list().find((candidate) => candidate.id === toolId);
|
|
22
|
+
if (isReadOnlyTool(descriptor))
|
|
23
|
+
return null;
|
|
24
|
+
return readOnlyToolRefusalMessage({ toolId, messages });
|
|
25
|
+
}
|
|
26
|
+
/**
|
|
27
|
+
* Preflight for every dispatch, including a recovery tool the caller never named.
|
|
28
|
+
* @returns Null for unconstrained principals or safe reads; otherwise refusal text.
|
|
29
|
+
*/
|
|
30
|
+
export function refuseNonReadOnlyDispatch(required, _optional = {}) {
|
|
31
|
+
if (!principalIsReadOnlyConstrained({ principal: required.principal }))
|
|
32
|
+
return null;
|
|
33
|
+
return checkReadOnlyTool(required);
|
|
34
|
+
}
|
|
35
|
+
/** @returns Caller-formatted recovery refusal, preserving the original refusal verbatim as input. */
|
|
36
|
+
export function readOnlyRemedyRefusalMessage({ refusal, formatMessage }, _optional = {}) {
|
|
37
|
+
return formatMessage({ refusal });
|
|
38
|
+
}
|
|
39
|
+
/**
|
|
40
|
+
* Gate every dispatch before its handler runs. Compose directly around the bare
|
|
41
|
+
* executor, beneath all decorators that can issue nested/recovery dispatches.
|
|
42
|
+
* Wrapping only a fully composed stack cannot intercept its inner references.
|
|
43
|
+
* @param required - Executor, registry, denial ID source and required host wording.
|
|
44
|
+
* @returns An executor using the existing kernel port's positional methods.
|
|
45
|
+
*/
|
|
46
|
+
export function withReadOnlyToolConstraint({ inner, registry, idGenerator, messages }, _optional = {}) {
|
|
47
|
+
return {
|
|
48
|
+
execute: async (principal, run, toolId, input, signal, emitSurface) => {
|
|
49
|
+
const refusal = refuseNonReadOnlyDispatch({ principal, toolId, registry, messages });
|
|
50
|
+
if (refusal !== null)
|
|
51
|
+
return { executionId: idGenerator.newId(), status: 'denied', error: refusal };
|
|
52
|
+
return inner.execute(principal, run, toolId, input, signal, emitSurface);
|
|
53
|
+
},
|
|
54
|
+
resumeConfirmation: (executionId, decision) => inner.resumeConfirmation(executionId, decision),
|
|
55
|
+
cancel: (executionId) => inner.cancel(executionId),
|
|
56
|
+
getAuditRecord: (executionId) => inner.getAuditRecord(executionId),
|
|
57
|
+
};
|
|
58
|
+
}
|
|
59
|
+
//# sourceMappingURL=read-only-tools.js.map
|
|
@@ -8,7 +8,7 @@
|
|
|
8
8
|
*
|
|
9
9
|
* This exists to relax `@jini-ai/daemon`'s co-location requirement (`RunLifecycle`/`ToolExecutor`
|
|
10
10
|
* previously had to live in one process per run, because `DelegatedToolBridge.execute()` calls
|
|
11
|
-
* `lifecycle.emit()` in-process with no remote path
|
|
11
|
+
* `lifecycle.emit()` in-process with no remote reporting path).
|
|
12
12
|
* It does not remove any authorization: whatever executed the tool remotely already ran it through
|
|
13
13
|
* its OWN `ToolExecutor`/`ToolPolicy` gate before calling here. This route only lets that outcome
|
|
14
14
|
* be recorded into a run it does not own the process of.
|
package/dist/request.d.ts
CHANGED
|
@@ -10,10 +10,16 @@ import type { RouteInputContext } from './types.js';
|
|
|
10
10
|
* Extracts `body`/`query`/`params` from an Express `Request` into a `RouteInputContext`, so a
|
|
11
11
|
* route's `parse` function can be unit-tested without constructing a real `Request`.
|
|
12
12
|
*/
|
|
13
|
-
export declare function rawInput(req
|
|
13
|
+
export declare function rawInput({ req }: {
|
|
14
|
+
readonly req: Request;
|
|
15
|
+
}, _optional?: Record<string, never>): RouteInputContext;
|
|
14
16
|
/**
|
|
15
17
|
* Builds a `BAD_REQUEST` `ApiError` for a failed parse. When `issues` is non-empty, attaches
|
|
16
18
|
* them as structured validation details so clients can render per-field errors.
|
|
17
19
|
*/
|
|
18
|
-
export declare function validationError(message
|
|
20
|
+
export declare function validationError({ message }: {
|
|
21
|
+
readonly message: string;
|
|
22
|
+
}, { issues }?: {
|
|
23
|
+
readonly issues?: Pick<ApiValidationIssue, 'path' | 'message'>[] | undefined;
|
|
24
|
+
}): ApiError;
|
|
19
25
|
//# sourceMappingURL=request.d.ts.map
|
package/dist/request.js
CHANGED
|
@@ -3,7 +3,7 @@ import { createApiError } from '@jini-ai/protocol';
|
|
|
3
3
|
* Extracts `body`/`query`/`params` from an Express `Request` into a `RouteInputContext`, so a
|
|
4
4
|
* route's `parse` function can be unit-tested without constructing a real `Request`.
|
|
5
5
|
*/
|
|
6
|
-
export function rawInput(req) {
|
|
6
|
+
export function rawInput({ req }, _optional = {}) {
|
|
7
7
|
return {
|
|
8
8
|
body: req.body,
|
|
9
9
|
query: (req.query ?? {}),
|
|
@@ -14,11 +14,11 @@ export function rawInput(req) {
|
|
|
14
14
|
* Builds a `BAD_REQUEST` `ApiError` for a failed parse. When `issues` is non-empty, attaches
|
|
15
15
|
* them as structured validation details so clients can render per-field errors.
|
|
16
16
|
*/
|
|
17
|
-
export function validationError(message, issues = []) {
|
|
17
|
+
export function validationError({ message }, { issues = [] } = {}) {
|
|
18
18
|
if (issues.length === 0) {
|
|
19
|
-
return createApiError('BAD_REQUEST', message);
|
|
19
|
+
return createApiError({ code: 'BAD_REQUEST', message: message });
|
|
20
20
|
}
|
|
21
|
-
return createApiError('BAD_REQUEST', message, {
|
|
21
|
+
return createApiError({ code: 'BAD_REQUEST', message: message }, {
|
|
22
22
|
details: { kind: 'validation', issues },
|
|
23
23
|
});
|
|
24
24
|
}
|
package/dist/response.d.ts
CHANGED
|
@@ -6,9 +6,21 @@
|
|
|
6
6
|
import type { Response } from 'express';
|
|
7
7
|
import { type ApiError } from '@jini-ai/protocol';
|
|
8
8
|
/** Writes `body` as JSON with the given status code. */
|
|
9
|
-
export declare function sendJson(res
|
|
10
|
-
|
|
11
|
-
|
|
9
|
+
export declare function sendJson({ res, status, body }: {
|
|
10
|
+
readonly res: Response;
|
|
11
|
+
readonly status: number;
|
|
12
|
+
readonly body: unknown;
|
|
13
|
+
}, _optional?: Record<string, never>): void;
|
|
14
|
+
/** Writes an `ApiError`, wrapped in the standard `{ error }` envelope, with the given status code.
|
|
15
|
+
* Older hand-mounted routes supplied code/message and metadata separately; construct their
|
|
16
|
+
* ApiError first so both generations now share one serialization and envelope policy. */
|
|
17
|
+
export declare function sendApiError({ res, status, error }: {
|
|
18
|
+
readonly res: Response;
|
|
19
|
+
readonly status: number;
|
|
20
|
+
readonly error: ApiError;
|
|
21
|
+
}, _optional?: Record<string, never>): void;
|
|
12
22
|
/** Resolves the HTTP status to send for an `ApiError`, defaulting to 500 for unmapped codes. */
|
|
13
|
-
export declare function statusForError(error
|
|
23
|
+
export declare function statusForError({ error }: {
|
|
24
|
+
readonly error: ApiError;
|
|
25
|
+
}, _optional?: Record<string, never>): number;
|
|
14
26
|
//# sourceMappingURL=response.d.ts.map
|
package/dist/response.js
CHANGED
|
@@ -1,11 +1,13 @@
|
|
|
1
1
|
import { createApiErrorResponse } from '@jini-ai/protocol';
|
|
2
2
|
/** Writes `body` as JSON with the given status code. */
|
|
3
|
-
export function sendJson(res, status, body) {
|
|
3
|
+
export function sendJson({ res, status, body }, _optional = {}) {
|
|
4
4
|
res.status(status).json(body);
|
|
5
5
|
}
|
|
6
|
-
/** Writes an `ApiError`, wrapped in the standard `{ error }` envelope, with the given status code.
|
|
7
|
-
|
|
8
|
-
|
|
6
|
+
/** Writes an `ApiError`, wrapped in the standard `{ error }` envelope, with the given status code.
|
|
7
|
+
* Older hand-mounted routes supplied code/message and metadata separately; construct their
|
|
8
|
+
* ApiError first so both generations now share one serialization and envelope policy. */
|
|
9
|
+
export function sendApiError({ res, status, error }, _optional = {}) {
|
|
10
|
+
res.status(status).json(createApiErrorResponse({ error: error }));
|
|
9
11
|
}
|
|
10
12
|
/**
|
|
11
13
|
* @internal
|
|
@@ -40,7 +42,7 @@ const ERROR_STATUS_BY_CODE = {
|
|
|
40
42
|
OAUTH_FLOW_IN_PROGRESS: 409,
|
|
41
43
|
};
|
|
42
44
|
/** Resolves the HTTP status to send for an `ApiError`, defaulting to 500 for unmapped codes. */
|
|
43
|
-
export function statusForError(error) {
|
|
45
|
+
export function statusForError({ error }, _optional = {}) {
|
|
44
46
|
return ERROR_STATUS_BY_CODE[error.code] ?? 500;
|
|
45
47
|
}
|
|
46
48
|
//# sourceMappingURL=response.js.map
|
|
@@ -7,7 +7,7 @@
|
|
|
7
7
|
* registration — e.g. two packs each mounting `POST /api/runs` would otherwise silently shadow
|
|
8
8
|
* one another instead of failing loudly at composition time.
|
|
9
9
|
*
|
|
10
|
-
* Genericized from an origin daemon's route-registration guard — see `
|
|
10
|
+
* Genericized from an origin daemon's route-registration guard — see `archived provenance ledger`. The
|
|
11
11
|
* origin hardcoded a fixed two-route guarded set (product routes with no meaning in the generic
|
|
12
12
|
* engine); here the guarded set is an injectable `ReadonlySet<string>` that defaults to empty, so
|
|
13
13
|
* installing this guard with no options is a pure inventory tap with no enforcement.
|
|
@@ -31,7 +31,11 @@ export interface RouteRegistration {
|
|
|
31
31
|
* @complexity O(1) — a single `Set` lookup.
|
|
32
32
|
* @overallScore 100/100
|
|
33
33
|
*/
|
|
34
|
-
export declare function guardedRouteKey(method
|
|
34
|
+
export declare function guardedRouteKey({ method, path, guardedRouteKeys }: {
|
|
35
|
+
readonly method: string;
|
|
36
|
+
readonly path: unknown;
|
|
37
|
+
readonly guardedRouteKeys: ReadonlySet<string>;
|
|
38
|
+
}, _optional?: Record<string, never>): string | null;
|
|
35
39
|
export interface InstallRouteRegistrationGuardOptions {
|
|
36
40
|
/** `METHOD PATH` keys (e.g. `'POST /api/runs'`) that must be registered at most once on `app`. Defaults to none — installing the guard with no options only builds the inventory, it enforces nothing. */
|
|
37
41
|
guardedRouteKeys?: ReadonlySet<string>;
|
|
@@ -51,15 +55,19 @@ export interface InstallRouteRegistrationGuardOptions {
|
|
|
51
55
|
* @complexity O(1) setup (patches 8 fixed methods); each wrapped call is O(1) beyond the wrapped original.
|
|
52
56
|
* @overallScore 100/100
|
|
53
57
|
*/
|
|
54
|
-
export declare function installRouteRegistrationGuard(app
|
|
58
|
+
export declare function installRouteRegistrationGuard({ app }: {
|
|
59
|
+
readonly app: Express;
|
|
60
|
+
}, options?: InstallRouteRegistrationGuardOptions): void;
|
|
55
61
|
/**
|
|
56
62
|
* Reads back every route {@link installRouteRegistrationGuard} recorded for `app`.
|
|
57
63
|
*
|
|
58
64
|
* @param app - An app the guard was installed on. Safe to call on an app with no guard installed
|
|
59
65
|
* (returns an empty array rather than throwing).
|
|
60
|
-
* @returns A fresh array
|
|
66
|
+
* @returns A fresh array with copied entries each call — the caller can never mutate the guard's own internal inventory through the returned reference.
|
|
61
67
|
* @complexity O(n) in the number of routes registered so far.
|
|
62
68
|
* @overallScore 100/100
|
|
63
69
|
*/
|
|
64
|
-
export declare function getRouteRegistrationInventory(app
|
|
70
|
+
export declare function getRouteRegistrationInventory({ app }: {
|
|
71
|
+
readonly app: Express;
|
|
72
|
+
}, _optional?: Record<string, never>): RouteRegistration[];
|
|
65
73
|
//# sourceMappingURL=route-registration-guard.d.ts.map
|