@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.
- package/CHANGELOG.md +709 -0
- package/LICENSE +21 -0
- package/README.md +33 -2
- package/dist/account/admin.d.ts +72 -0
- package/dist/account/admin.js +209 -0
- package/dist/account/device-deps.d.ts +379 -0
- package/dist/account/device-deps.js +36 -0
- package/dist/account/device-lineage.d.ts +199 -0
- package/dist/account/device-lineage.js +390 -0
- package/dist/account/device-registry.d.ts +93 -0
- package/dist/account/device-registry.js +1290 -0
- package/dist/account/device-rotation.d.ts +61 -0
- package/dist/account/device-rotation.js +827 -0
- package/dist/account/enrolment.d.ts +339 -0
- package/dist/account/enrolment.js +1247 -0
- package/dist/account/identity-proof.d.ts +79 -0
- package/dist/account/identity-proof.js +264 -0
- package/dist/account/index.d.ts +17 -0
- package/dist/account/index.js +16 -0
- package/dist/account/restore-rotation.d.ts +21 -0
- package/dist/account/restore-rotation.js +22 -0
- package/dist/account/same-account-authorization.d.ts +86 -0
- package/dist/account/same-account-authorization.js +180 -0
- package/dist/account/teardown.d.ts +127 -0
- package/dist/account/teardown.js +856 -0
- package/dist/client/before-create-group.d.ts +18 -0
- package/dist/client/before-create-group.js +65 -0
- package/dist/client/before-publish-hooks.d.ts +121 -0
- package/dist/client/before-publish-hooks.js +180 -0
- package/dist/client/client-config.d.ts +42 -0
- package/dist/client/client-config.js +13 -0
- package/dist/client/commit-redrive.d.ts +68 -0
- package/dist/client/commit-redrive.js +221 -0
- package/dist/client/component-update.d.ts +43 -0
- package/dist/client/component-update.js +53 -0
- package/dist/client/confirm-hooks.d.ts +50 -0
- package/dist/client/confirm-hooks.js +59 -0
- package/dist/client/create-client.d.ts +1022 -0
- package/dist/client/create-client.js +1125 -0
- package/dist/client/group-disband.d.ts +28 -0
- package/dist/client/group-disband.js +64 -0
- package/dist/client/group-history.d.ts +435 -0
- package/dist/client/group-history.js +1295 -0
- package/dist/client/group-profile.d.ts +31 -0
- package/dist/client/group-profile.js +62 -0
- package/dist/client/group-records.d.ts +485 -0
- package/dist/client/group-records.js +1034 -0
- package/dist/client/group-removal.d.ts +36 -0
- package/dist/client/group-removal.js +127 -0
- package/dist/client/group-remove-member.d.ts +49 -0
- package/dist/client/group-remove-member.js +163 -0
- package/dist/client/group-runtime.d.ts +388 -0
- package/dist/client/group-runtime.js +2701 -0
- package/dist/client/group-snapshot.d.ts +98 -0
- package/dist/client/group-snapshot.js +453 -0
- package/dist/client/history-pages.d.ts +107 -0
- package/dist/client/history-pages.js +194 -0
- package/dist/client/inbox-send.d.ts +19 -0
- package/dist/client/inbox-send.js +71 -0
- package/dist/client/index.d.ts +21 -0
- package/dist/client/index.js +13 -0
- package/dist/client/ingest.d.ts +82 -0
- package/dist/client/ingest.js +1550 -0
- package/dist/client/lifecycle-events.d.ts +63 -0
- package/dist/client/lifecycle-events.js +35 -0
- package/dist/client/opaque-candidates.d.ts +81 -0
- package/dist/client/opaque-candidates.js +169 -0
- package/dist/client/own-change-outbox.d.ts +66 -0
- package/dist/client/own-change-outbox.js +156 -0
- package/dist/client/pending-leaf.d.ts +116 -0
- package/dist/client/pending-leaf.js +378 -0
- package/dist/client/permissions.d.ts +9 -0
- package/dist/client/permissions.js +12 -0
- package/dist/client/pipeline.d.ts +554 -0
- package/dist/client/pipeline.js +3545 -0
- package/dist/client/reentrancy-guard.d.ts +96 -0
- package/dist/client/reentrancy-guard.js +153 -0
- package/dist/client/rekey.d.ts +58 -0
- package/dist/client/rekey.js +149 -0
- package/dist/client/transport-policy.d.ts +181 -0
- package/dist/client/transport-policy.js +214 -0
- package/dist/history/equivocation.d.ts +55 -0
- package/dist/history/equivocation.js +113 -0
- package/dist/history/fencing.d.ts +25 -0
- package/dist/history/fencing.js +61 -0
- package/dist/history/hex.d.ts +3 -0
- package/dist/history/hex.js +10 -0
- package/dist/history/index.d.ts +73 -0
- package/dist/history/index.js +31 -0
- package/dist/history/notifications.d.ts +270 -0
- package/dist/history/notifications.js +264 -0
- package/dist/history/ordering-key.d.ts +24 -0
- package/dist/history/ordering-key.js +101 -0
- package/dist/history/own-change-fork.d.ts +112 -0
- package/dist/history/own-change-fork.js +196 -0
- package/dist/history/own-change.d.ts +106 -0
- package/dist/history/own-change.js +146 -0
- package/dist/history/policy.d.ts +48 -0
- package/dist/history/policy.js +52 -0
- package/dist/history/retained-window.d.ts +215 -0
- package/dist/history/retained-window.js +565 -0
- package/dist/inbox/demux.d.ts +90 -0
- package/dist/inbox/demux.js +78 -0
- package/dist/inbox/handler-registry.d.ts +42 -0
- package/dist/inbox/handler-registry.js +37 -0
- package/dist/inbox/index.d.ts +11 -0
- package/dist/inbox/index.js +10 -0
- package/dist/inbox/seen-set.d.ts +82 -0
- package/dist/inbox/seen-set.js +202 -0
- package/dist/inbox/subscription.d.ts +236 -0
- package/dist/inbox/subscription.js +644 -0
- package/dist/index.d.ts +10 -0
- package/dist/index.js +9 -0
- package/dist/invitations/competing-welcome.d.ts +223 -0
- package/dist/invitations/competing-welcome.js +128 -0
- package/dist/invitations/decline.d.ts +61 -0
- package/dist/invitations/decline.js +143 -0
- package/dist/invitations/expect-welcome.d.ts +66 -0
- package/dist/invitations/expect-welcome.js +138 -0
- package/dist/invitations/index.d.ts +16 -0
- package/dist/invitations/index.js +16 -0
- package/dist/invitations/invite.d.ts +303 -0
- package/dist/invitations/invite.js +966 -0
- package/dist/invitations/offers.d.ts +79 -0
- package/dist/invitations/offers.js +115 -0
- package/dist/invitations/on-proposal.d.ts +47 -0
- package/dist/invitations/on-proposal.js +40 -0
- package/dist/invitations/pending-proposal-policy.d.ts +52 -0
- package/dist/invitations/pending-proposal-policy.js +139 -0
- package/dist/invitations/proposal-deadline.d.ts +133 -0
- package/dist/invitations/proposal-deadline.js +164 -0
- package/dist/invitations/relay-planes.d.ts +43 -0
- package/dist/invitations/relay-planes.js +70 -0
- package/dist/invitations/welcome-processor.d.ts +253 -0
- package/dist/invitations/welcome-processor.js +1180 -0
- package/dist/key-packages/device-key.d.ts +131 -0
- package/dist/key-packages/device-key.js +272 -0
- package/dist/key-packages/device-rotation-records.d.ts +83 -0
- package/dist/key-packages/device-rotation-records.js +173 -0
- package/dist/key-packages/group-refs.d.ts +40 -0
- package/dist/key-packages/group-refs.js +79 -0
- package/dist/key-packages/index.d.ts +18 -0
- package/dist/key-packages/index.js +18 -0
- package/dist/key-packages/key-package-ref.d.ts +16 -0
- package/dist/key-packages/key-package-ref.js +21 -0
- package/dist/key-packages/observation-stream.d.ts +4 -0
- package/dist/key-packages/observation-stream.js +120 -0
- package/dist/key-packages/offer-rumor.d.ts +26 -0
- package/dist/key-packages/offer-rumor.js +69 -0
- package/dist/key-packages/publisher.d.ts +174 -0
- package/dist/key-packages/publisher.js +1247 -0
- package/dist/key-packages/select-key-package.d.ts +24 -0
- package/dist/key-packages/select-key-package.js +90 -0
- package/dist/key-packages/slot-manager.d.ts +167 -0
- package/dist/key-packages/slot-manager.js +327 -0
- package/dist/key-packages/validate-key-package-event.d.ts +3 -0
- package/dist/key-packages/validate-key-package-event.js +49 -0
- package/dist/media/cache.d.ts +14 -0
- package/dist/media/cache.js +10 -0
- package/dist/media/index.d.ts +52 -0
- package/dist/media/index.js +71 -0
- package/dist/mls.d.ts +15 -0
- package/dist/mls.js +15 -0
- package/dist/shared/account-pubkey.d.ts +4 -0
- package/dist/shared/account-pubkey.js +10 -0
- package/dist/shared/errors.d.ts +21 -0
- package/dist/shared/errors.js +85 -0
- package/dist/shared/hex.d.ts +4 -0
- package/dist/shared/hex.js +13 -0
- package/dist/shared/index.d.ts +14 -0
- package/dist/shared/index.js +14 -0
- package/dist/shared/kinds.d.ts +8 -0
- package/dist/shared/kinds.js +28 -0
- package/dist/shared/publish-classification.d.ts +26 -0
- package/dist/shared/publish-classification.js +31 -0
- package/dist/storage/envelope.d.ts +39 -0
- package/dist/storage/envelope.js +201 -0
- package/dist/storage/index.d.ts +227 -0
- package/dist/storage/index.js +459 -0
- package/dist/storage/indexeddb/idb-types.d.ts +68 -0
- package/dist/storage/indexeddb/idb-types.js +1 -0
- package/dist/storage/indexeddb/index.d.ts +17 -0
- package/dist/storage/indexeddb/index.js +141 -0
- package/dist/storage/lease.d.ts +41 -0
- package/dist/storage/lease.js +117 -0
- package/dist/storage/memory/deterministic-signer.d.ts +27 -0
- package/dist/storage/memory/deterministic-signer.js +65 -0
- package/dist/storage/memory/index.d.ts +32 -0
- package/dist/storage/memory/index.js +87 -0
- package/dist/storage/memory/lock-manager.d.ts +8 -0
- package/dist/storage/memory/lock-manager.js +71 -0
- package/package.json +66 -3
|
@@ -0,0 +1,966 @@
|
|
|
1
|
+
import { getEventHash } from '@941design/nostr-events/event';
|
|
2
|
+
import { wrap as giftWrap } from '@941design/nostr-events/gift-wrap';
|
|
3
|
+
import { ADDRESSABLE_KEY_PACKAGE_KIND, commitDigest, createWelcomeRumor, evaluateKeyPackageForGroup, getCredentialPubkey, getKeyPackage, getWelcomeKeyPackageRefs, } from '@941design/marmot-engine/core';
|
|
4
|
+
import { defaultProposalTypes } from '@941design/marmot-engine/mls';
|
|
5
|
+
import { computeKeyPackageRefHex, selectKeyPackage, validateKeyPackageEvent } from '../key-packages/index.js';
|
|
6
|
+
import { classifyPublish, hexOfBytes, isHex64, isMarmotError, MarmotError, RUMOR_KINDS } from '../shared/index.js';
|
|
7
|
+
import { resolveInboxRelays } from './relay-planes.js';
|
|
8
|
+
import { welcomeIdOf } from './welcome-processor.js';
|
|
9
|
+
function invalid(message, details) {
|
|
10
|
+
return new MarmotError('invalid-options', `invite: ${message}`, { details });
|
|
11
|
+
}
|
|
12
|
+
// Group-scoped eligibility reasons of `evaluateKeyPackageForGroup` that block an Add. "already a
|
|
13
|
+
// member" does not (a same-account Add is a new device, ADR-003); lifetime is checked by
|
|
14
|
+
// `selectKeyPackage` on the client clock rather than here on the wall clock.
|
|
15
|
+
const BLOCKING_REASON = /^(cipher suite|missing|undecodable)/;
|
|
16
|
+
/**
|
|
17
|
+
* Validates the KeyPackage events of one `invite()` call, in order: the
|
|
18
|
+
* consumer verifier, then S4's selection rule (`selectKeyPackage` — kind,
|
|
19
|
+
* signature, credential/author binding, lifetime on the client clock, proof,
|
|
20
|
+
* baseline capabilities), then the group's own requirements (cipher suite,
|
|
21
|
+
* required capabilities). Any failure rejects the whole call with
|
|
22
|
+
* `invalid-options` before anything is recorded.
|
|
23
|
+
*/
|
|
24
|
+
export async function validateInvitees(keyPackages, opts) {
|
|
25
|
+
if (!Array.isArray(keyPackages) || keyPackages.length === 0) {
|
|
26
|
+
throw invalid('keyPackages must be a non-empty array of KeyPackage events', { reason: 'no-invitees' });
|
|
27
|
+
}
|
|
28
|
+
const invitees = [];
|
|
29
|
+
const refs = new Set();
|
|
30
|
+
for (const candidate of keyPackages) {
|
|
31
|
+
if (typeof candidate !== 'object' || candidate === null || typeof candidate.id !== 'string') {
|
|
32
|
+
throw invalid('every keyPackages entry must be a KeyPackage event', { reason: 'invalid-keypackage' });
|
|
33
|
+
}
|
|
34
|
+
const event = candidate;
|
|
35
|
+
if (opts.verify !== undefined) {
|
|
36
|
+
let trusted;
|
|
37
|
+
try {
|
|
38
|
+
trusted = await opts.verify(event);
|
|
39
|
+
}
|
|
40
|
+
catch {
|
|
41
|
+
trusted = false;
|
|
42
|
+
}
|
|
43
|
+
if (!trusted)
|
|
44
|
+
throw invalid(`KeyPackage event ${event.id} was rejected by the verifier`, { reason: 'verifier', eventId: event.id });
|
|
45
|
+
}
|
|
46
|
+
const selected = await selectKeyPackage([event], opts.nowSeconds);
|
|
47
|
+
if (selected === undefined)
|
|
48
|
+
throw invalid(`KeyPackage event ${event.id} is not a valid, current KeyPackage`, { reason: 'invalid-keypackage', eventId: event.id });
|
|
49
|
+
const blocking = evaluateKeyPackageForGroup(opts.state, event).reasons.filter((r) => BLOCKING_REASON.test(r));
|
|
50
|
+
if (blocking.length > 0)
|
|
51
|
+
throw invalid(`KeyPackage event ${event.id} cannot join this group`, { reason: 'ineligible', eventId: event.id, reasons: blocking });
|
|
52
|
+
if (refs.has(selected.keyPackageRef))
|
|
53
|
+
throw invalid(`KeyPackage ${selected.keyPackageRef} is listed twice`, { reason: 'duplicate', eventId: event.id });
|
|
54
|
+
refs.add(selected.keyPackageRef);
|
|
55
|
+
invitees.push({ inviteeRef: selected.keyPackageRef, pubkey: selected.pubkey, keyPackageEventId: selected.eventId, event });
|
|
56
|
+
}
|
|
57
|
+
return invitees;
|
|
58
|
+
}
|
|
59
|
+
/** One Add proposal per invitee, in order. */
|
|
60
|
+
export function addProposalsFor(events) {
|
|
61
|
+
return events.map((event) => ({ proposalType: defaultProposalTypes.add, add: { keyPackage: getKeyPackage(event) } }));
|
|
62
|
+
}
|
|
63
|
+
/** Deadline of the one batched KeyPackage-event lookup for a commit's staged Adds: short, since a miss only drops the optional `e` tag. */
|
|
64
|
+
export const STAGED_ADD_LOOKUP_TIMEOUT_MS = 2_000;
|
|
65
|
+
function stagedAddKeyPackages(state) {
|
|
66
|
+
const out = [];
|
|
67
|
+
for (const { proposal } of Object.values(state.unappliedProposals)) {
|
|
68
|
+
if (proposal.proposalType === defaultProposalTypes.add && 'add' in proposal)
|
|
69
|
+
out.push(proposal.add.keyPackage);
|
|
70
|
+
}
|
|
71
|
+
return out;
|
|
72
|
+
}
|
|
73
|
+
/** The leaf signature keys (hex) of the Adds staged in `state`: an own commit over them carries those Adds by reference. */
|
|
74
|
+
export function stagedAddLeafKeys(state) {
|
|
75
|
+
return new Set(stagedAddKeyPackages(state).map((keyPackage) => toHex(keyPackage.leafNode.signaturePublicKey)));
|
|
76
|
+
}
|
|
77
|
+
/** Whether `state` stages any Add proposal (an own commit over it admits a member). */
|
|
78
|
+
export function hasStagedAdds(state) {
|
|
79
|
+
return stagedAddKeyPackages(state).length > 0;
|
|
80
|
+
}
|
|
81
|
+
function toHex(bytes) {
|
|
82
|
+
return Array.from(bytes, (b) => b.toString(16).padStart(2, '0')).join('');
|
|
83
|
+
}
|
|
84
|
+
/**
|
|
85
|
+
* The Welcome recipients of the Adds staged in `state`: account (the leaf
|
|
86
|
+
* credential's identity) and KeyPackageRef, plus the id of the kind-30443
|
|
87
|
+
* event that carried the KeyPackage — a staged proposal carries only the
|
|
88
|
+
* KeyPackage itself. ONE batched lookup on `relays` for every staged Add's
|
|
89
|
+
* account (one deadline), each result verified (the single KeyPackage-event
|
|
90
|
+
* validator, then `verify`) and matched to its Add by KeyPackageRef. When no
|
|
91
|
+
* relay has it (a rotated slot, a timeout, a failed lookup) the recipient has
|
|
92
|
+
* no event id and its Welcome carries no `e` tag: `e` names an event, and a
|
|
93
|
+
* made-up id would send other clients after a reference that does not exist;
|
|
94
|
+
* the invitee matches a Welcome by the KeyPackageRef in its secrets.
|
|
95
|
+
*/
|
|
96
|
+
export async function stagedAddRecipients(state, opts) {
|
|
97
|
+
const adds = [];
|
|
98
|
+
for (const keyPackage of stagedAddKeyPackages(state)) {
|
|
99
|
+
let pubkey;
|
|
100
|
+
try {
|
|
101
|
+
pubkey = getCredentialPubkey(keyPackage.leafNode.credential);
|
|
102
|
+
}
|
|
103
|
+
catch {
|
|
104
|
+
continue; // not a Marmot credential: no account to deliver to
|
|
105
|
+
}
|
|
106
|
+
adds.push({ inviteeRef: await computeKeyPackageRefHex(keyPackage), pubkey });
|
|
107
|
+
}
|
|
108
|
+
const eventIds = new Map();
|
|
109
|
+
if (adds.length > 0 && opts.relays.length > 0) {
|
|
110
|
+
try {
|
|
111
|
+
const authors = [...new Set(adds.map((a) => a.pubkey))];
|
|
112
|
+
const result = await opts.request([...opts.relays], { kinds: [ADDRESSABLE_KEY_PACKAGE_KIND], authors }, { timeoutMs: opts.lookupTimeoutMs });
|
|
113
|
+
const wanted = new Set(adds.map((a) => a.inviteeRef));
|
|
114
|
+
for (const event of result.events) {
|
|
115
|
+
const candidate = validateKeyPackageEvent(event);
|
|
116
|
+
if (candidate === undefined)
|
|
117
|
+
continue;
|
|
118
|
+
const ref = await computeKeyPackageRefHex(candidate);
|
|
119
|
+
if (!wanted.has(ref) || eventIds.has(ref))
|
|
120
|
+
continue;
|
|
121
|
+
if (opts.verify !== undefined && !(await opts.verify(event).catch(() => false)))
|
|
122
|
+
continue;
|
|
123
|
+
eventIds.set(ref, event.id);
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
catch {
|
|
127
|
+
// No event ids: the Welcomes go out without `e` (see above).
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
return adds.map((a) => {
|
|
131
|
+
const keyPackageEventId = eventIds.get(a.inviteeRef);
|
|
132
|
+
return keyPackageEventId === undefined ? a : { ...a, keyPackageEventId };
|
|
133
|
+
});
|
|
134
|
+
}
|
|
135
|
+
/** The recipients among `candidates` the MLS Welcome actually holds a secret for (by KeyPackageRef), de-duplicated. */
|
|
136
|
+
export function recipientsOfWelcome(welcome, candidates) {
|
|
137
|
+
const refs = new Set(getWelcomeKeyPackageRefs(welcome).map(toHex));
|
|
138
|
+
const seen = new Set();
|
|
139
|
+
return candidates.filter((c) => refs.has(c.inviteeRef) && !seen.has(c.inviteeRef) && (seen.add(c.inviteeRef), true));
|
|
140
|
+
}
|
|
141
|
+
// Stands in for the event id `createWelcomeRumor` insists on; the tag is dropped again (and the id recomputed).
|
|
142
|
+
const NO_EVENT_ID = '0'.repeat(64);
|
|
143
|
+
/** Name of the Welcome rumor tag carrying the digest of the commit the Welcome belongs to (epic marmot-welcome-race-joiner). */
|
|
144
|
+
export const WELCOME_COMMIT_TAG = 'commit';
|
|
145
|
+
/**
|
|
146
|
+
* One Welcome rumor per invitee over the commit's single MLS Welcome (it holds
|
|
147
|
+
* a secret for every new member), each tagged with the group's relays after the
|
|
148
|
+
* commit, — when known — that invitee's KeyPackage event id (`e`), and the
|
|
149
|
+
* `['commit', <digest hex>]` tag: the lowercase hex `commitDigest` of the
|
|
150
|
+
* published commit's MLS bytes (`commit`, the bytes the pipeline publishes and
|
|
151
|
+
* `confirmRecord` digests). A joiner holding another Welcome for the same group
|
|
152
|
+
* needs that digest to rank the two branches the way the members do; the rumor
|
|
153
|
+
* id is recomputed over the tagged draft. The tag is appended last, so every
|
|
154
|
+
* other tag keeps its place and value.
|
|
155
|
+
*/
|
|
156
|
+
export function buildWelcomeRumors(opts) {
|
|
157
|
+
if (opts.commit.length === 0)
|
|
158
|
+
throw new Error('a Welcome rumor needs the published commit bytes for its commit tag');
|
|
159
|
+
const commitTag = [WELCOME_COMMIT_TAG, hexOfBytes(commitDigest(opts.commit))];
|
|
160
|
+
return opts.invitees.map((invitee) => {
|
|
161
|
+
const eventId = invitee.keyPackageEventId;
|
|
162
|
+
const built = createWelcomeRumor({ welcome: opts.welcome, author: opts.author, groupRelays: [...opts.groupRelays], keyPackageEventId: eventId ?? NO_EVENT_ID });
|
|
163
|
+
const tags = [...built.tags.filter((t) => eventId !== undefined || t[0] !== 'e'), commitTag];
|
|
164
|
+
const draft = { kind: built.kind, pubkey: built.pubkey, created_at: built.created_at, content: built.content, tags };
|
|
165
|
+
const rumor = { ...draft, id: getEventHash(draft) };
|
|
166
|
+
return { inviteeRef: invitee.inviteeRef, pubkey: invitee.pubkey, ...(eventId === undefined ? {} : { keyPackageEventId: eventId }), rumor };
|
|
167
|
+
});
|
|
168
|
+
}
|
|
169
|
+
/**
|
|
170
|
+
* The commit digest a Welcome rumor carries (`['commit', <64 lowercase hex>]`), or `undefined` when the rumor
|
|
171
|
+
* has no such tag, has more than one tag named `commit` (whatever their values), or its value is not 64
|
|
172
|
+
* lowercase hex. Total: never throws, for any tag order, extra tags and malformed input — an untagged
|
|
173
|
+
* (pre-epic or foreign) Welcome is an ordinary input, not an error. Entries after the value are ignored.
|
|
174
|
+
*/
|
|
175
|
+
export function welcomeCommitTagOf(rumor) {
|
|
176
|
+
const tags = rumor?.tags;
|
|
177
|
+
if (!Array.isArray(tags))
|
|
178
|
+
return undefined;
|
|
179
|
+
let found;
|
|
180
|
+
let count = 0;
|
|
181
|
+
for (const tag of tags) {
|
|
182
|
+
if (!Array.isArray(tag) || tag[0] !== WELCOME_COMMIT_TAG)
|
|
183
|
+
continue;
|
|
184
|
+
count += 1;
|
|
185
|
+
found = tag[1];
|
|
186
|
+
}
|
|
187
|
+
return count === 1 && isHex64(found) ? found : undefined;
|
|
188
|
+
}
|
|
189
|
+
function isObject(value) {
|
|
190
|
+
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
191
|
+
}
|
|
192
|
+
function malformed(where, detail) {
|
|
193
|
+
return new MarmotError('store-failed', `${where}: malformed record (${detail})`, { details: { where, malformed: true } });
|
|
194
|
+
}
|
|
195
|
+
function decodeRumor(where, raw) {
|
|
196
|
+
if (!isObject(raw))
|
|
197
|
+
throw malformed(where, 'rumor not an object');
|
|
198
|
+
const { id, pubkey, kind, created_at: createdAt, tags, content } = raw;
|
|
199
|
+
if (typeof id !== 'string' || typeof pubkey !== 'string' || kind !== RUMOR_KINDS.WELCOME || typeof createdAt !== 'number' || typeof content !== 'string') {
|
|
200
|
+
throw malformed(where, 'rumor fields');
|
|
201
|
+
}
|
|
202
|
+
if (!Array.isArray(tags) || !tags.every((t) => Array.isArray(t) && t.every((v) => typeof v === 'string')))
|
|
203
|
+
throw malformed(where, 'rumor tags');
|
|
204
|
+
return { id, pubkey, kind, created_at: createdAt, tags: tags, content };
|
|
205
|
+
}
|
|
206
|
+
function decodeStoredWelcome(where, raw) {
|
|
207
|
+
if (!isObject(raw))
|
|
208
|
+
throw malformed(where, 'welcome not an object');
|
|
209
|
+
const { inviteeRef, pubkey, keyPackageEventId } = raw;
|
|
210
|
+
if (typeof inviteeRef !== 'string' || typeof pubkey !== 'string' || (keyPackageEventId !== undefined && typeof keyPackageEventId !== 'string'))
|
|
211
|
+
throw malformed(where, 'welcome fields');
|
|
212
|
+
return { inviteeRef, pubkey, ...(keyPackageEventId === undefined ? {} : { keyPackageEventId }), rumor: decodeRumor(where, raw.rumor) };
|
|
213
|
+
}
|
|
214
|
+
function encodeStoredWelcome(welcome) {
|
|
215
|
+
return {
|
|
216
|
+
inviteeRef: welcome.inviteeRef,
|
|
217
|
+
pubkey: welcome.pubkey,
|
|
218
|
+
...(welcome.keyPackageEventId === undefined ? {} : { keyPackageEventId: welcome.keyPackageEventId }),
|
|
219
|
+
rumor: { ...welcome.rumor, tags: welcome.rumor.tags.map((t) => [...t]) },
|
|
220
|
+
};
|
|
221
|
+
}
|
|
222
|
+
/** `Storable` codec of a staged commit record's Welcome list (the pipeline stores it; this module owns its shape). */
|
|
223
|
+
export function encodeStoredWelcomes(welcomes) {
|
|
224
|
+
return welcomes.map(encodeStoredWelcome);
|
|
225
|
+
}
|
|
226
|
+
export function decodeStoredWelcomes(where, raw) {
|
|
227
|
+
if (!Array.isArray(raw))
|
|
228
|
+
throw malformed(where, 'welcomes not an array');
|
|
229
|
+
return raw.map((w) => decodeStoredWelcome(where, w));
|
|
230
|
+
}
|
|
231
|
+
/** `InviteeDelivery.reason` of a `delivered` delivery whose invite commit a rewind abandoned: the invitee may hold a membership of a branch the group left. */
|
|
232
|
+
export const DELIVERED_ON_ABANDONED_BRANCH = 'delivered-on-abandoned-branch';
|
|
233
|
+
const INVITES = 'invites';
|
|
234
|
+
const DELIVERY_STATUSES = new Set(['pending', 'retryable', 'delivered', 'failed', 'declined']);
|
|
235
|
+
/** Default `ClientOptions.inviteRetentionMs` (AC-HYG-2): 30 days. */
|
|
236
|
+
export const DEFAULT_INVITE_RETENTION_MS = 30 * 24 * 60 * 60 * 1000;
|
|
237
|
+
/**
|
|
238
|
+
* The `invites` key of a record (AC-HYG-2): `<groupId>/<inviteId>`. A group's records are found from the key list
|
|
239
|
+
* alone — loading, retrying or declining in group G reads G's records and no other group's.
|
|
240
|
+
*/
|
|
241
|
+
function inviteKey(groupId, inviteId) {
|
|
242
|
+
return `${groupId}/${inviteId}`;
|
|
243
|
+
}
|
|
244
|
+
/** The parts of a current key; `undefined` for a key without them (a record keyed `<inviteId>`, as written before AC-HYG-2). */
|
|
245
|
+
function parseInviteKey(key) {
|
|
246
|
+
const slash = key.lastIndexOf('/');
|
|
247
|
+
if (slash <= 0 || slash === key.length - 1)
|
|
248
|
+
return undefined;
|
|
249
|
+
return { groupId: key.slice(0, slash), inviteId: key.slice(slash + 1) };
|
|
250
|
+
}
|
|
251
|
+
/**
|
|
252
|
+
* AC-HYG-2 migration: re-keys every record still stored under its pre-AC-HYG-2 key `<inviteId>` (`InviteRecord.v: 1`
|
|
253
|
+
* as epic-marmot-client wrote it) to `<groupId>/<inviteId>`, in the caller's transaction, and returns the key list
|
|
254
|
+
* as it stands afterwards. The value is kept as stored. A record already present under the new key wins (it carries
|
|
255
|
+
* the newer progress) and the old copy is dropped. A row without a string `groupId` and its own `inviteId` cannot be
|
|
256
|
+
* addressed and is left where it is, as before.
|
|
257
|
+
*/
|
|
258
|
+
async function migrateLegacyKeys(view) {
|
|
259
|
+
const keys = await view.keys();
|
|
260
|
+
let moved = false;
|
|
261
|
+
for (const key of keys) {
|
|
262
|
+
if (parseInviteKey(key) !== undefined)
|
|
263
|
+
continue;
|
|
264
|
+
const raw = await view.get(key);
|
|
265
|
+
if (!isObject(raw) || typeof raw.groupId !== 'string' || raw.groupId.length === 0 || raw.inviteId !== key)
|
|
266
|
+
continue;
|
|
267
|
+
const target = inviteKey(raw.groupId, key);
|
|
268
|
+
if ((await view.get(target)) === undefined)
|
|
269
|
+
await view.put(target, raw);
|
|
270
|
+
await view.delete(key);
|
|
271
|
+
moved = true;
|
|
272
|
+
}
|
|
273
|
+
return moved ? view.keys() : keys;
|
|
274
|
+
}
|
|
275
|
+
/** The keys of `groupId`'s records among `keys`. */
|
|
276
|
+
function keysOfGroup(keys, groupId) {
|
|
277
|
+
return keys.filter((key) => parseInviteKey(key)?.groupId === groupId);
|
|
278
|
+
}
|
|
279
|
+
/** When the record last settled: the latest delivery settle time, never before the handoff. */
|
|
280
|
+
function settledAtOf(record) {
|
|
281
|
+
return Math.max(record.committedAt, ...record.invitees.map((i) => i.settledAt ?? record.committedAt));
|
|
282
|
+
}
|
|
283
|
+
/**
|
|
284
|
+
* AC-HYG-2: whether `record` is past its retention and nothing still needs it. Only a record whose every delivery is
|
|
285
|
+
* `delivered` or `declined` is pruned — a `pending`/`retryable` delivery is still auto-retried and a `failed` one
|
|
286
|
+
* awaits `retryWelcome` — and only once it settled more than `retentionMs` ago (client clock): until then a
|
|
287
|
+
* courtesy `retryWelcome` and decline matching (AC-HYG-3) still find it.
|
|
288
|
+
*/
|
|
289
|
+
function prunable(record, nowMs, retentionMs) {
|
|
290
|
+
return record.invitees.every((i) => i.status === 'delivered' || i.status === 'declined') && settledAtOf(record) + retentionMs < nowMs;
|
|
291
|
+
}
|
|
292
|
+
/**
|
|
293
|
+
* Deletes `groupId`'s prunable records. Best-effort: a record that does not decode, or cannot be read at all, is
|
|
294
|
+
* left as stored — retention never decides whether an operation of the group succeeds.
|
|
295
|
+
*/
|
|
296
|
+
async function pruneGroup(view, keys, groupId, nowMs, retentionMs) {
|
|
297
|
+
for (const key of keysOfGroup(keys, groupId)) {
|
|
298
|
+
let record;
|
|
299
|
+
try {
|
|
300
|
+
record = await readDecodable(view, key);
|
|
301
|
+
}
|
|
302
|
+
catch {
|
|
303
|
+
continue;
|
|
304
|
+
}
|
|
305
|
+
if (record !== undefined && prunable(record, nowMs, retentionMs))
|
|
306
|
+
await view.delete(key);
|
|
307
|
+
}
|
|
308
|
+
}
|
|
309
|
+
function decodeWrap(where, raw) {
|
|
310
|
+
if (raw === undefined)
|
|
311
|
+
return undefined;
|
|
312
|
+
if (!isObject(raw))
|
|
313
|
+
throw malformed(where, 'wrap not an object');
|
|
314
|
+
const { id, pubkey, kind, created_at: createdAt, tags, content, sig } = raw;
|
|
315
|
+
if (typeof id !== 'string' || typeof pubkey !== 'string' || typeof kind !== 'number' || typeof createdAt !== 'number' || typeof content !== 'string' || typeof sig !== 'string' || !Array.isArray(tags)) {
|
|
316
|
+
throw malformed(where, 'wrap fields');
|
|
317
|
+
}
|
|
318
|
+
return { id, pubkey, kind, created_at: createdAt, tags: tags, content, sig };
|
|
319
|
+
}
|
|
320
|
+
function decodeInvitee(where, raw) {
|
|
321
|
+
const base = decodeStoredWelcome(where, raw);
|
|
322
|
+
const r = raw;
|
|
323
|
+
if (typeof r.status !== 'string' || !DELIVERY_STATUSES.has(r.status))
|
|
324
|
+
throw malformed(where, 'status');
|
|
325
|
+
if (typeof r.attempts !== 'number')
|
|
326
|
+
throw malformed(where, 'attempts');
|
|
327
|
+
if (r.lookupRetries !== undefined && typeof r.lookupRetries !== 'number')
|
|
328
|
+
throw malformed(where, 'lookupRetries');
|
|
329
|
+
if (r.reason !== undefined && typeof r.reason !== 'string')
|
|
330
|
+
throw malformed(where, 'reason');
|
|
331
|
+
if (r.relays !== undefined && (!Array.isArray(r.relays) || !r.relays.every((x) => typeof x === 'string')))
|
|
332
|
+
throw malformed(where, 'relays');
|
|
333
|
+
if (r.settledAt !== undefined && typeof r.settledAt !== 'number')
|
|
334
|
+
throw malformed(where, 'settledAt');
|
|
335
|
+
const wrap = decodeWrap(where, r.wrap);
|
|
336
|
+
return {
|
|
337
|
+
...base,
|
|
338
|
+
...(wrap === undefined ? {} : { wrap }),
|
|
339
|
+
...(r.relays === undefined ? {} : { relays: [...r.relays] }),
|
|
340
|
+
status: r.status,
|
|
341
|
+
attempts: r.attempts,
|
|
342
|
+
...(r.lookupRetries === undefined ? {} : { lookupRetries: r.lookupRetries }),
|
|
343
|
+
...(r.reason === undefined ? {} : { reason: r.reason }),
|
|
344
|
+
...(r.settledAt === undefined ? {} : { settledAt: r.settledAt }),
|
|
345
|
+
};
|
|
346
|
+
}
|
|
347
|
+
/** Decodes the record stored under `key` (`<groupId>/<inviteId>`); its header must name the same group and invite. */
|
|
348
|
+
export function decodeInviteRecord(key, raw) {
|
|
349
|
+
const where = `invites/${key}`;
|
|
350
|
+
const parts = parseInviteKey(key);
|
|
351
|
+
if (parts === undefined || !isObject(raw) || raw.v !== 1 || raw.inviteId !== parts.inviteId || raw.groupId !== parts.groupId)
|
|
352
|
+
throw malformed(where, 'header');
|
|
353
|
+
const { commitEventId, commitTag, committedAt, invitees } = raw;
|
|
354
|
+
if (typeof commitEventId !== 'string' || typeof committedAt !== 'number' || !Array.isArray(invitees))
|
|
355
|
+
throw malformed(where, 'fields');
|
|
356
|
+
if (commitTag !== undefined && typeof commitTag !== 'string')
|
|
357
|
+
throw malformed(where, 'commitTag');
|
|
358
|
+
return {
|
|
359
|
+
v: 1,
|
|
360
|
+
inviteId: parts.inviteId,
|
|
361
|
+
groupId: parts.groupId,
|
|
362
|
+
commitEventId,
|
|
363
|
+
...(commitTag === undefined ? {} : { commitTag }),
|
|
364
|
+
committedAt,
|
|
365
|
+
invitees: invitees.map((i) => decodeInvitee(where, i)),
|
|
366
|
+
};
|
|
367
|
+
}
|
|
368
|
+
function encodeInviteRecord(record) {
|
|
369
|
+
return {
|
|
370
|
+
v: 1,
|
|
371
|
+
inviteId: record.inviteId,
|
|
372
|
+
groupId: record.groupId,
|
|
373
|
+
commitEventId: record.commitEventId,
|
|
374
|
+
...(record.commitTag === undefined ? {} : { commitTag: record.commitTag }),
|
|
375
|
+
committedAt: record.committedAt,
|
|
376
|
+
invitees: record.invitees.map((i) => ({
|
|
377
|
+
...encodeStoredWelcome(i),
|
|
378
|
+
...(i.wrap === undefined ? {} : { wrap: { ...i.wrap, tags: i.wrap.tags.map((t) => [...t]) } }),
|
|
379
|
+
...(i.relays === undefined ? {} : { relays: [...i.relays] }),
|
|
380
|
+
status: i.status,
|
|
381
|
+
attempts: i.attempts,
|
|
382
|
+
...(i.lookupRetries === undefined ? {} : { lookupRetries: i.lookupRetries }),
|
|
383
|
+
...(i.reason === undefined ? {} : { reason: i.reason }),
|
|
384
|
+
...(i.settledAt === undefined ? {} : { settledAt: i.settledAt }),
|
|
385
|
+
})),
|
|
386
|
+
};
|
|
387
|
+
}
|
|
388
|
+
/**
|
|
389
|
+
* S9 teardown (`abandon()`/`destroy()`): deletes the `invites` records of
|
|
390
|
+
* `groupId` — its Welcome deliveries end with the group. Its records are
|
|
391
|
+
* found by key (AC-HYG-2), whether they decode or not; a record still keyed
|
|
392
|
+
* `<inviteId>` (written before AC-HYG-2, not migrated yet) is matched on its
|
|
393
|
+
* raw `groupId` field.
|
|
394
|
+
*/
|
|
395
|
+
export async function purgeGroupInvites(tx, groupId) {
|
|
396
|
+
const view = tx.artifact(INVITES);
|
|
397
|
+
for (const key of await view.keys()) {
|
|
398
|
+
const parts = parseInviteKey(key);
|
|
399
|
+
if (parts !== undefined) {
|
|
400
|
+
if (parts.groupId === groupId)
|
|
401
|
+
await view.delete(key);
|
|
402
|
+
continue;
|
|
403
|
+
}
|
|
404
|
+
const raw = await view.get(key);
|
|
405
|
+
if (isObject(raw) && raw.groupId === groupId)
|
|
406
|
+
await view.delete(key);
|
|
407
|
+
}
|
|
408
|
+
}
|
|
409
|
+
async function readInvite(view, key) {
|
|
410
|
+
const raw = await view.get(key);
|
|
411
|
+
return raw === undefined ? undefined : decodeInviteRecord(key, raw);
|
|
412
|
+
}
|
|
413
|
+
/**
|
|
414
|
+
* The record under `key`, or `undefined` when there is none or it does not decode (a malformed record is skipped by
|
|
415
|
+
* the callers that scan a group). A storage failure is NOT a malformed record: it propagates, so the caller's
|
|
416
|
+
* operation fails transiently and is retried rather than concluding the record is not there.
|
|
417
|
+
*/
|
|
418
|
+
async function readDecodable(view, key) {
|
|
419
|
+
const raw = await view.get(key);
|
|
420
|
+
if (raw === undefined)
|
|
421
|
+
return undefined;
|
|
422
|
+
try {
|
|
423
|
+
return decodeInviteRecord(key, raw);
|
|
424
|
+
}
|
|
425
|
+
catch {
|
|
426
|
+
return undefined;
|
|
427
|
+
}
|
|
428
|
+
}
|
|
429
|
+
/** The content of a DECLINE rumor (`decline.ts` `buildDeclineRumor`): `{ v: 1, welcome, groupId }`; `undefined` otherwise. */
|
|
430
|
+
function parseDeclineContent(content) {
|
|
431
|
+
let parsed;
|
|
432
|
+
try {
|
|
433
|
+
parsed = JSON.parse(content);
|
|
434
|
+
}
|
|
435
|
+
catch {
|
|
436
|
+
return undefined;
|
|
437
|
+
}
|
|
438
|
+
if (!isObject(parsed) || parsed.v !== 1 || typeof parsed.welcome !== 'string' || typeof parsed.groupId !== 'string')
|
|
439
|
+
return undefined;
|
|
440
|
+
if (parsed.welcome.length === 0 || parsed.groupId.length === 0)
|
|
441
|
+
return undefined;
|
|
442
|
+
return { welcomeId: parsed.welcome, groupId: parsed.groupId };
|
|
443
|
+
}
|
|
444
|
+
export function toWelcomeOutcome(delivery, cause) {
|
|
445
|
+
const status = delivery.status === 'pending' ? 'retryable' : delivery.status;
|
|
446
|
+
const reason = delivery.status === 'pending' ? (delivery.reason ?? 'not-attempted') : delivery.reason;
|
|
447
|
+
const base = {
|
|
448
|
+
inviteeRef: delivery.inviteeRef,
|
|
449
|
+
pubkey: delivery.pubkey,
|
|
450
|
+
...(delivery.keyPackageEventId === undefined ? {} : { keyPackageEventId: delivery.keyPackageEventId }),
|
|
451
|
+
status,
|
|
452
|
+
relays: Object.freeze([...(delivery.relays ?? [])]),
|
|
453
|
+
};
|
|
454
|
+
if (status === 'delivered' || status === 'declined')
|
|
455
|
+
return base;
|
|
456
|
+
const details = { inviteeRef: delivery.inviteeRef, reason };
|
|
457
|
+
const opts = (d) => (cause === undefined ? { details: d } : { details: d, cause });
|
|
458
|
+
const error = reason === 'no-inbox-relays'
|
|
459
|
+
? new MarmotError('no-inbox-relays', `Welcome for ${delivery.inviteeRef}: the invitee has no resolvable inbox relay`, opts(details))
|
|
460
|
+
: status === 'failed'
|
|
461
|
+
? new MarmotError('send-rejected', `Welcome for ${delivery.inviteeRef} failed (${reason ?? 'unknown'})`, opts(details))
|
|
462
|
+
: new MarmotError('publish-failed', `Welcome for ${delivery.inviteeRef} is not delivered yet (${reason ?? 'unknown'})`, opts({ ...details, retryable: true }));
|
|
463
|
+
return { ...base, ...(reason === undefined ? {} : { reason }), error };
|
|
464
|
+
}
|
|
465
|
+
class SerialQueue {
|
|
466
|
+
#tail = Promise.resolve();
|
|
467
|
+
run(task) {
|
|
468
|
+
const result = this.#tail.then(task, task);
|
|
469
|
+
this.#tail = result.catch(() => undefined);
|
|
470
|
+
return result;
|
|
471
|
+
}
|
|
472
|
+
}
|
|
473
|
+
function backoffMs(count) {
|
|
474
|
+
return Math.min(1000 * 2 ** Math.max(0, count - 1), 60_000);
|
|
475
|
+
}
|
|
476
|
+
function withoutReason(delivery) {
|
|
477
|
+
const { reason: _reason, ...rest } = delivery;
|
|
478
|
+
return rest;
|
|
479
|
+
}
|
|
480
|
+
export function createInvitationsService(deps) {
|
|
481
|
+
const queue = new SerialQueue();
|
|
482
|
+
const timers = new Map();
|
|
483
|
+
let disposed = false;
|
|
484
|
+
/** This client re-keyed every pre-AC-HYG-2 record (a committed migration): later transactions skip the check. */
|
|
485
|
+
let migrated = false;
|
|
486
|
+
function assertLive() {
|
|
487
|
+
if (disposed || deps.isDisposed())
|
|
488
|
+
throw new MarmotError('disposed', 'Welcome delivery aborted: client has been disposed');
|
|
489
|
+
}
|
|
490
|
+
function stops(error) {
|
|
491
|
+
return disposed || deps.isDisposed() || isMarmotError(error, 'disposed') || isMarmotError(error, 'no-lease');
|
|
492
|
+
}
|
|
493
|
+
function schedule(key, attempts, run) {
|
|
494
|
+
if (disposed || deps.isDisposed() || timers.has(key))
|
|
495
|
+
return;
|
|
496
|
+
const handle = deps.timers.set(() => {
|
|
497
|
+
timers.delete(key);
|
|
498
|
+
if (!disposed && !deps.isDisposed())
|
|
499
|
+
run();
|
|
500
|
+
}, backoffMs(attempts));
|
|
501
|
+
timers.set(key, handle);
|
|
502
|
+
}
|
|
503
|
+
/**
|
|
504
|
+
* One account transaction over the `invites` artifact. Until a migration committed on this client, it first
|
|
505
|
+
* re-keys the records written before AC-HYG-2 (so every record is found by its group); `keys` is the key list
|
|
506
|
+
* the transaction sees.
|
|
507
|
+
*/
|
|
508
|
+
function invitesTx(fn) {
|
|
509
|
+
const migrating = !migrated;
|
|
510
|
+
return deps
|
|
511
|
+
.transaction(async (tx) => {
|
|
512
|
+
const view = tx.artifact(INVITES);
|
|
513
|
+
let listed = migrating ? await migrateLegacyKeys(view) : undefined;
|
|
514
|
+
return fn(view, async () => (listed ??= await view.keys()));
|
|
515
|
+
})
|
|
516
|
+
.then((result) => {
|
|
517
|
+
if (migrating)
|
|
518
|
+
migrated = true;
|
|
519
|
+
return result;
|
|
520
|
+
});
|
|
521
|
+
}
|
|
522
|
+
/**
|
|
523
|
+
* AC-HYG-2's retention pass for `groupId`, in its own transaction apart from the operation that triggers it (load,
|
|
524
|
+
* handoff, retry, decline). Best-effort: any failure is dropped and the group's next such operation tries again, so
|
|
525
|
+
* a record the store cannot read back never blocks a Welcome delivery.
|
|
526
|
+
*/
|
|
527
|
+
async function pruneBestEffort(groupId) {
|
|
528
|
+
try {
|
|
529
|
+
await invitesTx(async (view, keys) => pruneGroup(view, await keys(), groupId, deps.clock.now(), deps.inviteRetentionMs));
|
|
530
|
+
}
|
|
531
|
+
catch {
|
|
532
|
+
// dropped: retried at the group's next load, handoff, retry or decline
|
|
533
|
+
}
|
|
534
|
+
}
|
|
535
|
+
function readRecord(key) {
|
|
536
|
+
return invitesTx((view) => readInvite(view, key));
|
|
537
|
+
}
|
|
538
|
+
/**
|
|
539
|
+
* Re-reads the record and applies `change` to one invitee in one account
|
|
540
|
+
* transaction; `change` returning `undefined` leaves it as stored. Returns
|
|
541
|
+
* the invitee as stored afterwards, or `undefined` when it no longer exists.
|
|
542
|
+
* A `declined` delivery is never changed (AC-HYG-3: terminal) — whatever an
|
|
543
|
+
* attempt in flight when the decline landed would have written back.
|
|
544
|
+
*/
|
|
545
|
+
function updateInvitee(key, inviteeRef, change) {
|
|
546
|
+
return invitesTx(async (view) => {
|
|
547
|
+
const record = await readInvite(view, key);
|
|
548
|
+
const index = record?.invitees.findIndex((i) => i.inviteeRef === inviteeRef) ?? -1;
|
|
549
|
+
if (record === undefined || index < 0)
|
|
550
|
+
return undefined;
|
|
551
|
+
const current = record.invitees[index];
|
|
552
|
+
if (current.status === 'declined')
|
|
553
|
+
return current;
|
|
554
|
+
const changed = change(current);
|
|
555
|
+
if (changed === undefined)
|
|
556
|
+
return current;
|
|
557
|
+
// AC-HYG-2: the retention of a settled delivery runs from its (last) move to `delivered`.
|
|
558
|
+
const next = changed.status === 'delivered' && current.status !== 'delivered' ? { ...changed, settledAt: deps.clock.now() } : changed;
|
|
559
|
+
const invitees = [...record.invitees];
|
|
560
|
+
invitees[index] = next;
|
|
561
|
+
await view.put(key, encodeInviteRecord({ ...record, invitees }));
|
|
562
|
+
return next;
|
|
563
|
+
});
|
|
564
|
+
}
|
|
565
|
+
function scheduleRetry(key, attempts) {
|
|
566
|
+
schedule(`invite:${key}`, attempts, () => deliverInBackground(key));
|
|
567
|
+
}
|
|
568
|
+
function isFinal(delivery) {
|
|
569
|
+
return delivery.status === 'delivered' || delivery.status === 'failed' || delivery.status === 'declined';
|
|
570
|
+
}
|
|
571
|
+
/**
|
|
572
|
+
* One delivery attempt for one invitee. Returns what the caller reports:
|
|
573
|
+
* the invitee as stored afterwards — except for a `retry` of an already
|
|
574
|
+
* delivered Welcome (a courtesy re-send), whose own outcome is reported
|
|
575
|
+
* while the durable record stays `delivered` (nothing is re-attempted
|
|
576
|
+
* automatically for it). A `declined` delivery is never attempted.
|
|
577
|
+
*/
|
|
578
|
+
async function attempt(key, inviteeRef, mode) {
|
|
579
|
+
assertLive();
|
|
580
|
+
const record = await readRecord(key);
|
|
581
|
+
const stored = record?.invitees.find((i) => i.inviteeRef === inviteeRef);
|
|
582
|
+
if (record === undefined || stored === undefined)
|
|
583
|
+
return undefined;
|
|
584
|
+
if ((mode === 'auto' && isFinal(stored)) || stored.status === 'declined')
|
|
585
|
+
return stored;
|
|
586
|
+
const redelivery = mode === 'retry' && stored.status === 'delivered';
|
|
587
|
+
const keepsDelivered = (current) => redelivery && current.status === 'delivered';
|
|
588
|
+
// Set by an update that moved the invitee to `failed` (the `welcomeFailed` event fires once the write committed).
|
|
589
|
+
let failedNow;
|
|
590
|
+
const fail = (current, reason, extra = {}) => {
|
|
591
|
+
if (current.status !== 'failed')
|
|
592
|
+
failedNow = reason;
|
|
593
|
+
return { ...current, ...extra, status: 'failed', reason };
|
|
594
|
+
};
|
|
595
|
+
const reportFailure = () => {
|
|
596
|
+
if (failedNow !== undefined)
|
|
597
|
+
deps.onFailed?.({ groupId: record.groupId, inviteeRef, reason: failedNow });
|
|
598
|
+
};
|
|
599
|
+
assertLive();
|
|
600
|
+
const resolution = await resolveInboxRelays(deps, stored.pubkey);
|
|
601
|
+
assertLive();
|
|
602
|
+
if (resolution.kind !== 'relays') {
|
|
603
|
+
const transient = resolution.kind === 'transient';
|
|
604
|
+
const updated = await updateInvitee(key, inviteeRef, (current) => {
|
|
605
|
+
if ((mode === 'auto' && isFinal(current)) || keepsDelivered(current))
|
|
606
|
+
return undefined;
|
|
607
|
+
// A timed-out lookup is an unknown, never a publish attempt: it does not count toward
|
|
608
|
+
// maxPublishAttempts and stays retryable for as long as it lasts (AC-INVITE-5).
|
|
609
|
+
return transient
|
|
610
|
+
? { ...current, status: 'retryable', lookupRetries: (current.lookupRetries ?? 0) + 1, reason: resolution.reason }
|
|
611
|
+
: fail(current, 'no-inbox-relays');
|
|
612
|
+
});
|
|
613
|
+
reportFailure();
|
|
614
|
+
if (redelivery)
|
|
615
|
+
return transient ? { ...stored, status: 'retryable', reason: resolution.reason } : { ...stored, status: 'failed', reason: 'no-inbox-relays' };
|
|
616
|
+
if (transient && updated?.status === 'retryable')
|
|
617
|
+
scheduleRetry(key, updated.lookupRetries ?? 1);
|
|
618
|
+
return updated;
|
|
619
|
+
}
|
|
620
|
+
const relays = [...resolution.relays];
|
|
621
|
+
let wrap = stored.wrap;
|
|
622
|
+
if (mode === 'retry' || wrap === undefined) {
|
|
623
|
+
// Signed outside any transaction (a remote signer may wait on its user).
|
|
624
|
+
const fresh = await giftWrap({ senderSigner: deps.signer, recipientPubkey: stored.pubkey, rumor: stored.rumor });
|
|
625
|
+
assertLive();
|
|
626
|
+
const installed = await updateInvitee(key, inviteeRef, (current) => {
|
|
627
|
+
// A wrap stored meanwhile may already be live: keep publishing that one.
|
|
628
|
+
if (mode === 'auto' && (current.wrap !== undefined || current.status === 'failed'))
|
|
629
|
+
return undefined;
|
|
630
|
+
const { lookupRetries: _lookupRetries, ...rest } = withoutReason(current);
|
|
631
|
+
return { ...rest, wrap: fresh, relays, status: keepsDelivered(current) ? 'delivered' : 'pending', attempts: mode === 'retry' ? 0 : current.attempts };
|
|
632
|
+
});
|
|
633
|
+
// Declined meanwhile (AC-HYG-3): nothing more is published.
|
|
634
|
+
if (installed?.wrap === undefined || installed.status === 'declined')
|
|
635
|
+
return installed;
|
|
636
|
+
wrap = installed.wrap;
|
|
637
|
+
}
|
|
638
|
+
else {
|
|
639
|
+
// A reused stored wrap: the delivery may have been declined while its inbox relays were resolved (AC-HYG-3,
|
|
640
|
+
// terminal) — re-read right before publishing, as the new-wrap branch does through its install.
|
|
641
|
+
const current = (await readRecord(key))?.invitees.find((i) => i.inviteeRef === inviteeRef);
|
|
642
|
+
// A commit withdrawn meanwhile (`withdrawCommit`) went `failed`: its Welcome is not published either.
|
|
643
|
+
if (current === undefined || current.status === 'declined' || current.status === 'failed')
|
|
644
|
+
return current;
|
|
645
|
+
}
|
|
646
|
+
assertLive();
|
|
647
|
+
let responses;
|
|
648
|
+
try {
|
|
649
|
+
responses = await deps.transport.publish(relays, wrap);
|
|
650
|
+
}
|
|
651
|
+
catch {
|
|
652
|
+
responses = undefined; // a thrown network error is transient
|
|
653
|
+
}
|
|
654
|
+
// A client disposed meanwhile records nothing more: the next client resumes from the stored wrap.
|
|
655
|
+
assertLive();
|
|
656
|
+
const outcome = responses === undefined ? 'retryable' : classifyPublish(relays, responses).outcome;
|
|
657
|
+
const published = wrap;
|
|
658
|
+
const updated = await updateInvitee(key, inviteeRef, (current) => {
|
|
659
|
+
// Replaced meanwhile (a retry re-wrapped it): that attempt reports its own outcome.
|
|
660
|
+
if (current.wrap?.id !== published.id)
|
|
661
|
+
return undefined;
|
|
662
|
+
if (outcome === 'accepted')
|
|
663
|
+
return { ...withoutReason(current), relays, status: 'delivered' };
|
|
664
|
+
if (keepsDelivered(current))
|
|
665
|
+
return undefined;
|
|
666
|
+
// Withdrawn while this publish was in flight and not accepted: stays failed, not retried.
|
|
667
|
+
if (mode === 'auto' && current.status === 'failed' && current.reason === 'commit-withdrawn')
|
|
668
|
+
return undefined;
|
|
669
|
+
if (outcome === 'terminal')
|
|
670
|
+
return fail(current, 'publish-refused', { relays });
|
|
671
|
+
const attempts = current.attempts + 1;
|
|
672
|
+
return attempts >= deps.maxPublishAttempts
|
|
673
|
+
? fail(current, 'max-attempts', { relays, attempts })
|
|
674
|
+
: { ...current, relays, status: 'retryable', attempts, reason: 'publish-failed' };
|
|
675
|
+
});
|
|
676
|
+
reportFailure();
|
|
677
|
+
if (redelivery && updated?.status !== 'declined') {
|
|
678
|
+
const base = { ...stored, relays };
|
|
679
|
+
if (outcome === 'accepted')
|
|
680
|
+
return { ...withoutReason(base), status: 'delivered' };
|
|
681
|
+
return outcome === 'terminal' ? { ...base, status: 'failed', reason: 'publish-refused' } : { ...base, status: 'retryable', reason: 'publish-failed' };
|
|
682
|
+
}
|
|
683
|
+
if (updated?.status === 'retryable')
|
|
684
|
+
scheduleRetry(key, updated.attempts);
|
|
685
|
+
return updated;
|
|
686
|
+
}
|
|
687
|
+
async function deliverAll(key) {
|
|
688
|
+
const record = await readRecord(key);
|
|
689
|
+
if (record === undefined)
|
|
690
|
+
return [];
|
|
691
|
+
const outcomes = [];
|
|
692
|
+
for (const invitee of record.invitees) {
|
|
693
|
+
let result;
|
|
694
|
+
try {
|
|
695
|
+
result = await attempt(key, invitee.inviteeRef, 'auto');
|
|
696
|
+
}
|
|
697
|
+
catch (error) {
|
|
698
|
+
if (stops(error))
|
|
699
|
+
throw error;
|
|
700
|
+
// One invitee's failure (a signer or store error) never costs the others their
|
|
701
|
+
// attempt, nor the caller its per-invitee report: this one is retried on the backoff.
|
|
702
|
+
scheduleRetry(key, invitee.attempts + 1);
|
|
703
|
+
outcomes.push(toWelcomeOutcome({ ...invitee, status: 'retryable', reason: 'delivery-error' }, error));
|
|
704
|
+
continue;
|
|
705
|
+
}
|
|
706
|
+
outcomes.push(toWelcomeOutcome(result ?? invitee));
|
|
707
|
+
}
|
|
708
|
+
return outcomes;
|
|
709
|
+
}
|
|
710
|
+
function deliverInBackground(key) {
|
|
711
|
+
if (disposed || deps.isDisposed())
|
|
712
|
+
return;
|
|
713
|
+
queue.run(() => deliverAll(key)).catch((error) => {
|
|
714
|
+
if (!stops(error))
|
|
715
|
+
scheduleRetry(key, 1);
|
|
716
|
+
});
|
|
717
|
+
}
|
|
718
|
+
return {
|
|
719
|
+
async recordCommitted({ inviteId, groupId, commitEventId, commitTag, welcomes }) {
|
|
720
|
+
await invitesTx(async (view) => {
|
|
721
|
+
const key = inviteKey(groupId, inviteId);
|
|
722
|
+
if ((await view.get(key)) !== undefined)
|
|
723
|
+
return;
|
|
724
|
+
const now = deps.clock.now();
|
|
725
|
+
const record = {
|
|
726
|
+
v: 1,
|
|
727
|
+
inviteId,
|
|
728
|
+
groupId,
|
|
729
|
+
commitEventId,
|
|
730
|
+
...(commitTag === undefined ? {} : { commitTag }),
|
|
731
|
+
committedAt: now,
|
|
732
|
+
invitees: welcomes.map((w) => ({ ...w, status: 'pending', attempts: 0 })),
|
|
733
|
+
};
|
|
734
|
+
await view.put(key, encodeInviteRecord(record));
|
|
735
|
+
});
|
|
736
|
+
await pruneBestEffort(groupId);
|
|
737
|
+
},
|
|
738
|
+
async trackedCommits(groupId) {
|
|
739
|
+
return invitesTx(async (view, keys) => {
|
|
740
|
+
const out = [];
|
|
741
|
+
for (const key of keysOfGroup(await keys(), groupId)) {
|
|
742
|
+
const record = await readDecodable(view, key);
|
|
743
|
+
if (record === undefined)
|
|
744
|
+
continue;
|
|
745
|
+
const open = record.invitees.some((i) => i.status === 'pending' || i.status === 'retryable');
|
|
746
|
+
const withdrawn = record.invitees.some((i) => i.status === 'failed' && i.reason === 'commit-withdrawn');
|
|
747
|
+
const delivered = record.invitees.some((i) => i.status === 'delivered' && i.reason !== DELIVERED_ON_ABANDONED_BRANCH);
|
|
748
|
+
const deliveredAbandoned = record.invitees.some((i) => i.status === 'delivered' && i.reason === DELIVERED_ON_ABANDONED_BRANCH);
|
|
749
|
+
if (open || withdrawn || delivered || deliveredAbandoned)
|
|
750
|
+
out.push({ commitEventId: record.commitEventId, ...(record.commitTag === undefined ? {} : { commitTag: record.commitTag }), open, withdrawn, delivered, deliveredAbandoned });
|
|
751
|
+
}
|
|
752
|
+
return out;
|
|
753
|
+
});
|
|
754
|
+
},
|
|
755
|
+
async withdrawCommit(groupId, commitEventId, opts = {}) {
|
|
756
|
+
assertLive();
|
|
757
|
+
const failures = await invitesTx(async (view, keys) => {
|
|
758
|
+
const changed = [];
|
|
759
|
+
for (const key of keysOfGroup(await keys(), groupId)) {
|
|
760
|
+
const record = await readDecodable(view, key);
|
|
761
|
+
if (record === undefined || record.commitEventId !== commitEventId)
|
|
762
|
+
continue;
|
|
763
|
+
let touched = false;
|
|
764
|
+
const invitees = record.invitees.map((invitee) => {
|
|
765
|
+
if (invitee.status === 'delivered' && invitee.reason !== DELIVERED_ON_ABANDONED_BRANCH) {
|
|
766
|
+
// Already published: not recallable. Marked (once), so a restore can clear it and the signal is decided once.
|
|
767
|
+
touched = true;
|
|
768
|
+
if (opts.signalDelivered === true)
|
|
769
|
+
changed.push({ key, inviteeRef: invitee.inviteeRef, reason: DELIVERED_ON_ABANDONED_BRANCH });
|
|
770
|
+
return { ...invitee, reason: DELIVERED_ON_ABANDONED_BRANCH };
|
|
771
|
+
}
|
|
772
|
+
if (invitee.status !== 'pending' && invitee.status !== 'retryable')
|
|
773
|
+
return invitee;
|
|
774
|
+
touched = true;
|
|
775
|
+
changed.push({ key, inviteeRef: invitee.inviteeRef, reason: 'commit-withdrawn' });
|
|
776
|
+
return { ...invitee, status: 'failed', reason: 'commit-withdrawn' };
|
|
777
|
+
});
|
|
778
|
+
if (touched)
|
|
779
|
+
await view.put(key, encodeInviteRecord({ ...record, invitees }));
|
|
780
|
+
}
|
|
781
|
+
return changed;
|
|
782
|
+
});
|
|
783
|
+
for (const { key } of failures) {
|
|
784
|
+
const handle = timers.get(`invite:${key}`);
|
|
785
|
+
if (handle !== undefined) {
|
|
786
|
+
deps.timers.clear(handle);
|
|
787
|
+
timers.delete(`invite:${key}`);
|
|
788
|
+
}
|
|
789
|
+
}
|
|
790
|
+
for (const { inviteeRef, reason } of failures)
|
|
791
|
+
deps.onFailed?.({ groupId, inviteeRef, reason });
|
|
792
|
+
},
|
|
793
|
+
async restoreCommit(groupId, commitEventId) {
|
|
794
|
+
assertLive();
|
|
795
|
+
const restored = await invitesTx(async (view, keys) => {
|
|
796
|
+
const changed = [];
|
|
797
|
+
for (const key of keysOfGroup(await keys(), groupId)) {
|
|
798
|
+
const record = await readDecodable(view, key);
|
|
799
|
+
if (record === undefined || record.commitEventId !== commitEventId)
|
|
800
|
+
continue;
|
|
801
|
+
let touched = false;
|
|
802
|
+
const invitees = record.invitees.map((invitee) => {
|
|
803
|
+
// The commit is canonical again: a delivered Welcome was right after all (the mark goes, silently).
|
|
804
|
+
if (invitee.status === 'delivered' && invitee.reason === DELIVERED_ON_ABANDONED_BRANCH) {
|
|
805
|
+
touched = true;
|
|
806
|
+
return withoutReason(invitee);
|
|
807
|
+
}
|
|
808
|
+
if (invitee.status !== 'failed' || invitee.reason !== 'commit-withdrawn')
|
|
809
|
+
return invitee;
|
|
810
|
+
touched = true;
|
|
811
|
+
changed.push({ key, inviteeRef: invitee.inviteeRef });
|
|
812
|
+
return { ...withoutReason(invitee), status: 'pending', attempts: 0 };
|
|
813
|
+
});
|
|
814
|
+
if (touched)
|
|
815
|
+
await view.put(key, encodeInviteRecord({ ...record, invitees }));
|
|
816
|
+
}
|
|
817
|
+
return changed;
|
|
818
|
+
});
|
|
819
|
+
for (const { inviteeRef } of restored)
|
|
820
|
+
deps.onRestored?.({ groupId, inviteeRef });
|
|
821
|
+
for (const key of new Set(restored.map((r) => r.key)))
|
|
822
|
+
deliverInBackground(key);
|
|
823
|
+
},
|
|
824
|
+
deliver(groupId, inviteId) {
|
|
825
|
+
return queue.run(() => deliverAll(inviteKey(groupId, inviteId)));
|
|
826
|
+
},
|
|
827
|
+
deliverInBackground(groupId, inviteId) {
|
|
828
|
+
deliverInBackground(inviteKey(groupId, inviteId));
|
|
829
|
+
},
|
|
830
|
+
retry(groupId, inviteeRef) {
|
|
831
|
+
return queue.run(async () => {
|
|
832
|
+
assertLive();
|
|
833
|
+
if (typeof inviteeRef !== 'string' || inviteeRef.length === 0) {
|
|
834
|
+
throw new MarmotError('invalid-options', 'retryWelcome: inviteeRef must be a non-empty string');
|
|
835
|
+
}
|
|
836
|
+
// Pruned first, so a record past its retention is not found (AC-HYG-2).
|
|
837
|
+
await pruneBestEffort(groupId);
|
|
838
|
+
const latest = await invitesTx(async (view) => {
|
|
839
|
+
let found;
|
|
840
|
+
for (const key of keysOfGroup(await view.keys(), groupId)) {
|
|
841
|
+
const record = await readInvite(view, key);
|
|
842
|
+
if (record === undefined || !record.invitees.some((i) => i.inviteeRef === inviteeRef))
|
|
843
|
+
continue;
|
|
844
|
+
if (found === undefined || record.committedAt > found.record.committedAt)
|
|
845
|
+
found = { key, record };
|
|
846
|
+
}
|
|
847
|
+
return found;
|
|
848
|
+
});
|
|
849
|
+
if (latest === undefined) {
|
|
850
|
+
throw new MarmotError('invalid-options', `retryWelcome: no committed invite of group ${groupId} names ${inviteeRef}`, {
|
|
851
|
+
details: { reason: 'not-found', groupId, inviteeRef },
|
|
852
|
+
});
|
|
853
|
+
}
|
|
854
|
+
// A delivery marked `delivered-on-abandoned-branch` was PUBLISHED for a commit the group left: re-sending it would hand the invitee a Welcome of a
|
|
855
|
+
// dead branch (and clear the mark that a restore of the commit needs). The remedy is a new invite, not a retry.
|
|
856
|
+
const marked = latest.record.invitees.find((i) => i.inviteeRef === inviteeRef);
|
|
857
|
+
if (marked?.status === 'delivered' && marked.reason === DELIVERED_ON_ABANDONED_BRANCH) {
|
|
858
|
+
throw new MarmotError('send-rejected', `retryWelcome: the Welcome for ${inviteeRef} was delivered for a commit of group ${groupId} that a rewind abandoned; remove the member and invite it again with a fresh KeyPackage`, {
|
|
859
|
+
details: { reason: 'abandoned-branch', groupId, inviteeRef },
|
|
860
|
+
});
|
|
861
|
+
}
|
|
862
|
+
const result = await attempt(latest.key, inviteeRef, 'retry');
|
|
863
|
+
if (result === undefined)
|
|
864
|
+
throw new MarmotError('store-failed', `retryWelcome: invite ${latest.record.inviteId} vanished while retrying`, { details: { groupId, inviteeRef } });
|
|
865
|
+
return toWelcomeOutcome(result);
|
|
866
|
+
});
|
|
867
|
+
},
|
|
868
|
+
resumeGroup(groupId) {
|
|
869
|
+
if (disposed || deps.isDisposed())
|
|
870
|
+
return;
|
|
871
|
+
const run = () => {
|
|
872
|
+
queue
|
|
873
|
+
.run(async () => {
|
|
874
|
+
await pruneBestEffort(groupId);
|
|
875
|
+
const unfinished = await invitesTx(async (view) => {
|
|
876
|
+
const out = [];
|
|
877
|
+
for (const key of keysOfGroup(await view.keys(), groupId)) {
|
|
878
|
+
const record = await readInvite(view, key);
|
|
879
|
+
if (record?.invitees.some((i) => i.status === 'pending' || i.status === 'retryable'))
|
|
880
|
+
out.push(key);
|
|
881
|
+
}
|
|
882
|
+
return out;
|
|
883
|
+
});
|
|
884
|
+
for (const key of unfinished)
|
|
885
|
+
await deliverAll(key);
|
|
886
|
+
})
|
|
887
|
+
.catch((error) => {
|
|
888
|
+
if (!stops(error))
|
|
889
|
+
schedule(`group:${groupId}`, 1, run);
|
|
890
|
+
});
|
|
891
|
+
};
|
|
892
|
+
run();
|
|
893
|
+
},
|
|
894
|
+
async recordDecline(rumor) {
|
|
895
|
+
assertLive();
|
|
896
|
+
if (rumor.kind !== RUMOR_KINDS.DECLINE)
|
|
897
|
+
return;
|
|
898
|
+
const content = parseDeclineContent(rumor.content);
|
|
899
|
+
if (content === undefined)
|
|
900
|
+
return;
|
|
901
|
+
const author = rumor.pubkey;
|
|
902
|
+
// Retention first, as for retryWelcome (AC-HYG-2): a delivery past it is no longer matched — a late decline
|
|
903
|
+
// neither reports it nor renews its retention — and every decline of the group, matched or not, runs the pass.
|
|
904
|
+
await pruneBestEffort(content.groupId);
|
|
905
|
+
// 1. The candidate deliveries: the content's group's records, invitees authored by the seal's author.
|
|
906
|
+
const candidates = await invitesTx(async (view, keys) => {
|
|
907
|
+
const out = [];
|
|
908
|
+
for (const key of keysOfGroup(await keys(), content.groupId)) {
|
|
909
|
+
// A record that does not decode cannot be matched (and is left as stored).
|
|
910
|
+
const record = await readDecodable(view, key);
|
|
911
|
+
for (const invitee of record?.invitees ?? [])
|
|
912
|
+
if (invitee.pubkey === author && invitee.status !== 'declined')
|
|
913
|
+
out.push({ key, welcome: invitee.rumor.content });
|
|
914
|
+
}
|
|
915
|
+
return out;
|
|
916
|
+
});
|
|
917
|
+
if (candidates.length === 0)
|
|
918
|
+
return;
|
|
919
|
+
// 2. The Welcome identities, hashed outside any transaction.
|
|
920
|
+
const matching = new Set();
|
|
921
|
+
for (const welcome of new Set(candidates.map((c) => c.welcome))) {
|
|
922
|
+
let id;
|
|
923
|
+
try {
|
|
924
|
+
id = await welcomeIdOf({ ...rumor, kind: RUMOR_KINDS.WELCOME, content: welcome });
|
|
925
|
+
}
|
|
926
|
+
catch {
|
|
927
|
+
id = undefined; // not base64: names no Welcome
|
|
928
|
+
}
|
|
929
|
+
if (id === content.welcomeId)
|
|
930
|
+
matching.add(welcome);
|
|
931
|
+
}
|
|
932
|
+
if (matching.size === 0)
|
|
933
|
+
return;
|
|
934
|
+
assertLive();
|
|
935
|
+
// 3. One transaction: every matching delivery still not declined goes `declined` (re-read: a concurrent decline counts once).
|
|
936
|
+
const now = deps.clock.now();
|
|
937
|
+
const declined = await invitesTx(async (view) => {
|
|
938
|
+
const changed = [];
|
|
939
|
+
for (const key of new Set(candidates.map((c) => c.key))) {
|
|
940
|
+
const record = await readDecodable(view, key);
|
|
941
|
+
if (record === undefined)
|
|
942
|
+
continue;
|
|
943
|
+
let touched = false;
|
|
944
|
+
const invitees = record.invitees.map((invitee) => {
|
|
945
|
+
if (invitee.pubkey !== author || invitee.status === 'declined' || !matching.has(invitee.rumor.content))
|
|
946
|
+
return invitee;
|
|
947
|
+
touched = true;
|
|
948
|
+
changed.push({ groupId: record.groupId, inviteeRef: invitee.inviteeRef });
|
|
949
|
+
return { ...withoutReason(invitee), status: 'declined', settledAt: now };
|
|
950
|
+
});
|
|
951
|
+
if (touched)
|
|
952
|
+
await view.put(key, encodeInviteRecord({ ...record, invitees }));
|
|
953
|
+
}
|
|
954
|
+
return changed;
|
|
955
|
+
});
|
|
956
|
+
for (const d of declined)
|
|
957
|
+
deps.onDeclined?.(d);
|
|
958
|
+
},
|
|
959
|
+
dispose() {
|
|
960
|
+
disposed = true;
|
|
961
|
+
for (const handle of timers.values())
|
|
962
|
+
deps.timers.clear(handle);
|
|
963
|
+
timers.clear();
|
|
964
|
+
},
|
|
965
|
+
};
|
|
966
|
+
}
|