@bom-pi/core 0.1.3 → 0.1.4
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 +4 -9
- package/src/cloud-connector.ts +185 -0
- package/src/cloud-wss-transport.ts +309 -4
- package/src/pairing-storage.ts +233 -21
- package/src/relay-boundary.ts +499 -0
- package/src/secure-transport.ts +116 -11
- package/src/session-gateway.ts +151 -13
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@bom-pi/core",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.4",
|
|
4
4
|
"description": "Core pairing machinery for Bom Pi: ceremonies, transports, durable stores",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"license": "MIT",
|
|
@@ -16,12 +16,7 @@
|
|
|
16
16
|
"./lan-pairing.ts": "./src/lan-pairing.ts",
|
|
17
17
|
"./pairing-storage.ts": "./src/pairing-storage.ts",
|
|
18
18
|
"./secure-transport.ts": "./src/secure-transport.ts",
|
|
19
|
-
"./session-gateway.ts": "./src/session-gateway.ts"
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
"src/",
|
|
23
|
-
"README.md"
|
|
24
|
-
],
|
|
25
|
-
"main": "src/index.ts",
|
|
26
|
-
"types": "src/index.ts"
|
|
19
|
+
"./session-gateway.ts": "./src/session-gateway.ts",
|
|
20
|
+
"./relay-boundary.ts": "./src/relay-boundary.ts"
|
|
21
|
+
}
|
|
27
22
|
}
|
package/src/cloud-connector.ts
CHANGED
|
@@ -188,6 +188,59 @@ export interface CloudEndpoint {
|
|
|
188
188
|
cleanup(old: MemberRef, stored: StoredCleanupRequest, proof: ConnectorProof): Promise<string>;
|
|
189
189
|
}
|
|
190
190
|
|
|
191
|
+
/** §11 relay close reasons — the fixed, bounded vocabulary X may put on the wire. Duplicated
|
|
192
|
+
* literal of apps/bom-cloud/server/connect-wss.ts RELAY_CLOSE_REASONS (packages must not import
|
|
193
|
+
* apps; the leader owns single-sourcing this constant). */
|
|
194
|
+
export type RelayCloseReason = "overflow" | "peer-closed" | "session-ended";
|
|
195
|
+
|
|
196
|
+
/** The one bounded close notification a relayed channel ever delivers: X's channel id and a
|
|
197
|
+
* static reason. No payload, no diagnostics — nothing wire-derived beyond the fixed vocabulary. */
|
|
198
|
+
export type RelayClosedNotice = { channelId: string; reason: RelayCloseReason };
|
|
199
|
+
|
|
200
|
+
/** The exact §11/§12 routing claim B presents to open a relayed channel: the stored relation id,
|
|
201
|
+
* its grant epoch, both ORIGINAL membership refs and the requester→target direction. X validates
|
|
202
|
+
* this schema structurally against the stored relation and live topology; the authoritative §11
|
|
203
|
+
* re-verification happens at A's central boundary before X opens anything. */
|
|
204
|
+
export type RelayOpenClaim = {
|
|
205
|
+
relationId: string;
|
|
206
|
+
grantEpoch: number;
|
|
207
|
+
requesterMembership: MemberRef;
|
|
208
|
+
targetMembership: MemberRef;
|
|
209
|
+
direction: "requester-to-target";
|
|
210
|
+
};
|
|
211
|
+
|
|
212
|
+
/** The bounded, memory-only relayed-channel surface `openRelayChannel()` hands back: §16-bounded
|
|
213
|
+
* binary frames in both directions, one data listener, one-shot close notifications and a
|
|
214
|
+
* cooperative teardown. Nothing here persists — the channel lives exactly as long as the live
|
|
215
|
+
* session it was opened on. */
|
|
216
|
+
export interface CloudRelayChannel {
|
|
217
|
+
/** X's 32-hex channel id; echoed in every RelayClosedNotice for this channel. */
|
|
218
|
+
readonly channelId: string;
|
|
219
|
+
/** Sends one binary frame; refuses locally (static error, nothing written) when the frame
|
|
220
|
+
* exceeds the §16 whole-frame bound or the outbound backpressure bound. */
|
|
221
|
+
send(payload: Uint8Array): Promise<void>;
|
|
222
|
+
/** Registers THE data listener for inbound relayed frames; a second registration is refused.
|
|
223
|
+
* Frames arriving with no listener registered are refused, never buffered. */
|
|
224
|
+
onData(listener: (payload: Uint8Array) => void): void;
|
|
225
|
+
/** Registers a close callback; fires exactly once per channel with a static reason. */
|
|
226
|
+
onClose(callback: (notice: RelayClosedNotice) => void): void;
|
|
227
|
+
/** Cooperative teardown: sends relay-close, clears local state regardless of X's reply. */
|
|
228
|
+
close(): Promise<void>;
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
/** Feature-detect surface for a transport that can carry the relay lane. Old transports (old
|
|
232
|
+
* pinned cloud builds) simply lack these members; the connector probes with `typeof` and fails
|
|
233
|
+
* closed with a static error instead of assuming capability — relay needs both ends new, and
|
|
234
|
+
* every existing lane must stay byte-compatible (mixed-fleet rule). */
|
|
235
|
+
export interface RelayCapableTransport extends CloudTransport {
|
|
236
|
+
relayOpen(claim: RelayOpenClaim): Promise<string>;
|
|
237
|
+
relaySend(payload: Uint8Array): void;
|
|
238
|
+
relayClose(): Promise<void>;
|
|
239
|
+
relayChannelId(): string | null;
|
|
240
|
+
onRelayData(listener: (payload: Uint8Array) => void): void;
|
|
241
|
+
onRelayClosed(callback: (notice: RelayClosedNotice) => void): void;
|
|
242
|
+
}
|
|
243
|
+
|
|
191
244
|
export class ConnectorStateError extends Error {
|
|
192
245
|
constructor(message: string) {
|
|
193
246
|
super(message);
|
|
@@ -238,6 +291,8 @@ const FINGERPRINT = /^[0-9a-f]{64}$/;
|
|
|
238
291
|
const CLOUD_ID = /^cloud:[0-9a-f]{64}$/;
|
|
239
292
|
const REQUEST_HASH = /^[0-9a-f]{64}$/;
|
|
240
293
|
const BASE64URL = /^[A-Za-z0-9_-]+$/;
|
|
294
|
+
/** §11/§12 relation ids and X's relay channel ids are exactly 32 hex. */
|
|
295
|
+
const RELAY_ID_HEX = /^[0-9a-f]{32}$/;
|
|
241
296
|
|
|
242
297
|
const b64 = (bytes: Uint8Array): string => Buffer.from(bytes).toString("base64url");
|
|
243
298
|
|
|
@@ -247,6 +302,51 @@ function validRef(ref: MemberRef): boolean {
|
|
|
247
302
|
return ID_PATTERN.test(ref.id) && Number.isSafeInteger(ref.epoch) && ref.epoch >= 1;
|
|
248
303
|
}
|
|
249
304
|
|
|
305
|
+
/** Static, local validation of the §11/§12 routing claim: shapes, positive grant epoch, the
|
|
306
|
+
* requester→target direction and distinct endpoints — everything checkable WITHOUT the wire, so
|
|
307
|
+
* a malformed claim never produces any traffic. X re-validates the exact schema; A's central
|
|
308
|
+
* boundary authoritatively re-verifies the grant itself. */
|
|
309
|
+
function validateRelayClaim(claim: RelayOpenClaim): void {
|
|
310
|
+
if (
|
|
311
|
+
claim === null ||
|
|
312
|
+
typeof claim !== "object" ||
|
|
313
|
+
typeof claim.relationId !== "string" ||
|
|
314
|
+
!RELAY_ID_HEX.test(claim.relationId)
|
|
315
|
+
) {
|
|
316
|
+
throw new ConnectorStateError(
|
|
317
|
+
"Invalid relay open claim: relationId must be a 32-hex relation id",
|
|
318
|
+
);
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
if (
|
|
322
|
+
typeof claim.grantEpoch !== "number" ||
|
|
323
|
+
!Number.isSafeInteger(claim.grantEpoch) ||
|
|
324
|
+
claim.grantEpoch < 1
|
|
325
|
+
) {
|
|
326
|
+
throw new ConnectorStateError(
|
|
327
|
+
"Invalid relay open claim: grantEpoch must be a positive integer",
|
|
328
|
+
);
|
|
329
|
+
}
|
|
330
|
+
|
|
331
|
+
if (!validRef(claim.requesterMembership) || !validRef(claim.targetMembership)) {
|
|
332
|
+
throw new ConnectorStateError(
|
|
333
|
+
"Invalid relay open claim: membership references are invalid",
|
|
334
|
+
);
|
|
335
|
+
}
|
|
336
|
+
|
|
337
|
+
if (claim.direction !== "requester-to-target") {
|
|
338
|
+
throw new ConnectorStateError(
|
|
339
|
+
"Invalid relay open claim: direction must be requester-to-target",
|
|
340
|
+
);
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
if (claim.requesterMembership.id === claim.targetMembership.id) {
|
|
344
|
+
throw new ConnectorStateError(
|
|
345
|
+
"Invalid relay open claim: relay endpoints must be distinct memberships",
|
|
346
|
+
);
|
|
347
|
+
}
|
|
348
|
+
}
|
|
349
|
+
|
|
250
350
|
function refsEqual(a: MemberRef, b: MemberRef): boolean {
|
|
251
351
|
return a.id === b.id && a.epoch === b.epoch;
|
|
252
352
|
}
|
|
@@ -1091,6 +1191,91 @@ export class CloudConnector {
|
|
|
1091
1191
|
}
|
|
1092
1192
|
}
|
|
1093
1193
|
|
|
1194
|
+
/**
|
|
1195
|
+
* M4 lane B3: opens a relayed application channel to the relation target (A) over the CURRENT
|
|
1196
|
+
* live authenticated session. The §11/§12 routing claim rides X's relay-open control RPC; X
|
|
1197
|
+
* checks structure and live topology, then A's central boundary authoritatively re-verifies
|
|
1198
|
+
* the grant before anything opens — a switch-OFF refusal or any boundary denial maps onto the
|
|
1199
|
+
* STATIC bounded refusal error below (never the wire text). Every gate is fail-closed: the
|
|
1200
|
+
* connector must be ready (the cleanup-only path and every receipt lane can never reach this
|
|
1201
|
+
* method's transport), the credential must be unexpired, and the transport must advertise the
|
|
1202
|
+
* relay capability — an old pinned cloud (capability not advertised, or a transport without
|
|
1203
|
+
* the relay surface at all) refuses with a static error and leaves every existing lane
|
|
1204
|
+
* byte-identical. A replayed receipt has no path here: only the credential-authenticated
|
|
1205
|
+
* ready session opens relay. Nothing persists — the channel is memory-only and dies with the
|
|
1206
|
+
* session. Register the channel's onData/onClose before first use: unlistened inbound frames
|
|
1207
|
+
* are refused, never buffered.
|
|
1208
|
+
*/
|
|
1209
|
+
async openRelayChannel(claim: RelayOpenClaim): Promise<CloudRelayChannel> {
|
|
1210
|
+
validateRelayClaim(claim);
|
|
1211
|
+
|
|
1212
|
+
return this.serialize(async () => {
|
|
1213
|
+
if (this.snapshot.sealed || this.statusValue === "sealed") {
|
|
1214
|
+
this.failSealed();
|
|
1215
|
+
}
|
|
1216
|
+
|
|
1217
|
+
this.applicationGate();
|
|
1218
|
+
|
|
1219
|
+
const entry = this.requireEntry();
|
|
1220
|
+
|
|
1221
|
+
if (entry.credentialExpiresAt <= this.saneNow()) {
|
|
1222
|
+
throw new ConnectorStateError("Credential expired; fresh enrollment required");
|
|
1223
|
+
}
|
|
1224
|
+
|
|
1225
|
+
const transport = this.transport;
|
|
1226
|
+
|
|
1227
|
+
if (transport === null) {
|
|
1228
|
+
throw new ConnectorStateError("No live connector session for application work");
|
|
1229
|
+
}
|
|
1230
|
+
|
|
1231
|
+
const relay = transport as Partial<RelayCapableTransport>;
|
|
1232
|
+
|
|
1233
|
+
if (
|
|
1234
|
+
typeof relay.relayOpen !== "function" ||
|
|
1235
|
+
typeof relay.relaySend !== "function" ||
|
|
1236
|
+
typeof relay.relayClose !== "function" ||
|
|
1237
|
+
typeof relay.relayChannelId !== "function" ||
|
|
1238
|
+
typeof relay.onRelayData !== "function" ||
|
|
1239
|
+
typeof relay.onRelayClosed !== "function"
|
|
1240
|
+
) {
|
|
1241
|
+
throw new ConnectorStateError(
|
|
1242
|
+
"Relay is not supported by the pinned cloud transport (old cloud or relay lane absent)",
|
|
1243
|
+
);
|
|
1244
|
+
}
|
|
1245
|
+
|
|
1246
|
+
let channelId: string;
|
|
1247
|
+
|
|
1248
|
+
try {
|
|
1249
|
+
channelId = await relay.relayOpen(claim);
|
|
1250
|
+
} catch (error) {
|
|
1251
|
+
if (error instanceof ConnectorStateError) {
|
|
1252
|
+
throw error;
|
|
1253
|
+
}
|
|
1254
|
+
|
|
1255
|
+
if (error instanceof EndpointError) {
|
|
1256
|
+
throw new ConnectorStateError(
|
|
1257
|
+
`Relay open refused by the cloud or the target (status ${error.status})`,
|
|
1258
|
+
);
|
|
1259
|
+
}
|
|
1260
|
+
|
|
1261
|
+
throw error;
|
|
1262
|
+
}
|
|
1263
|
+
|
|
1264
|
+
if (typeof channelId !== "string" || !RELAY_ID_HEX.test(channelId)) {
|
|
1265
|
+
throw new ConnectorStateError("Malformed relay channel id from cloud");
|
|
1266
|
+
}
|
|
1267
|
+
|
|
1268
|
+
return {
|
|
1269
|
+
channelId,
|
|
1270
|
+
send: async (payload: Uint8Array) => relay.relaySend!(payload),
|
|
1271
|
+
onData: (listener: (payload: Uint8Array) => void) => relay.onRelayData!(listener),
|
|
1272
|
+
onClose: (callback: (notice: RelayClosedNotice) => void) =>
|
|
1273
|
+
relay.onRelayClosed!(callback),
|
|
1274
|
+
close: async () => relay.relayClose!(),
|
|
1275
|
+
};
|
|
1276
|
+
});
|
|
1277
|
+
}
|
|
1278
|
+
|
|
1094
1279
|
/**
|
|
1095
1280
|
* One cancellation-first reconciliation: open the pinned outbound transport, prove the pinned
|
|
1096
1281
|
* identity with a fresh membership-bound challenge, process removal (signed old-membership
|
|
@@ -28,8 +28,20 @@
|
|
|
28
28
|
* booleans. The envelope is the
|
|
29
29
|
* entire encoded wire frame at this hop, so a base64url seam payload admits slightly less than
|
|
30
30
|
* the 1 MiB data bound — a conservative consequence of §16's whole-frame limit, not a relaxation.
|
|
31
|
-
* Cloud-initiated RPC requests are refused locally
|
|
32
|
-
*
|
|
31
|
+
* Cloud-initiated RPC requests are refused locally except the §7 pair-delivery surface
|
|
32
|
+
* (`onCloudDelivery`) — and, since M4 lane B3, X's `relay-close` channel notifications, which
|
|
33
|
+
* dispose the local relay channel state (the wired delivery handler still sees the payload).
|
|
34
|
+
*
|
|
35
|
+
* M4 lane B3 adds the CLIENT side of the relay lane: `relayOpen` probes X's advertised capability
|
|
36
|
+
* with an authenticated `relay-caps` RPC and fails closed on an old cloud (static error, no
|
|
37
|
+
* relay-open frame ever leaves, every existing lane byte-identical). A successful `relay-open`
|
|
38
|
+
* — claim = relation id, grant epoch, both membership refs, requester→target direction; X checks
|
|
39
|
+
* topology and A's central boundary authoritatively re-verifies the grant — stores the channel id
|
|
40
|
+
* and admits §16-bounded binary frames (1 MiB whole-frame gate, empty refused, backpressure
|
|
41
|
+
* bound, oversize refused locally before any write) via `relaySend`/`onRelayData`, with one
|
|
42
|
+
* bounded close notification on teardown (peer notification, local close, or connection loss →
|
|
43
|
+
* `onRelayClosed`). The channel is memory-only: it dies with the connection and nothing about it
|
|
44
|
+
* persists. */
|
|
33
45
|
import { createPublicKey, randomBytes, verify, type KeyObject } from "node:crypto";
|
|
34
46
|
import {
|
|
35
47
|
canonicalJson,
|
|
@@ -50,6 +62,10 @@ import {
|
|
|
50
62
|
type PinnedCloud,
|
|
51
63
|
type ReceiptExpectation,
|
|
52
64
|
type ReceiptVerifier,
|
|
65
|
+
type RelayCapableTransport,
|
|
66
|
+
type RelayClosedNotice,
|
|
67
|
+
type RelayCloseReason,
|
|
68
|
+
type RelayOpenClaim,
|
|
53
69
|
type StoredCleanupRequest,
|
|
54
70
|
} from "./cloud-connector.ts";
|
|
55
71
|
|
|
@@ -66,6 +82,21 @@ const METHOD_PAIR_OFFER = "pair-offer";
|
|
|
66
82
|
const METHOD_PAIR_REDEEM = "pair-redeem";
|
|
67
83
|
/** X → daemon delivered control request (§7 prepare/provisional over the live connector). */
|
|
68
84
|
const METHOD_PAIR_DELIVER = "pair-deliver";
|
|
85
|
+
/** M4 lane B3 relay methods: capability probe, channel open, cooperative teardown. */
|
|
86
|
+
const METHOD_RELAY_CAPS = "relay-caps";
|
|
87
|
+
const METHOD_RELAY_OPEN = "relay-open";
|
|
88
|
+
const METHOD_RELAY_CLOSE = "relay-close";
|
|
89
|
+
|
|
90
|
+
/** The fixed close-reason vocabulary a relay notification may carry. Duplicated literal of
|
|
91
|
+
* apps/bom-cloud/server/connect-wss.ts RELAY_CLOSE_REASONS (packages must not import apps). */
|
|
92
|
+
const RELAY_CLOSE_REASONS: ReadonlySet<string> = new Set([
|
|
93
|
+
"overflow",
|
|
94
|
+
"peer-closed",
|
|
95
|
+
"session-ended",
|
|
96
|
+
]);
|
|
97
|
+
|
|
98
|
+
/** §11/§12 relation ids and X's relay channel ids are exactly 32 hex. */
|
|
99
|
+
const RELAY_ID_HEX = /^[0-9a-f]{32}$/;
|
|
69
100
|
|
|
70
101
|
/** §16 candidate whole-encoded-wire-frame bounds, per ingress class. */
|
|
71
102
|
const WIRE_LIMIT_BY_CLASS: Record<IngressClass, number> = {
|
|
@@ -298,12 +329,49 @@ function storedToWire(stored: StoredCleanupRequest): CanonicalValue {
|
|
|
298
329
|
return { request: stored.request, signature: stored.signature };
|
|
299
330
|
}
|
|
300
331
|
|
|
332
|
+
function isRelayCloseReason(value: CanonicalValue | undefined): value is RelayCloseReason {
|
|
333
|
+
return typeof value === "string" && RELAY_CLOSE_REASONS.has(value);
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
/** Structural validation of the §11/§12 routing claim before any wire activity: exactly the five
|
|
337
|
+
* schema fields, a 32-hex relation id, a positive grant epoch and the requester→target direction.
|
|
338
|
+
* Membership refs go through the same strict ref shape every cloud RPC uses. X re-validates the
|
|
339
|
+
* exact schema against the stored relation and live topology; A's central boundary authoritatively
|
|
340
|
+
* re-verifies the grant before anything opens. */
|
|
341
|
+
function relayClaimToWire(claim: RelayOpenClaim): { [key: string]: CanonicalValue } {
|
|
342
|
+
if (
|
|
343
|
+
!exactKeys(claim, [
|
|
344
|
+
"relationId",
|
|
345
|
+
"grantEpoch",
|
|
346
|
+
"requesterMembership",
|
|
347
|
+
"targetMembership",
|
|
348
|
+
"direction",
|
|
349
|
+
]) ||
|
|
350
|
+
typeof claim.relationId !== "string" ||
|
|
351
|
+
!RELAY_ID_HEX.test(claim.relationId) ||
|
|
352
|
+
typeof claim.grantEpoch !== "number" ||
|
|
353
|
+
!Number.isSafeInteger(claim.grantEpoch) ||
|
|
354
|
+
claim.grantEpoch < 1 ||
|
|
355
|
+
claim.direction !== "requester-to-target"
|
|
356
|
+
) {
|
|
357
|
+
throw new ConnectorStateError("Invalid relay open claim shape");
|
|
358
|
+
}
|
|
359
|
+
|
|
360
|
+
return {
|
|
361
|
+
relationId: claim.relationId,
|
|
362
|
+
grantEpoch: claim.grantEpoch,
|
|
363
|
+
requesterMembership: refToWire(claim.requesterMembership),
|
|
364
|
+
targetMembership: refToWire(claim.targetMembership),
|
|
365
|
+
direction: claim.direction,
|
|
366
|
+
};
|
|
367
|
+
}
|
|
368
|
+
|
|
301
369
|
/**
|
|
302
370
|
* The concrete pinned-cloud WSS transport: one CloudTransport + CloudEndpoint over one global
|
|
303
371
|
* WebSocket connection. One instance serves exactly one open() — the connector builds a fresh
|
|
304
372
|
* transport per reconcile attempt, so no state ever resurrects across connection generations.
|
|
305
373
|
*/
|
|
306
|
-
export class CloudWssTransport implements CloudTransport, CloudEndpoint {
|
|
374
|
+
export class CloudWssTransport implements CloudTransport, CloudEndpoint, RelayCapableTransport {
|
|
307
375
|
private readonly pinned: PinnedCloud;
|
|
308
376
|
private readonly options: CloudWssTransportOptions;
|
|
309
377
|
private readonly rpcTimeoutMs: number;
|
|
@@ -329,6 +397,16 @@ export class CloudWssTransport implements CloudTransport, CloudEndpoint {
|
|
|
329
397
|
private generationValue: number | null = null;
|
|
330
398
|
private refusedFrames = 0;
|
|
331
399
|
private seamErrors = 0;
|
|
400
|
+
/** M4 lane B3: the open relay channel's id on THIS connection (memory-only, dies with the
|
|
401
|
+
* connection), its single data listener, and its close callbacks (cleared on teardown). */
|
|
402
|
+
private relayChannelIdValue: string | null = null;
|
|
403
|
+
|
|
404
|
+
/** M4 target-side channel state: X adopts A's session into a relay channel via the
|
|
405
|
+
* relay-open pair-delivery (A never learns the channel id — X routes raw frames), so the
|
|
406
|
+
* target keeps its own adoption flag rather than a requester-side channel id. */
|
|
407
|
+
private relayTargetActive = false;
|
|
408
|
+
private relayDataListener: ((payload: Uint8Array) => void) | null = null;
|
|
409
|
+
private relayClosedCallbacks: ((notice: RelayClosedNotice) => void)[] = [];
|
|
332
410
|
|
|
333
411
|
constructor(input: { pinned: PinnedCloud; options?: CloudWssTransportOptions }) {
|
|
334
412
|
this.pinned = input.pinned;
|
|
@@ -365,6 +443,183 @@ export class CloudWssTransport implements CloudTransport, CloudEndpoint {
|
|
|
365
443
|
return this.generationValue;
|
|
366
444
|
}
|
|
367
445
|
|
|
446
|
+
/** The open relay channel's id on THIS connection, or null while none is open. */
|
|
447
|
+
relayChannelId(): string | null {
|
|
448
|
+
return this.relayChannelIdValue;
|
|
449
|
+
}
|
|
450
|
+
|
|
451
|
+
/** M4 target-side adoption (§12): the daemon accepted X's relay-open delivery, so this
|
|
452
|
+
* connection now carries relayed binary frames for exactly one channel. Mirrors the
|
|
453
|
+
* requester-side guards: a second adoption is refused, and every relay frame bound below
|
|
454
|
+
* (inbound/outbound/listener) accepts EITHER the requester channel or target adoption. */
|
|
455
|
+
adoptRelayTarget(): void {
|
|
456
|
+
if (this.relayChannelIdValue !== null || this.relayTargetActive) {
|
|
457
|
+
throw new ConnectorStateError("Relay channel already open on this transport");
|
|
458
|
+
}
|
|
459
|
+
|
|
460
|
+
this.relayTargetActive = true;
|
|
461
|
+
}
|
|
462
|
+
|
|
463
|
+
/** Target-side teardown: clears the adoption and fires the registered close callbacks
|
|
464
|
+
* exactly once. Safe to call when nothing is adopted. */
|
|
465
|
+
releaseRelayTarget(): void {
|
|
466
|
+
if (this.relayTargetActive) {
|
|
467
|
+
this.disposeRelayChannel("peer-closed");
|
|
468
|
+
}
|
|
469
|
+
}
|
|
470
|
+
|
|
471
|
+
/**
|
|
472
|
+
* M4 lane B3: opens the relayed application channel toward the relation target. Capability
|
|
473
|
+
* is probed FIRST (authenticated `relay-caps`): an old pinned cloud that does not know the
|
|
474
|
+
* method answers a failure, and the open fails closed with the static capability error — no
|
|
475
|
+
* relay-open frame ever leaves, and every existing lane is untouched. The claim is validated
|
|
476
|
+
* structurally before any wire activity; X then checks topology and forwards the exact claims
|
|
477
|
+
* to A's central boundary, which authoritatively re-verifies the grant before the channel id
|
|
478
|
+
* is issued (§11/§12 — this transport performs NO authorization of its own).
|
|
479
|
+
*/
|
|
480
|
+
async relayOpen(claim: RelayOpenClaim): Promise<string> {
|
|
481
|
+
this.requireOpenSocket();
|
|
482
|
+
|
|
483
|
+
if (this.relayChannelIdValue !== null) {
|
|
484
|
+
throw new ConnectorStateError("Relay channel already open on this transport");
|
|
485
|
+
}
|
|
486
|
+
|
|
487
|
+
const claimBody = relayClaimToWire(claim);
|
|
488
|
+
let caps: CanonicalValue;
|
|
489
|
+
|
|
490
|
+
try {
|
|
491
|
+
caps = await this.rpc(METHOD_RELAY_CAPS, {});
|
|
492
|
+
} catch {
|
|
493
|
+
// Any probe failure — unknown method on an old cloud, transient 503, deadline — fails
|
|
494
|
+
// the open closed with the same static error: this client never infers capability
|
|
495
|
+
// from wire text, so an old X and an unreachable one are indistinguishable here and
|
|
496
|
+
// both refuse closed (no relay-open frame ever leaves on a failed probe).
|
|
497
|
+
throw new ConnectorStateError("Relay capability not advertised by the cloud");
|
|
498
|
+
}
|
|
499
|
+
|
|
500
|
+
if (!isPlainObject(caps) || !exactKeys(caps, ["relay"]) || caps.relay !== 1) {
|
|
501
|
+
throw new ConnectorStateError("Relay capability not advertised by the cloud");
|
|
502
|
+
}
|
|
503
|
+
|
|
504
|
+
const result = await this.rpc(METHOD_RELAY_OPEN, { d: claimBody });
|
|
505
|
+
const channelId = isPlainObject(result) ? result.channel : undefined;
|
|
506
|
+
|
|
507
|
+
if (typeof channelId !== "string" || !RELAY_ID_HEX.test(channelId)) {
|
|
508
|
+
throw new ConnectorStateError("Malformed relay channel id from cloud");
|
|
509
|
+
}
|
|
510
|
+
|
|
511
|
+
this.relayChannelIdValue = channelId;
|
|
512
|
+
|
|
513
|
+
return channelId;
|
|
514
|
+
}
|
|
515
|
+
|
|
516
|
+
/** Sends one §16-bounded binary relay frame on the open channel; oversize or empty payloads
|
|
517
|
+
* are refused locally BEFORE any write, and the outbound backpressure bound applies exactly
|
|
518
|
+
* like every other send. Binary frames are only legal on this profile while a relay channel
|
|
519
|
+
* is open — anything else stays a refused protocol violation, byte-identical to pre-relay. */
|
|
520
|
+
relaySend(payload: Uint8Array): void {
|
|
521
|
+
const ws = this.requireOpenSocket();
|
|
522
|
+
|
|
523
|
+
if (this.relayChannelIdValue === null && !this.relayTargetActive) {
|
|
524
|
+
throw new ConnectorStateError("No relay channel is open");
|
|
525
|
+
}
|
|
526
|
+
|
|
527
|
+
const bytes = payload instanceof Uint8Array ? payload : null;
|
|
528
|
+
|
|
529
|
+
if (bytes === null || bytes.length === 0) {
|
|
530
|
+
throw new ConnectorStateError("Relay data frames must not be empty");
|
|
531
|
+
}
|
|
532
|
+
|
|
533
|
+
if (bytes.length > MAX_DATA_FRAME_BYTES) {
|
|
534
|
+
throw new ConnectorStateError(
|
|
535
|
+
`Relay data frame exceeds the ${MAX_DATA_FRAME_BYTES}-byte whole-frame wire bound; refused before send`,
|
|
536
|
+
);
|
|
537
|
+
}
|
|
538
|
+
|
|
539
|
+
if (ws.bufferedAmount + bytes.length > this.maxBufferedBytes) {
|
|
540
|
+
throw new EndpointError(503, "Cloud WSS outbound backpressure bound reached");
|
|
541
|
+
}
|
|
542
|
+
|
|
543
|
+
try {
|
|
544
|
+
// A fresh ArrayBuffer-backed view: WebSocket.send requires BufferSource over a plain
|
|
545
|
+
// ArrayBuffer, and the one bounded copy keeps the wire type honest (≤ 1 MiB).
|
|
546
|
+
ws.send(Uint8Array.from(bytes));
|
|
547
|
+
} catch {
|
|
548
|
+
throw new EndpointError(503, "Cloud WSS send failed");
|
|
549
|
+
}
|
|
550
|
+
}
|
|
551
|
+
|
|
552
|
+
/** Registers THE inbound relay-data listener (a second registration is refused: ambiguity
|
|
553
|
+
* about who consumes relayed frames is what fail-closed wiring must not allow). Frames that
|
|
554
|
+
* arrive with no listener registered are refused and counted, never buffered. */
|
|
555
|
+
onRelayData(listener: (payload: Uint8Array) => void): void {
|
|
556
|
+
if (this.relayChannelIdValue === null && !this.relayTargetActive) {
|
|
557
|
+
throw new ConnectorStateError("No relay channel is open");
|
|
558
|
+
}
|
|
559
|
+
|
|
560
|
+
if (this.relayDataListener !== null) {
|
|
561
|
+
throw new ConnectorStateError("Relay data listener already registered");
|
|
562
|
+
}
|
|
563
|
+
|
|
564
|
+
this.relayDataListener = listener;
|
|
565
|
+
}
|
|
566
|
+
|
|
567
|
+
/** Registers a relay-close callback; fires exactly once, when THIS channel is torn down
|
|
568
|
+
* (peer notification, local close, or connection loss). */
|
|
569
|
+
onRelayClosed(callback: (notice: RelayClosedNotice) => void): void {
|
|
570
|
+
if (this.relayChannelIdValue === null && !this.relayTargetActive) {
|
|
571
|
+
throw new ConnectorStateError("No relay channel is open");
|
|
572
|
+
}
|
|
573
|
+
|
|
574
|
+
this.relayClosedCallbacks.push(callback);
|
|
575
|
+
}
|
|
576
|
+
|
|
577
|
+
/** Cooperative teardown: the relay-close RPC is best effort (X may have already disposed the
|
|
578
|
+
* channel), and the local state clears either way with the one bounded close notification. */
|
|
579
|
+
async relayClose(): Promise<void> {
|
|
580
|
+
const channelId = this.relayChannelIdValue;
|
|
581
|
+
|
|
582
|
+
if (channelId === null) {
|
|
583
|
+
throw new ConnectorStateError("No relay channel is open");
|
|
584
|
+
}
|
|
585
|
+
|
|
586
|
+
try {
|
|
587
|
+
await this.rpc(METHOD_RELAY_CLOSE, { d: { channel: channelId } });
|
|
588
|
+
} catch {
|
|
589
|
+
// X may have already torn the channel down (peer ended, session rotated): the local
|
|
590
|
+
// channel is gone either way — clearing here is the fail-closed path.
|
|
591
|
+
}
|
|
592
|
+
|
|
593
|
+
this.disposeRelayChannel("peer-closed");
|
|
594
|
+
}
|
|
595
|
+
|
|
596
|
+
/** Tears the channel down exactly once: both listener slots cleared, every registered close
|
|
597
|
+
* callback fired with the static reason. A no-op when no channel is open — which includes
|
|
598
|
+
* the TARGET-side adoption (A never holds a channel id; X routes raw frames), so the
|
|
599
|
+
* guard must consider BOTH the requester channel and the target flag. */
|
|
600
|
+
private disposeRelayChannel(reason: RelayCloseReason): void {
|
|
601
|
+
const channelId = this.relayChannelIdValue;
|
|
602
|
+
|
|
603
|
+
if (channelId === null && !this.relayTargetActive) {
|
|
604
|
+
return;
|
|
605
|
+
}
|
|
606
|
+
|
|
607
|
+
this.relayChannelIdValue = null;
|
|
608
|
+
this.relayTargetActive = false;
|
|
609
|
+
this.relayDataListener = null;
|
|
610
|
+
|
|
611
|
+
const callbacks = this.relayClosedCallbacks.splice(0);
|
|
612
|
+
|
|
613
|
+
for (const callback of callbacks) {
|
|
614
|
+
try {
|
|
615
|
+
callback({ channelId: channelId ?? "target", reason });
|
|
616
|
+
} catch {
|
|
617
|
+
// A close listener must not break the teardown path; the channel is gone either
|
|
618
|
+
// way, and the connection-level onClosed path is unaffected.
|
|
619
|
+
}
|
|
620
|
+
}
|
|
621
|
+
}
|
|
622
|
+
|
|
368
623
|
/**
|
|
369
624
|
* Registers the ONLY cloud-initiated control surface this client will answer: X's §7 pair
|
|
370
625
|
* deliveries (prepare/provisional). No other X-initiated request is ever answered — anything
|
|
@@ -664,6 +919,8 @@ export class CloudWssTransport implements CloudTransport, CloudEndpoint {
|
|
|
664
919
|
|
|
665
920
|
this.closedByUs = true;
|
|
666
921
|
this.failPending(new EndpointError(503, "Cloud transport closed locally"));
|
|
922
|
+
// An open relay channel dies with the connection it was opened on (memory-only, §16).
|
|
923
|
+
this.disposeRelayChannel("session-ended");
|
|
667
924
|
|
|
668
925
|
if (this.openWait !== null) {
|
|
669
926
|
// A close() during opening fails the pending open instead of leaving it hanging, and
|
|
@@ -944,6 +1201,8 @@ export class CloudWssTransport implements CloudTransport, CloudEndpoint {
|
|
|
944
1201
|
* close settles close(), everything else is connection loss and fires onClosed exactly once. */
|
|
945
1202
|
private adoptClosed(): void {
|
|
946
1203
|
this.failPending(new EndpointError(503, "Cloud connection lost"));
|
|
1204
|
+
// The relay channel (if any) dies with the connection, before the loss callbacks fire.
|
|
1205
|
+
this.disposeRelayChannel("session-ended");
|
|
947
1206
|
this.state = "closed";
|
|
948
1207
|
|
|
949
1208
|
const ws = this.ws;
|
|
@@ -1010,6 +1269,21 @@ export class CloudWssTransport implements CloudTransport, CloudEndpoint {
|
|
|
1010
1269
|
if (requestShape) {
|
|
1011
1270
|
const payload = envelope.d;
|
|
1012
1271
|
|
|
1272
|
+
// M4 B3: X's relay-close notification rides the pair-delivery path. When it matches
|
|
1273
|
+
// THIS connection's open channel, the local channel state is disposed here (so the
|
|
1274
|
+
// bounded close event fires even with no delivery handler wired); everything else —
|
|
1275
|
+
// stray ids, unknown types, the handler's reply semantics — stays exactly as before.
|
|
1276
|
+
if (
|
|
1277
|
+
envelope.m === METHOD_PAIR_DELIVER &&
|
|
1278
|
+
isPlainObject(payload) &&
|
|
1279
|
+
payload.type === "relay-close" &&
|
|
1280
|
+
this.relayChannelIdValue !== null &&
|
|
1281
|
+
payload.channel === this.relayChannelIdValue &&
|
|
1282
|
+
isRelayCloseReason(payload.reason)
|
|
1283
|
+
) {
|
|
1284
|
+
this.disposeRelayChannel(payload.reason);
|
|
1285
|
+
}
|
|
1286
|
+
|
|
1013
1287
|
if (
|
|
1014
1288
|
envelope.m !== METHOD_PAIR_DELIVER ||
|
|
1015
1289
|
!isPlainObject(payload) ||
|
|
@@ -1204,7 +1478,38 @@ export class CloudWssTransport implements CloudTransport, CloudEndpoint {
|
|
|
1204
1478
|
const data: unknown = event.data;
|
|
1205
1479
|
|
|
1206
1480
|
if (typeof data !== "string") {
|
|
1207
|
-
//
|
|
1481
|
+
// M4 B3: binary belongs to an OPEN relay channel only — bounded §16 frames go to
|
|
1482
|
+
// the registered data listener; anything else (no channel, oversize, empty) is
|
|
1483
|
+
// refused locally exactly like the pre-relay profile: counted, never forwarded.
|
|
1484
|
+
if (
|
|
1485
|
+
(this.relayChannelIdValue !== null || this.relayTargetActive) &&
|
|
1486
|
+
data instanceof ArrayBuffer
|
|
1487
|
+
) {
|
|
1488
|
+
const payload = Buffer.from(data);
|
|
1489
|
+
|
|
1490
|
+
if (
|
|
1491
|
+
payload.length === 0 ||
|
|
1492
|
+
payload.length > MAX_DATA_FRAME_BYTES ||
|
|
1493
|
+
this.relayDataListener === null
|
|
1494
|
+
) {
|
|
1495
|
+
this.refuse();
|
|
1496
|
+
|
|
1497
|
+
return;
|
|
1498
|
+
}
|
|
1499
|
+
|
|
1500
|
+
const listener = this.relayDataListener;
|
|
1501
|
+
|
|
1502
|
+
try {
|
|
1503
|
+
listener(payload);
|
|
1504
|
+
} catch {
|
|
1505
|
+
// The relay consumer owns its session-fatal path; a throwing listener must
|
|
1506
|
+
// neither crash the event emitter nor corrupt transport state. Counted.
|
|
1507
|
+
this.seamErrors += 1;
|
|
1508
|
+
}
|
|
1509
|
+
|
|
1510
|
+
return;
|
|
1511
|
+
}
|
|
1512
|
+
|
|
1208
1513
|
this.refuse();
|
|
1209
1514
|
|
|
1210
1515
|
return;
|