@jini-ai/http-kit 0.4.0 → 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 +6 -0
- package/dist/adapter.d.ts +12 -5
- package/dist/adapter.js +32 -4
- package/dist/index.d.ts +9 -139
- package/dist/types.d.ts +38 -3
- package/dist/verified-origin/index.d.ts +1 -0
- package/dist/verified-origin/index.js +1 -0
- package/dist/verified-origin/site-path.d.ts +113 -0
- package/dist/verified-origin/site-path.js +179 -0
- package/package.json +23 -9
package/CHANGELOG.md
CHANGED
package/dist/adapter.d.ts
CHANGED
|
@@ -54,17 +54,24 @@ export declare class ClientFacingError extends Error {
|
|
|
54
54
|
* parameters at the definition site so callers do not have to repeat them. Optional settings take
|
|
55
55
|
* precedence. The returned spec is consumed by `mountJsonRoute` (live)
|
|
56
56
|
* and by tests (direct invocation of `route.parse` / `route.handle`).
|
|
57
|
+
* @param optionalArgs - Origin/success policy and optional injected host ports.
|
|
58
|
+
* @returns A fresh route spec; never mutates either argument.
|
|
59
|
+
* @complexity O(1) time/space for the fixed spec fields.
|
|
57
60
|
*/
|
|
58
|
-
export declare function defineJsonRoute<Input, Output, Deps>(requiredArgs: Omit<JsonRouteSpec<Input, Output, Deps>, 'requireSameOrigin' | 'successStatus'>, optionalArgs?: Pick<JsonRouteSpec<Input, Output, Deps>, 'requireSameOrigin' | 'successStatus'>): JsonRouteSpec<Input, Output, Deps>;
|
|
61
|
+
export declare function defineJsonRoute<Input, Output, Deps, Context = undefined>(requiredArgs: Omit<JsonRouteSpec<Input, Output, Deps, Context>, 'requireSameOrigin' | 'successStatus' | 'ports'>, optionalArgs?: Pick<JsonRouteSpec<Input, Output, Deps, Context>, 'requireSameOrigin' | 'successStatus' | 'ports'>): JsonRouteSpec<Input, Output, Deps, Context>;
|
|
59
62
|
/**
|
|
60
63
|
* Mounts one JsonRouteSpec on an Express app. The Adapter is the only code here that knows
|
|
61
64
|
* about req/res; the route's parse and handle functions operate on `RouteInputContext` and
|
|
62
|
-
* `Deps` respectively, so they are unit testable without Express.
|
|
65
|
+
* `Deps` respectively, so they are unit testable without Express. Optional host ports preserve
|
|
66
|
+
* workspace/auth/error policy without coupling this toolkit to a domain. An origin context is
|
|
67
|
+
* required only for routes that opt into the same-origin guard.
|
|
68
|
+
* @returns Void; registers one handler, without starting a listener.
|
|
69
|
+
* @complexity O(1) setup and per-request overhead, plus parsing, host ports and handling.
|
|
63
70
|
*/
|
|
64
|
-
export declare function mountJsonRoute<Input, Output, Deps>({ app, spec, deps, adapter }: {
|
|
71
|
+
export declare function mountJsonRoute<Input, Output, Deps, Context = undefined>({ app, spec, deps, adapter }: {
|
|
65
72
|
readonly app: Express;
|
|
66
|
-
readonly spec: JsonRouteSpec<Input, Output, Deps>;
|
|
73
|
+
readonly spec: JsonRouteSpec<Input, Output, Deps, Context>;
|
|
67
74
|
readonly deps: Deps;
|
|
68
|
-
readonly adapter
|
|
75
|
+
readonly adapter?: AdapterContext;
|
|
69
76
|
}, _optional?: Record<string, never>): void;
|
|
70
77
|
//# sourceMappingURL=adapter.d.ts.map
|
package/dist/adapter.js
CHANGED
|
@@ -46,6 +46,9 @@ export class ClientFacingError extends Error {
|
|
|
46
46
|
* parameters at the definition site so callers do not have to repeat them. Optional settings take
|
|
47
47
|
* precedence. The returned spec is consumed by `mountJsonRoute` (live)
|
|
48
48
|
* and by tests (direct invocation of `route.parse` / `route.handle`).
|
|
49
|
+
* @param optionalArgs - Origin/success policy and optional injected host ports.
|
|
50
|
+
* @returns A fresh route spec; never mutates either argument.
|
|
51
|
+
* @complexity O(1) time/space for the fixed spec fields.
|
|
49
52
|
*/
|
|
50
53
|
export function defineJsonRoute(requiredArgs, optionalArgs = {}) {
|
|
51
54
|
const spec = { ...requiredArgs, ...optionalArgs };
|
|
@@ -54,7 +57,11 @@ export function defineJsonRoute(requiredArgs, optionalArgs = {}) {
|
|
|
54
57
|
/**
|
|
55
58
|
* Mounts one JsonRouteSpec on an Express app. The Adapter is the only code here that knows
|
|
56
59
|
* about req/res; the route's parse and handle functions operate on `RouteInputContext` and
|
|
57
|
-
* `Deps` respectively, so they are unit testable without Express.
|
|
60
|
+
* `Deps` respectively, so they are unit testable without Express. Optional host ports preserve
|
|
61
|
+
* workspace/auth/error policy without coupling this toolkit to a domain. An origin context is
|
|
62
|
+
* required only for routes that opt into the same-origin guard.
|
|
63
|
+
* @returns Void; registers one handler, without starting a listener.
|
|
64
|
+
* @complexity O(1) setup and per-request overhead, plus parsing, host ports and handling.
|
|
58
65
|
*/
|
|
59
66
|
export function mountJsonRoute({ app, spec, deps, adapter }, _optional = {}) {
|
|
60
67
|
app[spec.method](spec.path, async (req, res) => {
|
|
@@ -76,19 +83,34 @@ export function mountJsonRoute({ app, spec, deps, adapter }, _optional = {}) {
|
|
|
76
83
|
// which is the correct behavior for a double that never fires `close` anyway.
|
|
77
84
|
res.on?.('close', onResponseClose);
|
|
78
85
|
try {
|
|
86
|
+
const raw = rawInput({ req });
|
|
87
|
+
if (spec.ports?.workspace)
|
|
88
|
+
await spec.ports.workspace({ raw, deps });
|
|
79
89
|
if (spec.requireSameOrigin) {
|
|
90
|
+
if (!adapter)
|
|
91
|
+
throw new Error('same-origin adapter context is required');
|
|
80
92
|
const origin = guardSameOrigin({ req, origin: adapter });
|
|
81
93
|
if (!origin.ok) {
|
|
82
94
|
sendApiError({ res, status: statusForError({ error: origin.error }), error: origin.error });
|
|
83
95
|
return;
|
|
84
96
|
}
|
|
85
97
|
}
|
|
86
|
-
|
|
98
|
+
let context;
|
|
99
|
+
if (spec.ports?.authenticate)
|
|
100
|
+
context = await spec.ports.authenticate({ raw, res, deps });
|
|
101
|
+
const parsed = spec.parse(raw);
|
|
87
102
|
if (!parsed.ok) {
|
|
88
103
|
sendApiError({ res, status: statusForError({ error: parsed.error }), error: parsed.error });
|
|
89
104
|
return;
|
|
90
105
|
}
|
|
91
|
-
|
|
106
|
+
// The route chooses where authorization occurs: reads may authorize before validation,
|
|
107
|
+
// while writes must reject an inconsistent tenant target before asking for a permission.
|
|
108
|
+
const authorize = async ({ permission, entityType }) => {
|
|
109
|
+
if (!spec.ports?.authorize)
|
|
110
|
+
throw new Error('JSON route authorizer is required');
|
|
111
|
+
await spec.ports.authorize({ context, deps, permission, entityType });
|
|
112
|
+
};
|
|
113
|
+
const result = await spec.handle({ input: parsed.value, deps, context, authorize }, { signal: abortController.signal });
|
|
92
114
|
// `abortController.signal` can only have been aborted by `onResponseClose` firing while the
|
|
93
115
|
// `await` above was pending — nothing here runs concurrently with it — so this unambiguously
|
|
94
116
|
// means the client was already gone before any response was sent. Writing one now would be
|
|
@@ -103,6 +125,12 @@ export function mountJsonRoute({ app, spec, deps, adapter }, _optional = {}) {
|
|
|
103
125
|
sendJson({ res, status: spec.successStatus ?? 200, body: result.value });
|
|
104
126
|
}
|
|
105
127
|
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
|
+
}
|
|
106
134
|
// A route (or something it called) already classified this failure as safe to disclose —
|
|
107
135
|
// see `ClientFacingError`'s own doc. Sent verbatim, at its own status; never routed to the
|
|
108
136
|
// SEC-005 sink below, because nothing unanticipated happened.
|
|
@@ -118,7 +146,7 @@ export function mountJsonRoute({ app, spec, deps, adapter }, _optional = {}) {
|
|
|
118
146
|
// caller could read it too, simply by getting a readiness dependency to fail. The real error
|
|
119
147
|
// still reaches the operator through the sink, correlated to what the caller was told.
|
|
120
148
|
const correlationId = randomUUID();
|
|
121
|
-
const sink = adapter
|
|
149
|
+
const sink = adapter?.onInternalError ?? defaultInternalErrorSink;
|
|
122
150
|
sink({ method: spec.method, path: spec.path, correlationId, error: e });
|
|
123
151
|
sendApiError({ res, status: 500, error: createApiError({ code: 'INTERNAL_ERROR', message: 'an internal error occurred' }, { requestId: correlationId }) });
|
|
124
152
|
}
|
package/dist/index.d.ts
CHANGED
|
@@ -1,145 +1,15 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* @module @jini-ai/http-kit
|
|
3
|
-
*
|
|
4
|
-
*
|
|
5
|
-
*
|
|
6
|
-
*
|
|
7
|
-
*
|
|
8
|
-
*
|
|
9
|
-
*
|
|
10
|
-
*
|
|
11
|
-
* the maintained-but-unused Fastify subtree cost a recurring "does this new route pack also need a
|
|
12
|
-
* Fastify mounting sibling" tax on every future addition to this package. The removed
|
|
13
|
-
* implementation is preserved, unchanged, on the `future/fastify-transport` branch — see
|
|
14
|
-
* `FASTIFY-TRANSPORT-PARKED.md` at the repo root of that branch for the full reasoning and how to
|
|
15
|
-
* revive it. See `archived provenance ledger` for this package's full provenance and scope-decision notes.
|
|
16
|
-
|
|
17
|
-
* Archived provenance rationale:
|
|
18
|
-
* ## Design decisions
|
|
19
|
-
*
|
|
20
|
-
* **1. `compat.ts` was ported despite having no current Jini call site.** OD's
|
|
21
|
-
* `compat/api-errors.ts` exists only because `server.ts`'s routes — written
|
|
22
|
-
* before `JsonRouteSpec` existed — call error helpers with a different argument
|
|
23
|
-
* shape than the rest of the module; Jini's `@jini/http` has no such legacy
|
|
24
|
-
* call sites of its own. It was kept anyway for two reasons: (a) the task brief
|
|
25
|
-
* explicitly named `api-errors.ts` in its file list, and (b) extraction-plan.md
|
|
26
|
-
* §4's OD-sync mechanism (hollow re-exports + patch canary) depends on Jini's
|
|
27
|
-
* port carrying the *same public surface* as the OD module it patch-routes
|
|
28
|
-
* against — dropping an exported symbol here would be exactly the kind of
|
|
29
|
-
* silent divergence that mechanism exists to catch. A future host application
|
|
30
|
-
* with its own legacy hand-mounted routes (mirroring OD's `server.ts`) is the
|
|
31
|
-
* plausible real consumer; until then it is inert, imported-but-unused code,
|
|
32
|
-
* which is an acceptable cost for sync fidelity in a package whose whole
|
|
33
|
-
* purpose is to be a faithful patch target.
|
|
34
|
-
*
|
|
35
|
-
* **2. `mountPackHttp` (route-pack registrar) is new, not a lift.** OD's
|
|
36
|
-
* `http/` module has no concept of "packs" — it predates `@jini/core`'s typed
|
|
37
|
-
* DI-token composition contract entirely; `server.ts` mounts every route by
|
|
38
|
-
* hand. Per extraction-plan.md §3's description of `@jini/http` as containing
|
|
39
|
-
* a "route-pack registrar," and per the task brief's explicit instruction to
|
|
40
|
-
* check `packages/core/src/pack.ts` and compose with it rather than inventing a
|
|
41
|
-
* separate pattern, `mountPackHttp(app, packs, daemon)` was built fresh: it
|
|
42
|
-
* iterates the same `packs` array passed to `createDaemon` and calls each
|
|
43
|
-
* pack's optional `Pack.http(app, services)` registrar (declared in
|
|
44
|
-
* `@jini/core`'s `pack.ts` with `app` deliberately typed `unknown` so the
|
|
45
|
-
* kernel never depends on Express) with the *same* Express `app` and the
|
|
46
|
-
* *same* composed `services` object `@jini/cli`'s eventual CLI registrar would
|
|
47
|
-
* receive via `Pack.cli` — satisfying extraction-plan.md §2.3's "both
|
|
48
|
-
* transports call one shared app-service" invariant. Packs with no `http`
|
|
49
|
-
* registrar are silently skipped (a CLI-only or headless pack is not an error).
|
|
50
|
-
*
|
|
51
|
-
* **3. `ExecutionDelegate` injection is explicitly out of scope, not
|
|
52
|
-
* overlooked.** Extraction-plan.md §3 describes `@jini/http` as also
|
|
53
|
-
* "injects `ExecutionDelegate`" (§2.5's tool-execution-boundary confirm/authorize
|
|
54
|
-
* callback pair, transport-specific by design). `ToolExecutor` now exists in
|
|
55
|
-
* `@jini/daemon`, but the external CLI stream currently reports a tool use after
|
|
56
|
-
* the CLI has executed it; it is not a pre-execution request/response protocol.
|
|
57
|
-
* This transport therefore does not pretend to inject a post-hoc callback as an
|
|
58
|
-
* authorization gate. A controlled agent protocol is a real, named follow-up.
|
|
59
|
-
*
|
|
60
|
-
* **4. `ERROR_STATUS_BY_CODE` was re-scoped to `@jini/protocol`'s codes, not
|
|
61
|
-
* copied 1:1.** See the `src/response.ts` file-map row above for the exact
|
|
62
|
-
* additions/removals. This keeps the status-mapping table honest about which
|
|
63
|
-
* codes are actually reachable through `@jini/protocol`'s `ApiErrorCode` type
|
|
64
|
-
* (an open string type — a pack's own codes still type-check and simply fall
|
|
65
|
-
* back to the conservative 500 default, same as OD's unmapped-code behavior).
|
|
66
|
-
*
|
|
67
|
-
* ### Design decision: deliberately duplicated, not a shared interface — with one exception
|
|
68
|
-
*
|
|
69
|
-
* `express/` and `fastify/`'s nine matching files (`adapter`, `api-security-middleware`, `compat`,
|
|
70
|
-
* `daemon-status`, `index`, `local-daemon-request`, `origin`, `request`, `response`,
|
|
71
|
-
* `route-registration-guard`) are **independent implementations of the same job, not two adapters
|
|
72
|
-
* behind one shared interface.** This was a deliberate choice, not an oversight: Express's
|
|
73
|
-
* middleware-chain model (`(req, res, next) => void`, `res.json(...)`, `app.use(...)`) and Fastify's
|
|
74
|
-
* hook/plugin model (`onRequest`/`onRoute` hooks, `reply.send(...)`, schema-validated route options)
|
|
75
|
-
* are different enough in shape that forcing them behind one abstraction would either leak one
|
|
76
|
-
* framework's idioms into the other's native surface, or flatten both down to a lowest-common-
|
|
77
|
-
* denominator API that fights each framework's own strengths (Fastify's schema-based validation and
|
|
78
|
-
* radix-tree routing, in particular, are not expressible through an Express-shaped adapter without
|
|
79
|
-
* losing most of their value). Each subtree is written the way an engineer fluent in that framework
|
|
80
|
-
* would write it, and each is independently tested to 100% coverage.
|
|
81
|
-
*
|
|
82
|
-
* **The one exception: `fastify/daemon-status.ts` reuses `express/daemon-status.ts`'s route-spec
|
|
83
|
-
* data directly** — `daemonStatusRoute`/`daemonShutdownRoute` are pure `defineJsonRoute`-shaped
|
|
84
|
-
* data plus framework-agnostic `parse`/`handle` functions (see that file's own doc). They never
|
|
85
|
-
* reference Express at runtime: `express/daemon-status.ts` only imports `type { Express }` for one
|
|
86
|
-
* parameter type, and TypeScript's `verbatimModuleSyntax` erases type-only imports from the compiled
|
|
87
|
-
* output entirely — verified there is zero runtime `express` dependency pulled into the `fastify/`
|
|
88
|
-
* subtree by this reuse. `fastify/daemon-status.ts`'s own job is only the Fastify-specific mounting
|
|
89
|
-
* wrapper (`registerDaemonStatusRoutes`, calling `./adapter.js`'s Fastify `mountJsonRoute`). This is
|
|
90
|
-
* the single case where sharing was correct instead of duplication: the route *data* (path, method,
|
|
91
|
-
* input parser, pure handler) has no framework opinion in it at all — only the *mounting glue* does,
|
|
92
|
-
* and that glue is what actually differs and stays independent per subtree.
|
|
93
|
-
*
|
|
94
|
-
* ### Merge note (2026-07-22, later the same day): four more audit-fix sections below merged in from a second, parallel cloud session
|
|
95
|
-
*
|
|
96
|
-
* The sections immediately below (`delegated-tools.ts` barrel export, `media.ts`, and the
|
|
97
|
-
* `runs.ts`/`terminals.ts` coverage pass) were written on a branch (`fix/audit-6-fixes-20260722`) that
|
|
98
|
-
* forked from `main` *before* the Fastify-transport-split merge above landed, so they were authored
|
|
99
|
-
* against the pre-split flat-file layout. They merged in cleanly with no logical conflict — the
|
|
100
|
-
* route-pack files they touch (`delegated-tools.ts`, `runs.ts`, `terminals.ts`) are exactly the ones
|
|
101
|
-
* this merge's "Corrected layout" section above kept flat at the package root, not moved into
|
|
102
|
-
* `express/`, so every path/import reference below is still accurate post-merge. `media.ts` (new in
|
|
103
|
-
* that branch) is likewise flat at the root and barrel-exported the same way. None of these four
|
|
104
|
-
* sections needed any correction for the Fastify split; see `server/archived provenance ledger`'s own merge note
|
|
105
|
-
* for the one piece that did (the six route packs `media.ts` joins are wired Express-only for now,
|
|
106
|
-
* deliberately, per this repo's owner's explicit instruction to table Fastify parity for the newly
|
|
107
|
-
* merged route packs — tracked as follow-up work, not silently dropped).
|
|
108
|
-
*
|
|
109
|
-
* ### Design decisions
|
|
110
|
-
*
|
|
111
|
-
* **`StoredAttachment` mirrors `@jini-ai/chat-core`'s `ChatAttachment` instead of importing it.** Same
|
|
112
|
-
* reasoning as `media.ts` declaring its own `MediaTask`/`MediaDispatchEngine` rather than depending on
|
|
113
|
-
* `@jini-ai/media`: a `jini.domain: "server"` transport package should not acquire a dependency on a
|
|
114
|
-
* *domain* package (`chat`) to describe an upload that is not chat-specific. There is no cycle — the edge
|
|
115
|
-
* would be legal — it is simply the wrong direction, and it would be the first `server` → `chat` package
|
|
116
|
-
* edge in the graph. The drift risk that makes a mirror tempting to avoid is paid for with a test instead
|
|
117
|
-
* of a dependency: `attachments.test.ts` holds a compile-time assignability assertion in **both**
|
|
118
|
-
* directions against the real `ChatAttachment` (`@jini-ai/chat-core` is a **devDependency** only, so
|
|
119
|
-
* nothing is added to the published dependency graph). A field added, removed, renamed, or retyped on
|
|
120
|
-
* either side fails the build.
|
|
121
|
-
*
|
|
122
|
-
* **Hand-mounted, not `defineJsonRoute`/`mountJsonRoute`.** Two hard reasons: the upload reads the raw
|
|
123
|
-
* request stream, so a JSON-parsed `req.body` is precisely what must *not* have happened; and the cleanup
|
|
124
|
-
* answers `204` with no body, which a JSON responder cannot express. `requireSameOrigin` is therefore a
|
|
125
|
-
* dep flag (defaulting to `true`) rather than a spec field, evaluated through the same `guardSameOrigin`.
|
|
126
|
-
*
|
|
127
|
-
* **Run-lifecycle wiring stays host-owned**, following `@jini-ai/daemon`'s `createRunScopedContextStore`
|
|
128
|
-
* precedent exactly: there is no generic post-run-start hook to auto-wire into, and inventing one for this
|
|
129
|
-
* would be a larger and worse change than documenting ten lines. The module doc carries the pattern
|
|
130
|
-
* (claim in `onRunStarted`, thread into `AgentExecutor.run()`'s pre-existing
|
|
131
|
-
* `imagePaths`/`extraAllowedDirs`/`uploadRoot`, `cleanupRun` in a `finally`). `daemon.ts` in the example is
|
|
132
|
-
* the live reference.
|
|
133
|
-
*
|
|
134
|
-
* **Typed rejections replaced substring matching.** The example's route decided status codes with
|
|
135
|
-
* `message.includes('20 MB') || message.includes('limited to') || ...` across a module boundary. Since one
|
|
136
|
-
* package now owns both the store and the routes, `AttachmentRejectedError.reason` maps to a status in one
|
|
137
|
-
* table. The externally-visible status mapping is unchanged (quota → 413, bad batch → 400, integrity →
|
|
138
|
-
* redacted 500); it is just no longer coupled to message wording. Reasons that describe a broken or
|
|
139
|
-
* hostile server-side state never expose their real message over HTTP, but exist so a host catching a
|
|
140
|
-
* rejection from `claim()` outside HTTP can still classify it.
|
|
3
|
+
* JSON-route transport: parsing/serialization, same-origin guards, Express mounting and pack
|
|
4
|
+
* registration. Capability-owned HTTP entries own domain route packs; core stays framework-free.
|
|
5
|
+
* pack-http.ts mounts the same composed app-services supplied to CLI, skipping packs without HTTP.
|
|
6
|
+
* Post-hoc external CLI tool events cannot serve as pre-execution authorization; a controlled
|
|
7
|
+
* agent protocol is required for that gate. Unknown API error codes default conservatively to 500.
|
|
8
|
+
* Hand-mounted legacy error helpers retain their public surface for patch-sync fidelity; response.ts
|
|
9
|
+
* owns sending. See the capability owners for raw-stream uploads, bodyless cleanup, attachment
|
|
10
|
+
* rejection mapping and host-owned claim/cleanup lifecycle rather than duplicating those rules here.
|
|
141
11
|
*/
|
|
142
|
-
export type { Handler, HttpMethod, InputParser, JsonRouteSpec, Result, RouteInputContext, } from './types.js';
|
|
12
|
+
export type { Handler, HttpMethod, InputParser, JsonRouteSpec, JsonRoutePorts, JsonRouteAuthorize, Result, RouteInputContext, } from './types.js';
|
|
143
13
|
export { err, ok } from './types.js';
|
|
144
14
|
export type { ParsedHostHeader, RequestWithOriginHeaders, } from '@jini-ai/core';
|
|
145
15
|
export { allowedBrowserPorts, assertValidAllowedOrigins, configuredAllowedHosts, configuredAllowedOrigins, isAllowedBrowserHost, isAllowedBrowserOrigin, isIpLiteralHostname, isLoopbackOrPrivateLanHost, isLocalSameOrigin, isPrivateIpv4, parseHostHeader, } from '@jini-ai/core';
|
package/dist/types.d.ts
CHANGED
|
@@ -5,6 +5,7 @@
|
|
|
5
5
|
*/
|
|
6
6
|
import type { Result as CoreResult } from '@jini-ai/core/primitives';
|
|
7
7
|
import type { ApiError } from '@jini-ai/protocol';
|
|
8
|
+
import type { Response } from 'express';
|
|
8
9
|
/**
|
|
9
10
|
* A discriminated success/failure envelope used throughout the module in place of throwing.
|
|
10
11
|
* Route parsing, handling, and origin checks all resolve to a `Result` so the Adapter can fold
|
|
@@ -37,24 +38,58 @@ export type InputParser<Input> = (raw: RouteInputContext) => Result<Input>;
|
|
|
37
38
|
* `signal` is optional and additive: it aborts if the underlying HTTP request's connection drops
|
|
38
39
|
* before the Adapter has written a response (see `mountJsonRoute` in `adapter.ts`) — handlers read it from their optional arguments when they perform cancellable work.
|
|
39
40
|
*/
|
|
40
|
-
export type Handler<Input, Output, Deps> = (requiredArgs: {
|
|
41
|
+
export type Handler<Input, Output, Deps, Context = undefined> = (requiredArgs: {
|
|
41
42
|
readonly input: Input;
|
|
42
43
|
readonly deps: Deps;
|
|
44
|
+
readonly context?: Context | undefined;
|
|
45
|
+
readonly authorize?: JsonRouteAuthorize;
|
|
43
46
|
}, optionalArgs?: {
|
|
44
47
|
readonly signal?: AbortSignal | undefined;
|
|
45
48
|
}) => Promise<Result<Output>> | Result<Output>;
|
|
46
49
|
/** HTTP verbs the Adapter can mount a `JsonRouteSpec` under. */
|
|
47
50
|
export type HttpMethod = 'get' | 'post' | 'put' | 'delete' | 'patch';
|
|
51
|
+
/** Explicit authorization remains at the route's chosen point, preserving validation precedence. */
|
|
52
|
+
export type JsonRouteAuthorize = (requiredArgs: {
|
|
53
|
+
readonly permission: string;
|
|
54
|
+
readonly entityType: string;
|
|
55
|
+
}, optionalArgs?: Record<string, never>) => Promise<void>;
|
|
56
|
+
/** Host-owned workspace, authentication/authorization and exception policy.
|
|
57
|
+
* Guards throw on rejection; the error port owns their wire envelope. Without an error port the
|
|
58
|
+
* adapter retains its caller-safe-error and SEC-005 redaction policy. Authentication can await
|
|
59
|
+
* host readiness; it runs after workspace rejection and before parsing or handling.
|
|
60
|
+
*/
|
|
61
|
+
export interface JsonRoutePorts<Deps, Context = undefined> {
|
|
62
|
+
readonly workspace?: (requiredArgs: {
|
|
63
|
+
readonly raw: RouteInputContext;
|
|
64
|
+
readonly deps: Deps;
|
|
65
|
+
}) => void | Promise<void>;
|
|
66
|
+
readonly authenticate?: (requiredArgs: {
|
|
67
|
+
readonly raw: RouteInputContext;
|
|
68
|
+
readonly res: Response;
|
|
69
|
+
readonly deps: Deps;
|
|
70
|
+
}) => Context | Promise<Context>;
|
|
71
|
+
readonly authorize?: (requiredArgs: {
|
|
72
|
+
readonly context: Context | undefined;
|
|
73
|
+
readonly deps: Deps;
|
|
74
|
+
readonly permission: string;
|
|
75
|
+
readonly entityType: string;
|
|
76
|
+
}) => void | Promise<void>;
|
|
77
|
+
readonly onError?: (requiredArgs: {
|
|
78
|
+
readonly res: Response;
|
|
79
|
+
readonly error: unknown;
|
|
80
|
+
}) => void;
|
|
81
|
+
}
|
|
48
82
|
/**
|
|
49
83
|
* Declarative description of one JSON route: how to parse input, how to handle it, and whether
|
|
50
84
|
* it requires a same-origin request. Consumed by `mountJsonRoute` in `adapter.ts`.
|
|
51
85
|
*/
|
|
52
|
-
export interface JsonRouteSpec<Input, Output, Deps> {
|
|
86
|
+
export interface JsonRouteSpec<Input, Output, Deps, Context = undefined> {
|
|
53
87
|
method: HttpMethod;
|
|
54
88
|
path: string;
|
|
55
89
|
requireSameOrigin?: boolean;
|
|
56
90
|
parse: InputParser<Input>;
|
|
57
|
-
handle: Handler<Input, Output, Deps>;
|
|
91
|
+
handle: Handler<Input, Output, Deps, Context>;
|
|
58
92
|
successStatus?: number;
|
|
93
|
+
ports?: JsonRoutePorts<Deps, Context>;
|
|
59
94
|
}
|
|
60
95
|
//# sourceMappingURL=types.d.ts.map
|
|
@@ -3,4 +3,5 @@ export type { VerifiedOriginRequestContext, RedirectTargetContext, EgressTargetC
|
|
|
3
3
|
export { OriginRegistry, hasForbiddenRawUrlCharacter, isSameOrigin, normalizeOriginCandidate, type NormalizedTarget, type OriginRegistryDeps, } from "./origin.js";
|
|
4
4
|
export { InMemoryOriginSettingRepo, type OriginSettingSeed } from "./repo.memory.js";
|
|
5
5
|
export { planOriginBoot, resolveConfiguredOrigin, type ConfiguredOriginRequired, type OriginBootRequired, type OriginBootPlan, } from "./configured-origin.js";
|
|
6
|
+
export { hasControlCharacter, checkSitePathname, checkSiteRelativeTarget, type SitePathCheck, type SiteRelativeTargetCheck, } from "./site-path.js";
|
|
6
7
|
//# sourceMappingURL=index.d.ts.map
|
|
@@ -2,4 +2,5 @@ export { InsecureOriginSourceError, OriginNotVerifiedError, createVerifiedOrigin
|
|
|
2
2
|
export { OriginRegistry, hasForbiddenRawUrlCharacter, isSameOrigin, normalizeOriginCandidate, } from "./origin.js";
|
|
3
3
|
export { InMemoryOriginSettingRepo } from "./repo.memory.js";
|
|
4
4
|
export { planOriginBoot, resolveConfiguredOrigin, } from "./configured-origin.js";
|
|
5
|
+
export { hasControlCharacter, checkSitePathname, checkSiteRelativeTarget, } from "./site-path.js";
|
|
5
6
|
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @file Shared site-path checks: decoded, dot-resolved segments and origin tracking.
|
|
3
|
+
*
|
|
4
|
+
* Why the rule is not `path.startsWith("/admin")`:
|
|
5
|
+
* - `/administer-survey` is ordinary site content and must keep working, so the comparison is per
|
|
6
|
+
* SEGMENT, not per prefix.
|
|
7
|
+
* - `/%61dmin` is compared AFTER one percent-decode, not on the raw bytes. Express (which routes on
|
|
8
|
+
* the raw path) and browsers (which do not decode `%61` in a path) do NOT treat it as `/admin`; a
|
|
9
|
+
* proxy or server that decodes before routing does. Refusing it is deliberate over-refusal — the
|
|
10
|
+
* safe direction for a rule whose job is to keep public redirects and fetches off the admin
|
|
11
|
+
* surface.
|
|
12
|
+
* - `/ADMIN` reaches the same Express mount (Express matches paths case-insensitively by default),
|
|
13
|
+
* so the comparison is case-folded.
|
|
14
|
+
* - `/blog/../admin` is `/admin` by the time a browser issues the request, so dot segments are
|
|
15
|
+
* resolved first.
|
|
16
|
+
*
|
|
17
|
+
*/
|
|
18
|
+
/** {@link checkSitePathname}'s verdict. Every arm is a refusal except `ok`. */
|
|
19
|
+
export type SitePathCheck = {
|
|
20
|
+
kind: "ok";
|
|
21
|
+
}
|
|
22
|
+
/** `decodeURIComponent` threw — a stray or truncated `%` sequence. */
|
|
23
|
+
| {
|
|
24
|
+
kind: "malformed-encoding";
|
|
25
|
+
}
|
|
26
|
+
/** Decodes to a backslash (a `/` to URL parsers) or a C0/C1 control character (CR/LF splitting). */
|
|
27
|
+
| {
|
|
28
|
+
kind: "disallowed-character";
|
|
29
|
+
} | {
|
|
30
|
+
kind: "reserved";
|
|
31
|
+
surface: string;
|
|
32
|
+
};
|
|
33
|
+
/** {@link checkSiteRelativeTarget}'s verdict — {@link SitePathCheck} plus the two structural arms
|
|
34
|
+
* that only apply when the input is still a raw, unparsed reference. */
|
|
35
|
+
export type SiteRelativeTargetCheck = SitePathCheck
|
|
36
|
+
/** `new URL()` could not parse it at all. */
|
|
37
|
+
| {
|
|
38
|
+
kind: "unparseable";
|
|
39
|
+
}
|
|
40
|
+
/** Parses, but resolves to a DIFFERENT host — e.g. `/\evil.example`, which starts with a single
|
|
41
|
+
* slash yet is `//evil.example` to a URL parser, so a `startsWith("//")` test never sees it. */
|
|
42
|
+
| {
|
|
43
|
+
kind: "off-origin";
|
|
44
|
+
};
|
|
45
|
+
/**
|
|
46
|
+
* Whether `value` contains a C0 or C1 control character.
|
|
47
|
+
*
|
|
48
|
+
* CR/LF in a request target is HTTP request splitting and in a `Location` header is response
|
|
49
|
+
* splitting; NUL and friends are path-truncation tricks.
|
|
50
|
+
*
|
|
51
|
+
* @param required.value - Any string, already decoded or not.
|
|
52
|
+
* @returns `true` if any code unit is in `U+0000`–`U+001F` or `U+007F`–`U+009F`.
|
|
53
|
+
* @complexity O(n) in the string length.
|
|
54
|
+
* @example hasControlCharacter({ value: "/ok" }, {}); // => false
|
|
55
|
+
*/
|
|
56
|
+
export declare function hasControlCharacter({ value }: {
|
|
57
|
+
value: string;
|
|
58
|
+
}, _optional?: Record<string, never>): boolean;
|
|
59
|
+
/**
|
|
60
|
+
* Classify an already-parsed URL's pathname against the admin application's URL space.
|
|
61
|
+
*
|
|
62
|
+
* Takes the {@link URL} itself, not a bare pathname string, so this cannot be handed a raw,
|
|
63
|
+
* unparsed reference by accident: a string has no way to prove it went through `new URL()` first,
|
|
64
|
+
* and this rule's whole design (see the module doc) depends on comparing the DECODED, dot-resolved
|
|
65
|
+
* form a URL parser would actually produce. A caller that only has a raw string — a stored redirect
|
|
66
|
+
* target, anything from user input — must go through {@link checkSiteRelativeTarget} instead, which
|
|
67
|
+
* parses it (and rejects what doesn't parse) before this check ever runs.
|
|
68
|
+
*
|
|
69
|
+
* PRECONDITION: the caller has already established that `url` is on the site's own origin. This
|
|
70
|
+
* function reads only `pathname`, so `new URL("//admin", base)` (host `admin`, pathname `/`)
|
|
71
|
+
* returns `ok`. It deliberately does not compare origins itself: `platform/routing` cannot use
|
|
72
|
+
* `features/origin`'s normalizer, and a string `URL.origin` comparison is wrong for redirect
|
|
73
|
+
* candidates (`https://site./admin`). Callers: `checkSiteRelativeTarget` (probe-origin check),
|
|
74
|
+
* `site-inspection`'s `resolveWithinOrigin`, and `features/redirects/reserved-destination.ts` (the
|
|
75
|
+
* origin oracle's `isSameOrigin`).
|
|
76
|
+
*
|
|
77
|
+
* @param required.url - An already-parsed `URL`; only `url.pathname` is read.
|
|
78
|
+
* @param required.reservedSegments - First segments reserved by the host, stored case-folded.
|
|
79
|
+
* @returns `{ kind: "ok" }` when it is ordinary site content; otherwise the arm naming the refusal.
|
|
80
|
+
* @complexity O(n) in the pathname length.
|
|
81
|
+
* @example checkSitePathname({ url: new URL("/administer-survey", "http://x.invalid"), reservedSegments: new Set(["admin", "api"]) }, {}); // => { kind: "ok" }
|
|
82
|
+
* @example checkSitePathname({ url: new URL("/%61dmin/settings", "http://x.invalid"), reservedSegments: new Set(["admin", "api"]) }, {}); // => { kind: "reserved", surface: "admin" }
|
|
83
|
+
*/
|
|
84
|
+
export declare function checkSitePathname({ url, reservedSegments }: {
|
|
85
|
+
url: URL;
|
|
86
|
+
reservedSegments: ReadonlySet<string>;
|
|
87
|
+
}, _optional?: Record<string, never>): SitePathCheck;
|
|
88
|
+
/**
|
|
89
|
+
* Classify a raw, site-relative reference (a stored redirect target, a caller-supplied path)
|
|
90
|
+
* against the admin application's URL space, including the structural check that it is site-
|
|
91
|
+
* relative at all.
|
|
92
|
+
*
|
|
93
|
+
* The structural pass runs FIRST and matters on its own: `/\evil.example` begins with exactly one
|
|
94
|
+
* slash, so a `startsWith("//")` or scheme test calls it site-relative, while `new URL()` — and
|
|
95
|
+
* every browser following a `Location` — reads the backslash as a separator and lands on
|
|
96
|
+
* `evil.example`. Resolving against a probe origin and asserting the origin TRACKED that base is a
|
|
97
|
+
* structural answer to that instead of a pattern someone has to keep correct — done against two
|
|
98
|
+
* different bases so the probe origin itself is not a nameable way to pass (see
|
|
99
|
+
* {@link PROBE_ORIGIN}).
|
|
100
|
+
*
|
|
101
|
+
* @param required.raw - The untrusted reference, expected to be site-relative.
|
|
102
|
+
* @param required.reservedSegments - First segments reserved by the host, stored case-folded.
|
|
103
|
+
* @returns `{ kind: "ok" }` when it stays on this site and names ordinary content; otherwise the
|
|
104
|
+
* arm naming the refusal.
|
|
105
|
+
* @complexity O(n) in the reference length.
|
|
106
|
+
* @example checkSiteRelativeTarget({ raw: "/new", reservedSegments: new Set(["admin", "api"]) }, {}); // => { kind: "ok" }
|
|
107
|
+
* @example checkSiteRelativeTarget({ raw: "/\\evil.example", reservedSegments: new Set(["admin", "api"]) }, {}); // => { kind: "off-origin" }
|
|
108
|
+
*/
|
|
109
|
+
export declare function checkSiteRelativeTarget({ raw, reservedSegments }: {
|
|
110
|
+
raw: string;
|
|
111
|
+
reservedSegments: ReadonlySet<string>;
|
|
112
|
+
}, _optional?: Record<string, never>): SiteRelativeTargetCheck;
|
|
113
|
+
//# sourceMappingURL=site-path.d.ts.map
|
|
@@ -0,0 +1,179 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @file Shared site-path checks: decoded, dot-resolved segments and origin tracking.
|
|
3
|
+
*
|
|
4
|
+
* Why the rule is not `path.startsWith("/admin")`:
|
|
5
|
+
* - `/administer-survey` is ordinary site content and must keep working, so the comparison is per
|
|
6
|
+
* SEGMENT, not per prefix.
|
|
7
|
+
* - `/%61dmin` is compared AFTER one percent-decode, not on the raw bytes. Express (which routes on
|
|
8
|
+
* the raw path) and browsers (which do not decode `%61` in a path) do NOT treat it as `/admin`; a
|
|
9
|
+
* proxy or server that decodes before routing does. Refusing it is deliberate over-refusal — the
|
|
10
|
+
* safe direction for a rule whose job is to keep public redirects and fetches off the admin
|
|
11
|
+
* surface.
|
|
12
|
+
* - `/ADMIN` reaches the same Express mount (Express matches paths case-insensitively by default),
|
|
13
|
+
* so the comparison is case-folded.
|
|
14
|
+
* - `/blog/../admin` is `/admin` by the time a browser issues the request, so dot segments are
|
|
15
|
+
* resolved first.
|
|
16
|
+
*
|
|
17
|
+
*/
|
|
18
|
+
/**
|
|
19
|
+
* Two hosts this deployment can never actually reach, used only so `new URL()` has a base to
|
|
20
|
+
* resolve a site-relative reference against. `.invalid` is reserved by RFC 2606 precisely for this.
|
|
21
|
+
*
|
|
22
|
+
* There are TWO because one base is NAMEABLE (t85 independent review, 2026-09-16). With a single
|
|
23
|
+
* base, `//reserved-path-probe.invalid/x` resolves to that very origin, so "did the origin survive"
|
|
24
|
+
* answered yes for a reference that leaves the site — reachable as `/store/buy`'s `returnTo`, which
|
|
25
|
+
* sent `Location: //reserved-path-probe.invalid/x`. Requiring the resolved origin to TRACK whichever
|
|
26
|
+
* base it was given leaves no origin an input can name, which is a structural answer rather than a
|
|
27
|
+
* denylist of the sentinel's spellings (the same reasoning as the probe itself — see
|
|
28
|
+
* {@link checkSiteRelativeTarget}). Both are bare origins, so a reference resolves to the same
|
|
29
|
+
* pathname against either.
|
|
30
|
+
*/
|
|
31
|
+
const PROBE_ORIGIN = "http://reserved-path-probe.invalid";
|
|
32
|
+
const SECOND_PROBE_ORIGIN = "http://reserved-path-probe-2.invalid";
|
|
33
|
+
/**
|
|
34
|
+
* Whether `value` contains a C0 or C1 control character.
|
|
35
|
+
*
|
|
36
|
+
* CR/LF in a request target is HTTP request splitting and in a `Location` header is response
|
|
37
|
+
* splitting; NUL and friends are path-truncation tricks.
|
|
38
|
+
*
|
|
39
|
+
* @param required.value - Any string, already decoded or not.
|
|
40
|
+
* @returns `true` if any code unit is in `U+0000`–`U+001F` or `U+007F`–`U+009F`.
|
|
41
|
+
* @complexity O(n) in the string length.
|
|
42
|
+
* @example hasControlCharacter({ value: "/ok" }, {}); // => false
|
|
43
|
+
*/
|
|
44
|
+
export function hasControlCharacter({ value }, _optional = {}) {
|
|
45
|
+
for (let index = 0; index < value.length; index += 1) {
|
|
46
|
+
const code = value.charCodeAt(index);
|
|
47
|
+
if (code <= 0x1f || (code >= 0x7f && code <= 0x9f))
|
|
48
|
+
return true;
|
|
49
|
+
}
|
|
50
|
+
return false;
|
|
51
|
+
}
|
|
52
|
+
/**
|
|
53
|
+
* Resolve `.` and `..` segments, RFC 3986 §5.2.4 style, on an already-decoded path.
|
|
54
|
+
*
|
|
55
|
+
* Done by hand rather than with a second `new URL()` pass because a decoded path can contain a
|
|
56
|
+
* literal `?` or `#` (from `%3F`/`%23`), and the URL parser would treat those as a query/fragment
|
|
57
|
+
* delimiter and TRUNCATE the path — turning `/x#/../admin` into `/x` and losing the very segment
|
|
58
|
+
* this check exists to find. A browser does no such thing: it never decodes `%23` before splitting
|
|
59
|
+
* the path, so the truncation would be a false negative, not a match for real behavior.
|
|
60
|
+
*
|
|
61
|
+
* Empty segments are dropped, so `//admin` collapses to `/admin`. That is deliberately stricter
|
|
62
|
+
* than a URL parser (which preserves `//`); over-matching here only ever refuses more.
|
|
63
|
+
*
|
|
64
|
+
* @param path - A decoded path, expected to start with `/`.
|
|
65
|
+
* @returns The path with dot segments removed, always starting with `/`.
|
|
66
|
+
* @complexity O(n) in the path length.
|
|
67
|
+
* @example resolveDotSegments("/blog/../admin"); // => "/admin"
|
|
68
|
+
*/
|
|
69
|
+
function resolveDotSegments(path) {
|
|
70
|
+
const out = [];
|
|
71
|
+
for (const segment of path.split("/")) {
|
|
72
|
+
if (segment === "" || segment === ".")
|
|
73
|
+
continue;
|
|
74
|
+
if (segment === "..") {
|
|
75
|
+
out.pop();
|
|
76
|
+
continue;
|
|
77
|
+
}
|
|
78
|
+
out.push(segment);
|
|
79
|
+
}
|
|
80
|
+
return `/${out.join("/")}`;
|
|
81
|
+
}
|
|
82
|
+
/**
|
|
83
|
+
* The actual per-segment rule, on a pathname string that is guaranteed to have come from a real
|
|
84
|
+
* `URL` (see {@link checkSitePathname}, this function's only caller). Kept private: a bare
|
|
85
|
+
* string carries no proof it was ever parsed — the query/fragment stripping, dot-segment removal
|
|
86
|
+
* relative to a real origin, etc. are exactly what `new URL()` already did before that caller
|
|
87
|
+
* reaches this. Do not export this directly.
|
|
88
|
+
*
|
|
89
|
+
* Order is load-bearing: decode ONCE, then resolve dot segments, then compare the first segment
|
|
90
|
+
* case-folded. Decoding first is what catches `/%61dmin` (over-refusal for Express and browsers, a
|
|
91
|
+
* real match for a decoding proxy — see the module doc); resolving dot segments after the decode is
|
|
92
|
+
* what catches `/blog/%2e%2e/admin`. Exactly one decode pass models one decoding intermediary:
|
|
93
|
+
* `/%2561dmin` would need two, so it stays allowed.
|
|
94
|
+
*
|
|
95
|
+
* @param pathname - An already-parsed `URL`'s `.pathname` (no query, no fragment).
|
|
96
|
+
* @returns `{ kind: "ok" }` when it is ordinary site content; otherwise the arm naming the refusal.
|
|
97
|
+
* @complexity O(n) in the pathname length.
|
|
98
|
+
*/
|
|
99
|
+
function checkDecodedSitePathname(pathname, reservedSegments) {
|
|
100
|
+
let decoded;
|
|
101
|
+
try {
|
|
102
|
+
decoded = decodeURIComponent(pathname);
|
|
103
|
+
}
|
|
104
|
+
catch {
|
|
105
|
+
return { kind: "malformed-encoding" };
|
|
106
|
+
}
|
|
107
|
+
if (decoded.includes("\\") || hasControlCharacter({ value: decoded }, {}))
|
|
108
|
+
return { kind: "disallowed-character" };
|
|
109
|
+
const first = (resolveDotSegments(decoded).split("/")[1] ?? "").toLowerCase();
|
|
110
|
+
if (reservedSegments.has(first))
|
|
111
|
+
return { kind: "reserved", surface: first };
|
|
112
|
+
return { kind: "ok" };
|
|
113
|
+
}
|
|
114
|
+
/**
|
|
115
|
+
* Classify an already-parsed URL's pathname against the admin application's URL space.
|
|
116
|
+
*
|
|
117
|
+
* Takes the {@link URL} itself, not a bare pathname string, so this cannot be handed a raw,
|
|
118
|
+
* unparsed reference by accident: a string has no way to prove it went through `new URL()` first,
|
|
119
|
+
* and this rule's whole design (see the module doc) depends on comparing the DECODED, dot-resolved
|
|
120
|
+
* form a URL parser would actually produce. A caller that only has a raw string — a stored redirect
|
|
121
|
+
* target, anything from user input — must go through {@link checkSiteRelativeTarget} instead, which
|
|
122
|
+
* parses it (and rejects what doesn't parse) before this check ever runs.
|
|
123
|
+
*
|
|
124
|
+
* PRECONDITION: the caller has already established that `url` is on the site's own origin. This
|
|
125
|
+
* function reads only `pathname`, so `new URL("//admin", base)` (host `admin`, pathname `/`)
|
|
126
|
+
* returns `ok`. It deliberately does not compare origins itself: `platform/routing` cannot use
|
|
127
|
+
* `features/origin`'s normalizer, and a string `URL.origin` comparison is wrong for redirect
|
|
128
|
+
* candidates (`https://site./admin`). Callers: `checkSiteRelativeTarget` (probe-origin check),
|
|
129
|
+
* `site-inspection`'s `resolveWithinOrigin`, and `features/redirects/reserved-destination.ts` (the
|
|
130
|
+
* origin oracle's `isSameOrigin`).
|
|
131
|
+
*
|
|
132
|
+
* @param required.url - An already-parsed `URL`; only `url.pathname` is read.
|
|
133
|
+
* @param required.reservedSegments - First segments reserved by the host, stored case-folded.
|
|
134
|
+
* @returns `{ kind: "ok" }` when it is ordinary site content; otherwise the arm naming the refusal.
|
|
135
|
+
* @complexity O(n) in the pathname length.
|
|
136
|
+
* @example checkSitePathname({ url: new URL("/administer-survey", "http://x.invalid"), reservedSegments: new Set(["admin", "api"]) }, {}); // => { kind: "ok" }
|
|
137
|
+
* @example checkSitePathname({ url: new URL("/%61dmin/settings", "http://x.invalid"), reservedSegments: new Set(["admin", "api"]) }, {}); // => { kind: "reserved", surface: "admin" }
|
|
138
|
+
*/
|
|
139
|
+
export function checkSitePathname({ url, reservedSegments }, _optional = {}) {
|
|
140
|
+
return checkDecodedSitePathname(url.pathname, reservedSegments);
|
|
141
|
+
}
|
|
142
|
+
/**
|
|
143
|
+
* Classify a raw, site-relative reference (a stored redirect target, a caller-supplied path)
|
|
144
|
+
* against the admin application's URL space, including the structural check that it is site-
|
|
145
|
+
* relative at all.
|
|
146
|
+
*
|
|
147
|
+
* The structural pass runs FIRST and matters on its own: `/\evil.example` begins with exactly one
|
|
148
|
+
* slash, so a `startsWith("//")` or scheme test calls it site-relative, while `new URL()` — and
|
|
149
|
+
* every browser following a `Location` — reads the backslash as a separator and lands on
|
|
150
|
+
* `evil.example`. Resolving against a probe origin and asserting the origin TRACKED that base is a
|
|
151
|
+
* structural answer to that instead of a pattern someone has to keep correct — done against two
|
|
152
|
+
* different bases so the probe origin itself is not a nameable way to pass (see
|
|
153
|
+
* {@link PROBE_ORIGIN}).
|
|
154
|
+
*
|
|
155
|
+
* @param required.raw - The untrusted reference, expected to be site-relative.
|
|
156
|
+
* @param required.reservedSegments - First segments reserved by the host, stored case-folded.
|
|
157
|
+
* @returns `{ kind: "ok" }` when it stays on this site and names ordinary content; otherwise the
|
|
158
|
+
* arm naming the refusal.
|
|
159
|
+
* @complexity O(n) in the reference length.
|
|
160
|
+
* @example checkSiteRelativeTarget({ raw: "/new", reservedSegments: new Set(["admin", "api"]) }, {}); // => { kind: "ok" }
|
|
161
|
+
* @example checkSiteRelativeTarget({ raw: "/\\evil.example", reservedSegments: new Set(["admin", "api"]) }, {}); // => { kind: "off-origin" }
|
|
162
|
+
*/
|
|
163
|
+
export function checkSiteRelativeTarget({ raw, reservedSegments }, _optional = {}) {
|
|
164
|
+
if (hasControlCharacter({ value: raw }, {}))
|
|
165
|
+
return { kind: "disallowed-character" };
|
|
166
|
+
let parsed;
|
|
167
|
+
let reparsed;
|
|
168
|
+
try {
|
|
169
|
+
parsed = new URL(raw, PROBE_ORIGIN);
|
|
170
|
+
reparsed = new URL(raw, SECOND_PROBE_ORIGIN);
|
|
171
|
+
}
|
|
172
|
+
catch {
|
|
173
|
+
return { kind: "unparseable" };
|
|
174
|
+
}
|
|
175
|
+
if (parsed.origin !== PROBE_ORIGIN || reparsed.origin !== SECOND_PROBE_ORIGIN)
|
|
176
|
+
return { kind: "off-origin" };
|
|
177
|
+
return checkSitePathname({ url: parsed, reservedSegments }, {});
|
|
178
|
+
}
|
|
179
|
+
//# sourceMappingURL=site-path.js.map
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@jini-ai/http-kit",
|
|
3
|
-
"version": "0.4.
|
|
3
|
+
"version": "0.4.1",
|
|
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": {
|
|
@@ -15,7 +15,7 @@
|
|
|
15
15
|
".": "node",
|
|
16
16
|
"./rate-limit": "node",
|
|
17
17
|
"./middleware": "node",
|
|
18
|
-
"./verified-origin": "
|
|
18
|
+
"./verified-origin": "universal",
|
|
19
19
|
"./observability": "node"
|
|
20
20
|
},
|
|
21
21
|
"runtime": "node"
|
|
@@ -67,15 +67,29 @@
|
|
|
67
67
|
"access": "public",
|
|
68
68
|
"registry": "https://registry.npmjs.org"
|
|
69
69
|
},
|
|
70
|
-
"dependencies": {
|
|
71
|
-
"express": "^4.21.0",
|
|
72
|
-
"@jini-ai/core": "0.4.0",
|
|
73
|
-
"@jini-ai/protocol": "0.4.0",
|
|
74
|
-
"@jini-ai/platform": "0.5.0"
|
|
75
|
-
},
|
|
76
70
|
"devDependencies": {
|
|
77
71
|
"@types/express": "^4.17.21",
|
|
78
|
-
"@vitest/coverage-v8": "^2.1.9"
|
|
72
|
+
"@vitest/coverage-v8": "^2.1.9",
|
|
73
|
+
"express": "^4.21.0",
|
|
74
|
+
"@jini-ai/core": "0.4.2",
|
|
75
|
+
"@jini-ai/protocol": "0.4.2",
|
|
76
|
+
"@jini-ai/platform": "0.5.2"
|
|
77
|
+
},
|
|
78
|
+
"dependencies": {
|
|
79
|
+
"@jini-ai/core": "^0.4.2",
|
|
80
|
+
"@jini-ai/protocol": "^0.4.2"
|
|
81
|
+
},
|
|
82
|
+
"peerDependencies": {
|
|
83
|
+
"@jini-ai/platform": "^0.5.1",
|
|
84
|
+
"express": "^4.21.0"
|
|
85
|
+
},
|
|
86
|
+
"peerDependenciesMeta": {
|
|
87
|
+
"@jini-ai/platform": {
|
|
88
|
+
"optional": true
|
|
89
|
+
},
|
|
90
|
+
"express": {
|
|
91
|
+
"optional": true
|
|
92
|
+
}
|
|
79
93
|
},
|
|
80
94
|
"scripts": {
|
|
81
95
|
"build": "tsc -p tsconfig.json",
|