@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.
@@ -0,0 +1,499 @@
1
+ /** A's central authorization boundary for M4 relayed application data (§11): EVERY relayed
2
+ * request is re-verified here against A's OWN stored grant, relation ledger and membership
3
+ * register — never against X's advertisement — before the admitted operation runs. The module
4
+ * is dependency-free by construction: ledger reads, the trusted clock and the bound session
5
+ * principal are injected, and no server module is imported. The admitted v1 surface is
6
+ * deliberately minimal (read-only session status/ping); everything else is a named,
7
+ * fail-closed denial. */
8
+
9
+ export type RelayDirection = "requester-to-target" | "target-to-requester";
10
+
11
+ export interface RelayMembershipRef {
12
+ id: string;
13
+ epoch: number;
14
+ }
15
+
16
+ /** The exact authorization claims X forwarded on the relay-open control frame. They are an
17
+ * input, never an authority: every field is compared against A's own stored grant below. */
18
+ export interface RelayAuthorizationClaims {
19
+ relationId: string;
20
+ grantEpoch: number;
21
+ requesterMembership: RelayMembershipRef;
22
+ targetMembership: RelayMembershipRef;
23
+ direction: RelayDirection;
24
+ requesterFp: string;
25
+ }
26
+
27
+ /** A's OWN stored grant for a relation: the authoritative epoch, expiry, direction, endpoints
28
+ * and both original membership refs (§11). X has no say in any of these fields. */
29
+ export interface RelayGrantRecord {
30
+ relationId: string;
31
+ direction: RelayDirection;
32
+ grantEpoch: number;
33
+ /** A-side absolute expiry, compared against A's trusted clock only. */
34
+ expiresAt: number;
35
+ requesterFp: string;
36
+ targetFp: string;
37
+ requesterMembership: RelayMembershipRef;
38
+ targetMembership: RelayMembershipRef;
39
+ }
40
+
41
+ export interface RelayMembershipRegisterEntry {
42
+ /** Live membership in the cloud (X), as tracked in A's own register. */
43
+ live: boolean;
44
+ /** The CURRENT enrollment epoch; a re-enroll bumps it and stales every older ref. */
45
+ currentEpoch: number;
46
+ }
47
+
48
+ /** Injected reads of A's own stores. Implementations must fail closed: a read that throws or
49
+ * returns null denies. No server module is imported here — the daemon wires these callbacks. */
50
+ export interface RelayLedgerReads {
51
+ /** A's own stored grant for a relation, or null when unknown. */
52
+ grant(relationId: string): RelayGrantRecord | null;
53
+ /** A's relation-ledger revoke state: true once the relation is revoked (either side,
54
+ * including offline-queued notices). */
55
+ revoked(relationId: string): boolean;
56
+ /** A's live membership register entry for an enrolled membership ref, or null when the
57
+ * id is unknown (e.g. removed from the cloud). */
58
+ membership(ref: RelayMembershipRef): RelayMembershipRegisterEntry | null;
59
+ }
60
+
61
+ /** The §11 negative list (a)–(d) as named, machine-readable denial categories:
62
+ * (a) approval-path — A-owner invite mint/redeem, /login, /join/:code cookie/bearer use to
63
+ * approve, pair approval of any kind;
64
+ * (b) credential-read — config.json, approval credentials/state, owner file APIs, agent shell;
65
+ * (c) local-approval-route — A-local approval direct, owner-management endpoints, proxied
66
+ * local requests;
67
+ * (d) extension-surface — enabled/installed extension routes or tools.
68
+ * Each is a static bounded name tests can assert; the pairing-approval exception (§13) keeps
69
+ * approvals A-local, so every one of these must FAIL through B's relay. */
70
+ export const RELAY_DENIAL_CATEGORIES = {
71
+ approvalPath: "approval-path",
72
+ credentialRead: "credential-read",
73
+ localApprovalRoute: "local-approval-route",
74
+ extensionSurface: "extension-surface",
75
+ } as const;
76
+
77
+ export type RelayDenialCategory =
78
+ (typeof RELAY_DENIAL_CATEGORIES)[keyof typeof RELAY_DENIAL_CATEGORIES];
79
+
80
+ /** The audience suffixes that classify into each named denial category. Matching is exact
81
+ * segment or segment-prefix (`app-data:invite` and `app-data:invite:some-id` both deny). The
82
+ * table is deny-support only: unlisted audiences are ALSO denied (as `not-admitted`), so this
83
+ * is never the inverse of a blanket allowlist. */
84
+ export const RELAY_DENIED_AUDIENCES: Readonly<Record<RelayDenialCategory, readonly string[]>> = {
85
+ "approval-path": [
86
+ "invite",
87
+ "invite-mint",
88
+ "invite-redeem",
89
+ "invites",
90
+ "join",
91
+ "join-code",
92
+ "login",
93
+ "owner-token",
94
+ "owner-token-mint",
95
+ "token",
96
+ "tokens",
97
+ "cookie",
98
+ "cookies",
99
+ "bearer",
100
+ "redeem",
101
+ "pair-approval",
102
+ "pair-approve",
103
+ "approve-pairing",
104
+ "pairing-approval",
105
+ ],
106
+ "credential-read": [
107
+ "config",
108
+ "config-json",
109
+ "configuration",
110
+ "credentials",
111
+ "credential",
112
+ "approval-credentials",
113
+ "approval-state",
114
+ "secrets",
115
+ "secret",
116
+ "owner-files",
117
+ "files",
118
+ "file",
119
+ "file-api",
120
+ "file-read",
121
+ "file-write",
122
+ "agent-shell",
123
+ "shell",
124
+ "shell-exec",
125
+ "exec",
126
+ "environment",
127
+ "env",
128
+ ],
129
+ "local-approval-route": [
130
+ "local-approval",
131
+ "approval",
132
+ "approve",
133
+ "owner-management",
134
+ "owner-endpoint",
135
+ "management",
136
+ "proxied-local",
137
+ "local-request",
138
+ "local-proxy",
139
+ "proxy",
140
+ "owner-api",
141
+ ],
142
+ "extension-surface": [
143
+ "extension",
144
+ "extensions",
145
+ "extension-route",
146
+ "extension-routes",
147
+ "extension-tool",
148
+ "extension-tools",
149
+ "tool",
150
+ "tools",
151
+ "tool-call",
152
+ "tool-run",
153
+ ],
154
+ };
155
+
156
+ /** EXTENSION POINT for later §11 matrix rows: the admitted v1 relay surface is read-only
157
+ * session status/ping ONLY. Every later row lands as an explicit, individually reviewed entry
158
+ * here — no pattern or wildcard admission, no blanket API allowlist, and never silent owner
159
+ * equivalence: a new surface needs its own central-boundary review plus the §11 negative tests
160
+ * for its row before it admits anything. */
161
+ export const RELAY_ADMITTED_SURFACE = [
162
+ { audience: "app-data:session-status", method: "GET" },
163
+ { audience: "app-data:session-ping", method: "GET" },
164
+ ] as const;
165
+
166
+ export type RelaySurfaceName = "session-status" | "session-ping";
167
+
168
+ const ADMITTED_SURFACES = new Map<string, RelaySurfaceName>([
169
+ ["app-data:session-status", "session-status"],
170
+ ["app-data:session-ping", "session-ping"],
171
+ ]);
172
+
173
+ /** The named (a)–(d) category for an audience, or null when the audience is not on the
174
+ * negative list (it may still be denied, as `not-admitted`, by the surface classification). */
175
+ export function relayDenialCategoryOf(audience: string): RelayDenialCategory | null {
176
+ const prefix = "app-data:";
177
+
178
+ if (!audience.startsWith(prefix)) {
179
+ return null;
180
+ }
181
+
182
+ const rest = audience.slice(prefix.length);
183
+
184
+ for (const category of Object.keys(RELAY_DENIED_AUDIENCES) as RelayDenialCategory[]) {
185
+ for (const suffix of RELAY_DENIED_AUDIENCES[category]) {
186
+ if (rest === suffix || rest.startsWith(`${suffix}:`)) {
187
+ return category;
188
+ }
189
+ }
190
+ }
191
+
192
+ return null;
193
+ }
194
+
195
+ export type RelaySurfaceVerdict =
196
+ | { admitted: true; surface: RelaySurfaceName }
197
+ | { admitted: false; denial: RelayDenialCategory | "not-admitted" };
198
+
199
+ /** Surface classification only — authorization is verified separately, first, per request. */
200
+ export function classifyRelayedRequest(
201
+ audience: string,
202
+ method: "GET" | "POST",
203
+ ): RelaySurfaceVerdict {
204
+ // §11 negative-list first, regardless of method: an approval/credential/extension
205
+ // audience carries its named category even as a write — the category is the security
206
+ // signal, and a bare `not-admitted` would hide WHICH forbidden lane was attempted.
207
+ const category = relayDenialCategoryOf(audience);
208
+
209
+ if (category !== null) {
210
+ return { admitted: false, denial: category };
211
+ }
212
+
213
+ if (method !== "GET") {
214
+ return { admitted: false, denial: "not-admitted" };
215
+ }
216
+
217
+ const surface = ADMITTED_SURFACES.get(audience);
218
+
219
+ if (surface !== undefined) {
220
+ return { admitted: true, surface };
221
+ }
222
+
223
+ return { admitted: false, denial: "not-admitted" };
224
+ }
225
+
226
+ /** Why a request's §11 authorization failed. Machine-readable, static, bounded; none of these
227
+ * names ever carry secret material (fingerprints and ids stay in A's stores). */
228
+ export type RelayAuthorizationDenial =
229
+ | "malformed-claims"
230
+ | "relation-unknown"
231
+ | "grant-epoch-mismatch"
232
+ | "direction-mismatch"
233
+ | "principal-mismatch"
234
+ | "membership-mismatch"
235
+ | "relation-revoked"
236
+ | "grant-expired"
237
+ | "membership-unknown"
238
+ | "membership-not-live"
239
+ | "membership-stale";
240
+
241
+ export type RelayRequestVerdict =
242
+ | { admitted: true; surface: RelaySurfaceName }
243
+ | { admitted: false; stage: "authorization"; denial: RelayAuthorizationDenial }
244
+ | { admitted: false; stage: "surface"; denial: RelayDenialCategory | "not-admitted" };
245
+
246
+ export interface RelaySessionInput {
247
+ /** A-attested principal bound to the live authenticated relayed session (B's fingerprint,
248
+ * as X's structural admission injected it from the AUTHENTICATED session (§12 delegation: A cannot observe the requester's session itself; X routes only between live sessions whose member ref exactly matches the forwarded claims)). */
249
+ sessionPrincipal: string;
250
+ /** The exact claims X forwarded on relay-open; never trusted without ledger verification. */
251
+ claims: RelayAuthorizationClaims;
252
+ /** An X-advertised expiry, when present, is type-checked and then deliberately NEVER
253
+ * consulted: A's own stored grant is the only expiry authority (§11). */
254
+ advertisedExpiry?: number;
255
+ }
256
+
257
+ export interface RelayRouteInput extends RelaySessionInput {
258
+ /** The relayed operation to admit or deny (the gateway audience + method). */
259
+ request: { audience: string; method: "GET" | "POST" };
260
+ }
261
+
262
+ export type RelaySessionAdmission =
263
+ | { admitted: true; authority: RelayChannelAuthority }
264
+ | { admitted: false; denial: RelayAuthorizationDenial };
265
+
266
+ /** The per-channel authority returned by a successful relay-open admission. It holds the
267
+ * bound principal and the exact claims, and re-runs the FULL §11 authorization for every
268
+ * request against fresh ledger reads — no verdict is ever cached (§11: test every relayed
269
+ * request at A's central boundary). */
270
+ export interface RelayChannelAuthority {
271
+ readonly sessionPrincipal: string;
272
+ readonly claims: RelayAuthorizationClaims;
273
+ checkRequest(request: { audience: string; method: "GET" | "POST" }): RelayRequestVerdict;
274
+ }
275
+
276
+ const RELATION_ID = /^[A-Za-z0-9][A-Za-z0-9_.:-]{0,127}$/;
277
+ const PRINCIPAL_ID = /^[A-Za-z0-9][A-Za-z0-9_.:-]{0,127}$/;
278
+
279
+ const validMembershipRef = (ref: unknown): ref is RelayMembershipRef =>
280
+ ref !== null &&
281
+ typeof ref === "object" &&
282
+ typeof (ref as RelayMembershipRef).id === "string" &&
283
+ RELATION_ID.test((ref as RelayMembershipRef).id) &&
284
+ typeof (ref as RelayMembershipRef).epoch === "number" &&
285
+ Number.isSafeInteger((ref as RelayMembershipRef).epoch) &&
286
+ (ref as RelayMembershipRef).epoch >= 0;
287
+
288
+ const validClaims = (claims: RelayAuthorizationClaims): boolean =>
289
+ claims !== null &&
290
+ typeof claims === "object" &&
291
+ typeof claims.relationId === "string" &&
292
+ RELATION_ID.test(claims.relationId) &&
293
+ typeof claims.requesterFp === "string" &&
294
+ PRINCIPAL_ID.test(claims.requesterFp) &&
295
+ typeof claims.grantEpoch === "number" &&
296
+ Number.isSafeInteger(claims.grantEpoch) &&
297
+ claims.grantEpoch >= 1 &&
298
+ (claims.direction === "requester-to-target" || claims.direction === "target-to-requester") &&
299
+ validMembershipRef(claims.requesterMembership) &&
300
+ validMembershipRef(claims.targetMembership);
301
+
302
+ /** A's own grant record is validated too: a corrupt read denies (fail-closed), it never admits. */
303
+ const validGrant = (grant: RelayGrantRecord): boolean =>
304
+ grant !== null &&
305
+ typeof grant === "object" &&
306
+ typeof grant.relationId === "string" &&
307
+ (grant.direction === "requester-to-target" || grant.direction === "target-to-requester") &&
308
+ typeof grant.grantEpoch === "number" &&
309
+ Number.isSafeInteger(grant.grantEpoch) &&
310
+ grant.grantEpoch >= 1 &&
311
+ typeof grant.expiresAt === "number" &&
312
+ Number.isFinite(grant.expiresAt) &&
313
+ typeof grant.requesterFp === "string" &&
314
+ typeof grant.targetFp === "string" &&
315
+ validMembershipRef(grant.requesterMembership) &&
316
+ validMembershipRef(grant.targetMembership);
317
+
318
+ const sameMembershipRef = (a: RelayMembershipRef, b: RelayMembershipRef): boolean =>
319
+ a.id === b.id && a.epoch === b.epoch;
320
+
321
+ export interface RelayBoundaryOptions {
322
+ /** A's trusted local clock; a cloud-provided clock is never used (§20 discipline). */
323
+ now?: () => number;
324
+ /** Injected reads of A's own grant store, relation ledger and membership register. */
325
+ ledger: RelayLedgerReads;
326
+ }
327
+
328
+ export class RelayBoundary {
329
+ private readonly now: () => number;
330
+ private readonly ledger: RelayLedgerReads;
331
+
332
+ constructor(options: RelayBoundaryOptions) {
333
+ this.now = options.now ?? Date.now;
334
+ this.ledger = options.ledger;
335
+ }
336
+
337
+ /** relay-open admission: the full §11 authorization runs NOW, and the returned channel
338
+ * authority re-verifies every subsequent request (expiry, revoke and membership loss can
339
+ * never be bypassed by an earlier admission, §11 "reauthorize ... at this boundary"). */
340
+ admitSession(input: RelaySessionInput): RelaySessionAdmission {
341
+ const verdict = this.verify(input);
342
+
343
+ if (!verdict.ok) {
344
+ return { admitted: false, denial: verdict.denial };
345
+ }
346
+
347
+ return { admitted: true, authority: new BoundChannelAuthority(this, input) };
348
+ }
349
+
350
+ /** One relayed request: full §11 authorization of the context first, then the surface
351
+ * classification. Denials are named verdicts, never throws. */
352
+ authorize(input: RelayRouteInput): RelayRequestVerdict {
353
+ const verdict = this.verify(input);
354
+
355
+ if (!verdict.ok) {
356
+ return { admitted: false, stage: "authorization", denial: verdict.denial };
357
+ }
358
+
359
+ const surface = classifyRelayedRequest(input.request.audience, input.request.method);
360
+
361
+ if (!surface.admitted) {
362
+ return { admitted: false, stage: "surface", denial: surface.denial };
363
+ }
364
+
365
+ return { admitted: true, surface: surface.surface };
366
+ }
367
+
368
+ /** Channel-authority hook: re-runs authorize with the bound principal and claims so every
369
+ * request re-reads the ledger fresh. */
370
+ check(
371
+ input: RelaySessionInput,
372
+ request: { audience: string; method: "GET" | "POST" },
373
+ ): RelayRequestVerdict {
374
+ return this.authorize({
375
+ sessionPrincipal: input.sessionPrincipal,
376
+ claims: input.claims,
377
+ request,
378
+ });
379
+ }
380
+
381
+ /** The per-request §11 verification order is fixed and documented: shape → stored grant →
382
+ * exact claims → binding/distinctness → revoke → expiry → live membership both sides. */
383
+ private verify(
384
+ input: RelaySessionInput,
385
+ ): { ok: true } | { ok: false; denial: RelayAuthorizationDenial } {
386
+ if (
387
+ typeof input.sessionPrincipal !== "string" ||
388
+ !PRINCIPAL_ID.test(input.sessionPrincipal) ||
389
+ !validClaims(input.claims) ||
390
+ (input.advertisedExpiry !== undefined && !Number.isFinite(input.advertisedExpiry))
391
+ ) {
392
+ return { ok: false, denial: "malformed-claims" };
393
+ }
394
+
395
+ const claims = input.claims;
396
+ const grant = this.ledger.grant(claims.relationId);
397
+
398
+ if (grant === null || !validGrant(grant)) {
399
+ return { ok: false, denial: "relation-unknown" };
400
+ }
401
+
402
+ if (claims.grantEpoch !== grant.grantEpoch) {
403
+ return { ok: false, denial: "grant-epoch-mismatch" };
404
+ }
405
+
406
+ if (claims.direction !== grant.direction) {
407
+ return { ok: false, denial: "direction-mismatch" };
408
+ }
409
+
410
+ // Distinct bound remote principal: the live session's principal must be exactly the
411
+ // relation's requester, and the two endpoints must differ (§11).
412
+ if (
413
+ input.sessionPrincipal !== claims.requesterFp ||
414
+ input.sessionPrincipal !== grant.requesterFp ||
415
+ grant.requesterFp === grant.targetFp
416
+ ) {
417
+ return { ok: false, denial: "principal-mismatch" };
418
+ }
419
+
420
+ // BOTH original membership IDs/epochs, exact (§11).
421
+ if (
422
+ !sameMembershipRef(claims.requesterMembership, grant.requesterMembership) ||
423
+ !sameMembershipRef(claims.targetMembership, grant.targetMembership)
424
+ ) {
425
+ return { ok: false, denial: "membership-mismatch" };
426
+ }
427
+
428
+ // Revoke state from A's relation ledger, per request (either side's revocation wins).
429
+ if (this.ledger.revoked(claims.relationId) === true) {
430
+ return { ok: false, denial: "relation-revoked" };
431
+ }
432
+
433
+ // Expiry from A's OWN stored grant against A's clock. `advertisedExpiry` is present on
434
+ // the input only to prove it is ignored: it is never compared to anything (§11).
435
+ if (this.now() >= grant.expiresAt) {
436
+ return { ok: false, denial: "grant-expired" };
437
+ }
438
+
439
+ // Authenticated LIVE membership, both sides: the original ref must still be the
440
+ // current enrollment (a re-enroll stales it) and registered live.
441
+ const requesterEntry = this.ledger.membership(claims.requesterMembership);
442
+
443
+ if (requesterEntry === null) {
444
+ return { ok: false, denial: "membership-unknown" };
445
+ }
446
+
447
+ if (requesterEntry.live !== true) {
448
+ return { ok: false, denial: "membership-not-live" };
449
+ }
450
+
451
+ if (requesterEntry.currentEpoch !== claims.requesterMembership.epoch) {
452
+ return { ok: false, denial: "membership-stale" };
453
+ }
454
+
455
+ const targetEntry = this.ledger.membership(claims.targetMembership);
456
+
457
+ if (targetEntry === null) {
458
+ return { ok: false, denial: "membership-unknown" };
459
+ }
460
+
461
+ if (targetEntry.live !== true) {
462
+ return { ok: false, denial: "membership-not-live" };
463
+ }
464
+
465
+ if (targetEntry.currentEpoch !== claims.targetMembership.epoch) {
466
+ return { ok: false, denial: "membership-stale" };
467
+ }
468
+
469
+ return { ok: true };
470
+ }
471
+ }
472
+
473
+ class BoundChannelAuthority implements RelayChannelAuthority {
474
+ readonly sessionPrincipal: string;
475
+ readonly claims: RelayAuthorizationClaims;
476
+ private readonly boundary: RelayBoundary;
477
+
478
+ constructor(boundary: RelayBoundary, input: RelaySessionInput) {
479
+ this.boundary = boundary;
480
+ this.sessionPrincipal = input.sessionPrincipal;
481
+ // Freeze the binding: the channel authority carries copies, so later mutation of the
482
+ // caller's objects cannot change what this channel is bound to.
483
+ this.claims = {
484
+ relationId: input.claims.relationId,
485
+ grantEpoch: input.claims.grantEpoch,
486
+ requesterMembership: { ...input.claims.requesterMembership },
487
+ targetMembership: { ...input.claims.targetMembership },
488
+ direction: input.claims.direction,
489
+ requesterFp: input.claims.requesterFp,
490
+ };
491
+ }
492
+
493
+ checkRequest(request: { audience: string; method: "GET" | "POST" }): RelayRequestVerdict {
494
+ return this.boundary.check(
495
+ { sessionPrincipal: this.sessionPrincipal, claims: this.claims },
496
+ request,
497
+ );
498
+ }
499
+ }
@@ -3,7 +3,9 @@
3
3
  * sealed frame; no plaintext send path exists by construction. The link is cancellation-first
