@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.
Files changed (92) hide show
  1. package/CHANGELOG.md +171 -0
  2. package/README.md +71 -98
  3. package/dist/adapter.d.ts +13 -5
  4. package/dist/adapter.js +17 -15
  5. package/dist/api-security-middleware.d.ts +27 -17
  6. package/dist/api-security-middleware.js +27 -36
  7. package/dist/compat.d.ts +12 -17
  8. package/dist/compat.js +4 -12
  9. package/dist/db-ops.d.ts +3 -3
  10. package/dist/db-ops.js +3 -3
  11. package/dist/delegated-tools.d.ts +31 -78
  12. package/dist/delegated-tools.js +62 -101
  13. package/dist/index.d.ts +140 -59
  14. package/dist/index.js +12 -32
  15. package/dist/local-daemon-request.d.ts +18 -8
  16. package/dist/local-daemon-request.js +23 -32
  17. package/dist/memory.d.ts +1 -1
  18. package/dist/middleware.d.ts +20 -0
  19. package/dist/middleware.js +21 -0
  20. package/dist/observability.d.ts +29 -0
  21. package/dist/observability.js +22 -0
  22. package/dist/origin.d.ts +8 -6
  23. package/dist/origin.js +8 -5
  24. package/dist/pack-http.d.ts +12 -8
  25. package/dist/pack-http.js +3 -3
  26. package/dist/rate-limit.d.ts +97 -0
  27. package/dist/rate-limit.js +94 -0
  28. package/dist/raw-sse.d.ts +7 -2
  29. package/dist/raw-sse.js +6 -7
  30. package/dist/read-only-tools.d.ts +67 -0
  31. package/dist/read-only-tools.js +59 -0
  32. package/dist/remote-run-events.js +1 -1
  33. package/dist/request.d.ts +8 -2
  34. package/dist/request.js +4 -4
  35. package/dist/response.d.ts +16 -4
  36. package/dist/response.js +7 -5
  37. package/dist/route-registration-guard.d.ts +13 -5
  38. package/dist/route-registration-guard.js +6 -6
  39. package/dist/sse.d.ts +25 -9
  40. package/dist/sse.js +10 -10
  41. package/dist/tool-catalog.d.ts +3 -3
  42. package/dist/types.d.ts +15 -13
  43. package/dist/types.js +2 -2
  44. package/dist/verified-origin/configured-origin.d.ts +37 -0
  45. package/dist/verified-origin/configured-origin.js +112 -0
  46. package/dist/verified-origin/index.d.ts +6 -0
  47. package/dist/verified-origin/index.js +5 -0
  48. package/dist/verified-origin/origin.d.ts +65 -0
  49. package/dist/verified-origin/origin.js +151 -0
  50. package/dist/verified-origin/ports.d.ts +40 -0
  51. package/dist/verified-origin/ports.js +2 -0
  52. package/dist/verified-origin/repo.memory.d.ts +34 -0
  53. package/dist/verified-origin/repo.memory.js +34 -0
  54. package/dist/verified-origin/types.d.ts +33 -0
  55. package/dist/verified-origin/types.js +23 -0
  56. package/dist/verified-origin.d.ts +2 -0
  57. package/dist/verified-origin.js +2 -0
  58. package/package.json +36 -9
  59. package/dist/express/run-stream.d.ts +0 -15
  60. package/dist/express/run-stream.js +0 -11
  61. package/dist/express-index.d.ts +0 -32
  62. package/dist/express-index.js +0 -14
  63. package/dist/fastify/adapter.d.ts +0 -31
  64. package/dist/fastify/adapter.js +0 -64
  65. package/dist/fastify/agents.d.ts +0 -13
  66. package/dist/fastify/agents.js +0 -7
  67. package/dist/fastify/api-security-middleware.d.ts +0 -64
  68. package/dist/fastify/api-security-middleware.js +0 -139
  69. package/dist/fastify/compat.d.ts +0 -22
  70. package/dist/fastify/compat.js +0 -16
  71. package/dist/fastify/daemon-status.d.ts +0 -22
  72. package/dist/fastify/daemon-status.js +0 -9
  73. package/dist/fastify/host-tools.d.ts +0 -13
  74. package/dist/fastify/host-tools.js +0 -8
  75. package/dist/fastify/index.d.ts +0 -36
  76. package/dist/fastify/index.js +0 -18
  77. package/dist/fastify/local-daemon-request.d.ts +0 -43
  78. package/dist/fastify/local-daemon-request.js +0 -155
  79. package/dist/fastify/origin.d.ts +0 -21
  80. package/dist/fastify/origin.js +0 -14
  81. package/dist/fastify/request.d.ts +0 -20
  82. package/dist/fastify/request.js +0 -25
  83. package/dist/fastify/response.d.ts +0 -20
  84. package/dist/fastify/response.js +0 -41
  85. package/dist/fastify/route-registration-guard.d.ts +0 -70
  86. package/dist/fastify/route-registration-guard.js +0 -69
  87. package/dist/fastify/run-stream.d.ts +0 -18
  88. package/dist/fastify/run-stream.js +0 -10
  89. package/dist/fastify/runs.d.ts +0 -17
  90. package/dist/fastify/runs.js +0 -33
  91. package/dist/run-stream.d.ts +0 -60
  92. package/dist/run-stream.js +0 -108
