@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,482 @@
1
+ /** The WEB-SIDE REMOTE CHANNEL BINDING (D3 backend): `RemoteChannel` — the object the
2
+ * api-funnel/host-state seam attaches for a paired remote host. Its `request(path, init)`
3
+ * carries EXACTLY the shape web/api-funnel.js builds for a relay call (the operation's
4
+ * method, body, abort signal, content-type, and the routing-only X-Pocket-Host header) over
5
+ * the per-channel E2EE lane (relay-secure-channel): the path is resolved to an admitted
6
+ * operation audience by an INJECTED exact-pair route table (deny-first: no route, no sealed
7
+ * frame — nothing is sent), the payload rides a §21 sealed frame, and the reply comes back
8
+ * as a fetch `Response` — the contract store.js's api() already consumes.
9
+ *
10
+ * Credential discipline is enforced here a second time (the funnel already strips them):
11
+ * headers other than content-type are DROPPED, never forwarded — no cookie, no
12
+ * authorization, no CSRF material ever crosses the relay. Abort signals abandon the call
13
+ * locally (the sealed request may already have left: a mutation's outcome stays unknown
14
+ * exactly as the §8 transport semantics dictate). Connection loss disposes the channel:
15
+ * every pending call fails closed and later calls refuse until a fresh channel is opened.
16
+ *
17
+ * Feature-detection/fail-closed is inherited from the layers below: an old cloud without
18
+ * mux never gets a relay-open (openSecureChannel refuses with a static error), and the
19
+ * canned pilot lane is untouched — this class is only constructed by the (coordinator-owned)
20
+ * wiring that attaches a remote host's channel. */
21
+
22
+ import { randomBytes } from "node:crypto";
23
+ import type { RelationContext } from "@bom-pi/protocol/crypto.ts";
24
+ import {
25
+ MAX_RELAY_REQUEST_BODY_B64,
26
+ openSecureChannel,
27
+ type ClientSecureChannel,
28
+ type SecureRelayOpenClaim,
29
+ type SecureRelayReply,
30
+ } from "./relay-secure-channel.ts";
31
+ import type { ApplicationActor } from "./relay-boundary.ts";
32
+
33
+ /** One exact route row: the funnel path an operation is reached by, and the admitted
34
+ * (audience, method) pair it routes to. No wildcards — the table is authored where the
35
+ * facade's own registry lives (coordinator integration), and A re-verifies everything. */
36
+ export interface RemoteChannelRoute {
37
+ path: string;
38
+ audience: string;
39
+ method: "GET" | "POST";
40
+ }
41
+
42
+ /** The transport seam RemoteChannel drives (CloudWssTransport satisfies this structurally). */
43
+ export interface RemoteChannelTransport {
44
+ relayOpenE2ee(
45
+ claim: SecureRelayOpenClaim,
46
+ clientHello: Uint8Array,
47
+ ): Promise<{ channelId: string; serverHello: Uint8Array }>;
48
+ relaySendChannel(channelId: string, payload: Uint8Array): void;
49
+ onRelayMuxData(listener: (frame: { channelId: string; payload: Uint8Array }) => void): void;
50
+ onRelayClosed(
51
+ callback: (notice: { channelId: string; reason: string }) => void,
52
+ options?: { early?: boolean },
53
+ ): void;
54
+ relayCloseChannel(channelId: string): Promise<void>;
55
+ }
56
+
57
+ export interface RemoteChannelOptions {
58
+ /** The funnel host id this channel is attached under (host-state). */
59
+ hostId: string;
60
+ /** The relation context built from B's OWN stored grant (never X-forwarded claims). */
61
+ context: RelationContext;
62
+ /** B's pinned identity (signs the handshake and every sealed frame). */
63
+ identity: { publicKeyDer: Uint8Array; privateKeyDer: Uint8Array; fingerprint: string };
64
+ /** A's public SPKI from B's stored grant. */
65
+ peerPublicDer: Uint8Array;
66
+ /** The exact-pair route table; without a row for a path the call fails closed, unsealed. */
67
+ routes: readonly RemoteChannelRoute[];
68
+ transport: RemoteChannelTransport;
69
+ log?: (line: string) => void;
70
+ }
71
+
72
+ /** A call was asked of a channel that cannot carry it: never caught, never fallen back from. */
73
+ export class RemoteChannelError extends Error {
74
+ readonly code: "not-routed" | "bad-path" | "bad-init" | "channel-closed";
75
+
76
+ constructor(code: "not-routed" | "bad-path" | "bad-init" | "channel-closed", message: string) {
77
+ super(message);
78
+ this.name = "RemoteChannelError";
79
+ this.code = code;
80
+ }
81
+ }
82
+
83
+ const OWN_URL = /^[^:/?#]+:|^\/\//;
84
+
85
+ /** Default per-call deadline (PROPOSED D3): an unanswered sealed call fails closed. */
86
+ export const REMOTE_CHANNEL_REQUEST_TIMEOUT_MS = 30_000;
87
+
88
+ const sleep = (ms: number): Promise<void> => new Promise((resolve) => setTimeout(resolve, ms));
89
+
90
+ export class RemoteChannel {
91
+ readonly channelId: string;
92
+ readonly hostId: string;
93
+
94
+ get state(): "open" | "closed" {
95
+ return this.#closed ? "closed" : "open";
96
+ }
97
+
98
+ get closeReason(): string | null {
99
+ return this.#closeReason;
100
+ }
101
+
102
+ readonly #channel: ClientSecureChannel;
103
+ readonly #transport: RemoteChannelTransport;
104
+ readonly #routes: Map<string, RemoteChannelRoute>;
105
+ readonly #actor: ApplicationActor;
106
+ readonly #log: (line: string) => void;
107
+ readonly #pending = new Map<
108
+ string,
109
+ {
110
+ resolve: (reply: SecureRelayReply) => void;
111
+ reject: (error: Error) => void;
112
+ timer: NodeJS.Timeout;
113
+ }
114
+ >();
115
+ readonly #replies: SecureRelayReply[] = [];
116
+ #closed = false;
117
+ #closeReason: string | null = null;
118
+ #listenerWired = false;
119
+
120
+ private constructor(options: RemoteChannelOptions, channel: ClientSecureChannel) {
121
+ this.hostId = options.hostId;
122
+ this.channelId = channel.channelId;
123
+ this.#channel = channel;
124
+ this.#transport = options.transport;
125
+ this.#routes = new Map(options.routes.map((route) => [route.path, route]));
126
+ this.#actor = {
127
+ kind: "remote-device",
128
+ fingerprint: options.identity.fingerprint,
129
+ relationId: options.context.relationId,
130
+ grantEpoch: options.context.grantEpoch,
131
+ };
132
+ this.#log = options.log ?? (() => {});
133
+ }
134
+
135
+ /** Opens the channel: real relay-open(e2ee) + the 3-message §21 handshake. The seams
136
+ * below fail closed on old peers (no mux → static error, no relay-open frame leaves).
137
+ * When `ownTransport` is true (default) the channel wires the transport's ONE mux
138
+ * listener and close callback itself — BEFORE the handshake finish is sent, so no
139
+ * inbound frame can be refused for a missing listener; a shared-transport wiring passes
140
+ * false and routes frames through `ingestFrame`/`noteClosed` instead. */
141
+ static async open(
142
+ options: RemoteChannelOptions & { ownTransport?: boolean },
143
+ ): Promise<RemoteChannel> {
144
+ const earlyFrames: { channelId: string; payload: Uint8Array }[] = [];
145
+ const own = options.ownTransport !== false;
146
+ let earlyClosed: string | null = null;
147
+ // The ONE registered listener routes through a late-bound sink: pre-construction
148
+ // frames buffer; post-construction they flow straight into the channel (single
149
+ // registration per transport — never a second onRelayMuxData call).
150
+ const sink: { deliver: (frame: { channelId: string; payload: Uint8Array }) => void } = {
151
+ deliver: (frame) => earlyFrames.push(frame),
152
+ };
153
+
154
+ if (own) {
155
+ options.transport.onRelayMuxData((frame) => sink.deliver(frame));
156
+ options.transport.onRelayClosed(
157
+ (notice) => {
158
+ earlyClosed = `relay-${notice.reason}`;
159
+ },
160
+ { early: true },
161
+ );
162
+ }
163
+
164
+ const channel = await openSecureChannel(
165
+ {
166
+ context: options.context,
167
+ identity: options.identity,
168
+ peerPublicDer: options.peerPublicDer,
169
+ activation: () => ({ currentLocalOwner: true, relationLive: true }),
170
+ openChannel: (claim, clientHello) =>
171
+ options.transport.relayOpenE2ee(claim, clientHello),
172
+ sendFrame: (channelId, payload) =>
173
+ options.transport.relaySendChannel(channelId, payload),
174
+ },
175
+ {
176
+ relationId: options.context.relationId,
177
+ grantEpoch: options.context.grantEpoch,
178
+ requesterMembership: options.context.requesterMembership ?? {
179
+ id: "0".repeat(32),
180
+ epoch: 0,
181
+ },
182
+ targetMembership: options.context.targetMembership ?? {
183
+ id: "0".repeat(32),
184
+ epoch: 0,
185
+ },
186
+ direction: "requester-to-target",
187
+ },
188
+ );
189
+
190
+ const remote = new RemoteChannel(options, channel);
191
+
192
+ if (own) {
193
+ remote.#listenerWired = true;
194
+ sink.deliver = (frame) => remote.#ingest(frame);
195
+
196
+ for (const frame of earlyFrames.splice(0)) {
197
+ remote.#ingest(frame);
198
+ }
199
+
200
+ options.transport.onRelayClosed(
201
+ (notice) => {
202
+ if (notice.channelId === remote.channelId) {
203
+ remote.#dispose(`relay-${notice.reason}`);
204
+ }
205
+ },
206
+ { early: true },
207
+ );
208
+ }
209
+
210
+ if (earlyClosed !== null) {
211
+ remote.#dispose(earlyClosed);
212
+ }
213
+
214
+ return remote;
215
+ }
216
+
217
+ /** Shared-transport wiring (ownTransport:false): route this channel's inbound frames. */
218
+ ingestFrame(frame: { channelId: string; payload: Uint8Array }): void {
219
+ this.#ingest(frame);
220
+ }
221
+
222
+ /** Shared-transport wiring (ownTransport:false): a close notice for this channel. */
223
+ noteClosed(reason: string): void {
224
+ this.#dispose(reason);
225
+ }
226
+
227
+ /** Takes over the transport listeners when the wiring hands the transport to this
228
+ * channel (idempotent; the mux listener is single-registration per transport). */
229
+ adopt(): void {
230
+ if (this.#listenerWired || this.#closed) {
231
+ return;
232
+ }
233
+
234
+ this.#listenerWired = true;
235
+ this.#transport.onRelayMuxData((frame) => this.#ingest(frame));
236
+ this.#transport.onRelayClosed(
237
+ (notice) => {
238
+ if (notice.channelId === this.channelId) {
239
+ this.#dispose(`relay-${notice.reason}`);
240
+ }
241
+ },
242
+ { early: true },
243
+ );
244
+ }
245
+
246
+ /** The funnel contract: carries `path` + the minimal init over the sealed lane and
247
+ * resolves with a fetch `Response` (the shape store.js's api() consumes). */
248
+ async request(
249
+ path: string,
250
+ init: { method?: string; body?: unknown; signal?: AbortSignal; headers?: unknown } = {},
251
+ ): Promise<Response> {
252
+ if (this.#closed) {
253
+ throw new RemoteChannelError(
254
+ "channel-closed",
255
+ `the remote channel is closed (${this.#closeReason ?? "unknown"}); a fresh channel must be opened`,
256
+ );
257
+ }
258
+
259
+ if (typeof path !== "string" || path === "" || OWN_URL.test(path) || path.startsWith("/")) {
260
+ throw new RemoteChannelError(
261
+ "bad-path",
262
+ `a channel carries the funnel's own path shape, not "${String(path)}"`,
263
+ );
264
+ }
265
+
266
+ const route = this.#routes.get(path);
267
+
268
+ if (route === undefined) {
269
+ // Deny-first: no exact route row, nothing is sealed, nothing is sent.
270
+ throw new RemoteChannelError(
271
+ "not-routed",
272
+ `no admitted operation is routed for "${path}"; the call fails closed`,
273
+ );
274
+ }
275
+
276
+ const method = init.method === undefined ? "GET" : String(init.method).toUpperCase();
277
+
278
+ if (method !== route.method) {
279
+ throw new RemoteChannelError(
280
+ "not-routed",
281
+ `"${path}" is routed as ${route.method}, not ${method}`,
282
+ );
283
+ }
284
+
285
+ let contentType: string | undefined;
286
+ let bodyB64: string | undefined;
287
+
288
+ if (init.body !== undefined) {
289
+ const headers =
290
+ init.headers !== null && typeof init.headers === "object"
291
+ ? (init.headers as Record<string, unknown>)
292
+ : {};
293
+ const found = Object.entries(headers).find(
294
+ ([name]) => name.toLowerCase() === "content-type",
295
+ );
296
+
297
+ contentType =
298
+ found !== undefined && typeof found[1] === "string" ? found[1] : "application/json";
299
+
300
+ if (typeof init.body === "string") {
301
+ bodyB64 = Buffer.from(init.body, "utf8").toString("base64url");
302
+ } else if (init.body instanceof Uint8Array) {
303
+ bodyB64 = Buffer.from(init.body).toString("base64url");
304
+ } else if (typeof Blob !== "undefined" && init.body instanceof Blob) {
305
+ const bytes = new Uint8Array(await init.body.arrayBuffer());
306
+
307
+ bodyB64 = Buffer.from(bytes).toString("base64url");
308
+ contentType = init.body.type || contentType;
309
+ } else {
310
+ throw new RemoteChannelError(
311
+ "bad-init",
312
+ "a channel carries string, bytes or Blob bodies, nothing else",
313
+ );
314
+ }
315
+
316
+ if (bodyB64.length > MAX_RELAY_REQUEST_BODY_B64) {
317
+ throw new RemoteChannelError(
318
+ "bad-init",
319
+ "the body exceeds the single-frame bound; use the chunked stream surface",
320
+ );
321
+ }
322
+ }
323
+
324
+ const requestId = randomBytes(16).toString("hex");
325
+ const reply = await this.#roundTrip(requestId, init.signal, {
326
+ v: 1,
327
+ requestId,
328
+ audience: route.audience,
329
+ method: route.method,
330
+ actor: this.#actor,
331
+ path,
332
+ ...(bodyB64 !== undefined ? { contentType, body: bodyB64 } : {}),
333
+ });
334
+
335
+ if (reply.ok !== 1) {
336
+ // The sealed denial surfaces as a 403 Response with the bounded name — the
337
+ // funnel's caller sees a failed call, never an unsealed reason.
338
+ return new Response(`{"error":"${reply.denied}"}`, {
339
+ status: 403,
340
+ headers: { "content-type": "application/json" },
341
+ });
342
+ }
343
+
344
+ const result = reply.result as { status?: unknown; json?: unknown };
345
+ const status =
346
+ typeof result.status === "number" && Number.isSafeInteger(result.status)
347
+ ? result.status
348
+ : 200;
349
+ const json =
350
+ result.json !== null && typeof result.json === "object"
351
+ ? result.json
352
+ : { error: "malformed handler result" };
353
+
354
+ return new Response(JSON.stringify(json), {
355
+ status,
356
+ headers: { "content-type": "application/json" },
357
+ });
358
+ }
359
+
360
+ /** Cooperative close: best-effort relay-close RPC, local dispose either way. */
361
+ async close(): Promise<void> {
362
+ this.#dispose("closed-locally");
363
+
364
+ try {
365
+ await this.#transport.relayCloseChannel(this.channelId);
366
+ } catch {
367
+ // X may already have disposed the channel; local teardown proceeds fail-closed.
368
+ }
369
+ }
370
+
371
+ /** Connection-loss dispose: pending calls fail closed, later calls refuse. */
372
+ #dispose(reason: string): void {
373
+ if (this.#closed) {
374
+ return;
375
+ }
376
+
377
+ this.#closed = true;
378
+ this.#closeReason = reason;
379
+ this.#log(`remote-channel: ${this.channelId} disposed (${reason})`);
380
+
381
+ for (const pending of this.#pending.values()) {
382
+ clearTimeout(pending.timer);
383
+ pending.reject(
384
+ new RemoteChannelError("channel-closed", `the channel was lost: ${reason}`),
385
+ );
386
+ }
387
+
388
+ this.#pending.clear();
389
+ }
390
+
391
+ #ingest(frame: { channelId: string; payload: Uint8Array }): void {
392
+ if (this.#closed || frame.channelId !== this.channelId) {
393
+ return;
394
+ }
395
+
396
+ let reply: SecureRelayReply;
397
+
398
+ try {
399
+ reply = this.#channel.receiveReply(frame.payload);
400
+ } catch (error) {
401
+ // Crypto failure is session-fatal: dispose the channel (fail-closed).
402
+ this.#log(
403
+ "remote-channel: reply rejected: " +
404
+ (error instanceof Error ? error.message : "frame"),
405
+ );
406
+ this.#dispose("session-fatal");
407
+
408
+ return;
409
+ }
410
+
411
+ const pending = this.#pending.get(reply.requestId);
412
+
413
+ if (pending !== undefined) {
414
+ this.#pending.delete(reply.requestId);
415
+ clearTimeout(pending.timer);
416
+ pending.resolve(reply);
417
+
418
+ return;
419
+ }
420
+
421
+ this.#replies.push(reply);
422
+ }
423
+
424
+ #roundTrip(
425
+ requestId: string,
426
+ signal: AbortSignal | undefined,
427
+ body: {
428
+ v: 1;
429
+ requestId: string;
430
+ audience: string;
431
+ method: "GET" | "POST";
432
+ actor: ApplicationActor;
433
+ path?: string;
434
+ contentType?: string;
435
+ body?: string;
436
+ },
437
+ ): Promise<SecureRelayReply> {
438
+ const early = this.#replies.find((reply) => reply.requestId === requestId);
439
+
440
+ if (early !== undefined) {
441
+ this.#replies.splice(this.#replies.indexOf(early), 1);
442
+
443
+ return Promise.resolve(early);
444
+ }
445
+
446
+ return new Promise<SecureRelayReply>((resolve, reject) => {
447
+ const timer = setTimeout(() => {
448
+ this.#pending.delete(requestId);
449
+ reject(new RemoteChannelError("channel-closed", "the sealed call timed out"));
450
+ }, REMOTE_CHANNEL_REQUEST_TIMEOUT_MS);
451
+
452
+ timer.unref();
453
+ this.#pending.set(requestId, { resolve, reject, timer });
454
+
455
+ if (signal !== undefined) {
456
+ signal.addEventListener(
457
+ "abort",
458
+ () => {
459
+ // The sealed frame may already have left: a mutation's outcome stays
460
+ // unknown (§8) — nothing is retried, nothing is assumed delivered.
461
+ if (this.#pending.delete(requestId)) {
462
+ clearTimeout(timer);
463
+ reject(signal.reason ?? new Error("aborted"));
464
+ }
465
+ },
466
+ { once: true },
467
+ );
468
+ }
469
+
470
+ try {
471
+ this.#channel.request(body as never, { mutation: body.method === "POST" });
472
+ } catch (error) {
473
+ this.#pending.delete(requestId);
474
+ clearTimeout(timer);
475
+ reject(error instanceof Error ? error : new Error("send failed"));
476
+ }
477
+ });
478
+ }
479
+
480
+ // Kept for the FE fixtures' polling loops (bounded, no busy-wait).
481
+ static readonly sleep = sleep;
482
+ }