4
4
  * and fail-closed: transport loss closes the session immediately, leaves unacknowledged
5
5
  * mutations outcome-unknown, and admits nothing until a fresh three-message handshake
6
- * completes. Application-data routing stays hard-disabled behind the §§11–12 access gate. */
6
+ * completes. Application-data routing exists only through `enableApplicationRouting`, which
7
+ * requires the durable owner relay switch to read ON and forwards EVERY request through A's
8
+ * central §11 boundary; with the switch OFF the refusal stays byte-identical. */
7
9
 
8
10
  import { createHash } from "node:crypto";
9
11
  import {
@@ -13,6 +15,13 @@ import {
13
15
  type Ephemeral,
14
16
  type RelationContext,
15
17
  } from "@bom-pi/protocol/crypto.ts";
18
+ import {
19
+ RelayBoundary,
20
+ type RelayAuthorizationClaims,
21
+ type RelayRequestVerdict,
22
+ type RelaySessionAdmission,
23
+ type RelaySessionInput,
24
+ } from "./relay-boundary.ts";
16
25
 
17
26
  /** §21: sessionId = base64url(first16(SHA-256(UTF8("bom-pi/session/v1") || transcriptHash))). */
18
27
  const sessionIdentifier = (transcriptHash: Buffer): string =>
@@ -84,16 +93,112 @@ export class TransportError extends Error {
84
93
  const REQUEST_ID = /^[A-Za-z0-9][A-Za-z0-9_.:-]{0,127}$/;
85
94
  const FRAME_TYPE = /^[A-Za-z0-9][A-Za-z0-9_.:-]{0,63}$/;
86
95
 
87
- /** Honest disabled adapter mirroring `createApprovalAuthority`: application-data routing is
88
- * unreachable until the §§11–12 access gate passes with independent review. There is no
89
- * plaintext fallback and this function never returns an enabled router. */
90
- export function enableApplicationRouting(): never {
91
- throw new TransportError(
92
- "fail-closed",
93
- "Application-data routing is disabled: the §§11–12 access gate has not passed, no grant " +
94
- "or relay exists, and no plaintext fallback is implemented. Routing can only be " +
95
- "enabled by a separately reviewed, owner-authorized build, never by this call.",
96
- );
96
+ /** The exact disabled-routing refusal. Its bytes are depended on by callers and tests: with
97
+ * the owner switch OFF (or absent, or unreadable) this exact text is thrown, unchanged from
98
+ * the pre-M4 candidate. */
99
+ const ROUTING_DISABLED_REFUSAL =
100
+ "Application-data routing is disabled: the §§11–12 access gate has not passed, no grant " +
101
+ "or relay exists, and no plaintext fallback is implemented. Routing can only be " +
102
+ "enabled by a separately reviewed, owner-authorized build, never by this call.";
103
+
104
+ /** Static bounded error for a switch that reads OFF after enablement (mid-channel): the
105
+ * channel owner must treat this as transport loss and close the relayed channel. */
106
+ const ROUTING_SWITCH_OFF =
107
+ "Application-data routing is disabled: the owner relay switch reads OFF; the relayed " +
108
+ "channel must close";
109
+
110
+ /** The activation seam `enableApplicationRouting` consumes: the durable owner relay switch
111
+ * read (`RelaySwitchRead` — false, throwing or absent reads OFF, never an env var) plus A's
112
+ * central §11 boundary, which every routed request must pass. */
113
+ export interface ApplicationRoutingActivation {
114
+ ownerSwitch: () => boolean;
115
+ boundary: RelayBoundary;
116
+ }
117
+
118
+ export interface RelayedRouteRequest {
119
+ requestId: string;
120
+ /** The authenticated remote principal bound to the live relayed session (A-attested). */
121
+ sessionPrincipal: string;
122
+ /** The exact claims X forwarded on relay-open; re-verified against A's ledger per request. */
123
+ claims: RelayAuthorizationClaims;
124
+ /** The relayed operation to admit or deny. */
125
+ request: { audience: string; method: "GET" | "POST" };
126
+ /** An X-advertised expiry, when present, is recorded but never trusted (§11). */
127
+ advertisedExpiry?: number;
128
+ }
129
+
130
+ export interface ApplicationRouter {
131
+ /** True only while the owner switch currently reads ON (fail-closed on any doubt). */
132
+ isLive(): boolean;
133
+ /** relay-open admission through the central boundary: full §11 authorization now, then a
134
+ * channel authority that re-verifies every subsequent request. */
135
+ admitSession(input: RelaySessionInput): RelaySessionAdmission;
136
+ /** Forwards EVERY request through the central boundary; denials return as named verdicts.
137
+ * A switch that reads OFF after enablement throws fail-closed so the channel closes. */
138
+ route(request: RelayedRouteRequest): RelayRequestVerdict;
139
+ }
140
+
141
+ /** Fail-closed switch read: only an unthrowing `true` counts as ON. */
142
+ const switchReadsOn = (activation: ApplicationRoutingActivation | undefined): boolean => {
143
+ if (activation === undefined) {
144
+ return false;
145
+ }
146
+
147
+ try {
148
+ return activation.ownerSwitch() === true;
149
+ } catch {
150
+ return false;
151
+ }
152
+ };
153
+
154
+ class OwnerSwitchedApplicationRouter implements ApplicationRouter {
155
+ private readonly ownerSwitch: () => boolean;
156
+ private readonly boundary: RelayBoundary;
157
+
158
+ constructor(activation: ApplicationRoutingActivation) {
159
+ this.ownerSwitch = activation.ownerSwitch;
160
+ this.boundary = activation.boundary;
161
+ }
162
+
163
+ isLive(): boolean {
164
+ return switchReadsOn({ ownerSwitch: this.ownerSwitch, boundary: this.boundary });
165
+ }
166
+
167
+ admitSession(input: RelaySessionInput): RelaySessionAdmission {
168
+ if (!this.isLive()) {
169
+ throw new TransportError("fail-closed", ROUTING_SWITCH_OFF);
170
+ }
171
+
172
+ return this.boundary.admitSession(input);
173
+ }
174
+
175
+ route(request: RelayedRouteRequest): RelayRequestVerdict {
176
+ if (!this.isLive()) {
177
+ throw new TransportError("fail-closed", ROUTING_SWITCH_OFF);
178
+ }
179
+
180
+ return this.boundary.authorize({
181
+ sessionPrincipal: request.sessionPrincipal,
182
+ claims: request.claims,
183
+ request: request.request,
184
+ advertisedExpiry: request.advertisedExpiry,
185
+ });
186
+ }
187
+ }
188
+
189
+ /** The §§11–12 application-data routing plumb. With no activation wired, or with the durable
190
+ * owner relay switch reading OFF (or throwing), this throws the byte-identical disabled
191
+ * refusal; it never returns a router without a live owner switch AND A's central boundary.
192
+ * There is still no plaintext fallback and no grant-switch path (GRANT stays a separate,
193
+ * not-yet-implemented switch). */
194
+ export function enableApplicationRouting(
195
+ activation?: ApplicationRoutingActivation,
196
+ ): ApplicationRouter {
197
+ if (activation === undefined || !switchReadsOn(activation)) {
198
+ throw new TransportError("fail-closed", ROUTING_DISABLED_REFUSAL);
199
+ }
200
+
201
+ return new OwnerSwitchedApplicationRouter(activation);
97
202
  }
98
203
 
99
204
  export class SecureTransport {