@941design/marmot 0.0.0-stage → 0.2.0-alpha.0

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 (192) hide show
  1. package/CHANGELOG.md +709 -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 +127 -0
  25. package/dist/account/teardown.js +856 -0
  26. package/dist/client/before-create-group.d.ts +18 -0
  27. package/dist/client/before-create-group.js +65 -0
  28. package/dist/client/before-publish-hooks.d.ts +121 -0
  29. package/dist/client/before-publish-hooks.js +180 -0
  30. package/dist/client/client-config.d.ts +42 -0
  31. package/dist/client/client-config.js +13 -0
  32. package/dist/client/commit-redrive.d.ts +68 -0
  33. package/dist/client/commit-redrive.js +221 -0
  34. package/dist/client/component-update.d.ts +43 -0
  35. package/dist/client/component-update.js +53 -0
  36. package/dist/client/confirm-hooks.d.ts +50 -0
  37. package/dist/client/confirm-hooks.js +59 -0
  38. package/dist/client/create-client.d.ts +1022 -0
  39. package/dist/client/create-client.js +1125 -0
  40. package/dist/client/group-disband.d.ts +28 -0
  41. package/dist/client/group-disband.js +64 -0
  42. package/dist/client/group-history.d.ts +435 -0
  43. package/dist/client/group-history.js +1295 -0
  44. package/dist/client/group-profile.d.ts +31 -0
  45. package/dist/client/group-profile.js +62 -0
  46. package/dist/client/group-records.d.ts +485 -0
  47. package/dist/client/group-records.js +1034 -0
  48. package/dist/client/group-removal.d.ts +36 -0
  49. package/dist/client/group-removal.js +127 -0
  50. package/dist/client/group-remove-member.d.ts +49 -0
  51. package/dist/client/group-remove-member.js +163 -0
  52. package/dist/client/group-runtime.d.ts +388 -0
  53. package/dist/client/group-runtime.js +2701 -0
  54. package/dist/client/group-snapshot.d.ts +98 -0
  55. package/dist/client/group-snapshot.js +453 -0
  56. package/dist/client/history-pages.d.ts +107 -0
  57. package/dist/client/history-pages.js +194 -0
  58. package/dist/client/inbox-send.d.ts +19 -0
  59. package/dist/client/inbox-send.js +71 -0
  60. package/dist/client/index.d.ts +21 -0
  61. package/dist/client/index.js +13 -0
  62. package/dist/client/ingest.d.ts +82 -0
  63. package/dist/client/ingest.js +1550 -0
  64. package/dist/client/lifecycle-events.d.ts +63 -0
  65. package/dist/client/lifecycle-events.js +35 -0
  66. package/dist/client/opaque-candidates.d.ts +81 -0
  67. package/dist/client/opaque-candidates.js +169 -0
  68. package/dist/client/own-change-outbox.d.ts +66 -0
  69. package/dist/client/own-change-outbox.js +156 -0
  70. package/dist/client/pending-leaf.d.ts +116 -0
  71. package/dist/client/pending-leaf.js +378 -0
  72. package/dist/client/permissions.d.ts +9 -0
  73. package/dist/client/permissions.js +12 -0
  74. package/dist/client/pipeline.d.ts +554 -0
  75. package/dist/client/pipeline.js +3545 -0
  76. package/dist/client/reentrancy-guard.d.ts +96 -0
  77. package/dist/client/reentrancy-guard.js +153 -0
  78. package/dist/client/rekey.d.ts +58 -0
  79. package/dist/client/rekey.js +149 -0
  80. package/dist/client/transport-policy.d.ts +181 -0
  81. package/dist/client/transport-policy.js +214 -0
  82. package/dist/history/equivocation.d.ts +55 -0
  83. package/dist/history/equivocation.js +113 -0
  84. package/dist/history/fencing.d.ts +25 -0
  85. package/dist/history/fencing.js +61 -0
  86. package/dist/history/hex.d.ts +3 -0
  87. package/dist/history/hex.js +10 -0
  88. package/dist/history/index.d.ts +73 -0
  89. package/dist/history/index.js +31 -0
  90. package/dist/history/notifications.d.ts +270 -0
  91. package/dist/history/notifications.js +264 -0
  92. package/dist/history/ordering-key.d.ts +24 -0
  93. package/dist/history/ordering-key.js +101 -0
  94. package/dist/history/own-change-fork.d.ts +112 -0
  95. package/dist/history/own-change-fork.js +196 -0
  96. package/dist/history/own-change.d.ts +106 -0
  97. package/dist/history/own-change.js +146 -0
  98. package/dist/history/policy.d.ts +48 -0
  99. package/dist/history/policy.js +52 -0
  100. package/dist/history/retained-window.d.ts +215 -0
  101. package/dist/history/retained-window.js +565 -0
  102. package/dist/inbox/demux.d.ts +90 -0
  103. package/dist/inbox/demux.js +78 -0
  104. package/dist/inbox/handler-registry.d.ts +42 -0
  105. package/dist/inbox/handler-registry.js +37 -0
  106. package/dist/inbox/index.d.ts +11 -0
  107. package/dist/inbox/index.js +10 -0
  108. package/dist/inbox/seen-set.d.ts +82 -0
  109. package/dist/inbox/seen-set.js +202 -0
  110. package/dist/inbox/subscription.d.ts +236 -0
  111. package/dist/inbox/subscription.js +644 -0
  112. package/dist/index.d.ts +10 -0
  113. package/dist/index.js +9 -0
  114. package/dist/invitations/competing-welcome.d.ts +223 -0
  115. package/dist/invitations/competing-welcome.js +128 -0
  116. package/dist/invitations/decline.d.ts +61 -0
  117. package/dist/invitations/decline.js +143 -0
  118. package/dist/invitations/expect-welcome.d.ts +66 -0
  119. package/dist/invitations/expect-welcome.js +138 -0
  120. package/dist/invitations/index.d.ts +16 -0
  121. package/dist/invitations/index.js +16 -0
  122. package/dist/invitations/invite.d.ts +303 -0
  123. package/dist/invitations/invite.js +966 -0
  124. package/dist/invitations/offers.d.ts +79 -0
  125. package/dist/invitations/offers.js +115 -0
  126. package/dist/invitations/on-proposal.d.ts +47 -0
  127. package/dist/invitations/on-proposal.js +40 -0
  128. package/dist/invitations/pending-proposal-policy.d.ts +52 -0
  129. package/dist/invitations/pending-proposal-policy.js +139 -0
  130. package/dist/invitations/proposal-deadline.d.ts +133 -0
  131. package/dist/invitations/proposal-deadline.js +164 -0
  132. package/dist/invitations/relay-planes.d.ts +43 -0
  133. package/dist/invitations/relay-planes.js +70 -0
  134. package/dist/invitations/welcome-processor.d.ts +253 -0
  135. package/dist/invitations/welcome-processor.js +1180 -0
  136. package/dist/key-packages/device-key.d.ts +131 -0
  137. package/dist/key-packages/device-key.js +272 -0
  138. package/dist/key-packages/device-rotation-records.d.ts +83 -0
  139. package/dist/key-packages/device-rotation-records.js +173 -0
  140. package/dist/key-packages/group-refs.d.ts +40 -0
  141. package/dist/key-packages/group-refs.js +79 -0
  142. package/dist/key-packages/index.d.ts +18 -0
  143. package/dist/key-packages/index.js +18 -0
  144. package/dist/key-packages/key-package-ref.d.ts +16 -0
  145. package/dist/key-packages/key-package-ref.js +21 -0
  146. package/dist/key-packages/observation-stream.d.ts +4 -0
  147. package/dist/key-packages/observation-stream.js +120 -0
  148. package/dist/key-packages/offer-rumor.d.ts +26 -0
  149. package/dist/key-packages/offer-rumor.js +69 -0
  150. package/dist/key-packages/publisher.d.ts +174 -0
  151. package/dist/key-packages/publisher.js +1247 -0
  152. package/dist/key-packages/select-key-package.d.ts +24 -0
  153. package/dist/key-packages/select-key-package.js +90 -0
  154. package/dist/key-packages/slot-manager.d.ts +167 -0
  155. package/dist/key-packages/slot-manager.js +327 -0
  156. package/dist/key-packages/validate-key-package-event.d.ts +3 -0
  157. package/dist/key-packages/validate-key-package-event.js +49 -0
  158. package/dist/media/cache.d.ts +14 -0
  159. package/dist/media/cache.js +10 -0
  160. package/dist/media/index.d.ts +52 -0
  161. package/dist/media/index.js +71 -0
  162. package/dist/mls.d.ts +15 -0
  163. package/dist/mls.js +15 -0
  164. package/dist/shared/account-pubkey.d.ts +4 -0
  165. package/dist/shared/account-pubkey.js +10 -0
  166. package/dist/shared/errors.d.ts +21 -0
  167. package/dist/shared/errors.js +85 -0
  168. package/dist/shared/hex.d.ts +4 -0
  169. package/dist/shared/hex.js +13 -0
  170. package/dist/shared/index.d.ts +14 -0
  171. package/dist/shared/index.js +14 -0
  172. package/dist/shared/kinds.d.ts +8 -0
  173. package/dist/shared/kinds.js +28 -0
  174. package/dist/shared/publish-classification.d.ts +26 -0
  175. package/dist/shared/publish-classification.js +31 -0
  176. package/dist/storage/envelope.d.ts +39 -0
  177. package/dist/storage/envelope.js +201 -0
  178. package/dist/storage/index.d.ts +227 -0
  179. package/dist/storage/index.js +459 -0
  180. package/dist/storage/indexeddb/idb-types.d.ts +68 -0
  181. package/dist/storage/indexeddb/idb-types.js +1 -0
  182. package/dist/storage/indexeddb/index.d.ts +17 -0
  183. package/dist/storage/indexeddb/index.js +141 -0
  184. package/dist/storage/lease.d.ts +41 -0
  185. package/dist/storage/lease.js +117 -0
  186. package/dist/storage/memory/deterministic-signer.d.ts +27 -0
  187. package/dist/storage/memory/deterministic-signer.js +65 -0
  188. package/dist/storage/memory/index.d.ts +32 -0
  189. package/dist/storage/memory/index.js +87 -0
  190. package/dist/storage/memory/lock-manager.d.ts +8 -0
  191. package/dist/storage/memory/lock-manager.js +71 -0
  192. package/package.json +66 -3
