@bom-pi/core 0.1.4 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,227 @@
1
+ /** A-side funnel dispatch (D3 backend, SEC-14 seam): the bridge between a VERIFIED relayed
2
+ * E2EE request and a domain handler. `createSecureRelayTargetHandler` admits a request only
3
+ * after the per-request §11 boundary re-verification AND the typed operation policy (actor
4
+ * verified, family admitted, GET-only rows); what reaches THIS factory is therefore already
5
+ * authorized — the factory only routes the sealed payload to a handler and shapes the
6
+ * sealed reply. Deny-first by construction: a handler that is not registered for the exact
7
+ * (audience, method) pair answers `not-admitted`; nothing is inferred from the path.
8
+ *
9
+ * The coordinator's integration wires the real domain handlers here (the same domain calls
10
+ * the local-json families make); this module owns the SHAPE: bounded path/contentType/body
11
+ * in, a JSON-serializable result out, static bounded failures — never a raw error echo. */
12
+
13
+ import type { SecureRelayRequest } from "./relay-secure-channel.ts";
14
+ import type { CanonicalValue } from "@bom-pi/protocol/codec.ts";
15
+
16
+ /** What one admitted operation's handler receives: the verified actor and the routed call. */
17
+ export interface RemoteFunnelCall {
18
+ requestId: string;
19
+ /** The handshake-proven remote device identity (never a local owner). */
20
+ sessionPrincipal: string;
21
+ relationId: string;
22
+ grantEpoch: number;
23
+ audience: string;
24
+ method: "GET" | "POST";
25
+ /** The api-funnel path the call was routed from, when the request carried one. */
26
+ path?: string;
27
+ contentType?: string;
28
+ /** The decoded operation payload bytes, when the request carried a body. */
29
+ body?: Uint8Array;
30
+ }
31
+
32
+ /** One handler row: an exact (audience, method) pair. No wildcards, no path routing. */
33
+ export interface RemoteFunnelHandlerRow {
34
+ audience: string;
35
+ method: "GET" | "POST";
36
+ handle(
37
+ call: RemoteFunnelCall,
38
+ ):
39
+ | Promise<{ status: number; json: { [key: string]: unknown } }>
40
+ | { status: number; json: { [key: string]: unknown } };
41
+ }
42
+
43
+ export type RemoteFunnelOutcome =
44
+ { ok: 1; result: { [key: string]: unknown } } | { ok: 0; denied: string };
45
+
46
+ const AUDIENCE = /^[a-z][a-z0-9:_-]{0,63}$/;
47
+
48
+ /** Builds the `deps.dispatch` function for `createSecureRelayTargetHandler`: exact-pair
49
+ * handler routing over an explicit table. Deny-first: an audience/method with no row (or a
50
+ * malformed row) answers the bounded `not-admitted` denial — the caller's authorize() has
51
+ * already passed, so a missing row is an integration gap, surfaced as a denial, never as an
52
+ * open fallback. */
53
+ /** Normalizes one handler payload to the sealed wire's canonical-JSON value space (§6):
54
+ * booleans become 0/1 (the wire's boolean convention — `e2ee:1`), arrays and plain objects
55
+ * recurse, and anything the codec would reject (undefined, floats, non-plain objects,
56
+ * accessors) returns null so the caller answers the bounded handler-malformed-result
57
+ * denial instead of letting the reply seal throw. */
58
+ const toCanonicalValue = (value: unknown): CanonicalValue | null => {
59
+ if (value === null) {
60
+ return null;
61
+ }
62
+
63
+ if (typeof value === "string") {
64
+ return value;
65
+ }
66
+
67
+ if (typeof value === "boolean") {
68
+ return value ? 1 : 0;
69
+ }
70
+
71
+ if (typeof value === "number") {
72
+ return Number.isSafeInteger(value) && !Object.is(value, -0) && value >= 0 ? value : null;
73
+ }
74
+
75
+ if (Array.isArray(value)) {
76
+ const items: CanonicalValue[] = [];
77
+
78
+ for (const item of value) {
79
+ const normalized = toCanonicalValue(item);
80
+
81
+ if (normalized === null && item !== null) {
82
+ return null;
83
+ }
84
+
85
+ items.push(normalized as CanonicalValue);
86
+ }
87
+
88
+ if (Object.keys(value).length !== value.length) {
89
+ return null;
90
+ }
91
+
92
+ return items;
93
+ }
94
+
95
+ if (typeof value !== "object") {
96
+ return null;
97
+ }
98
+
99
+ if (
100
+ Object.getPrototypeOf(value) !== Object.prototype &&
101
+ Object.getPrototypeOf(value) !== null
102
+ ) {
103
+ return null;
104
+ }
105
+
106
+ const out: { [key: string]: CanonicalValue } = {};
107
+
108
+ for (const key of Object.keys(value)) {
109
+ const descriptor = Object.getOwnPropertyDescriptor(value, key);
110
+
111
+ if (descriptor === undefined || !Object.hasOwn(descriptor, "value")) {
112
+ return null;
113
+ }
114
+
115
+ const normalized = toCanonicalValue(descriptor.value);
116
+
117
+ if (normalized === null && descriptor.value !== null) {
118
+ return null;
119
+ }
120
+
121
+ out[key] = normalized as CanonicalValue;
122
+ }
123
+
124
+ return out;
125
+ };
126
+
127
+ export function createRemoteFunnelDispatch(
128
+ rows: readonly RemoteFunnelHandlerRow[],
129
+ options: { log?: (line: string) => void } = {},
130
+ ): (
131
+ request: SecureRelayRequest & {
132
+ channelId: string;
133
+ sessionPrincipal: string;
134
+ relationId: string;
135
+ grantEpoch: number;
136
+ },
137
+ ) => Promise<RemoteFunnelOutcome> {
138
+ const table = new Map<string, RemoteFunnelHandlerRow>();
139
+ const log = options.log ?? (() => {});
140
+
141
+ for (const row of rows) {
142
+ if (
143
+ typeof row.audience !== "string" ||
144
+ !AUDIENCE.test(row.audience) ||
145
+ (row.method !== "GET" && row.method !== "POST") ||
146
+ typeof row.handle !== "function" ||
147
+ table.has(`${row.audience} ${row.method}`)
148
+ ) {
149
+ throw new Error(`Invalid remote funnel handler row: ${String(row.audience)}`);
150
+ }
151
+
152
+ table.set(`${row.audience} ${row.method}`, row);
153
+ }
154
+
155
+ return async (request) => {
156
+ const row = table.get(`${request.audience} ${request.method}`);
157
+
158
+ if (row === undefined) {
159
+ log(`remote-funnel: no handler for ${request.audience} ${request.method}`);
160
+
161
+ return { ok: 0, denied: "not-admitted" };
162
+ }
163
+
164
+ let body: Uint8Array | undefined;
165
+
166
+ if (request.body !== undefined) {
167
+ body = Buffer.from(request.body, "base64url");
168
+ }
169
+
170
+ try {
171
+ const outcome = await row.handle({
172
+ requestId: request.requestId,
173
+ sessionPrincipal: request.sessionPrincipal,
174
+ relationId: request.relationId,
175
+ grantEpoch: request.grantEpoch,
176
+ audience: request.audience,
177
+ method: request.method,
178
+ ...(request.path !== undefined ? { path: request.path } : {}),
179
+ ...(request.contentType !== undefined ? { contentType: request.contentType } : {}),
180
+ ...(body !== undefined ? { body } : {}),
181
+ });
182
+
183
+ if (
184
+ outcome === null ||
185
+ typeof outcome !== "object" ||
186
+ !Number.isSafeInteger(outcome.status) ||
187
+ outcome.status < 200 ||
188
+ outcome.status > 599 ||
189
+ outcome.json === null ||
190
+ typeof outcome.json !== "object"
191
+ ) {
192
+ return { ok: 0, denied: "handler-malformed-result" };
193
+ }
194
+
195
+ // The reply rides a §21 sealed frame whose payload is CANONICAL JSON (§6):
196
+ // strings, null, nonnegative safe integers, arrays, plain objects — booleans
197
+ // ride as 0/1 on this wire (the v1 pilots' e2ee:1 is the convention). A
198
+ // handler that answers with anything the codec rejects must fail AS THIS
199
+ // REQUEST'S typed denial; before this guard such a payload threw inside the
200
+ // reply seal, which dropped the whole channel ("session-fatal") — the reply
201
+ // vanished and every call after it on the channel timed out.
202
+ const json = toCanonicalValue(outcome.json);
203
+
204
+ if (json === null) {
205
+ log(
206
+ `remote-funnel: handler for ${request.audience} answered a non-canonical payload`,
207
+ );
208
+
209
+ return { ok: 0, denied: "handler-malformed-result" };
210
+ }
211
+
212
+ // The handler's own non-2xx answer is a legitimate denial-shaped reply: the
213
+ // status rides inside the sealed result for the funnel to surface.
214
+ return {
215
+ ok: 1,
216
+ result: { status: outcome.status, json },
217
+ };
218
+ } catch (error) {
219
+ log(
220
+ `remote-funnel: handler for ${request.audience} failed: ` +
221
+ (error instanceof Error ? error.message : "handler"),
222
+ );
223
+
224
+ return { ok: 0, denied: "handler-failed" };
225
+ }
226
+ };
227
+ }
@@ -0,0 +1,325 @@
1
+ /** SEC-13 item 2 / SEC-14 D2-scoped E2EE relay channels: ONE `CryptoSession` per relay
2
+ * channel, created by a fresh three-message §21 handshake whose bytes cross X OPAQUELY
3
+ * (X routes the handshake frames like any other channel body — public keys only, no
4
+ * plaintext application path ever exists, SEC-1/SEC-2). Each channel owns its own
5
+ * sessionId/sequence/nonce-base scope; no crypto state is ever shared across channels, and an
6
+ * epoch change kills every channel under the relation (the frame header already carries the
7
+ * grant epoch + both membership refs, so a stale channel cannot survive a re-issue).
8
+ *
9
+ * The single crypto stack is CONSUMED, never reimplemented: `@bom-pi/protocol/crypto.ts`
10
+ * below, wrapped per channel by the existing `SecureTransport` (activation checks per send,
11
+ * session-fatal on any frame error, cancellation-first outcomes, revoke). This module adds
12
+ * only the relay-specific choreography:
13
+ *
14
+ * B (requester) X (cloud, opaque routing) A (target)
15
+ * 1. clientHello ── relay-open(e2ee,hello) ──────────────────────────────▶ delivery
16
+ * 2. boundary.admitSession
17
+ * (live directed grant, §11)
18
+ * ◀──── serverHello ─────────── acceptance(hello)
19
+ * 3. verifyServerPair, clientFinish ── mux frame ──▶ ── mux frame ─▶ 4. verifyHandshake
20
+ * 5. every request/reply is a §21 sealed frame in both directions.
21
+ *
22
+ * Nothing here authorizes anything: admission stays at A's central §11 boundary (fresh
23
+ * ledger reads per request) and the typed operation policy (SEC-14) stays in
24
+ * relay-boundary.ts. Activation of this surface remains behind the owner relay switch and
25
+ * the D2 owner gate — wiring it into production dispatch is a coordinator/owner act. */
26
+
27
+ import {
28
+ createClientFinish,
29
+ createClientHello,
30
+ createServerHello,
31
+ ephemeralX25519,
32
+ type Ephemeral,
33
+ type RelationContext,
34
+ } from "@bom-pi/protocol/crypto.ts";
35
+ import { canonicalJson } from "@bom-pi/protocol/codec.ts";
36
+ import { SecureTransport, type ActivationCheck, type RequestOutcome } from "./secure-transport.ts";
37
+ import type { ApplicationActor } from "./relay-boundary.ts";
38
+
39
+ /** §16/REL-9-adjacent single-frame bound for a routed operation's payload: the base64url
40
+ * `body` a funnel request may carry in ONE sealed frame, comfortably inside the §21 seal
41
+ * bound with envelope headroom. Larger payloads are the streams lane's chunked surface —
42
+ * refusing here is fail-closed, never session-fatal (checked before any seal). */
43
+ export const MAX_RELAY_REQUEST_BODY_B64 = 700_000;
44
+
45
+ /** Sealed frame types on a secure relay channel (streamId is always the channel id). */
46
+ export const RELAY_REQUEST_FRAME_TYPE = "relay-request";
47
+ export const RELAY_REPLY_FRAME_TYPE = "relay-reply";
48
+
49
+ /** Bounded handshake deadline: a channel that never completes its three-message handshake
50
+ * within this window is disposed (PROPOSED D2 default; callers may only shorten it). */
51
+ export const RELAY_HANDSHAKE_DEADLINE_MS = 30_000;
52
+
53
+ /** The canonical request body sealed inside every relay-request frame: 1/0 envelope rules,
54
+ * an explicit actor field (SEC-14 actorField) and the operation coordinates. The actor is
55
+ * validated against the VERIFIED session principal at A — never trusted from the wire. The
56
+ * optional funnel fields carry a routed operation's payload (D3): `path` (the api-funnel's
57
+ * own path shape, provenance echo), `contentType` and `body` (base64url bytes) — strict
58
+ * strings, validated at A, and absent for the bodyless v1 pings. */
59
+ export interface SecureRelayRequest {
60
+ v: 1;
61
+ requestId: string;
62
+ audience: string;
63
+ method: "GET" | "POST";
64
+ actor: ApplicationActor;
65
+ /** The funnel path this call was routed from (no credentials ever ride this frame). */
66
+ path?: string;
67
+ contentType?: string;
68
+ /** The operation payload as base64url bytes; GET reads usually carry none. */
69
+ body?: string;
70
+ }
71
+
72
+ /** The canonical reply body sealed inside every relay-reply frame. Field presence decides
73
+ * success/failure (canonical 1/0 profile); `denied` carries the bounded denial name. */
74
+ export type SecureRelayReply =
75
+ | { v: 1; requestId: string; ok: 1; result: { [key: string]: unknown } }
76
+ | { v: 1; requestId: string; ok: 0; denied: string };
77
+
78
+ export interface SecureChannelIdentity {
79
+ publicKeyDer: Uint8Array;
80
+ privateKeyDer: Uint8Array;
81
+ fingerprint: string;
82
+ }
83
+
84
+ const asBuffer = (bytes: Uint8Array): Buffer =>
85
+ Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength);
86
+
87
+ /** One established (or establishing) E2EE relay channel on the CLIENT (requester, B) side. */
88
+ export class ClientSecureChannel {
89
+ readonly channelId: string;
90
+ private readonly transport: SecureTransport;
91
+
92
+ constructor(input: { channelId: string; transport: SecureTransport }) {
93
+ this.channelId = input.channelId;
94
+ this.transport = input.transport;
95
+ }
96
+
97
+ get sessionId(): string | null {
98
+ return this.transport.sessionId;
99
+ }
100
+
101
+ get state(): string {
102
+ return this.transport.currentState;
103
+ }
104
+
105
+ /** Seals and emits one request frame. The activation check (current local owner + live
106
+ * relation) runs inside the transport before anything is signed — a refused check emits
107
+ * nothing and the outcome stays "absent" (§20). */
108
+ request(body: SecureRelayRequest, options: { mutation: boolean }): Uint8Array {
109
+ if (body.body !== undefined && body.body.length > MAX_RELAY_REQUEST_BODY_B64) {
110
+ throw new RangeError(
111
+ "relay request body exceeds the single-frame bound; use the chunked stream surface",
112
+ );
113
+ }
114
+
115
+ return this.transport.send({
116
+ requestId: body.requestId,
117
+ mutation: options.mutation,
118
+ type: RELAY_REQUEST_FRAME_TYPE,
119
+ streamId: this.channelId,
120
+ plaintext: asBuffer(canonicalJson(body as never)),
121
+ });
122
+ }
123
+
124
+ /** Opens one sealed reply frame from A (session-fatal on any mismatch, via the transport). */
125
+ receiveReply(frameBytes: Uint8Array): SecureRelayReply {
126
+ const plaintext = this.transport.receive(
127
+ frameBytes,
128
+ RELAY_REPLY_FRAME_TYPE,
129
+ this.channelId,
130
+ );
131
+
132
+ return JSON.parse(plaintext.toString("utf8")) as SecureRelayReply;
133
+ }
134
+
135
+ outcomeOf(requestId: string): RequestOutcome {
136
+ return this.transport.outcomeOf(requestId);
137
+ }
138
+
139
+ acknowledge(requestId: string): void {
140
+ this.transport.acknowledge(requestId);
141
+ }
142
+
143
+ linkLost(reason: string): void {
144
+ this.transport.linkLost(reason);
145
+ }
146
+
147
+ revokeRelation(reason: string): void {
148
+ this.transport.revokeRelation(reason);
149
+ }
150
+ }
151
+
152
+ /** The exact §11/§12 routing claim B presents at relay-open (structural twin of the cloud
153
+ * connector's RelayOpenClaim — kept structural so this module stays dependency-free). */
154
+ export interface SecureRelayOpenClaim {
155
+ relationId: string;
156
+ grantEpoch: number;
157
+ requesterMembership: { id: string; epoch: number };
158
+ targetMembership: { id: string; epoch: number };
159
+ direction: "requester-to-target";
160
+ }
161
+
162
+ export interface SecureChannelClientOptions {
163
+ /** The relation context built from B's OWN stored grant (never from X-forwarded claims). */
164
+ context: RelationContext;
165
+ /** B's pinned identity; signs the client hello/finish and every sealed frame. */
166
+ identity: SecureChannelIdentity;
167
+ /** A's public SPKI from B's stored grant (pinned; fingerprint-checked inside the handshake). */
168
+ peerPublicDer: Uint8Array;
169
+ /** §20 activation check, re-run before every outbound send. */
170
+ activation: () => ActivationCheck;
171
+ /** Opens the mux channel on X: sends relay-open(e2ee, hello), returns the minted channel
172
+ * id plus A's opaque serverHello. Throwing fails the open closed. */
173
+ openChannel(
174
+ claim: SecureRelayOpenClaim,
175
+ clientHello: Uint8Array,
176
+ ): Promise<{ channelId: string; serverHello: Uint8Array }>;
177
+ /** Emits one mux-framed channel body (handshake finish or sealed frame) toward X. */
178
+ sendFrame: (channelId: string, payload: Uint8Array) => void;
179
+ }
180
+
181
+ /** Drives the client half of one channel's handshake and hands back the live channel. */
182
+ export async function openSecureChannel(
183
+ options: SecureChannelClientOptions,
184
+ claim: SecureRelayOpenClaim,
185
+ ): Promise<ClientSecureChannel> {
186
+ const ephemeral: Ephemeral = ephemeralX25519();
187
+ const clientHello = createClientHello(
188
+ options.context,
189
+ ephemeral,
190
+ options.identity.privateKeyDer,
191
+ );
192
+ const opened = await options.openChannel(claim, clientHello);
193
+ const clientFinish = createClientFinish(
194
+ options.context,
195
+ clientHello,
196
+ opened.serverHello,
197
+ options.identity.publicKeyDer,
198
+ options.peerPublicDer,
199
+ options.identity.privateKeyDer,
200
+ );
201
+
202
+ const transport = new SecureTransport({
203
+ role: "client",
204
+ activation: options.activation,
205
+ deliver: (frame) => options.sendFrame(opened.channelId, frame),
206
+ });
207
+
208
+ // verifyHandshake runs inside connect(): both Ed25519 signatures on the transcript are
209
+ // checked against the pinned peer key before any session exists (SEC-14 verified actor).
210
+ transport.connect({
211
+ context: options.context,
212
+ clientHello,
213
+ serverHello: opened.serverHello,
214
+ clientFinish,
215
+ clientPublicDer: options.identity.publicKeyDer,
216
+ serverPublicDer: options.peerPublicDer,
217
+ localEphemeral: ephemeral,
218
+ localPrivateDer: options.identity.privateKeyDer,
219
+ peerPublicDer: options.peerPublicDer,
220
+ });
221
+
222
+ // The finish message rides the channel as its first pre-session body; A completes the
223
+ // same verification from its side and only then does the channel carry sealed frames.
224
+ options.sendFrame(opened.channelId, clientFinish);
225
+
226
+ return new ClientSecureChannel({ channelId: opened.channelId, transport });
227
+ }
228
+
229
+ /** The server (target, A) half of one channel's handshake state, pre-verification. */
230
+ export class ServerChannelHandshake {
231
+ private readonly context: RelationContext;
232
+ private readonly identity: SecureChannelIdentity;
233
+ private readonly clientHello: Uint8Array;
234
+ private readonly clientPublicDer: Uint8Array;
235
+ private readonly ephemeral: Ephemeral = ephemeralX25519();
236
+ readonly serverHello: Uint8Array;
237
+
238
+ constructor(input: {
239
+ context: RelationContext;
240
+ identity: SecureChannelIdentity;
241
+ clientHello: Uint8Array;
242
+ /** The requester's pinned SPKI from A's OWN stored grant — X never supplies key
243
+ * material; the handshake binds this key to the grant's requesterFp or throws. */
244
+ clientPublicDer: Uint8Array;
245
+ }) {
246
+ this.context = input.context;
247
+ this.identity = input.identity;
248
+ this.clientHello = input.clientHello;
249
+ this.clientPublicDer = input.clientPublicDer;
250
+ this.serverHello = createServerHello(
251
+ input.context,
252
+ input.clientHello,
253
+ input.clientPublicDer,
254
+ this.ephemeral,
255
+ input.identity.privateKeyDer,
256
+ );
257
+ }
258
+
259
+ /** Consumes B's clientFinish, runs the full transcript verification and builds A's
260
+ * per-channel session. Any tamper, replay or key mismatch throws — the channel dies. */
261
+ complete(input: {
262
+ clientFinish: Uint8Array;
263
+ activation: () => ActivationCheck;
264
+ sendFrame: (payload: Uint8Array) => void;
265
+ }): ServerSecureChannel {
266
+ const transport = new SecureTransport({
267
+ role: "server",
268
+ activation: input.activation,
269
+ deliver: input.sendFrame,
270
+ });
271
+
272
+ transport.connect({
273
+ context: this.context,
274
+ clientHello: this.clientHello,
275
+ serverHello: this.serverHello,
276
+ clientFinish: input.clientFinish,
277
+ clientPublicDer: this.clientPublicDer,
278
+ serverPublicDer: this.identity.publicKeyDer,
279
+ localEphemeral: this.ephemeral,
280
+ localPrivateDer: this.identity.privateKeyDer,
281
+ peerPublicDer: this.clientPublicDer,
282
+ });
283
+
284
+ return new ServerSecureChannel({ transport });
285
+ }
286
+ }
287
+
288
+ /** One established E2EE relay channel on the SERVER (target, A) side. */
289
+ export class ServerSecureChannel {
290
+ private readonly transport: SecureTransport;
291
+
292
+ constructor(input: { transport: SecureTransport }) {
293
+ this.transport = input.transport;
294
+ }
295
+
296
+ get sessionId(): string | null {
297
+ return this.transport.sessionId;
298
+ }
299
+
300
+ /** Opens one sealed request frame from B; any verification failure is session-fatal. */
301
+ receiveRequest(frameBytes: Uint8Array, streamId: string): SecureRelayRequest {
302
+ const plaintext = this.transport.receive(frameBytes, RELAY_REQUEST_FRAME_TYPE, streamId);
303
+
304
+ return JSON.parse(plaintext.toString("utf8")) as SecureRelayRequest;
305
+ }
306
+
307
+ /** Seals one reply frame toward B. */
308
+ reply(streamId: string, body: SecureRelayReply): Uint8Array {
309
+ return this.transport.send({
310
+ requestId: body.requestId,
311
+ mutation: false,
312
+ type: RELAY_REPLY_FRAME_TYPE,
313
+ streamId,
314
+ plaintext: asBuffer(canonicalJson(body as never)),
315
+ });
316
+ }
317
+
318
+ linkLost(reason: string): void {
319
+ this.transport.linkLost(reason);
320
+ }
321
+
322
+ revokeRelation(reason: string): void {
323
+ this.transport.revokeRelation(reason);
324
+ }
325
+ }