@jini-ai/http-kit 0.3.8 → 0.4.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 +177 -0
- package/README.md +71 -98
- package/dist/adapter.d.ts +21 -6
- package/dist/adapter.js +47 -17
- 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 +9 -78
- package/dist/delegated-tools.js +27 -95
- package/dist/index.d.ts +21 -70
- 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 +52 -15
- 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 +7 -0
- package/dist/verified-origin/index.js +6 -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/site-path.d.ts +113 -0
- package/dist/verified-origin/site-path.js +179 -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 +52 -11
|
@@ -6,7 +6,7 @@
|
|
|
6
6
|
* rejection (always active), and — for a daemon whose threat model is a co-resident process rather
|
|
7
7
|
* than a remote one — a strict bearer gate with no loopback exemption and no disable flag
|
|
8
8
|
* ({@link requireStrictBearerToken}). The first two were genericized from an origin daemon's inline
|
|
9
|
-
* `startServer` middleware pair — see `
|
|
9
|
+
* `startServer` middleware pair — see `archived provenance ledger` for the exact drop-list. All are plain Express
|
|
10
10
|
* middleware factories with configuration injected, so none reads a hardcoded env var name or an
|
|
11
11
|
* OD-specific request shape.
|
|
12
12
|
*
|
|
@@ -15,16 +15,15 @@
|
|
|
15
15
|
* wrong one is a silent no-op rather than a visible error, so see each function's own doc before
|
|
16
16
|
* choosing.
|
|
17
17
|
*
|
|
18
|
-
* **Dropped, not carried over** (see `
|
|
18
|
+
* **Dropped, not carried over** (see `archived provenance ledger`'s transformation table for the full
|
|
19
19
|
* reasoning): the project-preview-scope GET exemption, the zero-config browser-extension
|
|
20
20
|
* ("clipper") bypass, the live-artifacts-preview bypass, and the `Origin: null` safe-GET
|
|
21
21
|
* allow-list regex — all four name or exist solely for OD product routes with no meaning in the
|
|
22
22
|
* generic engine. `Origin: null` is therefore always rejected here, not conditionally allowed.
|
|
23
23
|
*/
|
|
24
24
|
import { timingSafeEqual } from 'node:crypto';
|
|
25
|
-
import { apiTokenFromEnv, isApiTokenMiddlewareEnabled, } from '@jini-ai/core';
|
|
25
|
+
import { apiTokenFromEnv, allowedBrowserPorts, isAllowedBrowserOrigin, timingSafeTokenMatch as compareTokenWithPort, isApiTokenMiddlewareEnabled, } from '@jini-ai/core';
|
|
26
26
|
import { isLoopbackPeerAddress } from './local-daemon-request.js';
|
|
27
|
-
import { allowedBrowserPorts, isAllowedBrowserOrigin } from './origin-validation.js';
|
|
28
27
|
/** Health/readiness/version probes stay reachable without a bearer token so monitoring never needs one. Both the mount-relative and `/api`-prefixed forms are listed because this middleware is always registered via `app.use('/api', ...)`, under which Express strips the `/api` prefix from `req.path` for a request to `/api/health` — the prefixed form is kept for parity with the origin module's own set rather than dropped as dead, in case a future caller mounts this middleware unprefixed. */
|
|
29
28
|
const OPEN_PROBE_PATHS = new Set([
|
|
30
29
|
'/health',
|
|
@@ -48,7 +47,7 @@ const BEARER_TOKEN_PATTERN = /^Bearer\s+(\S+)\s*$/i;
|
|
|
48
47
|
* @complexity O(n) in the header length.
|
|
49
48
|
* @overallScore 100/100
|
|
50
49
|
*/
|
|
51
|
-
export function bearerTokenFromHeader(header) {
|
|
50
|
+
export function bearerTokenFromHeader({ header }, _optional = {}) {
|
|
52
51
|
return BEARER_TOKEN_PATTERN.exec(header ?? '')?.[1] ?? null;
|
|
53
52
|
}
|
|
54
53
|
/**
|
|
@@ -68,12 +67,11 @@ export function bearerTokenFromHeader(header) {
|
|
|
68
67
|
* @complexity O(n) in the token length, with no data-dependent early exit.
|
|
69
68
|
* @overallScore 100/100
|
|
70
69
|
*/
|
|
71
|
-
export function timingSafeTokenMatch(presented, expected) {
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
return timingSafeEqual(presentedBytes, expectedBytes);
|
|
70
|
+
export function timingSafeTokenMatch({ presented, expected }, _optional = {}) {
|
|
71
|
+
// Node port binding for the existing public name; this is not an alias of the pure helper.
|
|
72
|
+
return compareTokenWithPort({ presented, expected,
|
|
73
|
+
timingSafeEqual: ({ left, right }) => timingSafeEqual(left, right),
|
|
74
|
+
});
|
|
77
75
|
}
|
|
78
76
|
/**
|
|
79
77
|
* Headers a reverse proxy adds when it forwards a request on behalf of some other client. Their
|
|
@@ -89,10 +87,6 @@ function looksProxied(req) {
|
|
|
89
87
|
return typeof value === 'string' ? value.length > 0 : Array.isArray(value) && value.length > 0;
|
|
90
88
|
});
|
|
91
89
|
}
|
|
92
|
-
const DEFAULT_TOKEN_CONFIG = {
|
|
93
|
-
tokenEnvVar: 'JINI_API_TOKEN',
|
|
94
|
-
disableEnvVar: 'JINI_DISABLE_API_AUTH',
|
|
95
|
-
};
|
|
96
90
|
/**
|
|
97
91
|
* Registers a bearer-token gate on every `/api/*` route, active only when
|
|
98
92
|
* {@link isApiTokenMiddlewareEnabled} says a token is configured and auth hasn't been disabled.
|
|
@@ -101,18 +95,16 @@ const DEFAULT_TOKEN_CONFIG = {
|
|
|
101
95
|
* request is rejected with 401 before reaching any route handler.
|
|
102
96
|
*
|
|
103
97
|
* @param app - The Express app to register the gate on.
|
|
104
|
-
* @param
|
|
105
|
-
*
|
|
98
|
+
* @param requiredArgs - App, environment and host-selected token env var names.
|
|
99
|
+
* @param deps - Optional loopback trust policy; see {@link ApiBearerAuthMiddlewareDeps}.
|
|
106
100
|
* @returns Nothing. Registers zero middleware (a deliberate no-op, not a bug) when no token is configured.
|
|
107
101
|
* @complexity Setup is O(1). Each gated request is O(1) (one Set lookup, one regex match).
|
|
108
102
|
* @overallScore 100/100
|
|
109
103
|
*/
|
|
110
|
-
export function registerApiBearerAuthMiddleware(app, deps = {}) {
|
|
111
|
-
|
|
112
|
-
const env = deps.env ?? process.env;
|
|
113
|
-
if (!isApiTokenMiddlewareEnabled(tokenConfig, env))
|
|
104
|
+
export function registerApiBearerAuthMiddleware({ app, tokenConfig, env }, deps = {}) {
|
|
105
|
+
if (!isApiTokenMiddlewareEnabled({ config: tokenConfig, env }))
|
|
114
106
|
return;
|
|
115
|
-
const apiToken = apiTokenFromEnv(tokenConfig, env);
|
|
107
|
+
const apiToken = apiTokenFromEnv({ config: tokenConfig, env });
|
|
116
108
|
const trustLoopbackPeers = deps.trustLoopbackPeers ?? true;
|
|
117
109
|
app.use('/api', (req, res, next) => {
|
|
118
110
|
if (OPEN_PROBE_PATHS.has(req.path)) {
|
|
@@ -136,12 +128,12 @@ export function registerApiBearerAuthMiddleware(app, deps = {}) {
|
|
|
136
128
|
// deployment that strips its own forwarding headers is not covered by this and must set
|
|
137
129
|
// `trustLoopbackPeers: false`, which is also the correct setting for any host where an
|
|
138
130
|
// untrusted co-resident process can reach the port.
|
|
139
|
-
if (trustLoopbackPeers && isLoopbackPeerAddress(req.socket?.remoteAddress) && !looksProxied(req)) {
|
|
131
|
+
if (trustLoopbackPeers && isLoopbackPeerAddress({ address: req.socket?.remoteAddress }) && !looksProxied(req)) {
|
|
140
132
|
next();
|
|
141
133
|
return;
|
|
142
134
|
}
|
|
143
|
-
const presented = bearerTokenFromHeader(req.get('authorization'));
|
|
144
|
-
if (presented === null || !timingSafeTokenMatch(presented, apiToken)) {
|
|
135
|
+
const presented = bearerTokenFromHeader({ header: req.get('authorization') });
|
|
136
|
+
if (presented === null || !timingSafeTokenMatch({ presented, expected: apiToken })) {
|
|
145
137
|
res.status(401).json({
|
|
146
138
|
error: {
|
|
147
139
|
code: 'API_TOKEN_REQUIRED',
|
|
@@ -189,10 +181,9 @@ export function registerApiBearerAuthMiddleware(app, deps = {}) {
|
|
|
189
181
|
* than defended against in code: normalizing `req.baseUrl + req.path` here would silently accept both
|
|
190
182
|
* mount styles and remove the caller's ability to reason about which paths its entries refer to.
|
|
191
183
|
*/
|
|
192
|
-
export function requireStrictBearerToken(
|
|
193
|
-
const { tokenEnvVar } =
|
|
194
|
-
const
|
|
195
|
-
const exempt = new Set(deps.exemptPaths ?? []);
|
|
184
|
+
export function requireStrictBearerToken(requiredArgs, optionalArgs = {}) {
|
|
185
|
+
const { tokenEnvVar, env } = requiredArgs;
|
|
186
|
+
const exempt = new Set(optionalArgs.exemptPaths ?? []);
|
|
196
187
|
return function requireStrictBearerTokenMiddleware(req, res, next) {
|
|
197
188
|
if (exempt.has(req.path)) {
|
|
198
189
|
next();
|
|
@@ -209,8 +200,8 @@ export function requireStrictBearerToken(deps) {
|
|
|
209
200
|
return;
|
|
210
201
|
}
|
|
211
202
|
// Deliberately no loopback/peer-address exemption — see this function's doc.
|
|
212
|
-
const presented = bearerTokenFromHeader(req.get('authorization'));
|
|
213
|
-
if (presented === null || !timingSafeTokenMatch(presented, expected)) {
|
|
203
|
+
const presented = bearerTokenFromHeader({ header: req.get('authorization') });
|
|
204
|
+
if (presented === null || !timingSafeTokenMatch({ presented, expected })) {
|
|
214
205
|
res.status(401).json({
|
|
215
206
|
error: { code: 'API_TOKEN_REQUIRED', message: `Authorization: Bearer <${tokenEnvVar}> required` },
|
|
216
207
|
});
|
|
@@ -241,10 +232,10 @@ function isPortlessLoopbackOrigin(origin) {
|
|
|
241
232
|
* @complexity Setup is O(1). Each gated request is O(p) in the number of allowed ports (typically 1-2).
|
|
242
233
|
* @overallScore 100/100
|
|
243
234
|
*/
|
|
244
|
-
export function registerApiOriginGuardMiddleware(app, deps) {
|
|
245
|
-
const { host, getResolvedPort } = deps;
|
|
235
|
+
export function registerApiOriginGuardMiddleware({ app, deps }, _optional = {}) {
|
|
236
|
+
const { host, getResolvedPort, env, allowedOriginsEnvVar, webPortEnvVar, bindHostEnvVar } = deps;
|
|
237
|
+
const config = { allowedOriginsEnvVar, webPortEnvVar, bindHostEnvVar };
|
|
246
238
|
const extraAllowedOrigins = deps.extraAllowedOrigins ?? [];
|
|
247
|
-
const env = deps.env ?? process.env;
|
|
248
239
|
app.use('/api', (req, res, next) => {
|
|
249
240
|
const origin = req.headers.origin;
|
|
250
241
|
if (origin == null || origin === '') {
|
|
@@ -263,8 +254,8 @@ export function registerApiOriginGuardMiddleware(app, deps) {
|
|
|
263
254
|
res.status(403).json({ error: 'Server initializing' });
|
|
264
255
|
return;
|
|
265
256
|
}
|
|
266
|
-
const ports = allowedBrowserPorts(resolvedPort, env);
|
|
267
|
-
if (!isAllowedBrowserOrigin(origin, req.headers.host, ports, host, [...extraAllowedOrigins])) {
|
|
257
|
+
const ports = allowedBrowserPorts({ config, port: resolvedPort, env });
|
|
258
|
+
if (!isAllowedBrowserOrigin({ config, origin, hostHeader: req.headers.host, ports, bindHost: host, extraAllowedOrigins: [...extraAllowedOrigins] })) {
|
|
268
259
|
if (req.method !== 'GET' || !isPortlessLoopbackOrigin(String(origin))) {
|
|
269
260
|
res.status(403).json({ error: 'Cross-origin requests are not allowed' });
|
|
270
261
|
return;
|
package/dist/compat.d.ts
CHANGED
|
@@ -1,22 +1,17 @@
|
|
|
1
1
|
/**
|
|
2
|
-
*
|
|
3
|
-
*
|
|
4
|
-
*
|
|
5
|
-
* deliberately the same name as `response.ts`'s `ApiError`-object-taking `sendApiError` — they
|
|
6
|
-
* are different signatures for the same "send an error" job at two call-site generations; the
|
|
7
|
-
* package barrel re-exports this one as `sendCompatApiError` to keep both addressable without a
|
|
8
|
-
* collision.
|
|
2
|
+
* Error helpers: build an `ApiError` from required `code`/`message` fields
|
|
3
|
+
* and optional error metadata, including for a host application's hand-mounted routes.
|
|
4
|
+
* Sending uses the single `sendApiError` implementation in `response.ts`.
|
|
9
5
|
*/
|
|
10
6
|
import type { ApiError, ApiErrorCode, ApiErrorResponse } from '@jini-ai/protocol';
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
7
|
+
/** Builds an `ApiError` from required code/message and optional metadata. */
|
|
8
|
+
export declare function createCompatApiError({ code, message }: {
|
|
9
|
+
readonly code: ApiErrorCode;
|
|
10
|
+
readonly message: string;
|
|
11
|
+
}, init?: Omit<ApiError, 'code' | 'message'>): ApiError;
|
|
14
12
|
/** Wraps `createCompatApiError`'s result in the standard `{ error }` envelope. */
|
|
15
|
-
export declare function createCompatApiErrorResponse(code
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
* `sendCompatApiError`.
|
|
20
|
-
*/
|
|
21
|
-
export declare function sendApiError(res: Response, status: number, code: ApiErrorCode, message: string, init?: Omit<ApiError, 'code' | 'message'>): Response<ApiErrorResponse>;
|
|
13
|
+
export declare function createCompatApiErrorResponse({ code, message }: {
|
|
14
|
+
readonly code: ApiErrorCode;
|
|
15
|
+
readonly message: string;
|
|
16
|
+
}, init?: Omit<ApiError, 'code' | 'message'>): ApiErrorResponse;
|
|
22
17
|
//# sourceMappingURL=compat.d.ts.map
|
package/dist/compat.js
CHANGED
|
@@ -1,17 +1,9 @@
|
|
|
1
|
-
/** Builds an `ApiError` from
|
|
2
|
-
export function createCompatApiError(code, message, init = {}) {
|
|
1
|
+
/** Builds an `ApiError` from required code/message and optional metadata. */
|
|
2
|
+
export function createCompatApiError({ code, message }, init = {}) {
|
|
3
3
|
return { code, message, ...init };
|
|
4
4
|
}
|
|
5
5
|
/** Wraps `createCompatApiError`'s result in the standard `{ error }` envelope. */
|
|
6
|
-
export function createCompatApiErrorResponse(code, message, init = {}) {
|
|
7
|
-
return { error: createCompatApiError(code, message, init) };
|
|
8
|
-
}
|
|
9
|
-
/**
|
|
10
|
-
* Writes an `ApiError` response built from separate `code`/`message`/`init` arguments (legacy
|
|
11
|
-
* call shape) with the given status code. Exported from the package barrel as
|
|
12
|
-
* `sendCompatApiError`.
|
|
13
|
-
*/
|
|
14
|
-
export function sendApiError(res, status, code, message, init = {}) {
|
|
15
|
-
return res.status(status).json(createCompatApiErrorResponse(code, message, init));
|
|
6
|
+
export function createCompatApiErrorResponse({ code, message }, init = {}) {
|
|
7
|
+
return { error: createCompatApiError({ code, message }, init) };
|
|
16
8
|
}
|
|
17
9
|
//# sourceMappingURL=compat.js.map
|
package/dist/db-ops.d.ts
CHANGED
|
@@ -12,7 +12,7 @@ export interface DaemonDbTableInfo {
|
|
|
12
12
|
readonly name: string;
|
|
13
13
|
readonly rowCount: number;
|
|
14
14
|
}
|
|
15
|
-
/** Structurally identical to `@jini-ai/sqlite`'s `DaemonDbStatusReport` — defined locally so this package incurs no `better-sqlite3` dependency. */
|
|
15
|
+
/** Structurally identical to `@jini-ai/sqlite-chat`'s `DaemonDbStatusReport` — defined locally so this package incurs no `better-sqlite3` dependency. */
|
|
16
16
|
export interface DaemonDbStatusReport {
|
|
17
17
|
readonly kind: 'sqlite' | 'postgres';
|
|
18
18
|
readonly location: string;
|
|
@@ -26,7 +26,7 @@ export interface DbIntegrityIssue {
|
|
|
26
26
|
readonly kind: DbIntegrityIssueKind;
|
|
27
27
|
readonly message: string;
|
|
28
28
|
}
|
|
29
|
-
/** Structurally identical to `@jini-ai/sqlite`'s `DbIntegrityReport`. */
|
|
29
|
+
/** Structurally identical to `@jini-ai/sqlite-chat`'s `DbIntegrityReport`. */
|
|
30
30
|
export interface DbIntegrityReport {
|
|
31
31
|
readonly ok: boolean;
|
|
32
32
|
readonly mode: 'integrity_check' | 'quick_check';
|
|
@@ -41,7 +41,7 @@ export interface DaemonDbVacuumResult {
|
|
|
41
41
|
readonly reclaimedBytes: number;
|
|
42
42
|
readonly elapsedMs: number;
|
|
43
43
|
}
|
|
44
|
-
/** The real collaborator a host injects — typically backed by `@jini-ai/sqlite`'s `inspectSqliteDatabase`/`verifySqliteIntegrity` plus a small `vacuum` wrapper around `db.exec('VACUUM')`. */
|
|
44
|
+
/** The real collaborator a host injects — typically backed by `@jini-ai/sqlite-chat`'s `inspectSqliteDatabase`/`verifySqliteIntegrity` plus a small `vacuum` wrapper around `db.exec('VACUUM')`. */
|
|
45
45
|
export interface DaemonDbOperations {
|
|
46
46
|
inspect(): Promise<DaemonDbStatusReport> | DaemonDbStatusReport;
|
|
47
47
|
verify(quick: boolean): Promise<DbIntegrityReport> | DbIntegrityReport;
|
package/dist/db-ops.js
CHANGED
|
@@ -8,11 +8,11 @@
|
|
|
8
8
|
* `POST /api/daemon/db/verify`, `POST /api/daemon/db/vacuum` (see
|
|
9
9
|
* `source-map.md`'s routes-classification table, row `#12 daemon.ts`: "generic
|
|
10
10
|
* in shape but depend on a separate `storage/db-inspect.ts` port not built
|
|
11
|
-
* this round" — that port now exists as `@jini-ai/sqlite`'s `db-inspect.ts`).
|
|
11
|
+
* this round" — that port now exists as `@jini-ai/sqlite-chat`'s `db-inspect.ts`).
|
|
12
12
|
*
|
|
13
|
-
* This module does **not** depend on `@jini-ai/sqlite` or `better-sqlite3` at
|
|
13
|
+
* This module does **not** depend on `@jini-ai/sqlite-chat` or `better-sqlite3` at
|
|
14
14
|
* all: `DaemonDbOperations` is a plain injected interface (structurally
|
|
15
|
-
* compatible with `@jini-ai/sqlite`'s `inspectSqliteDatabase`/
|
|
15
|
+
* compatible with `@jini-ai/sqlite-chat`'s `inspectSqliteDatabase`/
|
|
16
16
|
* `verifySqliteIntegrity` return shapes, so a caller can wire those in with
|
|
17
17
|
* zero adapter code) — the same "caller supplies the real collaborator"
|
|
18
18
|
* convention `daemon-status.ts`/`host-tools.ts` already established in this
|
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
import type { Express } from 'express';
|
|
2
|
-
import {
|
|
2
|
+
import type { Principal, ToolRegistry } from '@jini-ai/core';
|
|
3
3
|
import { type RunLifecycle, type ToolExecutionResult, type ToolExecutor } from '@jini-ai/daemon';
|
|
4
4
|
import { type AdapterContext } from './adapter.js';
|
|
5
|
+
import * as readOnlyTools from './read-only-tools.js';
|
|
5
6
|
export interface DelegatedToolExecuteRequest {
|
|
6
7
|
readonly runId: string;
|
|
7
8
|
readonly toolUseId: string;
|
|
@@ -111,93 +112,23 @@ export declare function readOnlyRefusalMessage(toolId: string): string;
|
|
|
111
112
|
* fix is one line in the host's own wiring rather than an investigation.
|
|
112
113
|
*/
|
|
113
114
|
export declare const READ_ONLY_UNVERIFIABLE_MESSAGE = "this host cannot verify read-only tools \u2014 POST /api/delegated-tool-calls was mounted without DelegatedToolsHttpDeps.toolRegistry, so a requireReadOnly call cannot be checked and is refused";
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
* named in this request. It cannot see what a consumer's own `ToolExecutor` composition does
|
|
119
|
-
* once `bridge.execute()` hands control to `deps.toolExecutor`: a decorator that composition
|
|
120
|
-
* stacks on top of the bare executor (a recovery loop that retries through a different tool id
|
|
121
|
-
* after a failure, for instance) can dispatch a tool the caller never named, using the exact same
|
|
122
|
-
* `principal` the outer call carried — one hop past the only check this route ever ran. Adding a
|
|
123
|
-
* second request-shaped flag would not close that gap either: it would have to be threaded, by
|
|
124
|
-
* hand, through every decorator between here and the handler, and a decorator that forgot would
|
|
125
|
-
* fail open silently. `principal` is the one value every layer already passes unchanged, so the
|
|
126
|
-
* constraint travels as an ATTENUATED IDENTITY instead — a principal permitted to invoke only
|
|
127
|
-
* read-only tools, checkable by {@link refuseNonReadOnlyDispatch} at any depth a consumer's own
|
|
128
|
-
* composition cares to ask.
|
|
129
|
-
*
|
|
130
|
-
* A distinct field rather than a `Principal.roles` entry: `roles` is what a `ToolPolicy` branches
|
|
131
|
-
* on, and a synthetic role would silently join that decision for every registration in the
|
|
132
|
-
* process. This field is inert to everything except {@link refuseNonReadOnlyDispatch}.
|
|
133
|
-
*/
|
|
134
|
-
export interface ReadOnlyConstrainedPrincipal extends Principal {
|
|
135
|
-
readonly toolAccess: 'read-only';
|
|
136
|
-
}
|
|
137
|
-
/** Attenuates `principal` for one execution: it may now invoke only tools registered read-only. */
|
|
138
|
-
export declare function constrainPrincipalToReadOnlyTools(principal: Principal): ReadOnlyConstrainedPrincipal;
|
|
139
|
-
/**
|
|
140
|
-
* Whether `principal` is carrying the read-only attenuation.
|
|
141
|
-
*
|
|
142
|
-
* Reads the field structurally, so a principal that travelled through layers typed as the plain
|
|
143
|
-
* `Principal` (every decorator between here and wherever a dispatch is about to happen) still
|
|
144
|
-
* answers truthfully.
|
|
145
|
-
*
|
|
146
|
-
* @complexity O(1).
|
|
147
|
-
*/
|
|
115
|
+
export type { ReadOnlyConstrainedPrincipal } from './read-only-tools.js';
|
|
116
|
+
/** Compatibility wrapper; new object-shaped API lives at ./read-only-tools. */
|
|
117
|
+
export declare function constrainPrincipalToReadOnlyTools(principal: Principal): readOnlyTools.ReadOnlyConstrainedPrincipal;
|
|
118
|
+
/** Compatibility wrapper preserving the existing principal argument. */
|
|
148
119
|
export declare function principalIsReadOnlyConstrained(principal: Principal): boolean;
|
|
149
|
-
/**
|
|
150
|
-
* THE read-only dispatch decision for any tool id a consumer's own `ToolExecutor` composition is
|
|
151
|
-
* about to invoke — the outer call this route already checked, or a nested one a decorator issues
|
|
152
|
-
* one or more hops in. Every consumer's own composition should ask this before dispatching on
|
|
153
|
-
* behalf of a principal it did not itself resolve; none should re-implement the check, so changing
|
|
154
|
-
* what the constraint means stays one edit.
|
|
155
|
-
*
|
|
156
|
-
* @param options.principal - The principal the dispatch would run under. Unconstrained ⇒ always
|
|
157
|
-
* `null` — this is a no-op for every pre-existing caller that never attenuates a principal.
|
|
158
|
-
* @param options.toolId - The id actually about to be dispatched, which is not necessarily the id
|
|
159
|
-
* named in the original request — that difference is the whole reason this function exists.
|
|
160
|
-
* @param options.registry - Descriptors to resolve `toolId` against; `undefined` ⇒ refuse (an
|
|
161
|
-
* unverifiable constrained dispatch is refused, never waived, matching `checkReadOnlyConstraint`).
|
|
162
|
-
* @returns `null` when the dispatch may proceed, otherwise the refusal text to report.
|
|
163
|
-
* @complexity O(1) for an unconstrained principal; O(n) in registered tool count for a constrained
|
|
164
|
-
* one, since `ToolRegistry` exposes enumeration rather than lookup by id.
|
|
165
|
-
*/
|
|
120
|
+
/** Compatibility wrapper using the shared fail-closed dispatch decision. */
|
|
166
121
|
export declare function refuseNonReadOnlyDispatch(options: {
|
|
167
122
|
readonly principal: Principal;
|
|
168
123
|
readonly toolId: string;
|
|
169
124
|
readonly registry: Pick<ToolRegistry, 'list'> | undefined;
|
|
170
125
|
}): string | null;
|
|
171
126
|
export interface ReadOnlyToolConstraintDeps {
|
|
172
|
-
/** The same registry `inner` was built over — descriptors only; this gate never reaches a handler. */
|
|
173
127
|
readonly registry: Pick<ToolRegistry, 'list'> | undefined;
|
|
174
128
|
}
|
|
175
129
|
/**
|
|
176
|
-
*
|
|
177
|
-
*
|
|
178
|
-
* id. This is what turns the attenuation into an actual gate rather than a field nobody reads:
|
|
179
|
-
* {@link refuseNonReadOnlyDispatch} is the decision, this is its enforcement point.
|
|
180
|
-
*
|
|
181
|
-
* **Compose this as close to the bare `ToolExecutor` as your own stack allows** — directly around
|
|
182
|
-
* `@jini-ai/daemon`'s `createToolExecutor` output, beneath any decorator of your own that might
|
|
183
|
-
* dispatch a tool id the caller never named (a retry, a recovery loop that calls a different tool
|
|
184
|
-
* as a remedy, ...). Every such decorator's own `inner.execute` call still has to come through here
|
|
185
|
-
* to reach a handler, which is what makes this a gate on the CLASS of defect (an unnamed nested
|
|
186
|
-
* dispatch) rather than on one instance of it — see `read-only-tool-constraint.ts` in the consuming
|
|
187
|
-
* product's own `apps/website`, the consumer this was ported from, for the composition this mirrors.
|
|
188
|
-
*
|
|
189
|
-
* `delegatedToolExecuteRoute`'s own `handle` additionally composes this around whatever
|
|
190
|
-
* `ToolExecutor` a host supplies, whenever a call attenuates its principal. That outer composition
|
|
191
|
-
* only re-covers the SAME outer `toolId` {@link checkReadOnlyConstraint} already checked — it
|
|
192
|
-
* cannot see a nested dispatch a host's own inner decorator issues, because that decorator holds a
|
|
193
|
-
* reference to whatever `ToolExecutor` IT was built with, not to this route's wrapped one. Closing
|
|
194
|
-
* the nested case for a given host's stack requires that host to compose this decorator itself,
|
|
195
|
-
* innermost, in its own `ToolExecutor` construction — this export exists so it can, without having
|
|
196
|
-
* to rediscover or reimplement the mechanism.
|
|
197
|
-
*
|
|
198
|
-
* @returns A drop-in `ToolExecutor`; `resumeConfirmation`/`cancel`/`getAuditRecord` delegate
|
|
199
|
-
* straight through.
|
|
200
|
-
* @complexity One extra property read per unconstrained call; one registry scan per constrained one.
|
|
130
|
+
* Compatibility wrapper. Compose innermost, directly around the bare executor,
|
|
131
|
+
* so nested calls by outer decorators still pass through the shared gate.
|
|
201
132
|
*/
|
|
202
133
|
export declare function withReadOnlyToolConstraint(inner: ToolExecutor, deps: ReadOnlyToolConstraintDeps): ToolExecutor;
|
|
203
134
|
/**
|
package/dist/delegated-tools.js
CHANGED
|
@@ -27,11 +27,11 @@
|
|
|
27
27
|
*/
|
|
28
28
|
import { randomUUID } from 'node:crypto';
|
|
29
29
|
import { createApiError } from '@jini-ai/protocol';
|
|
30
|
-
import { isReadOnlyTool } from '@jini-ai/core';
|
|
31
30
|
import { createDelegatedToolBridge } from '@jini-ai/daemon';
|
|
32
31
|
import { defineJsonRoute, mountJsonRoute } from './adapter.js';
|
|
33
32
|
import { validationError } from './request.js';
|
|
34
33
|
import { err, ok } from './types.js';
|
|
34
|
+
import * as readOnlyTools from './read-only-tools.js';
|
|
35
35
|
/**
|
|
36
36
|
* Refusal text for a `requireReadOnly` call naming a tool that is not registered read-only —
|
|
37
37
|
* including one that is not registered at all, which is the same answer for the same reason
|
|
@@ -43,7 +43,7 @@ import { err, ok } from './types.js';
|
|
|
43
43
|
* and cost a second message to keep in step.
|
|
44
44
|
*/
|
|
45
45
|
export function readOnlyRefusalMessage(toolId) {
|
|
46
|
-
return
|
|
46
|
+
return readOnlyTools.readOnlyToolRefusalMessage({ toolId, messages: legacyReadOnlyMessages });
|
|
47
47
|
}
|
|
48
48
|
/**
|
|
49
49
|
* Refusal text for a `requireReadOnly` call this host has no way to check, because it mounted the
|
|
@@ -55,113 +55,45 @@ export function readOnlyRefusalMessage(toolId) {
|
|
|
55
55
|
* fix is one line in the host's own wiring rather than an investigation.
|
|
56
56
|
*/
|
|
57
57
|
export const READ_ONLY_UNVERIFIABLE_MESSAGE = 'this host cannot verify read-only tools — POST /api/delegated-tool-calls was mounted without DelegatedToolsHttpDeps.toolRegistry, so a requireReadOnly call cannot be checked and is refused';
|
|
58
|
-
/**
|
|
58
|
+
/** Exact existing gateway wording belongs to this compatibility adapter. */
|
|
59
|
+
const legacyReadOnlyMessages = {
|
|
60
|
+
unverifiableMessage: READ_ONLY_UNVERIFIABLE_MESSAGE,
|
|
61
|
+
toolRefusalMessage: ({ toolId }) => `tool "${toolId}" is not registered as read-only — this gateway executes only tools whose registration declares readOnly; call it through execute_delegated_tool instead`,
|
|
62
|
+
};
|
|
63
|
+
/** Compatibility wrapper; new object-shaped API lives at ./read-only-tools. */
|
|
59
64
|
export function constrainPrincipalToReadOnlyTools(principal) {
|
|
60
|
-
return {
|
|
65
|
+
return readOnlyTools.constrainPrincipalToReadOnlyTools({ principal });
|
|
61
66
|
}
|
|
62
|
-
/**
|
|
63
|
-
* Whether `principal` is carrying the read-only attenuation.
|
|
64
|
-
*
|
|
65
|
-
* Reads the field structurally, so a principal that travelled through layers typed as the plain
|
|
66
|
-
* `Principal` (every decorator between here and wherever a dispatch is about to happen) still
|
|
67
|
-
* answers truthfully.
|
|
68
|
-
*
|
|
69
|
-
* @complexity O(1).
|
|
70
|
-
*/
|
|
67
|
+
/** Compatibility wrapper preserving the existing principal argument. */
|
|
71
68
|
export function principalIsReadOnlyConstrained(principal) {
|
|
72
|
-
return
|
|
69
|
+
return readOnlyTools.principalIsReadOnlyConstrained({ principal });
|
|
73
70
|
}
|
|
74
|
-
/**
|
|
75
|
-
* THE read-only dispatch decision for any tool id a consumer's own `ToolExecutor` composition is
|
|
76
|
-
* about to invoke — the outer call this route already checked, or a nested one a decorator issues
|
|
77
|
-
* one or more hops in. Every consumer's own composition should ask this before dispatching on
|
|
78
|
-
* behalf of a principal it did not itself resolve; none should re-implement the check, so changing
|
|
79
|
-
* what the constraint means stays one edit.
|
|
80
|
-
*
|
|
81
|
-
* @param options.principal - The principal the dispatch would run under. Unconstrained ⇒ always
|
|
82
|
-
* `null` — this is a no-op for every pre-existing caller that never attenuates a principal.
|
|
83
|
-
* @param options.toolId - The id actually about to be dispatched, which is not necessarily the id
|
|
84
|
-
* named in the original request — that difference is the whole reason this function exists.
|
|
85
|
-
* @param options.registry - Descriptors to resolve `toolId` against; `undefined` ⇒ refuse (an
|
|
86
|
-
* unverifiable constrained dispatch is refused, never waived, matching `checkReadOnlyConstraint`).
|
|
87
|
-
* @returns `null` when the dispatch may proceed, otherwise the refusal text to report.
|
|
88
|
-
* @complexity O(1) for an unconstrained principal; O(n) in registered tool count for a constrained
|
|
89
|
-
* one, since `ToolRegistry` exposes enumeration rather than lookup by id.
|
|
90
|
-
*/
|
|
71
|
+
/** Compatibility wrapper using the shared fail-closed dispatch decision. */
|
|
91
72
|
export function refuseNonReadOnlyDispatch(options) {
|
|
92
|
-
|
|
93
|
-
return null;
|
|
94
|
-
if (options.registry === undefined)
|
|
95
|
-
return READ_ONLY_UNVERIFIABLE_MESSAGE;
|
|
96
|
-
const descriptor = options.registry.list().find((candidate) => candidate.id === options.toolId);
|
|
97
|
-
if (isReadOnlyTool(descriptor))
|
|
98
|
-
return null;
|
|
99
|
-
return readOnlyRefusalMessage(options.toolId);
|
|
73
|
+
return readOnlyTools.refuseNonReadOnlyDispatch({ ...options, messages: legacyReadOnlyMessages });
|
|
100
74
|
}
|
|
101
75
|
/**
|
|
102
|
-
*
|
|
103
|
-
*
|
|
104
|
-
* id. This is what turns the attenuation into an actual gate rather than a field nobody reads:
|
|
105
|
-
* {@link refuseNonReadOnlyDispatch} is the decision, this is its enforcement point.
|
|
106
|
-
*
|
|
107
|
-
* **Compose this as close to the bare `ToolExecutor` as your own stack allows** — directly around
|
|
108
|
-
* `@jini-ai/daemon`'s `createToolExecutor` output, beneath any decorator of your own that might
|
|
109
|
-
* dispatch a tool id the caller never named (a retry, a recovery loop that calls a different tool
|
|
110
|
-
* as a remedy, ...). Every such decorator's own `inner.execute` call still has to come through here
|
|
111
|
-
* to reach a handler, which is what makes this a gate on the CLASS of defect (an unnamed nested
|
|
112
|
-
* dispatch) rather than on one instance of it — see `read-only-tool-constraint.ts` in the consuming
|
|
113
|
-
* product's own `apps/website`, the consumer this was ported from, for the composition this mirrors.
|
|
114
|
-
*
|
|
115
|
-
* `delegatedToolExecuteRoute`'s own `handle` additionally composes this around whatever
|
|
116
|
-
* `ToolExecutor` a host supplies, whenever a call attenuates its principal. That outer composition
|
|
117
|
-
* only re-covers the SAME outer `toolId` {@link checkReadOnlyConstraint} already checked — it
|
|
118
|
-
* cannot see a nested dispatch a host's own inner decorator issues, because that decorator holds a
|
|
119
|
-
* reference to whatever `ToolExecutor` IT was built with, not to this route's wrapped one. Closing
|
|
120
|
-
* the nested case for a given host's stack requires that host to compose this decorator itself,
|
|
121
|
-
* innermost, in its own `ToolExecutor` construction — this export exists so it can, without having
|
|
122
|
-
* to rediscover or reimplement the mechanism.
|
|
123
|
-
*
|
|
124
|
-
* @returns A drop-in `ToolExecutor`; `resumeConfirmation`/`cancel`/`getAuditRecord` delegate
|
|
125
|
-
* straight through.
|
|
126
|
-
* @complexity One extra property read per unconstrained call; one registry scan per constrained one.
|
|
76
|
+
* Compatibility wrapper. Compose innermost, directly around the bare executor,
|
|
77
|
+
* so nested calls by outer decorators still pass through the shared gate.
|
|
127
78
|
*/
|
|
128
79
|
export function withReadOnlyToolConstraint(inner, deps) {
|
|
129
|
-
return {
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
// kernel execution to borrow one from.
|
|
136
|
-
if (refusal !== null)
|
|
137
|
-
return { executionId: randomUUID(), status: 'denied', error: refusal };
|
|
138
|
-
return inner.execute(principal, run, toolId, input, signal, emitSurface);
|
|
139
|
-
},
|
|
140
|
-
resumeConfirmation: (executionId, decision) => inner.resumeConfirmation(executionId, decision),
|
|
141
|
-
cancel: (executionId) => inner.cancel(executionId),
|
|
142
|
-
getAuditRecord: (executionId) => inner.getAuditRecord(executionId),
|
|
143
|
-
};
|
|
80
|
+
return readOnlyTools.withReadOnlyToolConstraint({
|
|
81
|
+
inner,
|
|
82
|
+
registry: deps.registry,
|
|
83
|
+
messages: legacyReadOnlyMessages,
|
|
84
|
+
idGenerator: { newId: randomUUID },
|
|
85
|
+
});
|
|
144
86
|
}
|
|
145
|
-
/**
|
|
146
|
-
* Evaluates a request's read-only constraint against the live registry.
|
|
147
|
-
*
|
|
148
|
-
* @param deps - Supplies the optional `toolRegistry` the check reads.
|
|
149
|
-
* @param input - The parsed request; an absent/false `requireReadOnly` short-circuits to `null`.
|
|
150
|
-
* @returns `null` when the call may proceed, or the `ApiError` to answer with.
|
|
151
|
-
* @complexity O(n) in registered tool count on a constrained call only (`ToolRegistry` exposes
|
|
152
|
-
* enumeration, not lookup by id); O(1) — a single boolean test — on every unconstrained call,
|
|
153
|
-
* which is every call the pre-existing gateway makes.
|
|
154
|
-
*/
|
|
87
|
+
/** Route preflight shares the same registration decision as nested dispatch. */
|
|
155
88
|
function checkReadOnlyConstraint(deps, input) {
|
|
156
89
|
if (input.requireReadOnly !== true)
|
|
157
90
|
return null;
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
}
|
|
161
|
-
|
|
162
|
-
if (isReadOnlyTool(descriptor))
|
|
91
|
+
const refusal = readOnlyTools.checkReadOnlyTool({
|
|
92
|
+
toolId: input.toolId, registry: deps.toolRegistry, messages: legacyReadOnlyMessages,
|
|
93
|
+
});
|
|
94
|
+
if (refusal === null)
|
|
163
95
|
return null;
|
|
164
|
-
return createApiError('TOOL_OPERATION_DENIED',
|
|
96
|
+
return createApiError('TOOL_OPERATION_DENIED', refusal);
|
|
165
97
|
}
|
|
166
98
|
/** Logs the real failure server-side and returns the generic, correlation-id-bearing public error (SEC-005: never the raw exception). */
|
|
167
99
|
function defaultInternalErrorSink(context) {
|