@941design/marmot 0.0.0-stage → 0.2.0-alpha.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.
Files changed (206) hide show
  1. package/CHANGELOG.md +739 -0
  2. package/LICENSE +21 -0
  3. package/README.md +33 -2
  4. package/dist/account/admin.d.ts +72 -0
  5. package/dist/account/admin.js +209 -0
  6. package/dist/account/device-deps.d.ts +379 -0
  7. package/dist/account/device-deps.js +36 -0
  8. package/dist/account/device-lineage.d.ts +199 -0
  9. package/dist/account/device-lineage.js +390 -0
  10. package/dist/account/device-registry.d.ts +93 -0
  11. package/dist/account/device-registry.js +1290 -0
  12. package/dist/account/device-rotation.d.ts +61 -0
  13. package/dist/account/device-rotation.js +827 -0
  14. package/dist/account/enrolment.d.ts +339 -0
  15. package/dist/account/enrolment.js +1247 -0
  16. package/dist/account/identity-proof.d.ts +79 -0
  17. package/dist/account/identity-proof.js +264 -0
  18. package/dist/account/index.d.ts +17 -0
  19. package/dist/account/index.js +16 -0
  20. package/dist/account/restore-rotation.d.ts +21 -0
  21. package/dist/account/restore-rotation.js +22 -0
  22. package/dist/account/same-account-authorization.d.ts +86 -0
  23. package/dist/account/same-account-authorization.js +180 -0
  24. package/dist/account/teardown.d.ts +190 -0
  25. package/dist/account/teardown.js +878 -0
  26. package/dist/client/admission-cleanup.d.ts +197 -0
  27. package/dist/client/admission-cleanup.js +635 -0
  28. package/dist/client/adoption-proof.d.ts +39 -0
  29. package/dist/client/adoption-proof.js +102 -0
  30. package/dist/client/before-create-group.d.ts +18 -0
  31. package/dist/client/before-create-group.js +65 -0
  32. package/dist/client/before-publish-hooks.d.ts +121 -0
  33. package/dist/client/before-publish-hooks.js +182 -0
  34. package/dist/client/client-config.d.ts +42 -0
  35. package/dist/client/client-config.js +13 -0
  36. package/dist/client/commit-redrive.d.ts +92 -0
  37. package/dist/client/commit-redrive.js +274 -0
  38. package/dist/client/component-update.d.ts +43 -0
  39. package/dist/client/component-update.js +53 -0
  40. package/dist/client/confirm-hooks.d.ts +55 -0
  41. package/dist/client/confirm-hooks.js +74 -0
  42. package/dist/client/create-client.d.ts +1126 -0
  43. package/dist/client/create-client.js +1232 -0
  44. package/dist/client/group-availability.d.ts +182 -0
  45. package/dist/client/group-availability.js +301 -0
  46. package/dist/client/group-disband.d.ts +28 -0
  47. package/dist/client/group-disband.js +64 -0
  48. package/dist/client/group-history.d.ts +461 -0
  49. package/dist/client/group-history.js +1365 -0
  50. package/dist/client/group-profile.d.ts +31 -0
  51. package/dist/client/group-profile.js +62 -0
  52. package/dist/client/group-records.d.ts +522 -0
  53. package/dist/client/group-records.js +1117 -0
  54. package/dist/client/group-removal.d.ts +36 -0
  55. package/dist/client/group-removal.js +127 -0
  56. package/dist/client/group-remove-member.d.ts +49 -0
  57. package/dist/client/group-remove-member.js +163 -0
  58. package/dist/client/group-runtime.d.ts +415 -0
  59. package/dist/client/group-runtime.js +2811 -0
  60. package/dist/client/group-snapshot.d.ts +104 -0
  61. package/dist/client/group-snapshot.js +474 -0
  62. package/dist/client/history-pages.d.ts +107 -0
  63. package/dist/client/history-pages.js +194 -0
  64. package/dist/client/inbox-send.d.ts +19 -0
  65. package/dist/client/inbox-send.js +71 -0
  66. package/dist/client/index.d.ts +24 -0
  67. package/dist/client/index.js +13 -0
  68. package/dist/client/ingest.d.ts +82 -0
  69. package/dist/client/ingest.js +1584 -0
  70. package/dist/client/invitation-outcomes.d.ts +50 -0
  71. package/dist/client/invitation-outcomes.js +135 -0
  72. package/dist/client/lifecycle-events.d.ts +63 -0
  73. package/dist/client/lifecycle-events.js +35 -0
  74. package/dist/client/opaque-candidates.d.ts +82 -0
  75. package/dist/client/opaque-candidates.js +170 -0
  76. package/dist/client/own-change-outbox.d.ts +66 -0
  77. package/dist/client/own-change-outbox.js +158 -0
  78. package/dist/client/pending-leaf.d.ts +116 -0
  79. package/dist/client/pending-leaf.js +378 -0
  80. package/dist/client/permissions.d.ts +9 -0
  81. package/dist/client/permissions.js +12 -0
  82. package/dist/client/pipeline.d.ts +583 -0
  83. package/dist/client/pipeline.js +3666 -0
  84. package/dist/client/reentrancy-guard.d.ts +102 -0
  85. package/dist/client/reentrancy-guard.js +159 -0
  86. package/dist/client/rekey.d.ts +58 -0
  87. package/dist/client/rekey.js +149 -0
  88. package/dist/client/transport-policy.d.ts +181 -0
  89. package/dist/client/transport-policy.js +214 -0
  90. package/dist/history/admission-lineage.d.ts +186 -0
  91. package/dist/history/admission-lineage.js +589 -0
  92. package/dist/history/equivocation.d.ts +55 -0
  93. package/dist/history/equivocation.js +113 -0
  94. package/dist/history/fencing.d.ts +66 -0
  95. package/dist/history/fencing.js +121 -0
  96. package/dist/history/hex.d.ts +3 -0
  97. package/dist/history/hex.js +10 -0
  98. package/dist/history/index.d.ts +74 -0
  99. package/dist/history/index.js +32 -0
  100. package/dist/history/notifications.d.ts +270 -0
  101. package/dist/history/notifications.js +264 -0
  102. package/dist/history/ordering-key.d.ts +24 -0
  103. package/dist/history/ordering-key.js +101 -0
  104. package/dist/history/own-change-fork.d.ts +112 -0
  105. package/dist/history/own-change-fork.js +196 -0
  106. package/dist/history/own-change.d.ts +118 -0
  107. package/dist/history/own-change.js +146 -0
  108. package/dist/history/policy.d.ts +48 -0
  109. package/dist/history/policy.js +52 -0
  110. package/dist/history/retained-window.d.ts +215 -0
  111. package/dist/history/retained-window.js +565 -0
  112. package/dist/inbox/demux.d.ts +90 -0
  113. package/dist/inbox/demux.js +78 -0
  114. package/dist/inbox/handler-registry.d.ts +42 -0
  115. package/dist/inbox/handler-registry.js +37 -0
  116. package/dist/inbox/index.d.ts +11 -0
  117. package/dist/inbox/index.js +10 -0
  118. package/dist/inbox/seen-set.d.ts +82 -0
  119. package/dist/inbox/seen-set.js +202 -0
  120. package/dist/inbox/subscription.d.ts +236 -0
  121. package/dist/inbox/subscription.js +644 -0
  122. package/dist/index.d.ts +10 -0
  123. package/dist/index.js +9 -0
  124. package/dist/invitations/competing-welcome.d.ts +223 -0
  125. package/dist/invitations/competing-welcome.js +128 -0
  126. package/dist/invitations/decline.d.ts +67 -0
  127. package/dist/invitations/decline.js +149 -0
  128. package/dist/invitations/delivery-evidence.d.ts +288 -0
  129. package/dist/invitations/delivery-evidence.js +766 -0
  130. package/dist/invitations/expect-welcome.d.ts +66 -0
  131. package/dist/invitations/expect-welcome.js +138 -0
  132. package/dist/invitations/index.d.ts +18 -0
  133. package/dist/invitations/index.js +18 -0
  134. package/dist/invitations/invitation-outcome.d.ts +110 -0
  135. package/dist/invitations/invitation-outcome.js +210 -0
  136. package/dist/invitations/invite.d.ts +358 -0
  137. package/dist/invitations/invite.js +1102 -0
  138. package/dist/invitations/offers.d.ts +79 -0
  139. package/dist/invitations/offers.js +115 -0
  140. package/dist/invitations/on-proposal.d.ts +47 -0
  141. package/dist/invitations/on-proposal.js +40 -0
  142. package/dist/invitations/pending-proposal-policy.d.ts +52 -0
  143. package/dist/invitations/pending-proposal-policy.js +139 -0
  144. package/dist/invitations/proposal-deadline.d.ts +133 -0
  145. package/dist/invitations/proposal-deadline.js +164 -0
  146. package/dist/invitations/relay-planes.d.ts +43 -0
  147. package/dist/invitations/relay-planes.js +70 -0
  148. package/dist/invitations/welcome-processor.d.ts +272 -0
  149. package/dist/invitations/welcome-processor.js +1241 -0
  150. package/dist/key-packages/device-key.d.ts +131 -0
  151. package/dist/key-packages/device-key.js +272 -0
  152. package/dist/key-packages/device-rotation-records.d.ts +83 -0
  153. package/dist/key-packages/device-rotation-records.js +173 -0
  154. package/dist/key-packages/group-refs.d.ts +40 -0
  155. package/dist/key-packages/group-refs.js +79 -0
  156. package/dist/key-packages/index.d.ts +18 -0
  157. package/dist/key-packages/index.js +18 -0
  158. package/dist/key-packages/key-package-ref.d.ts +16 -0
  159. package/dist/key-packages/key-package-ref.js +21 -0
  160. package/dist/key-packages/observation-stream.d.ts +4 -0
  161. package/dist/key-packages/observation-stream.js +120 -0
  162. package/dist/key-packages/offer-rumor.d.ts +26 -0
  163. package/dist/key-packages/offer-rumor.js +69 -0
  164. package/dist/key-packages/publisher.d.ts +174 -0
  165. package/dist/key-packages/publisher.js +1247 -0
  166. package/dist/key-packages/select-key-package.d.ts +24 -0
  167. package/dist/key-packages/select-key-package.js +90 -0
  168. package/dist/key-packages/slot-manager.d.ts +167 -0
  169. package/dist/key-packages/slot-manager.js +327 -0
  170. package/dist/key-packages/validate-key-package-event.d.ts +3 -0
  171. package/dist/key-packages/validate-key-package-event.js +49 -0
  172. package/dist/media/cache.d.ts +14 -0
  173. package/dist/media/cache.js +10 -0
  174. package/dist/media/index.d.ts +52 -0
  175. package/dist/media/index.js +71 -0
  176. package/dist/mls.d.ts +15 -0
  177. package/dist/mls.js +15 -0
  178. package/dist/shared/account-pubkey.d.ts +4 -0
  179. package/dist/shared/account-pubkey.js +10 -0
  180. package/dist/shared/errors.d.ts +28 -0
  181. package/dist/shared/errors.js +96 -0
  182. package/dist/shared/hex.d.ts +4 -0
  183. package/dist/shared/hex.js +13 -0
  184. package/dist/shared/index.d.ts +14 -0
  185. package/dist/shared/index.js +14 -0
  186. package/dist/shared/kinds.d.ts +8 -0
  187. package/dist/shared/kinds.js +28 -0
  188. package/dist/shared/publish-classification.d.ts +26 -0
  189. package/dist/shared/publish-classification.js +31 -0
  190. package/dist/storage/envelope.d.ts +39 -0
  191. package/dist/storage/envelope.js +201 -0
  192. package/dist/storage/index.d.ts +237 -0
  193. package/dist/storage/index.js +491 -0
  194. package/dist/storage/indexeddb/idb-types.d.ts +68 -0
  195. package/dist/storage/indexeddb/idb-types.js +1 -0
  196. package/dist/storage/indexeddb/index.d.ts +17 -0
  197. package/dist/storage/indexeddb/index.js +141 -0
  198. package/dist/storage/lease.d.ts +54 -0
  199. package/dist/storage/lease.js +168 -0
  200. package/dist/storage/memory/deterministic-signer.d.ts +27 -0
  201. package/dist/storage/memory/deterministic-signer.js +65 -0
  202. package/dist/storage/memory/index.d.ts +32 -0
  203. package/dist/storage/memory/index.js +87 -0
  204. package/dist/storage/memory/lock-manager.d.ts +8 -0
  205. package/dist/storage/memory/lock-manager.js +71 -0
  206. package/package.json +66 -3
