Initial Commit
This commit is contained in:
@@ -0,0 +1,56 @@
|
||||
# `@suaveplan/api-router-worker-bridge` — request/response marshalling across the worker boundary
|
||||
|
||||
**Package**: `@suaveplan/api-router-worker-bridge`
|
||||
**Status**: PROPOSED
|
||||
**Type**: new-package
|
||||
**Stage**: 3 (Worker isolation infrastructure)
|
||||
|
||||
## Why
|
||||
|
||||
Per design doc §6: when a plugin runs in `isolated` or `sandboxed` tier, the per-request pipeline executes steps 1–7 in the main process (intake, route match, auth, tenant, rate-limit, RBAC, validation, capability scoping), then marshals the result across `MessagePort` to the worker for step 8 (the user-code handler). Critically: the raw `Request` object is NEVER marshalled. Only the already-validated `body` / `params` / `query` cross the boundary. This is what lets worker-tier plugins gain isolation without losing any of the host-enforced security guarantees.
|
||||
|
||||
`api-router-worker-bridge` is the pair of half-bridges (main-side + worker-side) that implement that envelope. It sits between the main-process router (`api-router-hono` in Stage 4) and the worker-side request dispatcher (in `api-worker-host`).
|
||||
|
||||
## What changes
|
||||
|
||||
Net-new package. Two halves:
|
||||
|
||||
**ADDED exports:**
|
||||
|
||||
- `./main-side` — `BridgeMain`: accepts a route hit from `api-host`'s pipeline; constructs an `HttpDispatchEnvelope` (validated body, params, query, principal, tenantId, requestId, trace context); sends across the worker port via `api-worker-rpc`; awaits the response envelope; rehydrates the response into a `Response` object for the main-side response-validation + compose steps.
|
||||
- `./worker-side` — `BridgeWorker`: receives `HttpDispatchEnvelope` on the worker port; reconstructs a `RequestContext` (capability proxies already wired by `api-worker-host`); invokes the route handler; serialises the return value as an `HttpResponseEnvelope`; supports streaming via `Transferable` `ReadableStream`.
|
||||
- `./envelope-schemas` — Zod schemas for `HttpDispatchEnvelope` and `HttpResponseEnvelope`. Validated on both sides.
|
||||
- `./streaming-marshal` — request-body streams AND response-body streams via `Transferable`; back-pressure propagated.
|
||||
- `./header-allowlist` — only headers in the bridge's allowlist (or matching the configurable per-route allowlist) cross the boundary; the rest are dropped on the main side so worker code cannot read `Authorization` / `Cookie` etc.
|
||||
- `./error-codes` — `BRIDGE_*` codes (`BRIDGE_ENVELOPE_INVALID`, `BRIDGE_HANDLER_THROW`, `BRIDGE_HEADER_NOT_ALLOWED`, `BRIDGE_RESPONSE_NOT_SERIALISABLE`, `BRIDGE_REQUEST_BODY_STREAM_CLOSED`).
|
||||
|
||||
## Out of scope
|
||||
|
||||
- **Marshalling the raw `Request`** — explicitly forbidden by §6. The bridge marshals only the validated parts.
|
||||
- **Routing itself** — `api-router` / `api-router-hono` own URL matching. This package picks up after step 2.
|
||||
- **Capability proxies** — `api-db-worker-proxy` etc. live in their own packages. This package only marshals the request envelope.
|
||||
- **Auth / RBAC** — those run in the main process before the bridge. The bridge merely receives the resolved `principal` and `tenantId`.
|
||||
|
||||
## Source mapping
|
||||
|
||||
Genesis-original. Design doc sections: §6 (per-request data flow, especially the "isolated / sandboxed" paragraph), §5.2a.
|
||||
|
||||
| Requirement | Design doc section |
|
||||
|---|---|
|
||||
| Raw `Request` NEVER marshalled — only validated body/params/query | §6 |
|
||||
| Steps 1–7 + 9–11 always main-process | §6 |
|
||||
| Streams transferred via `Transferable` | §6, §5.2a |
|
||||
| Auth / RBAC / tenant resolution never run inside worker | §6 |
|
||||
|
||||
## Verification approach
|
||||
|
||||
- `src/main-side/main-side.test.ts` — given a fake `RouteMatch` + validated body, envelope is sent across paired `MessageChannel`; response rehydrates.
|
||||
- `src/worker-side/worker-side.test.ts` — given an envelope, handler is invoked with reconstructed `ctx.request`; response envelope serialises.
|
||||
- `src/envelope-schemas/envelope-schemas.test.ts` — Zod schemas reject malformed envelopes; valid envelopes round-trip.
|
||||
- `src/streaming-marshal/streaming-marshal.test.ts` — large request body stream + large response body stream both transfer; back-pressure ack works.
|
||||
- `src/header-allowlist/header-allowlist.spec-conformance.test.ts` — `Authorization`, `Cookie`, `Set-Cookie` MUST NOT cross by default; configurable allowlist works.
|
||||
- `tests/no-raw-request.test.ts` — pin the invariant: the wire envelope never contains a `Request` object reference; the raw header bag is filtered.
|
||||
|
||||
## Migration impact
|
||||
|
||||
None — additive only. `api-host` will wire this in Stage 4 once `api-router-hono` lands.
|
||||
@@ -0,0 +1,106 @@
|
||||
<!-- markdownlint-disable MD024 -->
|
||||
|
||||
# Capability Spec Delta: api-router-worker-bridge (api-router-worker-bridge)
|
||||
|
||||
**Package**: `@suaveplan/api-router-worker-bridge`
|
||||
**Status**: PROPOSED
|
||||
|
||||
> Every requirement below carries a `**Verified by:**` line at authoring time.
|
||||
|
||||
## ADDED Requirements
|
||||
|
||||
### Requirement: Raw Request object never crosses the worker boundary
|
||||
|
||||
The package SHALL marshal only the already-validated `body`, `params`, `query`, plus a filtered `headers` map, the resolved `principal`, `tenantId`, `requestId`, and W3C trace context across the worker port. The raw `Request` object MUST NOT appear in the wire envelope under any circumstance. Worker-side reconstruction SHALL produce a `ctx.request` shape that exposes ONLY these fields — there is no way for worker code to read the original socket, the original `Headers` instance, or any unfiltered header.
|
||||
|
||||
#### Scenario: envelope wire shape contains no Request reference
|
||||
|
||||
- **WHEN** an `HttpDispatchEnvelope` is serialised
|
||||
- **THEN** the structured-clone payload contains no `Request` instance AND `JSON.stringify` of the envelope succeeds (proving plain-data shape)
|
||||
|
||||
#### Scenario: worker ctx.request lacks underlying Request access
|
||||
|
||||
- **WHEN** a handler running under the bridge inspects `ctx.request`
|
||||
- **THEN** the available keys are exactly `["body", "params", "query", "headers", "method", "url"]` AND no `Request` prototype is reachable
|
||||
|
||||
**Verified by:** `tests/no-raw-request.test.ts::"envelope contains no Request reference"` AND `src/worker-side/worker-side.test.ts::"ctx.request exposes only marshalled fields"`
|
||||
|
||||
---
|
||||
|
||||
### Requirement: Default header allowlist denies credentials-bearing headers
|
||||
|
||||
The package SHALL apply a default deny list to outgoing envelopes that includes `authorization`, `cookie`, `set-cookie`, `x-csrf-token`, and `proxy-authorization`. Headers on the deny list MUST NOT appear in `envelope.headers` regardless of route configuration. Routes MAY EXTEND the allowlist via configuration to include arbitrary headers but MUST NOT REMOVE any default-denied header from the deny list.
|
||||
|
||||
#### Scenario: Authorization is stripped from envelope by default
|
||||
|
||||
- **WHEN** a route hit carries `Authorization: Bearer abc`
|
||||
- **THEN** the resulting envelope's `headers` map has no `authorization` key
|
||||
|
||||
#### Scenario: Cookie cannot be allowlisted via config
|
||||
|
||||
- **WHEN** a route attempts to allowlist `cookie`
|
||||
- **THEN** the bridge throws `BRIDGE_HEADER_NOT_ALLOWED` at configuration time
|
||||
|
||||
**Verified by:** `src/header-allowlist/header-allowlist.spec-conformance.test.ts::"Authorization stripped by default"` AND `src/header-allowlist/header-allowlist.spec-conformance.test.ts::"cookie cannot be allowlisted"`
|
||||
|
||||
---
|
||||
|
||||
### Requirement: Envelope schemas are Zod-validated on both sides
|
||||
|
||||
The package SHALL define Zod schemas for `HttpDispatchEnvelope` and `HttpResponseEnvelope`. Main-side `dispatch()` MUST validate before sending. Worker-side `serve()` MUST validate on receipt. Validation failure on either side MUST throw `BRIDGE_ENVELOPE_INVALID` with the Zod issue tree in `details`.
|
||||
|
||||
#### Scenario: malformed envelope is rejected
|
||||
|
||||
- **WHEN** a non-object value is sent across the port
|
||||
- **THEN** the receiving side throws `BRIDGE_ENVELOPE_INVALID` AND the request promise rejects
|
||||
|
||||
**Verified by:** `src/envelope-schemas/envelope-schemas.test.ts::"malformed envelope throws BRIDGE_ENVELOPE_INVALID"`
|
||||
|
||||
---
|
||||
|
||||
### Requirement: Request and response streams transfer via Transferable
|
||||
|
||||
The package SHALL marshal request-body `ReadableStream` and response-body `ReadableStream` via `Transferable` so chunks transfer zero-copy. Back-pressure SHALL be propagated end-to-end via `api-worker-rpc`'s streaming ack protocol — the consumer's slow read MUST throttle the producer.
|
||||
|
||||
#### Scenario: 16 MiB request stream round-trips
|
||||
|
||||
- **WHEN** the main side dispatches with a 16 MiB request body stream
|
||||
- **THEN** the worker handler observes the full byte sequence AND `transferList` was used (verified by absence of allocation in main process after transfer)
|
||||
|
||||
#### Scenario: response stream backpressure throttles producer
|
||||
|
||||
- **WHEN** the main side reads slowly from a worker-produced response stream
|
||||
- **THEN** the worker-side producer stalls on missing acks
|
||||
|
||||
**Verified by:** `src/streaming-marshal/streaming-marshal.test.ts::"16 MiB request stream round-trips"` AND `src/streaming-marshal/streaming-marshal.test.ts::"response stream backpressure throttles producer"`
|
||||
|
||||
---
|
||||
|
||||
### Requirement: Bridge passes the router conformance suite under the worker-proxy surface
|
||||
|
||||
The package SHALL be runnable as the surface argument to `runRouterConformance` from `@suaveplan/api-router/testing`. Every router invariant (route match, param extraction, middleware order, error propagation, etc.) MUST hold across the bridge identically to a direct in-process router. This is the Stage-3 gate that lets Stage 4 declare router conformance "both surfaces".
|
||||
|
||||
#### Scenario: router conformance suite passes against bridge
|
||||
|
||||
- **WHEN** `runRouterConformance("worker-bridge", makeBridgeFactory)` runs
|
||||
- **THEN** every conformance scenario passes
|
||||
|
||||
**Verified by:** `tests/conformance/router-conformance.test.ts::"runRouterConformance passes against bridge"`
|
||||
|
||||
---
|
||||
|
||||
### Requirement: Handler throw propagates as SuaveplanError without leaking handler internals
|
||||
|
||||
The package SHALL forward worker-side handler throws back across the bridge via `api-worker-rpc`'s error-reconstruction. `SuaveplanError` instances MUST round-trip with code + cause. Plain `Error` throws MUST be wrapped in `SuaveplanError` with code `BRIDGE_HANDLER_THROW`. The wire envelope MUST NOT carry the raw `Error.stack` as a live property — only as a `details.remoteStack` string.
|
||||
|
||||
#### Scenario: SuaveplanError round-trips with code preserved
|
||||
|
||||
- **WHEN** a worker-side handler throws `SuaveplanError("PLUGIN.X.NOT_FOUND")`
|
||||
- **THEN** the main side receives a `SuaveplanError` with code `PLUGIN.X.NOT_FOUND`
|
||||
|
||||
#### Scenario: plain Error wraps as BRIDGE_HANDLER_THROW
|
||||
|
||||
- **WHEN** a worker-side handler throws `new RangeError("boom")`
|
||||
- **THEN** the main side receives `SuaveplanError` with code `BRIDGE_HANDLER_THROW` AND `details.remoteName === "RangeError"`
|
||||
|
||||
**Verified by:** `src/worker-side/worker-side.test.ts::"SuaveplanError round-trips with code"` AND `src/worker-side/worker-side.test.ts::"plain Error wraps as BRIDGE_HANDLER_THROW"`
|
||||
@@ -0,0 +1,72 @@
|
||||
# Tasks — `@suaveplan/api-router-worker-bridge`
|
||||
|
||||
> Every checkbox MUST reflect work actually done in this change.
|
||||
|
||||
## 0. Pre-flight (non-negotiable)
|
||||
|
||||
- [ ] 0.1 Confirm clean working tree (`git status` reports nothing) and no in-flight worktrees with uncommitted work (`git worktree list` then `git status` in each)
|
||||
- [ ] 0.2 If any worktrees exist under `.claude/worktrees/`, account for each one: still-active agent, work-pending-merge, or stale-and-prune. Stale worktrees MUST be removed (`git worktree remove`) before opening a new one — code that has been lost twice on main is the failure mode this guards against.
|
||||
- [ ] 0.3 Confirm the package set in `MANIFEST.md` matches `find packages -maxdepth 3 -name package.json` count. Drift here means a prior change archived without regenerating the manifest.
|
||||
|
||||
## 1. Spec authoring
|
||||
|
||||
- [x] 1.1 Read design doc §6 (per-request data flow) + §5.2a
|
||||
- [x] 1.2 Read umbrella
|
||||
- [x] 1.3 Read `openspec/AGENTS.md` Sections 13 and 14
|
||||
- [x] 1.4 Draft `proposal.md`
|
||||
- [x] 1.5 Draft `specs/api-router-worker-bridge/spec.md`
|
||||
- [ ] 1.6 Every requirement carries `**Verified by:**`
|
||||
|
||||
## 2. Implementation
|
||||
|
||||
- [ ] 2.1 Scaffold `packages/api/api-router-worker-bridge/` (`0.1.0`, deps: `@suaveplan/api-worker-rpc`, `@suaveplan/api-types`, `@suaveplan/error`, `zod`)
|
||||
- [ ] 2.2 `src/main-side/` — `BridgeMain.dispatch(routeHit) → Promise<Response>`
|
||||
- [ ] 2.3 `src/worker-side/` — `BridgeWorker.serve(handler)` accepts envelopes from main
|
||||
- [ ] 2.4 `src/envelope-schemas/` — Zod schemas for `HttpDispatchEnvelope` + `HttpResponseEnvelope`
|
||||
- [ ] 2.5 `src/streaming-marshal/` — `Transferable` stream marshalling both directions
|
||||
- [ ] 2.6 `src/header-allowlist/` — default deny list (`authorization`, `cookie`, `set-cookie`, `x-csrf-token`); per-route allowlist
|
||||
- [ ] 2.7 `src/error-codes.ts` — every `BRIDGE_*` code
|
||||
- [ ] 2.8 `src/index.ts` — namespace re-exports
|
||||
- [ ] 2.9 Conformance: bridge MUST pass `runRouterConformance` (Stage 4 gate) under worker-proxy surface
|
||||
|
||||
## 3. Tests
|
||||
|
||||
- [ ] 3.1 `src/main-side/main-side.test.ts` — given route match + body, envelope sent + response rehydrated
|
||||
- [ ] 3.2 `src/worker-side/worker-side.test.ts` — envelope decoded; handler invoked with reconstructed ctx; response envelope sent
|
||||
- [ ] 3.3 `src/envelope-schemas/envelope-schemas.test.ts` — invalid envelope rejected (`BRIDGE_ENVELOPE_INVALID`)
|
||||
- [ ] 3.4 `src/streaming-marshal/streaming-marshal.test.ts` — large request stream + large response stream both round-trip with back-pressure
|
||||
- [ ] 3.5 `src/header-allowlist/header-allowlist.spec-conformance.test.ts` — `expectTypeOf` AND runtime assertions that `Authorization` / `Cookie` are NEVER in `ctx.request.headers` worker-side
|
||||
- [ ] 3.6 `tests/no-raw-request.test.ts` — pin invariant: envelope never carries `Request` reference; raw `Request` is unreachable from worker
|
||||
- [ ] 3.7 Every `it(...)` carries `{ timeout: 5000 }`
|
||||
|
||||
## 4. Documentation
|
||||
|
||||
- [ ] 4.1 Sibling `.md` for every implementation `.ts` (≥200 words, basic + advanced examples)
|
||||
- [ ] 4.2 README links every co-located `.md`; explicitly call out the no-raw-`Request` invariant
|
||||
- [ ] 4.3 Update CLAUDE.md
|
||||
|
||||
## 5. Pre-archive verification (the 5-gate triple)
|
||||
|
||||
- [ ] 5.1 `bun run check` — Biome 0/0/0
|
||||
- [ ] 5.2 `bunx turbo lint typecheck test --filter=@suaveplan/api-router-worker-bridge` — green
|
||||
- [ ] 5.3 `bunx turbo test:coverage --filter=@suaveplan/api-router-worker-bridge` — 100/100/100/100
|
||||
- [ ] 5.4 `bun scripts/openspec-conformance.ts @suaveplan/api-router-worker-bridge` — exit 0
|
||||
- [ ] 5.5 `bunx turbo build --filter=@suaveplan/api-router-worker-bridge` — green
|
||||
- [ ] 5.6 **Conformance gate**: `runRouterConformance` from `@suaveplan/api-router/testing` passes against the bridge as the surface — required before Stage 4 can complete
|
||||
|
||||
## 6. Pre-archive 7-row checklist
|
||||
|
||||
- [ ] 6.1 Generics threaded; `expectTypeOf` proves response type preserved across bridge
|
||||
- [ ] 6.2 Zod schemas validate envelopes on both sides
|
||||
- [ ] 6.3 Every `BRIDGE_*` code thrown from a production path
|
||||
- [ ] 6.4 Strict-mode behaviors (header allowlist on/off configurable; strict default)
|
||||
- [ ] 6.5 OTel — N/A (host's request span continues across bridge; bridge adds `api.bridge.dispatch` child span tested with `InMemoryMetricExporter`)
|
||||
- [ ] 6.6 Lifecycle dedup — N/A
|
||||
- [ ] 6.7 No retroactive tick
|
||||
|
||||
## 7. Archive
|
||||
|
||||
- [ ] 7.1 Fold spec delta into `openspec/specs/api-router-worker-bridge/spec.md`
|
||||
- [ ] 7.2 Move to `openspec/archive/<yyyy-mm-dd>-api-router-worker-bridge/`
|
||||
- [ ] 7.3 Tick Stage-3 row in umbrella
|
||||
- [ ] 7.4 Refresh `MANIFEST.md`
|
||||
Reference in New Issue
Block a user