@@ -0,0 +1,79 @@
1
+ /**
2
+ * KeyPackage offers (S8 wiring of S4's offer-rumor codec; ADR-008, spec
3
+ * Design Decision 5, AC-KP-7): a targeted KeyPackage travels to a sponsor as
4
+ * a `RUMOR_KINDS.KEYPACKAGE_OFFER` rumor inside a NIP-59 gift wrap — the
5
+ * group id exists only inside the wrap, and the KeyPackage's own kind-30443
6
+ * event is the ordinary, untargeted one S4 publishes (no group-identifying
7
+ * tag). This replaces nosti's time-window admission.
8
+ *
9
+ * Offering ({@link sendKeyPackageOffer}): a fresh KeyPackage through S4's
10
+ * lifecycle, then the offer rumor, sealed by the account key and published to
11
+ * the sponsor's inbox relays only (S5's inbox plane). Not a durable intent:
12
+ * the KeyPackage is durable (S4) and a failed delivery rejects, so the
13
+ * application simply offers again.
14
+ *
15
+ * Receiving ({@link handleKeyPackageOffer}, the native handler S7's demux runs
16
+ * on the inbox queue): the offer is decoded (the KeyPackage must be authored
17
+ * by the rumor's seal-authenticated author), the KeyPackage must pass S4's
18
+ * selection rule, and this client must hold the named group; the offer is then
19
+ * recorded in the account's `marmot.offers` extension namespace (with the
20
+ * wrap's seen mark) and reported by the `keyPackageOffered` event. Admitting it
21
+ * is the application's decision: `group.invite([offer.keyPackageEvent])`.
22
+ */
23
+ import type { NostrEvent, Rumor } from '@941design/nostr-events/event';
24
+ import type { Signer } from '@941design/nostr-events/signer';
25
+ import type { DispatchContext, RumorDisposition } from '../inbox/index.js';
26
+ import type { AccountStoreTx } from '../storage/index.js';
27
+ import { type InboxRelayDeps } from './relay-planes.js';
28
+ /** Internal extension namespace of received offers (like `client`'s `marmot.groups` index). */
29
+ export declare const OFFERS_EXTENSION = "marmot.offers";
30
+ /** Received offers are kept this long. */
31
+ export declare const OFFER_RETENTION_MS: number;
32
+ /** A KeyPackage another account offered for one of this client's groups. */
33
+ export interface KeyPackageOffer {
34
+ /** The offer rumor's id. */
35
+ readonly offerId: string;
36
+ readonly groupId: string;
37
+ /** The offering account (the rumor's seal-authenticated author). */
38
+ readonly from: string;
39
+ /** The offered kind-30443 event — what `group.invite([...])` takes. */
40
+ readonly keyPackageEvent: NostrEvent;
41
+ /** Client clock (ms). */
42
+ readonly receivedAt: number;
43
+ }
44
+ export interface OfferDeps extends InboxRelayDeps {
45
+ readonly clock: {
46
+ now(): number;
47
+ };
48
+ /** The account-key signer (seals), routed through the re-entrancy guard. */
49
+ readonly signer: Signer;
50
+ /** `AccountStore.transaction`, routed through the re-entrancy guard. */
51
+ transaction<T>(fn: (tx: AccountStoreTx) => Promise<T> | T): Promise<T>;
52
+ /** Whether this client holds `groupId`. */
53
+ hasGroup(groupId: string): Promise<boolean>;
54
+ }
55
+ /** The `RUMOR_KINDS.KEYPACKAGE_OFFER` native inbox handler; `onOffer` runs after the record committed. */
56
+ export declare function handleKeyPackageOffer(deps: OfferDeps, rumor: Rumor, ctx: DispatchContext, onOffer: (offer: KeyPackageOffer) => void): Promise<RumorDisposition>;
57
+ /** S9 teardown: deletes every recorded offer of `groupId`. */
58
+ export declare function purgeGroupOffers(tx: AccountStoreTx, groupId: string): Promise<void>;
59
+ /** Every recorded offer (optionally of one group), oldest first. */
60
+ export declare function listKeyPackageOffers(deps: Pick<OfferDeps, 'transaction' | 'clock'>, groupId?: string): Promise<readonly KeyPackageOffer[]>;
61
+ /**
62
+ * `keyPackages.offer({ groupId, to })`: offers `keyPackageEvent` (a fresh
63
+ * KeyPackage the caller minted) to sponsor `to` for `groupId`. Resolves once
64
+ * an inbox relay of `to` accepted the wrap; rejects `no-inbox-relays` /
65
+ * `publish-failed` otherwise.
66
+ */
67
+ export declare function sendKeyPackageOffer(deps: OfferDeps, opts: {
68
+ readonly groupId: string;
69
+ readonly to: string;
70
+ readonly keyPackageEvent: NostrEvent;
71
+ }): Promise<{
72
+ readonly offerId: string;
73
+ readonly keyPackageEvent: NostrEvent;
74
+ }>;
75
+ /** Validates `keyPackages.offer`'s options. */
76
+ export declare function validateOfferOptions(raw: unknown): {
77
+ readonly groupId: string;
78
+ readonly to: string;
79
+ };
@@ -0,0 +1,115 @@
1
+ import { wrap as giftWrap } from '@941design/nostr-events/gift-wrap';
2
+ import { decodeKeyPackageOfferRumor, encodeKeyPackageOfferRumor, selectKeyPackage } from '../key-packages/index.js';
3
+ import { classifyPublish, MarmotError } from '../shared/index.js';
4
+ import { resolveInboxRelays } from './relay-planes.js';
5
+ /** Internal extension namespace of received offers (like `client`'s `marmot.groups` index). */
6
+ export const OFFERS_EXTENSION = 'marmot.offers';
7
+ /** Received offers are kept this long. */
8
+ export const OFFER_RETENTION_MS = 7 * 24 * 60 * 60 * 1000;
9
+ const HEX = /^[0-9a-f]+$/;
10
+ const PUBKEY = /^[0-9a-f]{64}$/;
11
+ /** The event's NIP-01 fields only (signature verification tags the object it checked with a symbol). */
12
+ function plainEvent(event) {
13
+ const { id, pubkey, created_at, kind, tags, content, sig } = event;
14
+ return { id, pubkey, created_at, kind, tags: tags.map((t) => [...t]), content, sig };
15
+ }
16
+ function decodeOffer(raw) {
17
+ if (typeof raw !== 'object' || raw === null)
18
+ return undefined;
19
+ const r = raw;
20
+ if (typeof r.offerId !== 'string' || typeof r.groupId !== 'string' || typeof r.from !== 'string' || typeof r.receivedAt !== 'number' || typeof r.keyPackageEvent !== 'object')
21
+ return undefined;
22
+ return r;
23
+ }
24
+ async function pruneOffers(view, nowMs) {
25
+ for (const key of await view.keys()) {
26
+ const offer = decodeOffer(await view.get(key));
27
+ if (offer === undefined || offer.receivedAt + OFFER_RETENTION_MS < nowMs)
28
+ await view.delete(key);
29
+ }
30
+ }
31
+ /** The `RUMOR_KINDS.KEYPACKAGE_OFFER` native inbox handler; `onOffer` runs after the record committed. */
32
+ export async function handleKeyPackageOffer(deps, rumor, ctx, onOffer) {
33
+ const decoded = decodeKeyPackageOfferRumor(rumor);
34
+ if (decoded === undefined)
35
+ return { kind: 'rejected', reason: 'malformed-offer' };
36
+ const nowMs = deps.clock.now();
37
+ if ((await selectKeyPackage([decoded.keyPackageEvent], Math.floor(nowMs / 1000))) === undefined)
38
+ return { kind: 'rejected', reason: 'invalid-keypackage' };
39
+ if (!HEX.test(decoded.groupId) || !(await deps.hasGroup(decoded.groupId)))
40
+ return { kind: 'rejected', reason: 'unknown-group' };
41
+ const offer = { offerId: rumor.id, groupId: decoded.groupId, from: rumor.pubkey, keyPackageEvent: plainEvent(decoded.keyPackageEvent), receivedAt: nowMs };
42
+ const fresh = await deps.transaction(async (tx) => {
43
+ const view = tx.extension(OFFERS_EXTENSION);
44
+ await pruneOffers(view, nowMs);
45
+ const known = (await view.get(offer.offerId)) !== undefined;
46
+ if (!known)
47
+ await view.put(offer.offerId, offer);
48
+ await ctx.markSeen(tx);
49
+ return !known;
50
+ });
51
+ if (!fresh)
52
+ return { kind: 'rejected', reason: 'replayed' };
53
+ onOffer(Object.freeze({ ...offer }));
54
+ return { kind: 'recorded', rumorKind: rumor.kind, id: offer.offerId };
55
+ }
56
+ /** S9 teardown: deletes every recorded offer of `groupId`. */
57
+ export async function purgeGroupOffers(tx, groupId) {
58
+ const view = tx.extension(OFFERS_EXTENSION);
59
+ for (const key of await view.keys())
60
+ if (decodeOffer(await view.get(key))?.groupId === groupId)
61
+ await view.delete(key);
62
+ }
63
+ /** Every recorded offer (optionally of one group), oldest first. */
64
+ export async function listKeyPackageOffers(deps, groupId) {
65
+ const nowMs = deps.clock.now();
66
+ const offers = await deps.transaction(async (tx) => {
67
+ const view = tx.extension(OFFERS_EXTENSION);
68
+ const out = [];
69
+ for (const key of await view.keys()) {
70
+ const offer = decodeOffer(await view.get(key));
71
+ if (offer !== undefined && offer.receivedAt + OFFER_RETENTION_MS >= nowMs && (groupId === undefined || offer.groupId === groupId))
72
+ out.push(offer);
73
+ }
74
+ return out;
75
+ });
76
+ return Object.freeze(offers.sort((a, b) => a.receivedAt - b.receivedAt || (a.offerId < b.offerId ? -1 : 1)).map((o) => Object.freeze({ ...o })));
77
+ }
78
+ /**
79
+ * `keyPackages.offer({ groupId, to })`: offers `keyPackageEvent` (a fresh
80
+ * KeyPackage the caller minted) to sponsor `to` for `groupId`. Resolves once
81
+ * an inbox relay of `to` accepted the wrap; rejects `no-inbox-relays` /
82
+ * `publish-failed` otherwise.
83
+ */
84
+ export async function sendKeyPackageOffer(deps, opts) {
85
+ const self = await deps.signer.getPublicKey();
86
+ const rumor = encodeKeyPackageOfferRumor({ pubkey: self, keyPackageEvent: opts.keyPackageEvent, groupId: opts.groupId, createdAt: Math.floor(deps.clock.now() / 1000) });
87
+ const resolution = await resolveInboxRelays(deps, opts.to);
88
+ if (resolution.kind === 'none')
89
+ throw new MarmotError('no-inbox-relays', `keyPackages.offer: ${opts.to} has no resolvable inbox relay`, { details: { to: opts.to } });
90
+ if (resolution.kind === 'transient') {
91
+ throw new MarmotError('publish-failed', `keyPackages.offer: ${opts.to}'s inbox relays could not be resolved (${resolution.reason})`, { details: { to: opts.to, reason: resolution.reason, retryable: true } });
92
+ }
93
+ const wrap = await giftWrap({ senderSigner: deps.signer, recipientPubkey: opts.to, rumor });
94
+ let accepted = false;
95
+ try {
96
+ accepted = classifyPublish(resolution.relays, await deps.transport.publish([...resolution.relays], wrap)).outcome === 'accepted';
97
+ }
98
+ catch {
99
+ accepted = false;
100
+ }
101
+ if (!accepted)
102
+ throw new MarmotError('publish-failed', `keyPackages.offer: no inbox relay of ${opts.to} accepted the offer`, { details: { to: opts.to, retryable: true } });
103
+ return Object.freeze({ offerId: rumor.id, keyPackageEvent: opts.keyPackageEvent });
104
+ }
105
+ /** Validates `keyPackages.offer`'s options. */
106
+ export function validateOfferOptions(raw) {
107
+ if (typeof raw !== 'object' || raw === null)
108
+ throw new MarmotError('invalid-options', 'keyPackages.offer: options must be an object');
109
+ const { groupId, to } = raw;
110
+ if (typeof groupId !== 'string' || !HEX.test(groupId))
111
+ throw new MarmotError('invalid-options', 'keyPackages.offer: groupId must be a lower-case hex group id', { details: { reason: 'invalid-group' } });
112
+ if (typeof to !== 'string' || !PUBKEY.test(to))
113
+ throw new MarmotError('invalid-options', 'keyPackages.offer: to must be a 64-char lower-case hex pubkey', { details: { reason: 'invalid-recipient' } });
114
+ return { groupId, to };
115
+ }
@@ -0,0 +1,47 @@
1
+ /**
2
+ * The `onProposal` extension point (AC-INVITE-4): the application's decision
3
+ * on a staged proposal it did not send itself, asked right before the local
4
+ * client builds a commit that would carry it.
5
+ *
6
+ * - `accept` — the commit carries it;
7
+ * - `reject` — it is invalid under application policy: dropped from the
8
+ * local staged set, so the commit omits it (RFC 9420 lets a committer
9
+ * leave out a proposal it deems invalid);
10
+ * - `defer` — it stays staged and the commit is not built yet; the
11
+ * callback is asked again on the next attempt.
12
+ */
13
+ export type ProposalDecision = 'accept' | 'reject' | 'defer';
14
+ /** A staged foreign proposal, as the application sees it. */
15
+ export interface PendingProposal {
16
+ readonly groupId: string;
17
+ /** Opaque reference of the staged proposal (stable while it stays staged). */
18
+ readonly proposalRef: string;
19
+ readonly type: 'add' | 'update' | 'remove' | 'self-remove' | 'app-data-update' | 'other';
20
+ /** The MLS proposal type number. */
21
+ readonly proposalType: number;
22
+ /** Account pubkey of the proposing leaf, when it is a member leaf. */
23
+ readonly proposer: string | undefined;
24
+ readonly proposerLeafIndex: number | undefined;
25
+ /** Whether the proposer's account is listed as a group admin. */
26
+ readonly proposerIsAdmin: boolean;
27
+ /** For an Add: the account whose KeyPackage it adds. */
28
+ readonly addedAccount?: string;
29
+ /** For a Remove: the leaf it removes. */
30
+ readonly removedLeafIndex?: number;
31
+ }
32
+ export type ProposalCallback = (proposal: PendingProposal) => ProposalDecision | Promise<ProposalDecision>;
33
+ /**
34
+ * The decision without a callback. AC-INVITE-4: a non-admin member's Add is
35
+ * committed ONLY when `onProposal` accepts it — so, with no callback, a
36
+ * non-admin Add (and, by the same membership rule, Remove) is rejected; not
37
+ * deferred, which would block every own commit for good. Everything else —
38
+ * an admin's proposal, SelfRemove, Update, app-data updates — is accepted.
39
+ */
40
+ export declare function defaultDecision(proposal: PendingProposal): ProposalDecision;
41
+ /**
42
+ * The decision for `proposal`. `ask` is the consumer callback already routed
43
+ * through the re-entrancy guard, or `undefined` when none is configured
44
+ * (then {@link defaultDecision}). A callback that throws or answers anything
45
+ * else defers: a broken callback never gets a proposal committed or discarded.
46
+ */
47
+ export declare function decideProposal(ask: ((proposal: PendingProposal) => Promise<unknown>) | undefined, proposal: PendingProposal): Promise<ProposalDecision>;
@@ -0,0 +1,40 @@
1
+ /**
2
+ * The `onProposal` extension point (AC-INVITE-4): the application's decision
3
+ * on a staged proposal it did not send itself, asked right before the local
4
+ * client builds a commit that would carry it.
5
+ *
6
+ * - `accept` — the commit carries it;
7
+ * - `reject` — it is invalid under application policy: dropped from the
8
+ * local staged set, so the commit omits it (RFC 9420 lets a committer
9
+ * leave out a proposal it deems invalid);
10
+ * - `defer` — it stays staged and the commit is not built yet; the
11
+ * callback is asked again on the next attempt.
12
+ */
13
+ /**
14
+ * The decision without a callback. AC-INVITE-4: a non-admin member's Add is
15
+ * committed ONLY when `onProposal` accepts it — so, with no callback, a
16
+ * non-admin Add (and, by the same membership rule, Remove) is rejected; not
17
+ * deferred, which would block every own commit for good. Everything else —
18
+ * an admin's proposal, SelfRemove, Update, app-data updates — is accepted.
19
+ */
20
+ export function defaultDecision(proposal) {
21
+ return (proposal.type === 'add' || proposal.type === 'remove') && !proposal.proposerIsAdmin ? 'reject' : 'accept';
22
+ }
23
+ /**
24
+ * The decision for `proposal`. `ask` is the consumer callback already routed
25
+ * through the re-entrancy guard, or `undefined` when none is configured
26
+ * (then {@link defaultDecision}). A callback that throws or answers anything
27
+ * else defers: a broken callback never gets a proposal committed or discarded.
28
+ */
29
+ export async function decideProposal(ask, proposal) {
30
+ if (ask === undefined)
31
+ return defaultDecision(proposal);
32
+ let answer;
33
+ try {
34
+ answer = await ask(proposal);
35
+ }
36
+ catch {
37
+ return 'defer';
38
+ }
39
+ return answer === 'accept' || answer === 'reject' || answer === 'defer' ? answer : 'defer';
40
+ }
@@ -0,0 +1,52 @@
1
+ import { type ClientState } from '@941design/marmot-engine/mls';
2
+ import { type PendingProposal } from './on-proposal.js';
3
+ export interface StagedProposals {
4
+ /** Refs of proposals the local leaf sent itself (implicitly accepted). */
5
+ readonly own: readonly string[];
6
+ /** Every other staged proposal, described for `onProposal`. */
7
+ readonly foreign: readonly PendingProposal[];
8
+ }
9
+ /** The proposals staged in `state` (its `unappliedProposals`), split into own and foreign. */
10
+ export declare function stagedProposals(state: ClientState, groupId: string): StagedProposals;
11
+ export interface ProposalResolution {
12
+ readonly accepted: readonly string[];
13
+ readonly rejected: readonly string[];
14
+ readonly deferred: readonly string[];
15
+ }
16
+ /** Asks for a decision on each foreign proposal, in order (see `decideProposal` for the defaults). */
17
+ export declare function resolveProposals(foreign: readonly PendingProposal[], ask: ((proposal: PendingProposal) => Promise<unknown>) | undefined): Promise<ProposalResolution>;
18
+ /**
19
+ * `state` with the proposals `refs` removed from its staged set — marking them
20
+ * invalid under application policy: a commit built over the result omits
21
+ * them, and the epoch change it causes discards them everywhere else.
22
+ */
23
+ export declare function withoutProposals(state: ClientState, refs: readonly string[]): ClientState;
24
+ /** Whether `account` may commit other members' proposals in `state`: it is a listed group admin. */
25
+ export declare function isAuthorisedCommitter(state: ClientState, account: string): boolean;
26
+ /**
27
+ * Whether an application rumor sent now must be queued rather than published:
28
+ * proposals are staged, earlier rumors are queued, or an earlier application
29
+ * intent is still pending (a new rumor must not overtake it on the relay).
30
+ */
31
+ export declare function mustQueue(state: ClientState, queuedCount: number, applicationPending: boolean): boolean;
32
+ /**
33
+ * The epoch a newly queued rumor waits past: the current one when proposals
34
+ * are staged (it goes out only after the commit that clears them), else the
35
+ * barrier of the rumor queued ahead of it (it only keeps queue order).
36
+ */
37
+ export declare function queueBarrier(state: ClientState, previous: bigint | undefined): bigint | undefined;
38
+ export type QueueStep = 'publish' | 'commit' | 'wait';
39
+ /**
40
+ * What the queue does next for its head rumor:
41
+ * - `publish` — nothing is staged and the epoch moved past its barrier;
42
+ * - `commit` — a commit is needed and the local account may build it;
43
+ * - `wait` — a commit is needed, but an own commit is already in flight
44
+ * (its confirmation drains the queue) or the account is not authorised
45
+ * (a commit arriving by ingest does).
46
+ */
47
+ export declare function nextQueueStep(opts: {
48
+ readonly state: ClientState;
49
+ readonly barrier: bigint | undefined;
50
+ readonly authorised: boolean;
51
+ readonly ownCommitPending: boolean;
52
+ }): QueueStep;
@@ -0,0 +1,139 @@
1
+ /**
2
+ * Pending-proposal commit-or-queue policy (AC-INVITE-3, AC-INVITE-4) — pure
3
+ * functions over a group `ClientState`; the client pipeline owns the I/O
4
+ * (asking `onProposal`, persisting, committing, publishing).
5
+ *
6
+ * ts-mls refuses to send an application message while any proposal is staged
7
+ * (own ones included), so an application rumor sent then waits for the next
8
+ * confirmed commit. The local client builds that commit itself when it is an
9
+ * authorised committer (a group admin), after the application decided every
10
+ * staged foreign proposal (`onProposal`); otherwise the rumor waits for a
11
+ * commit to arrive by ingest.
12
+ */
13
+ import { getCredentialPubkey, getMarmotGroupView } from '@941design/marmot-engine/core';
14
+ import { appDataUpdateProposalType, defaultProposalTypes, nodeTypes, selfRemoveProposalType } from '@941design/marmot-engine/mls';
15
+ import { decideProposal } from './on-proposal.js';
16
+ function accountAt(state, leafIndex) {
17
+ if (leafIndex === undefined)
18
+ return undefined;
19
+ const node = state.ratchetTree[2 * leafIndex];
20
+ if (node?.nodeType !== nodeTypes.leaf)
21
+ return undefined;
22
+ try {
23
+ return getCredentialPubkey(node.leaf.credential);
24
+ }
25
+ catch {
26
+ return undefined;
27
+ }
28
+ }
29
+ function describeType(proposalType) {
30
+ switch (proposalType) {
31
+ case defaultProposalTypes.add:
32
+ return 'add';
33
+ case defaultProposalTypes.update:
34
+ return 'update';
35
+ case defaultProposalTypes.remove:
36
+ return 'remove';
37
+ case selfRemoveProposalType:
38
+ return 'self-remove';
39
+ case appDataUpdateProposalType:
40
+ return 'app-data-update';
41
+ default:
42
+ return 'other';
43
+ }
44
+ }
45
+ /** The proposals staged in `state` (its `unappliedProposals`), split into own and foreign. */
46
+ export function stagedProposals(state, groupId) {
47
+ const ownLeaf = Number(state.privatePath.leafIndex);
48
+ const admins = new Set(getMarmotGroupView(state)?.adminPubkeys ?? []);
49
+ const own = [];
50
+ const foreign = [];
51
+ for (const [proposalRef, { proposal, senderLeafIndex }] of Object.entries(state.unappliedProposals)) {
52
+ if (senderLeafIndex !== undefined && Number(senderLeafIndex) === ownLeaf) {
53
+ own.push(proposalRef);
54
+ continue;
55
+ }
56
+ const proposerLeafIndex = senderLeafIndex === undefined ? undefined : Number(senderLeafIndex);
57
+ const proposer = accountAt(state, proposerLeafIndex);
58
+ let addedAccount;
59
+ if (proposal.proposalType === defaultProposalTypes.add && 'add' in proposal) {
60
+ try {
61
+ addedAccount = getCredentialPubkey(proposal.add.keyPackage.leafNode.credential);
62
+ }
63
+ catch {
64
+ addedAccount = undefined;
65
+ }
66
+ }
67
+ const removedLeafIndex = proposal.proposalType === defaultProposalTypes.remove && 'remove' in proposal ? Number(proposal.remove.removed) : undefined;
68
+ foreign.push({
69
+ groupId,
70
+ proposalRef,
71
+ type: describeType(proposal.proposalType),
72
+ proposalType: proposal.proposalType,
73
+ proposer,
74
+ proposerLeafIndex,
75
+ proposerIsAdmin: proposer !== undefined && admins.has(proposer),
76
+ ...(addedAccount === undefined ? {} : { addedAccount }),
77
+ ...(removedLeafIndex === undefined ? {} : { removedLeafIndex }),
78
+ });
79
+ }
80
+ return { own, foreign };
81
+ }
82
+ /** Asks for a decision on each foreign proposal, in order (see `decideProposal` for the defaults). */
83
+ export async function resolveProposals(foreign, ask) {
84
+ const accepted = [];
85
+ const rejected = [];
86
+ const deferred = [];
87
+ for (const proposal of foreign) {
88
+ const decision = await decideProposal(ask, proposal);
89
+ (decision === 'accept' ? accepted : decision === 'reject' ? rejected : deferred).push(proposal.proposalRef);
90
+ }
91
+ return { accepted, rejected, deferred };
92
+ }
93
+ /**
94
+ * `state` with the proposals `refs` removed from its staged set — marking them
95
+ * invalid under application policy: a commit built over the result omits
96
+ * them, and the epoch change it causes discards them everywhere else.
97
+ */
98
+ export function withoutProposals(state, refs) {
99
+ const drop = new Set(refs);
100
+ const unappliedProposals = Object.fromEntries(Object.entries(state.unappliedProposals).filter(([ref]) => !drop.has(ref)));
101
+ return { ...state, unappliedProposals };
102
+ }
103
+ /** Whether `account` may commit other members' proposals in `state`: it is a listed group admin. */
104
+ export function isAuthorisedCommitter(state, account) {
105
+ return getMarmotGroupView(state)?.adminPubkeys.includes(account) ?? false;
106
+ }
107
+ /**
108
+ * Whether an application rumor sent now must be queued rather than published:
109
+ * proposals are staged, earlier rumors are queued, or an earlier application
110
+ * intent is still pending (a new rumor must not overtake it on the relay).
111
+ */
112
+ export function mustQueue(state, queuedCount, applicationPending) {
113
+ return applicationPending || queuedCount > 0 || Object.keys(state.unappliedProposals).length > 0;
114
+ }
115
+ /**
116
+ * The epoch a newly queued rumor waits past: the current one when proposals
117
+ * are staged (it goes out only after the commit that clears them), else the
118
+ * barrier of the rumor queued ahead of it (it only keeps queue order).
119
+ */
120
+ export function queueBarrier(state, previous) {
121
+ return Object.keys(state.unappliedProposals).length > 0 ? state.groupContext.epoch : previous;
122
+ }
123
+ /**
124
+ * What the queue does next for its head rumor:
125
+ * - `publish` — nothing is staged and the epoch moved past its barrier;
126
+ * - `commit` — a commit is needed and the local account may build it;
127
+ * - `wait` — a commit is needed, but an own commit is already in flight
128
+ * (its confirmation drains the queue) or the account is not authorised
129
+ * (a commit arriving by ingest does).
130
+ */
131
+ export function nextQueueStep(opts) {
132
+ const staged = Object.keys(opts.state.unappliedProposals).length > 0;
133
+ const behindBarrier = opts.barrier !== undefined && opts.state.groupContext.epoch <= opts.barrier;
134
+ if (!staged && !behindBarrier)
135
+ return 'publish';
136
+ if (opts.ownCommitPending || !opts.authorised)
137
+ return 'wait';
138
+ return 'commit';
139
+ }
@@ -0,0 +1,133 @@
1
+ /**
2
+ * The durable deadline of a deferred proposal (AC-INVITE-4, amended
3
+ * 2026-10-02): a proposal `onProposal` answered `defer` for carries a
4
+ * deadline, `deferredAt + proposalDeferralTimeoutMs` (client clock, ms;
5
+ * `0` = never). Once it passed, the proposal is treated as `reject` — the
6
+ * same drop from the staged set an explicit `reject` makes — `onProposal` is
7
+ * not asked about it again, and `proposalExpired` is announced. Never
8
+ * auto-accepted.
9
+ *
10
+ * No timer: one {@link DeferralRecord} per deferred proposal is persisted in
11
+ * the group extension {@link DEFERRED_PROPOSALS_EXTENSION}, and the client
12
+ * evaluates it against its injectable clock at its evaluation points — every
13
+ * own-commit attempt, the group's load, each history pass of the group and
14
+ * each account inbox pass. A deadline that passes while the process is down
15
+ * is therefore honoured after reload — once the group completed its first
16
+ * sync since load and since the last connectivity gap
17
+ * (`GroupRuntime.caughtUp`): before that nothing expires, so a peer admin's
18
+ * commit of the proposal resolves it first.
19
+ *
20
+ * Record lifecycle (pure partition: {@link planDeferrals}):
21
+ * - written with `deferredAt` the first time the proposal is deferred (a
22
+ * later `defer` keeps the original deferral time — the deadline never
23
+ * slides);
24
+ * - deleted silently when the proposal stops being staged without expiring
25
+ * (`accept`/`reject`, a commit — own or a peer's — that carried or
26
+ * discarded it): such a proposal is never announced as expired;
27
+ * - marked `expiredAt` in the SAME transaction that drops the proposal from
28
+ * the persisted staged set; the marker means "`proposalExpired` still
29
+ * owed";
30
+ * - deleted after the event was emitted.
31
+ *
32
+ * Emission semantics: exactly once, except that a crash between the emit and
33
+ * the marker's deletion re-emits the same payload once more on the next
34
+ * evaluation (at-least-once, idempotent: consumers deduplicate by
35
+ * `(groupId, proposalRef)`). A crash before the emit loses nothing — the
36
+ * marker survives and the next evaluation (at the latest the reload)
37
+ * announces it.
38
+ */
39
+ import type { KeyValueView } from '../storage/index.js';
40
+ /** Group extension namespace of the deferral records, keyed by proposal ref. */
41
+ export declare const DEFERRED_PROPOSALS_EXTENSION = "marmot.deferredProposals";
42
+ /** Default `ClientOptions.proposalDeferralTimeoutMs`: 24 h. */
43
+ export declare const DEFAULT_PROPOSAL_DEFERRAL_TIMEOUT_MS = 86400000;
44
+ export interface DeferralRecord {
45
+ readonly proposalRef: string;
46
+ /** Client clock (ms) of the proposal's first `defer`. */
47
+ readonly deferredAt: number;
48
+ /** Client clock (ms) at which it expired; present = dropped, `proposalExpired` still owed. */
49
+ readonly expiredAt?: number;
50
+ }
51
+ /** Whether `record`'s deadline has passed at `nowMs` (`timeoutMs` 0 = never), or it is already marked expired. */
52
+ export declare function deferralExpired(record: DeferralRecord, nowMs: number, timeoutMs: number): boolean;
53
+ export interface DeferralPlan {
54
+ /** Staged proposals whose deadline passed: dropped as `reject`, never asked about again. */
55
+ readonly expired: readonly DeferralRecord[];
56
+ /** Marked expired, no longer staged: the drop is durable, only `proposalExpired` is still owed. */
57
+ readonly owed: readonly DeferralRecord[];
58
+ /** Records whose proposal is no longer staged and never expired (committed, rejected, discarded): deleted, never announced. */
59
+ readonly stale: readonly string[];
60
+ /** Staged foreign proposal refs still decided by `onProposal` (no record, or a record not yet expired). */
61
+ readonly live: readonly string[];
62
+ /** The records of `live` refs, by ref (a re-deferral keeps its `deferredAt`). */
63
+ readonly recorded: ReadonlyMap<string, DeferralRecord>;
64
+ }
65
+ /** Partitions the staged foreign proposals and the stored deferral records at `nowMs`. */
66
+ export declare function planDeferrals(stagedForeignRefs: readonly string[], records: readonly DeferralRecord[], nowMs: number, timeoutMs: number): DeferralPlan;
67
+ /** Every stored deferral record of the group (a malformed row reads as absent). */
68
+ export declare function readDeferrals(view: KeyValueView): Promise<DeferralRecord[]>;
69
+ export declare function writeDeferral(view: KeyValueView, record: DeferralRecord): Promise<void>;
70
+ export declare function deleteDeferral(view: KeyValueView, proposalRef: string): Promise<void>;
71
+ /**
72
+ * Group extension namespace of the proposals this client dropped from its
73
+ * staged set by application policy.
74
+ *
75
+ * The drop only keeps the proposal out of OWN commits. ts-mls builds every
76
+ * own commit over all staged proposals (the engine has no per-commit
77
+ * selection), so the drop must remove it from the persisted staged set — and
78
+ * that same set is what a PEER's commit is resolved against: a peer admin
79
+ * that accepted the proposal commits it by reference, and without it that
80
+ * commit could never apply (the engine defers it as `missing_parent` for
81
+ * good). The same holds for a peer commit at an EARLIER epoch that fork
82
+ * recovery replays against a retained state (this client committed past the
83
+ * drop meanwhile).
84
+ *
85
+ * So each drop is recorded — `ref:<proposalRef>` → `{ epoch, tag, reason }`,
86
+ * `tag` being the hex confirmation tag of the state it was dropped from (its
87
+ * BRANCH: same-epoch fork siblings share the epoch, never the tag) — with ONE
88
+ * state snapshot per branch node, `snap:<tag>`: a serialized ClientState of
89
+ * that node staging every proposal dropped at it (merged on each drop). It
90
+ * holds no secret the retained window's state of that node does not. The
91
+ * client re-stages the proposals — into the current state, or into the
92
+ * retained window node, whose tag matches; never into a sibling of the same
93
+ * epoch, whose members never validated them — when a commit waits for a
94
+ * missing proposal, then retries the commit (client/ingest.ts). At the current epoch
95
+ * an exclusion is authoritative: a re-staged excluded proposal (that retry, a
96
+ * rewind) is dropped again before the next own commit, never asked about or
97
+ * deferred anew. Records and snapshots are kept for the rollback horizon
98
+ * (epochs older than `current - horizon` are deleted).
99
+ */
100
+ export declare const EXCLUDED_PROPOSALS_EXTENSION = "marmot.excludedProposals";
101
+ export interface ExclusionRecord {
102
+ readonly proposalRef: string;
103
+ /** The epoch (decimal string) the proposal was staged at. */
104
+ readonly epoch: string;
105
+ /** Hex confirmation tag of the state (branch node) it was dropped from. */
106
+ readonly tag: string;
107
+ readonly reason: 'rejected' | 'expired';
108
+ }
109
+ export interface Exclusions {
110
+ readonly records: readonly ExclusionRecord[];
111
+ /** Per branch node (hex confirmation tag): serialized ClientState staging every proposal excluded at it. */
112
+ readonly snapshots: ReadonlyMap<string, Uint8Array>;
113
+ }
114
+ /** Every stored exclusion and snapshot of the group (a malformed row reads as absent). */
115
+ export declare function readExclusions(view: KeyValueView): Promise<Exclusions>;
116
+ export declare function writeExclusion(view: KeyValueView, record: ExclusionRecord): Promise<void>;
117
+ /** Stores the (merged) snapshot of the branch node `tag`. */
118
+ export declare function writeExclusionSnapshot(view: KeyValueView, tag: string, snapshot: Uint8Array): Promise<void>;
119
+ /** Deletes the exclusions of every epoch in `epochs`, and every snapshot no kept exclusion names. */
120
+ export declare function deleteExclusionEpochs(view: KeyValueView, exclusions: Exclusions, epochs: ReadonlySet<string>): Promise<void>;
121
+ /**
122
+ * Splits exclusions for the current state (epoch `currentEpoch`, tag
123
+ * `currentTag`): `current` — those dropped from THIS state (authoritative;
124
+ * a same-epoch sibling's never apply here), `byTag` — every kept exclusion by
125
+ * the branch node it was dropped from, and `outdated` — epochs older than
126
+ * `current - horizon`, or newer than current (a rewind left them behind), to
127
+ * delete. A snapshot no kept exclusion names is deleted with them.
128
+ */
129
+ export declare function exclusionsAt(exclusions: Exclusions, currentEpoch: bigint, currentTag: string, horizon: number): {
130
+ readonly current: readonly ExclusionRecord[];
131
+ readonly byTag: ReadonlyMap<string, readonly ExclusionRecord[]>;
132
+ readonly outdated: ReadonlySet<string>;
133
+ };