@jini-ai/http-kit 0.4.2 → 0.4.3

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 CHANGED
@@ -1,5 +1,9 @@
1
1
  # @jini-ai/http-kit
2
2
 
3
+ ## 0.4.3 — 2026-10-22
4
+
5
+ - 2026-10-22: Completed-request logging off by default (one compact line when enabled), coverage.
6
+
3
7
  ## 0.4.2 — 2026-10-14
4
8
 
5
9
  - 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
- const spec = { ...requiredArgs, ...optionalArgs };
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.requireSameOrigin) {
90
- if (!adapter)
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
- // `abortController.signal` can only have been aborted by `onResponseClose` firing while the
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
- // An explicit host error port owns exception classification and serialization, including
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 (parsed.protocol !== 'http:' && parsed.protocol !== 'https:')
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
- if (originHeader !== undefined && !localOriginFromHeader({ value: originHeader })) {
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: localOriginFromHeader({ value: originHeader }) };
117
+ return { ok: true, origin };
112
118
  }
113
119
  /**
114
120
  * Express middleware that rejects any non-loopback request with a 403, and
@@ -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: {
@@ -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
- const first = (resolveDotSegments(decoded).split("/")[1] ?? "").toLowerCase();
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.4.2",
3
+ "version": "0.4.3",
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,13 +71,13 @@
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.4.6",
75
- "@jini-ai/platform": "0.5.7",
76
- "@jini-ai/protocol": "0.4.4"
74
+ "@jini-ai/core": "0.4.9",
75
+ "@jini-ai/platform": "0.5.10",
76
+ "@jini-ai/protocol": "0.4.5"
77
77
  },
78
78
  "dependencies": {
79
- "@jini-ai/protocol": "^0.4.4",
80
- "@jini-ai/core": "^0.4.6"
79
+ "@jini-ai/protocol": "^0.4.5",
80
+ "@jini-ai/core": "^0.4.9"
81
81
  },
82
82
  "peerDependencies": {
83
83
  "@jini-ai/platform": "^0.5.1",