@@ -0,0 +1,40 @@
1
+ type UUID = string;
2
+ import type { VerifiedOrigin } from "./types.js";
3
+ export interface VerifiedOriginRequestContext {
4
+ workspaceId: UUID;
5
+ siteId?: UUID;
6
+ locale?: string;
7
+ }
8
+ export interface RedirectTargetContext {
9
+ workspaceId: UUID;
10
+ siteId?: UUID;
11
+ originKey?: string;
12
+ }
13
+ export interface EgressTargetContext {
14
+ workspaceId: UUID;
15
+ siteId?: UUID;
16
+ }
17
+ export interface OriginRegistryPort {
18
+ canonicalOrigin(ctx: VerifiedOriginRequestContext): Promise<VerifiedOrigin>;
19
+ isAllowedRedirectTarget(required: {
20
+ context: RedirectTargetContext;
21
+ url: string;
22
+ }): Promise<boolean>;
23
+ isAllowedEgressTarget(required: {
24
+ context: EgressTargetContext;
25
+ url: string;
26
+ }): Promise<boolean>;
27
+ }
28
+ export interface OriginSettingRepoPort {
29
+ findByWorkspaceId(required: {
30
+ workspaceId: UUID;
31
+ }): Promise<VerifiedOrigin | null>;
32
+ findRedirectAllowlist(required: {
33
+ workspaceId: UUID;
34
+ }): Promise<string[]>;
35
+ findEgressAllowlist(required: {
36
+ workspaceId: UUID;
37
+ }): Promise<string[]>;
38
+ }
39
+ export {};
40
+ //# sourceMappingURL=ports.d.ts.map
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=ports.js.map
@@ -0,0 +1,34 @@
1
+ type UUID = string;
2
+ import type { OriginSettingRepoPort } from "./ports.js";
3
+ import { type VerifiedOrigin } from "./types.js";
4
+ export interface OriginSettingSeed {
5
+ workspaceId: UUID;
6
+ origin: VerifiedOrigin;
7
+ /** Exact-match hosts trusted for cross-origin redirects; independent of third-party egress. */
8
+ redirectAllowlist?: string[];
9
+ /** Exact-match hosts trusted for third-party egress; redirect permission alone does not grant it. */
10
+ egressAllowlist?: string[];
11
+ }
12
+ /** Seeded read adapter that returns copies of origins and lists to protect stored trust.
13
+ * Reads are O(1) for an origin, O(k) for an allowlist; construction is O(total seed host bytes).
14
+ * @example new InMemoryOriginSettingRepo({ seeds: [{ workspaceId, origin }] });
15
+ */
16
+ export declare class InMemoryOriginSettingRepo implements OriginSettingRepoPort {
17
+ private readonly origins;
18
+ private readonly redirectAllowlists;
19
+ private readonly egressAllowlists;
20
+ constructor({ seeds }: {
21
+ seeds: readonly OriginSettingSeed[];
22
+ });
23
+ findByWorkspaceId({ workspaceId }: {
24
+ workspaceId: UUID;
25
+ }): Promise<VerifiedOrigin | null>;
26
+ findRedirectAllowlist({ workspaceId }: {
27
+ workspaceId: UUID;
28
+ }): Promise<string[]>;
29
+ findEgressAllowlist({ workspaceId }: {
30
+ workspaceId: UUID;
31
+ }): Promise<string[]>;
32
+ }
33
+ export {};
34
+ //# sourceMappingURL=repo.memory.d.ts.map
@@ -0,0 +1,34 @@
1
+ import { createVerifiedOrigin } from "./types.js";
2
+ /** Seeded read adapter that returns copies of origins and lists to protect stored trust.
3
+ * Reads are O(1) for an origin, O(k) for an allowlist; construction is O(total seed host bytes).
4
+ * @example new InMemoryOriginSettingRepo({ seeds: [{ workspaceId, origin }] });
5
+ */
6
+ export class InMemoryOriginSettingRepo {
7
+ origins;
8
+ redirectAllowlists;
9
+ egressAllowlists;
10
+ constructor({ seeds }) {
11
+ this.origins = new Map();
12
+ this.redirectAllowlists = new Map();
13
+ this.egressAllowlists = new Map();
14
+ for (const seed of seeds) {
15
+ this.origins.set(seed.workspaceId, createVerifiedOrigin(seed.origin));
16
+ this.redirectAllowlists.set(seed.workspaceId, normalizeHostList(seed.redirectAllowlist));
17
+ this.egressAllowlists.set(seed.workspaceId, normalizeHostList(seed.egressAllowlist));
18
+ }
19
+ }
20
+ async findByWorkspaceId({ workspaceId }) {
21
+ const origin = this.origins.get(workspaceId);
22
+ return origin ? { ...origin } : null;
23
+ }
24
+ async findRedirectAllowlist({ workspaceId }) {
25
+ return [...(this.redirectAllowlists.get(workspaceId) ?? [])];
26
+ }
27
+ async findEgressAllowlist({ workspaceId }) {
28
+ return [...(this.egressAllowlists.get(workspaceId) ?? [])];
29
+ }
30
+ }
31
+ function normalizeHostList(hosts) {
32
+ return (hosts ?? []).map((host) => host.trim().toLowerCase());
33
+ }
34
+ //# sourceMappingURL=repo.memory.js.map
@@ -0,0 +1,33 @@
1
+ type ISODateTime = string;
2
+ /** Canonical links, redirect checks and egress decisions must use stored trust evidence,
3
+ * never the raw request Host/:authority, which is attacker-controlled. */
4
+ export type OriginScheme = "https" | "http";
5
+ export type OriginSource = "workspace-setting" | "dev-capability";
6
+ /** Stored trust evidence. Public origins use HTTPS; HTTP is limited to explicit development capabilities. */
7
+ export interface VerifiedOrigin {
8
+ scheme: OriginScheme;
9
+ host: string;
10
+ port?: number;
11
+ basePath?: string;
12
+ verifiedAt: ISODateTime;
13
+ source: OriginSource;
14
+ }
15
+ export declare class InsecureOriginSourceError extends Error {
16
+ constructor({ message }: {
17
+ message: string;
18
+ });
19
+ }
20
+ /** Missing trust evidence is a hard precondition failure. Callers must fail closed rather than
21
+ * guessing an origin from the request or another unverified value. */
22
+ export declare class OriginNotVerifiedError extends Error {
23
+ constructor({ message }: {
24
+ message: string;
25
+ });
26
+ }
27
+ /** Copy stored evidence, rejecting an HTTP public origin with InsecureOriginSourceError.
28
+ * @complexity O(1) time and space; pure, with no ownership or reachability probe.
29
+ * @example createVerifiedOrigin({ scheme: "https", host: "example.com", verifiedAt, source: "workspace-setting" });
30
+ */
31
+ export declare function createVerifiedOrigin(input: VerifiedOrigin): VerifiedOrigin;
32
+ export {};
33
+ //# sourceMappingURL=types.d.ts.map
@@ -0,0 +1,23 @@
1
+ export class InsecureOriginSourceError extends Error {
2
+ constructor({ message }) { super(message); }
3
+ }
4
+ /** Missing trust evidence is a hard precondition failure. Callers must fail closed rather than
5
+ * guessing an origin from the request or another unverified value. */
6
+ export class OriginNotVerifiedError extends Error {
7
+ constructor({ message }) { super(message); }
8
+ }
9
+ /** Copy stored evidence, rejecting an HTTP public origin with InsecureOriginSourceError.
10
+ * @complexity O(1) time and space; pure, with no ownership or reachability probe.
11
+ * @example createVerifiedOrigin({ scheme: "https", host: "example.com", verifiedAt, source: "workspace-setting" });
12
+ */
13
+ export function createVerifiedOrigin(input) {
14
+ // Repositories and other adapters must construct evidence through this function; an object
15
+ // literal can bypass the scheme/source invariant even though it satisfies the structural type.
16
+ if (input.scheme === "http" && input.source !== "dev-capability") {
17
+ throw new InsecureOriginSourceError({
18
+ message: `origin scheme 'http' is only legal for source 'dev-capability' (got source '${input.source}')`
19
+ });
20
+ }
21
+ return { ...input };
22
+ }
23
+ //# sourceMappingURL=types.js.map
@@ -0,0 +1,2 @@
1
+ export * from "./verified-origin/index.js";
2
+ //# sourceMappingURL=verified-origin.d.ts.map
@@ -0,0 +1,2 @@
1
+ export * from "./verified-origin/index.js";
2
+ //# sourceMappingURL=verified-origin.js.map
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@jini-ai/http-kit",
3
- "version": "0.3.7",
4
- "description": "Composable Express route packs and JSON-route transport for a @jini-ai/core daemon composition: request parsing, response serialization, same-origin guard, and a route-pack registrar.",
3
+ "version": "0.4.0",
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": {
7
7
  "type": "git",
