@jini-ai/http-kit 0.4.2 → 0.6.10
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 +149 -0
- package/dist/adapter.js +56 -47
- package/dist/local-daemon-request.js +11 -5
- package/dist/observability.d.ts +18 -0
- package/dist/observability.js +19 -0
- package/dist/verified-origin/site-path.js +5 -1
- package/package.json +7 -7
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,154 @@
|
|
|
1
1
|
# @jini-ai/http-kit
|
|
2
2
|
|
|
3
|
+
## 0.6.10
|
|
4
|
+
|
|
5
|
+
### Patch Changes
|
|
6
|
+
|
|
7
|
+
- 8ff5653: Add the attachment upload capability: `POST`/`DELETE /api/attachments` plus a disk-backed store.
|
|
8
|
+
|
|
9
|
+
Composer file and image uploads were something every host had to build for itself. Getting it _working_
|
|
10
|
+
is easy; getting it right is not, and the parts that are easy to skip are the parts that matter — a
|
|
11
|
+
renderer must never learn a filesystem path, a claimed file must be provably the same file that was
|
|
12
|
+
uploaded, and the bytes must be gone when the run ends. This is that whole capability, extracted from a
|
|
13
|
+
working host implementation rather than designed fresh.
|
|
14
|
+
|
|
15
|
+
`createDiskAttachmentStore({ uploadDirectory, ... })` satisfies the `AttachmentStore` port with every
|
|
16
|
+
quota defaulted (10 files / 50 MB per message, 100 files / 200 MB per store, one-hour retention).
|
|
17
|
+
`registerAttachmentRoutes(app, { store }, adapter)` mounts the two routes, with a per-registration
|
|
18
|
+
concurrent-upload limit, a streaming byte cap, and the same-origin guard on by default.
|
|
19
|
+
|
|
20
|
+
What the store guarantees, all of it re-derived server-side and none of it taken from the client:
|
|
21
|
+
|
|
22
|
+
- the wire `path` is an opaque `attachment:<uuid>` capability, never a filesystem path — `claim()` is
|
|
23
|
+
what exchanges one for a real path, and only once per attachment;
|
|
24
|
+
- `kind` is sniffed from the leading bytes (`detectAttachmentKind`), so a renderer cannot decide whether
|
|
25
|
+
its upload reaches the agent as an image;
|
|
26
|
+
- the display name is a sanitized basename; the _stored_ name is a fresh UUID;
|
|
27
|
+
- `claim()` re-verifies `dev`/`ino`/`size` and `realpath` against what registration recorded, so neither
|
|
28
|
+
the file nor a parent directory can be swapped for a symlink in between;
|
|
29
|
+
- quota decisions happen with no `await` between the check and the commit, so concurrent uploads cannot
|
|
30
|
+
both reserve the last slot;
|
|
31
|
+
- the upload directory is emptied on construction — files from an interrupted previous process cannot be
|
|
32
|
+
authenticated, so they are not adopted.
|
|
33
|
+
|
|
34
|
+
Run-lifecycle wiring stays host-owned, matching `createRunScopedContextStore`'s precedent: a host calls
|
|
35
|
+
`store.claim(...)` in its own `onRunStarted`, threads the result into `AgentExecutor.run()`'s existing
|
|
36
|
+
`imagePaths`/`extraAllowedDirs`/`uploadRoot`, and calls `store.cleanupRun(runId)` in a `finally`. The
|
|
37
|
+
module doc carries that ~10-line pattern. There is no generic run hook to auto-wire into, and inventing
|
|
38
|
+
one here would be worse than documenting the ten lines.
|
|
39
|
+
|
|
40
|
+
Two things found while extracting, both now handled rather than inherited:
|
|
41
|
+
|
|
42
|
+
- **A body parser silently eats uploads.** The route streams the raw request, so an app-wide
|
|
43
|
+
`express.json()` — which `compose-jini-kernel` mounts for every daemon — consumes the body of any
|
|
44
|
+
upload whose content type it claims. Dropping a `.json` file was enough to trigger it, and it surfaced
|
|
45
|
+
as the useless "attachment is empty". The route now detects an already-drained stream and reports it as
|
|
46
|
+
the host misconfiguration it is.
|
|
47
|
+
- **Two redundant integrity checks that could never fire.** A `path.relative` containment test sitting
|
|
48
|
+
behind a `dirname(filePath) === batchDirectory` check added nothing (parent-directory equality is
|
|
49
|
+
strictly stronger and implies containment), and an `isSymbolicLink()` check behind `!isFile()` on an
|
|
50
|
+
`lstat` result can never be the deciding one, since `lstat` reports exactly one file type. Both were
|
|
51
|
+
removed with the reasoning recorded inline. The accepted-input set is unchanged; the integrity decision
|
|
52
|
+
itself moved into a pure, exported `isUnchangedAttachment` so each condition — including a device
|
|
53
|
+
change, which no filesystem test can stage — is directly verifiable.
|
|
54
|
+
|
|
55
|
+
- 601fad5: Removed the `agui-stream` run-stream route: `RUN_STREAM_ROUTE_PATH`, `registerRunStreamRoute`, and
|
|
56
|
+
`handleRunStreamRequest` are no longer exported, and the route no longer mounts.
|
|
57
|
+
|
|
58
|
+
The route was named `agui-stream` from when Jini's own run-event protocol was mistakenly branded as
|
|
59
|
+
AG-UI; the TypeScript symbols were renamed to `GenUi` on 2026-07-27, but the URL was deliberately left
|
|
60
|
+
un-renamed on the assumption it was a wire contract an already-deployed client might be calling. A
|
|
61
|
+
2026-08-18 audit found zero callers anywhere — no client in this repo or in `Tovu` ever requested it,
|
|
62
|
+
`examples/reference-web`'s daemon only registered the route without anything ever calling it, and
|
|
63
|
+
`@jini-ai/http-kit` has never been published to npm, so no external integrator could depend on it either.
|
|
64
|
+
Rather than carry a dead, confusingly-named route indefinitely, it was removed outright.
|
|
65
|
+
|
|
66
|
+
`@jini-ai/agentic`'s `gen-ui` module (`createGenUiEncoder` and the six `GenUi*` event types) is
|
|
67
|
+
unaffected — it remains part of that package's public surface independent of this route.
|
|
68
|
+
|
|
69
|
+
- 4f52784: Publish a route manifest so a reverse proxy stops hand-copying path strings.
|
|
70
|
+
|
|
71
|
+
A host proxying a Jini daemon in another process needs that daemon's route list to forward anything,
|
|
72
|
+
and with no published inventory the only way to build one was to copy path strings by hand. A
|
|
73
|
+
hand-copied list falls behind the moment a family gains a route — which has already happened in a real
|
|
74
|
+
consumer, whose proxy shipped without `GET /api/runs` and left the daemon's list endpoint 404-ing at
|
|
75
|
+
the host's own router.
|
|
76
|
+
|
|
77
|
+
`JINI_ROUTE_MANIFEST`, `routeFamilyManifest(family)`, and `manifestRoutesForFamilies(families)` expose
|
|
78
|
+
`{method, path}` per feature family as inert data, readable without mounting anything.
|
|
79
|
+
|
|
80
|
+
The manifest declares **no method or path literals** — every entry is derived from the same
|
|
81
|
+
`JsonRouteSpec` constant the family's `register*Routes` mounts, so a path change moves the manifest with
|
|
82
|
+
it. A paired test mounts each declared family's real registrar and asserts the manifest matches, so the
|
|
83
|
+
one remaining failure mode (a family gains a route nobody lists) fails a test instead of a consumer.
|
|
84
|
+
|
|
85
|
+
That test earned its keep immediately: it found that the `runs` family mounts a spec-less streaming
|
|
86
|
+
route, `/api/runs/:runId/events`, that a hand-copied proxy list could easily miss. `RUN_EVENTS_ROUTE_PATH`
|
|
87
|
+
is now exported so it never has to be restated as a literal.
|
|
88
|
+
|
|
89
|
+
Scope is honest: the manifest covers the families a sidecar consumer proxies, not all 19 the package can
|
|
90
|
+
mount. `routeFamilyManifest` returns `undefined` for an undeclared family rather than an empty array, so
|
|
91
|
+
"not described here" is never mistaken for "has no routes".
|
|
92
|
+
|
|
93
|
+
- 4f52784: Add a `sidecar-strict` security mode and per-run MCP credential propagation.
|
|
94
|
+
|
|
95
|
+
For a daemon whose threat model is **another process running as the same OS user** rather than a
|
|
96
|
+
remote attacker, the existing `jini-local` mode is a no-op: `registerApiBearerAuthMiddleware`
|
|
97
|
+
short-circuits for any loopback peer before it reads the `Authorization` header, and a `127.0.0.1`
|
|
98
|
+
bind keeps remote hosts out while doing nothing about a co-resident process. A consumer that spawns a
|
|
99
|
+
Jini daemon holding real authority — starting agent runs, executing tools against a real database —
|
|
100
|
+
previously had to write its own middleware.
|
|
101
|
+
|
|
102
|
+
- `@jini-ai/http-kit` gains `requireStrictBearerToken`: fail-closed 503 when the named token env var
|
|
103
|
+
is unset, 401 on mismatch, **no loopback exemption and no disable flag**. Its `tokenEnvVar` is
|
|
104
|
+
required with no default, so this package never names a host's secret.
|
|
105
|
+
- `composeJiniKernel` gains `security: { mode: 'sidecar-strict', host, tokenEnvVar, exemptPaths? }`.
|
|
106
|
+
Purely additive — `host` and `jini-local` are unchanged by construction, since the modes are arms of
|
|
107
|
+
a discriminated union. The strict gate mounts ahead of the JSON body parser, so a caller it rejects
|
|
108
|
+
never has its body parsed.
|
|
109
|
+
- `@jini-ai/daemon`'s `McpJsonInjectionOptions` gains `credential?: (runId) => string | Promise<string>`
|
|
110
|
+
— a **resolver, not a string**, because injection options are built once before any run exists and a
|
|
111
|
+
boot-wide shared secret would defeat the point of scoping a credential to a run. It is delivered to
|
|
112
|
+
the child as `JINI_DAEMON_TOKEN`.
|
|
113
|
+
- `@jini-ai/mcp`'s `jini-mcp` reads that variable and attaches `Authorization` to every daemon call.
|
|
114
|
+
Optional throughout: with no credential, request headers and `.mcp.json` output are byte-identical
|
|
115
|
+
to before.
|
|
116
|
+
|
|
117
|
+
Also generalized: both existing bearer gates now compare tokens in constant time (`timingSafeEqual`)
|
|
118
|
+
and share one header-parsing helper, closing a timing side channel and removing a duplicated regex.
|
|
119
|
+
|
|
120
|
+
- 8ff5653: `GET /api/tools/:id` answers 404 for an unknown tool id, not 400.
|
|
121
|
+
|
|
122
|
+
`toolCatalogDescribeRoute` (the route `@jini-ai/mcp`'s `describe_tool` proxies) reported a
|
|
123
|
+
well-formed request naming a nonexistent catalog entry as `VALIDATION_FAILED` / **400**, because its
|
|
124
|
+
`handle` reached for the same `validationError` helper its `parse` step uses — where 400 genuinely is
|
|
125
|
+
correct. The result was that a caller could not tell "you sent a malformed request" apart from "that
|
|
126
|
+
tool does not exist", which are the two things a status code is supposed to separate.
|
|
127
|
+
|
|
128
|
+
The three sibling route families in this package with the identical "the referenced resource isn't
|
|
129
|
+
there" case — `memory.ts`'s `memory not found`, `routines.ts`'s `routine not found`, and `media.ts`'s
|
|
130
|
+
`media task not found` — all already answered 404. This was the one family out of step, so this is a
|
|
131
|
+
behavior correction toward an existing in-package convention rather than a new one.
|
|
132
|
+
|
|
133
|
+
Now `NOT_FOUND` / **404**, with the message unchanged (`no catalog entry for tool id "<id>"`).
|
|
134
|
+
`parse` failures on this route — a missing `:id` path segment — are still 400.
|
|
135
|
+
|
|
136
|
+
**Behavior change for callers**, hence the minor bump: anything that branched on 400 to detect an
|
|
137
|
+
unknown tool id must branch on 404 instead. Client code that only distinguishes success from failure
|
|
138
|
+
is unaffected. A wire-level test now pins the observed status code for the not-found case, the
|
|
139
|
+
malformed case, and the cross-origin case, so the two cannot silently converge again.
|
|
140
|
+
|
|
141
|
+
- Updated dependencies [22f0619]
|
|
142
|
+
- Updated dependencies [82ed2d3]
|
|
143
|
+
- Updated dependencies [3fe4d14]
|
|
144
|
+
- Updated dependencies [5a3de86]
|
|
145
|
+
- @jini-ai/core@0.6.10
|
|
146
|
+
- @jini-ai/protocol@0.6.10
|
|
147
|
+
|
|
148
|
+
## 0.4.3 — 2026-10-22
|
|
149
|
+
|
|
150
|
+
- 2026-10-22: Completed-request logging off by default (one compact line when enabled), coverage.
|
|
151
|
+
|
|
3
152
|
## 0.4.2 — 2026-10-14
|
|
4
153
|
|
|
5
154
|
- Express 5 accepted: the optional `express` peer is now `^4.21.0 || ^5.0.0` (1442d875), so an Express 5 host no longer hits ERESOLVE.
|
package/dist/adapter.js
CHANGED
|
@@ -51,8 +51,7 @@ export class ClientFacingError extends Error {
|
|
|
51
51
|
* @complexity O(1) time/space for the fixed spec fields.
|
|
52
52
|
*/
|
|
53
53
|
export function defineJsonRoute(requiredArgs, optionalArgs = {}) {
|
|
54
|
-
|
|
55
|
-
return spec;
|
|
54
|
+
return { ...requiredArgs, ...optionalArgs };
|
|
56
55
|
}
|
|
57
56
|
/**
|
|
58
57
|
* Mounts one JsonRouteSpec on an Express app. The Adapter is the only code here that knows
|
|
@@ -86,15 +85,8 @@ export function mountJsonRoute({ app, spec, deps, adapter }, _optional = {}) {
|
|
|
86
85
|
const raw = rawInput({ req });
|
|
87
86
|
if (spec.ports?.workspace)
|
|
88
87
|
await spec.ports.workspace({ raw, deps });
|
|
89
|
-
if (spec
|
|
90
|
-
|
|
91
|
-
throw new Error('same-origin adapter context is required');
|
|
92
|
-
const origin = guardSameOrigin({ req, origin: adapter });
|
|
93
|
-
if (!origin.ok) {
|
|
94
|
-
sendApiError({ res, status: statusForError({ error: origin.error }), error: origin.error });
|
|
95
|
-
return;
|
|
96
|
-
}
|
|
97
|
-
}
|
|
88
|
+
if (!allowRouteOrigin({ req, res, spec, adapter }))
|
|
89
|
+
return;
|
|
98
90
|
let context;
|
|
99
91
|
if (spec.ports?.authenticate)
|
|
100
92
|
context = await spec.ports.authenticate({ raw, res, deps });
|
|
@@ -111,48 +103,65 @@ export function mountJsonRoute({ app, spec, deps, adapter }, _optional = {}) {
|
|
|
111
103
|
await spec.ports.authorize({ context, deps, permission, entityType });
|
|
112
104
|
};
|
|
113
105
|
const result = await spec.handle({ input: parsed.value, deps, context, authorize }, { signal: abortController.signal });
|
|
114
|
-
|
|
115
|
-
// `await` above was pending — nothing here runs concurrently with it — so this unambiguously
|
|
116
|
-
// means the client was already gone before any response was sent. Writing one now would be
|
|
117
|
-
// wasted work at best and, worse, would route a benign disconnect into the SEC-005 catch
|
|
118
|
-
// below as a false internal error if the socket rejects the write.
|
|
119
|
-
if (abortController.signal.aborted)
|
|
120
|
-
return;
|
|
121
|
-
if (!result.ok) {
|
|
122
|
-
sendApiError({ res, status: statusForError({ error: result.error }), error: result.error });
|
|
123
|
-
return;
|
|
124
|
-
}
|
|
125
|
-
sendJson({ res, status: spec.successStatus ?? 200, body: result.value });
|
|
106
|
+
sendRouteResult({ res, result, spec, signal: abortController.signal });
|
|
126
107
|
}
|
|
127
108
|
catch (e) {
|
|
128
|
-
|
|
129
|
-
// its guard rejections. Hosts without it retain the SEC-005 policy below unchanged.
|
|
130
|
-
if (spec.ports?.onError) {
|
|
131
|
-
spec.ports.onError({ res, error: e });
|
|
132
|
-
return;
|
|
133
|
-
}
|
|
134
|
-
// A route (or something it called) already classified this failure as safe to disclose —
|
|
135
|
-
// see `ClientFacingError`'s own doc. Sent verbatim, at its own status; never routed to the
|
|
136
|
-
// SEC-005 sink below, because nothing unanticipated happened.
|
|
137
|
-
if (e instanceof ClientFacingError) {
|
|
138
|
-
sendApiError({ res, status: statusForError({ error: e.apiError }), error: e.apiError });
|
|
139
|
-
return;
|
|
140
|
-
}
|
|
141
|
-
// SEC-005. This catch exists for exceptions no route anticipated, which makes it precisely
|
|
142
|
-
// the path most likely to be holding something private: a driver error naming a database
|
|
143
|
-
// file, a connection string, a credential a provider echoed back. Serializing `e.message`
|
|
144
|
-
// into the response handed all of that to the caller — and because `health.ts`'s probes are
|
|
145
|
-
// mounted ahead of the security middleware and exempted from the bearer gate, an unauthorized
|
|
146
|
-
// caller could read it too, simply by getting a readiness dependency to fail. The real error
|
|
147
|
-
// still reaches the operator through the sink, correlated to what the caller was told.
|
|
148
|
-
const correlationId = randomUUID();
|
|
149
|
-
const sink = adapter?.onInternalError ?? defaultInternalErrorSink;
|
|
150
|
-
sink({ method: spec.method, path: spec.path, correlationId, error: e });
|
|
151
|
-
sendApiError({ res, status: 500, error: createApiError({ code: 'INTERNAL_ERROR', message: 'an internal error occurred' }, { requestId: correlationId }) });
|
|
109
|
+
sendRouteException({ res, spec, adapter, error: e });
|
|
152
110
|
}
|
|
153
111
|
finally {
|
|
154
112
|
res.off?.('close', onResponseClose);
|
|
155
113
|
}
|
|
156
114
|
});
|
|
157
115
|
}
|
|
116
|
+
function allowRouteOrigin({ req, res, spec, adapter }, _optional = {}) {
|
|
117
|
+
if (!spec.requireSameOrigin)
|
|
118
|
+
return true;
|
|
119
|
+
if (!adapter)
|
|
120
|
+
throw new Error('same-origin adapter context is required');
|
|
121
|
+
const origin = guardSameOrigin({ req, origin: adapter });
|
|
122
|
+
if (origin.ok)
|
|
123
|
+
return true;
|
|
124
|
+
sendApiError({ res, status: statusForError({ error: origin.error }), error: origin.error });
|
|
125
|
+
return false;
|
|
126
|
+
}
|
|
127
|
+
function sendRouteResult({ res, result, spec, signal }, _optional = {}) {
|
|
128
|
+
// `signal` can only have been aborted by `onResponseClose` firing while the
|
|
129
|
+
// `await spec.handle` in the request handler was pending — nothing here runs concurrently
|
|
130
|
+
// with it — so this unambiguously means the client was already gone before any response was
|
|
131
|
+
// sent. Writing one now would be wasted work at best and, worse, would route a benign
|
|
132
|
+
// disconnect into the SEC-005 catch as a false internal error if the socket rejects the write.
|
|
133
|
+
if (signal.aborted)
|
|
134
|
+
return;
|
|
135
|
+
if (!result.ok) {
|
|
136
|
+
sendApiError({ res, status: statusForError({ error: result.error }), error: result.error });
|
|
137
|
+
return;
|
|
138
|
+
}
|
|
139
|
+
sendJson({ res, status: spec.successStatus ?? 200, body: result.value });
|
|
140
|
+
}
|
|
141
|
+
function sendRouteException({ res, spec, adapter, error: e }, _optional = {}) {
|
|
142
|
+
// An explicit host error port owns exception classification and serialization, including
|
|
143
|
+
// its guard rejections. Hosts without it retain the SEC-005 policy below unchanged.
|
|
144
|
+
if (spec.ports?.onError) {
|
|
145
|
+
spec.ports.onError({ res, error: e });
|
|
146
|
+
return;
|
|
147
|
+
}
|
|
148
|
+
// A route (or something it called) already classified this failure as safe to disclose —
|
|
149
|
+
// see `ClientFacingError`'s own doc. Sent verbatim, at its own status; never routed to the
|
|
150
|
+
// SEC-005 sink below, because nothing unanticipated happened.
|
|
151
|
+
if (e instanceof ClientFacingError) {
|
|
152
|
+
sendApiError({ res, status: statusForError({ error: e.apiError }), error: e.apiError });
|
|
153
|
+
return;
|
|
154
|
+
}
|
|
155
|
+
// SEC-005. This catch exists for exceptions no route anticipated, which makes it precisely
|
|
156
|
+
// the path most likely to be holding something private: a driver error naming a database
|
|
157
|
+
// file, a connection string, a credential a provider echoed back. Serializing `e.message`
|
|
158
|
+
// into the response handed all of that to the caller — and because `health.ts`'s probes are
|
|
159
|
+
// mounted ahead of the security middleware and exempted from the bearer gate, an unauthorized
|
|
160
|
+
// caller could read it too, simply by getting a readiness dependency to fail. The real error
|
|
161
|
+
// still reaches the operator through the sink, correlated to what the caller was told.
|
|
162
|
+
const correlationId = randomUUID();
|
|
163
|
+
const sink = adapter?.onInternalError ?? defaultInternalErrorSink;
|
|
164
|
+
sink({ method: spec.method, path: spec.path, correlationId, error: e });
|
|
165
|
+
sendApiError({ res, status: 500, error: createApiError({ code: 'INTERNAL_ERROR', message: 'an internal error occurred' }, { requestId: correlationId }) });
|
|
166
|
+
}
|
|
158
167
|
//# sourceMappingURL=adapter.js.map
|
|
@@ -53,6 +53,13 @@ export function isLoopbackPeerAddress({ address }, _optional = {}) {
|
|
|
53
53
|
return normalized === '127.0.0.1' || normalized.startsWith('127.');
|
|
54
54
|
return false;
|
|
55
55
|
}
|
|
56
|
+
function isBareHttpOrigin({ parsed }, _optional = {}) {
|
|
57
|
+
if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:')
|
|
58
|
+
return false;
|
|
59
|
+
if (parsed.pathname !== '/' || parsed.search || parsed.hash || parsed.username || parsed.password)
|
|
60
|
+
return false;
|
|
61
|
+
return true;
|
|
62
|
+
}
|
|
56
63
|
/** Parses an `Origin` header value into its origin string, requiring a bare `scheme://loopback-host[:port]` with no path/query/userinfo. */
|
|
57
64
|
export function localOriginFromHeader({ value }, _optional = {}) {
|
|
58
65
|
if (typeof value !== 'string')
|
|
@@ -62,9 +69,7 @@ export function localOriginFromHeader({ value }, _optional = {}) {
|
|
|
62
69
|
return null;
|
|
63
70
|
try {
|
|
64
71
|
const parsed = new URL(trimmed);
|
|
65
|
-
if (
|
|
66
|
-
return null;
|
|
67
|
-
if (parsed.pathname !== '/' || parsed.search || parsed.hash || parsed.username || parsed.password)
|
|
72
|
+
if (!isBareHttpOrigin({ parsed }))
|
|
68
73
|
return null;
|
|
69
74
|
if (!isLoopbackHostname({ hostname: parsed.hostname }))
|
|
70
75
|
return null;
|
|
@@ -101,14 +106,15 @@ export function validateLocalDaemonRequest({ req }, _optional = {}) {
|
|
|
101
106
|
};
|
|
102
107
|
}
|
|
103
108
|
const originHeader = req.get('origin');
|
|
104
|
-
|
|
109
|
+
const origin = localOriginFromHeader({ value: originHeader });
|
|
110
|
+
if (originHeader !== undefined && !origin) {
|
|
105
111
|
return {
|
|
106
112
|
ok: false,
|
|
107
113
|
message: 'request origin must be a loopback daemon origin',
|
|
108
114
|
details: { header: 'origin' },
|
|
109
115
|
};
|
|
110
116
|
}
|
|
111
|
-
return { ok: true, origin
|
|
117
|
+
return { ok: true, origin };
|
|
112
118
|
}
|
|
113
119
|
/**
|
|
114
120
|
* Express middleware that rejects any non-loopback request with a 403, and
|
package/dist/observability.d.ts
CHANGED
|
@@ -1,4 +1,22 @@
|
|
|
1
1
|
import type { Express, RequestHandler } from 'express';
|
|
2
|
+
import { type Logger } from '@jini-ai/core/primitives';
|
|
3
|
+
/** Log request completions only when explicitly enabled, either all or above a threshold.
|
|
4
|
+
* Structured sinks retain correlation fields; the default console gets only the compact message.
|
|
5
|
+
* Missing or invalid thresholds disable slow logging; zero is supported. Duration must exceed it.
|
|
6
|
+
* Callers supply elapsed monotonic time and bounded route patterns, never raw request data.
|
|
7
|
+
* @complexity O(1) per completion, excluding the injected logger.
|
|
8
|
+
*/
|
|
9
|
+
export declare function logCompletedRequest(required: {
|
|
10
|
+
requestId: string;
|
|
11
|
+
method: string;
|
|
12
|
+
routePattern: string;
|
|
13
|
+
statusCode: number;
|
|
14
|
+
durationMs: number;
|
|
15
|
+
}, { logger, logRequests, slowRequestMs }?: {
|
|
16
|
+
logger?: Pick<Logger, 'info'>;
|
|
17
|
+
logRequests?: boolean;
|
|
18
|
+
slowRequestMs?: number;
|
|
19
|
+
}): void;
|
|
2
20
|
/** Structural port satisfied by diagnostics/observability, with host-owned logging and tracing. */
|
|
3
21
|
export interface HttpRequestObservabilityPort {
|
|
4
22
|
trackRequest(required: {
|
package/dist/observability.js
CHANGED
|
@@ -1,3 +1,22 @@
|
|
|
1
|
+
import { createConsoleLogger } from '@jini-ai/core/primitives';
|
|
2
|
+
/** Log request completions only when explicitly enabled, either all or above a threshold.
|
|
3
|
+
* Structured sinks retain correlation fields; the default console gets only the compact message.
|
|
4
|
+
* Missing or invalid thresholds disable slow logging; zero is supported. Duration must exceed it.
|
|
5
|
+
* Callers supply elapsed monotonic time and bounded route patterns, never raw request data.
|
|
6
|
+
* @complexity O(1) per completion, excluding the injected logger.
|
|
7
|
+
*/
|
|
8
|
+
export function logCompletedRequest(required, { logger, logRequests = false, slowRequestMs } = {}) {
|
|
9
|
+
const logSlowRequest = slowRequestMs !== undefined && Number.isFinite(slowRequestMs)
|
|
10
|
+
&& slowRequestMs >= 0 && required.durationMs > slowRequestMs;
|
|
11
|
+
if (!logRequests && !logSlowRequest)
|
|
12
|
+
return;
|
|
13
|
+
const { statusCode, method, routePattern, durationMs, requestId } = required;
|
|
14
|
+
const message = `http ${statusCode} ${method} ${routePattern} ${Math.round(durationMs)}ms req=${requestId}`;
|
|
15
|
+
if (logger)
|
|
16
|
+
logger.info({ message }, { meta: { ...required } });
|
|
17
|
+
else
|
|
18
|
+
createConsoleLogger({ prefix: '' }).info({ message });
|
|
19
|
+
}
|
|
1
20
|
/** Track requests before routing and read the mount-aware route pattern at response completion.
|
|
2
21
|
* Unmatched paths use a fixed label so attacker-selected paths do not become metric labels.
|
|
3
22
|
* Each response completes its tracker once; hook error policy belongs to the injected adapter.
|
|
@@ -28,7 +28,9 @@
|
|
|
28
28
|
* {@link checkSiteRelativeTarget}). Both are bare origins, so a reference resolves to the same
|
|
29
29
|
* pathname against either.
|
|
30
30
|
*/
|
|
31
|
+
// eslint-disable-next-line sonarjs/no-clear-text-protocols -- Reserved .invalid probe origin used only for URL parsing; no network transport is invoked.
|
|
31
32
|
const PROBE_ORIGIN = "http://reserved-path-probe.invalid";
|
|
33
|
+
// eslint-disable-next-line sonarjs/no-clear-text-protocols -- Reserved .invalid probe origin used only for URL parsing; no network transport is invoked.
|
|
32
34
|
const SECOND_PROBE_ORIGIN = "http://reserved-path-probe-2.invalid";
|
|
33
35
|
/**
|
|
34
36
|
* Whether `value` contains a C0 or C1 control character.
|
|
@@ -106,7 +108,9 @@ function checkDecodedSitePathname(pathname, reservedSegments) {
|
|
|
106
108
|
}
|
|
107
109
|
if (decoded.includes("\\") || hasControlCharacter({ value: decoded }, {}))
|
|
108
110
|
return { kind: "disallowed-character" };
|
|
109
|
-
|
|
111
|
+
// `resolveDotSegments` always returns a path with a leading "/", so the first segment is
|
|
112
|
+
// everything after it up to the next "/" — `split(..., 1)` yields exactly that one element.
|
|
113
|
+
const first = resolveDotSegments(decoded).slice(1).split("/", 1).join("").toLowerCase();
|
|
110
114
|
if (reservedSegments.has(first))
|
|
111
115
|
return { kind: "reserved", surface: first };
|
|
112
116
|
return { kind: "ok" };
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@jini-ai/http-kit",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.6.10",
|
|
4
4
|
"description": "Generic Express transport primitives, request parsing, response serialization, origin guards and route-pack mounting.",
|
|
5
5
|
"license": "Apache-2.0",
|
|
6
6
|
"repository": {
|
|
@@ -71,16 +71,16 @@
|
|
|
71
71
|
"@types/express": "^4.17.21",
|
|
72
72
|
"@vitest/coverage-v8": "^2.1.9",
|
|
73
73
|
"express": "^4.21.0",
|
|
74
|
-
"@jini-ai/core": "0.
|
|
75
|
-
"@jini-ai/platform": "0.
|
|
76
|
-
"@jini-ai/protocol": "0.
|
|
74
|
+
"@jini-ai/core": "0.6.10",
|
|
75
|
+
"@jini-ai/platform": "0.6.10",
|
|
76
|
+
"@jini-ai/protocol": "0.6.10"
|
|
77
77
|
},
|
|
78
78
|
"dependencies": {
|
|
79
|
-
"@jini-ai/
|
|
80
|
-
"@jini-ai/
|
|
79
|
+
"@jini-ai/core": "^0.6.10",
|
|
80
|
+
"@jini-ai/protocol": "^0.6.10"
|
|
81
81
|
},
|
|
82
82
|
"peerDependencies": {
|
|
83
|
-
"@jini-ai/platform": "^0.
|
|
83
|
+
"@jini-ai/platform": "^0.6.10",
|
|
84
84
|
"express": "^4.21.0 || ^5.0.0"
|
|
85
85
|
},
|
|
86
86
|
"peerDependenciesMeta": {
|