@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,24 @@
1
+ import type { NostrEvent } from '@941design/nostr-events/event';
2
+ /**
3
+ * What `selectKeyPackage` returns for the winning candidate: the seam
4
+ * S5/S6/S8 consume. Renamed from `KeyPackageRef` (gate-remediation F5,
5
+ * before any consuming story existed) to avoid colliding with the MLS
6
+ * `KeyPackageRef` HASH it now also carries.
7
+ */
8
+ export interface SelectedKeyPackage {
9
+ readonly eventId: string;
10
+ /** Hex-encoded MIP-00 KeyPackageRef (RFC 9420 `make_key_package_ref`) — what `rotate`/`forget` also accept as `ref` (F5). */
11
+ readonly keyPackageRef: string;
12
+ readonly dSlot: string;
13
+ readonly pubkey: string;
14
+ readonly createdAt: number;
15
+ }
16
+ /**
17
+ * The normative selection rule (AC-KP-4): among `candidates` that pass
18
+ * kind/signature/credential consistency (F2), lifetime, proof and
19
+ * capability validation, prefer a non-last-resort KeyPackage, then the
20
+ * newest `created_at`, then the lower event id (equal-length hex ids
21
+ * compare correctly as strings). Returns exactly one winner, or `undefined`
22
+ * when no candidate is eligible.
23
+ */
24
+ export declare function selectKeyPackage(candidates: readonly NostrEvent[], now: number): Promise<SelectedKeyPackage | undefined>;
@@ -0,0 +1,90 @@
1
+ /**
2
+ * `selectKeyPackage(candidates, now)` — the normative KeyPackage selection
3
+ * rule (AC-KP-4), and the {@link SelectedKeyPackage} seam other stories
4
+ * consume (S4 -> S5, S6, S8; architecture.md top-level `seams`).
5
+ *
6
+ * A pure function over its inputs: no engine state, no wall clock read —
7
+ * `now` is supplied by the caller as unix SECONDS (matching
8
+ * `NostrEvent.created_at` and the MLS `Lifetime` fields it is compared
9
+ * against directly; a caller driven by the client's millisecond
10
+ * `ClientClock` divides by 1000 before calling in). It IS async
11
+ * (gate-remediation F5): computing a candidate's `keyPackageRef` for the
12
+ * returned seam requires `calculateKeyPackageRef`, which hashes
13
+ * asynchronously.
14
+ */
15
+ import { calculateKeyPackageRef, isLastResortKeyPackage, marmotRequiredCapabilitiesExtension, verifyLeafAccountIdentityProof } from '@941design/marmot-engine/core';
16
+ import { validateKeyPackageEvent } from './validate-key-package-event.js';
17
+ const REQUIRED_CAPABILITIES = marmotRequiredCapabilitiesExtension().extensionData;
18
+ function hasBaselineCapabilities(capabilities) {
19
+ for (const type of REQUIRED_CAPABILITIES.extensionTypes ?? [])
20
+ if (!capabilities.extensions.includes(type))
21
+ return false;
22
+ for (const type of REQUIRED_CAPABILITIES.proposalTypes ?? [])
23
+ if (!capabilities.proposals.includes(type))
24
+ return false;
25
+ return true;
26
+ }
27
+ function evaluate(event, nowSeconds) {
28
+ // F2: kind, signature and credential<->pubkey consistency, before anything else.
29
+ const keyPackage = validateKeyPackageEvent(event);
30
+ if (keyPackage === undefined)
31
+ return undefined;
32
+ const { leafNode } = keyPackage;
33
+ // Lifetime — current at `now` (no cap check here: the cap is a producer-side
34
+ // rule already enforced by generateKeyPackage; a consumer only asks "is this
35
+ // usable right now").
36
+ const now = BigInt(nowSeconds);
37
+ if (now < leafNode.lifetime.notBefore || now > leafNode.lifetime.notAfter)
38
+ return undefined;
39
+ // Proof — the ADR-012 leaf account-identity proof must be present and valid.
40
+ try {
41
+ verifyLeafAccountIdentityProof(leafNode, keyPackage.cipherSuite);
42
+ }
43
+ catch {
44
+ return undefined;
45
+ }
46
+ // Capability — the leaf must advertise the group-independent Marmot v2
47
+ // baseline (app_data_dictionary + account-identity-proof extensions,
48
+ // app_data_update + self_remove proposals). A specific group's own
49
+ // `required_capabilities` extension needs group state and is a separate,
50
+ // group-scoped check (`evaluateKeyPackageForGroup`), not this pure function.
51
+ if (!hasBaselineCapabilities(leafNode.capabilities))
52
+ return undefined;
53
+ if (event.tags.find((t) => t[0] === 'd')?.[1] === undefined)
54
+ return undefined;
55
+ return { event, keyPackage, lastResort: isLastResortKeyPackage(keyPackage) };
56
+ }
57
+ /** Whether `a` outranks `b` under the AC-KP-4 precedence order. */
58
+ function better(a, b) {
59
+ if (a.lastResort !== b.lastResort)
60
+ return !a.lastResort;
61
+ if (a.event.created_at !== b.event.created_at)
62
+ return a.event.created_at > b.event.created_at;
63
+ return a.event.id < b.event.id;
64
+ }
65
+ function toHex(bytes) {
66
+ return Array.from(bytes, (b) => b.toString(16).padStart(2, '0')).join('');
67
+ }
68
+ /**
69
+ * The normative selection rule (AC-KP-4): among `candidates` that pass
70
+ * kind/signature/credential consistency (F2), lifetime, proof and
71
+ * capability validation, prefer a non-last-resort KeyPackage, then the
72
+ * newest `created_at`, then the lower event id (equal-length hex ids
73
+ * compare correctly as strings). Returns exactly one winner, or `undefined`
74
+ * when no candidate is eligible.
75
+ */
76
+ export async function selectKeyPackage(candidates, now) {
77
+ let best;
78
+ for (const event of candidates) {
79
+ const candidate = evaluate(event, now);
80
+ if (candidate === undefined)
81
+ continue;
82
+ if (best === undefined || better(candidate, best))
83
+ best = candidate;
84
+ }
85
+ if (best === undefined)
86
+ return undefined;
87
+ const dSlot = best.event.tags.find((t) => t[0] === 'd')[1];
88
+ const keyPackageRef = toHex(await calculateKeyPackageRef(best.keyPackage));
89
+ return { eventId: best.event.id, keyPackageRef, dSlot, pubkey: best.event.pubkey, createdAt: best.event.created_at };
90
+ }
@@ -0,0 +1,167 @@
1
+ import type { KeyPackage } from '@941design/marmot-engine/mls';
2
+ import type { NostrEvent } from '@941design/nostr-events/event';
3
+ import type { KeyValueView, Storable } from '../storage/index.js';
4
+ export interface PublishedEntry {
5
+ readonly event: NostrEvent;
6
+ /** Hex-encoded MIP-00 `KeyPackageRef` (RFC 9420 `make_key_package_ref`) of `event`'s KeyPackage. */
7
+ readonly keyPackageRef: string;
8
+ }
9
+ export interface SupersededEntry {
10
+ readonly keyPackageRef: string;
11
+ readonly privatePackage: Storable;
12
+ /** Client clock (ms) at which this generation was superseded by a rotate(). */
13
+ readonly supersededAtMs: number;
14
+ /** `supersededAtMs + graceWindowMs` at the time this entry was written — purge and lookup both compare against this directly, so neither needs `graceWindowMs` passed back in later (F3/F4). */
15
+ readonly expiresAtMs: number;
16
+ }
17
+ /**
18
+ * A create/rotate candidate that MAY be live on a relay but is neither a
19
+ * confirmed `published` entry nor a `superseded` one (round 6, R6/F1/F2):
20
+ * has no `graceWindowMs`-style expiry of its own — a flat grace window
21
+ * doesn't fit here, since a mayBeLive candidate might be the NEWEST version
22
+ * ever advertised at its address (C1's created_at floor), so it could still
23
+ * outlive whatever it would otherwise have been "superseded by". Instead
24
+ * it's reaped once its OWN KeyPackage leaf lifetime `notAfter` plus
25
+ * `graceWindowMs` passes (AC-KPL-3) — see {@link KeyPackageSlotRecord.unconfirmed} and
26
+ * `reapExpiredUnconfirmed`.
27
+ */
28
+ export interface UnconfirmedEntry {
29
+ readonly event: NostrEvent;
30
+ readonly keyPackageRef: string;
31
+ readonly privatePackage: Storable;
32
+ }
33
+ export type PendingIntentKind = 'create' | 'rotate' | 'delete';
34
+ /**
35
+ * A durable, not-yet-confirmed KeyPackage operation (F1/F7). `event` is
36
+ * already fully signed — resuming it is exactly "publish this same event
37
+ * again" (idempotent: a relay that already has it answers `duplicate:` or
38
+ * `ok: true`), never a re-sign. `targetRelays` is the relay set this
39
+ * specific attempt was built for; resume republishes to exactly this set
40
+ * rather than re-resolving (which could pick a different set on retry).
41
+ */
42
+ export interface PendingIntent {
43
+ readonly kind: PendingIntentKind;
44
+ /** The signed event to (re)publish: kind-30443 for create/rotate, kind-5 for delete. */
45
+ readonly event: NostrEvent;
46
+ /** The new private KeyPackage to adopt once `event` is accepted. Absent for `delete`. */
47
+ readonly privatePackage?: Storable;
48
+ /** The new KeyPackageRef hash of `event`. Absent for `delete`. */
49
+ readonly keyPackageRef?: string;
50
+ readonly targetRelays: readonly string[];
51
+ /**
52
+ * Client clock (ms) of the last publish ATTEMPT (accepted or not) — R2(4):
53
+ * `resumePendingIntents` skips a republish while `now - lastAttemptMs` is
54
+ * within the backoff window, so a stuck slot doesn't pay a relay
55
+ * round-trip on every `list()`/`count()` call. Absent = never attempted
56
+ * (resume always tries immediately).
57
+ */
58
+ readonly lastAttemptMs?: number;
59
+ /**
60
+ * R6 invariant (round 6): true once there is evidence this intent MAY
61
+ * already be live on some relay — durably set BEFORE any network I/O for
62
+ * an attempt that is not provably this intent's first ever (see
63
+ * `markAttemptStarting`), and immediately on any attempt whose own
64
+ * outcome classifies retryable or is unknown (a thrown/caught publish
65
+ * error). Monotonic: once true, never flips back to false. Absent (or
66
+ * `false`) means this intent has never had an attempt whose outcome is
67
+ * anything but a clean, provably-first-ever terminal rejection — the only
68
+ * case `abandonPendingIntent` may fully discard the candidate.
69
+ */
70
+ readonly mayBeLive?: boolean;
71
+ }
72
+ /** One retired event and the relays that accepted its kind-5 deletion. */
73
+ export interface DeletionEntry {
74
+ readonly id: string;
75
+ readonly relays: readonly string[];
76
+ }
77
+ export interface KeyPackageSlotRecord {
78
+ readonly dSlot: string;
79
+ readonly lastResort: boolean;
80
+ /** Union of every relay set this slot was ever published to (F12) — what `forget()` publishes its kind-5 to. */
81
+ readonly relays: readonly string[];
82
+ /** Every event ever published (i.e. successfully confirmed) under this `d`, oldest first. */
83
+ readonly published: readonly PublishedEntry[];
84
+ /** The private KeyPackage for `published[published.length - 1]`. Absent only before the slot's first intent ever confirms. */
85
+ readonly currentPrivate?: Storable;
86
+ readonly currentRef?: string;
87
+ readonly superseded: readonly SupersededEntry[];
88
+ /** A not-yet-confirmed create/rotate/delete; see {@link PendingIntent}. */
89
+ readonly pending?: PendingIntent;
90
+ /** Round 6 (R6/F1/F2): possibly-live candidates retained outside `pending`; see {@link UnconfirmedEntry}. */
91
+ readonly unconfirmed: readonly UnconfirmedEntry[];
92
+ /**
93
+ * Retired-key events (epic marmot-device-key-rotation, S4) a kind-5 deletion
94
+ * was accepted for, and on which relays — so `retireKeyPackagesSignedWith`
95
+ * neither re-signs nor re-publishes a finished deletion and retries only the
96
+ * relays still missing. Absent on a slot that never had a retirement.
97
+ */
98
+ readonly deletions?: readonly DeletionEntry[];
99
+ /**
100
+ * The signed kind-5 of a retirement in progress, stored BEFORE it is published (like {@link PendingIntent}):
101
+ * a resume re-publishes this event to the relays still missing while its `ids` cover the events left to delete,
102
+ * and signs a new one only when an id outside them appears. Cleared once every deletion is recorded.
103
+ */
104
+ readonly deletionEvent?: {
105
+ readonly event: NostrEvent;
106
+ readonly ids: readonly string[];
107
+ };
108
+ }
109
+ /** Decodes a stored row into a {@link KeyPackageSlotRecord}. Throws `store-failed` on a malformed record. */
110
+ export declare function decodeSlotRecord(dSlot: string, raw: Storable): KeyPackageSlotRecord;
111
+ /** Reads one slot's record, or `undefined` when the slot does not exist. */
112
+ export declare function readSlot(view: KeyValueView, dSlot: string): Promise<KeyPackageSlotRecord | undefined>;
113
+ export declare function writeSlot(view: KeyValueView, record: KeyPackageSlotRecord): Promise<void>;
114
+ export declare function deleteSlot(view: KeyValueView, dSlot: string): Promise<void>;
115
+ /** Every slot record currently held, in an unspecified order (callers sort as needed). */
116
+ export declare function listSlots(view: KeyValueView): Promise<KeyPackageSlotRecord[]>;
117
+ /** A cryptographically random 32-byte slot identifier, hex-encoded (AC-KP-1). */
118
+ export declare function generateSlotId(): string;
119
+ /** The hex-encoded MIP-00 KeyPackageRef (RFC 9420 `make_key_package_ref`) of `keyPackage`. */
120
+ export declare function computeKeyPackageRefHex(keyPackage: KeyPackage): Promise<string>;
121
+ /**
122
+ * Drops every `superseded` entry whose own `expiresAtMs` has passed
123
+ * (AC-KP-3; F4: each entry is purged on its own clock, not the slot's).
124
+ * Returns `record` unchanged (referential no-op) when nothing needs
125
+ * dropping, so a caller can skip a write when every slot is already current.
126
+ */
127
+ export declare function purgeExpiredSuperseded(record: KeyPackageSlotRecord, nowMs: number): KeyPackageSlotRecord;
128
+ /**
129
+ * Drops every `unconfirmed` entry whose OWN KeyPackage leaf lifetime ended
130
+ * more than `graceWindowMs` ago (AC-KPL-3): an entry is retained while
131
+ * `nowMs <= notAfter * 1000 + graceWindowMs` and reaped after. Never a flat
132
+ * window from when the entry was parked — a mayBeLive candidate can be the
133
+ * newest version advertised at its address — but once no conforming inviter
134
+ * can select it (`notAfter`, AC-KP-4), the same grace margin a superseded
135
+ * key gets (AC-KP-3) still covers a Welcome built against it just before
136
+ * `notAfter` and delivered later. `nowMs` and `graceWindowMs` are client-
137
+ * clock milliseconds; `notAfter` is unix seconds (`Lifetime.notAfter`, a
138
+ * `bigint`). An entry whose lifetime can't be decoded is retained (R6 is
139
+ * the stronger obligation; an explicit `forget()` still removes it).
140
+ * Returns `record` unchanged (referential no-op) when nothing is reaped.
141
+ */
142
+ export declare function reapExpiredUnconfirmed(record: KeyPackageSlotRecord, nowMs: number, graceWindowMs: number): KeyPackageSlotRecord;
143
+ /**
144
+ * S6's seam (F3): the private KeyPackage for `keyPackageRef` — the current
145
+ * one, an unexpired superseded one (`nowMs < expiresAtMs`), or a still-
146
+ * PENDING one (R3: a create/rotate whose event already reached a relay —
147
+ * and is therefore selectable by an inviter — but whose local commit hasn't
148
+ * landed yet must still be findable, or a Welcome built against it could
149
+ * never be joined) — so a Welcome built against a KeyPackage this client
150
+ * has since rotated past, or one whose confirmation is still in flight, can
151
+ * still be decrypted. `undefined` when `keyPackageRef` is unknown, or was
152
+ * superseded and has since expired.
153
+ *
154
+ * Round 6 (R6): also matches an `unconfirmed` entry — a create candidate
155
+ * that may be live on a relay despite never confirming locally (F1) — with
156
+ * no expiry check, matching its own indefinite (until-`forget()`)
157
+ * retention.
158
+ */
159
+ export declare function findPrivateKeyPackage(view: KeyValueView, keyPackageRef: string, nowMs: number): Promise<Storable | undefined>;
160
+ /**
161
+ * The kind-30443 event carrying the PUBLIC half of `keyPackageRef` (the join
162
+ * needs both halves; {@link findPrivateKeyPackage} stays the private-key
163
+ * seam): a `published` entry — which also covers a superseded generation,
164
+ * since `published` keeps every event of the slot —, an `unconfirmed` one,
165
+ * or a pending create/rotate's. `undefined` when the ref is unknown.
166
+ */
167
+ export declare function findKeyPackageEventByRef(view: KeyValueView, keyPackageRef: string): Promise<NostrEvent | undefined>;
@@ -0,0 +1,327 @@
1
+ /**
2
+ * Persisted record codec for one KeyPackage "slot" (S4): the `AccountStore`
3
+ * `keyPackages` artifact, keyed by the slot's `d` identifier. Pure
4
+ * `KeyValueView` codec helpers only — no transport, no re-entrancy guard
5
+ * (`publisher.ts` owns those), mirroring `client/group-records.ts`'s split
6
+ * between codec and orchestration.
7
+ *
8
+ * Gate-remediation round 1 (F1/F3/F4/F7): a slot now carries a durable
9
+ * `pending` intent (create/rotate/delete — `publisher.ts`'s intent ->
10
+ * publish -> confirm pipeline) and a LIST of superseded generations, each
11
+ * with its own absolute expiry, rather than a single `supersededPrivate`.
12
+ *
13
+ * - `published` — every kind-30443 event ever published under this `d`
14
+ * (oldest first), each paired with its MLS `KeyPackageRef` hash:
15
+ * `forgetKeyPackage` needs the whole list (AC-KP-5), and both
16
+ * `rotate`/`forget` match a caller's `ref` against either an event id
17
+ * or a `keyPackageRef` (F5).
18
+ * - `currentPrivate`/`currentRef` — the ts-mls `PrivateKeyPackage` and
19
+ * `KeyPackageRef` hash for `published`'s last entry. A ts-mls
20
+ * `KeyPackage`/`PrivateKeyPackage` is plain data (nested
21
+ * numbers/strings/`Uint8Array`, no methods — the same fact
22
+ * `group-records.ts` relies on for a `Proposal`), so it round-trips
23
+ * through the envelope's `Storable` codec with a direct cast, no
24
+ * dedicated (de)serializer needed the way `ClientState` has one.
25
+ * - `superseded` — every PREVIOUS current, retained until its own
26
+ * `expiresAtMs` (F4: "each purged on its own clock"), so a Welcome
27
+ * built against any of them can still be decrypted (AC-KP-3) and S6's
28
+ * `findPrivateKeyPackage` seam can look any of them up by ref.
29
+ * - `pending` — a durable intent: a signed event already built and
30
+ * persisted BEFORE it is published, so a crash between publish and
31
+ * confirm resumes from here rather than orphaning a private key
32
+ * nothing local points at (F1/F7).
33
+ * - `unconfirmed` — gate-remediation round 6 (R6 invariant, F1/F2): a
34
+ * create/rotate candidate that was ABANDONED (terminally rejected)
35
+ * while `mayBeLive` (F1), or absorbed out of `pending` by a `forget()`
36
+ * that is itself not yet confirmed (F2) — in both cases the candidate
37
+ * might already be live on a relay, so its private key and ref stay
38
+ * retained and addressable (`findPrivateKeyPackage`, `forget()`'s own
39
+ * ref lookup) rather than discarded, until an explicit `forget()`
40
+ * resolves it, an attempt the relay accepted promotes it to current
41
+ * (AC-KPL-1), or its OWN KeyPackage leaf lifetime `notAfter` plus
42
+ * `graceWindowMs` passes — reaped by `reapExpiredUnconfirmed` (AC-KPL-3),
43
+ * called alongside `purgeExpiredSuperseded` at the start of every op.
44
+ * Unlike `superseded`, entries here have no FLAT `graceWindowMs`
45
+ * expiry: a mayBeLive candidate can be the NEWEST version ever
46
+ * advertised at its address (C1's created_at floor), so a flat window
47
+ * could expire it while it is still the live one.
48
+ */
49
+ import { calculateKeyPackageRef, getKeyPackageLifetime } from '@941design/marmot-engine/core';
50
+ import { MarmotError } from '../shared/index.js';
51
+ function malformed(dSlot, reason) {
52
+ return new MarmotError('store-failed', `keyPackages: malformed slot record ${dSlot}: ${reason}`, { details: { dSlot, malformed: true } });
53
+ }
54
+ function asNostrEvent(value, dSlot, what) {
55
+ if (typeof value !== 'object' || value === null)
56
+ throw malformed(dSlot, `${what} is not an object`);
57
+ const e = value;
58
+ if (typeof e['id'] !== 'string' || typeof e['pubkey'] !== 'string' || typeof e['kind'] !== 'number' || typeof e['created_at'] !== 'number' || typeof e['sig'] !== 'string' || !Array.isArray(e['tags'])) {
59
+ throw malformed(dSlot, `${what} is not a well-formed NostrEvent`);
60
+ }
61
+ return value;
62
+ }
63
+ function asPublishedEntry(value, dSlot) {
64
+ if (typeof value !== 'object' || value === null)
65
+ throw malformed(dSlot, 'published entry is not an object');
66
+ const e = value;
67
+ if (typeof e['keyPackageRef'] !== 'string')
68
+ throw malformed(dSlot, 'published entry is missing keyPackageRef');
69
+ return { event: asNostrEvent(e['event'], dSlot, 'published entry event'), keyPackageRef: e['keyPackageRef'] };
70
+ }
71
+ function asSupersededEntry(value, dSlot) {
72
+ if (typeof value !== 'object' || value === null)
73
+ throw malformed(dSlot, 'superseded entry is not an object');
74
+ const e = value;
75
+ if (typeof e['keyPackageRef'] !== 'string' || typeof e['supersededAtMs'] !== 'number' || typeof e['expiresAtMs'] !== 'number' || e['privatePackage'] === undefined) {
76
+ throw malformed(dSlot, 'superseded entry is missing a required field');
77
+ }
78
+ return { keyPackageRef: e['keyPackageRef'], supersededAtMs: e['supersededAtMs'], expiresAtMs: e['expiresAtMs'], privatePackage: e['privatePackage'] };
79
+ }
80
+ function asPendingIntent(value, dSlot) {
81
+ if (typeof value !== 'object' || value === null)
82
+ throw malformed(dSlot, 'pending is not an object');
83
+ const p = value;
84
+ if (p['kind'] !== 'create' && p['kind'] !== 'rotate' && p['kind'] !== 'delete')
85
+ throw malformed(dSlot, 'pending.kind is invalid');
86
+ const targetRelays = p['targetRelays'];
87
+ if (!Array.isArray(targetRelays) || !targetRelays.every((r) => typeof r === 'string'))
88
+ throw malformed(dSlot, 'pending.targetRelays is not a string array');
89
+ return {
90
+ kind: p['kind'],
91
+ event: asNostrEvent(p['event'], dSlot, 'pending event'),
92
+ targetRelays: targetRelays,
93
+ ...(p['privatePackage'] === undefined ? {} : { privatePackage: p['privatePackage'] }),
94
+ ...(typeof p['keyPackageRef'] === 'string' ? { keyPackageRef: p['keyPackageRef'] } : {}),
95
+ ...(typeof p['lastAttemptMs'] === 'number' ? { lastAttemptMs: p['lastAttemptMs'] } : {}),
96
+ ...(typeof p['mayBeLive'] === 'boolean' ? { mayBeLive: p['mayBeLive'] } : {}),
97
+ };
98
+ }
99
+ function asUnconfirmedEntry(value, dSlot) {
100
+ if (typeof value !== 'object' || value === null)
101
+ throw malformed(dSlot, 'unconfirmed entry is not an object');
102
+ const e = value;
103
+ if (typeof e['keyPackageRef'] !== 'string')
104
+ throw malformed(dSlot, 'unconfirmed entry is missing keyPackageRef');
105
+ if (e['privatePackage'] === undefined)
106
+ throw malformed(dSlot, 'unconfirmed entry is missing privatePackage');
107
+ return { event: asNostrEvent(e['event'], dSlot, 'unconfirmed entry event'), keyPackageRef: e['keyPackageRef'], privatePackage: e['privatePackage'] };
108
+ }
109
+ /** Decodes a stored row into a {@link KeyPackageSlotRecord}. Throws `store-failed` on a malformed record. */
110
+ export function decodeSlotRecord(dSlot, raw) {
111
+ if (typeof raw !== 'object' || raw === null || Array.isArray(raw))
112
+ throw malformed(dSlot, 'not an object');
113
+ const r = raw;
114
+ if (r['dSlot'] !== dSlot)
115
+ throw malformed(dSlot, 'dSlot mismatch');
116
+ if (typeof r['lastResort'] !== 'boolean')
117
+ throw malformed(dSlot, 'lastResort is not a boolean');
118
+ const relaysRaw = r['relays'];
119
+ if (!Array.isArray(relaysRaw) || !relaysRaw.every((v) => typeof v === 'string'))
120
+ throw malformed(dSlot, 'relays is not a string array');
121
+ const publishedRaw = r['published'];
122
+ if (!Array.isArray(publishedRaw))
123
+ throw malformed(dSlot, 'published is missing');
124
+ const published = publishedRaw.map((v) => asPublishedEntry(v, dSlot));
125
+ const supersededRaw = r['superseded'];
126
+ if (!Array.isArray(supersededRaw))
127
+ throw malformed(dSlot, 'superseded is missing');
128
+ const superseded = supersededRaw.map((v) => asSupersededEntry(v, dSlot));
129
+ // Round 6: absent on any record written before this field existed — an
130
+ // older stored slot simply has nothing unconfirmed, not a malformed one.
131
+ const unconfirmedRaw = r['unconfirmed'];
132
+ if (unconfirmedRaw !== undefined && !Array.isArray(unconfirmedRaw))
133
+ throw malformed(dSlot, 'unconfirmed is not an array');
134
+ const unconfirmed = unconfirmedRaw === undefined ? [] : unconfirmedRaw.map((v) => asUnconfirmedEntry(v, dSlot));
135
+ // S4 (device-key rotation): absent on any slot that never had a retired-key deletion.
136
+ const deletionEventRaw = r['deletionEvent'];
137
+ let deletionEvent;
138
+ if (deletionEventRaw !== undefined) {
139
+ if (typeof deletionEventRaw !== 'object' || deletionEventRaw === null)
140
+ throw malformed(dSlot, 'deletionEvent is malformed');
141
+ const ids = deletionEventRaw['ids'];
142
+ if (!Array.isArray(ids) || !ids.every((x) => typeof x === 'string'))
143
+ throw malformed(dSlot, 'deletionEvent is malformed');
144
+ deletionEvent = { event: asNostrEvent(deletionEventRaw['event'], dSlot, 'deletionEvent event'), ids: ids };
145
+ }
146
+ const deletionsRaw = r['deletions'];
147
+ if (deletionsRaw !== undefined && !Array.isArray(deletionsRaw))
148
+ throw malformed(dSlot, 'deletions is not an array');
149
+ const deletions = deletionsRaw?.map((v) => {
150
+ const e = v;
151
+ if (typeof e !== 'object' || e === null || typeof e['id'] !== 'string' || !Array.isArray(e['relays']) || !e['relays'].every((x) => typeof x === 'string')) {
152
+ throw malformed(dSlot, 'a deletions entry is malformed');
153
+ }
154
+ return { id: e['id'], relays: e['relays'] };
155
+ });
156
+ return {
157
+ dSlot,
158
+ lastResort: r['lastResort'],
159
+ relays: relaysRaw,
160
+ published,
161
+ superseded,
162
+ unconfirmed,
163
+ ...(deletions === undefined ? {} : { deletions }),
164
+ ...(deletionEvent === undefined ? {} : { deletionEvent }),
165
+ ...(r['currentPrivate'] === undefined ? {} : { currentPrivate: r['currentPrivate'] }),
166
+ ...(typeof r['currentRef'] === 'string' ? { currentRef: r['currentRef'] } : {}),
167
+ ...(r['pending'] === undefined ? {} : { pending: asPendingIntent(r['pending'], dSlot) }),
168
+ };
169
+ }
170
+ function encodePublishedEntry(entry) {
171
+ return { event: entry.event, keyPackageRef: entry.keyPackageRef };
172
+ }
173
+ function encodeSupersededEntry(entry) {
174
+ return { keyPackageRef: entry.keyPackageRef, privatePackage: entry.privatePackage, supersededAtMs: entry.supersededAtMs, expiresAtMs: entry.expiresAtMs };
175
+ }
176
+ function encodePendingIntent(pending) {
177
+ return {
178
+ kind: pending.kind,
179
+ event: pending.event,
180
+ targetRelays: [...pending.targetRelays],
181
+ ...(pending.privatePackage === undefined ? {} : { privatePackage: pending.privatePackage }),
182
+ ...(pending.keyPackageRef === undefined ? {} : { keyPackageRef: pending.keyPackageRef }),
183
+ ...(pending.lastAttemptMs === undefined ? {} : { lastAttemptMs: pending.lastAttemptMs }),
184
+ ...(pending.mayBeLive === undefined ? {} : { mayBeLive: pending.mayBeLive }),
185
+ };
186
+ }
187
+ function encodeUnconfirmedEntry(entry) {
188
+ return { event: entry.event, keyPackageRef: entry.keyPackageRef, privatePackage: entry.privatePackage };
189
+ }
190
+ function encodeSlotRecord(record) {
191
+ return {
192
+ dSlot: record.dSlot,
193
+ lastResort: record.lastResort,
194
+ relays: [...record.relays],
195
+ published: record.published.map(encodePublishedEntry),
196
+ superseded: record.superseded.map(encodeSupersededEntry),
197
+ unconfirmed: record.unconfirmed.map(encodeUnconfirmedEntry),
198
+ ...(record.deletionEvent === undefined ? {} : { deletionEvent: { event: record.deletionEvent.event, ids: [...record.deletionEvent.ids] } }),
199
+ ...(record.deletions === undefined ? {} : { deletions: record.deletions.map((d) => ({ id: d.id, relays: [...d.relays] })) }),
200
+ ...(record.currentPrivate === undefined ? {} : { currentPrivate: record.currentPrivate }),
201
+ ...(record.currentRef === undefined ? {} : { currentRef: record.currentRef }),
202
+ ...(record.pending === undefined ? {} : { pending: encodePendingIntent(record.pending) }),
203
+ };
204
+ }
205
+ /** Reads one slot's record, or `undefined` when the slot does not exist. */
206
+ export async function readSlot(view, dSlot) {
207
+ const raw = await view.get(dSlot);
208
+ if (raw === undefined)
209
+ return undefined;
210
+ return decodeSlotRecord(dSlot, raw);
211
+ }
212
+ export async function writeSlot(view, record) {
213
+ await view.put(record.dSlot, encodeSlotRecord(record));
214
+ }
215
+ export async function deleteSlot(view, dSlot) {
216
+ await view.delete(dSlot);
217
+ }
218
+ /** Every slot record currently held, in an unspecified order (callers sort as needed). */
219
+ export async function listSlots(view) {
220
+ const keys = await view.keys();
221
+ const out = [];
222
+ for (const key of keys) {
223
+ const record = await readSlot(view, key);
224
+ if (record !== undefined)
225
+ out.push(record);
226
+ }
227
+ return out;
228
+ }
229
+ /** A cryptographically random 32-byte slot identifier, hex-encoded (AC-KP-1). */
230
+ export function generateSlotId() {
231
+ const bytes = new Uint8Array(32);
232
+ globalThis.crypto.getRandomValues(bytes);
233
+ return toHex(bytes);
234
+ }
235
+ function toHex(bytes) {
236
+ return Array.from(bytes, (b) => b.toString(16).padStart(2, '0')).join('');
237
+ }
238
+ /** The hex-encoded MIP-00 KeyPackageRef (RFC 9420 `make_key_package_ref`) of `keyPackage`. */
239
+ export async function computeKeyPackageRefHex(keyPackage) {
240
+ return toHex(await calculateKeyPackageRef(keyPackage));
241
+ }
242
+ /**
243
+ * Drops every `superseded` entry whose own `expiresAtMs` has passed
244
+ * (AC-KP-3; F4: each entry is purged on its own clock, not the slot's).
245
+ * Returns `record` unchanged (referential no-op) when nothing needs
246
+ * dropping, so a caller can skip a write when every slot is already current.
247
+ */
248
+ export function purgeExpiredSuperseded(record, nowMs) {
249
+ const kept = record.superseded.filter((s) => nowMs < s.expiresAtMs);
250
+ if (kept.length === record.superseded.length)
251
+ return record;
252
+ return { ...record, superseded: kept };
253
+ }
254
+ /**
255
+ * Drops every `unconfirmed` entry whose OWN KeyPackage leaf lifetime ended
256
+ * more than `graceWindowMs` ago (AC-KPL-3): an entry is retained while
257
+ * `nowMs <= notAfter * 1000 + graceWindowMs` and reaped after. Never a flat
258
+ * window from when the entry was parked — a mayBeLive candidate can be the
259
+ * newest version advertised at its address — but once no conforming inviter
260
+ * can select it (`notAfter`, AC-KP-4), the same grace margin a superseded
261
+ * key gets (AC-KP-3) still covers a Welcome built against it just before
262
+ * `notAfter` and delivered later. `nowMs` and `graceWindowMs` are client-
263
+ * clock milliseconds; `notAfter` is unix seconds (`Lifetime.notAfter`, a
264
+ * `bigint`). An entry whose lifetime can't be decoded is retained (R6 is
265
+ * the stronger obligation; an explicit `forget()` still removes it).
266
+ * Returns `record` unchanged (referential no-op) when nothing is reaped.
267
+ */
268
+ export function reapExpiredUnconfirmed(record, nowMs, graceWindowMs) {
269
+ const kept = record.unconfirmed.filter((u) => {
270
+ const lifetime = getKeyPackageLifetime(u.event);
271
+ return lifetime === undefined || nowMs <= Number(lifetime.notAfter) * 1000 + graceWindowMs;
272
+ });
273
+ if (kept.length === record.unconfirmed.length)
274
+ return record;
275
+ return { ...record, unconfirmed: kept };
276
+ }
277
+ /**
278
+ * S6's seam (F3): the private KeyPackage for `keyPackageRef` — the current
279
+ * one, an unexpired superseded one (`nowMs < expiresAtMs`), or a still-
280
+ * PENDING one (R3: a create/rotate whose event already reached a relay —
281
+ * and is therefore selectable by an inviter — but whose local commit hasn't
282
+ * landed yet must still be findable, or a Welcome built against it could
283
+ * never be joined) — so a Welcome built against a KeyPackage this client
284
+ * has since rotated past, or one whose confirmation is still in flight, can
285
+ * still be decrypted. `undefined` when `keyPackageRef` is unknown, or was
286
+ * superseded and has since expired.
287
+ *
288
+ * Round 6 (R6): also matches an `unconfirmed` entry — a create candidate
289
+ * that may be live on a relay despite never confirming locally (F1) — with
290
+ * no expiry check, matching its own indefinite (until-`forget()`)
291
+ * retention.
292
+ */
293
+ export async function findPrivateKeyPackage(view, keyPackageRef, nowMs) {
294
+ for (const record of await listSlots(view)) {
295
+ if (record.currentRef === keyPackageRef && record.currentPrivate !== undefined)
296
+ return record.currentPrivate;
297
+ const hit = record.superseded.find((s) => s.keyPackageRef === keyPackageRef && nowMs < s.expiresAtMs);
298
+ if (hit !== undefined)
299
+ return hit.privatePackage;
300
+ const unconfirmedHit = record.unconfirmed.find((u) => u.keyPackageRef === keyPackageRef);
301
+ if (unconfirmedHit !== undefined)
302
+ return unconfirmedHit.privatePackage;
303
+ if (record.pending?.keyPackageRef === keyPackageRef && record.pending.privatePackage !== undefined)
304
+ return record.pending.privatePackage;
305
+ }
306
+ return undefined;
307
+ }
308
+ /**
309
+ * The kind-30443 event carrying the PUBLIC half of `keyPackageRef` (the join
310
+ * needs both halves; {@link findPrivateKeyPackage} stays the private-key
311
+ * seam): a `published` entry — which also covers a superseded generation,
312
+ * since `published` keeps every event of the slot —, an `unconfirmed` one,
313
+ * or a pending create/rotate's. `undefined` when the ref is unknown.
314
+ */
315
+ export async function findKeyPackageEventByRef(view, keyPackageRef) {
316
+ for (const record of await listSlots(view)) {
317
+ const published = record.published.find((e) => e.keyPackageRef === keyPackageRef);
318
+ if (published !== undefined)
319
+ return published.event;
320
+ const unconfirmed = record.unconfirmed.find((u) => u.keyPackageRef === keyPackageRef);
321
+ if (unconfirmed !== undefined)
322
+ return unconfirmed.event;
323
+ if (record.pending !== undefined && record.pending.kind !== 'delete' && record.pending.keyPackageRef === keyPackageRef)
324
+ return record.pending.event;
325
+ }
326
+ return undefined;
327
+ }
@@ -0,0 +1,3 @@
1
+ import type { KeyPackage } from '@941design/marmot-engine/mls';
2
+ import { type NostrEvent } from '@941design/nostr-events/event';
3
+ export declare function validateKeyPackageEvent(event: NostrEvent): KeyPackage | undefined;
@@ -0,0 +1,49 @@
1
+ /**
2
+ * The one "is this really a KeyPackage event, honestly authored by the
3
+ * account it claims" predicate (F2/F9: single owner — `select-key-package
4
+ * .ts` and `observation-stream.ts` both call this rather than maintaining
5
+ * their own copy).
6
+ *
7
+ * A relay is not obliged to honour a filter or to serve only what it
8
+ * claims to (nostr-events' own inbox-relays module documents the same
9
+ * caution), so every boundary read of a kind-30443 event re-checks, in
10
+ * order:
11
+ * 1. `kind === 30443` — a well-signed event of another kind could still
12
+ * happen to decode as a KeyPackage (`getKeyPackage` only reads
13
+ * `content`), so this is checked before decoding, not inferred from a
14
+ * successful decode;
15
+ * 2. the event's id/signature verify (`verifyEvent`, nostr-events/event —
16
+ * wraps nostr-tools, the same BIP340 verifier the rest of the
17
+ * workspace uses; never vendored here);
18
+ * 3. `content` decodes as a KeyPackage at all;
19
+ * 4. the KeyPackage's own Marmot credential names the SAME pubkey as the
20
+ * event's `pubkey` — otherwise anyone could republish someone else's
21
+ * KeyPackage under their own signature and have it accepted as if it
22
+ * were an offer of their own identity.
23
+ *
24
+ * Returns the decoded `KeyPackage` on success so a caller (both current
25
+ * callers do) does not decode `event.content` a second time.
26
+ */
27
+ import { ADDRESSABLE_KEY_PACKAGE_KIND, getCredentialPubkey, getKeyPackage } from '@941design/marmot-engine/core';
28
+ import { verifyEvent } from '@941design/nostr-events/event';
29
+ export function validateKeyPackageEvent(event) {
30
+ if (event.kind !== ADDRESSABLE_KEY_PACKAGE_KIND)
31
+ return undefined;
32
+ if (!verifyEvent(event))
33
+ return undefined;
34
+ let keyPackage;
35
+ try {
36
+ keyPackage = getKeyPackage(event);
37
+ }
38
+ catch {
39
+ return undefined;
40
+ }
41
+ try {
42
+ if (getCredentialPubkey(keyPackage.leafNode.credential) !== event.pubkey)
43
+ return undefined;
44
+ }
45
+ catch {
46
+ return undefined;
47
+ }
48
+ return keyPackage;
49
+ }