@bom-pi/core 0.1.3 → 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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bom-pi/core",
3
- "version": "0.1.3",
3
+ "version": "0.2.0",
4
4
  "description": "Core pairing machinery for Bom Pi: ceremonies, transports, durable stores",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -15,13 +15,13 @@
15
15
  "./ingress-receiver.ts": "./src/ingress-receiver.ts",
16
16
  "./lan-pairing.ts": "./src/lan-pairing.ts",
17
17
  "./pairing-storage.ts": "./src/pairing-storage.ts",
18
+ "./relay-boundary.ts": "./src/relay-boundary.ts",
19
+ "./relay-mux-wire.ts": "./src/relay-mux-wire.ts",
20
+ "./relay-remote-channel.ts": "./src/relay-remote-channel.ts",
21
+ "./relay-remote-dispatch.ts": "./src/relay-remote-dispatch.ts",
22
+ "./relay-secure-channel.ts": "./src/relay-secure-channel.ts",
23
+ "./relay-secure-target.ts": "./src/relay-secure-target.ts",
18
24
  "./secure-transport.ts": "./src/secure-transport.ts",
19
25
  "./session-gateway.ts": "./src/session-gateway.ts"
20
- },
21
- "files": [
22
- "src/",
23
- "README.md"
24
- ],
25
- "main": "src/index.ts",
26
- "types": "src/index.ts"
26
+ }
27
27
  }
@@ -12,6 +12,7 @@ import {
12
12
  type KeyObject,
13
13
  } from "node:crypto";
14
14
  import { canonicalJson, parseCanonicalJson, type CanonicalValue } from "@bom-pi/protocol/codec.ts";
15
+ import { CLOUD_RECEIPT_DOMAIN } from "@bom-pi/protocol/receipt.ts";
15
16
  import { DAEMON_PROOF_DOMAIN } from "@bom-pi/protocol/daemon-proof.ts";
16
17
  import { fingerprintPublicKey } from "@bom-pi/protocol/identity.ts";
17
18
 
