@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.
@@ -0,0 +1,788 @@
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
+ /* --------------------- SEC-14 typed operation policy (D2) --------------------- */
167
+
168
+ /** The stable, explicit actor identity every relayed request must carry (SEC-14 actorField).
169
+ * A remote actor is ALWAYS its own remote device identity — never the local owner, never a
170
+ * claimed role, never derived from Origin/loopback/cookie (PARITY-3: no fake "User A"). */
171
+ export type ApplicationActor =
172
+ | { kind: "local-owner"; subject: string }
173
+ | {
174
+ kind: "remote-device";
175
+ fingerprint: string;
176
+ relationId: string;
177
+ grantEpoch: number;
178
+ };
179
+
180
+ /** The class of principal an operation entry admits. `remote-session` entries are reachable
181
+ * ONLY through a verified relayed session; `local-owner` entries only by the local owner
182
+ * session (whose admissions are separately governed by the session gateway's immutable
183
+ * LocalAdmission list — this registry never widens local access). */
184
+ export type RelayPrincipalClass = "local-owner" | "remote-session";
185
+
186
+ /** One typed operation-policy entry (SEC-14): an exact audience, the admitted methods, the
187
+ * principal class that may reach it, bounded capability names, and the required explicit
188
+ * actor field. Entries are registered here beside RELAY_DENIED_AUDIENCES and
189
+ * RELAY_ADMITTED_SURFACE with the same fail-closed default: anything unlisted is denied. */
190
+ export interface RelayOperationPolicyEntry {
191
+ readonly audience: string;
192
+ readonly methods: readonly ("GET" | "POST")[];
193
+ readonly principalClass: RelayPrincipalClass;
194
+ readonly caps: readonly string[];
195
+ readonly actorField: "actor";
196
+ }
197
+
198
+ /** The registered operation surface (D2-scoped): exactly the two admitted v1 read-only
199
+ * surfaces, reachable only by a REMOTE-SESSION principal through a verified relayed E2EE
200
+ * session. Adding an entry is a reviewed act with its own negative tests (SEC-12); no
201
+ * wildcards, no free-string allowlists. */
202
+ /** One widened row's caps vocabulary: bounded, static names — the family's read view. */
203
+ const familyRow = (audience: string, caps: string) => ({
204
+ audience,
205
+ methods: ["GET"] as const,
206
+ principalClass: "remote-session" as const,
207
+ caps: [caps] as readonly string[],
208
+ actorField: "actor" as const,
209
+ });
210
+
211
+ export const RELAY_OPERATION_POLICY: readonly RelayOperationPolicyEntry[] = [
212
+ {
213
+ audience: "app-data:session-status",
214
+ methods: ["GET"],
215
+ principalClass: "remote-session",
216
+ caps: ["canned-status"],
217
+ actorField: "actor",
218
+ },
219
+ {
220
+ audience: "app-data:session-ping",
221
+ methods: ["GET"],
222
+ principalClass: "remote-session",
223
+ caps: ["canned-ping"],
224
+ actorField: "actor",
225
+ },
226
+ // D3 widening (deny-first, read/view families of the 12 PARITY families; each row is an
227
+ // individually reviewed admission — no wildcards, remote-session GET-only, and every
228
+ // effect/write family stays out pending reliability receipts + owner review):
229
+ familyRow("app-data:conversation-history-read", "conversation-view"),
230
+ familyRow("app-data:conversation-entry-read", "conversation-view"),
231
+ familyRow("app-data:conversation-context-read", "conversation-view"),
232
+ familyRow("app-data:conversation-messages-read", "conversation-view"),
233
+ familyRow("app-data:conversation-changes-read", "conversation-view"),
234
+ familyRow("app-data:conversation-branches-read", "conversation-view"),
235
+ familyRow("app-data:conversation-files-list", "conversation-files-view"),
236
+ familyRow("app-data:conversation-prompts-list", "conversation-files-view"),
237
+ familyRow("app-data:conversation-view-file", "conversation-files-view"),
238
+ familyRow("app-data:conversation-memory-read", "conversation-memory-view"),
239
+ familyRow("app-data:conversation-trust-read", "conversation-memory-view"),
240
+ familyRow("app-data:conversation-artifact-state-read", "conversation-artifacts-view"),
241
+ familyRow("app-data:conversation-shares-list", "conversation-artifacts-view"),
242
+ familyRow("app-data:hooks-list", "hooks-view"),
243
+ familyRow("app-data:push-read", "push-view"),
244
+ ];
245
+
246
+ /** Machine-readable, bounded policy denials (SEC-14 typed verdicts). None of these names
247
+ * carries secret material; they are the actor-layer complements of the §11 denials above. */
248
+ export type OperationPolicyDenial =
249
+ | "actor-missing"
250
+ | "actor-forged"
251
+ | "actor-principal-mismatch"
252
+ | "policy-not-admitted"
253
+ | "method-not-admitted";
254
+
255
+ export type OperationPolicyVerdict =
256
+ | { admitted: true; entry: RelayOperationPolicyEntry }
257
+ | { admitted: false; denial: OperationPolicyDenial };
258
+
259
+ const ACTOR_FINGERPRINT = /^[A-Za-z0-9][A-Za-z0-9_.:-]{0,127}$/;
260
+
261
+ /** The typed operation-policy check (SEC-14). It runs AFTER the §11 authorization of the
262
+ * session context and validates the EXPLICIT actor against the VERIFIED session facts:
263
+ * a remote-session request must carry a remote-device actor whose fingerprint, relation and
264
+ * grant epoch are exactly the live session's (never a self-declared identity), a claimed
265
+ * local-owner actor over a relayed session is FORGED by definition, and every unlisted
266
+ * audience/method stays denied. Local (non-relayed) sessions have no registered entries —
267
+ * the local owner's app-data admissions stay owned by the session gateway's immutable list. */
268
+ export function authorizeOperationByPolicy(input: {
269
+ /** True only for a verified relayed remote session (SEC-14: verified actor path). */
270
+ sessionRelayed: boolean;
271
+ /** The A-attested principal bound to the live verified session. */
272
+ sessionPrincipal: string;
273
+ /** The live relation/grant binding of the session, when relayed. */
274
+ sessionRelation: { relationId: string; grantEpoch: number } | null;
275
+ /** The explicit actor field the request carried (unknown shape until validated here). */
276
+ actor: unknown;
277
+ audience: string;
278
+ method: "GET" | "POST";
279
+ }): OperationPolicyVerdict {
280
+ if (input.actor === null || typeof input.actor !== "object") {
281
+ return { admitted: false, denial: "actor-missing" };
282
+ }
283
+
284
+ const actor = input.actor as Record<string, unknown>;
285
+
286
+ if (input.sessionRelayed) {
287
+ // A relayed session may only ever present its own remote device identity. A local-owner
288
+ // claim over a relayed session is forged by definition — the remote actor is never the
289
+ // local owner and can never become it (PARITY-3).
290
+ if (actor.kind !== "remote-device") {
291
+ return { admitted: false, denial: "actor-forged" };
292
+ }
293
+
294
+ if (
295
+ typeof actor.fingerprint !== "string" ||
296
+ !ACTOR_FINGERPRINT.test(actor.fingerprint) ||
297
+ typeof actor.relationId !== "string" ||
298
+ typeof actor.grantEpoch !== "number" ||
299
+ !Number.isSafeInteger(actor.grantEpoch)
300
+ ) {
301
+ return { admitted: false, denial: "actor-forged" };
302
+ }
303
+
304
+ // Identity comes ONLY from the verified session facts, never from the request claim:
305
+ // the actor must BE the session's principal on the same live relation and grant epoch.
306
+ if (
307
+ actor.fingerprint !== input.sessionPrincipal ||
308
+ input.sessionRelation === null ||
309
+ actor.relationId !== input.sessionRelation.relationId ||
310
+ actor.grantEpoch !== input.sessionRelation.grantEpoch
311
+ ) {
312
+ return { admitted: false, denial: "actor-principal-mismatch" };
313
+ }
314
+ } else {
315
+ // Local sessions have no registered remote-session entries; a remote-device actor on a
316
+ // local session is just as forged (an actor may never claim a class it cannot hold).
317
+ if (actor.kind !== "local-owner" || typeof actor.subject !== "string") {
318
+ return { admitted: false, denial: "actor-forged" };
319
+ }
320
+ }
321
+
322
+ const entry = RELAY_OPERATION_POLICY.find((each) => each.audience === input.audience);
323
+
324
+ if (
325
+ entry === undefined ||
326
+ entry.principalClass !== (input.sessionRelayed ? "remote-session" : "local-owner")
327
+ ) {
328
+ return { admitted: false, denial: "policy-not-admitted" };
329
+ }
330
+
331
+ if (!entry.methods.includes(input.method)) {
332
+ return { admitted: false, denial: "method-not-admitted" };
333
+ }
334
+
335
+ return { admitted: true, entry };
336
+ }
337
+
338
+ export type RelaySurfaceName =
339
+ | "session-status"
340
+ | "session-ping"
341
+ | "conversation-history-read"
342
+ | "conversation-entry-read"
343
+ | "conversation-context-read"
344
+ | "conversation-messages-read"
345
+ | "conversation-changes-read"
346
+ | "conversation-branches-read"
347
+ | "conversation-files-list"
348
+ | "conversation-prompts-list"
349
+ | "conversation-view-file"
350
+ | "conversation-memory-read"
351
+ | "conversation-trust-read"
352
+ | "conversation-artifact-state-read"
353
+ | "conversation-shares-list"
354
+ | "hooks-list"
355
+ | "push-read";
356
+
357
+ /** The frozen M4 v1 admitted surface (the canned pilot lane's set): exactly the two
358
+ * read-only session operations. Byte-identical default for every existing consumer. */
359
+ const ADMITTED_SURFACES = new Map<string, RelaySurfaceName>([
360
+ ["app-data:session-status", "session-status"],
361
+ ["app-data:session-ping", "session-ping"],
362
+ ]);
363
+
364
+ /** D3 backend gap (2): the family-by-family WIDENED read/view surface for the remote
365
+ * (secure) lane — one explicit GET row per family operation of the 12 PARITY families'
366
+ * read-only subset, deny-first: nothing is admitted that is not an exact row here, every
367
+ * effect/write family stays out, and every row is off the §11 negative lists (asserted by
368
+ * test). This table is INERT until a boundary is constructed with surfaceSet "remote-v2";
369
+ * the default boundary keeps the v1 two. */
370
+ export const RELAY_REMOTE_SURFACE_V2: readonly {
371
+ audience: string;
372
+ method: "GET";
373
+ surface: RelaySurfaceName;
374
+ }[] = [
375
+ {
376
+ audience: "app-data:conversation-history-read",
377
+ method: "GET",
378
+ surface: "conversation-history-read",
379
+ },
380
+ {
381
+ audience: "app-data:conversation-entry-read",
382
+ method: "GET",
383
+ surface: "conversation-entry-read",
384
+ },
385
+ {
386
+ audience: "app-data:conversation-context-read",
387
+ method: "GET",
388
+ surface: "conversation-context-read",
389
+ },
390
+ {
391
+ audience: "app-data:conversation-messages-read",
392
+ method: "GET",
393
+ surface: "conversation-messages-read",
394
+ },
395
+ {
396
+ audience: "app-data:conversation-changes-read",
397
+ method: "GET",
398
+ surface: "conversation-changes-read",
399
+ },
400
+ {
401
+ audience: "app-data:conversation-branches-read",
402
+ method: "GET",
403
+ surface: "conversation-branches-read",
404
+ },
405
+ {
406
+ audience: "app-data:conversation-files-list",
407
+ method: "GET",
408
+ surface: "conversation-files-list",
409
+ },
410
+ {
411
+ audience: "app-data:conversation-prompts-list",
412
+ method: "GET",
413
+ surface: "conversation-prompts-list",
414
+ },
415
+ {
416
+ audience: "app-data:conversation-view-file",
417
+ method: "GET",
418
+ surface: "conversation-view-file",
419
+ },
420
+ {
421
+ audience: "app-data:conversation-memory-read",
422
+ method: "GET",
423
+ surface: "conversation-memory-read",
424
+ },
425
+ {
426
+ audience: "app-data:conversation-trust-read",
427
+ method: "GET",
428
+ surface: "conversation-trust-read",
429
+ },
430
+ {
431
+ audience: "app-data:conversation-artifact-state-read",
432
+ method: "GET",
433
+ surface: "conversation-artifact-state-read",
434
+ },
435
+ {
436
+ audience: "app-data:conversation-shares-list",
437
+ method: "GET",
438
+ surface: "conversation-shares-list",
439
+ },
440
+ { audience: "app-data:hooks-list", method: "GET", surface: "hooks-list" },
441
+ { audience: "app-data:push-read", method: "GET", surface: "push-read" },
442
+ ];
443
+
444
+ const REMOTE_V2_SURFACES = new Map<string, RelaySurfaceName>([
445
+ ...ADMITTED_SURFACES,
446
+ ...RELAY_REMOTE_SURFACE_V2.map((row) => [row.audience, row.surface] as const),
447
+ ]);
448
+
449
+ /** The named (a)–(d) category for an audience, or null when the audience is not on the
450
+ * negative list (it may still be denied, as `not-admitted`, by the surface classification). */
451
+ export function relayDenialCategoryOf(audience: string): RelayDenialCategory | null {
452
+ const prefix = "app-data:";
453
+
454
+ if (!audience.startsWith(prefix)) {
455
+ return null;
456
+ }
457
+
458
+ const rest = audience.slice(prefix.length);
459
+
460
+ for (const category of Object.keys(RELAY_DENIED_AUDIENCES) as RelayDenialCategory[]) {
461
+ for (const suffix of RELAY_DENIED_AUDIENCES[category]) {
462
+ if (rest === suffix || rest.startsWith(`${suffix}:`)) {
463
+ return category;
464
+ }
465
+ }
466
+ }
467
+
468
+ return null;
469
+ }
470
+
471
+ export type RelaySurfaceVerdict =
472
+ | { admitted: true; surface: RelaySurfaceName }
473
+ | { admitted: false; denial: RelayDenialCategory | "not-admitted" };
474
+
475
+ /** Surface classification only — authorization is verified separately, first, per request. */
476
+ export function classifyRelayedRequest(
477
+ audience: string,
478
+ method: "GET" | "POST",
479
+ surfaces: ReadonlyMap<string, RelaySurfaceName> = ADMITTED_SURFACES,
480
+ ): RelaySurfaceVerdict {
481
+ // §11 negative-list first, regardless of method: an approval/credential/extension
482
+ // audience carries its named category even as a write — the category is the security
483
+ // signal, and a bare `not-admitted` would hide WHICH forbidden lane was attempted.
484
+ // The negative list applies to EVERY surface set, widened or not.
485
+ const category = relayDenialCategoryOf(audience);
486
+
487
+ if (category !== null) {
488
+ return { admitted: false, denial: category };
489
+ }
490
+
491
+ if (method !== "GET") {
492
+ return { admitted: false, denial: "not-admitted" };
493
+ }
494
+
495
+ const surface = surfaces.get(audience);
496
+
497
+ if (surface !== undefined) {
498
+ return { admitted: true, surface };
499
+ }
500
+
501
+ return { admitted: false, denial: "not-admitted" };
502
+ }
503
+
504
+ /** Why a request's §11 authorization failed. Machine-readable, static, bounded; none of these
505
+ * names ever carry secret material (fingerprints and ids stay in A's stores). */
506
+ export type RelayAuthorizationDenial =
507
+ | "malformed-claims"
508
+ | "relation-unknown"
509
+ | "grant-epoch-mismatch"
510
+ | "direction-mismatch"
511
+ | "principal-mismatch"
512
+ | "membership-mismatch"
513
+ | "relation-revoked"
514
+ | "grant-expired"
515
+ | "membership-unknown"
516
+ | "membership-not-live"
517
+ | "membership-stale";
518
+
519
+ export type RelayRequestVerdict =
520
+ | { admitted: true; surface: RelaySurfaceName }
521
+ | { admitted: false; stage: "authorization"; denial: RelayAuthorizationDenial }
522
+ | { admitted: false; stage: "surface"; denial: RelayDenialCategory | "not-admitted" };
523
+
524
+ export interface RelaySessionInput {
525
+ /** A-attested principal bound to the live authenticated relayed session (B's fingerprint,
526
+ * 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)). */
527
+ sessionPrincipal: string;
528
+ /** The exact claims X forwarded on relay-open; never trusted without ledger verification. */
529
+ claims: RelayAuthorizationClaims;
530
+ /** An X-advertised expiry, when present, is type-checked and then deliberately NEVER
531
+ * consulted: A's own stored grant is the only expiry authority (§11). */
532
+ advertisedExpiry?: number;
533
+ }
534
+
535
+ export interface RelayRouteInput extends RelaySessionInput {
536
+ /** The relayed operation to admit or deny (the gateway audience + method). */
537
+ request: { audience: string; method: "GET" | "POST" };
538
+ }
539
+
540
+ export type RelaySessionAdmission =
541
+ | { admitted: true; authority: RelayChannelAuthority }
542
+ | { admitted: false; denial: RelayAuthorizationDenial };
543
+
544
+ /** The per-channel authority returned by a successful relay-open admission. It holds the
545
+ * bound principal and the exact claims, and re-runs the FULL §11 authorization for every
546
+ * request against fresh ledger reads — no verdict is ever cached (§11: test every relayed
547
+ * request at A's central boundary). */
548
+ export interface RelayChannelAuthority {
549
+ readonly sessionPrincipal: string;
550
+ readonly claims: RelayAuthorizationClaims;
551
+ checkRequest(request: { audience: string; method: "GET" | "POST" }): RelayRequestVerdict;
552
+ }
553
+
554
+ const RELATION_ID = /^[A-Za-z0-9][A-Za-z0-9_.:-]{0,127}$/;
555
+ const PRINCIPAL_ID = /^[A-Za-z0-9][A-Za-z0-9_.:-]{0,127}$/;
556
+
557
+ const validMembershipRef = (ref: unknown): ref is RelayMembershipRef =>
558
+ ref !== null &&
559
+ typeof ref === "object" &&
560
+ typeof (ref as RelayMembershipRef).id === "string" &&
561
+ RELATION_ID.test((ref as RelayMembershipRef).id) &&
562
+ typeof (ref as RelayMembershipRef).epoch === "number" &&
563
+ Number.isSafeInteger((ref as RelayMembershipRef).epoch) &&
564
+ (ref as RelayMembershipRef).epoch >= 0;
565
+
566
+ const validClaims = (claims: RelayAuthorizationClaims): boolean =>
567
+ claims !== null &&
568
+ typeof claims === "object" &&
569
+ typeof claims.relationId === "string" &&
570
+ RELATION_ID.test(claims.relationId) &&
571
+ typeof claims.requesterFp === "string" &&
572
+ PRINCIPAL_ID.test(claims.requesterFp) &&
573
+ typeof claims.grantEpoch === "number" &&
574
+ Number.isSafeInteger(claims.grantEpoch) &&
575
+ claims.grantEpoch >= 1 &&
576
+ (claims.direction === "requester-to-target" || claims.direction === "target-to-requester") &&
577
+ validMembershipRef(claims.requesterMembership) &&
578
+ validMembershipRef(claims.targetMembership);
579
+
580
+ /** A's own grant record is validated too: a corrupt read denies (fail-closed), it never admits. */
581
+ const validGrant = (grant: RelayGrantRecord): boolean =>
582
+ grant !== null &&
583
+ typeof grant === "object" &&
584
+ typeof grant.relationId === "string" &&
585
+ (grant.direction === "requester-to-target" || grant.direction === "target-to-requester") &&
586
+ typeof grant.grantEpoch === "number" &&
587
+ Number.isSafeInteger(grant.grantEpoch) &&
588
+ grant.grantEpoch >= 1 &&
589
+ typeof grant.expiresAt === "number" &&
590
+ Number.isFinite(grant.expiresAt) &&
591
+ typeof grant.requesterFp === "string" &&
592
+ typeof grant.targetFp === "string" &&
593
+ validMembershipRef(grant.requesterMembership) &&
594
+ validMembershipRef(grant.targetMembership);
595
+
596
+ const sameMembershipRef = (a: RelayMembershipRef, b: RelayMembershipRef): boolean =>
597
+ a.id === b.id && a.epoch === b.epoch;
598
+
599
+ export interface RelayBoundaryOptions {
600
+ /** A's trusted local clock; a cloud-provided clock is never used (§20 discipline). */
601
+ now?: () => number;
602
+ /** Injected reads of A's own grant store, relation ledger and membership register. */
603
+ ledger: RelayLedgerReads;
604
+ /** Which admitted-surface set §11 classification uses: "v1" (default — the frozen M4
605
+ * two, the canned pilot lane's exact behavior) or "remote-v2" (the widened read/view
606
+ * family registry, for the SECURE lane only). Deny-first either way: the negative list
607
+ * and the exact-row lookup govern; nothing outside the chosen set is ever admitted. */
608
+ surfaceSet?: "v1" | "remote-v2";
609
+ }
610
+
611
+ export class RelayBoundary {
612
+ private readonly now: () => number;
613
+ private readonly surfaces: ReadonlyMap<string, RelaySurfaceName>;
614
+ private readonly ledger: RelayLedgerReads;
615
+
616
+ constructor(options: RelayBoundaryOptions) {
617
+ this.now = options.now ?? Date.now;
618
+ this.ledger = options.ledger;
619
+ this.surfaces = options.surfaceSet === "remote-v2" ? REMOTE_V2_SURFACES : ADMITTED_SURFACES;
620
+ }
621
+
622
+ /** relay-open admission: the full §11 authorization runs NOW, and the returned channel
623
+ * authority re-verifies every subsequent request (expiry, revoke and membership loss can
624
+ * never be bypassed by an earlier admission, §11 "reauthorize ... at this boundary"). */
625
+ admitSession(input: RelaySessionInput): RelaySessionAdmission {
626
+ const verdict = this.verify(input);
627
+
628
+ if (!verdict.ok) {
629
+ return { admitted: false, denial: verdict.denial };
630
+ }
631
+
632
+ return { admitted: true, authority: new BoundChannelAuthority(this, input) };
633
+ }
634
+
635
+ /** One relayed request: full §11 authorization of the context first, then the surface
636
+ * classification. Denials are named verdicts, never throws. */
637
+ authorize(input: RelayRouteInput): RelayRequestVerdict {
638
+ const verdict = this.verify(input);
639
+
640
+ if (!verdict.ok) {
641
+ return { admitted: false, stage: "authorization", denial: verdict.denial };
642
+ }
643
+
644
+ const surface = classifyRelayedRequest(
645
+ input.request.audience,
646
+ input.request.method,
647
+ this.surfaces,
648
+ );
649
+
650
+ if (!surface.admitted) {
651
+ return { admitted: false, stage: "surface", denial: surface.denial };
652
+ }
653
+
654
+ return { admitted: true, surface: surface.surface };
655
+ }
656
+
657
+ /** Channel-authority hook: re-runs authorize with the bound principal and claims so every
658
+ * request re-reads the ledger fresh. */
659
+ check(
660
+ input: RelaySessionInput,
661
+ request: { audience: string; method: "GET" | "POST" },
662
+ ): RelayRequestVerdict {
663
+ return this.authorize({
664
+ sessionPrincipal: input.sessionPrincipal,
665
+ claims: input.claims,
666
+ request,
667
+ });
668
+ }
669
+
670
+ /** The per-request §11 verification order is fixed and documented: shape → stored grant →
671
+ * exact claims → binding/distinctness → revoke → expiry → live membership both sides. */
672
+ private verify(
673
+ input: RelaySessionInput,
674
+ ): { ok: true } | { ok: false; denial: RelayAuthorizationDenial } {
675
+ if (
676
+ typeof input.sessionPrincipal !== "string" ||
677
+ !PRINCIPAL_ID.test(input.sessionPrincipal) ||
678
+ !validClaims(input.claims) ||
679
+ (input.advertisedExpiry !== undefined && !Number.isFinite(input.advertisedExpiry))
680
+ ) {
681
+ return { ok: false, denial: "malformed-claims" };
682
+ }
683
+
684
+ const claims = input.claims;
685
+ const grant = this.ledger.grant(claims.relationId);
686
+
687
+ if (grant === null || !validGrant(grant)) {
688
+ return { ok: false, denial: "relation-unknown" };
689
+ }
690
+
691
+ if (claims.grantEpoch !== grant.grantEpoch) {
692
+ return { ok: false, denial: "grant-epoch-mismatch" };
693
+ }
694
+
695
+ if (claims.direction !== grant.direction) {
696
+ return { ok: false, denial: "direction-mismatch" };
697
+ }
698
+
699
+ // Distinct bound remote principal: the live session's principal must be exactly the
700
+ // relation's requester, and the two endpoints must differ (§11).
701
+ if (
702
+ input.sessionPrincipal !== claims.requesterFp ||
703
+ input.sessionPrincipal !== grant.requesterFp ||
704
+ grant.requesterFp === grant.targetFp
705
+ ) {
706
+ return { ok: false, denial: "principal-mismatch" };
707
+ }
708
+
709
+ // BOTH original membership IDs/epochs, exact (§11).
710
+ if (
711
+ !sameMembershipRef(claims.requesterMembership, grant.requesterMembership) ||
712
+ !sameMembershipRef(claims.targetMembership, grant.targetMembership)
713
+ ) {
714
+ return { ok: false, denial: "membership-mismatch" };
715
+ }
716
+
717
+ // Revoke state from A's relation ledger, per request (either side's revocation wins).
718
+ if (this.ledger.revoked(claims.relationId) === true) {
719
+ return { ok: false, denial: "relation-revoked" };
720
+ }
721
+
722
+ // Expiry from A's OWN stored grant against A's clock. `advertisedExpiry` is present on
723
+ // the input only to prove it is ignored: it is never compared to anything (§11).
724
+ if (this.now() >= grant.expiresAt) {
725
+ return { ok: false, denial: "grant-expired" };
726
+ }
727
+
728
+ // Authenticated LIVE membership, both sides: the original ref must still be the
729
+ // current enrollment (a re-enroll stales it) and registered live.
730
+ const requesterEntry = this.ledger.membership(claims.requesterMembership);
731
+
732
+ if (requesterEntry === null) {
733
+ return { ok: false, denial: "membership-unknown" };
734
+ }
735
+
736
+ if (requesterEntry.live !== true) {
737
+ return { ok: false, denial: "membership-not-live" };
738
+ }
739
+
740
+ if (requesterEntry.currentEpoch !== claims.requesterMembership.epoch) {
741
+ return { ok: false, denial: "membership-stale" };
742
+ }
743
+
744
+ const targetEntry = this.ledger.membership(claims.targetMembership);
745
+
746
+ if (targetEntry === null) {
747
+ return { ok: false, denial: "membership-unknown" };
748
+ }
749
+
750
+ if (targetEntry.live !== true) {
751
+ return { ok: false, denial: "membership-not-live" };
752
+ }
753
+
754
+ if (targetEntry.currentEpoch !== claims.targetMembership.epoch) {
755
+ return { ok: false, denial: "membership-stale" };
756
+ }
757
+
758
+ return { ok: true };
759
+ }
760
+ }
761
+
762
+ class BoundChannelAuthority implements RelayChannelAuthority {
763
+ readonly sessionPrincipal: string;
764
+ readonly claims: RelayAuthorizationClaims;
765
+ private readonly boundary: RelayBoundary;
766
+
767
+ constructor(boundary: RelayBoundary, input: RelaySessionInput) {
768
+ this.boundary = boundary;
769
+ this.sessionPrincipal = input.sessionPrincipal;
770
+ // Freeze the binding: the channel authority carries copies, so later mutation of the
771
+ // caller's objects cannot change what this channel is bound to.
772
+ this.claims = {
773
+ relationId: input.claims.relationId,
774
+ grantEpoch: input.claims.grantEpoch,
775
+ requesterMembership: { ...input.claims.requesterMembership },
776
+ targetMembership: { ...input.claims.targetMembership },
777
+ direction: input.claims.direction,
778
+ requesterFp: input.claims.requesterFp,
779
+ };
780
+ }
781
+
782
+ checkRequest(request: { audience: string; method: "GET" | "POST" }): RelayRequestVerdict {
783
+ return this.boundary.check(
784
+ { sessionPrincipal: this.sessionPrincipal, claims: this.claims },
785
+ request,
786
+ );
787
+ }
788
+ }