@bom-pi/core 0.1.1 → 0.1.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,21 +1,27 @@
1
1
  {
2
- "name": "@bom-pi/core",
3
- "version": "0.1.1",
4
- "description": "Core pairing machinery for Bom Pi: ceremonies, transports, durable stores",
5
- "type": "module",
6
- "license": "MIT",
7
- "dependencies": {
8
- "@bom-pi/protocol": "0.1.0"
9
- },
10
- "exports": {
11
- "./cloud-connector.ts": "./src/cloud-connector.ts",
12
- "./cloud-wss-transport.ts": "./src/cloud-wss-transport.ts",
13
- "./connector-store.ts": "./src/connector-store.ts",
14
- "./device-ceremony.ts": "./src/device-ceremony.ts",
15
- "./ingress-receiver.ts": "./src/ingress-receiver.ts",
16
- "./lan-pairing.ts": "./src/lan-pairing.ts",
17
- "./pairing-storage.ts": "./src/pairing-storage.ts",
18
- "./secure-transport.ts": "./src/secure-transport.ts",
19
- "./session-gateway.ts": "./src/session-gateway.ts"
20
- }
2
+ "name": "@bom-pi/core",
3
+ "version": "0.1.3",
4
+ "description": "Core pairing machinery for Bom Pi: ceremonies, transports, durable stores",
5
+ "type": "module",
6
+ "license": "MIT",
7
+ "dependencies": {
8
+ "@bom-pi/protocol": "^0.1.1"
9
+ },
10
+ "exports": {
11
+ "./cloud-connector.ts": "./src/cloud-connector.ts",
12
+ "./cloud-wss-transport.ts": "./src/cloud-wss-transport.ts",
13
+ "./connector-store.ts": "./src/connector-store.ts",
14
+ "./device-ceremony.ts": "./src/device-ceremony.ts",
15
+ "./ingress-receiver.ts": "./src/ingress-receiver.ts",
16
+ "./lan-pairing.ts": "./src/lan-pairing.ts",
17
+ "./pairing-storage.ts": "./src/pairing-storage.ts",
18
+ "./secure-transport.ts": "./src/secure-transport.ts",
19
+ "./session-gateway.ts": "./src/session-gateway.ts"
20
+ },
21
+ "files": [
22
+ "src/",
23
+ "README.md"
24
+ ],
25
+ "main": "src/index.ts",
26
+ "types": "src/index.ts"
21
27
  }
@@ -12,6 +12,7 @@ import {
12
12
  type KeyObject,
13
13
  } from "node:crypto";
14
14
  import { canonicalJson, parseCanonicalJson, type CanonicalValue } from "@bom-pi/protocol/codec.ts";
15
+ import { DAEMON_PROOF_DOMAIN } from "@bom-pi/protocol/daemon-proof.ts";
15
16
  import { fingerprintPublicKey } from "@bom-pi/protocol/identity.ts";
16
17
 
17
18
  export type MemberRef = { id: string; epoch: number };
@@ -125,10 +126,6 @@ export type ConnectorProof = {
125
126
  cleanup?: { old: MemberRef; requestHash: string };
126
127
  };
127
128
 
128
- // Candidate v1 transcript domain, byte-identical to apps/bom-cloud/server/pickup-authority.ts
129
- // (duplicated literal: packages must not import apps). Leader owns single-sourcing this constant.
130
- const DAEMON_PROOF_DOMAIN = "bom-pi/cloud-daemon-proof/v1";
131
-
132
129
  // Candidate cleanup-request domain, byte-identical to apps/bom-cloud/server/{cloud,pickup-authority}.ts
133
130
  // (duplicated literal: packages must not import apps). Leader owns single-sourcing this constant.
134
131
  const CLEANUP_REQUEST_DOMAIN = "bom-pi/connector/cleanup-request/v1";
@@ -976,7 +973,10 @@ export class CloudConnector {
976
973
  return this.snapshot.entry;
977
974
  }
978
975
 
