@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.
- package/package.json +8 -3
- package/src/cloud-connector.ts +4 -3
- package/src/cloud-wss-transport.ts +388 -33
- package/src/relay-boundary.ts +292 -3
- package/src/relay-mux-wire.ts +105 -0
- package/src/relay-remote-channel.ts +482 -0
- package/src/relay-remote-dispatch.ts +227 -0
- package/src/relay-secure-channel.ts +325 -0
- package/src/relay-secure-target.ts +592 -0
- package/src/session-gateway.ts +129 -12
|
@@ -0,0 +1,592 @@
|
|
|
1
|
+
/** A-side SECURE relay target handler (D2-scoped SEC-13/SEC-14): the E2EE counterpart of the
|
|
2
|
+
* canned `createRelayTargetHandler` pilot lane (apps/bom-core/src/server/pairing-daemon.ts). relay-open(e2ee)
|
|
3
|
+
* runs the SAME central §11 admission against A's OWN stored grant — live, directed, exact
|
|
4
|
+
* membership refs, fresh ledger reads — and then every channel must complete a verified
|
|
5
|
+
* three-message §21 handshake before it carries anything. From that point:
|
|
6
|
+
*
|
|
7
|
+
* - the session principal is the HANDSHAKE-PROVEN requester identity (the client key pinned
|
|
8
|
+
* in A's own grant signed the transcript; SEC-14 "verified remote actor"), never a header
|
|
9
|
+
* claim, never X's word;
|
|
10
|
+
* - EVERY request is re-authorized per call through the central boundary (no verdict caching)
|
|
11
|
+
* and through the typed operation policy (explicit actor field, fail-closed default);
|
|
12
|
+
* - a remote actor is never the local owner: a claimed local-owner actor over a relayed
|
|
13
|
+
* session is a typed `actor-forged` denial (PARITY-3, no fake "User A");
|
|
14
|
+
* - every reply — including denials — is a sealed frame; a frame that fails crypto is
|
|
15
|
+
* session-fatal and disposes the channel (no plaintext error path exists);
|
|
16
|
+
* - the owner relay switch is re-read for EVERY frame: OFF closes the channel (fail-closed).
|
|
17
|
+
*
|
|
18
|
+
* Nothing here activates anything by itself: the handler is constructed inert, admits only
|
|
19
|
+
* the two v1 read-only surfaces, and production wiring (which handler answers which delivery)
|
|
20
|
+
* remains a coordinator/owner act behind the D2 gate. The canned pilot lane stays isolated
|
|
21
|
+
* and byte-identical.
|
|
22
|
+
*
|
|
23
|
+
* Channel lifecycle at A: `onSecureRelayOpen` admits the claims and mints the server hello;
|
|
24
|
+
* `bindChannel` registers X's adopted channel id with its outbound send seam and starts the
|
|
25
|
+
* handshake deadline; the channel's first inbound body must be B's clientFinish — the
|
|
26
|
+
* transport verifies the full transcript (finish must bind THIS channel's hello pair, so a
|
|
27
|
+
* finish replayed from any other handshake fails structurally; a duplicate finish on a live
|
|
28
|
+
* channel is not a sealed frame and is session-fatal) — and every later body must be a
|
|
29
|
+
* §21-sealed request. */
|
|
30
|
+
|
|
31
|
+
import type { RelationContext } from "@bom-pi/protocol/crypto.ts";
|
|
32
|
+
import {
|
|
33
|
+
RelayBoundary,
|
|
34
|
+
authorizeOperationByPolicy,
|
|
35
|
+
type OperationPolicyVerdict,
|
|
36
|
+
type RelayAuthorizationClaims,
|
|
37
|
+
type RelayChannelAuthority,
|
|
38
|
+
type RelayRequestVerdict,
|
|
39
|
+
type RelaySessionInput,
|
|
40
|
+
} from "./relay-boundary.ts";
|
|
41
|
+
import { MUX_CHANNEL_ID_HEX } from "./relay-mux-wire.ts";
|
|
42
|
+
import {
|
|
43
|
+
RELAY_HANDSHAKE_DEADLINE_MS,
|
|
44
|
+
ServerChannelHandshake,
|
|
45
|
+
ServerSecureChannel,
|
|
46
|
+
type SecureChannelIdentity,
|
|
47
|
+
type SecureRelayReply,
|
|
48
|
+
type SecureRelayRequest,
|
|
49
|
+
} from "./relay-secure-channel.ts";
|
|
50
|
+
|
|
51
|
+
/** The grant facts this handler reads from A's own ledger (structural slice of the daemon's
|
|
52
|
+
* LedgerGrant: role "target", transport "cloud" — kept structural so this module stays
|
|
53
|
+
* dependency-free and the daemon adapts its real store). */
|
|
54
|
+
export interface SecureTargetGrant {
|
|
55
|
+
role: "target";
|
|
56
|
+
transport: "cloud";
|
|
57
|
+
cloudId: string;
|
|
58
|
+
relationId: string;
|
|
59
|
+
grantEpoch: number;
|
|
60
|
+
selfFp: string;
|
|
61
|
+
peerFp: string;
|
|
62
|
+
/** The requester's pinned SPKI (base64url) from A's OWN grant — the handshake key. */
|
|
63
|
+
peerSpki: string;
|
|
64
|
+
selfMembership: { id: string; epoch: number };
|
|
65
|
+
peerMembership: { id: string; epoch: number };
|
|
66
|
+
/** Grant expiry in epoch SECONDS (the ledger's scale). */
|
|
67
|
+
expiry: number;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
export interface SecureRelayTargetDeps {
|
|
71
|
+
/** The durable owner-switch read (§11/§16); false refuses/denies everything, per frame. */
|
|
72
|
+
relayEnabled(): boolean;
|
|
73
|
+
/** A's trusted clock in epoch SECONDS (grant expiries live on the same scale). */
|
|
74
|
+
now(): number;
|
|
75
|
+
/** A's stored grants (the §11 authority: X's forwarded claims are only an input). */
|
|
76
|
+
grants(): readonly SecureTargetGrant[];
|
|
77
|
+
/** A's secret-free pending termination notices: a listed relation is revoked (§8). */
|
|
78
|
+
pendingCleanup(): readonly { relationId: string }[];
|
|
79
|
+
/** A's CURRENT cloud membership ref, or null while offline/quarantined. */
|
|
80
|
+
selfMembership(): { id: string; epoch: number } | null;
|
|
81
|
+
/** A's pinned identity: signs the server hello and every sealed reply, nothing else. */
|
|
82
|
+
identity: SecureChannelIdentity;
|
|
83
|
+
/** Test-only shortening of the handshake deadline; longer values are refused. */
|
|
84
|
+
handshakeDeadlineMs?: number;
|
|
85
|
+
/** Which admitted-surface set the boundary uses: "v1" (default — the frozen M4 two;
|
|
86
|
+
* the daemon's secure branch keeps this today) or "remote-v2" (the widened read/view
|
|
87
|
+
* family registry, D3 backend). Deny-first either way; per-request re-verify unchanged. */
|
|
88
|
+
surfaceSet?: "v1" | "remote-v2";
|
|
89
|
+
/** The admitted-surface dispatcher. Default: the two v1 read-only surfaces. An injected
|
|
90
|
+
* dispatcher receives the VERIFIED actor and may only answer — never authorize; it may
|
|
91
|
+
* answer synchronously or with a promise (the funnel dispatch awaits its handlers). */
|
|
92
|
+
dispatch?(
|
|
93
|
+
request: SecureRelayRequest & {
|
|
94
|
+
channelId: string;
|
|
95
|
+
sessionPrincipal: string;
|
|
96
|
+
relationId: string;
|
|
97
|
+
grantEpoch: number;
|
|
98
|
+
},
|
|
99
|
+
):
|
|
100
|
+
| { ok: 1; result: { [key: string]: unknown } }
|
|
101
|
+
| { ok: 0; denied: string }
|
|
102
|
+
| Promise<{ ok: 1; result: { [key: string]: unknown } } | { ok: 0; denied: string }>;
|
|
103
|
+
log?: (line: string) => void;
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
export type SecureRelayOpenVerdict =
|
|
107
|
+
| {
|
|
108
|
+
ok: true;
|
|
109
|
+
serverHello: Uint8Array;
|
|
110
|
+
/** Registers X's adopted channel id and its outbound send seam; starts the
|
|
111
|
+
* handshake deadline. Rejects duplicate or malformed channel ids fail-closed. */
|
|
112
|
+
bindChannel(channelId: string, sendFrame: (payload: Uint8Array) => void): void;
|
|
113
|
+
}
|
|
114
|
+
| { ok: false; denial: string };
|
|
115
|
+
|
|
116
|
+
interface PendingHandshake {
|
|
117
|
+
authority: RelayChannelAuthority;
|
|
118
|
+
context: RelationContext;
|
|
119
|
+
handshake: ServerChannelHandshake;
|
|
120
|
+
sendFrame: (payload: Uint8Array) => void;
|
|
121
|
+
deadline: NodeJS.Timeout;
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
interface LiveChannel {
|
|
125
|
+
authority: RelayChannelAuthority;
|
|
126
|
+
channel: ServerSecureChannel;
|
|
127
|
+
sessionPrincipal: string;
|
|
128
|
+
sendFrame: (payload: Uint8Array) => void;
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
const REQUEST_ID = /^[A-Za-z0-9][A-Za-z0-9_.:-]{0,127}$/;
|
|
132
|
+
const AUDIENCE = /^[a-z][a-z0-9:_-]{0,63}$/;
|
|
133
|
+
|
|
134
|
+
/** The optional funnel fields (D3): strict strings, bounded; anything else is malformed.
|
|
135
|
+
* A `path` carries the api-funnel's own path shape (no credentials ever ride it),
|
|
136
|
+
* `contentType` a bounded token, `body` base64url bytes within the single-frame bound. */
|
|
137
|
+
const FUNNEL_PATH = /^[^\s?#]{1,512}$/;
|
|
138
|
+
const FUNNEL_CONTENT_TYPE = /^[A-Za-z0-9][A-Za-z0-9!#$&^_.+\/:;=-]{0,127}$/;
|
|
139
|
+
const FUNNEL_BODY_B64 = /^[A-Za-z0-9_-]*$/;
|
|
140
|
+
|
|
141
|
+
const validFunnelFields = (request: SecureRelayRequest): boolean => {
|
|
142
|
+
if (request.path !== undefined) {
|
|
143
|
+
if (typeof request.path !== "string" || !FUNNEL_PATH.test(request.path)) {
|
|
144
|
+
return false;
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
if (request.contentType !== undefined) {
|
|
149
|
+
if (
|
|
150
|
+
typeof request.contentType !== "string" ||
|
|
151
|
+
!FUNNEL_CONTENT_TYPE.test(request.contentType)
|
|
152
|
+
) {
|
|
153
|
+
return false;
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
if (request.body !== undefined) {
|
|
158
|
+
if (
|
|
159
|
+
typeof request.body !== "string" ||
|
|
160
|
+
!FUNNEL_BODY_B64.test(request.body) ||
|
|
161
|
+
request.body.length > 700_000
|
|
162
|
+
) {
|
|
163
|
+
return false;
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
return true;
|
|
168
|
+
};
|
|
169
|
+
|
|
170
|
+
/** Builds the §21 relation context from A's OWN grant + the admitted claims. The boundary
|
|
171
|
+
* already compared every forwarded claim field against the grant; the context below is
|
|
172
|
+
* grant-authoritative and the handshake SIGNS these facts, so a claims/grant mismatch can
|
|
173
|
+
* never produce a verifiable handshake. `expiresAt` is the grant expiry on the millisecond
|
|
174
|
+
* scale (both endpoints build it from the same stored grant). */
|
|
175
|
+
const contextOf = (
|
|
176
|
+
grant: SecureTargetGrant,
|
|
177
|
+
claims: RelayAuthorizationClaims,
|
|
178
|
+
): RelationContext => ({
|
|
179
|
+
v: 1,
|
|
180
|
+
transport: "cloud",
|
|
181
|
+
cloudId: grant.cloudId,
|
|
182
|
+
requesterFp: grant.peerFp,
|
|
183
|
+
targetFp: grant.selfFp,
|
|
184
|
+
requesterMembership: { ...grant.peerMembership },
|
|
185
|
+
targetMembership: { ...grant.selfMembership },
|
|
186
|
+
direction: "requester-to-target",
|
|
187
|
+
relationId: claims.relationId,
|
|
188
|
+
grantEpoch: grant.grantEpoch,
|
|
189
|
+
expiresAt: grant.expiry * 1000,
|
|
190
|
+
});
|
|
191
|
+
|
|
192
|
+
export function createSecureRelayTargetHandler(deps: SecureRelayTargetDeps): {
|
|
193
|
+
/** relay-open(e2ee): §11 admission now (fresh ledger reads), then the server hello and
|
|
194
|
+
* the channel-binding hook. Nothing is retained until bindChannel runs. */
|
|
195
|
+
onSecureRelayOpen(
|
|
196
|
+
claims: RelayAuthorizationClaims,
|
|
197
|
+
clientHello: Uint8Array,
|
|
198
|
+
): SecureRelayOpenVerdict;
|
|
199
|
+
/** One inbound channel body: the handshake finish first, sealed requests after. */
|
|
200
|
+
onChannelFrame(channelId: string, payload: Uint8Array): void;
|
|
201
|
+
/** Releases one channel (X close notice, deadline expiry, local teardown). */
|
|
202
|
+
releaseChannel(channelId: string, reason: string): void;
|
|
203
|
+
/** Releases every channel (connection loss / owner decision). */
|
|
204
|
+
release(reason: string): void;
|
|
205
|
+
/** Close notification per dropped channel (fires exactly once per channel). */
|
|
206
|
+
onChannelClosed(callback: (channelId: string, reason: string) => void): void;
|
|
207
|
+
channelIds(): readonly string[];
|
|
208
|
+
establishedChannelIds(): readonly string[];
|
|
209
|
+
setRelayEnabledForTest(enabled: boolean): void;
|
|
210
|
+
} {
|
|
211
|
+
const deadlineMs = deps.handshakeDeadlineMs ?? RELAY_HANDSHAKE_DEADLINE_MS;
|
|
212
|
+
|
|
213
|
+
if (
|
|
214
|
+
!Number.isSafeInteger(deadlineMs) ||
|
|
215
|
+
deadlineMs < 1 ||
|
|
216
|
+
deadlineMs > RELAY_HANDSHAKE_DEADLINE_MS
|
|
217
|
+
) {
|
|
218
|
+
throw new Error("Handshake deadline may only shorten the D2 bound");
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
const log = deps.log ?? (() => {});
|
|
222
|
+
const boundary = new RelayBoundary({
|
|
223
|
+
now: () => deps.now() * 1000,
|
|
224
|
+
surfaceSet: deps.surfaceSet ?? "v1",
|
|
225
|
+
ledger: {
|
|
226
|
+
grant: (relationId) => {
|
|
227
|
+
for (const entry of deps.grants()) {
|
|
228
|
+
if (
|
|
229
|
+
entry.relationId === relationId &&
|
|
230
|
+
entry.role === "target" &&
|
|
231
|
+
entry.transport === "cloud"
|
|
232
|
+
) {
|
|
233
|
+
return {
|
|
234
|
+
relationId: entry.relationId,
|
|
235
|
+
direction: "requester-to-target" as const,
|
|
236
|
+
grantEpoch: entry.grantEpoch,
|
|
237
|
+
expiresAt: entry.expiry * 1000,
|
|
238
|
+
requesterFp: entry.peerFp,
|
|
239
|
+
targetFp: entry.selfFp,
|
|
240
|
+
requesterMembership: { ...entry.peerMembership },
|
|
241
|
+
targetMembership: { ...entry.selfMembership },
|
|
242
|
+
};
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
return null;
|
|
247
|
+
},
|
|
248
|
+
revoked: (relationId) =>
|
|
249
|
+
deps.pendingCleanup().some((entry) => entry.relationId === relationId),
|
|
250
|
+
membership: (ref) => {
|
|
251
|
+
// A's own side is authoritative (the register is A's current membership; a
|
|
252
|
+
// re-enroll stales the grant binding by comparison). The peer side: A cannot
|
|
253
|
+
// observe B's session liveness itself — X's structural admission is the
|
|
254
|
+
// liveness oracle and A independently binds the ref against its own stored
|
|
255
|
+
// grant in the same verify pass (documented §12 division, not a shortcut).
|
|
256
|
+
const self = deps.selfMembership();
|
|
257
|
+
|
|
258
|
+
if (self !== null && self.id === ref.id) {
|
|
259
|
+
return { live: true, currentEpoch: self.epoch };
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
return { live: true, currentEpoch: ref.epoch };
|
|
263
|
+
},
|
|
264
|
+
},
|
|
265
|
+
});
|
|
266
|
+
|
|
267
|
+
const pending = new Map<string, PendingHandshake>();
|
|
268
|
+
const live = new Map<string, LiveChannel>();
|
|
269
|
+
const closeCallbacks: ((channelId: string, reason: string) => void)[] = [];
|
|
270
|
+
let enabledForTest = true;
|
|
271
|
+
|
|
272
|
+
const notifyClosed = (channelId: string, reason: string): void => {
|
|
273
|
+
for (const callback of [...closeCallbacks]) {
|
|
274
|
+
try {
|
|
275
|
+
callback(channelId, reason);
|
|
276
|
+
} catch {
|
|
277
|
+
// A close listener must not break teardown; the channel is gone either way.
|
|
278
|
+
}
|
|
279
|
+
}
|
|
280
|
+
};
|
|
281
|
+
|
|
282
|
+
const dropChannel = (channelId: string, reason: string): void => {
|
|
283
|
+
const handshake = pending.get(channelId);
|
|
284
|
+
|
|
285
|
+
if (handshake !== undefined) {
|
|
286
|
+
clearTimeout(handshake.deadline);
|
|
287
|
+
pending.delete(channelId);
|
|
288
|
+
notifyClosed(channelId, reason);
|
|
289
|
+
|
|
290
|
+
return;
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
const channel = live.get(channelId);
|
|
294
|
+
|
|
295
|
+
if (channel !== undefined) {
|
|
296
|
+
channel.channel.linkLost(reason);
|
|
297
|
+
live.delete(channelId);
|
|
298
|
+
notifyClosed(channelId, reason);
|
|
299
|
+
}
|
|
300
|
+
};
|
|
301
|
+
|
|
302
|
+
const answer = (
|
|
303
|
+
entry: { channel: ServerSecureChannel; sendFrame: (payload: Uint8Array) => void },
|
|
304
|
+
channelId: string,
|
|
305
|
+
requestId: string,
|
|
306
|
+
outcome: { ok: 1; result: { [key: string]: unknown } } | { ok: 0; denied: string },
|
|
307
|
+
): void => {
|
|
308
|
+
const reply: SecureRelayReply =
|
|
309
|
+
outcome.ok === 1
|
|
310
|
+
? { v: 1, requestId, ok: 1, result: outcome.result }
|
|
311
|
+
: { v: 1, requestId, ok: 0, denied: outcome.denied };
|
|
312
|
+
|
|
313
|
+
try {
|
|
314
|
+
// reply() seals AND delivers through the channel's own send seam exactly once
|
|
315
|
+
// (the transport's deliver callback IS the send seam — no second write).
|
|
316
|
+
entry.channel.reply(channelId, reply);
|
|
317
|
+
} catch (error) {
|
|
318
|
+
// Sealing is session-fatal (rekey window, closed session): dispose the channel.
|
|
319
|
+
log(
|
|
320
|
+
`secure-relay: channel ${channelId} closed on reply seal: ` +
|
|
321
|
+
(error instanceof Error ? error.message : "seal"),
|
|
322
|
+
);
|
|
323
|
+
dropChannel(channelId, "session-fatal");
|
|
324
|
+
}
|
|
325
|
+
};
|
|
326
|
+
|
|
327
|
+
const defaultDispatch = (
|
|
328
|
+
request: SecureRelayRequest,
|
|
329
|
+
): { ok: 1; result: { [key: string]: unknown } } | { ok: 0; denied: string } => {
|
|
330
|
+
if (request.audience === "app-data:session-ping") {
|
|
331
|
+
return { ok: 1, result: { pong: 1, at: deps.now(), e2ee: 1 } };
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
return { ok: 1, result: { state: "secure-ready", relay: 1, e2ee: 1 } };
|
|
335
|
+
};
|
|
336
|
+
|
|
337
|
+
return {
|
|
338
|
+
onSecureRelayOpen(claims, clientHello) {
|
|
339
|
+
if (!(deps.relayEnabled() && enabledForTest)) {
|
|
340
|
+
return { ok: false, denial: "relay-disabled" };
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
const input: RelaySessionInput = { sessionPrincipal: claims.requesterFp, claims };
|
|
344
|
+
const admission = boundary.admitSession(input);
|
|
345
|
+
|
|
346
|
+
if (!admission.admitted) {
|
|
347
|
+
return { ok: false, denial: admission.denial };
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
// Grant-authoritative context + the requester's pinned SPKI from A's OWN store.
|
|
351
|
+
const grant = deps
|
|
352
|
+
.grants()
|
|
353
|
+
.find(
|
|
354
|
+
(entry) =>
|
|
355
|
+
entry.relationId === claims.relationId &&
|
|
356
|
+
entry.role === "target" &&
|
|
357
|
+
entry.transport === "cloud",
|
|
358
|
+
);
|
|
359
|
+
|
|
360
|
+
if (grant === undefined) {
|
|
361
|
+
// The ledger changed between admission and context build: fail closed.
|
|
362
|
+
return { ok: false, denial: "relation-unknown" };
|
|
363
|
+
}
|
|
364
|
+
|
|
365
|
+
let handshake: ServerChannelHandshake;
|
|
366
|
+
|
|
367
|
+
try {
|
|
368
|
+
handshake = new ServerChannelHandshake({
|
|
369
|
+
context: contextOf(grant, claims),
|
|
370
|
+
identity: deps.identity,
|
|
371
|
+
clientHello,
|
|
372
|
+
clientPublicDer: Buffer.from(grant.peerSpki, "base64url"),
|
|
373
|
+
});
|
|
374
|
+
} catch (error) {
|
|
375
|
+
// A malformed hello or key mismatch fails the open closed; no channel exists.
|
|
376
|
+
log(
|
|
377
|
+
"secure-relay: server hello refused: " +
|
|
378
|
+
(error instanceof Error ? error.message : "handshake"),
|
|
379
|
+
);
|
|
380
|
+
|
|
381
|
+
return { ok: false, denial: "handshake-refused" };
|
|
382
|
+
}
|
|
383
|
+
|
|
384
|
+
const authority = admission.authority;
|
|
385
|
+
const context = contextOf(grant, claims);
|
|
386
|
+
|
|
387
|
+
return {
|
|
388
|
+
ok: true,
|
|
389
|
+
serverHello: handshake.serverHello,
|
|
390
|
+
bindChannel(channelId, sendFrame) {
|
|
391
|
+
if (!MUX_CHANNEL_ID_HEX.test(channelId)) {
|
|
392
|
+
throw new Error("secure-relay: malformed channel id");
|
|
393
|
+
}
|
|
394
|
+
|
|
395
|
+
if (pending.has(channelId) || live.has(channelId)) {
|
|
396
|
+
throw new Error(`secure-relay: channel ${channelId} already bound`);
|
|
397
|
+
}
|
|
398
|
+
|
|
399
|
+
const deadline = setTimeout(() => {
|
|
400
|
+
// No clientFinish within the bound: the channel dies, X reclaims it.
|
|
401
|
+
if (pending.has(channelId)) {
|
|
402
|
+
log(`secure-relay: channel ${channelId} handshake deadline`);
|
|
403
|
+
dropChannel(channelId, "handshake-deadline");
|
|
404
|
+
}
|
|
405
|
+
}, deadlineMs);
|
|
406
|
+
|
|
407
|
+
deadline.unref();
|
|
408
|
+
pending.set(channelId, {
|
|
409
|
+
authority,
|
|
410
|
+
context,
|
|
411
|
+
handshake,
|
|
412
|
+
sendFrame,
|
|
413
|
+
deadline,
|
|
414
|
+
});
|
|
415
|
+
},
|
|
416
|
+
};
|
|
417
|
+
},
|
|
418
|
+
|
|
419
|
+
onChannelFrame(channelId, payload) {
|
|
420
|
+
// Owner switch re-read for EVERY frame: OFF closes the channel immediately.
|
|
421
|
+
if (!(deps.relayEnabled() && enabledForTest)) {
|
|
422
|
+
dropChannel(channelId, "owner-switch-off");
|
|
423
|
+
|
|
424
|
+
return;
|
|
425
|
+
}
|
|
426
|
+
|
|
427
|
+
const awaiting = pending.get(channelId);
|
|
428
|
+
|
|
429
|
+
if (awaiting !== undefined) {
|
|
430
|
+
let channel: ServerSecureChannel;
|
|
431
|
+
|
|
432
|
+
try {
|
|
433
|
+
// verifyHandshake inside complete() checks the full transcript: the
|
|
434
|
+
// finish must bind THIS channel's exact hello pair and both signatures,
|
|
435
|
+
// so a finish replayed from any other handshake fails structurally.
|
|
436
|
+
channel = awaiting.handshake.complete({
|
|
437
|
+
clientFinish: payload,
|
|
438
|
+
activation: () => ({ currentLocalOwner: true, relationLive: true }),
|
|
439
|
+
sendFrame: awaiting.sendFrame,
|
|
440
|
+
});
|
|
441
|
+
} catch (error) {
|
|
442
|
+
log(
|
|
443
|
+
`secure-relay: channel ${channelId} handshake failed: ` +
|
|
444
|
+
(error instanceof Error ? error.message : "verify"),
|
|
445
|
+
);
|
|
446
|
+
dropChannel(channelId, "handshake-failed");
|
|
447
|
+
|
|
448
|
+
return;
|
|
449
|
+
}
|
|
450
|
+
|
|
451
|
+
clearTimeout(awaiting.deadline);
|
|
452
|
+
pending.delete(channelId);
|
|
453
|
+
live.set(channelId, {
|
|
454
|
+
authority: awaiting.authority,
|
|
455
|
+
channel,
|
|
456
|
+
sessionPrincipal: awaiting.context.requesterFp,
|
|
457
|
+
sendFrame: awaiting.sendFrame,
|
|
458
|
+
});
|
|
459
|
+
log(
|
|
460
|
+
`secure-relay: channel ${channelId} established ` +
|
|
461
|
+
`(principal ${awaiting.context.requesterFp})`,
|
|
462
|
+
);
|
|
463
|
+
|
|
464
|
+
return;
|
|
465
|
+
}
|
|
466
|
+
|
|
467
|
+
const entry = live.get(channelId);
|
|
468
|
+
|
|
469
|
+
if (entry === undefined) {
|
|
470
|
+
// A frame for an unknown channel is never answered and never buffered.
|
|
471
|
+
log(`secure-relay: frame for unknown channel ${channelId} ignored`);
|
|
472
|
+
|
|
473
|
+
return;
|
|
474
|
+
}
|
|
475
|
+
|
|
476
|
+
let request: SecureRelayRequest;
|
|
477
|
+
|
|
478
|
+
try {
|
|
479
|
+
request = entry.channel.receiveRequest(payload, channelId);
|
|
480
|
+
} catch (error) {
|
|
481
|
+
// Crypto failure is session-fatal: dispose, never answer in plaintext.
|
|
482
|
+
log(
|
|
483
|
+
`secure-relay: channel ${channelId} frame rejected: ` +
|
|
484
|
+
(error instanceof Error ? error.message : "frame"),
|
|
485
|
+
);
|
|
486
|
+
dropChannel(channelId, "session-fatal");
|
|
487
|
+
|
|
488
|
+
return;
|
|
489
|
+
}
|
|
490
|
+
|
|
491
|
+
if (
|
|
492
|
+
request === null ||
|
|
493
|
+
typeof request !== "object" ||
|
|
494
|
+
request.v !== 1 ||
|
|
495
|
+
typeof request.requestId !== "string" ||
|
|
496
|
+
!REQUEST_ID.test(request.requestId) ||
|
|
497
|
+
typeof request.audience !== "string" ||
|
|
498
|
+
!AUDIENCE.test(request.audience) ||
|
|
499
|
+
(request.method !== "GET" && request.method !== "POST") ||
|
|
500
|
+
!validFunnelFields(request)
|
|
501
|
+
) {
|
|
502
|
+
answer(
|
|
503
|
+
entry,
|
|
504
|
+
channelId,
|
|
505
|
+
typeof request?.requestId === "string" ? request.requestId : "unknown",
|
|
506
|
+
{ ok: 0, denied: "malformed-frame" },
|
|
507
|
+
);
|
|
508
|
+
|
|
509
|
+
return;
|
|
510
|
+
}
|
|
511
|
+
|
|
512
|
+
// Per-request §11 authorization: FULL fresh ledger re-verification, no caching.
|
|
513
|
+
const verdict: RelayRequestVerdict = entry.authority.checkRequest({
|
|
514
|
+
audience: request.audience,
|
|
515
|
+
method: request.method,
|
|
516
|
+
});
|
|
517
|
+
|
|
518
|
+
if (!verdict.admitted) {
|
|
519
|
+
answer(entry, channelId, request.requestId, { ok: 0, denied: verdict.denial });
|
|
520
|
+
|
|
521
|
+
return;
|
|
522
|
+
}
|
|
523
|
+
|
|
524
|
+
// Typed operation policy: explicit verified actor, fail-closed surface registry.
|
|
525
|
+
const policy: OperationPolicyVerdict = authorizeOperationByPolicy({
|
|
526
|
+
sessionRelayed: true,
|
|
527
|
+
sessionPrincipal: entry.sessionPrincipal,
|
|
528
|
+
sessionRelation: {
|
|
529
|
+
relationId: entry.authority.claims.relationId,
|
|
530
|
+
grantEpoch: entry.authority.claims.grantEpoch,
|
|
531
|
+
},
|
|
532
|
+
actor: request.actor,
|
|
533
|
+
audience: request.audience,
|
|
534
|
+
method: request.method,
|
|
535
|
+
});
|
|
536
|
+
|
|
537
|
+
if (!policy.admitted) {
|
|
538
|
+
answer(entry, channelId, request.requestId, { ok: 0, denied: policy.denial });
|
|
539
|
+
|
|
540
|
+
return;
|
|
541
|
+
}
|
|
542
|
+
|
|
543
|
+
// A dispatch seam may be sync OR async (the funnel dispatch awaits handlers);
|
|
544
|
+
// normalize through a promise so an async outcome can never be mistaken for a
|
|
545
|
+
// denial, and a throwing handler answers the bounded handler-failed name.
|
|
546
|
+
const dispatched = (deps.dispatch ?? defaultDispatch)({
|
|
547
|
+
...request,
|
|
548
|
+
channelId,
|
|
549
|
+
sessionPrincipal: entry.sessionPrincipal,
|
|
550
|
+
relationId: entry.authority.claims.relationId,
|
|
551
|
+
grantEpoch: entry.authority.claims.grantEpoch,
|
|
552
|
+
});
|
|
553
|
+
|
|
554
|
+
void Promise.resolve(dispatched)
|
|
555
|
+
.then((outcome) => {
|
|
556
|
+
answer(entry, channelId, request.requestId, outcome);
|
|
557
|
+
})
|
|
558
|
+
.catch(() => {
|
|
559
|
+
answer(entry, channelId, request.requestId, {
|
|
560
|
+
ok: 0,
|
|
561
|
+
denied: "handler-failed",
|
|
562
|
+
});
|
|
563
|
+
});
|
|
564
|
+
},
|
|
565
|
+
|
|
566
|
+
releaseChannel(channelId, reason) {
|
|
567
|
+
dropChannel(channelId, reason);
|
|
568
|
+
},
|
|
569
|
+
|
|
570
|
+
release(reason) {
|
|
571
|
+
for (const channelId of [...pending.keys(), ...live.keys()]) {
|
|
572
|
+
dropChannel(channelId, reason);
|
|
573
|
+
}
|
|
574
|
+
},
|
|
575
|
+
|
|
576
|
+
onChannelClosed(callback) {
|
|
577
|
+
closeCallbacks.push(callback);
|
|
578
|
+
},
|
|
579
|
+
|
|
580
|
+
channelIds() {
|
|
581
|
+
return [...pending.keys(), ...live.keys()];
|
|
582
|
+
},
|
|
583
|
+
|
|
584
|
+
establishedChannelIds() {
|
|
585
|
+
return [...live.keys()];
|
|
586
|
+
},
|
|
587
|
+
|
|
588
|
+
setRelayEnabledForTest(enabled) {
|
|
589
|
+
enabledForTest = enabled;
|
|
590
|
+
},
|
|
591
|
+
};
|
|
592
|
+
}
|