@bom-pi/core 0.2.4 → 0.2.6

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,11 +1,11 @@
1
1
  {
2
2
  "name": "@bom-pi/core",
3
- "version": "0.2.4",
3
+ "version": "0.2.6",
4
4
  "description": "Core pairing machinery for Bom Pi: ceremonies, transports, durable stores",
5
5
  "type": "module",
6
6
  "license": "MIT",
7
7
  "dependencies": {
8
- "@bom-pi/protocol": "^0.1.1"
8
+ "@bom-pi/protocol": "^0.1.2"
9
9
  },
10
10
  "exports": {
11
11
  "./cloud-connector.ts": "./src/cloud-connector.ts",
@@ -1,6 +1,18 @@
1
1
  /** Candidate v1 pinned outbound cloud-connector workers (one per joined cloud): reconcile, backoff, removal, cleanup. Inert transports only; no listener, application relay, agent adapter or service activation is implemented here.
2
2
  * §4.1/§16 cleanup invariant: the signed secret-free deletion request is durably stored AT REST in the same atomic write that erases the credential; retries present those stored bytes plus a fresh cleanup-only proof; storage failures seal fail-closed and a memory-only seal honestly discloses that no restart safety guarantee exists (no independent boot gate).
3
- * §16 restart fail-closed default: there is no trusted rollback/boot gate, so EVERY credential loaded from disk at open() is quarantined before any use — erased in the same atomic write that durably stores a fresh signed cleanup intent for its membership. A stored credential is never adopted as fresh, repair/reconcile can never resume it, and there is deliberately no `allowRestored` bypass. The only admission path is enroll(): an X-signed approval receipt verified against the PINNED cloud key (exact issuance bindings, replay-rejected request IDs, §16 cleanup-capacity reservation), installed in one durable write. Consequent impact, stated plainly: after every restart the membership is disabled locally and application work requires a fresh cloud-admin-approved enrollment, while cleanup delivery and local removal keep working without any credential.
3
+ * §16 restart fail-closed default: EXCEPT for ADR-19's single owner-approved deviation, EVERY
4
+ * credential loaded from disk at open() is quarantined before any use — erased in the same atomic
5
+ * write that durably stores a fresh signed cleanup intent for its membership. A stored credential
6
+ * is never adopted as fresh, repair/reconcile can never resume it, and there is deliberately no
7
+ * `allowRestored` bypass. The ADR-19 deviation is narrower than it sounds and still cloud-gated:
8
+ * a stored credential is USED only after the pinned cloud VERIFIED it live (nonce-fresh proof,
9
+ * X-signed receipt against the pinned key) and handed back a FRESH rotated credential bound to the
10
+ * SAME membership ref — so the authority the disk carries never crosses the gap, the row keeps its
11
+ * id/epoch (the relation binding and the §13 pin survive), and the moment the cloud does not
12
+ * answer, or says removed/superseded/wrong, the connector falls back to TODAY's quarantine and the
13
+ * one owner click. The only admission path for a NEW membership is still enroll(): an X-signed
14
+ * approval receipt verified against the PINNED cloud key (exact issuance bindings, replay-rejected
15
+ * request IDs, §16 cleanup-capacity reservation), installed in one durable write.
4
16
  * §16 never-deletion: pending cleanup intents are a DURABLE LIST, not a single slot — a new cancellation is never refused because an older signed intent is still unacknowledged; every intent is preserved across restart and delivered/acked individually. */
5
17
  import {
6
18
  createHash,
@@ -158,6 +170,15 @@ export type ReceiptExpectation = {
158
170
  /** P7 F-5: when set, the receipt must name exactly this fingerprint (removal receipts are
159
171
  * prover-bound; a receipt about someone else's ref never verifies). */
160
172
  fingerprint?: string;
173
+ /** ADR-19: when set, the receipt must be a boot-verify ROTATION binding exactly these
174
+ * facts — the epoch this boot presented, the rotated epoch, the new credential's hash and
175
+ * expiry. A receipt that does not carry all four, exactly, never verifies. */
176
+ credentialRotation?: {
177
+ fromEpoch: number;
178
+ toEpoch: number;
179
+ credentialHash: string;
180
+ expiresAt: number;
181
+ };
161
182
  };
162
183
 
163
184
  /**
@@ -169,7 +190,7 @@ export type ReceiptExpectation = {
169
190
  export type ReceiptVerifier = (
170
191
  receipt: string,
171
192
  expected: ReceiptExpectation,
172
- ) => Promise<{ action: string } | null>;
193
+ ) => Promise<{ action: string; payload?: Record<string, CanonicalValue> } | null>;
173
194
 
174
195
  export const failClosedReceiptVerifier: ReceiptVerifier = async () => null;
175
196
 
@@ -187,8 +208,34 @@ export interface CloudEndpoint {
187
208
  /** Cleanup-only deletion: presents the STORED signed request bytes verbatim plus a fresh
188
209
  * cleanup-only proof; identity-signed, no bearer credential; deletion-only, never enrollment. */
189
210
  cleanup(old: MemberRef, stored: StoredCleanupRequest, proof: ConnectorProof): Promise<string>;
211
+ /** ADR-19 (owner-decided): boot membership VERIFY + credential ROTATION — the one lane that lets
212
+ * a restart KEEP what the owner already approved instead of quarantining it into a click.
213
+ *
214
+ * Optional BY DESIGN. A pinned cloud (or a test wiring) that does not offer it is an old cloud:
215
+ * `open()` then degrades to today's boot quarantine with a typed reason (ADR-19 R8, the same
216
+ * capability-detect discipline the relay lane uses), never a silent "keep". An implementation
217
+ * must only ever answer for the exact ref it was asked about, must never create a membership,
218
+ * grant, signer pin or identity change, and must return an X-signed receipt binding the exact
219
+ * ref, the presented credential epoch, the new epoch, the new credential hash and expiry — the
220
+ * connector refuses to adopt a rotated credential it cannot check against the PINNED key. */
221
+ verify?(
222
+ ref: MemberRef,
223
+ credential: string,
224
+ credentialEpoch: number,
225
+ proof: ConnectorProof,
226
+ ): Promise<VerifiedCredential>;
190
227
  }
191
228
 
229
+ /** ADR-19 boot-verify answer: the SAME membership ref (the row is kept, only the credential moves),
230
+ * the rotated credential and the X-signed receipt that admits it. */
231
+ export type VerifiedCredential = {
232
+ membership: MemberRef;
233
+ credential: string;
234
+ credentialEpoch: number;
235
+ credentialExpiresAt: number;
236
+ receipt: string;
237
+ };
238
+
192
239
  /** §11 relay close reasons — the fixed, bounded vocabulary X may put on the wire. Duplicated
193
240
  * literal of apps/bom-cloud/server/connect-wss.ts RELAY_CLOSE_REASONS (packages must not import
194
241
  * apps; the leader owns single-sourcing this constant). */
@@ -261,7 +308,19 @@ export class EndpointError extends Error {
261
308
  }
262
309
 
263
310
  export type ConnectorStatus =
264
- "fresh" | "ready" | "retrying" | "removed" | "expired" | "sealed" | "stopped";
311
+ | "fresh"
312
+ | "ready"
313
+ | "retrying"
314
+ | "removed"
315
+ | "expired"
316
+ | "sealed"
317
+ /** ADR-19 §2.3: the cloud said this record's credential was SUPERSEDED by a newer verified
318
+ * boot of the same identity (a copied/restored disk). The dead credential is kept (it is
319
+ * authority for nothing), no cleanup intent is queued — revoking the live member here would
320
+ * kill the machine that legitimately holds it — and every lane stays inert until the owner
321
+ * acts. Honest, typed, never silent. */
322
+ | "displaced"
323
+ | "stopped";
265
324
 
266
325
  export type ReconcileResult =
267
326
  | { outcome: "ready"; generation: number }
@@ -274,12 +333,32 @@ export type ConnectorOptions = {
274
333
  transportFactory: () => CloudTransport;
275
334
  endpointFactory: (transport: CloudTransport) => CloudEndpoint;
276
335
  receiptVerifier?: ReceiptVerifier;
336
+ /** ADR-19 (owner-decided, 2026-11-14): the boot anchor. When TRUE, open() does NOT
337
+ * quarantine a stored credential; it holds it INERT and a later verifyStoredMembership()
338
+ * decides — X-verified live → adopt the rotated credential; removed / superseded /
339
+ * unreachable-within-the-window → TODAY's quarantine. Default FALSE (the §16 fail-closed
340
+ * default keeps exact pre-ADR behaviour for every wiring that does not ask for the anchor). */
341
+ verifiedAnchor?: boolean;
277
342
  now?: () => number;
278
343
  random?: (length: number) => Uint8Array;
279
344
  sleep?: (ms: number) => Promise<void>;
280
345
  backoff?: BackoffOptions;
281
346
  };
282
347
 
348
+ /** ADR-19 §8: what a boot verify decided, published for the daemon's status surface. Secret-free
349
+ * (the rotated credential is never part of it). */
350
+ export type BootVerifyOutcome =
351
+ | { outcome: "verified"; membership: MemberRef; credentialEpoch: number }
352
+ | {
353
+ outcome: "quarantined";
354
+ reason: "removed" | "superseded" | "refused" | "unreachable" | "unsupported";
355
+ }
356
+ /** ADR-19 hardening (fleet race): the entry this verify started with was REPLACED while
357
+ * the answer was in flight (a ceremony won the boot race). The verify is moot: nothing was
358
+ * erased, no cleanup was queued, and the connector now lives on the ceremony's credential —
359
+ * callers must treat the lane as owned by that ceremony and touch nothing. */
360
+ | { outcome: "overtaken" };
361
+
283
362
  export type BackoffOptions = {
284
363
  baseMs?: number;
285
364
  capMs?: number;
@@ -856,6 +935,16 @@ export class CloudConnector {
856
935
  private readonly random: (length: number) => Uint8Array;
857
936
  private readonly sleep: (ms: number) => Promise<void>;
858
937
  private readonly backoffOptions: BackoffOptions;
938
+ /** ADR-19: the owner-approved boot anchor flag (see ConnectorOptions). */
939
+ private readonly verifiedAnchor: boolean;
940
+ /** ADR-19 §8: the last boot-verify decision, published through sanitizedState()/describe(). */
941
+ private lastBootVerify: BootVerifyOutcome | null = null;
942
+ /** ADR-19 §2.4: X's §13 pin as echoed by the last verified receipt (read-only). */
943
+ private verifiedSignerPin: {
944
+ signerFingerprint: string;
945
+ signerEpoch: number;
946
+ signerPublicKeySpki: string;
947
+ } | null = null;
859
948
 
860
949
  private constructor(options: ConnectorOptions, snapshot: ConnectorSnapshot) {
861
950
  this.pinned = { ...options.pinned };
@@ -874,6 +963,7 @@ export class CloudConnector {
874
963
  this.random = options.random ?? ((length: number) => randomBytes(length));
875
964
  this.sleep = options.sleep ?? ((ms: number) => new Promise((r) => setTimeout(r, ms)));
876
965
  this.backoffOptions = options.backoff ?? {};
966
+ this.verifiedAnchor = options.verifiedAnchor === true;
877
967
  this.snapshot = snapshot;
878
968
  // An opened record that says "credential erased, cleanup pending" is honestly "removed",
879
969
  // never "fresh" (§16 wording; reconcile/delivery resume from the stored state). A record
@@ -887,11 +977,15 @@ export class CloudConnector {
887
977
  }
888
978
 
889
979
  /** Opens one pinned cloud connector. A fresh store is initialized; a stale/mismatched record
890
- * is refused; and ANY stored credential is quarantined before the connector is returned: it is
891
- * erased in the same atomic write that durably stores a fresh signed cleanup intent for its
892
- * membership (§16 fail-closed restart default — there is no trusted boot gate, so persisted
893
- * credentials are never trusted across restart). Re-admission requires a fresh authenticated
894
- * enroll(); cleanup delivery and removal keep working without any credential. */
980
+ * is refused. ANY stored credential is quarantined before the connector is returned — UNLESS
981
+ * the ADR-19 anchor was asked for (verifiedAnchor), in which case the credential is KEPT ON
982
+ * DISK BUT HELD INERT: `status` stays "fresh" only so the anchor path can run, no lane may
983
+ * use the credential, and verifyStoredMembership() decides within its bounded window —
984
+ * X-verified live ⇒ adopt the ROTATED credential in one durable write (same membership ref,
985
+ * relation binding and §13 pin untouched); removed/superseded/refused/unreachable/old-cloud ⇒
986
+ * today's quarantine exactly (erase + signed cleanup intent + re-enroll click, ADR-19 §2.3).
987
+ * Re-admission of a NEW membership always requires a fresh authenticated enroll(); cleanup
988
+ * delivery and removal keep working without any credential. */
895
989
  static async open(options: ConnectorOptions): Promise<CloudConnector> {
896
990
  validPinned(options.pinned);
897
991
 
@@ -939,10 +1033,20 @@ export class CloudConnector {
939
1033
  const snapshot = migrateSnapshot(structuredClone(stored), options.pinned, identity);
940
1034
  const connector = new CloudConnector(options, snapshot);
941
1035
 
942
- if (snapshot.entry !== null) {
1036
+ if (snapshot.entry !== null && !connector.verifiedAnchor) {
943
1037
  await connector.quarantineStoredEntry();
944
1038
  }
945
1039
 
1040
+ if (snapshot.entry !== null && connector.verifiedAnchor) {
1041
+ // ADR-19 §2.1: the anchor holds the credential INERT. The record still says "has a
1042
+ // credential", so nothing else may read it as adoptable: this flag is the difference
1043
+ // between "kept, pending cloud verify" and "fresh from a ceremony". reconcile()
1044
+ // and every other credential lane refuses while it is set (and while a copy stands
1045
+ // displaced): the stored credential never authenticates anywhere until
1046
+ // verifyStoredMembership() replaces it with a rotated, receipt-verified one.
1047
+ connector.quarantinedAtBoot = true;
1048
+ }
1049
+
946
1050
  return connector;
947
1051
  }
948
1052
 
@@ -972,8 +1076,13 @@ export class CloudConnector {
972
1076
  /** The ceremony-adopted pinned cloud key (base64url SPKI) or null — never a secret. */
973
1077
  pinnedCloudPublicSpki: string | null;
974
1078
  cleanupAcknowledged: boolean;
975
- /** True when open() quarantined a credential loaded from disk (§16 restart default). */
1079
+ /** True when open() quarantined a credential loaded from disk (§16 restart default), or
1080
+ * when the ADR-19 anchor is HOLDING a stored credential inert pending its boot verify
1081
+ * (same meaning for every reader: the stored credential is not usable as-is). */
976
1082
  quarantinedAtBoot: boolean;
1083
+ /** ADR-19 §8: the last boot-verify decision ("verified" ⇔ the current credential was
1084
+ * admitted through the X-verified rotation lane), or null when no verify ran this boot. */
1085
+ bootVerify: BootVerifyOutcome | null;
977
1086
  /** "durable"/"memory-only" while sealed; "none" otherwise (§16 honesty surface). */
978
1087
  seal: "none" | "durable" | "memory-only";
979
1088
  lastFailure: string | null;
@@ -995,6 +1104,7 @@ export class CloudConnector {
995
1104
  pinnedCloudPublicSpki: this.snapshot.pinnedCloudPublicSpki,
996
1105
  cleanupAcknowledged: this.cleanupAcknowledged,
997
1106
  quarantinedAtBoot: this.quarantinedAtBoot,
1107
+ bootVerify: this.lastBootVerify === null ? null : { ...this.lastBootVerify },
998
1108
  seal:
999
1109
  this.statusValue === "sealed"
1000
1110
  ? this.sealMemoryOnly
@@ -1005,6 +1115,26 @@ export class CloudConnector {
1005
1115
  };
1006
1116
  }
1007
1117
 
1118
+ /** ADR-19 §2.4: the §13 signer pin X echoed inside the last VERIFIED boot-verify receipt, or
1119
+ * null when the last verify was not "verified" or X holds no pin. Read-only facts for the
1120
+ * daemon's `signer-changed` honesty — the connector never pins anything itself. */
1121
+ lastVerifiedSignerPin(): {
1122
+ signerFingerprint: string;
1123
+ signerEpoch: number;
1124
+ signerPublicKeySpki: string;
1125
+ } | null {
1126
+ return this.verifiedSignerPin === null ? null : { ...this.verifiedSignerPin };
1127
+ }
1128
+
1129
+ /** ADR-19: true while the anchor holds a stored credential INERT pending its boot verify
1130
+ * (verifiedAnchor boot + a credential on disk + not yet adopted). False for every other
1131
+ * connector: a ceremony-fresh credential, a quarantined/removed store, or an anchor that
1132
+ * already adopted its rotation. This is the ONE flag callers gate the anchor path on — a
1133
+ * live membership in the SAME process is not a boot and must take the ordinary lanes. */
1134
+ get bootAnchorPending(): boolean {
1135
+ return this.verifiedAnchor && this.quarantinedAtBoot && this.snapshot.entry !== null;
1136
+ }
1137
+
1008
1138
  /** §4.1/§8 owner-visible status wording: never claims "erased everywhere" before the final ACK,
1009
1139
  * and never hides that a boot quarantine disabled the stored credential. */
1010
1140
  describe(): string {
@@ -1016,6 +1146,10 @@ export class CloudConnector {
1016
1146
  return this.sealMemoryOnly ? prefix : "fail-closed: storage recovery required";
1017
1147
  }
1018
1148
 
1149
+ if (this.statusValue === "displaced") {
1150
+ return "displaced: a newer boot of this identity holds the live credential; this record is inert — remove it and re-enroll, or revoke the member at the cloud";
1151
+ }
1152
+
1019
1153
  if (this.statusValue === "expired") {
1020
1154
  return "credential expired; fresh enrollment required";
1021
1155
  }
@@ -1289,6 +1423,25 @@ export class CloudConnector {
1289
1423
  this.failSealed();
1290
1424
  }
1291
1425
 
1426
+ // ADR-19 §2.1: an INERT credential never authenticates — not through this lane and
1427
+ // not through any future one. While the boot anchor HOLDS a stored credential
1428
+ // (quarantinedAtBoot with the entry still present) or while a superseded copy stands
1429
+ // displaced, reconcile is a refusal, not a re-check by the caller: the only way back
1430
+ // is verifyStoredMembership() adopting a rotated, receipt-verified credential (which
1431
+ // clears the marker) or today's §16 quarantine erasing the entry. A §16 boot that
1432
+ // ALREADY erased the credential has nothing inert to guard — it keeps its honest
1433
+ // pre-ADR behavior (requireEntry()'s refusal below), byte for byte.
1434
+ if (
1435
+ (this.quarantinedAtBoot && this.snapshot.entry !== null) ||
1436
+ this.statusValue === "displaced"
1437
+ ) {
1438
+ throw new ConnectorStateError(
1439
+ this.statusValue === "displaced"
1440
+ ? "Displaced credential copy: superseded by a newer boot; removal or re-enrollment required"
1441
+ : "Boot anchor pending: stored credential is inert until verifyStoredMembership()",
1442
+ );
1443
+ }
1444
+
1292
1445
  const entry = this.requireEntry();
1293
1446
 
1294
1447
  if (entry.credentialExpiresAt <= this.saneNow()) {
@@ -1517,6 +1670,320 @@ export class CloudConnector {
1517
1670
  this.statusValue = "removed";
1518
1671
  }
1519
1672
 
1673
+ /**
1674
+ * ADR-19 §2 (owner-decided, one wave: anchor + rotation): the boot decision for a stored
1675
+ * credential the anchor held inert. BOUNDED (wall clock, stop()-cancellable): opens a
1676
+ * verify-only transport, presents the stored credential + a nonce-fresh identity proof, and
1677
+ * lets the cloud decide:
1678
+ *
1679
+ * - `live` → adopt the ROTATED credential the cloud returned, in ONE durable write, after its
1680
+ * X-signed receipt verified against the pinned key and bound exactly this ref, this boot's
1681
+ * PRESENTED epoch and the new epoch/hash/expiry. The membership ref never changes (the
1682
+ * relation binding and the §13 pin survive the restart); NO cleanup intent is created (R3);
1683
+ * an undelivered intent for an OLDER ref stays undisturbed and still delivers later (R2/R4).
1684
+ * - removed/superseded/refused/no answer in the window/old cloud without the lane → TODAY's
1685
+ * quarantine, exactly: erase + signed cleanup intent, re-enroll click (R1 checked BEFORE
1686
+ * anything: a pending intent for THIS ref anchors nothing — it delivers instead).
1687
+ *
1688
+ * Clock-rollback-irrelevant by construction (R5/T4): there is NO cached anchor — every boot
1689
+ * asks, the answer is consumed once, and the adopted credential is always one the cloud
1690
+ * minted AFTER this boot.
1691
+ */
1692
+ async verifyStoredMembership(options?: {
1693
+ /** Wall-clock bound in ms (default 60 000, ADR-19 §2.3). Elapsed time, not a clock verdict. */
1694
+ timeoutMs?: number;
1695
+ }): Promise<BootVerifyOutcome> {
1696
+ const deadline = Date.now() + (options?.timeoutMs ?? 60_000);
1697
+
1698
+ return this.serialize(async () => {
1699
+ if (this.snapshot.sealed || this.statusValue === "sealed") {
1700
+ this.failSealed();
1701
+ }
1702
+
1703
+ const entry = this.requireEntry();
1704
+
1705
+ // ADR-19 hardening (fleet race 2026-11-15): every destructive decision below may act
1706
+ // ONLY on the exact entry this verify started with — same membership ref AND same
1707
+ // credential epoch. If a ceremony replaced the entry while an answer was in flight,
1708
+ // this verify is MOOT: no erase, no cleanup intent, no displacement, no adoption.
1709
+ // (The serialization chain makes the swap invisible to this body today; the guard
1710
+ // keeps the invariant local and true under any future refactor that splits it.)
1711
+ const verifiedRef: MemberRef = { ...entry.membership };
1712
+ const verifiedEpoch = entry.credentialEpoch;
1713
+
1714
+ const stillTheVerifiedEntry = (): boolean => {
1715
+ const current = this.snapshot.entry;
1716
+
1717
+ return (
1718
+ current !== null &&
1719
+ current.credentialEpoch === verifiedEpoch &&
1720
+ refsEqual(current.membership, verifiedRef)
1721
+ );
1722
+ };
1723
+
1724
+ const overtaken = (): { outcome: "overtaken" } => {
1725
+ this.lastFailure =
1726
+ "boot verify moot: the stored entry was replaced by a fresh ceremony while the answer was in flight";
1727
+ this.lastBootVerify = { outcome: "overtaken" };
1728
+
1729
+ return this.lastBootVerify;
1730
+ };
1731
+
1732
+ // R1: a pending intent for THIS exact ref wins over any anchor — the structural rule
1733
+ // "a credential and its own pending cleanup may not coexist" must hold here too.
1734
+ if (
1735
+ this.snapshot.pendingCleanups.some((pending) =>
1736
+ refsEqual(pending.membership, entry.membership),
1737
+ )
1738
+ ) {
1739
+ if (!stillTheVerifiedEntry()) {
1740
+ return overtaken();
1741
+ }
1742
+
1743
+ await this.quarantineStoredEntry();
1744
+ this.lastBootVerify = { outcome: "quarantined", reason: "refused" };
1745
+
1746
+ return this.lastBootVerify;
1747
+ }
1748
+
1749
+ if (entry.credentialExpiresAt <= this.saneNow()) {
1750
+ if (!stillTheVerifiedEntry()) {
1751
+ return overtaken();
1752
+ }
1753
+
1754
+ await this.quarantineStoredEntry();
1755
+ this.lastBootVerify = { outcome: "quarantined", reason: "refused" };
1756
+
1757
+ return this.lastBootVerify;
1758
+ }
1759
+
1760
+ let transport: CloudTransport | null = null;
1761
+
1762
+ try {
1763
+ transport = this.transportFactory();
1764
+ await transport.open();
1765
+
1766
+ const endpoint = this.endpointFactory(transport);
1767
+
1768
+ if (typeof endpoint.verify !== "function") {
1769
+ // R8 mixed fleet: an old cloud without the lane degrades to TODAY's boot, typed.
1770
+ throw new EndpointError(503, "verify lane unsupported by the pinned cloud");
1771
+ }
1772
+
1773
+ const verified = await this.raceDeadline(
1774
+ endpoint.verify(
1775
+ entry.membership,
1776
+ entry.credential,
1777
+ entry.credentialEpoch,
1778
+ this.makeProof("connector"),
1779
+ ),
1780
+ deadline,
1781
+ );
1782
+
1783
+ if (!stillTheVerifiedEntry()) {
1784
+ return overtaken();
1785
+ }
1786
+
1787
+ const outcome = await this.adoptVerifiedCredential(entry, verified);
1788
+
1789
+ this.lastBootVerify = outcome;
1790
+
1791
+ return outcome;
1792
+ } catch (error) {
1793
+ // ADR-19 §2.3 displacement: the cloud says a NEWER verified boot of this identity
1794
+ // already rotated the credential — the honest terminal state, NOT a quarantine
1795
+ // (queueing a cleanup here would delete the member row the REAL machine holds).
1796
+ if (error instanceof EndpointError && error.status === 409) {
1797
+ if (!stillTheVerifiedEntry()) {
1798
+ return overtaken();
1799
+ }
1800
+
1801
+ await this.markDisplaced();
1802
+ this.lastBootVerify = { outcome: "quarantined", reason: "superseded" };
1803
+
1804
+ return this.lastBootVerify;
1805
+ }
1806
+
1807
+ const reason: "removed" | "superseded" | "refused" | "unreachable" | "unsupported" =
1808
+ error instanceof EndpointError && error.status === 410
1809
+ ? "removed"
1810
+ : error instanceof EndpointError && error.status === 409
1811
+ ? "superseded"
1812
+ : error instanceof EndpointError && error.status === 503
1813
+ ? "unsupported"
1814
+ : "refused";
1815
+
1816
+ this.lastFailure = `boot verify failed (${reason}): ${
1817
+ error instanceof Error ? error.message : String(error)
1818
+ }`;
1819
+
1820
+ if (!stillTheVerifiedEntry()) {
1821
+ return overtaken();
1822
+ }
1823
+
1824
+ await this.quarantineStoredEntry();
1825
+ this.lastBootVerify = { outcome: "quarantined", reason };
1826
+
1827
+ return this.lastBootVerify;
1828
+ } finally {
1829
+ if (transport !== null) {
1830
+ await safeClose(transport);
1831
+ }
1832
+ }
1833
+ });
1834
+ }
1835
+
1836
+ /** Rejects ("unreachable") when the wall-clock deadline passes first; resolves otherwise. */
1837
+ private raceDeadline<T>(promise: Promise<T>, deadline: number): Promise<T> {
1838
+ return new Promise<T>((resolve, reject) => {
1839
+ const timer = setTimeout(
1840
+ () => {
1841
+ reject(new EndpointError(503, "boot verify window elapsed (unreachable)"));
1842
+ },
1843
+ Math.max(0, deadline - Date.now()),
1844
+ );
1845
+
1846
+ promise.then(
1847
+ (value) => {
1848
+ clearTimeout(timer);
1849
+ resolve(value);
1850
+ },
1851
+ (error) => {
1852
+ clearTimeout(timer);
1853
+ reject(error);
1854
+ },
1855
+ );
1856
+ });
1857
+ }
1858
+
1859
+ /** Verifies the rotation receipt against the pinned key and adopts the rotated credential in
1860
+ * ONE durable write. The ref must be EXACTLY the stored one (the row never moves); the
1861
+ * receipt must bind this boot's presented epoch and the new epoch/hash/expiry. */
1862
+ private async adoptVerifiedCredential(
1863
+ entry: CloudEntry,
1864
+ verified: VerifiedCredential,
1865
+ ): Promise<BootVerifyOutcome> {
1866
+ if (
1867
+ !validRef(verified.membership) ||
1868
+ !refsEqual(verified.membership, entry.membership) ||
1869
+ typeof verified.credential !== "string" ||
1870
+ verified.credential.length === 0 ||
1871
+ verified.credential.length > 1024 ||
1872
+ !Number.isSafeInteger(verified.credentialEpoch) ||
1873
+ verified.credentialEpoch < 1 ||
1874
+ !Number.isSafeInteger(verified.credentialExpiresAt) ||
1875
+ verified.credentialExpiresAt <= this.saneNow() ||
1876
+ typeof verified.receipt !== "string"
1877
+ ) {
1878
+ throw new ConnectorStateError("Malformed boot-verify answer from cloud");
1879
+ }
1880
+
1881
+ const check = await this.receiptVerifier(verified.receipt, {
1882
+ cloudId: this.pinned.cloudId,
1883
+ membership: { id: entry.membership.id, epoch: entry.membership.epoch },
1884
+ acceptedActions: ["verified"],
1885
+ fingerprint: this.identityFingerprint,
1886
+ credentialRotation: {
1887
+ fromEpoch: entry.credentialEpoch,
1888
+ toEpoch: verified.credentialEpoch,
1889
+ credentialHash: sha256Hex(Buffer.from(verified.credential, "utf8")),
1890
+ expiresAt: verified.credentialExpiresAt,
1891
+ },
1892
+ });
1893
+
1894
+ if (check === null) {
1895
+ throw new ConnectorStateError(
1896
+ "Boot-verify receipt did not verify against the pinned cloud key; credential retained for quarantine",
1897
+ );
1898
+ }
1899
+
1900
+ // §2.4: remember X's pin ONLY from a receipt that just verified (secret-free facts).
1901
+ const signer = (check.payload?.signer ?? null) as {
1902
+ signerFingerprint?: unknown;
1903
+ signerEpoch?: unknown;
1904
+ signerPublicKeySpki?: unknown;
1905
+ } | null;
1906
+
1907
+ this.verifiedSignerPin =
1908
+ signer !== null &&
1909
+ typeof signer.signerFingerprint === "string" &&
1910
+ typeof signer.signerEpoch === "number" &&
1911
+ typeof signer.signerPublicKeySpki === "string"
1912
+ ? {
1913
+ signerFingerprint: signer.signerFingerprint,
1914
+ signerEpoch: signer.signerEpoch,
1915
+ signerPublicKeySpki: signer.signerPublicKeySpki,
1916
+ }
1917
+ : null;
1918
+
1919
+ // ADR-19 hardening (review 2026-11-15): the receipt verifier above is an AWAIT — the
1920
+ // only reason the entry cannot change across it today is the outer serialize chain.
1921
+ // Keep the invariant LOCAL: re-check that the entry is still the exact one this verify
1922
+ // started with (same ref + credential epoch) immediately BEFORE the durable write. A
1923
+ // mismatch aborts the adoption — nothing written, nothing queued — and the throw lands
1924
+ // in the caller's fail-closed catch, whose own changed-entry guard maps it to a silent
1925
+ // "overtaken" (a ceremony owns the connector now).
1926
+ const current = this.snapshot.entry;
1927
+
1928
+ if (
1929
+ current === null ||
1930
+ current.credentialEpoch !== entry.credentialEpoch ||
1931
+ !refsEqual(current.membership, entry.membership)
1932
+ ) {
1933
+ throw new ConnectorStateError(
1934
+ "Boot verify moot: the stored entry changed while the rotation receipt was being verified; nothing adopted",
1935
+ );
1936
+ }
1937
+
1938
+ // R3: the anchored boot creates no intent, ever — and it adopts nothing else either: same
1939
+ // ref, same identity, only the credential material moves.
1940
+ const next: ConnectorSnapshot = {
1941
+ ...structuredClone(this.snapshot),
1942
+ entry: {
1943
+ membership: { ...entry.membership },
1944
+ credentialEpoch: verified.credentialEpoch,
1945
+ credential: verified.credential,
1946
+ credentialExpiresAt: verified.credentialExpiresAt,
1947
+ },
1948
+ pendingCleanups: [...this.snapshot.pendingCleanups],
1949
+ sealed: false,
1950
+ };
1951
+
1952
+ await this.store.write(next);
1953
+
1954
+ this.snapshot = next;
1955
+ this.quarantinedAtBoot = false;
1956
+ this.sealMemoryOnly = false;
1957
+ this.uncertainRemovalWrite = false;
1958
+ this.statusValue = "fresh";
1959
+ this.lastFailure = null;
1960
+
1961
+ return {
1962
+ outcome: "verified",
1963
+ membership: { ...entry.membership },
1964
+ credentialEpoch: verified.credentialEpoch,
1965
+ };
1966
+ }
1967
+
1968
+ /** ADR-19 §2: the pinned cloud answered that this record's credential was SUPERSEDED by a
1969
+ * newer verified boot of the same identity (a copied or restored disk). The dead credential is
1970
+ * kept as authority for nothing, no cleanup intent is queued — deleting the member at X here
1971
+ * would kill the machine that legitimately holds the live credential — and every lane stays
1972
+ * inert until the owner acts (revoke at X, or remove locally and re-enroll). */
1973
+ async markDisplaced(): Promise<void> {
1974
+ this.statusValue = "displaced";
1975
+ this.lastFailure =
1976
+ "displaced: a newer verified boot holds this membership's live credential";
1977
+
1978
+ if (this.transport !== null) {
1979
+ const transport = this.transport;
1980
+
1981
+ this.transport = null;
1982
+ await safeClose(transport);
1983
+ this.resolveDisconnect();
1984
+ }
1985
+ }
1986
+
1520
1987
  /**
1521
1988
  * Local `cloud remove` (§4.1): close the connector first, then atomically erase the credential
1522
1989
  * while appending the SIGNED secret-free pending cleanup request to the durable intent list
@@ -1668,6 +2135,13 @@ export class CloudConnector {
1668
2135
  this.sealMemoryOnly = false;
1669
2136
  this.cleanupAcknowledged = false;
1670
2137
 
2138
+ // The boot marker describes the DISK credential this process found at open() — held
2139
+ // inert (anchor) or quarantined (§16). A ceremony just REPLACED it with a fresh,
2140
+ // receipt-verified credential, so the marker must clear here: leaving it set kept
2141
+ // reconcile() fail-closed forever and hung the ceremony's connect watch (the
2142
+ // §16-quarantine-then-fresh-enroll lane — wiring test 5 regression).
2143
+ this.quarantinedAtBoot = false;
2144
+
1671
2145
  // Any live connection authenticated the PREVIOUS credential; force a fresh reconcile.
1672
2146
  if (this.transport !== null) {
1673
2147
  const transport = this.transport;