@@ -130,9 +131,9 @@ export type ConnectorProof = {
130
131
  // (duplicated literal: packages must not import apps). Leader owns single-sourcing this constant.
131
132
  const CLEANUP_REQUEST_DOMAIN = "bom-pi/connector/cleanup-request/v1";
132
133
 
133
- // Candidate X-receipt domain, byte-identical to apps/bom-cloud/server/pickup-authority.ts
134
- // (duplicated literal: packages must not import apps). Leader owns single-sourcing this constant.
135
- const RECEIPT_DOMAIN = "bom-pi/cloud-receipt/v1";
134
+ // REL-13: the X-receipt domain literal is single-sourced in @bom-pi/protocol/receipt.ts
135
+ // (imported above) and aliased here so the existing uses stay unchanged.
136
+ const RECEIPT_DOMAIN = CLOUD_RECEIPT_DOMAIN;
136
137
 
137
138
  /** §16 candidate resource limit: durable cleanup capacity reserved for active grants/memberships.
138
139
  * Admission (enroll) refuses when this reserve cannot be guaranteed; deletion/removal is NEVER
@@ -188,6 +189,59 @@ export interface CloudEndpoint {
188
189
  cleanup(old: MemberRef, stored: StoredCleanupRequest, proof: ConnectorProof): Promise<string>;
189
190
  }
190
191
 
192
+ /** §11 relay close reasons — the fixed, bounded vocabulary X may put on the wire. Duplicated
193
+ * literal of apps/bom-cloud/server/connect-wss.ts RELAY_CLOSE_REASONS (packages must not import
194
+ * apps; the leader owns single-sourcing this constant). */
195
+ export type RelayCloseReason = "overflow" | "peer-closed" | "session-ended";
196
+
197
+ /** The one bounded close notification a relayed channel ever delivers: X's channel id and a
198
+ * static reason. No payload, no diagnostics — nothing wire-derived beyond the fixed vocabulary. */
199
+ export type RelayClosedNotice = { channelId: string; reason: RelayCloseReason };
200
+
201
+ /** The exact §11/§12 routing claim B presents to open a relayed channel: the stored relation id,
202
+ * its grant epoch, both ORIGINAL membership refs and the requester→target direction. X validates
203
+ * this schema structurally against the stored relation and live topology; the authoritative §11
204
+ * re-verification happens at A's central boundary before X opens anything. */
205
+ export type RelayOpenClaim = {
206
+ relationId: string;
207
+ grantEpoch: number;
208
+ requesterMembership: MemberRef;
209
+ targetMembership: MemberRef;
210
+ direction: "requester-to-target";
211
+ };
212
+
213
+ /** The bounded, memory-only relayed-channel surface `openRelayChannel()` hands back: §16-bounded
214
+ * binary frames in both directions, one data listener, one-shot close notifications and a
215
+ * cooperative teardown. Nothing here persists — the channel lives exactly as long as the live
216
+ * session it was opened on. */
217
+ export interface CloudRelayChannel {
218
+ /** X's 32-hex channel id; echoed in every RelayClosedNotice for this channel. */
219
+ readonly channelId: string;
220
+ /** Sends one binary frame; refuses locally (static error, nothing written) when the frame
221
+ * exceeds the §16 whole-frame bound or the outbound backpressure bound. */
222
+ send(payload: Uint8Array): Promise<void>;
223
+ /** Registers THE data listener for inbound relayed frames; a second registration is refused.
224
+ * Frames arriving with no listener registered are refused, never buffered. */
225
+ onData(listener: (payload: Uint8Array) => void): void;
226
+ /** Registers a close callback; fires exactly once per channel with a static reason. */
227
+ onClose(callback: (notice: RelayClosedNotice) => void): void;
228
+ /** Cooperative teardown: sends relay-close, clears local state regardless of X's reply. */
229
+ close(): Promise<void>;
230
+ }
231
+
232
+ /** Feature-detect surface for a transport that can carry the relay lane. Old transports (old
233
+ * pinned cloud builds) simply lack these members; the connector probes with `typeof` and fails
234
+ * closed with a static error instead of assuming capability — relay needs both ends new, and
235
+ * every existing lane must stay byte-compatible (mixed-fleet rule). */
236
+ export interface RelayCapableTransport extends CloudTransport {
237
+ relayOpen(claim: RelayOpenClaim): Promise<string>;
238
+ relaySend(payload: Uint8Array): void;
239
+ relayClose(): Promise<void>;
240
+ relayChannelId(): string | null;
241
+ onRelayData(listener: (payload: Uint8Array) => void): void;
242
+ onRelayClosed(callback: (notice: RelayClosedNotice) => void): void;
243
+ }
244
+
191
245
  export class ConnectorStateError extends Error {
192
246
  constructor(message: string) {
193
247
  super(message);
@@ -238,6 +292,8 @@ const FINGERPRINT = /^[0-9a-f]{64}$/;
238
292
  const CLOUD_ID = /^cloud:[0-9a-f]{64}$/;
239
293
  const REQUEST_HASH = /^[0-9a-f]{64}$/;
240
294
  const BASE64URL = /^[A-Za-z0-9_-]+$/;
295
+ /** §11/§12 relation ids and X's relay channel ids are exactly 32 hex. */
296
+ const RELAY_ID_HEX = /^[0-9a-f]{32}$/;
241
297
 
242
298
  const b64 = (bytes: Uint8Array): string => Buffer.from(bytes).toString("base64url");
243
299
 
@@ -247,6 +303,51 @@ function validRef(ref: MemberRef): boolean {
247
303
  return ID_PATTERN.test(ref.id) && Number.isSafeInteger(ref.epoch) && ref.epoch >= 1;
248
304
  }
249
305
 
306
+ /** Static, local validation of the §11/§12 routing claim: shapes, positive grant epoch, the
307
+ * requester→target direction and distinct endpoints — everything checkable WITHOUT the wire, so
308
+ * a malformed claim never produces any traffic. X re-validates the exact schema; A's central
309
+ * boundary authoritatively re-verifies the grant itself. */
310
+ function validateRelayClaim(claim: RelayOpenClaim): void {
311
+ if (
312
+ claim === null ||
313
+ typeof claim !== "object" ||
314
+ typeof claim.relationId !== "string" ||
315
+ !RELAY_ID_HEX.test(claim.relationId)
316
+ ) {
317
+ throw new ConnectorStateError(
318
+ "Invalid relay open claim: relationId must be a 32-hex relation id",
319
+ );
320
+ }
321
+
322
+ if (
323
+ typeof claim.grantEpoch !== "number" ||
324
+ !Number.isSafeInteger(claim.grantEpoch) ||
325
+ claim.grantEpoch < 1
326
+ ) {
327
+ throw new ConnectorStateError(
328
+ "Invalid relay open claim: grantEpoch must be a positive integer",
329
+ );
330
+ }
331
+
332
+ if (!validRef(claim.requesterMembership) || !validRef(claim.targetMembership)) {
333
+ throw new ConnectorStateError(
334
+ "Invalid relay open claim: membership references are invalid",
335
+ );
336
+ }
337
+
338
+ if (claim.direction !== "requester-to-target") {
339
+ throw new ConnectorStateError(
340
+ "Invalid relay open claim: direction must be requester-to-target",
341
+ );
342
+ }
343
+
344
+ if (claim.requesterMembership.id === claim.targetMembership.id) {
345
+ throw new ConnectorStateError(
346
+ "Invalid relay open claim: relay endpoints must be distinct memberships",
347
+ );
348
+ }
349
+ }
350
+
250
351
  function refsEqual(a: MemberRef, b: MemberRef): boolean {
251
352
  return a.id === b.id && a.epoch === b.epoch;
252
353
  }
@@ -1091,6 +1192,91 @@ export class CloudConnector {
1091
1192
  }
1092
1193
  }
1093
1194
 
1195
+ /**
1196
+ * M4 lane B3: opens a relayed application channel to the relation target (A) over the CURRENT
1197
+ * live authenticated session. The §11/§12 routing claim rides X's relay-open control RPC; X
1198
+ * checks structure and live topology, then A's central boundary authoritatively re-verifies
1199
+ * the grant before anything opens — a switch-OFF refusal or any boundary denial maps onto the
1200
+ * STATIC bounded refusal error below (never the wire text). Every gate is fail-closed: the
1201
+ * connector must be ready (the cleanup-only path and every receipt lane can never reach this
1202
+ * method's transport), the credential must be unexpired, and the transport must advertise the
1203
+ * relay capability — an old pinned cloud (capability not advertised, or a transport without
1204
+ * the relay surface at all) refuses with a static error and leaves every existing lane
1205
+ * byte-identical. A replayed receipt has no path here: only the credential-authenticated
1206
+ * ready session opens relay. Nothing persists — the channel is memory-only and dies with the
1207
+ * session. Register the channel's onData/onClose before first use: unlistened inbound frames
1208
+ * are refused, never buffered.
1209
+ */
1210
+ async openRelayChannel(claim: RelayOpenClaim): Promise<CloudRelayChannel> {
1211
+ validateRelayClaim(claim);
1212
+
1213
+ return this.serialize(async () => {
1214
+ if (this.snapshot.sealed || this.statusValue === "sealed") {
1215
+ this.failSealed();
1216
+ }
1217
+
1218
+ this.applicationGate();
1219
+
1220
+ const entry = this.requireEntry();
1221
+
1222
+ if (entry.credentialExpiresAt <= this.saneNow()) {
1223
+ throw new ConnectorStateError("Credential expired; fresh enrollment required");
1224
+ }
1225
+
1226
+ const transport = this.transport;
1227
+
1228
+ if (transport === null) {
1229
+ throw new ConnectorStateError("No live connector session for application work");
1230
+ }
1231
+
1232
+ const relay = transport as Partial<RelayCapableTransport>;
1233
+
1234
+ if (
1235
+ typeof relay.relayOpen !== "function" ||
1236
+ typeof relay.relaySend !== "function" ||
1237
+ typeof relay.relayClose !== "function" ||
1238
+ typeof relay.relayChannelId !== "function" ||
1239
+ typeof relay.onRelayData !== "function" ||
1240
+ typeof relay.onRelayClosed !== "function"
1241
+ ) {
1242
+ throw new ConnectorStateError(
1243
+ "Relay is not supported by the pinned cloud transport (old cloud or relay lane absent)",
1244
+ );
1245
+ }
1246
+
1247
+ let channelId: string;
1248
+
1249
+ try {
1250
+ channelId = await relay.relayOpen(claim);
1251
+ } catch (error) {
1252
+ if (error instanceof ConnectorStateError) {
1253
+ throw error;
1254
+ }
1255
+
1256
+ if (error instanceof EndpointError) {
1257
+ throw new ConnectorStateError(
1258
+ `Relay open refused by the cloud or the target (status ${error.status})`,
1259
+ );
1260
+ }
1261
+
1262
+ throw error;
1263
+ }
1264
+
1265
+ if (typeof channelId !== "string" || !RELAY_ID_HEX.test(channelId)) {
1266
+ throw new ConnectorStateError("Malformed relay channel id from cloud");
1267
+ }
1268
+
1269
+ return {
1270
+ channelId,
1271
+ send: async (payload: Uint8Array) => relay.relaySend!(payload),
1272
+ onData: (listener: (payload: Uint8Array) => void) => relay.onRelayData!(listener),
1273
+ onClose: (callback: (notice: RelayClosedNotice) => void) =>
1274
+ relay.onRelayClosed!(callback),
1275
+ close: async () => relay.relayClose!(),
1276
+ };
1277
+ });
1278
+ }
1279
+
1094
1280
  /**
1095
1281
  * One cancellation-first reconciliation: open the pinned outbound transport, prove the pinned
1096
1282
  * identity with a fresh membership-bound challenge, process removal (signed old-membership