979
- /** Fresh domain-separated proof over the phase-1 daemon-proof transcript; a new challenge for every operation. */
976
+ /** Fresh domain-separated proof over the phase-1 daemon-proof transcript; a new challenge for
977
+ * every operation. M4 R6: X consumes the challenge of every verified "connector"/"cleanup"
978
+ * proof (consume-on-verify, replay → 401), so the per-operation freshness here is mandatory,
979
+ * not stylistic — the same bytes must never be re-presented. */
980
980
  private makeProof(purpose: "connector" | "cleanup" | "removed-connector"): ConnectorProof {
981
981
  const challenge = b64(this.random(16));
982
982
  const publicKeySpki = b64(this.identityPublicDer);
@@ -544,6 +544,47 @@ export class FileConnectorStore implements ConnectorStore {
544
544
  return store;
545
545
  }
546
546
 
547
+ /** open() when a record exists, else create() — the one-shot enroll lane's provisioning. It
548
+ * tolerates exactly one leftover: a directory holding no record for this pin (an aborted
549
+ * create: mkdir ran, the record never landed — crash, power loss, or a platform check that
550
+ * refused mid-way). That orphan is removed and re-provisioned; a directory with any record,
551
+ * for this pin or another, is still never re-initialized over. */
552
+ static async openOrProvision(
553
+ directory: string,
554
+ pinned: PinnedCloud,
555
+ options?: FileConnectorStoreOptions,
556
+ ): Promise<FileConnectorStore> {
557
+ try {
558
+ return await FileConnectorStore.open(directory, pinned, options);
559
+ } catch (error) {
560
+ if (
561
+ !(error instanceof Error) ||
562
+ !/missing (?:store directory|record)/.test(error.message)
563
+ ) {
564
+ throw error;
565
+ }
566
+ }
567
+
568
+ try {
569
+ return await FileConnectorStore.create(directory, pinned, options);
570
+ } catch (error) {
571
+ if (!(error instanceof Error) || !/already exists/.test(error.message)) {
572
+ throw error;
573
+ }
574
+
575
+ const slot = slotPaths(directory, pinned);
576
+ const record = await lstat(slot.recordPath).catch(() => null);
577
+
578
+ if (record !== null) {
579
+ throw error;
580
+ }
581
+
582
+ await rm(directory, { recursive: true, force: true });
583
+
584
+ return await FileConnectorStore.create(directory, pinned, options);
585
+ }
586
+ }
587
+
547
588
  /** Opens an EXISTING store: the directory must pre-exist as a private 0700 directory owned by
548
589
  * the current user, and the record must be present, private (0600), structurally valid and
549
590
  * bound to exactly this pinned cloud. A missing record is refused (never silently treated as a
@@ -1848,6 +1848,15 @@ export class DevicePairBroker {
1848
1848
  fail(503, "No independent owner signer is pinned for this target");
1849
1849
  }
1850
1850
 
1851
+ // R2: the decision re-checks the target's LIVE membership against the create-time
1852
+ // binding in the offer. A rotation (new id/epoch) or removal between request-create
1853
+ // and decide leaves that binding stale — refuse before any receipt is signed.
1854
+ const liveTarget = await this.env.members.membership(record.offer.targetFp);
1855
+
1856
+ if (liveTarget === null || !equalRef(liveTarget.ref, record.offer.targetMembership)) {
1857
+ fail(503, "Target membership changed since the request was created");
1858
+ }
1859
+
1851
1860
  const subjectMembership = memberRef(
1852
1861
  record.request.envelope.subjectMembership,
1853
1862
  "subjectMembership",
@@ -2322,18 +2331,22 @@ export class DevicePairBroker {
2322
2331
  });
2323
2332
  }
2324
2333
 
2325
- /** P7 MINOR-3: drop terminal pending records past the bounded replay window. §3 forbids
2326
- * permanent pair history; expired/decided records carry signed requester material. */
2334
+ /** P7 MINOR-3 + M4 R3: drop records past the bounded replay window. §3 forbids permanent
2335
+ * pair history; expired/decided records carry signed requester material. Terminal and
2336
+ * expired-undecided records age out past pendingExpiresAt + 24h; a provisional crash
2337
+ * leftover that outlived its §7 transaction deadline by the same window goes too. Records
2338
+ * still inside the window always stay (replay semantics). */
2327
2339
  private async purgeTerminalRecords(now: number): Promise<void> {
2328
2340
  const before = this.state.requests.length;
2329
2341
 
2330
2342
  this.state.requests = this.state.requests.filter(
2331
2343
  (record) =>
2332
2344
  !(
2333
- record.state !== "provisional" &&
2334
- record.state !== "pending-device" &&
2335
- record.pendingExpiresAt !== null &&
2336
- now >= record.pendingExpiresAt + TERMINAL_RETENTION_SECONDS
2345
+ (record.state === "provisional" &&
2346
+ now >= record.transactionDeadline + TERMINAL_RETENTION_SECONDS) ||
2347
+ (record.state !== "provisional" &&
2348
+ record.pendingExpiresAt !== null &&
2349
+ now >= record.pendingExpiresAt + TERMINAL_RETENTION_SECONDS)
2337
2350
  ),
2338
2351
  );
2339
2352
 
@@ -2482,6 +2495,18 @@ export type LedgerCleanup = {
2482
2495
  requestNonce: string;
2483
2496
  };
2484
2497
 
2498
+ /** P7 MINOR-4 (§13): crash-window intent — the exact signed decision bytes, durably recorded
2499
+ * BEFORE they are sent to X and kept until the local decided commit lands. Secret-free: the
2500
+ * bytes are the owner-signed public certificate X itself retains for its replay lane. */
2501
+ export type LedgerDecisionIntent = {
2502
+ requestId: string;
2503
+ revision: number;
2504
+ decision: "approve" | "deny";
2505
+ /** Canonical JSON of the signed §13 envelope; identical bytes re-hit X's replay lane. */
2506
+ bytes: string;
2507
+ sentAt: number;
2508
+ };
2509
+
2485
2510
  export type LedgerSnapshot = {
2486
2511
  version: 1;
2487
2512
  revision: number;
@@ -2491,6 +2516,7 @@ export type LedgerSnapshot = {
2491
2516
  grants: LedgerGrant[];
2492
2517
  cleanups: LedgerCleanup[];
2493
2518
  pending: PendingDisplayRecord[];
2519
+ decisionIntents: LedgerDecisionIntent[];
2494
2520
  };
2495
2521
 
2496
2522
  export type PendingDisplayRecord = {
@@ -2556,6 +2582,11 @@ export interface LedgerEnvironment {
2556
2582
  fetchFinalReceipt(requestId: string): Promise<string>;
2557
2583
  /** Delivers an owner-signed decision envelope; returns X's nonsecret receipt. */
2558
2584
  sendDecision(bytes: Uint8Array): Promise<{ receipt: string }>;
2585
+ /** P7 MINOR-4: X's live §6 view of a request (state only is consumed); optional — the
2586
+ * decision reconcile skips gracefully when the surface is absent (test rigs). */
2587
+ requestStatus?(
2588
+ requestId: string,
2589
+ ): Promise<{ view: { [key: string]: CanonicalValue }; challengeReceipt: string | null }>;
2559
2590
  /** Delivers a termination notice; returns X's signed deleted/already-absent ACK. */
2560
2591
  sendTermination(bytes: Uint8Array): Promise<string>;
2561
2592
  }
@@ -2569,12 +2600,17 @@ export const emptyLedgerSnapshot = (): LedgerSnapshot => ({
2569
2600
  grants: [],
2570
2601
  cleanups: [],
2571
2602
  pending: [],
2603
+ decisionIntents: [],
2572
2604
  });
2573
2605
 
2574
2606
  export class PairingLedger {
2575
2607
  private state: LedgerSnapshot = emptyLedgerSnapshot();
2576
2608
  private sealed = false;
2577
2609
  private queue: Promise<unknown> = Promise.resolve();
2610
+ /** P7 MINOR-4: the intent set as of the last SUCCESSFUL durable write. Rollbacks restore
2611
+ * it so a committed intent always survives a failed operation (memory never diverges
2612
+ * from disk about which crash-window intents exist). */
2613
+ private committedIntents: LedgerDecisionIntent[] = [];
2578
2614
 
2579
2615
  private readonly env: LedgerEnvironment;
2580
2616
  private readonly store: LedgerStore;
@@ -2601,6 +2637,14 @@ export class PairingLedger {
2601
2637
  }
2602
2638
 
2603
2639
  ledger.state = structuredClone(snapshot);
2640
+
2641
+ // Snapshots written before P7 MINOR-4 carry no decision intents: normalize the
2642
+ // missing field instead of failing, then seed the rollback mirror from disk.
2643
+ if (!Array.isArray(ledger.state.decisionIntents)) {
2644
+ ledger.state.decisionIntents = [];
2645
+ }
2646
+
2647
+ ledger.committedIntents = structuredClone(ledger.state.decisionIntents);
2604
2648
  }
2605
2649
 
2606
2650
  return ledger;
@@ -2618,6 +2662,9 @@ export class PairingLedger {
2618
2662
  try {
2619
2663
  await this.store.write(next);
2620
2664
  this.state = next;
2665
+ // The rollback mirror only ever advances on a SUCCESSFUL write: memory and disk
2666
+ // never disagree about which decision intents exist (P7 MINOR-4).
2667
+ this.committedIntents = structuredClone(next.decisionIntents);
2621
2668
  } catch (error) {
2622
2669
  this.sealed = true;
2623
2670
 
@@ -2636,6 +2683,12 @@ export class PairingLedger {
2636
2683
  } catch (error) {
2637
2684
  this.state = before;
2638
2685
 
2686
+ // P7 MINOR-4: a decision intent is a deliberate out-of-band sentinel — one
2687
+ // already durably committed inside this failed operation must SURVIVE the
2688
+ // rollback (memory stays equal to disk), or the next unrelated commit would
2689
+ // erase the crash-window evidence and resurrect the 409 wedge on restart.
2690
+ this.state.decisionIntents = structuredClone(this.committedIntents);
2691
+
2639
2692
  throw error;
2640
2693
  }
2641
2694
  });
@@ -3250,6 +3303,22 @@ export class PairingLedger {
3250
3303
  });
3251
3304
  const signed = await signDecision(input.signer, decision);
3252
3305
  const bytes = canonicalJson(signed as unknown as CanonicalValue);
3306
+
3307
+ // P7 MINOR-4 (§13): the exact signed bytes are durable BEFORE they leave A — a
3308
+ // crash after X processed the decision but before the local commit leaves an
3309
+ // intent that reconcileDecisions() replays through X's identical-bytes lane.
3310
+ this.state.decisionIntents = this.state.decisionIntents.filter(
3311
+ (entry) => entry.requestId !== record.requestId,
3312
+ );
3313
+ this.state.decisionIntents.push({
3314
+ requestId: record.requestId,
3315
+ revision: record.revision,
3316
+ decision: input.decision,
3317
+ bytes: Buffer.from(bytes).toString("utf8"),
3318
+ sentAt: now,
3319
+ });
3320
+ await this.commit();
3321
+
3253
3322
  const { receipt } = await this.env.sendDecision(bytes);
3254
3323
 
3255
3324
  // P7 MINOR-4 (§7): A never marks its own record decided on an UNVERIFIED word from
@@ -3267,18 +3336,173 @@ export class PairingLedger {
3267
3336
  fail(503, "X decision receipt does not verify; the request stays undecided");
3268
3337
  }
3269
3338
 
3270
- record.decided = {
3339
+ // The intent commit advanced the snapshot generation: `record` aliases the stale
3340
+ // clone now, so the decided commit must re-bind the LIVE record (P7 MINOR-4).
3341
+ const current = this.state.pending.find(
3342
+ (entry) => entry.requestId === record.requestId,
3343
+ );
3344
+
3345
+ if (current === undefined) {
3346
+ fail(503, "The decided request vanished mid-decision; the intent stays replayable");
3347
+ }
3348
+
3349
+ current.decided = {
3271
3350
  decision: input.decision,
3272
3351
  approvedExpiry: input.approvedExpiry,
3273
3352
  certificateHash: sha256Hex(bytes),
3274
3353
  };
3275
- record.lastSyncedAt = now;
3354
+ current.lastSyncedAt = now;
3355
+ this.state.decisionIntents = this.state.decisionIntents.filter(
3356
+ (entry) => entry.requestId !== record.requestId,
3357
+ );
3276
3358
  await this.commit();
3277
3359
 
3278
3360
  return { receipt };
3279
3361
  });
3280
3362
  }
3281
3363
 
3364
+ /* --------- P7 MINOR-4: crash-window decision reconcile on boot/reconnect --------- */
3365
+
3366
+ /** P7 MINOR-4 (§7/§13): reconciliation for decisions caught in the send↔commit crash
3367
+ * window. For every sent-but-uncommitted decision intent, X's live request state decides
3368
+ * the outcome: a TERMINAL state matching the intent is committed locally by replaying
3369
+ * the intent's exact signed bytes through X's identical-bytes lane and verifying the
3370
+ * returned receipt against the pinned X key (A never acts on an unverified word); X
3371
+ * undecided or absent stays RESUMABLE — the record remains undecided, so the owner may
3372
+ * simply re-decide and no fresh-envelope 409 wedge can arise. Read-only except for the
3373
+ * single local commit it performs; every transport error is a skip, never a throw, so a
3374
+ * boot or reconnect can never fail on reconcile. */
3375
+ async reconcileDecisions(): Promise<{
3376
+ committed: string[];
3377
+ resumable: { requestId: string; reason: string }[];
3378
+ }> {
3379
+ const committed: string[] = [];
3380
+ const resumable: { requestId: string; reason: string }[] = [];
3381
+
3382
+ for (const intent of [...this.state.decisionIntents]) {
3383
+ const record = this.state.pending.find((entry) => entry.requestId === intent.requestId);
3384
+
3385
+ if (record === undefined) {
3386
+ if (this.env.now() - intent.sentAt >= TERMINAL_RETENTION_SECONDS) {
3387
+ // M4 R5 residue: an orphan intent whose local record never came back
3388
+ // within the retention window is dropped — the residue cannot grow
3389
+ // unbounded and reconcile noise stays bounded (fail-closed: replay of
3390
+ // dropped bytes still only ever hits X's identical-bytes lane).
3391
+ this.state.decisionIntents = this.state.decisionIntents.filter(
3392
+ (entry) => entry.requestId !== intent.requestId,
3393
+ );
3394
+ await this.commit();
3395
+ } else {
3396
+ resumable.push({ requestId: intent.requestId, reason: "no local record" });
3397
+ }
3398
+
3399
+ continue;
3400
+ }
3401
+
3402
+ if (record.decided !== null) {
3403
+ // The decided commit consumes its intent in the same snapshot; a survivor is
3404
+ // a stale leftover — drop it so it cannot shadow a later decision.
3405
+ this.state.decisionIntents = this.state.decisionIntents.filter(
3406
+ (entry) => entry.requestId !== intent.requestId,
3407
+ );
3408
+ await this.commit();
3409
+
3410
+ continue;
3411
+ }
3412
+
3413
+ let state: string | null = null;
3414
+
3415
+ try {
3416
+ const status = await this.env.requestStatus?.(intent.requestId);
3417
+
3418
+ state =
3419
+ status === undefined || typeof status.view.state !== "string"
3420
+ ? null
3421
+ : status.view.state;
3422
+ } catch {
3423
+ resumable.push({ requestId: intent.requestId, reason: "X status unavailable" });
3424
+
3425
+ continue;
3426
+ }
3427
+
3428
+ const terminal = state === "approved" ? "approve" : state === "denied" ? "deny" : null;
3429
+
3430
+ if (terminal === null) {
3431
+ resumable.push({
3432
+ requestId: intent.requestId,
3433
+ reason: state === null ? "status unavailable" : `X still ${state}`,
3434
+ });
3435
+
3436
+ continue;
3437
+ }
3438
+
3439
+ if (terminal !== intent.decision) {
3440
+ resumable.push({
3441
+ requestId: intent.requestId,
3442
+ reason: `X is ${state} but the local intent is ${intent.decision}`,
3443
+ });
3444
+
3445
+ continue;
3446
+ }
3447
+
3448
+ try {
3449
+ // Identical bytes re-hit X's replay lane and return the ORIGINAL receipt; the
3450
+ // utf8 round-trip is exact (canonical JSON), so the certificate hash matches
3451
+ // the one decide() itself would have committed.
3452
+ const replay = Buffer.from(intent.bytes, "utf8");
3453
+ const { receipt } = await this.env.sendDecision(replay);
3454
+ const verified = await this.env.verifyCloudReceipt(receipt);
3455
+
3456
+ if (
3457
+ verified === null ||
3458
+ verified.kind !== "pair-decision" ||
3459
+ verified.requestId !== intent.requestId ||
3460
+ verified.revision !== intent.revision ||
3461
+ verified.decision !== intent.decision
3462
+ ) {
3463
+ resumable.push({
3464
+ requestId: intent.requestId,
3465
+ reason: "X receipt did not verify against the intent",
3466
+ });
3467
+
3468
+ continue;
3469
+ }
3470
+
3471
+ const approvedExpiry =
3472
+ intent.decision === "approve"
3473
+ ? integer(verified.approvedExpiry, "approvedExpiry", true)
3474
+ : null;
3475
+
3476
+ await this.mutate(async () => {
3477
+ const current = this.state.pending.find(
3478
+ (entry) => entry.requestId === intent.requestId,
3479
+ );
3480
+
3481
+ if (current === undefined || current.decided !== null) {
3482
+ return; // raced with another writer; the durable truth already moved
3483
+ }
3484
+
3485
+ current.decided = {
3486
+ decision: intent.decision,
3487
+ approvedExpiry,
3488
+ certificateHash: sha256Hex(replay),
3489
+ };
3490
+ current.lastSyncedAt = this.env.now();
3491
+ this.state.decisionIntents = this.state.decisionIntents.filter(
3492
+ (entry) => entry.requestId !== intent.requestId,
3493
+ );
3494
+ await this.commit();
3495
+ });
3496
+
3497
+ committed.push(intent.requestId);
3498
+ } catch {
3499
+ resumable.push({ requestId: intent.requestId, reason: "replay send failed" });
3500
+ }
3501
+ }
3502
+
3503
+ return { committed, resumable };
3504
+ }
3505
+
3282
3506
  /* --------------- §4.2/§14 issuance lane: sealed relation pickup --------------- */
3283
3507
 
3284
3508
  /** §7/§14: verifies B's signed X25519 pickup request against the APPROVED §13 decision and