@@ -11,6 +11,13 @@
11
11
  "jini": {
12
12
  "domain": "server",
13
13
  "kind": "transport",
14
+ "entries": {
15
+ ".": "node",
16
+ "./rate-limit": "node",
17
+ "./middleware": "node",
18
+ "./verified-origin": "node",
19
+ "./observability": "node"
20
+ },
14
21
  "runtime": "node"
15
22
  },
16
23
  "type": "module",
@@ -22,10 +29,33 @@
22
29
  "types": "./dist/index.d.ts",
23
30
  "import": "./dist/index.js",
24
31
  "default": "./dist/index.js"
32
+ },
33
+ "./rate-limit": {
34
+ "types": "./dist/rate-limit.d.ts",
35
+ "import": "./dist/rate-limit.js",
36
+ "default": "./dist/rate-limit.js"
37
+ },
38
+ "./middleware": {
39
+ "types": "./dist/middleware.d.ts",
40
+ "import": "./dist/middleware.js",
41
+ "default": "./dist/middleware.js"
42
+ },
43
+ "./verified-origin": {
44
+ "types": "./dist/verified-origin.d.ts",
45
+ "import": "./dist/verified-origin.js",
46
+ "default": "./dist/verified-origin.js"
47
+ },
48
+ "./observability": {
49
+ "types": "./dist/observability.d.ts",
50
+ "import": "./dist/observability.js",
51
+ "default": "./dist/observability.js"
25
52
  }
