@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,138 @@
1
+ /**
2
+ * `expectWelcome(manifest)` (S6, AC-WEL-1): manifest validation, the
3
+ * account `enrolmentManifests` record codec (ADR-008: one API for
4
+ * application invitations and ADR-003 enrolment, so both share the
5
+ * artifact) and the match rule. Pure helpers; `welcome-processor.ts` runs
6
+ * them on the inbox's serial queue.
7
+ *
8
+ * A manifest auto-accepts a Welcome only when its group id, the consumed
9
+ * KeyPackageRef and the sponsor account all equal the manifest's and it is
10
+ * processed before `deadline` (client-clock milliseconds). One processed at
11
+ * or after the deadline expires the manifest and is surfaced as an
12
+ * unexpected Welcome instead (AC-WEL-5). The sponsor is the account of the
13
+ * leaf that signed the Welcome's GroupInfo, recovered during the join by the
14
+ * engine's `joinGroupFromWelcomeWithSigner` seam; who sealed or forwarded the
15
+ * copy does not matter.
16
+ */
17
+ import { MarmotError } from '../shared/index.js';
18
+ const MANIFESTS = 'enrolmentManifests';
19
+ const HEX = /^[0-9a-f]+$/;
20
+ const PUBKEY = /^[0-9a-f]{64}$/;
21
+ const STATUSES = new Set(['waiting', 'fulfilled', 'expired']);
22
+ export function manifestKey(groupId, keyPackageRef) {
23
+ return `${groupId}:${keyPackageRef}`;
24
+ }
25
+ function invalid(message, reason) {
26
+ return new MarmotError('invalid-options', `expectWelcome: ${message}`, { details: { reason } });
27
+ }
28
+ /** Validates an `expectWelcome` argument (hex ids lower-case, `deadline` after `nowMs`). */
29
+ export function validateManifest(manifest, nowMs) {
30
+ if (typeof manifest !== 'object' || manifest === null)
31
+ throw invalid('manifest must be an object', 'invalid-manifest');
32
+ const { groupId, keyPackageRef, sponsorAccount, deadline } = manifest;
33
+ if (typeof groupId !== 'string' || !HEX.test(groupId))
34
+ throw invalid('manifest.groupId must be a lower-case hex group id', 'invalid-manifest');
35
+ if (typeof keyPackageRef !== 'string' || !HEX.test(keyPackageRef))
36
+ throw invalid('manifest.keyPackageRef must be a lower-case hex KeyPackageRef', 'invalid-manifest');
37
+ if (typeof sponsorAccount !== 'string' || !PUBKEY.test(sponsorAccount))
38
+ throw invalid('manifest.sponsorAccount must be a 64-char lower-case hex pubkey', 'invalid-manifest');
39
+ if (typeof deadline !== 'number' || !Number.isFinite(deadline))
40
+ throw invalid('manifest.deadline must be a finite number (client-clock ms)', 'invalid-manifest');
41
+ if (deadline <= nowMs)
42
+ throw invalid('manifest.deadline has already passed', 'deadline-passed');
43
+ return { groupId, keyPackageRef, sponsorAccount, deadline };
44
+ }
45
+ function malformed(key) {
46
+ return new MarmotError('store-failed', `enrolmentManifests/${key}: malformed record`, { details: { key, malformed: true } });
47
+ }
48
+ export function decodeManifest(key, raw) {
49
+ if (typeof raw !== 'object' || raw === null || Array.isArray(raw))
50
+ throw malformed(key);
51
+ const { v, groupId, keyPackageRef, sponsorAccount, deadline, status, invitationId, recordedAt } = raw;
52
+ if (v !== 1 || typeof groupId !== 'string' || typeof keyPackageRef !== 'string' || typeof sponsorAccount !== 'string' || typeof deadline !== 'number')
53
+ throw malformed(key);
54
+ if (typeof status !== 'string' || !STATUSES.has(status) || (invitationId !== undefined && typeof invitationId !== 'string'))
55
+ throw malformed(key);
56
+ if (manifestKey(groupId, keyPackageRef) !== key)
57
+ throw malformed(key);
58
+ if (recordedAt !== undefined && typeof recordedAt !== 'number')
59
+ throw malformed(key);
60
+ return { v: 1, groupId, keyPackageRef, sponsorAccount, deadline, ...(recordedAt === undefined ? {} : { recordedAt }), status: status, ...(invitationId === undefined ? {} : { invitationId: invitationId }) };
61
+ }
62
+ function encodeManifest(record) {
63
+ return {
64
+ v: 1,
65
+ groupId: record.groupId,
66
+ keyPackageRef: record.keyPackageRef,
67
+ sponsorAccount: record.sponsorAccount,
68
+ deadline: record.deadline,
69
+ ...(record.recordedAt === undefined ? {} : { recordedAt: record.recordedAt }),
70
+ status: record.status,
71
+ ...(record.invitationId === undefined ? {} : { invitationId: record.invitationId }),
72
+ };
73
+ }
74
+ function view(tx) {
75
+ return tx.artifact(MANIFESTS);
76
+ }
77
+ export async function readManifest(tx, groupId, keyPackageRef) {
78
+ const key = manifestKey(groupId, keyPackageRef);
79
+ const raw = await view(tx).get(key);
80
+ return raw === undefined ? undefined : decodeManifest(key, raw);
81
+ }
82
+ export async function writeManifest(tx, record) {
83
+ await view(tx).put(manifestKey(record.groupId, record.keyPackageRef), encodeManifest(record));
84
+ }
85
+ /**
86
+ * Records `manifest` as `waiting`. A manifest for the same (group,
87
+ * KeyPackageRef) that is still waiting is replaced (a new deadline or
88
+ * sponsor); a fulfilled one is kept — that Welcome is already joined.
89
+ */
90
+ export async function recordManifest(tx, manifest) {
91
+ const current = await readManifest(tx, manifest.groupId, manifest.keyPackageRef);
92
+ if (current?.status === 'fulfilled')
93
+ return current;
94
+ const record = { v: 1, ...manifest, status: 'waiting' };
95
+ await writeManifest(tx, record);
96
+ return record;
97
+ }
98
+ /**
99
+ * Starting a forget of the own device: every WAITING manifest loses its `recordedAt`, so the Welcome of a request made
100
+ * before the forget can never end it (it is not an answer to a decision made after the forget), whatever the clock says.
101
+ * Rows are read loosely; one that does not read is left as it is.
102
+ */
103
+ export async function stripWaitingRequestTimes(tx) {
104
+ const v = view(tx);
105
+ for (const key of await v.keys()) {
106
+ const raw = (await v.get(key));
107
+ if (typeof raw !== 'object' || raw === null || Array.isArray(raw))
108
+ continue;
109
+ const { recordedAt, ...rest } = raw;
110
+ if (recordedAt !== undefined && rest.status === 'waiting')
111
+ await v.put(key, rest);
112
+ }
113
+ }
114
+ /** S9 teardown: the KeyPackageRefs of every manifest of `groupId` (keys are `<groupId>:<ref>`). */
115
+ export async function manifestRefsOfGroup(tx, groupId) {
116
+ const prefix = `${groupId}:`;
117
+ return (await view(tx).keys()).filter((k) => k.startsWith(prefix)).map((k) => k.slice(prefix.length));
118
+ }
119
+ /** S9 teardown: deletes every manifest of `groupId`. */
120
+ export async function purgeGroupManifests(tx, groupId) {
121
+ const prefix = `${groupId}:`;
122
+ for (const key of await view(tx).keys())
123
+ if (key.startsWith(prefix))
124
+ await view(tx).delete(key);
125
+ }
126
+ /**
127
+ * AC-WEL-1: `accept` only for a waiting manifest whose sponsor equals the
128
+ * Welcome's sponsor, processed before its deadline; `expired` when the
129
+ * deadline has passed (the caller marks it); `mismatch` when the sponsor
130
+ * differs; `none` without a waiting manifest.
131
+ */
132
+ export function matchManifest(manifest, candidate, nowMs) {
133
+ if (manifest === undefined || manifest.status !== 'waiting')
134
+ return 'none';
135
+ if (nowMs >= manifest.deadline)
136
+ return 'expired';
137
+ return manifest.sponsorAccount === candidate.sponsorAccount ? 'accept' : 'mismatch';
138
+ }
@@ -0,0 +1,16 @@
1
+ /**
2
+ * `invitations` module barrel (S5 inviter side; S6 the invitee side).
3
+ * The in-repo seam `client` imports through (architecture.md
4
+ * dependencies_allowed); the public types are re-exported from the package
5
+ * root by `client/index.ts`.
6
+ */
7
+ export { addProposalsFor, buildWelcomeRumors, createInvitationsService, DEFAULT_INVITE_RETENTION_MS, STAGED_ADD_LOOKUP_TIMEOUT_MS, hasStagedAdds, stagedAddLeafKeys, purgeGroupInvites, recipientsOfWelcome, stagedAddRecipients, decodeStoredWelcomes, encodeStoredWelcomes, toWelcomeOutcome, validateInvitees, WELCOME_COMMIT_TAG, welcomeCommitTagOf, type InvitationsDeps, type InvitationsService, type Invitee, type StoredWelcome, type WelcomeRecipient, type WelcomeOutcome, } from './invite.js';
8
+ export { decideProposal, defaultDecision, type PendingProposal, type ProposalCallback, type ProposalDecision } from './on-proposal.js';
9
+ export { isAuthorisedCommitter, mustQueue, nextQueueStep, queueBarrier, resolveProposals, stagedProposals, withoutProposals, type ProposalResolution, type QueueStep, type StagedProposals, } from './pending-proposal-policy.js';
10
+ export { DEFAULT_PROPOSAL_DEFERRAL_TIMEOUT_MS, DEFERRED_PROPOSALS_EXTENSION, deferralExpired, deleteDeferral, deleteExclusionEpochs, EXCLUDED_PROPOSALS_EXTENSION, exclusionsAt, planDeferrals, readExclusions, writeExclusion, writeExclusionSnapshot, type ExclusionRecord, type Exclusions, readDeferrals, writeDeferral, type DeferralPlan, type DeferralRecord, } from './proposal-deadline.js';
11
+ export { resolveInboxRelays, type InboxRelayDeps, type InboxRelayResolution } from './relay-planes.js';
12
+ export { carriesBranch, decideCompetingWelcome, judgeCompetingWelcome, otherLeafSignatureKeysOf, terminalClassOf, type CompetingBranch, type CompetingDecision, type CompetingGate, type CompetingVerdict, type CompetingWelcomePorts, type HeldBranch, type HeldScore, type KeepReason, type MissingEvidence, type RebaseRequest, type SwitchState, } from './competing-welcome.js';
13
+ export { createWelcomeService, decodeWelcomeRumor, purgeGroupInvitations, welcomeIdOf, type InvitationRecord, type InvitationStatus, type JoinEvidenceOfWelcome, type MaintenanceKind, MAX_MAINTENANCE_FAILURES, type PendingInvitation, type WelcomeService, type WelcomeServiceDeps, } from './welcome-processor.js';
14
+ export { manifestKey, manifestRefsOfGroup, matchManifest, purgeGroupManifests, recordManifest, stripWaitingRequestTimes, validateManifest, type ManifestMatch, type ManifestRecord, type ManifestStatus, type WelcomeManifestInput } from './expect-welcome.js';
15
+ export { attemptDeclineDelivery, buildDeclineRumor, type DeclineDeliveryDeps, type DeclineState, type DeclineStatus } from './decline.js';
16
+ export { handleKeyPackageOffer, listKeyPackageOffers, OFFERS_EXTENSION, purgeGroupOffers, sendKeyPackageOffer, validateOfferOptions, type KeyPackageOffer, type OfferDeps, } from './offers.js';
@@ -0,0 +1,16 @@
1
+ /**
2
+ * `invitations` module barrel (S5 inviter side; S6 the invitee side).
3
+ * The in-repo seam `client` imports through (architecture.md
4
+ * dependencies_allowed); the public types are re-exported from the package
5
+ * root by `client/index.ts`.
6
+ */
7
+ export { addProposalsFor, buildWelcomeRumors, createInvitationsService, DEFAULT_INVITE_RETENTION_MS, STAGED_ADD_LOOKUP_TIMEOUT_MS, hasStagedAdds, stagedAddLeafKeys, purgeGroupInvites, recipientsOfWelcome, stagedAddRecipients, decodeStoredWelcomes, encodeStoredWelcomes, toWelcomeOutcome, validateInvitees, WELCOME_COMMIT_TAG, welcomeCommitTagOf, } from './invite.js';
8
+ export { decideProposal, defaultDecision } from './on-proposal.js';
9
+ export { isAuthorisedCommitter, mustQueue, nextQueueStep, queueBarrier, resolveProposals, stagedProposals, withoutProposals, } from './pending-proposal-policy.js';
10
+ export { DEFAULT_PROPOSAL_DEFERRAL_TIMEOUT_MS, DEFERRED_PROPOSALS_EXTENSION, deferralExpired, deleteDeferral, deleteExclusionEpochs, EXCLUDED_PROPOSALS_EXTENSION, exclusionsAt, planDeferrals, readExclusions, writeExclusion, writeExclusionSnapshot, readDeferrals, writeDeferral, } from './proposal-deadline.js';
11
+ export { resolveInboxRelays } from './relay-planes.js';
12
+ export { carriesBranch, decideCompetingWelcome, judgeCompetingWelcome, otherLeafSignatureKeysOf, terminalClassOf, } from './competing-welcome.js';
13
+ export { createWelcomeService, decodeWelcomeRumor, purgeGroupInvitations, welcomeIdOf, MAX_MAINTENANCE_FAILURES, } from './welcome-processor.js';
14
+ export { manifestKey, manifestRefsOfGroup, matchManifest, purgeGroupManifests, recordManifest, stripWaitingRequestTimes, validateManifest } from './expect-welcome.js';
15
+ export { attemptDeclineDelivery, buildDeclineRumor } from './decline.js';
16
+ export { handleKeyPackageOffer, listKeyPackageOffers, OFFERS_EXTENSION, purgeGroupOffers, sendKeyPackageOffer, validateOfferOptions, } from './offers.js';
@@ -0,0 +1,303 @@
1
+ /**
2
+ * Inviter side of the invitation flow (AC-INVITE-1, AC-INVITE-2, AC-INVITE-5,
3
+ * AC-INVITE-6): invitee validation, the Add proposals and Welcome rumors of
4
+ * one invite commit, and the durable per-invitee Welcome delivery.
5
+ *
6
+ * The commit itself is an ordinary durable intent of the client pipeline
7
+ * (`client/pipeline.ts`): its record carries the invitees' KeyPackage events
8
+ * from the start and, from staging on, the Welcome rumors built from the
9
+ * engine's MLS Welcome — atomically with the commit envelope. Once a relay
10
+ * accepted the commit, the pipeline hands the rumors to this module
11
+ * ({@link InvitationsService.recordCommitted}): one `invites` record per
12
+ * commit, one delivery per invitee, each intent -> publish -> confirm:
13
+ *
14
+ * 1. resolve the invitee's inbox relays (`relay-planes.ts`); a transient
15
+ * lookup leaves the delivery `retryable` with nothing published;
16
+ * 2. gift-wrap the stored rumor (the seal is signed by the account key,
17
+ * outside any transaction) and store the wrap before publishing it;
18
+ * 3. publish; the classified outcome is written back after re-reading the
19
+ * record and checking the wrap is still the one published.
20
+ *
21
+ * Automatic retries re-publish the stored wrap byte-identically; only
22
+ * `retry()` (`group.retryWelcome`) re-wraps the same rumor — the invitee
23
+ * recognises the second copy of one Welcome (AC-WEL-2). Nothing here ever
24
+ * builds a commit. Deliveries run on the service's own serial queue, outside
25
+ * the group's operation queue: a remote signer waiting on its user must not
26
+ * stall the group.
27
+ */
28
+ import type { NostrEvent, Rumor } from '@941design/nostr-events/event';
29
+ import type { Signer } from '@941design/nostr-events/signer';
30
+ import type { Filter } from '@941design/nostr-events/event';
31
+ import type { RequestWithDeadlineResult } from '@941design/nostr-events/transport/contract';
32
+ import { type ClientState, type Proposal, type Welcome } from '@941design/marmot-engine/mls';
33
+ import { MarmotError } from '../shared/index.js';
34
+ import type { AccountStoreTx, Storable } from '../storage/index.js';
35
+ import { type InboxRelayDeps } from './relay-planes.js';
36
+ export interface Invitee {
37
+ /** The invitee's KeyPackageRef (hex) — `retryWelcome`'s `inviteeRef`. */
38
+ readonly inviteeRef: string;
39
+ readonly pubkey: string;
40
+ readonly keyPackageEventId: string;
41
+ readonly event: NostrEvent;
42
+ }
43
+ /**
44
+ * Validates the KeyPackage events of one `invite()` call, in order: the
45
+ * consumer verifier, then S4's selection rule (`selectKeyPackage` — kind,
46
+ * signature, credential/author binding, lifetime on the client clock, proof,
47
+ * baseline capabilities), then the group's own requirements (cipher suite,
48
+ * required capabilities). Any failure rejects the whole call with
49
+ * `invalid-options` before anything is recorded.
50
+ */
51
+ export declare function validateInvitees(keyPackages: unknown, opts: {
52
+ readonly verify: ((event: NostrEvent) => Promise<boolean>) | undefined;
53
+ readonly nowSeconds: number;
54
+ readonly state: ClientState;
55
+ }): Promise<Invitee[]>;
56
+ /** One Add proposal per invitee, in order. */
57
+ export declare function addProposalsFor(events: readonly NostrEvent[]): Proposal[];
58
+ /** Who a Welcome goes to. `keyPackageEventId` is absent when the KeyPackage event is not known (a staged Add whose event no relay has). */
59
+ export interface WelcomeRecipient {
60
+ readonly inviteeRef: string;
61
+ readonly pubkey: string;
62
+ readonly keyPackageEventId?: string;
63
+ }
64
+ /** Deadline of the one batched KeyPackage-event lookup for a commit's staged Adds: short, since a miss only drops the optional `e` tag. */
65
+ export declare const STAGED_ADD_LOOKUP_TIMEOUT_MS = 2000;
66
+ /** The leaf signature keys (hex) of the Adds staged in `state`: an own commit over them carries those Adds by reference. */
67
+ export declare function stagedAddLeafKeys(state: ClientState): Set<string>;
68
+ /** Whether `state` stages any Add proposal (an own commit over it admits a member). */
69
+ export declare function hasStagedAdds(state: ClientState): boolean;
70
+ /**
71
+ * The Welcome recipients of the Adds staged in `state`: account (the leaf
72
+ * credential's identity) and KeyPackageRef, plus the id of the kind-30443
73
+ * event that carried the KeyPackage — a staged proposal carries only the
74
+ * KeyPackage itself. ONE batched lookup on `relays` for every staged Add's
75
+ * account (one deadline), each result verified (the single KeyPackage-event
76
+ * validator, then `verify`) and matched to its Add by KeyPackageRef. When no
77
+ * relay has it (a rotated slot, a timeout, a failed lookup) the recipient has
78
+ * no event id and its Welcome carries no `e` tag: `e` names an event, and a
79
+ * made-up id would send other clients after a reference that does not exist;
80
+ * the invitee matches a Welcome by the KeyPackageRef in its secrets.
81
+ */
82
+ export declare function stagedAddRecipients(state: ClientState, opts: {
83
+ readonly relays: readonly string[];
84
+ readonly lookupTimeoutMs: number;
85
+ readonly request: (relays: string[], filter: Filter, opts: {
86
+ timeoutMs: number;
87
+ }) => Promise<RequestWithDeadlineResult>;
88
+ readonly verify: ((event: NostrEvent) => Promise<boolean>) | undefined;
89
+ }): Promise<WelcomeRecipient[]>;
90
+ /** The recipients among `candidates` the MLS Welcome actually holds a secret for (by KeyPackageRef), de-duplicated. */
91
+ export declare function recipientsOfWelcome(welcome: Welcome, candidates: readonly WelcomeRecipient[]): WelcomeRecipient[];
92
+ export interface StoredWelcome {
93
+ readonly inviteeRef: string;
94
+ readonly pubkey: string;
95
+ /** Absent when the KeyPackage event is unknown: the rumor then carries no `e` tag. */
96
+ readonly keyPackageEventId?: string;
97
+ /** The kind-`RUMOR_KINDS.WELCOME` rumor, authored by the inviter's account. */
98
+ readonly rumor: Rumor;
99
+ }
100
+ /** Name of the Welcome rumor tag carrying the digest of the commit the Welcome belongs to (epic marmot-welcome-race-joiner). */
101
+ export declare const WELCOME_COMMIT_TAG = "commit";
102
+ /**
103
+ * One Welcome rumor per invitee over the commit's single MLS Welcome (it holds
104
+ * a secret for every new member), each tagged with the group's relays after the
105
+ * commit, — when known — that invitee's KeyPackage event id (`e`), and the
106
+ * `['commit', <digest hex>]` tag: the lowercase hex `commitDigest` of the
107
+ * published commit's MLS bytes (`commit`, the bytes the pipeline publishes and
108
+ * `confirmRecord` digests). A joiner holding another Welcome for the same group
109
+ * needs that digest to rank the two branches the way the members do; the rumor
110
+ * id is recomputed over the tagged draft. The tag is appended last, so every
111
+ * other tag keeps its place and value.
112
+ */
113
+ export declare function buildWelcomeRumors(opts: {
114
+ readonly welcome: Welcome;
115
+ /** The encoded MLS message of the published commit (`encode(mlsMessageEncoder, commitMessage)`). */
116
+ readonly commit: Uint8Array;
117
+ readonly author: string;
118
+ readonly groupRelays: readonly string[];
119
+ readonly invitees: readonly WelcomeRecipient[];
120
+ }): StoredWelcome[];
121
+ /**
122
+ * The commit digest a Welcome rumor carries (`['commit', <64 lowercase hex>]`), or `undefined` when the rumor
123
+ * has no such tag, has more than one tag named `commit` (whatever their values), or its value is not 64
124
+ * lowercase hex. Total: never throws, for any tag order, extra tags and malformed input — an untagged
125
+ * (pre-epic or foreign) Welcome is an ordinary input, not an error. Entries after the value are ignored.
126
+ */
127
+ export declare function welcomeCommitTagOf(rumor: Rumor): string | undefined;
128
+ /** `Storable` codec of a staged commit record's Welcome list (the pipeline stores it; this module owns its shape). */
129
+ export declare function encodeStoredWelcomes(welcomes: readonly StoredWelcome[]): Storable;
130
+ export declare function decodeStoredWelcomes(where: string, raw: unknown): StoredWelcome[];
131
+ /**
132
+ * `declined` (AC-HYG-3): the invitee declined the Welcome — terminal: never
133
+ * re-published, automatically or by `retryWelcome`.
134
+ */
135
+ export type WelcomeDeliveryStatus = 'pending' | 'retryable' | 'delivered' | 'failed' | 'declined';
136
+ /** `InviteeDelivery.reason` of a `delivered` delivery whose invite commit a rewind abandoned: the invitee may hold a membership of a branch the group left. */
137
+ export declare const DELIVERED_ON_ABANDONED_BRANCH = "delivered-on-abandoned-branch";
138
+ export interface InviteeDelivery extends StoredWelcome {
139
+ /** The gift wrap last stored for publishing (kept once it may be live). */
140
+ readonly wrap?: NostrEvent;
141
+ /** Relays of the last publish attempt. */
142
+ readonly relays?: readonly string[];
143
+ readonly status: WelcomeDeliveryStatus;
144
+ /** Failed publishes (they count toward `maxPublishAttempts`). */
145
+ readonly attempts: number;
146
+ /** Consecutive timed-out relay-list lookups (backoff only — never toward `maxPublishAttempts`). */
147
+ readonly lookupRetries?: number;
148
+ readonly reason?: string;
149
+ /**
150
+ * Client clock (ms) of the delivery's last move to `delivered` or `declined` (AC-HYG-2's retention runs from it;
151
+ * absent on records written before it existed, which count from `committedAt`).
152
+ */
153
+ readonly settledAt?: number;
154
+ }
155
+ export interface InviteRecord {
156
+ readonly v: 1;
157
+ readonly inviteId: string;
158
+ readonly groupId: string;
159
+ readonly commitEventId: string;
160
+ /**
161
+ * The confirmation tag of the state the invite commit produced (the commit's node in the group's retained window),
162
+ * so a rewind that abandons that node can find the record without an event-id-to-node map. Absent on records
163
+ * written before it existed (those are never withdrawn automatically).
164
+ */
165
+ readonly commitTag?: string;
166
+ /** Client clock (ms) of the handoff. */
167
+ readonly committedAt: number;
168
+ readonly invitees: readonly InviteeDelivery[];
169
+ }
170
+ /** Default `ClientOptions.inviteRetentionMs` (AC-HYG-2): 30 days. */
171
+ export declare const DEFAULT_INVITE_RETENTION_MS: number;
172
+ /** Decodes the record stored under `key` (`<groupId>/<inviteId>`); its header must name the same group and invite. */
173
+ export declare function decodeInviteRecord(key: string, raw: unknown): InviteRecord;
174
+ /**
175
+ * S9 teardown (`abandon()`/`destroy()`): deletes the `invites` records of
176
+ * `groupId` — its Welcome deliveries end with the group. Its records are
177
+ * found by key (AC-HYG-2), whether they decode or not; a record still keyed
178
+ * `<inviteId>` (written before AC-HYG-2, not migrated yet) is matched on its
179
+ * raw `groupId` field.
180
+ */
181
+ export declare function purgeGroupInvites(tx: AccountStoreTx, groupId: string): Promise<void>;
182
+ /** One invitee's Welcome delivery, as `invite()` / `retryWelcome()` report it (AC-INVITE-2). */
183
+ export interface WelcomeOutcome {
184
+ readonly inviteeRef: string;
185
+ readonly pubkey: string;
186
+ /** The KeyPackage event the Welcome names; absent for a staged Add whose event no relay had. */
187
+ readonly keyPackageEventId?: string;
188
+ /**
189
+ * `retryable` deliveries are re-attempted automatically; `failed` ones only by `retryWelcome`; `declined` ones
190
+ * (the invitee declined, AC-HYG-3) never again.
191
+ */
192
+ readonly status: 'delivered' | 'retryable' | 'failed' | 'declined';
193
+ /** Relays of the last publish attempt (empty when nothing was published). */
194
+ readonly relays: readonly string[];
195
+ /** Why it is not delivered (`nip17-timed-out`, `no-inbox-relays`, `publish-failed`, `publish-refused`, …). */
196
+ readonly reason?: string;
197
+ /** `no-inbox-relays`, `publish-failed` (retryable) or `send-rejected` (failed). */
198
+ readonly error?: MarmotError;
199
+ }
200
+ export declare function toWelcomeOutcome(delivery: WelcomeRecipient & {
201
+ readonly status: WelcomeDeliveryStatus;
202
+ readonly reason?: string;
203
+ readonly relays?: readonly string[];
204
+ }, cause?: unknown): WelcomeOutcome;
205
+ export interface InvitationsDeps extends InboxRelayDeps {
206
+ readonly clock: {
207
+ now(): number;
208
+ };
209
+ readonly timers: {
210
+ set(callback: () => void, ms: number): unknown;
211
+ clear(handle: unknown): void;
212
+ };
213
+ /** Failed publishes after which a Welcome delivery goes `failed`. */
214
+ readonly maxPublishAttempts: number;
215
+ /** The account-key signer (seals the gift wrap), every member already routed through the re-entrancy guard. */
216
+ readonly signer: Signer;
217
+ /** `AccountStore.transaction`, already routed through the re-entrancy guard. */
218
+ transaction<T>(fn: (tx: AccountStoreTx) => Promise<T> | T): Promise<T>;
219
+ isDisposed(): boolean;
220
+ /** Called once a delivery went `failed` (after the write committed): the application may `retryWelcome` it. */
221
+ readonly onFailed?: (failure: {
222
+ readonly groupId: string;
223
+ readonly inviteeRef: string;
224
+ readonly reason: string;
225
+ }) => void;
226
+ /** AC-HYG-2: how long (client-clock ms) a record whose every delivery is delivered or declined is kept after it settled. */
227
+ readonly inviteRetentionMs: number;
228
+ /** AC-HYG-3: called once per delivery that went `declined` (after the write committed). */
229
+ readonly onDeclined?: (declined: {
230
+ readonly groupId: string;
231
+ readonly inviteeRef: string;
232
+ }) => void;
233
+ /** Called once per delivery {@link InvitationsService.restoreCommit} put back to `pending` (after the write committed). */
234
+ readonly onRestored?: (restored: {
235
+ readonly groupId: string;
236
+ readonly inviteeRef: string;
237
+ }) => void;
238
+ }
239
+ export interface InvitationsService {
240
+ /** Hands a relay-accepted invite commit's Welcomes over for delivery; a record already present keeps its progress. */
241
+ recordCommitted(input: {
242
+ readonly inviteId: string;
243
+ readonly groupId: string;
244
+ readonly commitEventId: string;
245
+ /** The confirmation tag of the state the commit produced (see {@link InviteRecord.commitTag}). */
246
+ readonly commitTag?: string;
247
+ readonly welcomes: readonly StoredWelcome[];
248
+ }): Promise<void>;
249
+ /**
250
+ * The group's invite commits a rewind may have to withdraw or restore: `open` (a delivery still `pending` or
251
+ * `retryable`) and/or `withdrawn` (a delivery `failed` with reason `commit-withdrawn`), `delivered` (a delivery already published and not yet
252
+ * marked) and/or `deliveredAbandoned` (marked {@link DELIVERED_ON_ABANDONED_BRANCH}). `commitTag` is absent for a
253
+ * record written before it was stored.
254
+ */
255
+ trackedCommits(groupId: string): Promise<ReadonlyArray<{
256
+ readonly commitEventId: string;
257
+ readonly commitTag?: string;
258
+ readonly open: boolean;
259
+ readonly withdrawn: boolean;
260
+ readonly delivered: boolean;
261
+ readonly deliveredAbandoned: boolean;
262
+ }>>;
263
+ /**
264
+ * The invite commit `commitEventId` was withdrawn by a rewind (its branch lost a same-epoch race): every delivery of
265
+ * its record that is still `pending` or `retryable` goes `failed` with reason `commit-withdrawn`, its backoff timer
266
+ * is cleared, and `onFailed` fires for each. A delivery already `delivered`, `failed` or `declined` is untouched. A
267
+ * publish already in flight is not recallable: if its relay accepts it the delivery reads `delivered` (the invitee
268
+ * then decides the Welcome like any competing one); a refused or failed one leaves `failed`/`commit-withdrawn` as it
269
+ * was. A delivery already `delivered` stays `delivered` and is marked `reason: 'delivered-on-abandoned-branch'` (once; a restore of the commit
270
+ * clears the mark silently). The mark is silent unless the caller says `signalDelivered`: only the caller knows whether something follows the
271
+ * withdrawal that re-delivers (a re-drive's new Welcome, an approval's re-issue) -- `onFailed` then fires once with that reason for the invitees
272
+ * that may be stranded on the abandoned branch. Idempotent. If the commit returns to the canonical path later, {@link restoreCommit} puts the deliveries back;
273
+ * to send one on request in the meantime, `retryWelcome` (re-sends the stored Welcome; no new commit) is the remedy,
274
+ * not a re-invite.
275
+ */
276
+ withdrawCommit(groupId: string, commitEventId: string, opts?: {
277
+ readonly signalDelivered?: boolean;
278
+ }): Promise<void>;
279
+ /**
280
+ * The commit returned to the canonical path (equivocation credit, a longer branch): its deliveries that
281
+ * {@link withdrawCommit} failed (`failed`/`commit-withdrawn` only) go back to `pending` and are delivered in the
282
+ * background; `onRestored` fires for each. Idempotent; a delivery failed for another reason is untouched.
283
+ */
284
+ restoreCommit(groupId: string, commitEventId: string): Promise<void>;
285
+ /** One delivery pass over every undelivered invitee of the invite; the outcome of every invitee (empty when no record exists). */
286
+ deliver(groupId: string, inviteId: string): Promise<readonly WelcomeOutcome[]>;
287
+ deliverInBackground(groupId: string, inviteId: string): void;
288
+ /** Re-wraps and re-publishes `inviteeRef`'s Welcome of the group's latest invite naming it — never a new commit. */
289
+ retry(groupId: string, inviteeRef: string): Promise<WelcomeOutcome>;
290
+ /** Resumes, in the background, every unfinished delivery of the group's invites (after a reload); prunes its expired records first. */
291
+ resumeGroup(groupId: string): void;
292
+ /**
293
+ * AC-HYG-3: native bookkeeping of an inbound DECLINE rumor (additive — the inbox still delivers it to
294
+ * `onApplicationRumor`). `rumor.pubkey` is the seal author (NIP-59 unwrap binds the two). Every delivery of the
295
+ * content's group whose invitee is that author and whose Welcome has the content's welcome id (`welcomeIdOf`:
296
+ * SHA-256 of the MLS Welcome bytes) goes `declined` — terminal, no further publish — in ONE transaction, and
297
+ * `onDeclined` fires once for each delivery that changed. Any other author, an unknown welcome id or a malformed
298
+ * content changes nothing. A delivery already `declined` (a redelivered or repeated decline) is not reported again.
299
+ */
300
+ recordDecline(rumor: Rumor): Promise<void>;
301
+ dispose(): void;
302
+ }
303
+ export declare function createInvitationsService(deps: InvitationsDeps): InvitationsService;