@bom-pi/core 0.1.4 → 0.2.1

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.
@@ -163,13 +163,289 @@ export const RELAY_ADMITTED_SURFACE = [
163
163
  { audience: "app-data:session-ping", method: "GET" },
164
164
  ] as const;
165
165
 
166
- export type RelaySurfaceName = "session-status" | "session-ping";
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
+ }
167
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. */
168
359
  const ADMITTED_SURFACES = new Map<string, RelaySurfaceName>([
169
360
  ["app-data:session-status", "session-status"],
170
361
  ["app-data:session-ping", "session-ping"],
171
362
  ]);
172
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
+
173
449
  /** The named (a)–(d) category for an audience, or null when the audience is not on the
174
450
  * negative list (it may still be denied, as `not-admitted`, by the surface classification). */
175
451
  export function relayDenialCategoryOf(audience: string): RelayDenialCategory | null {
@@ -200,10 +476,12 @@ export type RelaySurfaceVerdict =
200
476
  export function classifyRelayedRequest(
201
477
  audience: string,
202
478
  method: "GET" | "POST",
479
+ surfaces: ReadonlyMap<string, RelaySurfaceName> = ADMITTED_SURFACES,
203
480
  ): RelaySurfaceVerdict {
204
481
  // §11 negative-list first, regardless of method: an approval/credential/extension
205
482
  // audience carries its named category even as a write — the category is the security
206
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.
207
485
  const category = relayDenialCategoryOf(audience);
208
486
 
209
487
  if (category !== null) {
@@ -214,7 +492,7 @@ export function classifyRelayedRequest(
214
492
  return { admitted: false, denial: "not-admitted" };
215
493
  }
216
494
 
217
- const surface = ADMITTED_SURFACES.get(audience);
495
+ const surface = surfaces.get(audience);
218
496
 
219
497
  if (surface !== undefined) {
220
498
  return { admitted: true, surface };
@@ -323,15 +601,22 @@ export interface RelayBoundaryOptions {
323
601
  now?: () => number;
324
602
  /** Injected reads of A's own grant store, relation ledger and membership register. */
325
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";
326
609
  }
327
610
 
328
611
  export class RelayBoundary {
329
612
  private readonly now: () => number;
613
+ private readonly surfaces: ReadonlyMap<string, RelaySurfaceName>;
330
614
  private readonly ledger: RelayLedgerReads;
331
615
 
332
616
  constructor(options: RelayBoundaryOptions) {
333
617
  this.now = options.now ?? Date.now;
334
618
  this.ledger = options.ledger;
619
+ this.surfaces = options.surfaceSet === "remote-v2" ? REMOTE_V2_SURFACES : ADMITTED_SURFACES;
335
620
  }
336
621
 
337
622
  /** relay-open admission: the full §11 authorization runs NOW, and the returned channel
@@ -356,7 +641,11 @@ export class RelayBoundary {
356
641
  return { admitted: false, stage: "authorization", denial: verdict.denial };
357
642
  }
358
643
 
359
- const surface = classifyRelayedRequest(input.request.audience, input.request.method);
644
+ const surface = classifyRelayedRequest(
645
+ input.request.audience,
646
+ input.request.method,
647
+ this.surfaces,
648
+ );
360
649
 
361
650
  if (!surface.admitted) {
362
651
  return { admitted: false, stage: "surface", denial: surface.denial };
@@ -0,0 +1,105 @@
1
+ /** SEC-13 multichannel relay wire framing (D2-scoped, feature-detected): one single-source
2
+ * binary envelope that carries a relayed frame's CHANNEL identity next to its opaque payload.
3
+ * The format is deliberately header-only: X (the cloud relay) reads the version byte and the
4
+ * 16-byte channel id for ROUTING and never inspects, parses or rewrites the body — routing
5
+ * authority, not payload authority (§12). Endpoints frame and deframe; every body byte is the
6
+ * endpoint's own §21 material (handshake bytes before the session exists, sealed frames
7
+ * after), so X still has no plaintext application path by construction (SEC-1).
8
+ *
9
+ * Wire layout of one mux frame (both directions, after a mux channel is open):
10
+ *
11
+ * byte 0 mux frame version, always 0x01
12
+ * bytes 1..17 the channel id as 16 raw bytes (the 32-hex id X minted via CSPRNG)
13
+ * bytes 17.. opaque channel body (handshake or sealed frame)
14
+ *
15
+ * The 0x01 leading byte can never collide with the legacy relay lane's payloads in practice:
16
+ * those are canonical JSON objects, which always begin with `{` (0x7B). A session that holds
17
+ * mux channels requires every binary frame to be a well-formed mux frame for a channel it
18
+ * holds; anything else is a protocol violation, never a silent fallback to the legacy lane
19
+ * (fail-closed, no mode mixing inside one session pair).
20
+ *
21
+ * Channel ids are unprivileged routing tokens minted by X from the CSPRNG (`randomBytes(16)`
22
+ * hex-encoded): they are NOT capabilities — every authorization decision stays at A's central
23
+ * §11 boundary per request (SEC-13 item 1 upgrade of the old `Date.now/Math.random` mix; the
24
+ * id still grants nothing). */
25
+
26
+ /** The only mux frame version this module emits or accepts. */
27
+ export const MUX_FRAME_VERSION = 1;
28
+
29
+ /** Channel ids are 16 raw bytes on the wire (32 hex characters in every API surface). */
30
+ export const MUX_CHANNEL_BYTES = 16;
31
+
32
+ /** Total header size: version byte + 16 channel-id bytes. */
33
+ export const MUX_HEADER_BYTES = 1 + MUX_CHANNEL_BYTES;
34
+
35
+ /** Channel ids are exactly 32 lowercase hex characters everywhere except inside a frame. */
36
+ export const MUX_CHANNEL_ID_HEX = /^[0-9a-f]{32}$/;
37
+
38
+ export type MuxFrame = {
39
+ readonly channelId: string;
40
+ readonly body: Uint8Array;
41
+ };
42
+
43
+ const fromHex = (hex: string): Uint8Array | null => {
44
+ if (!MUX_CHANNEL_ID_HEX.test(hex)) {
45
+ return null;
46
+ }
47
+
48
+ const out = new Uint8Array(MUX_CHANNEL_BYTES);
49
+
50
+ for (let index = 0; index < MUX_CHANNEL_BYTES; index++) {
51
+ out[index] = Number.parseInt(hex.slice(index * 2, index * 2 + 2), 16);
52
+ }
53
+
54
+ return out;
55
+ };
56
+
57
+ const toHex = (raw: Uint8Array): string => {
58
+ let hex = "";
59
+
60
+ for (const byte of raw) {
61
+ hex += byte.toString(16).padStart(2, "0");
62
+ }
63
+
64
+ return hex;
65
+ };
66
+
67
+ /** Frames one opaque channel body for a known channel id. The id must be the exact 32-hex
68
+ * token X minted; the body may be empty only when a caller explicitly wants a keepalive —
69
+ * relay data frames themselves stay non-empty by the §16 lane rules. */
70
+ export function encodeMuxFrame(channelId: string, body: Uint8Array): Uint8Array {
71
+ const id = fromHex(channelId);
72
+
73
+ if (id === null) {
74
+ throw new Error("Invalid mux channel id");
75
+ }
76
+
77
+ const frame = new Uint8Array(MUX_HEADER_BYTES + body.length);
78
+
79
+ frame[0] = MUX_FRAME_VERSION;
80
+ frame.set(id, 1);
81
+ frame.set(body, MUX_HEADER_BYTES);
82
+
83
+ return frame;
84
+ }
85
+
86
+ /** Parses a mux frame header and returns the channel id plus a view of the opaque body.
87
+ * Returns null for anything that is not a well-formed v1 mux frame: wrong version, short
88
+ * header, or a non-hex-neutral id encoding. The body is returned as-is, never validated. */
89
+ export function parseMuxFrame(payload: Uint8Array): MuxFrame | null {
90
+ if (payload.length < MUX_HEADER_BYTES || payload[0] !== MUX_FRAME_VERSION) {
91
+ return null;
92
+ }
93
+
94
+ return {
95
+ channelId: toHex(payload.subarray(1, MUX_HEADER_BYTES)),
96
+ body: payload.subarray(MUX_HEADER_BYTES),
97
+ };
98
+ }
99
+
100
+ /** True only when the payload carries the v1 mux leading byte with a full header present.
101
+ * Routing decisions still require parseMuxFrame plus a channel-table hit — this is the cheap
102
+ * first-byte/length precheck the transports use to pick the demux branch. */
103
+ export function isMuxFrame(payload: Uint8Array): boolean {
104
+ return payload.length >= MUX_HEADER_BYTES && payload[0] === MUX_FRAME_VERSION;
105
+ }