26
53
  },
27
54
  "files": [
28
55
  "dist",
56
+ "README.md",
57
+ "CHANGELOG.md",
58
+ "LICENSE",
29
59
  "!dist/**/*.test.js",
30
60
  "!dist/**/*.test.d.ts",
31
61
  "!dist/**/*.test.js.map",
@@ -39,16 +69,13 @@
39
69
  },
40
70
  "dependencies": {
41
71
  "express": "^4.21.0",
42
- "@jini-ai/core": "0.3.1",
43
- "@jini-ai/platform": "0.3.0",
44
- "@jini-ai/agent-runtime": "0.3.9",
45
- "@jini-ai/protocol": "0.3.0",
46
- "@jini-ai/daemon": "0.3.7"
72
+ "@jini-ai/core": "0.4.0",
73
+ "@jini-ai/protocol": "0.4.0",
74
+ "@jini-ai/platform": "0.5.0"
47
75
  },
48
76
  "devDependencies": {
49
77
  "@types/express": "^4.17.21",
50
- "@vitest/coverage-v8": "^2.1.9",
51
- "@jini-ai/chat": "0.3.8"
78
+ "@vitest/coverage-v8": "^2.1.9"
52
79
  },
53
80
  "scripts": {
54
81
  "build": "tsc -p tsconfig.json",
@@ -1,15 +0,0 @@
1
- /**
2
- * @module express/run-stream
3
- *
4
- * Express-specific mounting glue for the shared AG-UI SSE run-stream handler (`../run-stream.js`).
5
- * Express's `Request`/`Response` already *are* Node's raw `http.IncomingMessage`/
6
- * `http.ServerResponse` (Express's `Response` extends `http.ServerResponse` directly), so this
7
- * file's only job is resolving `req.params.runId` and handing the request/response straight
8
- * through — a few lines, not a reimplementation, per the design decision that motivated building
9
- * the SSE primitive once instead of duplicating it per transport.
10
- */
11
- import type { Express } from 'express';
12
- import { type RunStreamDeps } from '../run-stream.js';
13
- /** Mounts the AG-UI SSE run-stream route on `app`. A pack's `http(app, services)` calls this directly. */
14
- export declare function registerRunStreamRoute(app: Express, deps: RunStreamDeps): void;
15
- //# sourceMappingURL=run-stream.d.ts.map
@@ -1,11 +0,0 @@
1
- import { handleRunStreamRequest, RUN_STREAM_ROUTE_PATH } from '../run-stream.js';
2
- /** Mounts the AG-UI SSE run-stream route on `app`. A pack's `http(app, services)` calls this directly. */
3
- export function registerRunStreamRoute(app, deps) {
4
- app.get(RUN_STREAM_ROUTE_PATH, async (req, res) => {
5
- // `:runId` is a required path segment of RUN_STREAM_ROUTE_PATH — this handler is only ever
6
- // reached via a URL that already matched it, so the param is always present at runtime even
7
- // though @types/express types every param as possibly `undefined` in general.
8
- await handleRunStreamRequest(req, res, req.params.runId, deps);
9
- });
10
- }
11
- //# sourceMappingURL=run-stream.js.map
@@ -1,32 +0,0 @@
1
- /**
2
- * @module @jini/http/express
3
- *
4
- * The Express-native transport namespace: re-exports this package's existing flat Express
5
- * implementation (request parsing, response serialization, the mounting Adapter, the `/api`
6
- * security middleware, the route-registration guard, compat error helpers, the daemon-status
7
- * routes, and the runs/agents/host-tools route packs) under one namespace, mirroring
8
- * `./fastify/index.js`'s shape so a transport-switchable caller (`@jini/node-host`'s
9
- * `createLocalNodeDaemon`) can import either namespace symmetrically. Nothing here is a new
10
- * implementation — every export is the same flat file every other consumer of this package
11
- * already imports directly from the root barrel; this module exists only so `httpExpress.*` and
12
- * `httpFastify.*` read the same at call sites that need to pick a transport explicitly.
13
- */
14
- export type { AdapterContext } from './adapter.js';
15
- export { defineJsonRoute, mountJsonRoute } from './adapter.js';
16
- export type { ApiBearerAuthMiddlewareDeps, ApiOriginGuardMiddlewareDeps } from './api-security-middleware.js';
17
- export { registerApiBearerAuthMiddleware, registerApiOriginGuardMiddleware } from './api-security-middleware.js';
18
- export { createCompatApiError, createCompatApiErrorResponse, sendApiError as sendCompatApiError, } from './compat.js';
19
- export type { DaemonShutdownResponse, DaemonStatusDeps, DaemonStatusResponse, } from './daemon-status.js';
20
- export { daemonShutdownRoute, daemonStatusRoute, registerDaemonStatusRoutes } from './daemon-status.js';
21
- export { isLoopbackHostname, isLoopbackPeerAddress, localOriginFromHeader, normalizeLocalAuthority, requireLocalDaemonRequest, validateLocalDaemonRequest, } from './local-daemon-request.js';
22
- export type { OriginContext } from './origin.js';
23
- export { guardSameOrigin } from './origin.js';
24
- export { rawInput, validationError } from './request.js';
25
- export { registerRunStreamRoute } from './express/run-stream.js';
26
- export { sendApiError, sendJson, statusForError } from './response.js';
27
- export type { InstallRouteRegistrationGuardOptions, RouteRegistration } from './route-registration-guard.js';
28
- export { getRouteRegistrationInventory, guardedRouteKey, installRouteRegistrationGuard, } from './route-registration-guard.js';
29
- export { registerRunRoutes } from './runs.js';
30
- export { registerAgentRoutes } from './agents.js';
31
- export { registerHostToolsRoutes } from './host-tools.js';
32
- //# sourceMappingURL=express-index.d.ts.map
@@ -1,14 +0,0 @@
1
- export { defineJsonRoute, mountJsonRoute } from './adapter.js';
2
- export { registerApiBearerAuthMiddleware, registerApiOriginGuardMiddleware } from './api-security-middleware.js';
3
- export { createCompatApiError, createCompatApiErrorResponse, sendApiError as sendCompatApiError, } from './compat.js';
4
- export { daemonShutdownRoute, daemonStatusRoute, registerDaemonStatusRoutes } from './daemon-status.js';
5
- export { isLoopbackHostname, isLoopbackPeerAddress, localOriginFromHeader, normalizeLocalAuthority, requireLocalDaemonRequest, validateLocalDaemonRequest, } from './local-daemon-request.js';
6
- export { guardSameOrigin } from './origin.js';
7
- export { rawInput, validationError } from './request.js';
8
- export { registerRunStreamRoute } from './express/run-stream.js';
9
- export { sendApiError, sendJson, statusForError } from './response.js';
10
- export { getRouteRegistrationInventory, guardedRouteKey, installRouteRegistrationGuard, } from './route-registration-guard.js';
11
- export { registerRunRoutes } from './runs.js';
12
- export { registerAgentRoutes } from './agents.js';
13
- export { registerHostToolsRoutes } from './host-tools.js';
14
- //# sourceMappingURL=express-index.js.map
@@ -1,31 +0,0 @@
1
- /**
2
- * The module's top orchestration layer: wires request parsing, the same-origin guard, a route's
3
- * `handle`, and response serialization into a single Fastify route handler. This is the only file
4
- * in this subtree that knows about Fastify's `request`/`reply` on the mounting side. Same job as
5
- * `../express/adapter.ts`'s `mountJsonRoute`, registered through Fastify's native
6
- * `fastify.route({ method, url, handler })` instead of Express's `app[method](path, handler)`.
7
- */
8
- import type { FastifyInstance } from 'fastify';
9
- import { type OriginContext } from './origin.js';
10
- import type { JsonRouteSpec } from '../types.js';
11
- /** Server startup state a mounted route needs to evaluate its same-origin guard. */
12
- export interface AdapterContext extends OriginContext {
13
- }
14
- /**
15
- * Identity function that pins a route spec's generic parameters at the definition site so
16
- * callers do not have to repeat them. The returned spec is consumed by `mountJsonRoute` (live)
17
- * and by tests (direct invocation of `route.parse` / `route.handle`).
18
- */
19
- export declare function defineJsonRoute<Input, Output, Deps>(spec: JsonRouteSpec<Input, Output, Deps>): JsonRouteSpec<Input, Output, Deps>;
20
- /**
21
- * Mounts one JsonRouteSpec on a Fastify instance. The Adapter is the only code here that knows
22
- * about request/reply; the route's parse and handle functions operate on `RouteInputContext` and
23
- * `Deps` respectively, so they are unit testable without Fastify.
24
- *
25
- * `exposeHeadRoute: false` is passed explicitly so a `GET` spec does not also register Fastify's
26
- * automatic `HEAD` sibling route — the Express version never registers one either, and a spec's
27
- * `handle` is not written to answer a bodyless `HEAD` request correctly (e.g. `daemonStatusRoute`
28
- * always returns a JSON body).
29
- */
30
- export declare function mountJsonRoute<Input, Output, Deps>(app: FastifyInstance, spec: JsonRouteSpec<Input, Output, Deps>, deps: Deps, adapter: AdapterContext): void;
31
- //# sourceMappingURL=adapter.d.ts.map
@@ -1,64 +0,0 @@
1
- import { createApiError } from '@jini/protocol';
2
- import { rawInput } from './request.js';
3
- import { sendApiError, sendJson, statusForError } from './response.js';
4
- import { guardSameOrigin } from './origin.js';
5
- /**
6
- * Identity function that pins a route spec's generic parameters at the definition site so
7
- * callers do not have to repeat them. The returned spec is consumed by `mountJsonRoute` (live)
8
- * and by tests (direct invocation of `route.parse` / `route.handle`).
9
- */
10
- export function defineJsonRoute(spec) {
11
- return spec;
12
- }
13
- /** Maps the shared, lower-case `HttpMethod` union to the upper-case method literal Fastify's `route()` expects. */
14
- const FASTIFY_METHOD = {
15
- get: 'GET',
16
- post: 'POST',
17
- put: 'PUT',
18
- delete: 'DELETE',
19
- patch: 'PATCH',
20
- };
21
- /**
22
- * Mounts one JsonRouteSpec on a Fastify instance. The Adapter is the only code here that knows
23
- * about request/reply; the route's parse and handle functions operate on `RouteInputContext` and
24
- * `Deps` respectively, so they are unit testable without Fastify.
25
- *
26
- * `exposeHeadRoute: false` is passed explicitly so a `GET` spec does not also register Fastify's
27
- * automatic `HEAD` sibling route — the Express version never registers one either, and a spec's
28
- * `handle` is not written to answer a bodyless `HEAD` request correctly (e.g. `daemonStatusRoute`
29
- * always returns a JSON body).
30
- */
31
- export function mountJsonRoute(app, spec, deps, adapter) {
32
- app.route({
33
- method: FASTIFY_METHOD[spec.method],
34
- url: spec.path,
35
- exposeHeadRoute: false,
36
- handler: async (req, reply) => {
37
- try {
38
- if (spec.requireSameOrigin) {
39
- const origin = guardSameOrigin(req, adapter);
40
- if (!origin.ok) {
41
- sendApiError(reply, statusForError(origin.error), origin.error);
42
- return;
43
- }
44
- }
45
- const parsed = spec.parse(rawInput(req));
46
- if (!parsed.ok) {
47
- sendApiError(reply, statusForError(parsed.error), parsed.error);
48
- return;
49
- }
50
- const result = await spec.handle(parsed.value, deps);
51
- if (!result.ok) {
52
- sendApiError(reply, statusForError(result.error), result.error);
53
- return;
54
- }
55
- sendJson(reply, spec.successStatus ?? 200, result.value);
56
- }
57
- catch (e) {
58
- const message = e instanceof Error ? e.message : String(e);
59
- sendApiError(reply, 500, createApiError('INTERNAL_ERROR', message));
60
- }
61
- },
62
- });
63
- }
64
- //# sourceMappingURL=adapter.js.map
@@ -1,13 +0,0 @@
1
- /**
2
- * @module fastify/agents
3
- *
4
- * Fastify-mounting glue for `../agents.js`'s `agentListRoute` — the exact same `JsonRouteSpec`
5
- * the Express mounting in `../agents.js` uses, just mounted through this subtree's own
6
- * `mountJsonRoute` instead.
7
- */
8
- import type { FastifyInstance } from 'fastify';
9
- import { type AgentsHttpDeps } from '../agents.js';
10
- import { type AdapterContext } from './adapter.js';
11
- /** Mounts `GET /api/agents` on `app` — the Fastify-native equivalent of `../agents.js`'s `registerAgentRoutes`. */
12
- export declare function registerAgentRoutes(app: FastifyInstance, deps: AgentsHttpDeps, adapter: AdapterContext): void;
13
- //# sourceMappingURL=agents.d.ts.map
@@ -1,7 +0,0 @@
1
- import { agentListRoute } from '../agents.js';
2
- import { mountJsonRoute } from './adapter.js';
3
- /** Mounts `GET /api/agents` on `app` — the Fastify-native equivalent of `../agents.js`'s `registerAgentRoutes`. */
4
- export function registerAgentRoutes(app, deps, adapter) {
5
- mountJsonRoute(app, agentListRoute, deps, adapter);
6
- }
7
- //# sourceMappingURL=agents.js.map
@@ -1,64 +0,0 @@
1
- /**
2
- * @module fastify/api-security-middleware
3
- *
4
- * The two `/api` request gates a locally-bound daemon needs before any route handler runs:
5
- * bearer-token authentication (optional, active only when a token is configured) and cross-origin
6
- * rejection (always active). Same job and decision logic as `../express/api-security-middleware.ts`
7
- * (see that file's own doc for the full drop-list this was genericized from), reimplemented on
8
- * Fastify's native `onRequest` lifecycle hook (`app.addHook('onRequest', ...)`) in place of
9
- * Express's `app.use('/api', ...)` path-scoped middleware. Fastify has no first-class "scope this
10
- * hook to a URL prefix" primitive at the plain-instance level (that requires nesting the routes
11
- * themselves inside a `.register()` plugin with a `prefix`, which `mountPackHttp`'s pack-agnostic
12
- * mounting does not do), so both hooks below scope themselves manually by checking the request's
13
- * own path against the `/api` prefix before applying either gate — the observable behavior is
14
- * identical to the Express version's `app.use('/api', ...)` scoping.
15
- */
16
- import type { FastifyInstance } from 'fastify';
17
- import { type ApiTokenAuthEnvConfig } from '@jini/core';
18
- export interface ApiBearerAuthMiddlewareDeps {
19
- /** Env var names for the token/disable flags. Defaults to `JINI_API_TOKEN` / `JINI_DISABLE_API_AUTH`. */
20
- tokenConfig?: ApiTokenAuthEnvConfig;
21
- /** Defaults to `process.env`. Threaded through so tests never have to mutate real process env. */
22
- env?: NodeJS.ProcessEnv;
23
- }
24
- /**
25
- * Registers a bearer-token gate on every `/api/*` route, active only when
26
- * {@link isApiTokenMiddlewareEnabled} says a token is configured and auth hasn't been disabled.
27
- * When active: open-probe paths and loopback peers skip the check unconditionally; every other
28
- * request must send `Authorization: Bearer <token>` matching the configured token exactly, or the
29
- * request is rejected with 401 before reaching any route handler.
30
- *
31
- * @param app - The Fastify instance to register the gate on.
32
- * @param deps - See {@link ApiBearerAuthMiddlewareDeps}. Both fields are optional; omitting `deps`
33
- * entirely reads `JINI_API_TOKEN`/`JINI_DISABLE_API_AUTH` from real `process.env`.
34
- * @returns Nothing. Registers zero hooks (a deliberate no-op, not a bug) when no token is configured.
35
- * @complexity Setup is O(1). Each gated request is O(1) (one Set lookup, one regex match).
36
- * @overallScore 100/100
37
- */
38
- export declare function registerApiBearerAuthMiddleware(app: FastifyInstance, deps?: ApiBearerAuthMiddlewareDeps): void;
39
- export interface ApiOriginGuardMiddlewareDeps {
40
- /** The host this daemon is bound to — compared against a request's `Host`/`Origin` headers. */
41
- host: string;
42
- /** Extra allow-listed origins (e.g. a reverse-proxy's public origin). Defaults to none. */
43
- extraAllowedOrigins?: readonly string[];
44
- /** Returns the daemon's resolved listen port, or a falsy value before it has resolved. */
45
- getResolvedPort: () => number | null | undefined;
46
- /** Defaults to `process.env`. Threaded through so `JINI_WEB_PORT` is testable without mutating real process env. */
47
- env?: NodeJS.ProcessEnv;
48
- }
49
- /**
50
- * Registers an unconditional cross-origin gate on every `/api/*` route: non-browser clients (no
51
- * `Origin` header) and requests whose `Origin` resolves to a loopback, private-LAN, or explicitly
52
- * allow-listed origin are let through; everything else is rejected with 403. `Origin: null`
53
- * (typically a sandboxed iframe) is always rejected — see the Express version's doc for why the
54
- * origin daemon's safe-GET exemption for that case was dropped.
55
- *
56
- * @param app - The Fastify instance to register the gate on.
57
- * @param deps - See {@link ApiOriginGuardMiddlewareDeps}.
58
- * @returns Nothing. Unlike the bearer-token gate, this always registers its hook — there is
59
- * no "disabled" state.
60
- * @complexity Setup is O(1). Each gated request is O(p) in the number of allowed ports (typically 1-2).
61
- * @overallScore 100/100
62
- */
63
- export declare function registerApiOriginGuardMiddleware(app: FastifyInstance, deps: ApiOriginGuardMiddlewareDeps): void;
64
- //# sourceMappingURL=api-security-middleware.d.ts.map