@@ -0,0 +1,1247 @@
1
+ /**
2
+ * KeyPackage lifecycle orchestration (S4): `create`/`rotate`/`forget`/
3
+ * `list`/`count`. Depends only on {@link KeyPackagesDeps} — never on
4
+ * `client/create-client.ts`'s `ClientContext` or `ReentrancyGuard` type
5
+ * (architecture.md boundary rule: a feature module must not import
6
+ * `client/`). `client/create-client.ts` wires its own `ctx`/`guard` into
7
+ * this shape at the call site, the same way `group-runtime.ts` wires the
8
+ * signer/store/transport calls of `groups.create` through `guard.call`.
9
+ *
10
+ * Gate-remediation round 1 (F1/F7): every state change is intent -> publish
11
+ * -> confirm, per spec.md's Design Decision 1:
12
+ *
13
+ * 1. tx1 persists a durable {@link PendingIntent} — the signed event, the
14
+ * new private KeyPackage (create/rotate) and the exact relay set this
15
+ * attempt targets.
16
+ * 2. The event is (re)published OUTSIDE any transaction.
17
+ * 3. On acceptance, tx2 commits: the intent's event moves into
18
+ * `published`, the new private KeyPackage becomes `currentPrivate`,
19
+ * and — for a rotate — the OLD current moves into `superseded` with
20
+ * its own absolute expiry. `pending` is cleared.
21
+ *
22
+ * `resumePendingIntents` runs this same publish -> commit step for any
23
+ * slot still carrying a `pending` intent, at the START of every op (create/
24
+ * rotate/forget/list/count) — the "at client start/reload" case is simply
25
+ * the first op call after a reload, since nothing here runs a background
26
+ * loop.
27
+ *
28
+ * Gate-remediation round 2 adds:
29
+ * - R1: every tx1 RE-READS the slot inside the transaction and rejects
30
+ * `pending-intent` (or, for rotate, `already-superseded`) if the
31
+ * situation changed since the pre-check that ran before the (possibly
32
+ * slow, off-transaction) mint/sign step — closing the race a
33
+ * transaction-serialised pre-check-then-write alone does not.
34
+ * `commitPendingIntent` additionally requires the freshly-read
35
+ * `pending.event.id` to match the intent being committed, so a stale
36
+ * resume (one that started before a newer intent replaced this slot's
37
+ * `pending`) can never clobber it.
38
+ * - R2: (1) an empty resolved relay set is rejected `no-relays` before
39
+ * any KeyPackage is minted; (2) a publish is classified via the shared
40
+ * `classifyPublish` (promoted to `shared/`); a `terminal` classification
41
+ * ABANDONS the intent (round 3, P1, superseded round 2's own delete-
42
+ * pending design — see below); (3) `forget()` on a slot with a pending
43
+ * create/rotate REPLACES that intent with a delete covering every
44
+ * published event plus the pending one (round 3, P2, superseded round
45
+ * 2's sign-inside-the-transaction approach — see below); (4)
46
+ * `resumePendingIntents` skips a slot within `RESUME_BACKOFF_MS` of its
47
+ * last attempt, so `list()`/`count()` do not pay a relay round-trip per
48
+ * stuck slot on every call.
49
+ * - R3: `findPrivateKeyPackage` (slot-manager.ts) also matches a pending
50
+ * intent's `keyPackageRef` — moved there since it operates on a
51
+ * `KeyValueView` directly.
52
+ *
53
+ * Gate-remediation round 3 corrects two round-2 designs the re-review found
54
+ * unsafe:
55
+ * - P1/P3: a TERMINAL classification no longer builds a kind-5 delete at
56
+ * all. `terminal` means EVERY relay in the plane refused the event
57
+ * outright (a relay that already held it would answer `duplicate:`,
58
+ * which is `accepted`, not `terminal`), so there is nothing on any
59
+ * relay to delete. `abandonPendingIntent` now simply DROPS the pending
60
+ * intent in one transaction — `create` drops the whole slot, `rotate`
61
+ * clears `pending` only (keeping the OLD current KeyPackage) — never
62
+ * signs, never publishes. This also fixes a hazard round 2 missed:
63
+ * `createDeleteKeyPackageEvent` given a full event emits an `a`
64
+ * (address) tag, and a rotate's abandoned candidate shares its slot's
65
+ * `d` tag with the OLD current KeyPackage — an address-scoped delete
66
+ * could have wiped the very KeyPackage the abandon promises to keep —
67
+ * and it means a read-only `list()`/`count()` resume can never trigger
68
+ * a signer prompt.
69
+ * - P2: `forget()`'s absorb step no longer calls `deps.signEvent` from
70
+ * inside `deps.transaction`'s `fn` (a regression from the F1/F7
71
+ * optimistic pattern every other write in this module uses). It now
72
+ * snapshots the target id set in one transaction, signs the kind-5
73
+ * OUTSIDE any transaction, then re-reads and compares in a second
74
+ * ("absorb") transaction — installing the pending delete only if the
75
+ * target set still matches, else retrying the whole cycle (bounded) and
76
+ * finally rejecting `pending-intent` rather than installing a delete
77
+ * that might miss a concurrently-added event.
78
+ * - P4: `forget()` on a slot whose `pending` is ALREADY a genuine
79
+ * full-slot delete is idempotent — it returns without throwing, without
80
+ * touching the existing pending delete. A slot whose pending is some
81
+ * OTHER kind of delete (a shape no code path produces any more, but
82
+ * handled defensively) is instead absorbed and replaced the same way a
83
+ * pending create/rotate is.
84
+ */
85
+ import { ADDRESSABLE_KEY_PACKAGE_KIND, createCredential, createDeleteKeyPackageEvent, createKeyPackageEvent, generateKeyPackage, getKeyPackage, getKeyPackageLifetime, } from '@941design/marmot-engine/core';
86
+ // Ciphersuite selection is not part of `/core`'s own surface — every core
87
+ // function that builds a KeyPackage (`generateKeyPackage`, `createSimpleGroup`,
88
+ // ...) takes an already-resolved `CiphersuiteImpl` as a parameter, so a
89
+ // caller reaches `/mls` for it exactly as `client/group-runtime.ts` does
90
+ // (architecture.md's dependencies_allowed row for key-packages is amended
91
+ // to include `mls` for this narrow reason — see this story's architecture.json).
92
+ import { defaultCryptoProvider, getCiphersuiteImpl } from '@941design/marmot-engine/mls';
93
+ import { verifyEvent } from '@941design/nostr-events/event';
94
+ import { parseRelayList10002 } from '@941design/nostr-events/parsers';
95
+ import { classifyPublish, isMarmotError, MarmotError } from '../shared/index.js';
96
+ import { computeKeyPackageRefHex, deleteSlot, generateSlotId, listSlots, purgeExpiredSuperseded, readSlot, reapExpiredUnconfirmed, writeSlot, } from './slot-manager.js';
97
+ import { isKeyUnretained } from './group-refs.js';
98
+ import { isLeafKeyHex } from './device-rotation-records.js';
99
+ import { deviceProofSigner, ensureDeviceSigningKey, readDeviceSigningKey, readDeviceSigningKeyIn, withDeviceSignatureKey } from './device-key.js';
100
+ import { validateKeyPackageEvent } from './validate-key-package-event.js';
101
+ // Matches `client/group-runtime.ts`'s DEFAULT_CIPHERSUITE — every KeyPackage
102
+ // this client mints (as opposed to one it only reads/selects) uses it. Exported for the client's device-key rotation wiring
103
+ // (`devices.rotateKey()` generates its key with the suite every leaf uses).
104
+ export const DEFAULT_CIPHERSUITE_NAME = 'MLS_128_DHKEMX25519_AES128GCM_SHA256_Ed25519';
105
+ // R2(4): a stuck pending intent is retried at most once per this window on
106
+ // resume (create()/rotate()/forget()'s OWN first attempt always runs
107
+ // immediately, regardless — this only throttles `resumePendingIntents`'s
108
+ // opportunistic retry on every `list()`/`count()`/other-slot's op). Picked
109
+ // to be comfortably longer than a normal relay round-trip (so a genuinely
110
+ // transient failure gets a few retries per minute) while keeping `list()`/
111
+ // `count()` cheap for an account with a long-stuck slot.
112
+ export const RESUME_BACKOFF_MS = 30_000;
113
+ export function createParkedProbeState() {
114
+ return { done: false, lastAttemptMs: undefined, inFlight: false };
115
+ }
116
+ function invalid(message, details) {
117
+ return new MarmotError('invalid-options', `keyPackages: ${message}`, details === undefined ? undefined : { details });
118
+ }
119
+ const ARTIFACT = 'keyPackages';
120
+ // ---------------------------------------------------------------------------
121
+ // Relay resolution (10002 write-capable set, AC-KP publish-relay clause)
122
+ // ---------------------------------------------------------------------------
123
+ /** Newest-first, tied-break-by-lower-id: the same ordering `pickLatestRelayListEvent` used before gate-remediation C2, now used to try candidates in preference order rather than to pick a single winner outright. */
124
+ function relayListCandidatesNewestFirst(events, pubkey) {
125
+ return events
126
+ .filter((e) => e.kind === 10002 && e.pubkey === pubkey)
127
+ .sort((a, b) => (b.created_at !== a.created_at ? b.created_at - a.created_at : a.id < b.id ? -1 : a.id > b.id ? 1 : 0));
128
+ }
129
+ /**
130
+ * Gate-remediation C2: a relay is not obliged to honour the filter it was
131
+ * asked, and MUST NOT be trusted to serve only genuine kind-10002 events
132
+ * for `pubkey` — every candidate's signature is verified (`verifyEvent`,
133
+ * regardless of whether a consumer `verifier` is configured: forged/
134
+ * tampered relay-list events are always a signature-verification concern,
135
+ * not merely a policy one) and, when a consumer `verifier` IS configured,
136
+ * that too (matching `observeKeyPackages`'s own gate). The newest candidate
137
+ * that passes both wins; `undefined` when none does.
138
+ */
139
+ async function selectValidRelayListEvent(deps, events, pubkey) {
140
+ for (const candidate of relayListCandidatesNewestFirst(events, pubkey)) {
141
+ if (!verifyEvent(candidate))
142
+ continue;
143
+ if (deps.verifier !== undefined) {
144
+ let ok;
145
+ try {
146
+ ok = await deps.verifier(candidate);
147
+ }
148
+ catch {
149
+ ok = false;
150
+ }
151
+ if (!ok)
152
+ continue;
153
+ }
154
+ return candidate;
155
+ }
156
+ return undefined;
157
+ }
158
+ /**
159
+ * Resolves the write-relay set for `pubkey`: an explicit `override` wins;
160
+ * else `relays.mode === 'fixed'` uses `relays.defaults` directly; else
161
+ * (`'discover'`) fetches `pubkey`'s newest VALID (signature- and, when
162
+ * configured, verifier-passing — C2) kind-10002 and takes its `write` set,
163
+ * falling back to `relays.defaults` on timeout/absence/no valid candidate/
164
+ * empty write set. Shared by `create()`, `rotate()` (F12: rotate re-resolves
165
+ * on every call) and `observeKeyPackages` (F9: "the same way create does"),
166
+ * parameterised on `pubkey` so `observe(account, ...)` resolves the
167
+ * OBSERVED account's relays, not necessarily the caller's own.
168
+ */
169
+ export async function resolveWriteRelays(deps, pubkey, override) {
170
+ if (override !== undefined)
171
+ return [...override];
172
+ if (deps.relays.mode === 'fixed')
173
+ return [...deps.relays.defaults];
174
+ const result = await deps.requestWithDeadline(deps.relays.defaults, { kinds: [10002], authors: [pubkey] }, { timeoutMs: deps.historyTimeoutMs });
175
+ if (!result.timedOut) {
176
+ const latest = await selectValidRelayListEvent(deps, result.events, pubkey);
177
+ if (latest !== undefined) {
178
+ const { write } = parseRelayList10002(latest);
179
+ if (write.length > 0)
180
+ return write;
181
+ }
182
+ }
183
+ return [...deps.relays.defaults];
184
+ }
185
+ function unionRelays(a, b) {
186
+ const set = new Set(a);
187
+ for (const r of b)
188
+ set.add(r);
189
+ return [...set];
190
+ }
191
+ async function classifyAttempt(deps, relays, event) {
192
+ let responses;
193
+ try {
194
+ responses = await deps.publish(relays, event);
195
+ }
196
+ catch {
197
+ return 'retryable'; // a thrown network error is transient, never terminal
198
+ }
199
+ return classifyPublish(relays, responses).outcome;
200
+ }
201
+ // ---------------------------------------------------------------------------
202
+ // Durable intent: commit (tx2), abandon, and the publish-then-settle step
203
+ // ---------------------------------------------------------------------------
204
+ /**
205
+ * NIP-01 addressable replacement order: whether `a` replaces `b` at the same
206
+ * address — a greater `created_at`, ties broken towards the lower event id.
207
+ */
208
+ function replaces(a, b) {
209
+ return a.created_at > b.created_at || (a.created_at === b.created_at && a.id < b.id);
210
+ }
211
+ /**
212
+ * The slot after `entry` becomes its current KeyPackage: appended to
213
+ * `published`, `currentPrivate`/`currentRef` replaced, and the previous
214
+ * current (if any) moved into `superseded` with its own absolute expiry —
215
+ * or dropped when S9 marked its key unretained. `unconfirmed` is the caller's
216
+ * to decide; every other field is carried forward explicitly.
217
+ */
218
+ async function adoptAsCurrent(deps, tx, fresh, entry, targetRelays, unconfirmed, nowMs) {
219
+ const retain = fresh.currentRef !== undefined && !(await isKeyUnretained(tx, fresh.currentRef));
220
+ const superseded = fresh.currentPrivate !== undefined && fresh.currentRef !== undefined && retain
221
+ ? [...fresh.superseded, { keyPackageRef: fresh.currentRef, privatePackage: fresh.currentPrivate, supersededAtMs: nowMs, expiresAtMs: nowMs + deps.graceWindowMs }]
222
+ : fresh.superseded;
223
+ return {
224
+ dSlot: fresh.dSlot,
225
+ lastResort: fresh.lastResort,
226
+ relays: unionRelays(fresh.relays, targetRelays),
227
+ published: [...fresh.published, { event: entry.event, keyPackageRef: entry.keyPackageRef }],
228
+ superseded,
229
+ unconfirmed,
230
+ ...(fresh.deletions === undefined ? {} : { deletions: fresh.deletions }),
231
+ ...(fresh.deletionEvent === undefined ? {} : { deletionEvent: fresh.deletionEvent }),
232
+ ...(entry.privatePackage === undefined ? {} : { currentPrivate: entry.privatePackage }),
233
+ currentRef: entry.keyPackageRef,
234
+ };
235
+ }
236
+ /**
237
+ * `published` with `entry` inserted among the non-current entries at its
238
+ * `created_at` position (after any entry with an equal or smaller one); the
239
+ * current entry stays last.
240
+ */
241
+ function insertBeforeCurrent(published, entry) {
242
+ const history = published.slice(0, -1);
243
+ const current = published.slice(-1);
244
+ let at = history.length;
245
+ while (at > 0 && history[at - 1].event.created_at > entry.event.created_at)
246
+ at -= 1;
247
+ return [...history.slice(0, at), entry, ...history.slice(at), ...current];
248
+ }
249
+ /**
250
+ * AC-KPL-1: settles a relay-accepted create/rotate event a concurrent attempt
251
+ * already parked in `unconfirmed` (that attempt came back terminal while
252
+ * `mayBeLive`). Returns whether the event became current:
253
+ * - not parked, or a `forget()` delete is pending on the slot (the
254
+ * candidate stays in `unconfirmed`, where the in-flight delete targets
255
+ * it) — `false`, nothing written;
256
+ * - the slot's current replaces the accepted event at the address (a newer
257
+ * current was adopted meanwhile) — the accepted event leaves
258
+ * `unconfirmed` as a superseded generation: its key into `superseded`
259
+ * with the grace window (dropped when S9-unretained), its event into
260
+ * `published` at its `created_at` position before the current entry, so
261
+ * a Welcome built against it can still be joined and `forget()` still
262
+ * targets it; `false`;
263
+ * - otherwise — it leaves `unconfirmed` and becomes current exactly as a
264
+ * normal commit would, `true`.
265
+ */
266
+ async function settleParkedAcceptance(deps, tx, fresh, eventId, targetRelays) {
267
+ if (fresh.pending?.kind === 'delete')
268
+ return false;
269
+ const parked = fresh.unconfirmed.find((u) => u.event.id === eventId);
270
+ if (parked === undefined)
271
+ return false;
272
+ const view = tx.artifact(ARTIFACT);
273
+ const nowMs = deps.clock.now();
274
+ const unconfirmed = fresh.unconfirmed.filter((u) => u.event.id !== parked.event.id);
275
+ const current = fresh.published[fresh.published.length - 1];
276
+ if (current !== undefined && replaces(current.event, parked.event)) {
277
+ const retain = !(await isKeyUnretained(tx, parked.keyPackageRef));
278
+ const superseded = retain
279
+ ? [...fresh.superseded, { keyPackageRef: parked.keyPackageRef, privatePackage: parked.privatePackage, supersededAtMs: nowMs, expiresAtMs: nowMs + deps.graceWindowMs }]
280
+ : fresh.superseded;
281
+ const published = insertBeforeCurrent(fresh.published, { event: parked.event, keyPackageRef: parked.keyPackageRef });
282
+ await writeSlot(view, { ...fresh, relays: unionRelays(fresh.relays, targetRelays), published, unconfirmed, superseded });
283
+ return false;
284
+ }
285
+ await writeSlot(view, { ...(await adoptAsCurrent(deps, tx, fresh, parked, targetRelays, unconfirmed, nowMs)), ...(fresh.pending === undefined ? {} : { pending: fresh.pending }) });
286
+ return true;
287
+ }
288
+ /**
289
+ * tx2: adopts a confirmed intent's event/private KeyPackage into the slot
290
+ * and clears `pending`. A `delete` intent drops the whole slot. Returns
291
+ * `false` — "not adopted", although the publish WAS accepted by a relay —
292
+ * when the slot's `pending` no longer names this intent and the intent was
293
+ * neither already adopted by a concurrent attempt (create/rotate: our event
294
+ * in `published` and current; delete: slot gone) nor promotable out of
295
+ * `unconfirmed` ({@link settleParkedAcceptance}, AC-KPL-1). The caller MUST
296
+ * treat `false` as "not confirmed" and never report success for it.
297
+ */
298
+ async function commitPendingIntent(deps, dSlot, pending) {
299
+ return deps.transaction(async (tx) => {
300
+ const view = tx.artifact(ARTIFACT);
301
+ const fresh = await readSlot(view, dSlot);
302
+ if (fresh?.pending === undefined || fresh.pending.event.id !== pending.event.id) {
303
+ // A concurrent attempt on this same intent may have settled it first:
304
+ // committed it (already adopted), or — terminal while mayBeLive —
305
+ // parked it in `unconfirmed` although this attempt was accepted.
306
+ if (pending.kind === 'delete')
307
+ return fresh === undefined;
308
+ if (fresh === undefined)
309
+ return false;
310
+ if (fresh.currentRef === pending.keyPackageRef && fresh.published.some((e) => e.event.id === pending.event.id))
311
+ return true;
312
+ return settleParkedAcceptance(deps, tx, fresh, pending.event.id, pending.targetRelays);
313
+ }
314
+ if (pending.kind === 'delete') {
315
+ await deleteSlot(view, dSlot);
316
+ return true;
317
+ }
318
+ const { pending: _cleared, ...rest } = fresh;
319
+ void _cleared;
320
+ const entry = { event: pending.event, keyPackageRef: pending.keyPackageRef, privatePackage: pending.privatePackage };
321
+ await writeSlot(view, await adoptAsCurrent(deps, tx, rest, entry, pending.targetRelays, fresh.unconfirmed, deps.clock.now()));
322
+ return true;
323
+ });
324
+ }
325
+ /**
326
+ * R6 invariant (round 6): runs BEFORE any network I/O for an attempt, in
327
+ * its OWN transaction, so a crash DURING the publish call itself still
328
+ * leaves durable evidence, on resume, that this intent has now had at
329
+ * least one real attempt — not just evidence collected after a clean
330
+ * `classifyAttempt` return (F1: "the relay stored the event, the ack was
331
+ * lost" is exactly the case a purely after-the-fact marker would miss).
332
+ * `mayBeLive` flips permanently true the moment there is evidence of a
333
+ * PRIOR attempt (this round's own `lastAttemptMs`, once durably written
334
+ * here, becomes "prior" evidence for whichever attempt comes after it) —
335
+ * it only ever goes false -> true, never back. A no-op (returns `pending`
336
+ * unchanged) if the intent has since been replaced elsewhere — the same
337
+ * stale guard every other step in this pipeline uses; the caller proceeds
338
+ * to publish with the ORIGINAL `pending` in that case, and
339
+ * `commitPendingIntent`/`abandonPendingIntent`'s own fresh re-read settles
340
+ * the race as usual (D1).
341
+ */
342
+ async function markAttemptStarting(deps, dSlot, pending, nowMs) {
343
+ return deps.transaction(async (tx) => {
344
+ const view = tx.artifact(ARTIFACT);
345
+ const fresh = await readSlot(view, dSlot);
346
+ if (fresh?.pending === undefined || fresh.pending.event.id !== pending.event.id)
347
+ return pending;
348
+ const mayBeLive = fresh.pending.mayBeLive === true || fresh.pending.lastAttemptMs !== undefined;
349
+ const updated = { ...fresh.pending, mayBeLive, lastAttemptMs: nowMs };
350
+ await writeSlot(view, { ...fresh, pending: updated });
351
+ return updated;
352
+ });
353
+ }
354
+ /** Records a publish attempt's timestamp for R2(4)'s backoff, without disturbing anything else. A no-op if the intent has since been replaced. */
355
+ async function recordAttempt(deps, dSlot, pending, nowMs) {
356
+ await deps.transaction(async (tx) => {
357
+ const view = tx.artifact(ARTIFACT);
358
+ const fresh = await readSlot(view, dSlot);
359
+ if (fresh?.pending === undefined || fresh.pending.event.id !== pending.event.id)
360
+ return;
361
+ // R6: this attempt's own outcome classified retryable (which also
362
+ // covers a thrown/caught publish error, `classifyAttempt`'s "unknown"
363
+ // case) — "may be live" holds immediately, not only once some LATER
364
+ // attempt's own `markAttemptStarting` happens to notice `lastAttemptMs`
365
+ // was already set.
366
+ await writeSlot(view, { ...fresh, pending: { ...fresh.pending, lastAttemptMs: nowMs, mayBeLive: true } });
367
+ });
368
+ }
369
+ /**
370
+ * Gate-remediation round 3 (P1/P3): a TERMINALLY-rejected create/rotate is
371
+ * simply DROPPED — never turned into a kind-5 delete. `terminal` means
372
+ * EVERY relay in the plane refused the event outright; a relay that
373
+ * already held it would have answered `duplicate:`, which classifies as
374
+ * `accepted`, not `terminal` — so by construction nothing exists on any
375
+ * relay to delete. Signing and publishing a delete here would also be
376
+ * wrong on two counts the round-2 design missed: (a) `createDeleteKeyPackageEvent`
377
+ * given a full event emits an `a` (address) tag alongside the `e` tag, and
378
+ * a rotate's abandoned candidate shares its slot's `d` tag with the OLD
379
+ * current KeyPackage — an address-scoped NIP-09 delete could wipe the very
380
+ * KeyPackage rotate-abandon promises to keep; (b) `abandonPendingIntent`
381
+ * runs from ANY op's opportunistic resume, including the read-only
382
+ * `list()`/`count()` — signing a delete there means a read-only call could
383
+ * trigger a signer prompt.
384
+ *
385
+ * Gate-remediation round 6 (F1, the R6 "never discard potentially-published
386
+ * material" invariant): a TERMINAL classification no longer proves nothing
387
+ * was ever accepted — only a TERMINAL result on this intent's PROVABLY
388
+ * FIRST-EVER attempt does. `fresh.pending.mayBeLive` (durably set by
389
+ * `markAttemptStarting`/`recordAttempt`, never this function) is the source
390
+ * of truth:
391
+ *
392
+ * - `!mayBeLive` (first-ever attempt, cleanly terminal): nothing was ever
393
+ * accepted anywhere — safe to drop everything, exactly as rounds 1-5
394
+ * always have.
395
+ * - `mayBeLive` (a prior attempt happened, or this round's own earlier
396
+ * outcome was retryable/unknown before a later resume's attempt came
397
+ * back terminal): the candidate's private key/ref/event stay retained
398
+ * and addressable rather than discarded — for BOTH `create` and
399
+ * `rotate` (round 6 stop-rule fix: an earlier version of this moved a
400
+ * mayBeLive rotate candidate into `superseded` instead, but that
401
+ * expires after a flat `graceWindowMs`, and C1's created_at floor can
402
+ * make exactly this candidate the NEWEST version advertised at the
403
+ * address — its key could expire while still live, breaking Welcome
404
+ * decryption, and `superseded` carries no `event`, so `forget()` could
405
+ * no longer find it by ref either). The candidate moves into
406
+ * `unconfirmed` — hidden from `list()`/`count()` (D2's `isListable`
407
+ * only ever looks at `published`, round 6 unchanged), but resolvable by
408
+ * `findPrivateKeyPackage` (a Welcome built against it) and by
409
+ * `forget()`'s own ref lookup. For `rotate`, the OLD current is
410
+ * untouched and stays current throughout. Reaped by
411
+ * `reapExpiredUnconfirmed` (slot-manager.ts, called alongside the
412
+ * existing `superseded` grace-window purge) once the KeyPackage's own
413
+ * leaf lifetime `notAfter` plus `graceWindowMs` passes (AC-KPL-3), see
414
+ * {@link UnconfirmedEntry}'s own doc comment for why.
415
+ * - `delete`: a delete candidate has no private key/ref of its own to
416
+ * protect — clearing `pending` and leaving everything else (`published`/
417
+ * `unconfirmed`/`superseded`/`currentPrivate`/`currentRef`) exactly as
418
+ * it was already satisfies F2: a terminally-rejected delete drops
419
+ * NOTHING, so a later `forget()` can retry against the very same
420
+ * targets; only a CONFIRMED delete (`commitPendingIntent`) ever calls
421
+ * `deleteSlot`.
422
+ *
423
+ * Never signs, never publishes. A no-op if the intent has since been
424
+ * replaced by something else.
425
+ */
426
+ async function abandonPendingIntent(deps, dSlot, pending) {
427
+ await deps.transaction(async (tx) => {
428
+ const view = tx.artifact(ARTIFACT);
429
+ const fresh = await readSlot(view, dSlot);
430
+ if (fresh?.pending === undefined || fresh.pending.event.id !== pending.event.id)
431
+ return;
432
+ const current = fresh.pending;
433
+ const { pending: _drop, ...rest } = fresh;
434
+ void _drop;
435
+ if (current.kind === 'delete') {
436
+ await writeSlot(view, rest);
437
+ return;
438
+ }
439
+ if (current.mayBeLive !== true) {
440
+ if (current.kind === 'create') {
441
+ await deleteSlot(view, dSlot);
442
+ }
443
+ else {
444
+ await writeSlot(view, rest);
445
+ }
446
+ return;
447
+ }
448
+ // Gate-remediation round 6 stop-rule fix (Codex P1 / Opus N-R6-2): a
449
+ // mayBeLive ROTATE candidate used to move into `superseded`, which
450
+ // expires after a flat `graceWindowMs` — but C1's created_at floor can
451
+ // make this exact candidate the NEWEST version advertised at the
452
+ // address, so its key could expire from `superseded` while it is still
453
+ // the live one, breaking Welcome decryption, and it loses its event
454
+ // identity (a `superseded` entry carries no `event`), so
455
+ // `forget(candidateRef)` could no longer find it. Both create AND
456
+ // rotate mayBeLive candidates now move into the SAME `unconfirmed`
457
+ // bucket, keeping the full entry (event, keyPackageRef, privatePackage)
458
+ // — reaped by `reapExpiredUnconfirmed` (slot-manager.ts) once the
459
+ // KeyPackage's OWN leaf lifetime `notAfter` plus `graceWindowMs` has passed (AC-KPL-3), not a flat
460
+ // grace window (N-R6-1: `unconfirmed` was otherwise never reaped at
461
+ // all). The OLD current (for a rotate) is untouched either way.
462
+ const unconfirmedEntry = { event: current.event, keyPackageRef: current.keyPackageRef, privatePackage: current.privatePackage };
463
+ await writeSlot(view, { ...rest, unconfirmed: [...fresh.unconfirmed, unconfirmedEntry] });
464
+ });
465
+ }
466
+ /**
467
+ * Publishes `pending.event` to `pending.targetRelays`, classifies the
468
+ * outcome, and settles accordingly: `accepted` commits (tx2) — `stale` when
469
+ * that commit turns out to be a no-op (R1); `terminal` abandons (turns into
470
+ * a durable delete, R2(2)); `retryable` just records the attempt for the
471
+ * backoff window.
472
+ */
473
+ async function attemptPublishAndCommit(deps, dSlot, pending) {
474
+ const marked = await markAttemptStarting(deps, dSlot, pending, deps.clock.now()); // R6: before any network I/O
475
+ const outcome = await classifyAttempt(deps, marked.targetRelays, marked.event);
476
+ if (outcome === 'accepted') {
477
+ const committed = await commitPendingIntent(deps, dSlot, marked);
478
+ return committed ? 'confirmed' : 'stale';
479
+ }
480
+ if (outcome === 'terminal') {
481
+ await abandonPendingIntent(deps, dSlot, marked);
482
+ return 'not-confirmed';
483
+ }
484
+ await recordAttempt(deps, dSlot, marked, deps.clock.now());
485
+ return 'not-confirmed';
486
+ }
487
+ /**
488
+ * AC-KPL-1 after a crash or reload: an accepted event can stay parked in
489
+ * `unconfirmed` when the process stopped after a concurrent terminal resume
490
+ * parked it but before the accepting attempt committed. Until one probe
491
+ * completes on this client, asks the slots' relays for every `unconfirmed`
492
+ * event id in one batched request within `historyTimeoutMs`, and settles
493
+ * each event a relay returns (signature-checked, id-matched) through
494
+ * {@link settleParkedAcceptance}, oldest `created_at` first per slot. The
495
+ * probe counts as done only when the request completed without timing out
496
+ * (or nothing was parked); a failed or timed-out probe is retried at most
497
+ * once per {@link RESUME_BACKOFF_MS}, and meanwhile the entries simply stay
498
+ * in `unconfirmed` (reaped at `notAfter * 1000 + graceWindowMs`). Run by
499
+ * `create()`/`rotate()` and the inbox pass, never by `list()`/`count()`, so
500
+ * reads never wait on a relay.
501
+ */
502
+ export async function probeParkedUnconfirmed(deps) {
503
+ const state = deps.parkedProbe;
504
+ if (state.done || state.inFlight)
505
+ return;
506
+ const nowMs = deps.clock.now();
507
+ if (state.lastAttemptMs !== undefined && nowMs - state.lastAttemptMs < RESUME_BACKOFF_MS)
508
+ return;
509
+ state.inFlight = true;
510
+ state.lastAttemptMs = nowMs;
511
+ try {
512
+ const parked = await deps.transaction(async (tx) => (await listSlots(tx.artifact(ARTIFACT))).filter((r) => r.unconfirmed.length > 0));
513
+ const ids = new Set(parked.flatMap((r) => r.unconfirmed.map((u) => u.event.id)));
514
+ const relays = parked.reduce((acc, r) => unionRelays(acc, r.relays), []);
515
+ if (ids.size === 0 || relays.length === 0) {
516
+ state.done = true;
517
+ return;
518
+ }
519
+ const result = await deps.requestWithDeadline(relays, { ids: [...ids] }, { timeoutMs: deps.historyTimeoutMs });
520
+ const held = new Set(result.events.filter((e) => ids.has(e.id) && verifyEvent(e)).map((e) => e.id));
521
+ for (const record of parked) {
522
+ const found = record.unconfirmed.filter((u) => held.has(u.event.id)).sort((a, b) => a.event.created_at - b.event.created_at);
523
+ if (found.length === 0)
524
+ continue;
525
+ await deps.transaction(async (tx) => {
526
+ for (const entry of found) {
527
+ const fresh = await readSlot(tx.artifact(ARTIFACT), record.dSlot);
528
+ if (fresh === undefined)
529
+ return;
530
+ await settleParkedAcceptance(deps, tx, fresh, entry.event.id, []);
531
+ }
532
+ });
533
+ }
534
+ if (!result.timedOut)
535
+ state.done = true;
536
+ }
537
+ catch {
538
+ // A failed probe changes nothing: the entries stay in `unconfirmed` until a later retry.
539
+ }
540
+ finally {
541
+ state.inFlight = false;
542
+ }
543
+ }
544
+ /**
545
+ * Resolves every slot's pending intent, if any and if due (R2(4) backoff), by (re)publishing its already-signed event — idempotent, so a duplicate republish is harmless.
546
+ * Exported for S6: every inbox pass runs it, so an idle client still settles a rotation whose publish failed.
547
+ */
548
+ export async function resumePendingIntents(deps) {
549
+ const pendingSlots = await deps.transaction(async (tx) => {
550
+ const records = await listSlots(tx.artifact(ARTIFACT));
551
+ return records.filter((r) => r.pending !== undefined).map((r) => r.dSlot);
552
+ });
553
+ const nowMs = deps.clock.now();
554
+ for (const dSlot of pendingSlots) {
555
+ const record = await deps.transaction((tx) => readSlot(tx.artifact(ARTIFACT), dSlot));
556
+ if (record?.pending === undefined)
557
+ continue; // resolved by a concurrent op since the list above
558
+ const lastAttempt = record.pending.lastAttemptMs;
559
+ if (lastAttempt !== undefined && nowMs - lastAttempt < RESUME_BACKOFF_MS)
560
+ continue;
561
+ await attemptPublishAndCommit(deps, dSlot, record.pending);
562
+ }
563
+ }
564
+ /**
565
+ * Round 6 stop-rule fix: also reaps `unconfirmed` entries past their OWN
566
+ * KeyPackage lifetime (`reapExpiredUnconfirmed`), alongside the existing
567
+ * `superseded` grace-window purge — one pass, one write per changed record.
568
+ * Exported for S6: every inbox pass runs this same purge.
569
+ */
570
+ export async function purgeAllExpiredSuperseded(deps) {
571
+ await deps.transaction(async (tx) => {
572
+ const view = tx.artifact(ARTIFACT);
573
+ const now = deps.clock.now();
574
+ for (const record of await listSlots(view)) {
575
+ const purged = reapExpiredUnconfirmed(purgeExpiredSuperseded(record, now), now, deps.graceWindowMs);
576
+ if (purged !== record)
577
+ await writeSlot(view, purged);
578
+ }
579
+ });
580
+ }
581
+ /** Run at the start of every public op (F1: "at the start of every KeyPackage op and at client start/reload" — the latter is simply the first op call after a reload). */
582
+ async function startOp(deps, opts) {
583
+ await resumePendingIntents(deps);
584
+ if (opts.probeParked)
585
+ await probeParkedUnconfirmed(deps);
586
+ await purgeAllExpiredSuperseded(deps);
587
+ }
588
+ // ---------------------------------------------------------------------------
589
+ // generateKeyPackage plumbing
590
+ // ---------------------------------------------------------------------------
591
+ async function mintKeyPackage(deps, pubkey, lastResort) {
592
+ const impl = await getCiphersuiteImpl(DEFAULT_CIPHERSUITE_NAME, defaultCryptoProvider);
593
+ const credential = createCredential(pubkey);
594
+ // S8: every leaf this client mints carries its one device signing key (device-key.ts).
595
+ const deviceKey = await ensureDeviceSigningKey((fn) => deps.transaction(fn), impl, deps.clock.now());
596
+ const kp = await generateKeyPackage({
597
+ credential,
598
+ ciphersuiteImpl: withDeviceSignatureKey(impl, deviceKey),
599
+ isLastResort: lastResort,
600
+ // Every KeyPackage this client mints carries the ADR-012 account-identity
601
+ // proof (required before it can ever be added to a group), same as
602
+ // `group-runtime.ts`'s own internal KeyPackage generation. A device key
603
+ // that carries its stored proof (after a rotation prepare) reuses it: no
604
+ // kind-450 signer call per KeyPackage (Design Decision 3).
605
+ accountProofSigner: deviceProofSigner(deviceKey, deps.signEvent),
606
+ });
607
+ return { kp, leafKey: deviceKey.leafKey };
608
+ }
609
+ /** How often create()/rotate() re-mint when a device-key rotation prepare landed between the mint and the install. */
610
+ const MAX_MINT_ATTEMPTS = 2;
611
+ /**
612
+ * Gate-remediation C1: `createKeyPackageEvent` (marmot-engine) stamps
613
+ * `created_at` from the wall clock (`unixNow()`) with no override option —
614
+ * so a rotate within the same wall-clock second as the slot's previous
615
+ * publication would otherwise get the SAME `created_at`. Under NIP-01,
616
+ * addressable replacement then keeps the LOWER event id, which has no
617
+ * relationship to which KeyPackage was actually minted last — the rotation
618
+ * can lose on the relay while local state believes it won, and after the
619
+ * grace window a Welcome built against the still-advertised OLD package
620
+ * can no longer be decrypted. `minCreatedAt`, when given, is enforced by
621
+ * overriding the template's `created_at` BEFORE signing (never after — that
622
+ * would invalidate the signature).
623
+ */
624
+ async function buildSignedEvent(deps, kp, dSlot, relays, minCreatedAt) {
625
+ const template = await createKeyPackageEvent({ keyPackage: kp.publicPackage, identifier: dSlot, relays: [...relays] });
626
+ const created_at = minCreatedAt === undefined ? template.created_at : Math.max(template.created_at, minCreatedAt);
627
+ return deps.signEvent({ ...template, created_at });
628
+ }
629
+ /**
630
+ * The newest `created_at` (unix seconds) of any event this slot has
631
+ * published, is attempting, or may have published — C1's `lastPublished`
632
+ * over `published`, `pending` and `unconfirmed` (AC-KPL-2: an unconfirmed
633
+ * event may be live at the address, so a rotate must order after it too).
634
+ */
635
+ function lastPublishedCreatedAt(record) {
636
+ let latest = 0;
637
+ for (const entry of record.published)
638
+ latest = Math.max(latest, entry.event.created_at);
639
+ for (const entry of record.unconfirmed)
640
+ latest = Math.max(latest, entry.event.created_at);
641
+ if (record.pending !== undefined)
642
+ latest = Math.max(latest, record.pending.event.created_at);
643
+ return latest;
644
+ }
645
+ // ---------------------------------------------------------------------------
646
+ // ref matching (F5): rotate()/forget() accept EITHER a kind-30443 event id
647
+ // or a hex KeyPackageRef hash, uniformly.
648
+ // ---------------------------------------------------------------------------
649
+ function entryMatchesRef(entry, ref) {
650
+ return entry.event.id === ref || entry.keyPackageRef === ref;
651
+ }
652
+ /** Finds the slot (if any) some published entry of which matches `ref`, and whether that entry is the slot's CURRENT one. Used by `rotate()`, which only ever targets a CONFIRMED (published) entry. */
653
+ function findByRef(records, ref) {
654
+ for (const record of records) {
655
+ const current = record.published[record.published.length - 1];
656
+ if (current !== undefined && entryMatchesRef(current, ref))
657
+ return { record, isCurrent: true };
658
+ if (record.published.some((e) => entryMatchesRef(e, ref)))
659
+ return { record, isCurrent: false };
660
+ }
661
+ return undefined;
662
+ }
663
+ /**
664
+ * Whether `ref` names ANY KeyPackage of `record` — a published (confirmed)
665
+ * entry, an `unconfirmed` one (round 6, F1/F2: a candidate this slot's
666
+ * `pending` no longer names, because it was either abandoned-but-possibly-
667
+ * live or absorbed by an in-flight `forget()`, but which must stay
668
+ * independently addressable), OR a still-pending create/rotate's own event
669
+ * (R2(3): `forget()` must be able to target a slot that has never confirmed
670
+ * anything, e.g. one stuck on a terminally- or retryably-refusing relay). A
671
+ * pending `delete` is not matched here — it names no NEW KeyPackage of its
672
+ * own (its OWN targets are already covered by `published`/`unconfirmed`).
673
+ */
674
+ function slotMatchesRef(record, ref) {
675
+ if (record.published.some((e) => entryMatchesRef(e, ref)))
676
+ return true;
677
+ if (record.unconfirmed.some((e) => entryMatchesRef(e, ref)))
678
+ return true;
679
+ const { pending } = record;
680
+ return pending !== undefined && pending.kind !== 'delete' && (pending.event.id === ref || pending.keyPackageRef === ref);
681
+ }
682
+ /**
683
+ * S9 (`group.destroy()`): where `ref`'s KeyPackage stands locally — `absent`
684
+ * (no slot holds it: never minted here, already deleted, or superseded by a
685
+ * rotation), `deleting` (a `forget()`'s kind-5 is durably pending on its
686
+ * slot), or `present`.
687
+ */
688
+ export async function keyPackageStatus(deps, ref) {
689
+ const record = await deps.transaction(async (tx) => (await listSlots(tx.artifact(ARTIFACT))).find((r) => slotMatchesRef(r, ref)));
690
+ if (record === undefined)
691
+ return 'absent';
692
+ return record.pending?.kind === 'delete' ? 'deleting' : 'present';
693
+ }
694
+ function noRelays(op) {
695
+ return invalid(`${op}: resolved relay set is empty`, { reason: 'no-relays' });
696
+ }
697
+ /** Throws the right error for a non-`confirmed` {@link SettleOutcome} (R1: `stale` is a clear, distinguishable "you lost the race", never a generic publish failure). */
698
+ function throwUnlessConfirmed(outcome, op, dSlot, ref) {
699
+ if (outcome === 'confirmed')
700
+ return;
701
+ if (outcome === 'stale') {
702
+ throw invalid(`${op}: slot ${dSlot} changed concurrently before this operation could be confirmed; retry`, { reason: 'pending-intent', ...(ref === undefined ? {} : { ref }) });
703
+ }
704
+ throw new MarmotError('publish-failed', `keyPackages: ${op}: no relay accepted the publish; the operation is durably pending and will be retried on the next keyPackages operation`, {
705
+ details: { dSlot },
706
+ });
707
+ }
708
+ // ---------------------------------------------------------------------------
709
+ // Public operations
710
+ // ---------------------------------------------------------------------------
711
+ export async function createKeyPackage(deps, options) {
712
+ if (options !== undefined && (typeof options !== 'object' || options === null))
713
+ throw invalid('create: options must be an object');
714
+ const relaysOpt = options?.relays;
715
+ if (relaysOpt !== undefined && (!Array.isArray(relaysOpt) || !relaysOpt.every((r) => typeof r === 'string'))) {
716
+ throw invalid('create: options.relays must be an array of relay URLs');
717
+ }
718
+ const lastResortOpt = options?.lastResort;
719
+ if (lastResortOpt !== undefined && typeof lastResortOpt !== 'boolean')
720
+ throw invalid('create: options.lastResort must be a boolean');
721
+ const lastResort = lastResortOpt ?? false;
722
+ await startOp(deps, { probeParked: true });
723
+ const pubkey = await deps.getPublicKey();
724
+ const relays = await resolveWriteRelays(deps, pubkey, relaysOpt);
725
+ if (relays.length === 0)
726
+ throw noRelays('create'); // R2(1): before minting anything
727
+ const dSlot = generateSlotId();
728
+ let pending;
729
+ for (let attempt = 0; attempt < MAX_MINT_ATTEMPTS && pending === undefined; attempt++) {
730
+ const minted = await mintKeyPackage(deps, pubkey, lastResort);
731
+ const kp = minted.kp;
732
+ const keyPackageRef = await computeKeyPackageRefHex(kp.publicPackage);
733
+ const event = await buildSignedEvent(deps, kp, dSlot, relays);
734
+ const candidate = { kind: 'create', event, privatePackage: kp.privatePackage, keyPackageRef, targetRelays: relays };
735
+ const installed = await deps.transaction(async (tx) => {
736
+ // A rotation prepare may have landed since the mint: never install a KeyPackage on a retired key.
737
+ if ((await readDeviceSigningKeyIn(tx))?.leafKey !== minted.leafKey)
738
+ return false;
739
+ const view = tx.artifact(ARTIFACT);
740
+ // R1: `dSlot` is fresh random (2^256 space) — this can only ever fire if
741
+ // something else already wrote under the exact same id, but the guard is
742
+ // added for the same defence-in-depth reason as rotate/forget's.
743
+ const fresh = await readSlot(view, dSlot);
744
+ if (fresh?.pending !== undefined)
745
+ throw invalid(`create: slot ${dSlot} already has a pending KeyPackage operation in flight`, { reason: 'pending-intent' });
746
+ const record = { dSlot, lastResort, relays, published: [], superseded: [], unconfirmed: [], pending: candidate };
747
+ await writeSlot(view, record);
748
+ return true;
749
+ });
750
+ if (installed)
751
+ pending = candidate;
752
+ }
753
+ if (pending === undefined)
754
+ throw invalid('create: the device key changed concurrently too many times; retry', { reason: 'pending-intent' });
755
+ const event = pending.event;
756
+ const outcome = await attemptPublishAndCommit(deps, dSlot, pending);
757
+ throwUnlessConfirmed(outcome, 'create', dSlot);
758
+ return event;
759
+ }
760
+ export async function rotateKeyPackage(deps, ref) {
761
+ if (typeof ref !== 'string' || ref.length === 0)
762
+ throw invalid('rotate: ref must be a non-empty string');
763
+ await startOp(deps, { probeParked: true });
764
+ const found = await deps.transaction(async (tx) => findByRef(await listSlots(tx.artifact(ARTIFACT)), ref));
765
+ if (found === undefined)
766
+ throw invalid(`rotate: no KeyPackage matches ref ${JSON.stringify(ref)}`, { reason: 'not-found', ref });
767
+ if (!found.isCurrent)
768
+ throw invalid(`rotate: ref ${JSON.stringify(ref)} is an already-superseded KeyPackage; only the current one can be rotated`, { reason: 'already-superseded', ref });
769
+ const { record } = found;
770
+ if (record.pending !== undefined)
771
+ throw invalid(`rotate: slot ${record.dSlot} has a pending KeyPackage operation in flight; retry once it resolves`, { reason: 'pending-intent', ref });
772
+ if (record.currentPrivate === undefined || record.currentRef === undefined) {
773
+ throw new MarmotError('store-failed', `keyPackages: rotate: slot ${record.dSlot} has no current private KeyPackage to supersede`, { details: { dSlot: record.dSlot } });
774
+ }
775
+ const pubkey = await deps.getPublicKey();
776
+ const relays = await resolveWriteRelays(deps, pubkey); // F12: re-resolved on every rotate, not reused from the record.
777
+ if (relays.length === 0)
778
+ throw noRelays('rotate'); // R2(1): before minting anything
779
+ let minted = await mintKeyPackage(deps, pubkey, record.lastResort);
780
+ let kp = minted.kp;
781
+ let keyPackageRef = await computeKeyPackageRefHex(kp.publicPackage);
782
+ let mintAttempts = 1;
783
+ // C1 / AC-KPL-2: strictly newer than anything this slot has published,
784
+ // attempted or parked, and never earlier than the client's own clock (unix
785
+ // seconds). The floor is taken from a snapshot before the (possibly slow)
786
+ // sign; if the slot's floor moved past the signed event by the install
787
+ // transaction (a concurrent rotate installed, published and was parked
788
+ // meanwhile), the same never-published KeyPackage is re-signed against
789
+ // the fresh floor, at most MAX_ROTATE_SIGN_ATTEMPTS times.
790
+ let floorRecord = record;
791
+ let pending;
792
+ for (let attempt = 0; attempt < MAX_ROTATE_SIGN_ATTEMPTS && pending === undefined; attempt++) {
793
+ let staleKey = false;
794
+ const minCreatedAt = Math.max(Math.floor(deps.clock.now() / 1000), lastPublishedCreatedAt(floorRecord) + 1);
795
+ const event = await buildSignedEvent(deps, kp, record.dSlot, relays, minCreatedAt);
796
+ const candidate = { kind: 'rotate', event, privatePackage: kp.privatePackage, keyPackageRef, targetRelays: relays };
797
+ const floorMoved = await deps.transaction(async (tx) => {
798
+ // A rotation prepare may have landed since the mint: never install a KeyPackage on a retired key.
799
+ if ((await readDeviceSigningKeyIn(tx))?.leafKey !== minted.leafKey) {
800
+ staleKey = true;
801
+ return undefined;
802
+ }
803
+ const view = tx.artifact(ARTIFACT);
804
+ // R1: re-read and re-verify INSIDE the transaction — the mint/sign work
805
+ // above took real (unserialised) time, during which another op could
806
+ // have raced ahead and already started (or finished) its own intent on
807
+ // this exact slot.
808
+ const fresh = await readSlot(view, record.dSlot);
809
+ // R1: a concurrent forget() may have already deleted the whole slot —
810
+ // from rotate()'s perspective this is the same "lost the race, retry"
811
+ // situation as an in-flight pending intent, so it gets the SAME
812
+ // `pending-intent` reason, not a generic store-failed.
813
+ if (fresh === undefined)
814
+ throw invalid(`rotate: slot ${record.dSlot} was concurrently forgotten`, { reason: 'pending-intent', ref });
815
+ if (fresh.pending !== undefined)
816
+ throw invalid(`rotate: slot ${record.dSlot} has a pending KeyPackage operation in flight; retry once it resolves`, { reason: 'pending-intent', ref });
817
+ const current = fresh.published[fresh.published.length - 1];
818
+ if (current === undefined || !entryMatchesRef(current, ref)) {
819
+ throw invalid(`rotate: ref ${JSON.stringify(ref)} is no longer the current KeyPackage of its slot`, { reason: 'already-superseded', ref });
820
+ }
821
+ if (event.created_at <= lastPublishedCreatedAt(fresh))
822
+ return fresh;
823
+ await writeSlot(view, { ...fresh, relays: unionRelays(fresh.relays, relays), pending: candidate });
824
+ return undefined;
825
+ });
826
+ if (staleKey) {
827
+ if (mintAttempts >= MAX_MINT_ATTEMPTS)
828
+ break;
829
+ mintAttempts += 1;
830
+ minted = await mintKeyPackage(deps, pubkey, record.lastResort);
831
+ kp = minted.kp;
832
+ keyPackageRef = await computeKeyPackageRefHex(kp.publicPackage);
833
+ attempt -= 1; // the re-mint does not spend a floor-retry
834
+ }
835
+ else if (floorMoved === undefined)
836
+ pending = candidate;
837
+ else
838
+ floorRecord = floorMoved;
839
+ }
840
+ if (pending === undefined) {
841
+ throw invalid(`rotate: slot ${record.dSlot} changed concurrently too many times; retry`, { reason: 'pending-intent', ref });
842
+ }
843
+ const { event } = pending;
844
+ const outcome = await attemptPublishAndCommit(deps, record.dSlot, pending);
845
+ throwUnlessConfirmed(outcome, 'rotate', record.dSlot, ref);
846
+ return event;
847
+ }
848
+ /**
849
+ * Reads the slot fresh and classifies it for `forget()`'s absorb step:
850
+ * - `undefined` — the slot is gone; nothing to forget.
851
+ * - `'already-deleting'` — a delete is already pending (N1: every pending
852
+ * delete is a full-slot `forget()` now — round 3's P1 removed the only
853
+ * code path that ever built a partial one, and gate-remediation N1
854
+ * removed the `dropSlotOnSuccess` flag that used to distinguish them,
855
+ * so this branch no longer needs to check it) — idempotent (P4),
856
+ * `forget()` does nothing further.
857
+ * - `ForgetTargets` — every event this forget should cover right now:
858
+ * every published entry, every `unconfirmed` one (round 6, F1/F2 — a
859
+ * candidate that might be live but is no longer named by `pending`),
860
+ * PLUS a still-pending create/rotate's own event.
861
+ */
862
+ function classifyForgetTargets(fresh) {
863
+ if (fresh === undefined)
864
+ return undefined;
865
+ if (fresh.pending?.kind === 'delete')
866
+ return 'already-deleting';
867
+ const events = [
868
+ ...fresh.published.map((e) => e.event),
869
+ ...fresh.unconfirmed.map((e) => e.event),
870
+ ...(fresh.pending !== undefined ? [fresh.pending.event] : []),
871
+ ];
872
+ // F12: reach every relay ever used for this slot, PLUS the pending
873
+ // intent's own target (in case it differs, e.g. a rotate mid-flight
874
+ // that re-resolved to a relay not yet folded into `relays`).
875
+ const relays = unionRelays(fresh.relays, fresh.pending?.targetRelays ?? []);
876
+ return { events, ids: events.map((e) => e.id), relays };
877
+ }
878
+ function sameIds(a, b) {
879
+ return a.length === b.length && a.every((id, i) => id === b[i]);
880
+ }
881
+ const MAX_FORGET_SNAPSHOT_ATTEMPTS = 3;
882
+ /** How often rotate() re-signs its candidate when the slot's created_at floor moved before install (AC-KPL-2). */
883
+ const MAX_ROTATE_SIGN_ATTEMPTS = 3;
884
+ export async function forgetKeyPackage(deps, ref) {
885
+ if (typeof ref !== 'string' || ref.length === 0)
886
+ throw invalid('forget: ref must be a non-empty string');
887
+ await startOp(deps, { probeParked: false });
888
+ const record = await deps.transaction(async (tx) => (await listSlots(tx.artifact(ARTIFACT))).find((r) => slotMatchesRef(r, ref)));
889
+ if (record === undefined)
890
+ throw invalid(`forget: no KeyPackage matches ref ${JSON.stringify(ref)}`, { reason: 'not-found', ref });
891
+ // Gate-remediation round 3 (P2, F7 regression fix): the OPTIMISTIC
892
+ // pattern every other write in this module already uses — sign OUTSIDE
893
+ // any transaction, never inside one — rather than round 2's `deps
894
+ // .signEvent` call from inside the absorb transaction's `fn`. Signing
895
+ // inside a store transaction is technically permitted by storage/index.ts's
896
+ // own contract, but it broke the invariant every other call site in this
897
+ // module relies on (a consumer signer is never invoked while an
898
+ // account-scope store frame is on the stack) — tested directly in
899
+ // lifecycle.test.ts via a counting store wrapper's `inTx` flag.
900
+ //
901
+ // 1. Snapshot the target id set in a (read-only) transaction.
902
+ // 2. Build and sign the kind-5 OUTSIDE any transaction.
903
+ // 3. In the absorb transaction, re-read and compare the fresh target set
904
+ // to the snapshot: equal -> install the pending delete; changed ->
905
+ // retry the snapshot/sign cycle (bounded); still unresolved -> reject
906
+ // `pending-intent` rather than install a delete that might miss an
907
+ // event a concurrent create/rotate just added.
908
+ let installed;
909
+ for (let attempt = 0; attempt < MAX_FORGET_SNAPSHOT_ATTEMPTS && installed === undefined; attempt++) {
910
+ const resolved = await deps.transaction(async (tx) => classifyForgetTargets(await readSlot(tx.artifact(ARTIFACT), record.dSlot)));
911
+ if (resolved === undefined)
912
+ return; // the slot vanished before we could act; nothing to forget
913
+ if (resolved === 'already-deleting')
914
+ return; // P4: idempotent — a delete for this whole slot is already in flight
915
+ const deleteTemplate = createDeleteKeyPackageEvent({ events: [...resolved.events] });
916
+ const deleteEvent = await deps.signEvent(deleteTemplate); // OUTSIDE any transaction
917
+ const candidate = { kind: 'delete', event: deleteEvent, targetRelays: resolved.relays };
918
+ installed = await deps.transaction(async (tx) => {
919
+ const view = tx.artifact(ARTIFACT);
920
+ const fresh = await readSlot(view, record.dSlot);
921
+ const freshTargets = classifyForgetTargets(fresh);
922
+ if (freshTargets === undefined || freshTargets === 'already-deleting' || !sameIds(freshTargets.ids, resolved.ids))
923
+ return undefined;
924
+ // Gate-remediation round 6 (F2): `pending` is about to be OVERWRITTEN
925
+ // with this delete intent — if it currently names a still-pending
926
+ // create/rotate candidate (never published), that candidate's
927
+ // event/ref is already part of THIS delete's own target set (folded
928
+ // in by classifyForgetTargets above) and must stay independently
929
+ // addressable for as long as the delete itself remains unresolved:
930
+ // a second forget() over the SAME ref must still find this slot
931
+ // (slotMatchesRef now also checks `unconfirmed`) and land on the
932
+ // idempotent 'already-deleting' path, and a terminally-rejected
933
+ // delete (abandonPendingIntent) must be able to hand the same target
934
+ // back to a later forget() retry rather than losing it. Handled
935
+ // uniformly for create AND rotate — `classifyForgetTargets` already
936
+ // treats either kind's pending event as a target the same way, so
937
+ // absorbing either into `unconfirmed` the same way keeps this one
938
+ // code path, rather than a kind-specific special case.
939
+ const absorbed = fresh.pending;
940
+ const unconfirmed = absorbed === undefined ? [...fresh.unconfirmed] : [...fresh.unconfirmed, { event: absorbed.event, keyPackageRef: absorbed.keyPackageRef, privatePackage: absorbed.privatePackage }];
941
+ await writeSlot(view, { ...fresh, unconfirmed, pending: candidate });
942
+ return candidate;
943
+ });
944
+ }
945
+ if (installed === undefined) {
946
+ throw invalid(`forget: slot ${record.dSlot} changed concurrently too many times; retry`, { reason: 'pending-intent', ref });
947
+ }
948
+ const outcome = await attemptPublishAndCommit(deps, record.dSlot, installed);
949
+ throwUnlessConfirmed(outcome, 'forget', record.dSlot, ref);
950
+ }
951
+ /**
952
+ * Gate-remediation D2: a slot is listable/countable whenever it has a
953
+ * CONFIRMED current KeyPackage — a still-in-flight `pending` ROTATE does
954
+ * NOT hide it (the OLD current is still published and its key is still
955
+ * retained; only the candidate replacing it is pending). Hidden only when:
956
+ * - nothing has ever confirmed (`published` is empty — a pure pending
957
+ * `create`, never published, has nothing to show yet), or
958
+ * - the pending intent is a `delete` (a `forget()` in flight): the user
959
+ * asked for removal, so it is treated as already gone from the
960
+ * caller's point of view, even though the local record and its key
961
+ * technically still exist until the delete confirms (decided by the
962
+ * lead; documented here rather than inferred).
963
+ */
964
+ function isListable(record) {
965
+ if (record.published.length === 0)
966
+ return false;
967
+ if (record.pending?.kind === 'delete')
968
+ return false;
969
+ return true;
970
+ }
971
+ /**
972
+ * S8 (`devices.forget`): every valid kind-30443 event `pubkey` has on its
973
+ * write relays (resolved like `create` resolves them) — each one passed
974
+ * {@link validateKeyPackageEvent} and the consumer verifier. `timedOut`:
975
+ * the answer may be incomplete. `relays` is where it was asked (a deletion
976
+ * goes there too).
977
+ */
978
+ export async function fetchKeyPackageEvents(deps, pubkey) {
979
+ const relays = [...new Set([...(await resolveWriteRelays(deps, pubkey)), ...deps.relays.defaults])];
980
+ if (relays.length === 0)
981
+ return { events: [], relays, timedOut: false };
982
+ const result = await deps.requestWithDeadline(relays, { kinds: [ADDRESSABLE_KEY_PACKAGE_KIND], authors: [pubkey] }, { timeoutMs: deps.historyTimeoutMs });
983
+ const events = [];
984
+ const seen = new Set();
985
+ for (const event of result.events) {
986
+ if (seen.has(event.id) || event.pubkey !== pubkey || validateKeyPackageEvent(event) === undefined)
987
+ continue;
988
+ if (deps.verifier !== undefined) {
989
+ let ok;
990
+ try {
991
+ ok = await deps.verifier(event);
992
+ }
993
+ catch {
994
+ ok = false;
995
+ }
996
+ if (!ok)
997
+ continue;
998
+ }
999
+ seen.add(event.id);
1000
+ events.push(event);
1001
+ }
1002
+ return { events, relays, timedOut: result.timedOut };
1003
+ }
1004
+ export async function listKeyPackages(deps) {
1005
+ await startOp(deps, { probeParked: false });
1006
+ const records = await deps.transaction((tx) => listSlots(tx.artifact(ARTIFACT)));
1007
+ const current = records.filter(isListable).map((r) => r.published[r.published.length - 1].event);
1008
+ return current.sort((a, b) => a.created_at - b.created_at || (a.id < b.id ? -1 : a.id > b.id ? 1 : 0));
1009
+ }
1010
+ export async function countKeyPackages(deps) {
1011
+ await startOp(deps, { probeParked: false });
1012
+ const records = await deps.transaction((tx) => listSlots(tx.artifact(ARTIFACT)));
1013
+ return records.filter(isListable).length;
1014
+ }
1015
+ function leafKeyHexOfEvent(event) {
1016
+ try {
1017
+ return Array.from(getKeyPackage(event).leafNode.signaturePublicKey, (b) => b.toString(16).padStart(2, '0')).join('');
1018
+ }
1019
+ catch {
1020
+ return undefined; // not a decodable KeyPackage event: not ours to retire
1021
+ }
1022
+ }
1023
+ /** The reason a failed `rotate()` is a retryable block rather than a failure of the retirement, or `undefined` for any other error. */
1024
+ function retirementBlockReason(error) {
1025
+ if (!isMarmotError(error))
1026
+ return undefined;
1027
+ if (error.code === 'publish-failed')
1028
+ return 'publish-failed';
1029
+ if (error.code !== 'invalid-options')
1030
+ return undefined;
1031
+ const reason = error.details?.['reason'];
1032
+ if (reason === 'no-relays')
1033
+ return 'no-relays';
1034
+ if (reason === 'pending-intent' || reason === 'already-superseded')
1035
+ return 'pending-intent';
1036
+ return undefined;
1037
+ }
1038
+ /**
1039
+ * Replaces every KeyPackage whose leaf signature key is in `keys` (Design
1040
+ * Decision 10, AC-KP-1..5) — the last-resort slot included — by one carrying
1041
+ * the device key and its stored proof, and then kind-5 deletes the retired-key
1042
+ * events.
1043
+ *
1044
+ * Per slot, in order: (1) a slot whose current KeyPackage, or any possibly-live
1045
+ * `unconfirmed` one that can still be live at the address (not replaced by the
1046
+ * current event, not deleted) carries a retired key is `rotate()`d — the replacement is
1047
+ * minted with the device key (`ensureDeviceSigningKey` = `self`) and published
1048
+ * under the same `d` address, so the relay's addressable replacement swaps it in
1049
+ * and there is never a moment with no advertised KeyPackage; (2) only once the
1050
+ * replacement is accepted, a kind-5 over the retired events' IDS (`e` tags
1051
+ * only — an address-scoped deletion would take the replacement with it) is
1052
+ * signed once and sent only to relays known to hold the replacement (the current
1053
+ * event is re-published first; the accepting relays count) plus the slot relays
1054
+ * that left the write set, and recorded per relay in the slot's `deletions`; a
1055
+ * relay still missing is retried by the next run. A deleted `unconfirmed`
1056
+ * candidate moves to `superseded`. The superseded
1057
+ * private material stays resolvable for the usual grace window
1058
+ * (`findPrivateKeyPackage`), so a Welcome built against the old KeyPackage still
1059
+ * joins. Signer cost per slot: the replacement event and the deletion — at most
1060
+ * two, whatever the number of held groups.
1061
+ *
1062
+ * Idempotent and resumable: every step rests on the slot's durable record, so a
1063
+ * run that stopped at any await boundary, run again, ends where an uninterrupted
1064
+ * one would — a slot already on the device key is skipped, a deletion already
1065
+ * recorded is not repeated. A slot it cannot finish (a stuck pending intent, no
1066
+ * relay accepting) is reported in `blocked`, never thrown; any other error
1067
+ * propagates.
1068
+ *
1069
+ * `keys` are 64-hex leaf keys. Rejects `invalid-options` when there is no device
1070
+ * key yet (`reason: 'no-device-key'`) or when `keys` names the device key itself
1071
+ * (`reason: 'retire-current-key'`).
1072
+ */
1073
+ export async function retireKeyPackagesSignedWith(deps, keys) {
1074
+ if (!Array.isArray(keys) || !keys.every((k) => typeof k === 'string' && isLeafKeyHex(k)))
1075
+ throw invalid('retire: keys must be 64-hex leaf keys');
1076
+ const retired = new Set(keys);
1077
+ const none = { replaced: [], deleted: [], blocked: [] };
1078
+ if (retired.size === 0)
1079
+ return none;
1080
+ await startOp(deps, { probeParked: true });
1081
+ const device = await readDeviceSigningKey((fn) => deps.transaction(fn));
1082
+ if (device === undefined)
1083
+ throw invalid('retire: there is no device key to replace the retired ones with', { reason: 'no-device-key' });
1084
+ if (retired.has(device.leafKey))
1085
+ throw invalid('retire: the device key itself cannot be retired', { reason: 'retire-current-key' });
1086
+ const isRetired = (event) => {
1087
+ const key = leafKeyHexOfEvent(event);
1088
+ return key !== undefined && retired.has(key);
1089
+ };
1090
+ const read = (dSlot) => deps.transaction((tx) => readSlot(tx.artifact(ARTIFACT), dSlot));
1091
+ const dSlots = (await deps.transaction(async (tx) => (await listSlots(tx.artifact(ARTIFACT))).map((r) => r.dSlot))).sort();
1092
+ const replaced = [];
1093
+ const deleted = [];
1094
+ const blocked = [];
1095
+ for (const dSlot of dSlots) {
1096
+ let record = await read(dSlot);
1097
+ if (record === undefined || record.pending?.kind === 'delete')
1098
+ continue; // gone, or being forgotten
1099
+ const current = record.published[record.published.length - 1];
1100
+ // An unconfirmed candidate matters only while it can still be the live event at the address: not replaced by
1101
+ // the slot's current one, not already deleted (a retired one parked there must not re-rotate the slot forever).
1102
+ const stillLive = (u) => isRetired(u.event) && (current === undefined || !replaces(current.event, u.event)) && !(record.deletions ?? []).some((d) => d.id === u.event.id);
1103
+ const needsReplacement = (current !== undefined && isRetired(current.event)) || record.unconfirmed.some(stillLive);
1104
+ if (record.pending !== undefined && isRetired(record.pending.event)) {
1105
+ blocked.push({ dSlot, reason: 'pending-intent' }); // startOp could not settle it: a retired-key mint still waits for a relay
1106
+ continue;
1107
+ }
1108
+ if (needsReplacement) {
1109
+ if (current === undefined || record.currentRef === undefined || record.currentPrivate === undefined) {
1110
+ blocked.push({ dSlot, reason: 'no-current' });
1111
+ continue;
1112
+ }
1113
+ try {
1114
+ await rotateKeyPackage(deps, record.currentRef);
1115
+ }
1116
+ catch (error) {
1117
+ if (isMarmotError(error, 'invalid-options') && error.details?.['reason'] === 'not-found')
1118
+ continue; // forgotten mid-run
1119
+ const reason = retirementBlockReason(error);
1120
+ if (reason === undefined)
1121
+ throw error;
1122
+ blocked.push({ dSlot, reason });
1123
+ continue;
1124
+ }
1125
+ replaced.push(dSlot);
1126
+ record = await read(dSlot);
1127
+ if (record === undefined || record.pending?.kind === 'delete')
1128
+ continue;
1129
+ }
1130
+ const step = await deleteRetiredEvents(deps, record, isRetired);
1131
+ if (step.recorded)
1132
+ deleted.push(dSlot);
1133
+ for (const reason of step.blocked)
1134
+ blocked.push({ dSlot, reason });
1135
+ }
1136
+ return { replaced, deleted, blocked };
1137
+ }
1138
+ /** Publishes `event` to `relays`; the relays that accepted it (a thrown error counts as none). */
1139
+ async function acceptingRelays(deps, relays, event) {
1140
+ if (relays.length === 0)
1141
+ return [];
1142
+ try {
1143
+ return [...classifyPublish(relays, await deps.publish(relays, event)).accepted];
1144
+ }
1145
+ catch {
1146
+ return [];
1147
+ }
1148
+ }
1149
+ /**
1150
+ * The deletion step of a retirement for one slot, under one uniform rule: the current (replacement) event is
1151
+ * re-published — idempotent, no signature — to EVERY relay of the slot, and the kind-5 goes only to the relays that
1152
+ * accepted it. A relay that refuses even that (dead, or refusing the new key) is reported `relay-unreachable` and is
1153
+ * never sent the deletion, so the only KeyPackage it holds is not deleted. The signed kind-5 is stored on the slot
1154
+ * before it is published and re-published to the relays still missing; a new one is signed only when an id outside the
1155
+ * stored set has to be deleted. Accepted relays are recorded per event; an event deleted on every holding relay leaves
1156
+ * `unconfirmed` for `published`/`superseded` (see {@link settleDeleted}).
1157
+ */
1158
+ async function deleteRetiredEvents(deps, record, isRetired) {
1159
+ const entryOf = (id) => (record.deletions ?? []).find((d) => d.id === id);
1160
+ const targets = [...record.published.map((e) => e.event), ...record.unconfirmed.map((u) => u.event)].filter(isRetired);
1161
+ if (targets.length === 0)
1162
+ return { recorded: false, blocked: [] };
1163
+ if (record.relays.length === 0)
1164
+ return { recorded: false, blocked: ['no-relays'] };
1165
+ if (targets.every((e) => record.relays.every((r) => entryOf(e.id)?.relays.includes(r) === true))) {
1166
+ // Everything deleted on every relay of the slot: only the bookkeeping move can be left over.
1167
+ await settleDeleted(deps, record.dSlot, record.relays);
1168
+ return { recorded: false, blocked: [] };
1169
+ }
1170
+ const current = record.published[record.published.length - 1];
1171
+ const holding = current === undefined ? [] : await acceptingRelays(deps, record.relays, current.event);
1172
+ const unreachable = record.relays.filter((r) => !holding.includes(r));
1173
+ const missing = (e) => holding.filter((r) => !(entryOf(e.id)?.relays ?? []).includes(r));
1174
+ const todo = targets.filter((e) => missing(e).length > 0);
1175
+ let recorded = false;
1176
+ if (todo.length > 0) {
1177
+ const stored = record.deletionEvent;
1178
+ let deleteEvent;
1179
+ if (stored !== undefined && todo.every((e) => stored.ids.includes(e.id))) {
1180
+ deleteEvent = stored.event;
1181
+ }
1182
+ else {
1183
+ const ids = todo.map((e) => e.id);
1184
+ deleteEvent = await deps.signEvent(createDeleteKeyPackageEvent({ events: ids })); // string ids: `e` tags only; OUTSIDE any transaction
1185
+ await deps.transaction(async (tx) => {
1186
+ const view = tx.artifact(ARTIFACT);
1187
+ const fresh = await readSlot(view, record.dSlot);
1188
+ if (fresh !== undefined)
1189
+ await writeSlot(view, { ...fresh, deletionEvent: { event: deleteEvent, ids } });
1190
+ });
1191
+ }
1192
+ const accepted = await acceptingRelays(deps, [...new Set(todo.flatMap(missing))], deleteEvent);
1193
+ if (accepted.length > 0) {
1194
+ await deps.transaction(async (tx) => {
1195
+ const view = tx.artifact(ARTIFACT);
1196
+ const fresh = await readSlot(view, record.dSlot);
1197
+ if (fresh === undefined)
1198
+ return;
1199
+ const entries = new Map((fresh.deletions ?? []).map((d) => [d.id, d.relays]));
1200
+ for (const e of todo) {
1201
+ const got = accepted.filter((r) => missing(e).includes(r));
1202
+ if (got.length > 0)
1203
+ entries.set(e.id, [...new Set([...(entries.get(e.id) ?? []), ...got])]);
1204
+ }
1205
+ const finished = targets.every((e) => holding.every((r) => (entries.get(e.id) ?? []).includes(r)));
1206
+ const { deletionEvent: _done, ...rest } = fresh;
1207
+ await writeSlot(view, { ...(finished ? rest : fresh), deletions: [...entries].map(([id, relays]) => ({ id, relays })) });
1208
+ });
1209
+ recorded = true;
1210
+ }
1211
+ }
1212
+ if (holding.length > 0)
1213
+ await settleDeleted(deps, record.dSlot, holding);
1214
+ const after = await deps.transaction((tx) => readSlot(tx.artifact(ARTIFACT), record.dSlot));
1215
+ const incomplete = after !== undefined && targets.some((e) => holding.some((r) => !((after.deletions ?? []).find((d) => d.id === e.id)?.relays ?? []).includes(r)));
1216
+ return { recorded, blocked: [...(incomplete ? ['delete-pending'] : []), ...(unreachable.length > 0 ? ['relay-unreachable'] : [])] };
1217
+ }
1218
+ /**
1219
+ * Moves each unconfirmed retired candidate whose deletion covers `relays` out of `unconfirmed`: its event joins
1220
+ * `published` before the current entry (so `findKeyPackageEventByRef` still resolves it and it stays a deletion
1221
+ * target, exactly as `settleParkedAcceptance` does for a superseded generation) and its private half joins
1222
+ * `superseded`, expiring at the earlier of the grace window and the KeyPackage's own `notAfter` plus the window
1223
+ * (a Welcome built against it can still join; the retired private half is bounded, Design Decision 9).
1224
+ */
1225
+ async function settleDeleted(deps, dSlot, relays) {
1226
+ await deps.transaction(async (tx) => {
1227
+ const view = tx.artifact(ARTIFACT);
1228
+ const fresh = await readSlot(view, dSlot);
1229
+ if (fresh === undefined)
1230
+ return;
1231
+ const done = fresh.unconfirmed.filter((u) => (fresh.deletions ?? []).some((d) => d.id === u.event.id && d.relays.length > 0 && relays.every((r) => d.relays.includes(r))));
1232
+ if (done.length === 0)
1233
+ return;
1234
+ const nowMs = deps.clock.now();
1235
+ let published = fresh.published;
1236
+ const superseded = [...fresh.superseded];
1237
+ for (const u of done) {
1238
+ if (published.length > 0 && !published.some((p) => p.event.id === u.event.id))
1239
+ published = insertBeforeCurrent(published, { event: u.event, keyPackageRef: u.keyPackageRef });
1240
+ const lifetime = getKeyPackageLifetime(u.event);
1241
+ const expiresAtMs = Math.min(nowMs + deps.graceWindowMs, lifetime === undefined ? Number.POSITIVE_INFINITY : Number(lifetime.notAfter) * 1000 + deps.graceWindowMs);
1242
+ if (expiresAtMs > nowMs && !(await isKeyUnretained(tx, u.keyPackageRef)))
1243
+ superseded.push({ keyPackageRef: u.keyPackageRef, privatePackage: u.privatePackage, supersededAtMs: nowMs, expiresAtMs });
1244
+ }
1245
+ await writeSlot(view, { ...fresh, published, unconfirmed: fresh.unconfirmed.filter((u) => !done.includes(u)), superseded });
1246
+ });
1247
+ }