@941design/marmot 0.2.0-alpha.0 → 0.2.0-alpha.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +30 -0
- package/dist/account/teardown.d.ts +66 -3
- package/dist/account/teardown.js +24 -2
- package/dist/client/admission-cleanup.d.ts +197 -0
- package/dist/client/admission-cleanup.js +635 -0
- package/dist/client/adoption-proof.d.ts +39 -0
- package/dist/client/adoption-proof.js +102 -0
- package/dist/client/before-publish-hooks.js +3 -1
- package/dist/client/commit-redrive.d.ts +28 -4
- package/dist/client/commit-redrive.js +54 -1
- package/dist/client/confirm-hooks.d.ts +6 -1
- package/dist/client/confirm-hooks.js +15 -0
- package/dist/client/create-client.d.ts +107 -3
- package/dist/client/create-client.js +114 -7
- package/dist/client/group-availability.d.ts +182 -0
- package/dist/client/group-availability.js +301 -0
- package/dist/client/group-history.d.ts +26 -0
- package/dist/client/group-history.js +77 -7
- package/dist/client/group-records.d.ts +39 -2
- package/dist/client/group-records.js +88 -5
- package/dist/client/group-runtime.d.ts +30 -3
- package/dist/client/group-runtime.js +131 -21
- package/dist/client/group-snapshot.d.ts +7 -1
- package/dist/client/group-snapshot.js +23 -2
- package/dist/client/index.d.ts +4 -1
- package/dist/client/ingest.js +47 -13
- package/dist/client/invitation-outcomes.d.ts +50 -0
- package/dist/client/invitation-outcomes.js +135 -0
- package/dist/client/opaque-candidates.d.ts +2 -1
- package/dist/client/opaque-candidates.js +2 -1
- package/dist/client/own-change-outbox.js +2 -0
- package/dist/client/pipeline.d.ts +30 -1
- package/dist/client/pipeline.js +142 -21
- package/dist/client/reentrancy-guard.d.ts +6 -0
- package/dist/client/reentrancy-guard.js +6 -0
- package/dist/history/admission-lineage.d.ts +186 -0
- package/dist/history/admission-lineage.js +589 -0
- package/dist/history/fencing.d.ts +41 -0
- package/dist/history/fencing.js +67 -7
- package/dist/history/index.d.ts +2 -1
- package/dist/history/index.js +2 -1
- package/dist/history/own-change.d.ts +13 -1
- package/dist/invitations/decline.d.ts +8 -2
- package/dist/invitations/decline.js +9 -3
- package/dist/invitations/delivery-evidence.d.ts +288 -0
- package/dist/invitations/delivery-evidence.js +766 -0
- package/dist/invitations/index.d.ts +4 -2
- package/dist/invitations/index.js +4 -2
- package/dist/invitations/invitation-outcome.d.ts +110 -0
- package/dist/invitations/invitation-outcome.js +210 -0
- package/dist/invitations/invite.d.ts +61 -6
- package/dist/invitations/invite.js +187 -51
- package/dist/invitations/welcome-processor.d.ts +20 -1
- package/dist/invitations/welcome-processor.js +81 -20
- package/dist/shared/errors.d.ts +7 -0
- package/dist/shared/errors.js +11 -0
- package/dist/shared/index.d.ts +1 -1
- package/dist/shared/index.js +1 -1
- package/dist/storage/index.d.ts +10 -0
- package/dist/storage/index.js +33 -1
- package/dist/storage/lease.d.ts +13 -0
- package/dist/storage/lease.js +51 -0
- package/package.json +2 -2
|
@@ -0,0 +1,766 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Inviter-side delivery evidence and decline matching (epic marmot-invitation-outcomes S3; ADR-019 D1, D2;
|
|
3
|
+
* architecture SC-1, SC-2, SC-3, SC-13).
|
|
4
|
+
*
|
|
5
|
+
* Two account extensions, written in the same transaction as the fact they record and never pruned by
|
|
6
|
+
* `inviteRetentionMs` (only a group purge or an account wipe deletes them):
|
|
7
|
+
*
|
|
8
|
+
* - `marmot.delivery-evidence`, key `<groupId>/<candidateId>`: one payload-free {@link DeliveryEvidence} per
|
|
9
|
+
* locally issued delivery (one recipient row of one Welcome), written with the `invites` record at the hand-off;
|
|
10
|
+
* - `marmot.decline-evidence`, key `<groupId>/<welcomeId>/<author>`: the authenticated declines of one Welcome by
|
|
11
|
+
* one account ({@link DeclineEvidence}).
|
|
12
|
+
*
|
|
13
|
+
* A *candidate* is a delivery with decline evidence. Its identity ({@link candidateIdOf}) is stable across Welcome
|
|
14
|
+
* retransmission; its status and basis are a pure function of the evidence ({@link matchCandidates}): a valid
|
|
15
|
+
* selector makes its own delivery actionable, an unqualified (or legacy) decline makes the delivery actionable only
|
|
16
|
+
* when the Welcome went to exactly one KeyPackage of that account, and everything else is ambiguous — never inferred
|
|
17
|
+
* by elimination. Every candidate carries a {@link CleanupReference}: identity only, never authority.
|
|
18
|
+
*
|
|
19
|
+
* Records written before this release have no evidence. A retained `invites` record backfills it
|
|
20
|
+
* ({@link evidenceFromLegacyInvite}): materialized on the write paths that touch the group, synthesized virtually
|
|
21
|
+
* by the read-only scan ({@link scanDeclineCandidates}), which writes nothing.
|
|
22
|
+
*
|
|
23
|
+
* Pure apart from the `AccountStoreTx` shells; `history/` never imports this module (SC-1 I3).
|
|
24
|
+
*/
|
|
25
|
+
import { commitDigest } from '@941design/marmot-engine/core';
|
|
26
|
+
import { defaultProposalTypes, leafNodeSources, nodeTypes } from '@941design/marmot-engine/mls';
|
|
27
|
+
import { computeKeyPackageRefHex } from '../key-packages/index.js';
|
|
28
|
+
import { hexOfBytes, isHex64, isMalformedRowError, MarmotError } from '../shared/index.js';
|
|
29
|
+
export const DELIVERY_EVIDENCE_EXTENSION = 'marmot.delivery-evidence';
|
|
30
|
+
export const DECLINE_EVIDENCE_EXTENSION = 'marmot.decline-evidence';
|
|
31
|
+
/** Upper bound of one `declineCandidates` page (SC-13); a larger `limit` is clamped to it. */
|
|
32
|
+
export const DECLINE_SCAN_PAGE_MAX = 256;
|
|
33
|
+
// ---------------------------------------------------------------------------
|
|
34
|
+
// Identities
|
|
35
|
+
// ---------------------------------------------------------------------------
|
|
36
|
+
/** Hex SHA-256 of `bytes`. `commitDigest` is the engine's plain SHA-256 (MIP-03), synchronous — usable inside a store transaction. */
|
|
37
|
+
function sha256Hex(bytes) {
|
|
38
|
+
return hexOfBytes(commitDigest(bytes));
|
|
39
|
+
}
|
|
40
|
+
/** SC-2 I4: hex SHA-256 over `groupId|inviteId|inviteeRef`. A re-drive has a new `inviteId`, hence a new candidate. */
|
|
41
|
+
export function candidateIdOf(groupId, inviteId, inviteeRef) {
|
|
42
|
+
return sha256Hex(new TextEncoder().encode(`${groupId}|${inviteId}|${inviteeRef}`));
|
|
43
|
+
}
|
|
44
|
+
/**
|
|
45
|
+
* The Welcome id of a Welcome rumor's content (base64 MLS Welcome) — the same value as `welcomeIdOf`
|
|
46
|
+
* (`welcome-processor.ts`), computed synchronously. `undefined` for content that is not base64: it names no Welcome.
|
|
47
|
+
*/
|
|
48
|
+
export function welcomeIdOfContent(content) {
|
|
49
|
+
let binary;
|
|
50
|
+
try {
|
|
51
|
+
binary = globalThis.atob(content);
|
|
52
|
+
}
|
|
53
|
+
catch {
|
|
54
|
+
return undefined;
|
|
55
|
+
}
|
|
56
|
+
const bytes = new Uint8Array(binary.length);
|
|
57
|
+
for (let i = 0; i < binary.length; i++)
|
|
58
|
+
bytes[i] = binary.charCodeAt(i);
|
|
59
|
+
return sha256Hex(bytes);
|
|
60
|
+
}
|
|
61
|
+
const CLEANUP_REF_PREFIX = 'mcr1';
|
|
62
|
+
/** SC-3: the reference of `candidateId` of `groupId` in `account`'s store. */
|
|
63
|
+
export function encodeCleanupReference(account, groupId, candidateId) {
|
|
64
|
+
return `${CLEANUP_REF_PREFIX}.${account}.${groupId}.${candidateId}`;
|
|
65
|
+
}
|
|
66
|
+
/**
|
|
67
|
+
* SC-3 I9: format check only — `undefined` for anything that is not `mcr1.<64 hex>.<groupId>.<64 hex>` (a group id
|
|
68
|
+
* holds no `.`). Whether the account, group and candidate are this store's is the reader's question.
|
|
69
|
+
*/
|
|
70
|
+
export function decodeCleanupReference(raw) {
|
|
71
|
+
if (typeof raw !== 'string')
|
|
72
|
+
return undefined;
|
|
73
|
+
const parts = raw.split('.');
|
|
74
|
+
if (parts.length !== 4 || parts[0] !== CLEANUP_REF_PREFIX)
|
|
75
|
+
return undefined;
|
|
76
|
+
const [, account, groupId, candidateId] = parts;
|
|
77
|
+
if (!isHex64(account) || !isHex64(candidateId) || groupId.length === 0)
|
|
78
|
+
return undefined;
|
|
79
|
+
return { account, groupId, candidateId };
|
|
80
|
+
}
|
|
81
|
+
// ---------------------------------------------------------------------------
|
|
82
|
+
// AddAnchor (SC-1)
|
|
83
|
+
// ---------------------------------------------------------------------------
|
|
84
|
+
function leafKeysAt(state) {
|
|
85
|
+
const out = [];
|
|
86
|
+
for (let i = 0; i < state.ratchetTree.length; i += 2) {
|
|
87
|
+
const node = state.ratchetTree[i];
|
|
88
|
+
if (node?.nodeType !== nodeTypes.leaf)
|
|
89
|
+
continue;
|
|
90
|
+
out.push({ leafIndex: i / 2, leafKey: hexOfBytes(node.leaf.signaturePublicKey), fromKeyPackage: node.leaf.leafNodeSource === leafNodeSources.key_package });
|
|
91
|
+
}
|
|
92
|
+
return out;
|
|
93
|
+
}
|
|
94
|
+
/** The KeyPackages of the Add proposals staged in `state` (an own commit over it carries them by reference). */
|
|
95
|
+
function stagedAddKeyPackages(state) {
|
|
96
|
+
const out = [];
|
|
97
|
+
for (const { proposal } of Object.values(state.unappliedProposals)) {
|
|
98
|
+
if (proposal.proposalType === defaultProposalTypes.add && 'add' in proposal)
|
|
99
|
+
out.push(proposal.add.keyPackage);
|
|
100
|
+
}
|
|
101
|
+
return out;
|
|
102
|
+
}
|
|
103
|
+
/**
|
|
104
|
+
* SC-1 I1: the {@link AddAnchor} of each delivery of one confirmed own commit, by KeyPackageRef. Computed only from
|
|
105
|
+
* the confirmed `parentState` → `newState` pair plus the KeyPackages the commit added (the intent's invitee
|
|
106
|
+
* KeyPackages and the Adds staged in the parent). A delivery gets an anchor only when exactly one leaf of `newState`
|
|
107
|
+
* carries its KeyPackage's signature key, that key is on no leaf of `parentState`, and the leaf came from a
|
|
108
|
+
* KeyPackage; otherwise it gets none. Never throws (an undecodable KeyPackage anchors nothing).
|
|
109
|
+
*/
|
|
110
|
+
export async function addAnchorsOf(input) {
|
|
111
|
+
const anchors = new Map();
|
|
112
|
+
try {
|
|
113
|
+
const parentKeys = new Set(leafKeysAt(input.parentState).map((l) => l.leafKey));
|
|
114
|
+
const childLeaves = leafKeysAt(input.newState);
|
|
115
|
+
const refs = new Map();
|
|
116
|
+
for (const keyPackage of [...input.keyPackages, ...stagedAddKeyPackages(input.parentState)]) {
|
|
117
|
+
let ref;
|
|
118
|
+
try {
|
|
119
|
+
ref = await computeKeyPackageRefHex(keyPackage);
|
|
120
|
+
}
|
|
121
|
+
catch {
|
|
122
|
+
continue;
|
|
123
|
+
}
|
|
124
|
+
if (!refs.has(ref))
|
|
125
|
+
refs.set(ref, hexOfBytes(keyPackage.leafNode.signaturePublicKey));
|
|
126
|
+
}
|
|
127
|
+
for (const [ref, leafKey] of refs) {
|
|
128
|
+
if (parentKeys.has(leafKey))
|
|
129
|
+
continue;
|
|
130
|
+
const matches = childLeaves.filter((l) => l.leafKey === leafKey);
|
|
131
|
+
if (matches.length !== 1 || !matches[0].fromKeyPackage)
|
|
132
|
+
continue;
|
|
133
|
+
anchors.set(ref, { addDigest: input.addDigest, addTag: input.addTag, commitEventId: input.commitEventId, leafIndex: matches[0].leafIndex, leafKey });
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
catch {
|
|
137
|
+
// An unreadable state anchors nothing: the deliveries are recorded without an anchor.
|
|
138
|
+
}
|
|
139
|
+
return anchors;
|
|
140
|
+
}
|
|
141
|
+
// ---------------------------------------------------------------------------
|
|
142
|
+
// Codecs (strict; an absent optional field is accepted)
|
|
143
|
+
// ---------------------------------------------------------------------------
|
|
144
|
+
function isObject(value) {
|
|
145
|
+
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
146
|
+
}
|
|
147
|
+
function malformed(where, detail) {
|
|
148
|
+
return new MarmotError('store-failed', `${where}: malformed record (${detail})`, { details: { where, malformed: true } });
|
|
149
|
+
}
|
|
150
|
+
function decodeAnchor(where, raw) {
|
|
151
|
+
if (!isObject(raw))
|
|
152
|
+
throw malformed(where, 'anchor');
|
|
153
|
+
const { addDigest, addTag, commitEventId, leafIndex, leafKey } = raw;
|
|
154
|
+
if (typeof addDigest !== 'string' || typeof addTag !== 'string' || typeof commitEventId !== 'string' || typeof leafKey !== 'string' || typeof leafIndex !== 'number' || !Number.isInteger(leafIndex) || leafIndex < 0) {
|
|
155
|
+
throw malformed(where, 'anchor fields');
|
|
156
|
+
}
|
|
157
|
+
return { addDigest, addTag, commitEventId, leafIndex, leafKey };
|
|
158
|
+
}
|
|
159
|
+
/** Decodes the delivery evidence stored under `key` (`<groupId>/<candidateId>`); its fields must name the same group and candidate. */
|
|
160
|
+
export function decodeDeliveryEvidence(key, raw) {
|
|
161
|
+
const where = `${DELIVERY_EVIDENCE_EXTENSION}/${key}`;
|
|
162
|
+
if (!isObject(raw) || raw.v !== 1)
|
|
163
|
+
throw malformed(where, 'header');
|
|
164
|
+
const { candidateId, groupId, inviteId, inviteeRef, recipient, welcomeId, issuedAt, origin } = raw;
|
|
165
|
+
if (typeof candidateId !== 'string' ||
|
|
166
|
+
typeof groupId !== 'string' ||
|
|
167
|
+
typeof inviteId !== 'string' ||
|
|
168
|
+
typeof inviteeRef !== 'string' ||
|
|
169
|
+
typeof recipient !== 'string' ||
|
|
170
|
+
typeof welcomeId !== 'string' ||
|
|
171
|
+
typeof issuedAt !== 'number' ||
|
|
172
|
+
(origin !== 'issued' && origin !== 'legacy-backfill')) {
|
|
173
|
+
throw malformed(where, 'fields');
|
|
174
|
+
}
|
|
175
|
+
if (key !== deliveryKey(groupId, candidateId) || candidateId !== candidateIdOf(groupId, inviteId, inviteeRef))
|
|
176
|
+
throw malformed(where, 'identity');
|
|
177
|
+
return {
|
|
178
|
+
v: 1,
|
|
179
|
+
candidateId,
|
|
180
|
+
groupId,
|
|
181
|
+
inviteId,
|
|
182
|
+
inviteeRef,
|
|
183
|
+
recipient,
|
|
184
|
+
welcomeId,
|
|
185
|
+
issuedAt,
|
|
186
|
+
...(raw.anchor === undefined ? {} : { anchor: decodeAnchor(where, raw.anchor) }),
|
|
187
|
+
origin,
|
|
188
|
+
};
|
|
189
|
+
}
|
|
190
|
+
export function encodeDeliveryEvidence(evidence) {
|
|
191
|
+
return {
|
|
192
|
+
v: 1,
|
|
193
|
+
candidateId: evidence.candidateId,
|
|
194
|
+
groupId: evidence.groupId,
|
|
195
|
+
inviteId: evidence.inviteId,
|
|
196
|
+
inviteeRef: evidence.inviteeRef,
|
|
197
|
+
recipient: evidence.recipient,
|
|
198
|
+
welcomeId: evidence.welcomeId,
|
|
199
|
+
issuedAt: evidence.issuedAt,
|
|
200
|
+
...(evidence.anchor === undefined ? {} : { anchor: { ...evidence.anchor } }),
|
|
201
|
+
origin: evidence.origin,
|
|
202
|
+
};
|
|
203
|
+
}
|
|
204
|
+
export function decodeDeclineEvidence(key, raw) {
|
|
205
|
+
const where = `${DECLINE_EVIDENCE_EXTENSION}/${key}`;
|
|
206
|
+
if (!isObject(raw) || raw.v !== 1)
|
|
207
|
+
throw malformed(where, 'header');
|
|
208
|
+
const { unqualifiedAt, qualified, legacy, rev } = raw;
|
|
209
|
+
if (unqualifiedAt !== undefined && typeof unqualifiedAt !== 'number')
|
|
210
|
+
throw malformed(where, 'unqualifiedAt');
|
|
211
|
+
if (legacy !== undefined && legacy !== true)
|
|
212
|
+
throw malformed(where, 'legacy');
|
|
213
|
+
if (typeof rev !== 'number' || !Number.isInteger(rev) || rev < 1)
|
|
214
|
+
throw malformed(where, 'rev');
|
|
215
|
+
if (!Array.isArray(qualified) || !qualified.every((q) => isObject(q) && typeof q.inviteeRef === 'string' && typeof q.at === 'number'))
|
|
216
|
+
throw malformed(where, 'qualified');
|
|
217
|
+
return {
|
|
218
|
+
v: 1,
|
|
219
|
+
...(unqualifiedAt === undefined ? {} : { unqualifiedAt }),
|
|
220
|
+
qualified: qualified.map((q) => ({ inviteeRef: q.inviteeRef, at: q.at })),
|
|
221
|
+
...(legacy === true ? { legacy: true } : {}),
|
|
222
|
+
rev,
|
|
223
|
+
};
|
|
224
|
+
}
|
|
225
|
+
export function encodeDeclineEvidence(evidence) {
|
|
226
|
+
return {
|
|
227
|
+
v: 1,
|
|
228
|
+
...(evidence.unqualifiedAt === undefined ? {} : { unqualifiedAt: evidence.unqualifiedAt }),
|
|
229
|
+
qualified: evidence.qualified.map((q) => ({ inviteeRef: q.inviteeRef, at: q.at })),
|
|
230
|
+
...(evidence.legacy === true ? { legacy: true } : {}),
|
|
231
|
+
rev: evidence.rev,
|
|
232
|
+
};
|
|
233
|
+
}
|
|
234
|
+
// ---------------------------------------------------------------------------
|
|
235
|
+
// Keys
|
|
236
|
+
// ---------------------------------------------------------------------------
|
|
237
|
+
export function deliveryKey(groupId, candidateId) {
|
|
238
|
+
return `${groupId}/${candidateId}`;
|
|
239
|
+
}
|
|
240
|
+
export function declineKey(groupId, welcomeId, author) {
|
|
241
|
+
return `${groupId}/${welcomeId}/${author}`;
|
|
242
|
+
}
|
|
243
|
+
function groupOfDeliveryKey(key) {
|
|
244
|
+
const slash = key.lastIndexOf('/');
|
|
245
|
+
return slash <= 0 ? undefined : key.slice(0, slash);
|
|
246
|
+
}
|
|
247
|
+
function partsOfDeclineKey(key) {
|
|
248
|
+
const last = key.lastIndexOf('/');
|
|
249
|
+
const middle = last <= 0 ? -1 : key.lastIndexOf('/', last - 1);
|
|
250
|
+
if (middle <= 0)
|
|
251
|
+
return undefined;
|
|
252
|
+
return { groupId: key.slice(0, middle), welcomeId: key.slice(middle + 1, last), author: key.slice(last + 1) };
|
|
253
|
+
}
|
|
254
|
+
/**
|
|
255
|
+
* Every candidate the evidence holds (SC-2 I5, I6). The candidate set of a decline row is every delivery of its group
|
|
256
|
+
* to its author (recipient) with its Welcome id, pruned or not, declined or not. A delivery is a candidate when that
|
|
257
|
+
* row holds any decline for it: its own valid selector (`qualified`), or an unqualified or legacy decline of the
|
|
258
|
+
* whole set. It is `actionable` when a selector names it, or when an unqualified or legacy decline covers a set
|
|
259
|
+
* whose deliveries all name the same KeyPackage (exactly one recipient device); otherwise `ambiguous` — never decided
|
|
260
|
+
* by elimination. `rev` counts the kinds of evidence present for the delivery (legacy, unqualified, own selector):
|
|
261
|
+
* it only grows as evidence is added, and an equal `rev` means the same status and basis. The result is ordered by
|
|
262
|
+
* `<groupId>/<candidateId>`.
|
|
263
|
+
*/
|
|
264
|
+
export function matchCandidates(account, deliveries, declines) {
|
|
265
|
+
const bySet = new Map();
|
|
266
|
+
for (const d of deliveries) {
|
|
267
|
+
const key = declineKey(d.groupId, d.welcomeId, d.recipient);
|
|
268
|
+
const set = bySet.get(key);
|
|
269
|
+
if (set === undefined)
|
|
270
|
+
bySet.set(key, [d]);
|
|
271
|
+
else
|
|
272
|
+
set.push(d);
|
|
273
|
+
}
|
|
274
|
+
const out = [];
|
|
275
|
+
for (const row of declines) {
|
|
276
|
+
const set = bySet.get(declineKey(row.groupId, row.welcomeId, row.author)) ?? [];
|
|
277
|
+
const distinctRefs = new Set(set.map((d) => d.inviteeRef));
|
|
278
|
+
const covered = row.evidence.unqualifiedAt !== undefined || row.evidence.legacy === true;
|
|
279
|
+
for (const d of set) {
|
|
280
|
+
const selected = row.evidence.qualified.some((q) => q.inviteeRef === d.inviteeRef);
|
|
281
|
+
if (!selected && !covered)
|
|
282
|
+
continue;
|
|
283
|
+
const rev = (row.evidence.legacy === true ? 1 : 0) + (row.evidence.unqualifiedAt !== undefined ? 1 : 0) + (selected ? 1 : 0);
|
|
284
|
+
out.push({
|
|
285
|
+
candidateId: d.candidateId,
|
|
286
|
+
groupId: d.groupId,
|
|
287
|
+
recipient: d.recipient,
|
|
288
|
+
inviteeRef: d.inviteeRef,
|
|
289
|
+
welcomeId: d.welcomeId,
|
|
290
|
+
status: selected || distinctRefs.size === 1 ? 'actionable' : 'ambiguous',
|
|
291
|
+
basis: selected ? 'qualified' : row.evidence.unqualifiedAt !== undefined ? 'unqualified' : 'legacy',
|
|
292
|
+
rev,
|
|
293
|
+
cleanupRef: encodeCleanupReference(account, d.groupId, d.candidateId),
|
|
294
|
+
});
|
|
295
|
+
}
|
|
296
|
+
}
|
|
297
|
+
return out.sort((a, b) => compareKeys(deliveryKey(a.groupId, a.candidateId), deliveryKey(b.groupId, b.candidateId)));
|
|
298
|
+
}
|
|
299
|
+
function compareKeys(a, b) {
|
|
300
|
+
return a < b ? -1 : a > b ? 1 : 0;
|
|
301
|
+
}
|
|
302
|
+
/**
|
|
303
|
+
* Spec DD3 applied to one decline row: the evidence after an authenticated decline of a Welcome whose candidate set
|
|
304
|
+
* (the deliveries of that Welcome to the author) is `set`. `undefined` when the decline changes nothing — an empty
|
|
305
|
+
* set (no delivery of that Welcome went to that account), a present but invalid or non-matching selector (SC-2 I7:
|
|
306
|
+
* never downgraded to an unqualified decline), or a duplicate.
|
|
307
|
+
*/
|
|
308
|
+
export function applyDecline(current, set, selector, at) {
|
|
309
|
+
if (set.length === 0 || selector.kind === 'invalid')
|
|
310
|
+
return undefined;
|
|
311
|
+
const base = current ?? { v: 1, qualified: [], rev: 0 };
|
|
312
|
+
if (selector.kind === 'unqualified') {
|
|
313
|
+
if (base.unqualifiedAt !== undefined)
|
|
314
|
+
return undefined;
|
|
315
|
+
return { ...base, unqualifiedAt: at, rev: base.rev + 1 };
|
|
316
|
+
}
|
|
317
|
+
if (!set.some((d) => d.inviteeRef === selector.inviteeRef))
|
|
318
|
+
return undefined;
|
|
319
|
+
if (base.qualified.some((q) => q.inviteeRef === selector.inviteeRef))
|
|
320
|
+
return undefined;
|
|
321
|
+
return { ...base, qualified: [...base.qualified, { inviteeRef: selector.inviteeRef, at }], rev: base.rev + 1 };
|
|
322
|
+
}
|
|
323
|
+
/**
|
|
324
|
+
* The evidence a retained `invites` record proves: one `legacy-backfill` {@link DeliveryEvidence} (no anchor) per
|
|
325
|
+
* delivery whose Welcome content names a Welcome, and a legacy decline for each Welcome and account with a `declined`
|
|
326
|
+
* delivery (the pre-upgrade code declined every delivery of the Welcome to that account at once). Pure.
|
|
327
|
+
*/
|
|
328
|
+
export function evidenceFromLegacyInvite(record) {
|
|
329
|
+
const deliveries = [];
|
|
330
|
+
const legacy = new Map();
|
|
331
|
+
for (const invitee of record.invitees) {
|
|
332
|
+
const welcomeId = welcomeIdOfContent(invitee.rumor.content);
|
|
333
|
+
if (welcomeId === undefined)
|
|
334
|
+
continue;
|
|
335
|
+
deliveries.push({
|
|
336
|
+
v: 1,
|
|
337
|
+
candidateId: candidateIdOf(record.groupId, record.inviteId, invitee.inviteeRef),
|
|
338
|
+
groupId: record.groupId,
|
|
339
|
+
inviteId: record.inviteId,
|
|
340
|
+
inviteeRef: invitee.inviteeRef,
|
|
341
|
+
recipient: invitee.pubkey,
|
|
342
|
+
welcomeId,
|
|
343
|
+
issuedAt: record.committedAt,
|
|
344
|
+
origin: 'legacy-backfill',
|
|
345
|
+
});
|
|
346
|
+
if (invitee.status === 'declined')
|
|
347
|
+
legacy.set(declineKey(record.groupId, welcomeId, invitee.pubkey), { groupId: record.groupId, welcomeId, author: invitee.pubkey });
|
|
348
|
+
}
|
|
349
|
+
return { deliveries, legacyDeclines: [...legacy.values()] };
|
|
350
|
+
}
|
|
351
|
+
/** `current` with the legacy mark (rev + 1), or `undefined` when it already carries it. */
|
|
352
|
+
function withLegacy(current) {
|
|
353
|
+
if (current?.legacy === true)
|
|
354
|
+
return undefined;
|
|
355
|
+
const base = current ?? { v: 1, qualified: [], rev: 0 };
|
|
356
|
+
return { ...base, legacy: true, rev: base.rev + 1 };
|
|
357
|
+
}
|
|
358
|
+
/**
|
|
359
|
+
* The evidence of `record` whose delivery row is absent per `isPresent` — exactly {@link evidenceFromLegacyInvite}'s
|
|
360
|
+
* deliveries filtered to the missing ones, and its legacy declines filtered to the sets of those missing deliveries.
|
|
361
|
+
* A delivery's key depends only on the group, the invite and the KeyPackageRef, so presence is checked first and a
|
|
362
|
+
* Welcome is decoded and hashed only for a delivery actually missing (or a declined one of a missing delivery's
|
|
363
|
+
* recipient): a fully materialized record costs no Welcome hash. With `firstWins`, a key repeated inside the record
|
|
364
|
+
* counts once (its first delivery with a Welcome), as the scan's in-memory merge counts it.
|
|
365
|
+
*/
|
|
366
|
+
async function missingLegacyDeliveries(record, isPresent, firstWins) {
|
|
367
|
+
const welcomeIds = new Map();
|
|
368
|
+
const welcomeOf = (content) => {
|
|
369
|
+
if (!welcomeIds.has(content))
|
|
370
|
+
welcomeIds.set(content, welcomeIdOfContent(content));
|
|
371
|
+
return welcomeIds.get(content);
|
|
372
|
+
};
|
|
373
|
+
const deliveries = [];
|
|
374
|
+
const accepted = new Set();
|
|
375
|
+
for (const invitee of record.invitees) {
|
|
376
|
+
const candidateId = candidateIdOf(record.groupId, record.inviteId, invitee.inviteeRef);
|
|
377
|
+
const key = deliveryKey(record.groupId, candidateId);
|
|
378
|
+
if ((firstWins && accepted.has(key)) || (await isPresent(key)))
|
|
379
|
+
continue;
|
|
380
|
+
const welcomeId = welcomeOf(invitee.rumor.content);
|
|
381
|
+
if (welcomeId === undefined)
|
|
382
|
+
continue;
|
|
383
|
+
accepted.add(key);
|
|
384
|
+
deliveries.push({
|
|
385
|
+
v: 1,
|
|
386
|
+
candidateId,
|
|
387
|
+
groupId: record.groupId,
|
|
388
|
+
inviteId: record.inviteId,
|
|
389
|
+
inviteeRef: invitee.inviteeRef,
|
|
390
|
+
recipient: invitee.pubkey,
|
|
391
|
+
welcomeId,
|
|
392
|
+
issuedAt: record.committedAt,
|
|
393
|
+
origin: 'legacy-backfill',
|
|
394
|
+
});
|
|
395
|
+
}
|
|
396
|
+
const legacyDeclines = new Map();
|
|
397
|
+
if (deliveries.length === 0)
|
|
398
|
+
return { deliveries, legacyDeclines: [] };
|
|
399
|
+
const missingSets = new Set(deliveries.map((d) => declineKey(d.groupId, d.welcomeId, d.recipient)));
|
|
400
|
+
const missingRecipients = new Set(deliveries.map((d) => d.recipient));
|
|
401
|
+
for (const invitee of record.invitees) {
|
|
402
|
+
if (invitee.status !== 'declined' || !missingRecipients.has(invitee.pubkey))
|
|
403
|
+
continue;
|
|
404
|
+
const welcomeId = welcomeOf(invitee.rumor.content);
|
|
405
|
+
if (welcomeId === undefined)
|
|
406
|
+
continue;
|
|
407
|
+
const key = declineKey(record.groupId, welcomeId, invitee.pubkey);
|
|
408
|
+
if (missingSets.has(key) && !legacyDeclines.has(key))
|
|
409
|
+
legacyDeclines.set(key, { groupId: record.groupId, welcomeId, author: invitee.pubkey });
|
|
410
|
+
}
|
|
411
|
+
return { deliveries, legacyDeclines: [...legacyDeclines.values()] };
|
|
412
|
+
}
|
|
413
|
+
/**
|
|
414
|
+
* The evidence of `record` that is not stored yet: a delivery whose evidence row is absent is a pre-upgrade one —
|
|
415
|
+
* every delivery handed off since this release has its row from the hand-off on. Read-only.
|
|
416
|
+
*/
|
|
417
|
+
async function missingLegacyEvidence(tx, record) {
|
|
418
|
+
const deliveryView = tx.extension(DELIVERY_EVIDENCE_EXTENSION);
|
|
419
|
+
const { deliveries, legacyDeclines } = await missingLegacyDeliveries(record, (key) => rowPresent(deliveryView, key), false);
|
|
420
|
+
const declines = [];
|
|
421
|
+
if (legacyDeclines.length === 0)
|
|
422
|
+
return { deliveries, declines };
|
|
423
|
+
const declineView = tx.extension(DECLINE_EVIDENCE_EXTENSION);
|
|
424
|
+
for (const l of legacyDeclines) {
|
|
425
|
+
const key = declineKey(l.groupId, l.welcomeId, l.author);
|
|
426
|
+
const next = withLegacy(await decodedOrSkipped(declineView, key, decodeDeclineEvidence));
|
|
427
|
+
if (next !== undefined)
|
|
428
|
+
declines.push({ key, next });
|
|
429
|
+
}
|
|
430
|
+
return { deliveries, declines };
|
|
431
|
+
}
|
|
432
|
+
/**
|
|
433
|
+
* The backfill deliveries of `record` to `recipient` whose evidence row is absent — read-only, what
|
|
434
|
+
* {@link materializeLegacyEvidence} would write for that recipient (a key repeated inside the record counts once).
|
|
435
|
+
* Deliveries to other accounts are skipped unread, and a Welcome is decoded and hashed only for a missing delivery: a
|
|
436
|
+
* decline's candidate set costs no Welcome hash once the group's evidence is materialized.
|
|
437
|
+
*/
|
|
438
|
+
export async function missingLegacyDeliveriesTo(tx, record, recipient) {
|
|
439
|
+
const invitees = record.invitees.filter((i) => i.pubkey === recipient);
|
|
440
|
+
if (invitees.length === 0)
|
|
441
|
+
return [];
|
|
442
|
+
const deliveryView = tx.extension(DELIVERY_EVIDENCE_EXTENSION);
|
|
443
|
+
return (await missingLegacyDeliveries({ ...record, invitees }, (key) => rowPresent(deliveryView, key), true)).deliveries;
|
|
444
|
+
}
|
|
445
|
+
/**
|
|
446
|
+
* Materializes `record`'s backfill in the caller's (write) transaction: idempotent — a second run finds every row
|
|
447
|
+
* and writes nothing. Called on write paths before anything prunes or flips the record.
|
|
448
|
+
*/
|
|
449
|
+
export async function materializeLegacyEvidence(tx, record) {
|
|
450
|
+
const { deliveries, declines } = await missingLegacyEvidence(tx, record);
|
|
451
|
+
const deliveryView = tx.extension(DELIVERY_EVIDENCE_EXTENSION);
|
|
452
|
+
for (const d of deliveries)
|
|
453
|
+
await deliveryView.put(deliveryKey(d.groupId, d.candidateId), encodeDeliveryEvidence(d));
|
|
454
|
+
const declineView = tx.extension(DECLINE_EVIDENCE_EXTENSION);
|
|
455
|
+
for (const { key, next } of declines)
|
|
456
|
+
await declineView.put(key, encodeDeclineEvidence(next));
|
|
457
|
+
}
|
|
458
|
+
// ---------------------------------------------------------------------------
|
|
459
|
+
// Shells over one account transaction
|
|
460
|
+
// ---------------------------------------------------------------------------
|
|
461
|
+
/**
|
|
462
|
+
* The stored deliveries of `groupId` with Welcome `welcomeId` to `recipient` — the candidate set of a decline. A
|
|
463
|
+
* row that does not decode is skipped (a malformed row never blocks matching the others); a failed read propagates.
|
|
464
|
+
*/
|
|
465
|
+
export async function deliveriesOfSet(tx, groupId, welcomeId, recipient) {
|
|
466
|
+
const view = tx.extension(DELIVERY_EVIDENCE_EXTENSION);
|
|
467
|
+
const out = [];
|
|
468
|
+
for (const key of await view.keys()) {
|
|
469
|
+
if (groupOfDeliveryKey(key) !== groupId)
|
|
470
|
+
continue;
|
|
471
|
+
const evidence = await decodedOrSkipped(view, key, decodeDeliveryEvidence);
|
|
472
|
+
if (evidence?.welcomeId === welcomeId && evidence.recipient === recipient)
|
|
473
|
+
out.push(evidence);
|
|
474
|
+
}
|
|
475
|
+
return out;
|
|
476
|
+
}
|
|
477
|
+
/**
|
|
478
|
+
* The decline evidence row of `(groupId, welcomeId, author)`. A row that does not decode reads absent (the next
|
|
479
|
+
* write replaces it): a damaged secondary row must not block recording a decline; a failed read propagates.
|
|
480
|
+
*/
|
|
481
|
+
export async function readDeclineEvidence(tx, groupId, welcomeId, author) {
|
|
482
|
+
return decodedOrSkipped(tx.extension(DECLINE_EVIDENCE_EXTENSION), declineKey(groupId, welcomeId, author), decodeDeclineEvidence);
|
|
483
|
+
}
|
|
484
|
+
export async function writeDeclineEvidence(tx, groupId, welcomeId, author, evidence) {
|
|
485
|
+
await tx.extension(DECLINE_EVIDENCE_EXTENSION).put(declineKey(groupId, welcomeId, author), encodeDeclineEvidence(evidence));
|
|
486
|
+
}
|
|
487
|
+
/**
|
|
488
|
+
* Writes `evidence` unless a row already exists for its candidate (the hand-off is idempotent: the first row wins,
|
|
489
|
+
* anchors are immutable). A row that does not open is present: it is left as stored, never overwritten.
|
|
490
|
+
*/
|
|
491
|
+
export async function recordDeliveryEvidence(tx, evidence) {
|
|
492
|
+
const view = tx.extension(DELIVERY_EVIDENCE_EXTENSION);
|
|
493
|
+
const key = deliveryKey(evidence.groupId, evidence.candidateId);
|
|
494
|
+
if (!(await rowPresent(view, key)))
|
|
495
|
+
await view.put(key, encodeDeliveryEvidence(evidence));
|
|
496
|
+
}
|
|
497
|
+
/** Group purge: deletes every evidence row of `groupId` (group purge ends inviter matching for the group). */
|
|
498
|
+
export async function purgeGroupEvidence(tx, groupId) {
|
|
499
|
+
const deliveries = tx.extension(DELIVERY_EVIDENCE_EXTENSION);
|
|
500
|
+
for (const key of await deliveries.keys())
|
|
501
|
+
if (groupOfDeliveryKey(key) === groupId)
|
|
502
|
+
await deliveries.delete(key);
|
|
503
|
+
const declines = tx.extension(DECLINE_EVIDENCE_EXTENSION);
|
|
504
|
+
for (const key of await declines.keys())
|
|
505
|
+
if (partsOfDeclineKey(key)?.groupId === groupId)
|
|
506
|
+
await declines.delete(key);
|
|
507
|
+
}
|
|
508
|
+
/** Marks a stored row whose envelope or payload does not open ({@link isMalformedRowError}). */
|
|
509
|
+
export const MALFORMED_ROW = Symbol('malformed-row');
|
|
510
|
+
/**
|
|
511
|
+
* The stored value at `key`, `undefined` when absent, or {@link MALFORMED_ROW} when the row is present but does not
|
|
512
|
+
* open. Any other read error (storage, backend, version, lease) propagates.
|
|
513
|
+
*/
|
|
514
|
+
export async function getOrMalformed(view, key) {
|
|
515
|
+
try {
|
|
516
|
+
return await view.get(key);
|
|
517
|
+
}
|
|
518
|
+
catch (error) {
|
|
519
|
+
if (isMalformedRowError(error))
|
|
520
|
+
return MALFORMED_ROW;
|
|
521
|
+
throw error;
|
|
522
|
+
}
|
|
523
|
+
}
|
|
524
|
+
/** Whether a row exists at `key` — a row that does not open counts as present (present but unusable). */
|
|
525
|
+
async function rowPresent(view, key) {
|
|
526
|
+
return (await getOrMalformed(view, key)) !== undefined;
|
|
527
|
+
}
|
|
528
|
+
/** The decoded row at `key`; `undefined` when absent or malformed (envelope or payload). Other read errors propagate. */
|
|
529
|
+
async function decodedOrSkipped(view, key, decode) {
|
|
530
|
+
const raw = await getOrMalformed(view, key);
|
|
531
|
+
if (raw === undefined || raw === MALFORMED_ROW)
|
|
532
|
+
return undefined;
|
|
533
|
+
try {
|
|
534
|
+
return decode(key, raw);
|
|
535
|
+
}
|
|
536
|
+
catch (error) {
|
|
537
|
+
if (isMalformedRowError(error))
|
|
538
|
+
return undefined;
|
|
539
|
+
throw error;
|
|
540
|
+
}
|
|
541
|
+
}
|
|
542
|
+
/**
|
|
543
|
+
* SC-13: one page of the account's decline candidates, in `<groupId>/<candidateId>` order after the cursor `after`,
|
|
544
|
+
* at most `limit` long. READ-ONLY: it never writes, prunes, publishes or opens a group — a retained pre-upgrade
|
|
545
|
+
* record's backfill is synthesized here, not written. Malformed evidence rows and undecodable records are skipped; a
|
|
546
|
+
* failed read propagates. Keyset pagination: each candidate is returned at most once across pages; one created
|
|
547
|
+
* meanwhile below the cursor surfaces through the live `declineCandidate` event registered before the scan.
|
|
548
|
+
*
|
|
549
|
+
* Cost: the ordered delivery keys skip everything up to the cursor without a read; from there the walk reads one
|
|
550
|
+
* delivery row and its set's decline row per key until the page is full and one more candidate proves `next`. A
|
|
551
|
+
* delivery whose own selector does not name it but whose set an unqualified or legacy decline covers needs its set's
|
|
552
|
+
* KeyPackages (`ambiguous` vs `actionable`): delivery keys do not carry the Welcome or the recipient, so that reads
|
|
553
|
+
* the delivery rows of its group once per page, indexed by set, and matches each such set once per page.
|
|
554
|
+
*/
|
|
555
|
+
export async function scanDeclineCandidates(tx, opts) {
|
|
556
|
+
const deliveryView = tx.extension(DELIVERY_EVIDENCE_EXTENSION);
|
|
557
|
+
const declineView = tx.extension(DECLINE_EVIDENCE_EXTENSION);
|
|
558
|
+
const storedKeys = await deliveryView.keys();
|
|
559
|
+
const stored = new Set(storedKeys);
|
|
560
|
+
const declineKeys = new Set(await declineView.keys());
|
|
561
|
+
// The virtual backfill: exactly what materializeLegacyEvidence would write, merged in memory. A stored delivery
|
|
562
|
+
// key — decodable or not — is present; only absent ones are synthesized (and only those are hashed).
|
|
563
|
+
const virtual = new Map();
|
|
564
|
+
const legacyMarked = new Set();
|
|
565
|
+
for (const record of opts.legacy) {
|
|
566
|
+
const { deliveries, legacyDeclines } = await missingLegacyDeliveries(record, (key) => stored.has(key) || virtual.has(key), true);
|
|
567
|
+
for (const d of deliveries)
|
|
568
|
+
virtual.set(deliveryKey(d.groupId, d.candidateId), d);
|
|
569
|
+
for (const l of legacyDeclines)
|
|
570
|
+
legacyMarked.add(declineKey(l.groupId, l.welcomeId, l.author));
|
|
571
|
+
}
|
|
572
|
+
// Every delivery key in order; keyset: start strictly after the cursor.
|
|
573
|
+
// Always sorted here, not trusted from `keys()`: a consumer store that breaks the sorted-keys contract must not make the
|
|
574
|
+
// keyset cursor skip or repeat candidates (the keys are already read in full, so this costs no extra store access).
|
|
575
|
+
const ordered = [...storedKeys, ...virtual.keys()].sort(compareKeys);
|
|
576
|
+
const after = opts.after;
|
|
577
|
+
let start = 0;
|
|
578
|
+
if (after !== undefined) {
|
|
579
|
+
let hi = ordered.length;
|
|
580
|
+
while (start < hi) {
|
|
581
|
+
const mid = (start + hi) >>> 1;
|
|
582
|
+
if (compareKeys(ordered[mid], after) > 0)
|
|
583
|
+
hi = mid;
|
|
584
|
+
else
|
|
585
|
+
start = mid + 1;
|
|
586
|
+
}
|
|
587
|
+
}
|
|
588
|
+
const decoded = new Map();
|
|
589
|
+
const deliveryAt = async (key) => {
|
|
590
|
+
const synthesized = virtual.get(key);
|
|
591
|
+
if (synthesized !== undefined)
|
|
592
|
+
return synthesized;
|
|
593
|
+
if (!decoded.has(key))
|
|
594
|
+
decoded.set(key, await decodedOrSkipped(deliveryView, key, decodeDeliveryEvidence));
|
|
595
|
+
return decoded.get(key);
|
|
596
|
+
};
|
|
597
|
+
const declineRows = new Map();
|
|
598
|
+
const declineOf = async (setKey) => {
|
|
599
|
+
if (!declineRows.has(setKey)) {
|
|
600
|
+
const storedRow = declineKeys.has(setKey) && partsOfDeclineKey(setKey) !== undefined ? await decodedOrSkipped(declineView, setKey, decodeDeclineEvidence) : undefined;
|
|
601
|
+
declineRows.set(setKey, legacyMarked.has(setKey) ? (withLegacy(storedRow) ?? storedRow) : storedRow);
|
|
602
|
+
}
|
|
603
|
+
return declineRows.get(setKey);
|
|
604
|
+
};
|
|
605
|
+
// A covering decline's set, resolved once per page: the group's deliveries are read and indexed by their set key once,
|
|
606
|
+
// and each set is matched once, its candidates cached by id for every delivery of it the page reaches.
|
|
607
|
+
// The ordered keys are bucketed by group once (on first need), so a page spanning many covered groups does not walk
|
|
608
|
+
// the account's whole key list per group.
|
|
609
|
+
let keysByGroup;
|
|
610
|
+
const keysOfGroup = (groupId) => {
|
|
611
|
+
if (keysByGroup === undefined) {
|
|
612
|
+
keysByGroup = new Map();
|
|
613
|
+
for (const key of ordered) {
|
|
614
|
+
const g = groupOfDeliveryKey(key);
|
|
615
|
+
const bucket = keysByGroup.get(g);
|
|
616
|
+
if (bucket === undefined)
|
|
617
|
+
keysByGroup.set(g, [key]);
|
|
618
|
+
else
|
|
619
|
+
bucket.push(key);
|
|
620
|
+
}
|
|
621
|
+
}
|
|
622
|
+
return keysByGroup.get(groupId) ?? [];
|
|
623
|
+
};
|
|
624
|
+
const indexedGroups = new Map();
|
|
625
|
+
const setsOfGroup = async (groupId) => {
|
|
626
|
+
let sets = indexedGroups.get(groupId);
|
|
627
|
+
if (sets === undefined) {
|
|
628
|
+
sets = new Map();
|
|
629
|
+
for (const key of keysOfGroup(groupId)) {
|
|
630
|
+
const x = await deliveryAt(key);
|
|
631
|
+
if (x === undefined)
|
|
632
|
+
continue;
|
|
633
|
+
const setKey = declineKey(x.groupId, x.welcomeId, x.recipient);
|
|
634
|
+
const members = sets.get(setKey);
|
|
635
|
+
if (members === undefined)
|
|
636
|
+
sets.set(setKey, [x]);
|
|
637
|
+
else
|
|
638
|
+
members.push(x);
|
|
639
|
+
}
|
|
640
|
+
indexedGroups.set(groupId, sets);
|
|
641
|
+
}
|
|
642
|
+
return sets;
|
|
643
|
+
};
|
|
644
|
+
const coveredCandidates = new Map();
|
|
645
|
+
const candidatesOfCoveredSet = async (d, setKey, row) => {
|
|
646
|
+
let byId = coveredCandidates.get(setKey);
|
|
647
|
+
if (byId === undefined) {
|
|
648
|
+
const set = (await setsOfGroup(d.groupId)).get(setKey) ?? [];
|
|
649
|
+
byId = new Map(matchCandidates(opts.account, set, [{ groupId: d.groupId, welcomeId: d.welcomeId, author: d.recipient, evidence: row }]).map((c) => [c.candidateId, c]));
|
|
650
|
+
coveredCandidates.set(setKey, byId);
|
|
651
|
+
}
|
|
652
|
+
return byId;
|
|
653
|
+
};
|
|
654
|
+
const found = [];
|
|
655
|
+
for (let i = start; i < ordered.length && found.length <= opts.limit; i++) {
|
|
656
|
+
const d = await deliveryAt(ordered[i]);
|
|
657
|
+
if (d === undefined)
|
|
658
|
+
continue;
|
|
659
|
+
const setKey = declineKey(d.groupId, d.welcomeId, d.recipient);
|
|
660
|
+
const row = await declineOf(setKey);
|
|
661
|
+
if (row === undefined)
|
|
662
|
+
continue;
|
|
663
|
+
const selected = row.qualified.some((q) => q.inviteeRef === d.inviteeRef);
|
|
664
|
+
if (!selected && row.unqualifiedAt === undefined && row.legacy !== true)
|
|
665
|
+
continue;
|
|
666
|
+
// A selector decides on its own; a covering decline needs the whole set (never decided by elimination).
|
|
667
|
+
const candidate = selected
|
|
668
|
+
? matchCandidates(opts.account, [d], [{ groupId: d.groupId, welcomeId: d.welcomeId, author: d.recipient, evidence: row }]).find((c) => c.candidateId === d.candidateId)
|
|
669
|
+
: (await candidatesOfCoveredSet(d, setKey, row)).get(d.candidateId);
|
|
670
|
+
if (candidate !== undefined)
|
|
671
|
+
found.push(candidate);
|
|
672
|
+
}
|
|
673
|
+
const candidates = found.slice(0, opts.limit);
|
|
674
|
+
const last = candidates[candidates.length - 1];
|
|
675
|
+
return found.length <= opts.limit || last === undefined ? { candidates, complete: true } : { candidates, next: deliveryKey(last.groupId, last.candidateId), complete: false };
|
|
676
|
+
}
|
|
677
|
+
async function locateDelivery(tx, opts) {
|
|
678
|
+
const deliveryView = tx.extension(DELIVERY_EVIDENCE_EXTENSION);
|
|
679
|
+
const groupKeys = (await deliveryView.keys()).filter((key) => groupOfDeliveryKey(key) === opts.groupId);
|
|
680
|
+
const stored = new Set(groupKeys);
|
|
681
|
+
const virtual = new Map();
|
|
682
|
+
const legacyMarked = new Set();
|
|
683
|
+
for (const record of opts.legacy) {
|
|
684
|
+
if (record.groupId !== opts.groupId)
|
|
685
|
+
continue;
|
|
686
|
+
const { deliveries, legacyDeclines } = await missingLegacyDeliveries(record, (key) => stored.has(key) || virtual.has(key), true);
|
|
687
|
+
for (const d of deliveries)
|
|
688
|
+
virtual.set(deliveryKey(d.groupId, d.candidateId), d);
|
|
689
|
+
for (const l of legacyDeclines)
|
|
690
|
+
legacyMarked.add(declineKey(l.groupId, l.welcomeId, l.author));
|
|
691
|
+
}
|
|
692
|
+
const deliveryAt = async (key) => virtual.get(key) ?? (stored.has(key) ? await decodedOrSkipped(deliveryView, key, decodeDeliveryEvidence) : undefined);
|
|
693
|
+
const delivery = await deliveryAt(deliveryKey(opts.groupId, opts.candidateId));
|
|
694
|
+
if (delivery === undefined)
|
|
695
|
+
return undefined;
|
|
696
|
+
const setKey = declineKey(delivery.groupId, delivery.welcomeId, delivery.recipient);
|
|
697
|
+
const storedRow = await decodedOrSkipped(tx.extension(DECLINE_EVIDENCE_EXTENSION), setKey, decodeDeclineEvidence);
|
|
698
|
+
const row = legacyMarked.has(setKey) ? (withLegacy(storedRow) ?? storedRow) : storedRow;
|
|
699
|
+
const set = async () => {
|
|
700
|
+
const out = [];
|
|
701
|
+
for (const key of [...groupKeys, ...virtual.keys()]) {
|
|
702
|
+
const d = await deliveryAt(key);
|
|
703
|
+
if (d !== undefined && declineKey(d.groupId, d.welcomeId, d.recipient) === setKey)
|
|
704
|
+
out.push(d);
|
|
705
|
+
}
|
|
706
|
+
return out;
|
|
707
|
+
};
|
|
708
|
+
return { delivery, row, set };
|
|
709
|
+
}
|
|
710
|
+
/** Whether `row` holds the delivery's own selector, or a covering (unqualified or legacy) decline of its set. */
|
|
711
|
+
function declineOfDelivery(row, delivery) {
|
|
712
|
+
if (row.qualified.some((q) => q.inviteeRef === delivery.inviteeRef))
|
|
713
|
+
return 'selected';
|
|
714
|
+
return row.unqualifiedAt !== undefined || row.legacy === true ? 'covered' : undefined;
|
|
715
|
+
}
|
|
716
|
+
/**
|
|
717
|
+
* Epic marmot-invitation-outcomes S4: one delivery and its candidate by identity, read-only — the candidate exactly as
|
|
718
|
+
* {@link scanDeclineCandidates} returns it (the same virtual backfill of `groupId`'s retained records in `legacy`, the
|
|
719
|
+
* same set matching). `undefined` when no delivery (stored and decodable, or synthesized) has that identity; a delivery
|
|
720
|
+
* without decline evidence comes back without a candidate. A malformed row is no delivery; a failed read propagates.
|
|
721
|
+
*
|
|
722
|
+
* Cost: the group's delivery keys, the delivery row and its set's decline row. Only a delivery a covering (unqualified
|
|
723
|
+
* or legacy) decline holds without its own selector reads the rest of its group's delivery rows — its set's
|
|
724
|
+
* KeyPackages decide `actionable` vs `ambiguous`; a selector decides on its own, as in the scan.
|
|
725
|
+
*/
|
|
726
|
+
export async function findDeclineCandidate(tx, opts) {
|
|
727
|
+
const located = await locateDelivery(tx, opts);
|
|
728
|
+
if (located === undefined)
|
|
729
|
+
return undefined;
|
|
730
|
+
const { delivery, row } = located;
|
|
731
|
+
const kind = row === undefined ? undefined : declineOfDelivery(row, delivery);
|
|
732
|
+
if (row === undefined || kind === undefined)
|
|
733
|
+
return { delivery };
|
|
734
|
+
const evidence = [{ groupId: delivery.groupId, welcomeId: delivery.welcomeId, author: delivery.recipient, evidence: row }];
|
|
735
|
+
const set = kind === 'selected' ? [delivery] : await located.set();
|
|
736
|
+
const candidate = matchCandidates(opts.account, set, evidence).find((c) => c.candidateId === opts.candidateId);
|
|
737
|
+
return candidate === undefined ? { delivery } : { delivery, candidate };
|
|
738
|
+
}
|
|
739
|
+
/**
|
|
740
|
+
* Whether {@link findDeclineCandidate} would return a candidate, without resolving it: a delivery holds a candidate
|
|
741
|
+
* exactly when its set's decline row selects it or covers its set (the delivery is a member of its own set). Reads the
|
|
742
|
+
* group's delivery keys, the delivery row and its set's decline row — never the rest of the set.
|
|
743
|
+
*/
|
|
744
|
+
export async function hasDeclineCandidate(tx, opts) {
|
|
745
|
+
const located = await locateDelivery(tx, opts);
|
|
746
|
+
return located?.row !== undefined && declineOfDelivery(located.row, located.delivery) !== undefined;
|
|
747
|
+
}
|
|
748
|
+
/**
|
|
749
|
+
* SC-13: the validated paging options of `invitations.declineCandidates(options?)` — `after` a cursor string (a
|
|
750
|
+
* previous page's `next`), `limit` a finite number clamped to `[1, DECLINE_SCAN_PAGE_MAX]` (default: the maximum).
|
|
751
|
+
* Throws `invalid-options` for anything else.
|
|
752
|
+
*/
|
|
753
|
+
export function declineScanOptions(options) {
|
|
754
|
+
const fail = (reason, message) => new MarmotError('invalid-options', `invitations.declineCandidates: ${message}`, { details: { reason } });
|
|
755
|
+
if (options === undefined)
|
|
756
|
+
return { limit: DECLINE_SCAN_PAGE_MAX };
|
|
757
|
+
if (!isObject(options))
|
|
758
|
+
throw fail('invalid-options', 'options must be an object');
|
|
759
|
+
const { after, limit } = options;
|
|
760
|
+
if (after !== undefined && typeof after !== 'string')
|
|
761
|
+
throw fail('invalid-after', 'options.after must be a string (a previous page’s `next`)');
|
|
762
|
+
if (limit !== undefined && (typeof limit !== 'number' || !Number.isFinite(limit)))
|
|
763
|
+
throw fail('invalid-limit', 'options.limit must be a finite number');
|
|
764
|
+
const clamped = limit === undefined ? DECLINE_SCAN_PAGE_MAX : Math.min(DECLINE_SCAN_PAGE_MAX, Math.max(1, Math.floor(limit)));
|
|
765
|
+
return { ...(after === undefined ? {} : { after }), limit: clamped };
|
|
766
|
+
}
|