@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.
@@ -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 {
@@ -3,11 +3,15 @@
3
3
  * web forwards only the handle, a request ID and bounded origin/CSRF context, and can never
4
4
  * mint a local-user assertion or label a request `owner`. Handles are hashed at rest and held
5
5
  * only in memory: a core restart revokes every session until secure persistence is separately
6
- * tested (§19). No application-data routing, no owner-token persistence, no plaintext
7
- * fallback and no session-only pair decisions are possible through this module; those stay
8
- * disabled behind the §§11–12 access gates. */
6
+ * tested (§19). No owner-token persistence, no plaintext fallback and no session-only pair
7
+ * decisions are possible through this module. Application-data audiences stay hard-disabled
8
+ * for LOCAL sessions (byte-identical to the pre-M4 candidate); a RELAYED owner-role principal
9
+ * (§5: a distinct remote principal, never a token sign-in and never a guest downgrade) reaches
10
+ * only the v1 surface admitted by the injected central §11 boundary, with every denial named
11
+ * and approvals staying A-local (§13). */
9
12
 
10
13
  import { createHash, randomBytes, timingSafeEqual } from "node:crypto";
14
+ import type { RelayRequestVerdict } from "./relay-boundary.ts";
11
15
 
12
16
  /** §20 proposed v1 session profile: owner idle timeout 15 minutes, absolute lifetime 8 hours.
13
17
  * Test overrides may only shorten these bounds, never extend them. */
@@ -26,6 +30,7 @@ const SUBJECT_ID = /^[A-Za-z0-9][A-Za-z0-9_.:-]{0,63}$/;
26
30
  const REQUEST_ID = /^[A-Za-z0-9][A-Za-z0-9_.:-]{0,127}$/;
27
31
  const AUDIENCE = /^[a-z][a-z0-9:_-]{0,63}$/;
28
32
  const MAX_TOKEN_LENGTH = 512;
33
+ const MAX_PIN_ORIGIN = 255;
29
34
 
30
35
  export type SessionRole = "owner" | "guest";
31
36
  export type GatewayMethod = "GET" | "POST";
@@ -36,6 +41,10 @@ export interface SessionView {
36
41
  subjectId: string;
37
42
  createdAt: number;
38
43
  expiresAt: number;
44
+ /** §5/§11: true ONLY for a relayed remote principal's owner-equivalent session — a
45
+ * distinct principal that never touches local audiences and is boundary-checked per
46
+ * request. Local owner and guest sessions are always false. */
47
+ relayed: boolean;
39
48
  }
40
49
 
41
50
  export interface IssuedCookie {
@@ -59,6 +68,7 @@ export interface IssuedSession {
59
68
  interface SessionRecord {
60
69
  role: SessionRole;
61
70
  subjectId: string;
71
+ relayed: boolean;
62
72
  handleHash: string;
63
73
  csrfTokenHash: string;
64
74
  createdAt: number;
@@ -79,7 +89,22 @@ export type GatewayFailureReason =
79
89
  | "handler-failed"
80
90
  | "core-unavailable"
81
91
  | "overloaded"
82
- | "incompatible-version";
92
+ | "incompatible-version"
93
+ | "transport-unproved"
94
+ // M4 §11 relay denials: machine-readable names sourced from the central boundary's
95
+ // verdicts (relay-boundary.ts). All static and bounded; no context is echoed back.
96
+ | "relay-authorization-failed"
97
+ | "relay-not-admitted"
98
+ | "relay-denied-approval-path"
99
+ | "relay-denied-credential-read"
100
+ | "relay-denied-local-approval"
101
+ | "relay-denied-extension-surface"
102
+ // A domain handler's own bounded 4xx refusal (a named operation's legacy route text,
103
+ // status preserved): added 2026-11-08 by owner-directed remediation so domain refusals
104
+ // stop collapsing into malformed-envelope — an envelope SHAPE error stays
105
+ // malformed-envelope; a domain refusal is this reason, carrying the route's bounded
106
+ // message in `data.error` (never an exception object or stack).
107
+ | "domain-refused";
83
108
 
84
109
  export interface GatewayRequest {
85
110
  v: 1;
@@ -109,6 +134,28 @@ export type DecisionAuthorizer = (input: {
109
134
  session: SessionView;
110
135
  }) => { verified: boolean } | Promise<{ verified: boolean }>;
111
136
 
137
+ /** The per-request check A's central boundary exposes for one bound relayed session
138
+ * (relay-boundary.ts `RelayChannelAuthority.checkRequest`). */
139
+ export type RelayedRequestCheck = (request: {
140
+ audience: string;
141
+ method: GatewayMethod;
142
+ }) => RelayRequestVerdict | Promise<RelayRequestVerdict>;
143
+
144
+ /** M4 §11 wiring: resolves a RELAYED session to its channel's central-boundary check. The
145
+ * daemon closes this over the `RelayChannelAuthority` it admitted at relay-open. Returning
146
+ * null (or not wiring the resolver at all) denies fail-closed — a relayed session without a
147
+ * boundary must never fall through to any local path. */
148
+ export type RelayedBoundaryResolver = (session: SessionView) => RelayedRequestCheck | null;
149
+
150
+ /** Maps a boundary verdict's denial name to the machine-readable gateway reason. */
151
+ const RELAY_DENIAL_REASONS: Record<string, GatewayFailureReason> = {
152
+ "approval-path": "relay-denied-approval-path",
153
+ "credential-read": "relay-denied-credential-read",
154
+ "local-approval-route": "relay-denied-local-approval",
155
+ "extension-surface": "relay-denied-extension-surface",
156
+ "not-admitted": "relay-not-admitted",
157
+ };
158
+
112
159
  const STATUS_BY_REASON: Record<GatewayFailureReason, number> = {
113
160
  "malformed-envelope": 400,
114
161
  "invalid-session": 401,
@@ -122,17 +169,42 @@ const STATUS_BY_REASON: Record<GatewayFailureReason, number> = {
122
169
  "core-unavailable": 503,
123
170
  overloaded: 503,
124
171
  "incompatible-version": 400,
172
+ "transport-unproved": 403,
173
+ "relay-authorization-failed": 403,
174
+ "relay-not-admitted": 403,
175
+ "relay-denied-approval-path": 403,
176
+ "relay-denied-credential-read": 403,
177
+ "relay-denied-local-approval": 403,
178
+ "relay-denied-extension-surface": 403,
179
+ "domain-refused": 400,
125
180
  };
126
181
 
127
182
  export class GatewayError extends Error {
128
183
  readonly reason: GatewayFailureReason;
129
184
  readonly status: number;
185
+ /** A bounded, human-readable refusal detail (the legacy route's own message). Only
186
+ * domain-refused sets it; nothing else echoes error text. */
187
+ readonly detail?: string;
130
188
 
131
189
  constructor(reason: GatewayFailureReason, message?: string) {
132
190
  super(message ?? reason);
133
191
  this.reason = reason;
134
192
  this.status = STATUS_BY_REASON[reason];
135
193
  }
194
+
195
+ /** One domain refusal: the legacy route's own status and bounded message. The detail is
196
+ * clamped hard (a route's fixed words are short) so nothing long can ever ride along. */
197
+ static domainRefused(status: number, message: string): GatewayError {
198
+ const error = new GatewayError("domain-refused", message);
199
+
200
+ if (Number.isInteger(status) && status >= 400 && status < 500) {
201
+ (error as { status: number }).status = status;
202
+ }
203
+
204
+ (error as { detail?: string }).detail = message.slice(0, 200);
205
+
206
+ return error;
207
+ }
136
208
  }
137
209
 
138
210
  const hashHex = (value: string): string =>
@@ -145,9 +217,21 @@ const hashBuffersEqual = (hexA: string, hexB: string): boolean => {
145
217
  return a.length === b.length && timingSafeEqual(a, b);
146
218
  };
147
219
 
220
+ /** One named LOCAL owner operation admitted past the default app-data gate: an exact
221
+ * audience/method pair. Entries are fixed at construction, never at request time. */
222
+ export interface LocalAdmission {
223
+ audience: string;
224
+ method: GatewayMethod;
225
+ }
226
+
148
227
  export interface SessionAuthorityOptions {
149
228
  /** Trusted local clock; a cloud-provided clock is never used (§20). */
150
229
  now?: () => number;
230
+ /** Immutable allowlist of named LOCAL owner app-data operations. Empty/absent (the
231
+ * default) keeps every app-data request denied exactly as before; the list can never be
232
+ * changed after construction and never admits a relayed session, a guest, a non-local
233
+ * subject, or an audience outside `app-data:`. */
234
+ localAdmissions?: readonly LocalAdmission[];
151
235
  /** Test-only shortenings of the §20 idle bound; longer values are rejected. */
152
236
  idleTimeoutMs?: number;
153
237
  /** Test-only shortenings of the §20 absolute bound; longer values are rejected. */
@@ -165,7 +249,8 @@ export class SessionAuthority {
165
249
  SessionRole,
166
250
  { idleTimeoutMs: number; absoluteLifetimeMs: number }
167
251
  >;
168
- private readonly expectedOrigin?: string;
252
+ private readonly localAdmissions: readonly LocalAdmission[];
253
+ private expectedOrigin?: string;
169
254
  private epoch = 0;
170
255
 
171
256
  constructor(options: SessionAuthorityOptions = {}) {
@@ -175,6 +260,7 @@ export class SessionAuthority {
175
260
 
176
261
  this.nowFn = now;
177
262
  this.expectedOrigin = options.expectedOrigin;
263
+ this.localAdmissions = Object.freeze([...(options.localAdmissions ?? [])]);
178
264
  this.caps = {
179
265
  owner: {
180
266
  idleTimeoutMs: idle,
@@ -190,7 +276,7 @@ export class SessionAuthority {
190
276
  /** §20: owner sessions are issued only by core, after the one-time legacy-token
191
277
  * verification of §19's migration exception or an equivalent owner authentication. */
192
278
  issueOwner(subjectId = "local-owner"): IssuedSession {
193
- return this.issue("owner", subjectId);
279
+ return this.issue("owner", subjectId, false);
194
280
  }
195
281
 
196
282
  issueGuest(subjectId: string): IssuedSession {
@@ -198,7 +284,20 @@ export class SessionAuthority {
198
284
  throw new GatewayError("malformed-envelope", "Invalid guest subject");
199
285
  }
200
286
 
201
- return this.issue("guest", subjectId);
287
+ return this.issue("guest", subjectId, false);
288
+ }
289
+
290
+ /** §5/§11: mints the owner-equivalent session for a RELAYED remote principal — a distinct
291
+ * principal bound by its fingerprint, never a sign-in with A's reusable owner token and
292
+ * never a guest/viewer downgrade. The session reaches only the app-data surface admitted
293
+ * by the injected central §11 boundary: no local browser audience and no pair-decision
294
+ * audience is reachable from it, and `revokeSubject` ends it when the relation is lost. */
295
+ issueRelayed(subjectId: string): IssuedSession {
296
+ if (!SUBJECT_ID.test(subjectId)) {
297
+ throw new GatewayError("malformed-envelope", "Invalid relayed subject");
298
+ }
299
+
300
+ return this.issue("owner", subjectId, true);
202
301
  }
203
302
 
204
303
  /** §19 migration exception, once per redemption: core verifies the legacy browser
@@ -275,17 +374,78 @@ export class SessionAuthority {
275
374
  session: {
276
375
  role: record.role,
277
376
  subjectId: record.subjectId,
377
+ relayed: record.relayed,
278
378
  createdAt: record.createdAt,
279
379
  expiresAt: record.expiresAt,
280
380
  },
281
381
  };
282
382
  }
283
383
 
384
+ /** The one admission hook past the local app-data gate: an exact audience/method pair
385
+ * from the immutable constructor allowlist, only for a local (never relayed) owner
386
+ * session whose subject is the fixed local owner. Everything else stays denied, and a
387
+ * constructed-without-list authority denies every app-data request as before. */
388
+ admitsLocalAppData(session: SessionView, audience: string, method: GatewayMethod): boolean {
389
+ return (
390
+ !session.relayed &&
391
+ session.role === "owner" &&
392
+ session.subjectId === LOCAL_OWNER_SUBJECT &&
393
+ audience.startsWith(APPLICATION_DATA_AUDIENCE_PREFIX) &&
394
+ this.localAdmissions.some(
395
+ (each) => each.audience === audience && each.method === method,
396
+ )
397
+ );
398
+ }
399
+
284
400
  /** §20: logout invalidates the session immediately; unknown handles stay unknown. */
285
401
  logout(handle: string): boolean {
286
402
  return typeof handle === "string" && this.sessions.delete(hashHex(handle));
287
403
  }
288
404
 
405
+ /** Re-pin the exact browser origin this authority expects — the launcher moving its
406
+ * browser to a tunnel URL, or back to the loopback bind. The re-pin burns every live
407
+ * session and bumps the epoch, which moves the bootstrap generation, so any armed
408
+ * capability minted for the old origin dies with it. Re-pinning to the origin already
409
+ * pinned is a no-op (no churn, no burn). `undefined` removes the pin for a bind whose
410
+ * policy keeps the gateway off; sessions still burn. The immutable local-admission list
411
+ * is never touched by a re-pin. */
412
+ rePinOrigin(origin: string | undefined): void {
413
+ let next: string | undefined;
414
+
415
+ if (origin !== undefined) {
416
+ if (origin.length === 0 || origin.length > MAX_PIN_ORIGIN) {
417
+ throw new GatewayError("malformed-envelope", "Invalid origin pin");
418
+ }
419
+
420
+ try {
421
+ const url = new URL(origin);
422
+
423
+ if (
424
+ (url.protocol !== "http:" && url.protocol !== "https:") ||
425
+ url.origin !== origin
426
+ ) {
427
+ throw new GatewayError("malformed-envelope", "Invalid origin pin");
428
+ }
429
+ } catch (error) {
430
+ if (error instanceof GatewayError) {
431
+ throw error;
432
+ }
433
+
434
+ throw new GatewayError("malformed-envelope", "Invalid origin pin");
435
+ }
436
+
437
+ next = origin;
438
+ }
439
+
440
+ if (next === this.expectedOrigin) {
441
+ return;
442
+ }
443
+
444
+ this.expectedOrigin = next;
445
+ this.sessions.clear();
446
+ this.epoch += 1;
447
+ }
448
+
289
449
  /** §20: a role change invalidates every live session of that subject; re-auth is forced. */
290
450
  revokeSubject(subjectId: string): number {
291
451
  let removed = 0;
@@ -328,7 +488,7 @@ export class SessionAuthority {
328
488
  return { persisted: false, restartInvalidatesAllSessions: true };
329
489
  }
330
490
 
331
- private issue(role: SessionRole, subjectId: string): IssuedSession {
491
+ private issue(role: SessionRole, subjectId: string, relayed: boolean): IssuedSession {
332
492
  if (role === "owner" && !SUBJECT_ID.test(subjectId)) {
333
493
  throw new GatewayError("malformed-envelope", "Invalid subject");
334
494
  }
@@ -340,6 +500,7 @@ export class SessionAuthority {
340
500
  const record: SessionRecord = {
341
501
  role,
342
502
  subjectId,
503
+ relayed,
343
504
  handleHash: hashHex(handle),
344
505
  csrfTokenHash: hashHex(csrfToken),
345
506
  createdAt: now,
@@ -365,6 +526,7 @@ export class SessionAuthority {
365
526
  view: {
366
527
  role,
367
528
  subjectId,
529
+ relayed,
368
530
  createdAt: record.createdAt,
369
531
  expiresAt: record.expiresAt,
370
532
  },
@@ -472,23 +634,50 @@ export function parseGatewayRequest(input: unknown): GatewayRequest {
472
634
  };
473
635
  }
474
636
 
475
- const failure = <T>(requestId: string, reason: GatewayFailureReason): GatewayResponse<T> => ({
637
+ const failure = <T>(
638
+ requestId: string,
639
+ reason: GatewayFailureReason,
640
+ error?: GatewayError,
641
+ ): GatewayResponse<T> => ({
642
+ v: 1,
643
+ requestId,
644
+ ok: false,
645
+ status: error instanceof GatewayError ? error.status : STATUS_BY_REASON[reason],
646
+ reason,
647
+ ...(error?.detail === undefined ? {} : { data: { error: error.detail } as T }),
648
+ });
649
+
650
+ /** Relay failures carry the named, bounded denial so callers (and tests) can assert exactly
651
+ * which §11 rule fired; the payload is diagnostic only and never contains secrets. */
652
+ const relayFailure = <T>(
653
+ requestId: string,
654
+ reason: GatewayFailureReason,
655
+ denial: string,
656
+ ): GatewayResponse<T> => ({
476
657
  v: 1,
477
658
  requestId,
478
659
  ok: false,
479
660
  status: STATUS_BY_REASON[reason],
480
661
  reason,
662
+ data: { denial } as T,
481
663
  });
482
664
 
483
665
  /** §19: core resolves the handle, checks expiry/revocation and current owner/guest session
484
666
  * rights, validates audience/method and CSRF policy, then — and only then — runs the
485
- * operation handler. Application-data audiences are hard-disabled; pair decisions require
486
- * the independent signed envelope verified by the injected authorizer, never the handle. */
667
+ * operation handler. Application-data audiences stay hard-disabled for LOCAL sessions
668
+ * (byte-identical to the pre-M4 candidate: the local owner gets `app-routing-disabled`, a
669
+ * guest is role-forbidden). A RELAYED owner-role principal (§5/§11) reaches ONLY the v1
670
+ * surface through the injected central boundary: every request is boundary-verified per call,
671
+ * every denial carries its named category, pair decisions stay A-local (§13), and nothing
672
+ * outside the app-data audiences is reachable. */
487
673
  export async function processRequest<T>(
488
674
  authority: SessionAuthority,
489
675
  input: unknown,
490
676
  handler: (session: SessionView, request: GatewayRequest) => T | Promise<T>,
491
- options: { decisionAuthorizer?: DecisionAuthorizer } = {},
677
+ options: {
678
+ decisionAuthorizer?: DecisionAuthorizer;
679
+ relayedBoundary?: RelayedBoundaryResolver;
680
+ } = {},
492
681
  ): Promise<GatewayResponse<T>> {
493
682
  let request: GatewayRequest;
494
683
 
@@ -514,9 +703,68 @@ export async function processRequest<T>(
514
703
 
515
704
  const { session } = outcome;
516
705
 
517
- // Total access gate: application data routing stays disabled for every role.
518
- if (request.audience.startsWith(APPLICATION_DATA_AUDIENCE_PREFIX)) {
519
- return failure(request.requestId, "app-routing-disabled");
706
+ // §5/§11: a relayed remote principal never touches local surfaces. The pair-decision
707
+ // audience is the A-local approval route (§13): named denial BEFORE any authorizer runs.
708
+ // Local browser audiences are simply not admitted — no broad owner equivalence. The
709
+ // admitted v1 app-data surface is decided ONLY by the central boundary, per request.
710
+ if (session.relayed) {
711
+ if (request.audience === PAIR_DECISION_AUDIENCE) {
712
+ return relayFailure<T>(
713
+ request.requestId,
714
+ "relay-denied-local-approval",
715
+ "local-approval-route",
716
+ );
717
+ }
718
+
719
+ if (!request.audience.startsWith(APPLICATION_DATA_AUDIENCE_PREFIX)) {
720
+ return relayFailure<T>(request.requestId, "relay-not-admitted", "not-admitted");
721
+ }
722
+
723
+ const check = options.relayedBoundary?.(session) ?? null;
724
+
725
+ if (check === null) {
726
+ return relayFailure<T>(
727
+ request.requestId,
728
+ "relay-authorization-failed",
729
+ "boundary-unavailable",
730
+ );
731
+ }
732
+
733
+ let verdict: RelayRequestVerdict;
734
+
735
+ try {
736
+ verdict = await check({ audience: request.audience, method: request.method });
737
+ } catch {
738
+ // A boundary failure denies; the error text is never echoed (static, bounded).
739
+ return relayFailure<T>(
740
+ request.requestId,
741
+ "relay-authorization-failed",
742
+ "boundary-unavailable",
743
+ );
744
+ }
745
+
746
+ if (verdict.admitted !== true) {
747
+ const reason =
748
+ verdict.stage === "authorization"
749
+ ? "relay-authorization-failed"
750
+ : (RELAY_DENIAL_REASONS[verdict.denial] ?? "relay-not-admitted");
751
+
752
+ return relayFailure<T>(request.requestId, reason, verdict.denial);
753
+ }
754
+
755
+ // Admitted: the handler runs below, receiving the relayed session view.
756
+ } else if (request.audience.startsWith(APPLICATION_DATA_AUDIENCE_PREFIX)) {
757
+ // Total access gate for LOCAL sessions: denied unless the authority's immutable
758
+ // allowlist admits exactly this named local-owner operation. A guest is always
759
+ // role-forbidden; without the list the gate is byte-identical to the pre-M4
760
+ // candidate (the local owner gets app-routing-disabled).
761
+ if (!authority.admitsLocalAppData(session, request.audience, request.method)) {
762
+ if (session.role === "guest") {
763
+ return failure<T>(request.requestId, "role-forbidden");
764
+ }
765
+
766
+ return failure<T>(request.requestId, "app-routing-disabled");
767
+ }
520
768
  }
521
769
 
522
770
  if (session.role === "guest") {
@@ -542,8 +790,15 @@ export async function processRequest<T>(
542
790
  const data = await handler(session, request);
543
791
 
544
792
  return { v: 1, requestId: request.requestId, ok: true, status: 200, data };
545
- } catch {
546
- return failure(request.requestId, "handler-failed");
793
+ } catch (error) {
794
+ // A typed gateway error carries its own bounded reason and status (a handler can
795
+ // reject a bad operation payload with a 4xx); anything else stays handler-failed.
796
+ // Neither path echoes the error text.
797
+ return failure<T>(
798
+ request.requestId,
799
+ error instanceof GatewayError ? error.reason : "handler-failed",
800
+ error instanceof GatewayError ? error : undefined,
801
+ );
547
802
  }
548
803
  }
549
804