@941design/marmot 0.0.0-stage → 0.2.0-alpha.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +739 -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 +190 -0
- package/dist/account/teardown.js +878 -0
- 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-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 +182 -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 +92 -0
- package/dist/client/commit-redrive.js +274 -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 +55 -0
- package/dist/client/confirm-hooks.js +74 -0
- package/dist/client/create-client.d.ts +1126 -0
- package/dist/client/create-client.js +1232 -0
- package/dist/client/group-availability.d.ts +182 -0
- package/dist/client/group-availability.js +301 -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 +461 -0
- package/dist/client/group-history.js +1365 -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 +522 -0
- package/dist/client/group-records.js +1117 -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 +415 -0
- package/dist/client/group-runtime.js +2811 -0
- package/dist/client/group-snapshot.d.ts +104 -0
- package/dist/client/group-snapshot.js +474 -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 +24 -0
- package/dist/client/index.js +13 -0
- package/dist/client/ingest.d.ts +82 -0
- package/dist/client/ingest.js +1584 -0
- package/dist/client/invitation-outcomes.d.ts +50 -0
- package/dist/client/invitation-outcomes.js +135 -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 +82 -0
- package/dist/client/opaque-candidates.js +170 -0
- package/dist/client/own-change-outbox.d.ts +66 -0
- package/dist/client/own-change-outbox.js +158 -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 +583 -0
- package/dist/client/pipeline.js +3666 -0
- package/dist/client/reentrancy-guard.d.ts +102 -0
- package/dist/client/reentrancy-guard.js +159 -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/admission-lineage.d.ts +186 -0
- package/dist/history/admission-lineage.js +589 -0
- package/dist/history/equivocation.d.ts +55 -0
- package/dist/history/equivocation.js +113 -0
- package/dist/history/fencing.d.ts +66 -0
- package/dist/history/fencing.js +121 -0
- package/dist/history/hex.d.ts +3 -0
- package/dist/history/hex.js +10 -0
- package/dist/history/index.d.ts +74 -0
- package/dist/history/index.js +32 -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 +118 -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 +67 -0
- package/dist/invitations/decline.js +149 -0
- package/dist/invitations/delivery-evidence.d.ts +288 -0
- package/dist/invitations/delivery-evidence.js +766 -0
- package/dist/invitations/expect-welcome.d.ts +66 -0
- package/dist/invitations/expect-welcome.js +138 -0
- package/dist/invitations/index.d.ts +18 -0
- package/dist/invitations/index.js +18 -0
- package/dist/invitations/invitation-outcome.d.ts +110 -0
- package/dist/invitations/invitation-outcome.js +210 -0
- package/dist/invitations/invite.d.ts +358 -0
- package/dist/invitations/invite.js +1102 -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 +272 -0
- package/dist/invitations/welcome-processor.js +1241 -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 +28 -0
- package/dist/shared/errors.js +96 -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 +237 -0
- package/dist/storage/index.js +491 -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 +54 -0
- package/dist/storage/lease.js +168 -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,1241 @@
|
|
|
1
|
+
import { getCredentialPubkey, getGroupIdHex, getKeyPackage, getWelcomeKeyPackageRefs, joinGroupFromWelcomeWithSigner, } from '@941design/marmot-engine/core';
|
|
2
|
+
import { ciphersuites, decode, defaultCryptoProvider, getCiphersuiteImpl, mlsMessageDecoder, } from '@941design/marmot-engine/mls';
|
|
3
|
+
import { maintenanceFailureReason } from '../inbox/index.js';
|
|
4
|
+
import { findKeyPackageEventByRef, findPrivateKeyPackage } from '../key-packages/index.js';
|
|
5
|
+
import { hexOfBytes, isHex64, isMarmotError, MarmotError, RUMOR_KINDS } from '../shared/index.js';
|
|
6
|
+
import { epochOf, judgeCompetingWelcome, otherLeafSignatureKeysOf, terminalClassOf } from './competing-welcome.js';
|
|
7
|
+
import { welcomeCommitTagOf } from './invite.js';
|
|
8
|
+
import { attemptDeclineDelivery, buildDeclineRumor, decodeDecline, decodeRumor, encodeDecline, encodeRumor } from './decline.js';
|
|
9
|
+
import { matchManifest, readManifest, recordManifest, validateManifest, writeManifest } from './expect-welcome.js';
|
|
10
|
+
import { isMalformedRowError } from '../shared/index.js';
|
|
11
|
+
// ---------------------------------------------------------------------------
|
|
12
|
+
// Welcome decoding and identity
|
|
13
|
+
// ---------------------------------------------------------------------------
|
|
14
|
+
function base64ToBytes(content) {
|
|
15
|
+
const binary = globalThis.atob(content);
|
|
16
|
+
const bytes = new Uint8Array(binary.length);
|
|
17
|
+
for (let i = 0; i < binary.length; i++)
|
|
18
|
+
bytes[i] = binary.charCodeAt(i);
|
|
19
|
+
return bytes;
|
|
20
|
+
}
|
|
21
|
+
function toHex(bytes) {
|
|
22
|
+
return Array.from(bytes, (b) => b.toString(16).padStart(2, '0')).join('');
|
|
23
|
+
}
|
|
24
|
+
/** The MLS Welcome of a Welcome rumor, decoded from its base64 content (no tag is required). Throws on anything else. */
|
|
25
|
+
export function decodeWelcomeRumor(rumor) {
|
|
26
|
+
if (rumor.kind !== RUMOR_KINDS.WELCOME)
|
|
27
|
+
throw new Error(`not a Welcome rumor (kind ${rumor.kind})`);
|
|
28
|
+
const message = decode(mlsMessageDecoder, base64ToBytes(rumor.content));
|
|
29
|
+
if (message === undefined || !('welcome' in message))
|
|
30
|
+
throw new Error('rumor content is not an MLS Welcome');
|
|
31
|
+
return message.welcome;
|
|
32
|
+
}
|
|
33
|
+
/** The Welcome identity: hex SHA-256 of the serialized MLS Welcome (the rumor content, base64-decoded). */
|
|
34
|
+
export async function welcomeIdOf(rumor) {
|
|
35
|
+
const digest = await globalThis.crypto.subtle.digest('SHA-256', base64ToBytes(rumor.content));
|
|
36
|
+
return toHex(new Uint8Array(digest));
|
|
37
|
+
}
|
|
38
|
+
const INVITATIONS = 'pendingInvitations';
|
|
39
|
+
const STATUSES = new Set(['pending', 'joining', 'joined', 'declined', 'rejected', 'competing']);
|
|
40
|
+
function malformed(id, detail) {
|
|
41
|
+
return new MarmotError('store-failed', `pendingInvitations/${id}: malformed record (${detail})`, { details: { id, malformed: true } });
|
|
42
|
+
}
|
|
43
|
+
function optionalString(id, record, field) {
|
|
44
|
+
const value = record[field];
|
|
45
|
+
if (value !== undefined && typeof value !== 'string')
|
|
46
|
+
throw malformed(id, field);
|
|
47
|
+
return value;
|
|
48
|
+
}
|
|
49
|
+
function decodeAdoption(id, raw) {
|
|
50
|
+
const r = raw;
|
|
51
|
+
if (typeof r !== 'object' || r === null || Array.isArray(r))
|
|
52
|
+
throw malformed(id, 'adoption');
|
|
53
|
+
if ((r.via !== 'join' && r.via !== 'switch') || (r.source !== 'group-proof' && r.source !== 'legacy-index') || typeof r.at !== 'number' || !Number.isFinite(r.at)) {
|
|
54
|
+
throw malformed(id, 'adoption');
|
|
55
|
+
}
|
|
56
|
+
return { via: r.via, source: r.source, at: r.at };
|
|
57
|
+
}
|
|
58
|
+
export function decodeInvitation(id, raw) {
|
|
59
|
+
if (typeof raw !== 'object' || raw === null || Array.isArray(raw))
|
|
60
|
+
throw malformed(id, 'not an object');
|
|
61
|
+
const r = raw;
|
|
62
|
+
if (r.v !== 1 || r.id !== id || typeof r.status !== 'string' || !STATUSES.has(r.status) || typeof r.receivedAt !== 'number')
|
|
63
|
+
throw malformed(id, 'header');
|
|
64
|
+
if (r.rotation !== undefined && r.rotation !== 'pending' && r.rotation !== 'done' && r.rotation !== 'failed')
|
|
65
|
+
throw malformed(id, 'rotation');
|
|
66
|
+
const f = r.failures;
|
|
67
|
+
if (f !== undefined && (typeof f !== 'object' || f === null || !Object.values(f).every((n) => typeof n === 'number')))
|
|
68
|
+
throw malformed(id, 'failures');
|
|
69
|
+
const joinFailed = optionalString(id, r, 'joinFailed');
|
|
70
|
+
if (r.deferred !== undefined && r.deferred !== 'restore-in-flight')
|
|
71
|
+
throw malformed(id, 'deferred');
|
|
72
|
+
const groupId = optionalString(id, r, 'groupId');
|
|
73
|
+
const sponsorAccount = optionalString(id, r, 'sponsorAccount');
|
|
74
|
+
const keyPackageRef = optionalString(id, r, 'keyPackageRef');
|
|
75
|
+
const reason = optionalString(id, r, 'reason');
|
|
76
|
+
const where = `pendingInvitations/${id}`;
|
|
77
|
+
let switching;
|
|
78
|
+
if (r.switching !== undefined) {
|
|
79
|
+
const s = r.switching;
|
|
80
|
+
if (r.status !== 'competing' || s === null || typeof s !== 'object' || typeof s.from !== 'string' || s.from.length === 0 || typeof s.to !== 'string' || s.to.length === 0)
|
|
81
|
+
throw malformed(id, 'switching');
|
|
82
|
+
switching = { from: s.from, to: s.to };
|
|
83
|
+
}
|
|
84
|
+
let pinned;
|
|
85
|
+
if (r.pinned !== undefined) {
|
|
86
|
+
const p = r.pinned;
|
|
87
|
+
const event = p?.event;
|
|
88
|
+
if (p === null || typeof p !== 'object' || p.privatePackage === undefined || typeof event !== 'object' || event === null || typeof event.id !== 'string' || typeof event.content !== 'string' || !Array.isArray(event.tags)) {
|
|
89
|
+
throw malformed(id, 'pinned');
|
|
90
|
+
}
|
|
91
|
+
pinned = { event: event, privatePackage: p.privatePackage };
|
|
92
|
+
}
|
|
93
|
+
return {
|
|
94
|
+
v: 1,
|
|
95
|
+
id,
|
|
96
|
+
status: r.status,
|
|
97
|
+
receivedAt: r.receivedAt,
|
|
98
|
+
...(groupId === undefined ? {} : { groupId }),
|
|
99
|
+
...(sponsorAccount === undefined ? {} : { sponsorAccount }),
|
|
100
|
+
...(keyPackageRef === undefined ? {} : { keyPackageRef }),
|
|
101
|
+
...(r.rumor === undefined ? {} : { rumor: decodeRumor(where, r.rumor, RUMOR_KINDS.WELCOME) }),
|
|
102
|
+
...(pinned === undefined ? {} : { pinned }),
|
|
103
|
+
...(r.rotation === undefined ? {} : { rotation: r.rotation }),
|
|
104
|
+
...(f === undefined ? {} : { failures: { ...f } }),
|
|
105
|
+
...(joinFailed === undefined ? {} : { joinFailed }),
|
|
106
|
+
...(r.deferred === undefined ? {} : { deferred: 'restore-in-flight' }),
|
|
107
|
+
...(reason === undefined ? {} : { reason }),
|
|
108
|
+
...(r.decline === undefined ? {} : { decline: decodeDecline(where, r.decline) }),
|
|
109
|
+
...(switching === undefined ? {} : { switching }),
|
|
110
|
+
...(r.adoption === undefined ? {} : { adoption: decodeAdoption(id, r.adoption) }),
|
|
111
|
+
};
|
|
112
|
+
}
|
|
113
|
+
export function encodeInvitation(record) {
|
|
114
|
+
return {
|
|
115
|
+
v: 1,
|
|
116
|
+
id: record.id,
|
|
117
|
+
status: record.status,
|
|
118
|
+
receivedAt: record.receivedAt,
|
|
119
|
+
...(record.groupId === undefined ? {} : { groupId: record.groupId }),
|
|
120
|
+
...(record.sponsorAccount === undefined ? {} : { sponsorAccount: record.sponsorAccount }),
|
|
121
|
+
...(record.keyPackageRef === undefined ? {} : { keyPackageRef: record.keyPackageRef }),
|
|
122
|
+
...(record.rumor === undefined ? {} : { rumor: encodeRumor(record.rumor) }),
|
|
123
|
+
...(record.pinned === undefined ? {} : { pinned: { event: { ...record.pinned.event, tags: record.pinned.event.tags.map((t) => [...t]) }, privatePackage: record.pinned.privatePackage } }),
|
|
124
|
+
...(record.rotation === undefined ? {} : { rotation: record.rotation }),
|
|
125
|
+
...(record.failures === undefined ? {} : { failures: { ...record.failures } }),
|
|
126
|
+
...(record.joinFailed === undefined ? {} : { joinFailed: record.joinFailed }),
|
|
127
|
+
...(record.deferred === undefined ? {} : { deferred: record.deferred }),
|
|
128
|
+
...(record.reason === undefined ? {} : { reason: record.reason }),
|
|
129
|
+
...(record.decline === undefined ? {} : { decline: encodeDecline(record.decline) }),
|
|
130
|
+
...(record.switching === undefined ? {} : { switching: { from: record.switching.from, to: record.switching.to } }),
|
|
131
|
+
...(record.adoption === undefined ? {} : { adoption: { via: record.adoption.via, source: record.adoption.source, at: record.adoption.at } }),
|
|
132
|
+
};
|
|
133
|
+
}
|
|
134
|
+
async function readInvitation(view, id) {
|
|
135
|
+
const raw = await view.get(id);
|
|
136
|
+
return raw === undefined ? undefined : decodeInvitation(id, raw);
|
|
137
|
+
}
|
|
138
|
+
async function writeInvitation(view, record) {
|
|
139
|
+
await view.put(record.id, encodeInvitation(record));
|
|
140
|
+
}
|
|
141
|
+
/** Whether a stored adoption stamp decodes: only a readable stamp is evidence to preserve a record as `joined` at purge. */
|
|
142
|
+
function hasDecodableAdoption(id, raw) {
|
|
143
|
+
try {
|
|
144
|
+
decodeAdoption(id, raw);
|
|
145
|
+
return true;
|
|
146
|
+
}
|
|
147
|
+
catch {
|
|
148
|
+
return false;
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
/**
|
|
152
|
+
* S9 teardown: the consumed KeyPackageRefs of the invitations that named
|
|
153
|
+
* `groupId` (their retained keys are purged with the group); deletes the
|
|
154
|
+
* still-`pending` ones among them and turns an interrupted `joining` one
|
|
155
|
+
* terminal (`rejected`, reason `abandoned`, pinned key and Welcome dropped). Decided invitations (joined, declined,
|
|
156
|
+
* rejected) are kept: they are what makes a redelivered Welcome of the
|
|
157
|
+
* abandoned group a no-op rather than a re-join (at-most-once join).
|
|
158
|
+
*
|
|
159
|
+
* Epic marmot-invitation-outcomes S2: a record teardown stamped (`adoption`, written by `stampAdoptions` before this
|
|
160
|
+
* runs) caused the adoption — whatever its status, it becomes `joined` with its stamp (pinned key, Welcome and open
|
|
161
|
+
* markers dropped), never `rejected/abandoned` nor deleted: its outcome reads `joined` after the purge, and a
|
|
162
|
+
* redelivered Welcome answers `already-member`.
|
|
163
|
+
*/
|
|
164
|
+
export async function purgeGroupInvitations(tx, groupId) {
|
|
165
|
+
const view = tx.artifact(INVITATIONS);
|
|
166
|
+
const refs = [];
|
|
167
|
+
for (const key of await view.keys()) {
|
|
168
|
+
let raw;
|
|
169
|
+
try {
|
|
170
|
+
raw = (await view.get(key));
|
|
171
|
+
}
|
|
172
|
+
catch (error) {
|
|
173
|
+
// A row whose envelope does not open names no group this purge could act on: it never aborts an unrelated
|
|
174
|
+
// group's teardown. A version mismatch or a backend failure still propagates.
|
|
175
|
+
if (isMalformedRowError(error))
|
|
176
|
+
continue;
|
|
177
|
+
throw error;
|
|
178
|
+
}
|
|
179
|
+
if (typeof raw !== 'object' || raw === null || raw.groupId !== groupId)
|
|
180
|
+
continue;
|
|
181
|
+
if (typeof raw.keyPackageRef === 'string')
|
|
182
|
+
refs.push(raw.keyPackageRef);
|
|
183
|
+
if (raw.adoption !== undefined && hasDecodableAdoption(key, raw.adoption) && (raw.status === 'pending' || raw.status === 'competing' || raw.status === 'joining')) {
|
|
184
|
+
const { rumor: _rumor, pinned: _pinned, deferred: _deferred, switching: _switching, joinFailed: _joinFailed, reason: _reason, ...rest } = raw;
|
|
185
|
+
await view.put(key, { ...rest, status: 'joined' });
|
|
186
|
+
continue;
|
|
187
|
+
}
|
|
188
|
+
// A `competing` record (a second Welcome waiting for the group's gate) goes with the group it was to switch.
|
|
189
|
+
if (raw.status === 'pending' || raw.status === 'competing')
|
|
190
|
+
await view.delete(key);
|
|
191
|
+
// An interrupted join (persisted the group, crashed before `joined`) would be completed by the next pass and
|
|
192
|
+
// bring the group back: terminal, its pinned key and Welcome dropped.
|
|
193
|
+
else if (raw.status === 'joining') {
|
|
194
|
+
const { rumor: _rumor, pinned: _pinned, deferred: _deferred, ...rest } = raw;
|
|
195
|
+
await view.put(key, { ...rest, status: 'rejected', reason: 'abandoned' });
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
return refs;
|
|
199
|
+
}
|
|
200
|
+
/** Permanent failures after which one maintenance item of an invitation is given up (`maintenanceFailed`). */
|
|
201
|
+
export const MAX_MAINTENANCE_FAILURES = 10;
|
|
202
|
+
/** The join evidence of a candidate: only a tagged Welcome has any (an untagged one is the sponsor's older build). */
|
|
203
|
+
function joinEvidenceOf(candidate, rumor) {
|
|
204
|
+
const digest = welcomeCommitTagOf(rumor);
|
|
205
|
+
return digest !== undefined && isHex64(candidate.sponsorAccount) ? { digest, committer: candidate.sponsorAccount } : undefined;
|
|
206
|
+
}
|
|
207
|
+
/** The competing branch a candidate Welcome stands for, as the decision compares it. */
|
|
208
|
+
function competingBranchOf(candidate, rumor) {
|
|
209
|
+
return {
|
|
210
|
+
epoch: epochOf(candidate.state),
|
|
211
|
+
tag: hexOfBytes(candidate.state.confirmationTag),
|
|
212
|
+
digest: welcomeCommitTagOf(rumor),
|
|
213
|
+
sponsorAccount: candidate.sponsorAccount,
|
|
214
|
+
otherLeafSignatureKeys: otherLeafSignatureKeysOf(candidate.state),
|
|
215
|
+
};
|
|
216
|
+
}
|
|
217
|
+
const CIPHERSUITE_NAME_BY_ID = new Map(Object.entries(ciphersuites).map(([name, id]) => [id, name]));
|
|
218
|
+
/** The group runtime's answer to an `onConfirm` hook that refused inside the switch transaction (`details.reason: 'hook'`). */
|
|
219
|
+
function isHookRefusal(error) {
|
|
220
|
+
return isMarmotError(error, 'confirm-blocked') && error.details?.['reason'] === 'hook';
|
|
221
|
+
}
|
|
222
|
+
/** AC-MX-2: `adoptJoinedGroup` deferred the join — the group is being restored (transient). */
|
|
223
|
+
function isRestoreInFlight(error) {
|
|
224
|
+
return isMarmotError(error, 'commit-pending') && error.details?.reason === 'restore-in-flight';
|
|
225
|
+
}
|
|
226
|
+
function invalid(operation, message, reason, details = {}) {
|
|
227
|
+
return new MarmotError('invalid-options', `invitations.${operation}: ${message}`, { details: { reason, ...details } });
|
|
228
|
+
}
|
|
229
|
+
export function createWelcomeService(deps) {
|
|
230
|
+
const ciphersuiteCache = new Map();
|
|
231
|
+
/** Rotations and decline deliveries in flight off the inbox queue, by invitation. */
|
|
232
|
+
const maintenance = new Map();
|
|
233
|
+
function ciphersuiteFor(id) {
|
|
234
|
+
let pending = ciphersuiteCache.get(id);
|
|
235
|
+
if (pending === undefined) {
|
|
236
|
+
const name = CIPHERSUITE_NAME_BY_ID.get(id);
|
|
237
|
+
if (name === undefined)
|
|
238
|
+
return Promise.reject(new Error(`unknown MLS ciphersuite id ${id}`));
|
|
239
|
+
pending = getCiphersuiteImpl(name, defaultCryptoProvider);
|
|
240
|
+
ciphersuiteCache.set(id, pending);
|
|
241
|
+
}
|
|
242
|
+
return pending;
|
|
243
|
+
}
|
|
244
|
+
function readRecord(id) {
|
|
245
|
+
return deps.transaction((tx) => readInvitation(tx.artifact(INVITATIONS), id));
|
|
246
|
+
}
|
|
247
|
+
/** The first KeyPackageRef of the Welcome's secrets this account holds both halves of. */
|
|
248
|
+
function locateKeyPackage(welcome) {
|
|
249
|
+
const refs = getWelcomeKeyPackageRefs(welcome).map(toHex);
|
|
250
|
+
return deps.transaction(async (tx) => {
|
|
251
|
+
const view = tx.artifact('keyPackages');
|
|
252
|
+
const nowMs = deps.clock.now();
|
|
253
|
+
for (const ref of refs) {
|
|
254
|
+
const privatePackage = await findPrivateKeyPackage(view, ref, nowMs);
|
|
255
|
+
if (privatePackage === undefined)
|
|
256
|
+
continue;
|
|
257
|
+
const event = await findKeyPackageEventByRef(view, ref);
|
|
258
|
+
if (event !== undefined)
|
|
259
|
+
return { ref, event, privatePackage };
|
|
260
|
+
}
|
|
261
|
+
return undefined;
|
|
262
|
+
});
|
|
263
|
+
}
|
|
264
|
+
/** The key a pending record pinned on arrival (older records: none). */
|
|
265
|
+
function pinnedOf(record) {
|
|
266
|
+
if (record?.pinned === undefined || record.keyPackageRef === undefined)
|
|
267
|
+
return undefined;
|
|
268
|
+
return { ref: record.keyPackageRef, event: record.pinned.event, privatePackage: record.pinned.privatePackage };
|
|
269
|
+
}
|
|
270
|
+
/** Steps 3–4: key lookup (or the pinned key), in-memory join recovering the GroupInfo signer, proof check. Persists nothing. */
|
|
271
|
+
async function evaluate(welcome, pinned) {
|
|
272
|
+
const local = pinned ?? (await locateKeyPackage(welcome));
|
|
273
|
+
if (local === undefined)
|
|
274
|
+
return { kind: 'no-key' };
|
|
275
|
+
let joined;
|
|
276
|
+
try {
|
|
277
|
+
const publicPackage = getKeyPackage(local.event);
|
|
278
|
+
joined = await joinGroupFromWelcomeWithSigner({
|
|
279
|
+
welcome,
|
|
280
|
+
keyPackage: { publicPackage, privatePackage: local.privatePackage },
|
|
281
|
+
ciphersuiteImpl: await ciphersuiteFor(publicPackage.cipherSuite),
|
|
282
|
+
// The group runtime's engine config: a join under another config is a silent-fork hazard (AC-VENDOR-6).
|
|
283
|
+
clientConfig: deps.clientConfig,
|
|
284
|
+
});
|
|
285
|
+
}
|
|
286
|
+
catch {
|
|
287
|
+
return { kind: 'rejected', reason: 'join-failed', keyPackageRef: local.ref };
|
|
288
|
+
}
|
|
289
|
+
const { state, signer } = joined;
|
|
290
|
+
const groupId = getGroupIdHex(state);
|
|
291
|
+
if (deps.checkJoinedState(state).length > 0)
|
|
292
|
+
return { kind: 'rejected', reason: 'proof-missing', groupId, keyPackageRef: local.ref };
|
|
293
|
+
let sponsorAccount;
|
|
294
|
+
try {
|
|
295
|
+
sponsorAccount = getCredentialPubkey(signer.credential);
|
|
296
|
+
}
|
|
297
|
+
catch {
|
|
298
|
+
// Unreachable past the proof check (every leaf carries a valid account identity); fails closed regardless.
|
|
299
|
+
return { kind: 'rejected', reason: 'proof-missing', groupId, keyPackageRef: local.ref };
|
|
300
|
+
}
|
|
301
|
+
return { kind: 'ok', state, groupId, sponsorAccount, keyPackageRef: local.ref, local };
|
|
302
|
+
}
|
|
303
|
+
/**
|
|
304
|
+
* Persists a join as intent → effect → confirm: a `joining` record (one
|
|
305
|
+
* account transaction), the group (`adoptJoinedGroup`, stamped with the
|
|
306
|
+
* Welcome's arrival), then the `joined` record — with the wrap's seen mark
|
|
307
|
+
* and the manifest's `fulfilled` — in one account transaction. Reports
|
|
308
|
+
* `joined` (and fires `groupJoined`) when this join persisted the group, or
|
|
309
|
+
* when it completes a join a crash interrupted (the record already read
|
|
310
|
+
* `joining`); a Welcome for a group already held through another path is
|
|
311
|
+
* `already-member`, silently. Rotate-after-consume then runs OFF the inbox
|
|
312
|
+
* queue (a remote signer awaiting approval must not stall the next wrap);
|
|
313
|
+
* the record keeps `rotation: 'pending'` until it is done, and every pass's
|
|
314
|
+
* `resume()` retries it.
|
|
315
|
+
*
|
|
316
|
+
* AC-MX-2: while the group is being restored, `adoptJoinedGroup` defers the
|
|
317
|
+
* join (transient, nothing adopted). The record stays `joining` (flagged
|
|
318
|
+
* `deferred`) with the wrap marked seen in the same transaction — no
|
|
319
|
+
* redelivery is unwrapped again — and the pass the restore's release runs
|
|
320
|
+
* completes it (`completeStuckJoins`): `already-member` when the restore
|
|
321
|
+
* succeeded, `joined` when it failed. From the inbox dispatch (`ctx`) that
|
|
322
|
+
* reports `deferred`; from any other caller (accept, expectWelcome, the
|
|
323
|
+
* pass's completion) the transient error propagates.
|
|
324
|
+
*/
|
|
325
|
+
async function join(id, candidate, rumor, receivedAt, ctx) {
|
|
326
|
+
const prior = await deps.transaction(async (tx) => {
|
|
327
|
+
const view = tx.artifact(INVITATIONS);
|
|
328
|
+
const current = await readInvitation(view, id);
|
|
329
|
+
if (current?.status === 'joined')
|
|
330
|
+
return current.status;
|
|
331
|
+
if (current?.status === 'joining') {
|
|
332
|
+
if (current.deferred === undefined)
|
|
333
|
+
return current.status;
|
|
334
|
+
// Deferred before anything was adopted: cleared before this attempt adopts, so a crash after the
|
|
335
|
+
// adoption is completed as an ordinary interrupted join (reported `joined`).
|
|
336
|
+
const { deferred: _deferred, ...rest } = current;
|
|
337
|
+
await writeInvitation(view, rest);
|
|
338
|
+
return 'deferred';
|
|
339
|
+
}
|
|
340
|
+
const { reason: _reason, switching: _switching, deferred: _deferred, ...base } = current ?? { v: 1, id, receivedAt };
|
|
341
|
+
// The intent carries everything the join needs (the Welcome, the pinned key): whatever interrupts it,
|
|
342
|
+
// the next pass completes it — the decision to join was made here, whatever a manifest's deadline says later.
|
|
343
|
+
await writeInvitation(view, {
|
|
344
|
+
...base,
|
|
345
|
+
status: 'joining',
|
|
346
|
+
groupId: candidate.groupId,
|
|
347
|
+
sponsorAccount: candidate.sponsorAccount,
|
|
348
|
+
keyPackageRef: candidate.keyPackageRef,
|
|
349
|
+
rumor,
|
|
350
|
+
pinned: { event: candidate.local.event, privatePackage: candidate.local.privatePackage },
|
|
351
|
+
rotation: current?.rotation === 'done' || current?.rotation === 'failed' ? current.rotation : 'pending',
|
|
352
|
+
});
|
|
353
|
+
return current?.status;
|
|
354
|
+
});
|
|
355
|
+
let adopted;
|
|
356
|
+
try {
|
|
357
|
+
// Owner decision 20: the Welcome's own stamp bounds the group's first sync (group-runtime.ts adoptJoinedGroupOp).
|
|
358
|
+
adopted = await deps.adoptJoinedGroup(candidate.groupId, candidate.state, receivedAt, joinEvidenceOf(candidate, rumor), id, rumor.created_at * 1000);
|
|
359
|
+
}
|
|
360
|
+
catch (error) {
|
|
361
|
+
if (isRestoreInFlight(error)) {
|
|
362
|
+
await deps.transaction(async (tx) => {
|
|
363
|
+
const view = tx.artifact(INVITATIONS);
|
|
364
|
+
const current = await readInvitation(view, id);
|
|
365
|
+
if (current?.status === 'joining')
|
|
366
|
+
await writeInvitation(view, { ...current, deferred: 'restore-in-flight' });
|
|
367
|
+
await ctx?.markSeen(tx);
|
|
368
|
+
});
|
|
369
|
+
if (ctx === undefined)
|
|
370
|
+
throw error;
|
|
371
|
+
return 'deferred';
|
|
372
|
+
}
|
|
373
|
+
if (!isMarmotError(error, 'not-a-member'))
|
|
374
|
+
throw error;
|
|
375
|
+
// S9: this client tore the group down (abandon, leave, destroy); the Welcome would bring its old state
|
|
376
|
+
// back. Terminal, with the pinned key and the Welcome dropped: nothing can join it any more.
|
|
377
|
+
await deps.transaction(async (tx) => {
|
|
378
|
+
const view = tx.artifact(INVITATIONS);
|
|
379
|
+
const current = await readInvitation(view, id);
|
|
380
|
+
// A stamped record caused an adoption: never turned negative (S2, negative writers skip stamps).
|
|
381
|
+
if (current !== undefined && current.status !== 'joined' && current.adoption === undefined) {
|
|
382
|
+
const { rumor: _rumor, pinned: _pinned, deferred: _deferred, ...rest } = current;
|
|
383
|
+
await writeInvitation(view, { ...rest, status: 'rejected', reason: 'abandoned' });
|
|
384
|
+
}
|
|
385
|
+
await ctx?.markSeen(tx);
|
|
386
|
+
});
|
|
387
|
+
return 'abandoned';
|
|
388
|
+
}
|
|
389
|
+
// S2 (architecture SC-7): this call's adoption is proven when it wrote the group, or — a join resumed after its
|
|
390
|
+
// group transaction committed in an earlier attempt — when the held group's proof names this invitation. An
|
|
391
|
+
// `already-member` that another invitation's Welcome caused proves nothing for this one. Read before the account
|
|
392
|
+
// transaction (group → account, never an account transaction awaiting a group scope).
|
|
393
|
+
const proof = adopted === 'already-member' && prior === 'joining' ? await deps.adoptionProofOf(candidate.groupId, id) : undefined;
|
|
394
|
+
const joined = await deps.transaction(async (tx) => {
|
|
395
|
+
const view = tx.artifact(INVITATIONS);
|
|
396
|
+
const current = await readInvitation(view, id);
|
|
397
|
+
const manifest = await readManifest(tx, candidate.groupId, candidate.keyPackageRef);
|
|
398
|
+
if (manifest?.status === 'waiting' && manifest.sponsorAccount === candidate.sponsorAccount) {
|
|
399
|
+
await writeManifest(tx, { ...manifest, status: 'fulfilled', invitationId: id });
|
|
400
|
+
await deps.onManifestFulfilled?.(tx, manifest);
|
|
401
|
+
}
|
|
402
|
+
await ctx?.markSeen(tx);
|
|
403
|
+
if (current?.status === 'joined')
|
|
404
|
+
return false;
|
|
405
|
+
const caused = adopted === 'joined' || prior === 'joining';
|
|
406
|
+
// S2 (architecture SC-7): the joined record of the adopting invitation carries its stamp (an existing one is
|
|
407
|
+
// kept), timed like teardown's A1 stamp: the proof's `at` — the arrival `adoptJoinedGroup` wrote it with.
|
|
408
|
+
const stampAt = adopted === 'joined' ? receivedAt : proof?.at;
|
|
409
|
+
const adoption = current?.adoption ?? (stampAt === undefined ? undefined : { via: 'join', source: 'group-proof', at: stampAt });
|
|
410
|
+
await writeInvitation(view, {
|
|
411
|
+
v: 1,
|
|
412
|
+
id,
|
|
413
|
+
status: 'joined',
|
|
414
|
+
receivedAt: current?.receivedAt ?? receivedAt,
|
|
415
|
+
groupId: candidate.groupId,
|
|
416
|
+
sponsorAccount: candidate.sponsorAccount,
|
|
417
|
+
keyPackageRef: candidate.keyPackageRef,
|
|
418
|
+
// Rotated on arrival already (a pending invitation): not again.
|
|
419
|
+
rotation: current?.rotation === 'done' || current?.rotation === 'failed' ? current.rotation : 'pending',
|
|
420
|
+
...(current?.failures === undefined ? {} : { failures: current.failures }),
|
|
421
|
+
...(adoption === undefined ? {} : { adoption }),
|
|
422
|
+
});
|
|
423
|
+
return caused;
|
|
424
|
+
});
|
|
425
|
+
if (joined)
|
|
426
|
+
deps.onJoined({ groupId: candidate.groupId, invitationId: id });
|
|
427
|
+
rotateInBackground(id);
|
|
428
|
+
return joined ? 'joined' : 'already-member';
|
|
429
|
+
}
|
|
430
|
+
/** Rotate-after-consume off the inbox queue; while not done it stays `rotation: 'pending'` for the next pass's `resume()`. */
|
|
431
|
+
function rotateInBackground(id, after) {
|
|
432
|
+
void once(`rotation:${id}`, async () => {
|
|
433
|
+
// After S4's own intent resume when one is running: a rotation racing it would only meet `pending-intent`.
|
|
434
|
+
await after;
|
|
435
|
+
try {
|
|
436
|
+
if (!(await rotateAfterConsume(id)))
|
|
437
|
+
deps.onOutstanding();
|
|
438
|
+
}
|
|
439
|
+
catch (error) {
|
|
440
|
+
await failed(id, 'rotation', error);
|
|
441
|
+
}
|
|
442
|
+
});
|
|
443
|
+
}
|
|
444
|
+
/** A decline delivery attempt off the inbox queue; resolves when it settled (never rejects). */
|
|
445
|
+
function deliverDeclineInBackground(id) {
|
|
446
|
+
return once(`decline:${id}`, async () => {
|
|
447
|
+
try {
|
|
448
|
+
if ((await attemptDeclineDelivery(deps, declineStore(id)))?.status === 'pending')
|
|
449
|
+
deps.onOutstanding();
|
|
450
|
+
}
|
|
451
|
+
catch (error) {
|
|
452
|
+
await failed(id, 'decline', error);
|
|
453
|
+
}
|
|
454
|
+
});
|
|
455
|
+
}
|
|
456
|
+
/**
|
|
457
|
+
* Runs `task` unless one for `key` is already in flight (then joins it).
|
|
458
|
+
* These attempts may wait on a remote signer's approval, so they never run
|
|
459
|
+
* on the inbox queue; a failure asks for a retry pass.
|
|
460
|
+
*/
|
|
461
|
+
function once(key, task) {
|
|
462
|
+
const running = maintenance.get(key);
|
|
463
|
+
if (running !== undefined)
|
|
464
|
+
return running;
|
|
465
|
+
const run = task()
|
|
466
|
+
.catch(() => deps.onOutstanding())
|
|
467
|
+
.finally(() => maintenance.delete(key));
|
|
468
|
+
maintenance.set(key, run);
|
|
469
|
+
return run;
|
|
470
|
+
}
|
|
471
|
+
/**
|
|
472
|
+
* A maintenance attempt threw. An explicitly transient cause asks for a
|
|
473
|
+
* retry pass; any other ({@link maintenanceFailureReason}: a refusal, a
|
|
474
|
+
* malformed record, an unclassified error) is counted in the record, and the
|
|
475
|
+
* {@link MAX_MAINTENANCE_FAILURES}th gives the item up — rotation `failed`,
|
|
476
|
+
* decline `failed`, join `joinFailed` — so it stops being outstanding and
|
|
477
|
+
* no signer is prompted for it again; `maintenanceFailed` fires.
|
|
478
|
+
*/
|
|
479
|
+
async function failed(id, kind, error) {
|
|
480
|
+
const reason = maintenanceFailureReason(error);
|
|
481
|
+
if (reason === undefined) {
|
|
482
|
+
deps.onOutstanding();
|
|
483
|
+
return;
|
|
484
|
+
}
|
|
485
|
+
const gaveUp = await deps.transaction(async (tx) => {
|
|
486
|
+
const view = tx.artifact(INVITATIONS);
|
|
487
|
+
const current = await readInvitation(view, id);
|
|
488
|
+
if (current === undefined)
|
|
489
|
+
return false;
|
|
490
|
+
// A join already given up counts and reports nothing more (an uncapped switch keeps retrying).
|
|
491
|
+
if (kind === 'join' && current.joinFailed !== undefined)
|
|
492
|
+
return false;
|
|
493
|
+
const count = (current.failures?.[kind] ?? 0) + 1;
|
|
494
|
+
const failures = { ...current.failures, [kind]: count };
|
|
495
|
+
if (count < MAX_MAINTENANCE_FAILURES) {
|
|
496
|
+
await writeInvitation(view, { ...current, failures });
|
|
497
|
+
return false;
|
|
498
|
+
}
|
|
499
|
+
const next = kind === 'rotation'
|
|
500
|
+
? { ...current, failures, rotation: 'failed' }
|
|
501
|
+
: kind === 'decline'
|
|
502
|
+
? { ...current, failures, ...(current.decline === undefined ? {} : { decline: { ...current.decline, status: 'failed', reason } }) }
|
|
503
|
+
: { ...current, failures, joinFailed: reason };
|
|
504
|
+
await writeInvitation(view, next);
|
|
505
|
+
return true;
|
|
506
|
+
});
|
|
507
|
+
if (gaveUp)
|
|
508
|
+
deps.onMaintenanceFailed({ invitationId: id, kind, reason });
|
|
509
|
+
else
|
|
510
|
+
deps.onOutstanding();
|
|
511
|
+
}
|
|
512
|
+
/**
|
|
513
|
+
* Rotates the KeyPackage a joined or declined invitation consumed, once.
|
|
514
|
+
* `true` when nothing is left to do: rotated, or the ref is no longer its
|
|
515
|
+
* slot's current KeyPackage (already rotated, or forgotten). `false` while
|
|
516
|
+
* it is not: a busy slot, or a rotate whose publish failed — S4 keeps that
|
|
517
|
+
* intent durable and the next attempt (via `rotateKeyPackage`'s own intent
|
|
518
|
+
* resume, and every pass's `resumeKeyPackageIntents`) settles it; only then
|
|
519
|
+
* does the ref stop being current. Throws what a transient or permanent
|
|
520
|
+
* signer/store failure threw.
|
|
521
|
+
*/
|
|
522
|
+
async function rotateAfterConsume(id) {
|
|
523
|
+
const record = await readRecord(id);
|
|
524
|
+
if (record?.rotation !== 'pending')
|
|
525
|
+
return true;
|
|
526
|
+
const ref = record.keyPackageRef;
|
|
527
|
+
// A record without a ref (written by an older build) has nothing to rotate: it is settled `done` below, or
|
|
528
|
+
// every pass's `resume()` would report it outstanding forever.
|
|
529
|
+
if (ref !== undefined) {
|
|
530
|
+
try {
|
|
531
|
+
await deps.rotateKeyPackage(ref);
|
|
532
|
+
}
|
|
533
|
+
catch (error) {
|
|
534
|
+
const reason = isMarmotError(error, 'invalid-options') ? error.details?.reason : undefined;
|
|
535
|
+
if (reason === 'pending-intent' || isMarmotError(error, 'publish-failed'))
|
|
536
|
+
return false;
|
|
537
|
+
if (reason !== 'not-found' && reason !== 'already-superseded')
|
|
538
|
+
throw error;
|
|
539
|
+
}
|
|
540
|
+
}
|
|
541
|
+
await deps.transaction(async (tx) => {
|
|
542
|
+
const view = tx.artifact(INVITATIONS);
|
|
543
|
+
const current = await readInvitation(view, id);
|
|
544
|
+
if (current?.rotation !== 'pending' || current.keyPackageRef !== ref)
|
|
545
|
+
return;
|
|
546
|
+
await writeInvitation(view, { ...current, rotation: 'done' });
|
|
547
|
+
});
|
|
548
|
+
return true;
|
|
549
|
+
}
|
|
550
|
+
function declineStore(id) {
|
|
551
|
+
return {
|
|
552
|
+
read: async () => (await readRecord(id))?.decline,
|
|
553
|
+
update: (change) => deps.transaction(async (tx) => {
|
|
554
|
+
const view = tx.artifact(INVITATIONS);
|
|
555
|
+
const current = await readInvitation(view, id);
|
|
556
|
+
if (current?.decline === undefined)
|
|
557
|
+
return undefined;
|
|
558
|
+
const next = change(current.decline);
|
|
559
|
+
if (next === undefined)
|
|
560
|
+
return current.decline;
|
|
561
|
+
await writeInvitation(view, { ...current, decline: next });
|
|
562
|
+
return next;
|
|
563
|
+
}),
|
|
564
|
+
};
|
|
565
|
+
}
|
|
566
|
+
// -------------------------------------------------------------------------
|
|
567
|
+
// A second Welcome for a group this client holds (epic marmot-welcome-race-joiner, S3)
|
|
568
|
+
// -------------------------------------------------------------------------
|
|
569
|
+
/**
|
|
570
|
+
* Writes the terminal record of a Welcome that is kept out (`reason` names why) or whose switch is confirmed (no
|
|
571
|
+
* reason): `joined`, without the rumor and the pinned key, so a redelivery under any wrap answers `already-member`
|
|
572
|
+
* with no second evaluation. The wrap's seen mark and the manifest update go in the same transaction; the consumed key
|
|
573
|
+
* is rotated like after any join.
|
|
574
|
+
*/
|
|
575
|
+
async function settleTerminal(id, candidate, receivedAt, reason, ctx) {
|
|
576
|
+
await deps.transaction(async (tx) => {
|
|
577
|
+
const view = tx.artifact(INVITATIONS);
|
|
578
|
+
const current = await readInvitation(view, id);
|
|
579
|
+
const manifest = await readManifest(tx, candidate.groupId, candidate.keyPackageRef);
|
|
580
|
+
// A confirmed switch fulfils a waiting manifest of its sponsor; an expiry marks a waiting matching manifest expired;
|
|
581
|
+
// a Welcome kept out for any other reason leaves the manifest as it is.
|
|
582
|
+
if (manifest !== undefined && manifest.sponsorAccount === candidate.sponsorAccount) {
|
|
583
|
+
if (reason === undefined && manifest.status === 'waiting') {
|
|
584
|
+
await writeManifest(tx, { ...manifest, status: 'fulfilled', invitationId: id });
|
|
585
|
+
await deps.onManifestFulfilled?.(tx, manifest);
|
|
586
|
+
}
|
|
587
|
+
else if (reason === 'expired' && manifest.status === 'waiting')
|
|
588
|
+
await writeManifest(tx, { ...manifest, status: 'expired' });
|
|
589
|
+
}
|
|
590
|
+
if (current?.status !== 'joined') {
|
|
591
|
+
// S2: a confirmed switch (no reason) is this Welcome's adoption via its branch switch; an existing stamp is kept.
|
|
592
|
+
const adoption = current?.adoption ?? (reason === undefined ? { via: 'switch', source: 'group-proof', at: deps.clock.now() } : undefined);
|
|
593
|
+
await writeInvitation(view, {
|
|
594
|
+
v: 1,
|
|
595
|
+
id,
|
|
596
|
+
status: 'joined',
|
|
597
|
+
receivedAt: current?.receivedAt ?? receivedAt,
|
|
598
|
+
groupId: candidate.groupId,
|
|
599
|
+
sponsorAccount: candidate.sponsorAccount,
|
|
600
|
+
keyPackageRef: candidate.keyPackageRef,
|
|
601
|
+
...(reason === undefined ? {} : { reason }),
|
|
602
|
+
rotation: current?.rotation === 'done' || current?.rotation === 'failed' ? current.rotation : 'pending',
|
|
603
|
+
...(current?.failures === undefined ? {} : { failures: current.failures }),
|
|
604
|
+
...(adoption === undefined ? {} : { adoption }),
|
|
605
|
+
});
|
|
606
|
+
}
|
|
607
|
+
await ctx?.markSeen(tx);
|
|
608
|
+
});
|
|
609
|
+
rotateInBackground(id);
|
|
610
|
+
}
|
|
611
|
+
/**
|
|
612
|
+
* Writes (or keeps) the durable `competing` record of a Welcome that cannot be decided now, with the wrap's seen
|
|
613
|
+
* mark in the same transaction: the rumor and the pinned consumed key, like a `pending` invitation. `switching`
|
|
614
|
+
* is the switch's intent marker (written before the group transaction); `undefined` clears it. A record that
|
|
615
|
+
* already says exactly this is left untouched (a re-decision every pass must not rewrite the store).
|
|
616
|
+
*/
|
|
617
|
+
/** Groups an open `competing` record waits for (a superset between passes; rebuilt by each pass's scan, seeded on first use). */
|
|
618
|
+
const groupsWithCompeting = new Set();
|
|
619
|
+
let seeded;
|
|
620
|
+
async function holdCompeting(id, candidate, rumor, receivedAt, switching, ctx) {
|
|
621
|
+
const written = await deps.transaction(async (tx) => {
|
|
622
|
+
const view = tx.artifact(INVITATIONS);
|
|
623
|
+
const current = await readInvitation(view, id);
|
|
624
|
+
const settled = current?.status === 'joined' || (current?.status === 'competing' && current.switching?.from === switching?.from && current.switching?.to === switching?.to);
|
|
625
|
+
if (!settled) {
|
|
626
|
+
const { reason: _reason, deferred: _deferred, switching: _switching, failures: oldFailures, joinFailed: oldJoinFailed, ...base } = current ?? { v: 1, id, receivedAt };
|
|
627
|
+
// Clearing an existing marker starts the next attempt clean: its join failures and give-up go with it.
|
|
628
|
+
const clearing = current?.switching !== undefined && switching === undefined;
|
|
629
|
+
const { join: _join, ...otherFailures } = oldFailures ?? {};
|
|
630
|
+
const failures = clearing ? otherFailures : oldFailures;
|
|
631
|
+
await writeInvitation(view, {
|
|
632
|
+
...base,
|
|
633
|
+
...(failures === undefined || Object.keys(failures).length === 0 ? {} : { failures }),
|
|
634
|
+
...(clearing || oldJoinFailed === undefined ? {} : { joinFailed: oldJoinFailed }),
|
|
635
|
+
status: 'competing',
|
|
636
|
+
groupId: candidate.groupId,
|
|
637
|
+
sponsorAccount: candidate.sponsorAccount,
|
|
638
|
+
keyPackageRef: candidate.keyPackageRef,
|
|
639
|
+
rumor,
|
|
640
|
+
pinned: { event: candidate.local.event, privatePackage: candidate.local.privatePackage },
|
|
641
|
+
rotation: current?.rotation === 'done' || current?.rotation === 'failed' ? current.rotation : 'pending',
|
|
642
|
+
...(switching === undefined ? {} : { switching: { from: switching.from, to: switching.to } }),
|
|
643
|
+
});
|
|
644
|
+
}
|
|
645
|
+
await ctx?.markSeen(tx);
|
|
646
|
+
return !settled;
|
|
647
|
+
});
|
|
648
|
+
groupsWithCompeting.add(candidate.groupId);
|
|
649
|
+
if (written)
|
|
650
|
+
rotateInBackground(id);
|
|
651
|
+
}
|
|
652
|
+
/**
|
|
653
|
+
* Runs the rebase through the port. `failed`: it threw (counted against the record like a stuck join's attempts;
|
|
654
|
+
* the group is as the throw found it and the record keeps its marker for the next pass).
|
|
655
|
+
*/
|
|
656
|
+
async function runSwitch(id, candidate, rumor, competing, switching, ports, uncapped) {
|
|
657
|
+
const joinEvidence = joinEvidenceOf(candidate, rumor);
|
|
658
|
+
const request = {
|
|
659
|
+
groupId: candidate.groupId,
|
|
660
|
+
invitationId: id,
|
|
661
|
+
state: candidate.state,
|
|
662
|
+
competing,
|
|
663
|
+
...(joinEvidence === undefined ? {} : { joinEvidence }),
|
|
664
|
+
from: switching.from,
|
|
665
|
+
to: switching.to,
|
|
666
|
+
welcomeCreatedAtMs: rumor.created_at * 1000,
|
|
667
|
+
};
|
|
668
|
+
try {
|
|
669
|
+
return await ports.rebaseToWelcome(request);
|
|
670
|
+
}
|
|
671
|
+
catch (error) {
|
|
672
|
+
// The state was written (the stored tip carries `to`): the finish steps are idempotent and retried every pass,
|
|
673
|
+
// never counted and never given up.
|
|
674
|
+
// A hook that refused inside the switch transaction rolled the state back: not a failure of the switch, retried
|
|
675
|
+
// every pass without counting toward the give-up (the application's hook decides when it stops refusing).
|
|
676
|
+
if (uncapped || isHookRefusal(error) || (await switchStateOf(candidate.groupId, switching, id)) === 'written')
|
|
677
|
+
deps.onOutstanding();
|
|
678
|
+
else
|
|
679
|
+
await failed(id, 'join', error);
|
|
680
|
+
return 'failed';
|
|
681
|
+
}
|
|
682
|
+
}
|
|
683
|
+
/** Where the switch of `id` stands in the STORED group (read failures count as "absent"). */
|
|
684
|
+
async function switchStateOf(groupId, switching, id) {
|
|
685
|
+
if (switching === undefined)
|
|
686
|
+
return 'absent';
|
|
687
|
+
try {
|
|
688
|
+
return await deps.competing.switchState(groupId, switching.to, id);
|
|
689
|
+
}
|
|
690
|
+
catch {
|
|
691
|
+
return 'absent';
|
|
692
|
+
}
|
|
693
|
+
}
|
|
694
|
+
/** The group of a `competing` record is gone: terminal, nothing can join it any more. */
|
|
695
|
+
async function abandonCompeting(id, ctx) {
|
|
696
|
+
await deps.transaction(async (tx) => {
|
|
697
|
+
const view = tx.artifact(INVITATIONS);
|
|
698
|
+
const current = await readInvitation(view, id);
|
|
699
|
+
if (current?.status === 'competing' && current.adoption === undefined) {
|
|
700
|
+
const { rumor: _rumor, pinned: _pinned, switching: _switching, deferred: _deferred, ...rest } = current;
|
|
701
|
+
await writeInvitation(view, { ...rest, status: 'rejected', reason: 'abandoned' });
|
|
702
|
+
}
|
|
703
|
+
await ctx?.markSeen(tx);
|
|
704
|
+
});
|
|
705
|
+
}
|
|
706
|
+
/** The switch happened: report it once, then confirm the record (`joined`, as the abandoned Welcome's record stays). */
|
|
707
|
+
async function finishSwitch(id, candidate, receivedAt, switching, ports, ctx) {
|
|
708
|
+
ports.onBranchSwitched({ invitationId: id, groupId: candidate.groupId, from: switching.from, to: switching.to });
|
|
709
|
+
await settleTerminal(id, candidate, receivedAt, undefined, ctx);
|
|
710
|
+
return { kind: 'switched', from: switching.from, to: switching.to };
|
|
711
|
+
}
|
|
712
|
+
/**
|
|
713
|
+
* Whether the matching manifest's deadline (same group, KeyPackageRef and sponsor, any status) passed for an open
|
|
714
|
+
* `competing` record — but never before the consumed key's retention window (Design Decision 12) passed, counted
|
|
715
|
+
* from the Welcome's receipt: a re-issued Welcome gets its decision chance.
|
|
716
|
+
*/
|
|
717
|
+
async function manifestExpired(candidate, record) {
|
|
718
|
+
const manifest = await deps.transaction((tx) => readManifest(tx, candidate.groupId, candidate.keyPackageRef));
|
|
719
|
+
return manifest !== undefined && manifest.sponsorAccount === candidate.sponsorAccount && deps.clock.now() >= Math.max(manifest.deadline, record.receivedAt + deps.graceWindowMs);
|
|
720
|
+
}
|
|
721
|
+
/**
|
|
722
|
+
* Design Decisions 2, 3, 5, 7, 8, 13, 14: settles a valid Welcome for a group this client holds. In order:
|
|
723
|
+
*
|
|
724
|
+
* 1. a `competing` record with a `switching` marker is completed first (the rebase is idempotent over a crash);
|
|
725
|
+
* a marker whose switch never wrote its state expires past the matching manifest's deadline only while the
|
|
726
|
+
* gate is open;
|
|
727
|
+
* 2. the held branch is read from the stored group; C below its tip epoch, or the very branch it is on, is
|
|
728
|
+
* terminal without the gate;
|
|
729
|
+
* 3. a closed gate holds C as a durable `competing` record — never expired, whatever the clock says (AC-JOIN-7:
|
|
730
|
+
* the library decides nothing for the application while the gate is closed);
|
|
731
|
+
* 4. an open gate decides — `keep` is terminal, `switch` writes the intent and runs the rebase, `undecidable`
|
|
732
|
+
* is held until the matching manifest's deadline passed, then expires (AC-FWJ-16).
|
|
733
|
+
*
|
|
734
|
+
* `legacy`: the decision does not apply and the caller keeps the plain join path (an interrupted join
|
|
735
|
+
* of this very Welcome; a group with nothing stored to compare). Never throws for a rebase failure.
|
|
736
|
+
*/
|
|
737
|
+
async function settleHeld(id, candidate, rumor, receivedAt, record, ctx) {
|
|
738
|
+
const ports = deps.competing;
|
|
739
|
+
const competing = competingBranchOf(candidate, rumor);
|
|
740
|
+
// A switch that failed MAX_MAINTENANCE_FAILURES times: given up only while the group's state was NOT written. A
|
|
741
|
+
// stored group that already carries this switch's transaction is never given up (its finish steps are idempotent).
|
|
742
|
+
let uncapped = false;
|
|
743
|
+
if (record?.status === 'competing' && record.joinFailed !== undefined) {
|
|
744
|
+
if ((await switchStateOf(candidate.groupId, record.switching, id)) === 'written')
|
|
745
|
+
uncapped = true;
|
|
746
|
+
else {
|
|
747
|
+
await settleTerminal(id, candidate, receivedAt, 'switch-failed', ctx);
|
|
748
|
+
return { kind: 'kept' };
|
|
749
|
+
}
|
|
750
|
+
}
|
|
751
|
+
if (record?.status === 'competing' && record.switching !== undefined) {
|
|
752
|
+
const written = await switchStateOf(candidate.groupId, record.switching, id);
|
|
753
|
+
// The stored group carries C but this invitation's switch did not write it: C was reached by ordinary ingest, so
|
|
754
|
+
// the Welcome is the group's own lineage — kept, nothing switched, nothing reported.
|
|
755
|
+
if (written === 'foreign') {
|
|
756
|
+
await settleTerminal(id, candidate, receivedAt, 'same-lineage', ctx);
|
|
757
|
+
return { kind: 'kept' };
|
|
758
|
+
}
|
|
759
|
+
// A switch that never wrote its state is still a held Welcome: the manifest's deadline applies to it, but only
|
|
760
|
+
// under an open gate (AC-JOIN-7: a closed gate holds the Welcome unresolved, whatever the clock says).
|
|
761
|
+
if (written === 'absent' && (await ports.competingGate(candidate.groupId)).open && (await manifestExpired(candidate, record))) {
|
|
762
|
+
await settleTerminal(id, candidate, receivedAt, 'expired', ctx);
|
|
763
|
+
return { kind: 'kept' };
|
|
764
|
+
}
|
|
765
|
+
const outcome = await runSwitch(id, candidate, rumor, competing, record.switching, ports, uncapped);
|
|
766
|
+
if (outcome === 'switched')
|
|
767
|
+
return finishSwitch(id, candidate, receivedAt, record.switching, ports, ctx);
|
|
768
|
+
if (outcome === 'failed')
|
|
769
|
+
return { kind: 'open' };
|
|
770
|
+
// `stale`: the situation changed under the marker; it is cleared and the Welcome is classified afresh.
|
|
771
|
+
await holdCompeting(id, candidate, rumor, receivedAt, undefined, ctx);
|
|
772
|
+
}
|
|
773
|
+
// A `joining` record that did not defer is a join this Welcome itself began. It is "its own adoption" when the held
|
|
774
|
+
// group was joined at exactly this Welcome's state (join epoch and join tag equal C's) or was adopted at this
|
|
775
|
+
// record (`adoptedBy`, which survives the join root leaving the window): the tip may have moved on
|
|
776
|
+
// since, and the plain join path then completes the join and reports `joined` once. Any other held group meets
|
|
777
|
+
// the decision (Design Decision 14).
|
|
778
|
+
if (record?.status === 'joining' && record.deferred === undefined) {
|
|
779
|
+
const own = await ports.heldBranch(candidate.groupId);
|
|
780
|
+
if (own === undefined || (own.joinEpoch === competing.epoch && own.joinTag === competing.tag) || own.adoptedBy === id)
|
|
781
|
+
return { kind: 'legacy' };
|
|
782
|
+
}
|
|
783
|
+
const held = await ports.heldBranch(candidate.groupId);
|
|
784
|
+
if (held === undefined)
|
|
785
|
+
return record?.status === 'competing' ? { kind: 'open' } : { kind: 'legacy' };
|
|
786
|
+
const terminal = terminalClassOf(held, competing);
|
|
787
|
+
if (terminal !== undefined) {
|
|
788
|
+
await settleTerminal(id, candidate, receivedAt, terminal, ctx);
|
|
789
|
+
return { kind: 'kept' };
|
|
790
|
+
}
|
|
791
|
+
if (!(await ports.competingGate(candidate.groupId)).open) {
|
|
792
|
+
await holdCompeting(id, candidate, rumor, receivedAt, undefined, ctx);
|
|
793
|
+
// A condition that cleared before the record was durable had no record to wake: look once more, and ask for the
|
|
794
|
+
// pass that decides when the gate is open now (otherwise the record waits for unrelated traffic).
|
|
795
|
+
if ((await ports.competingGate(candidate.groupId)).open)
|
|
796
|
+
deps.passNow();
|
|
797
|
+
return { kind: 'open' };
|
|
798
|
+
}
|
|
799
|
+
const verdict = judgeCompetingWelcome((await ports.withOwnLeafChain?.(candidate.groupId, held)) ?? held, competing);
|
|
800
|
+
if (verdict.decision === 'keep') {
|
|
801
|
+
await settleTerminal(id, candidate, receivedAt, verdict.reason, ctx);
|
|
802
|
+
return { kind: 'kept' };
|
|
803
|
+
}
|
|
804
|
+
if (verdict.decision === 'undecidable') {
|
|
805
|
+
// Only a Welcome the open gate could not decide is bounded by the matching manifest's deadline (AC-FWJ-16).
|
|
806
|
+
if (record?.status === 'competing' && (await manifestExpired(candidate, record))) {
|
|
807
|
+
await settleTerminal(id, candidate, receivedAt, 'expired', ctx);
|
|
808
|
+
return { kind: 'kept' };
|
|
809
|
+
}
|
|
810
|
+
await holdCompeting(id, candidate, rumor, receivedAt, undefined, ctx);
|
|
811
|
+
return { kind: 'open' };
|
|
812
|
+
}
|
|
813
|
+
const switching = { from: held.tag, to: competing.tag };
|
|
814
|
+
await holdCompeting(id, candidate, rumor, receivedAt, switching, ctx);
|
|
815
|
+
const outcome = await runSwitch(id, candidate, rumor, competing, switching, ports, false);
|
|
816
|
+
if (outcome === 'switched')
|
|
817
|
+
return finishSwitch(id, candidate, receivedAt, switching, ports, ctx);
|
|
818
|
+
// `stale` re-decides next pass; `failed` retries (the marker stays: the rebase is idempotent).
|
|
819
|
+
if (outcome === 'stale')
|
|
820
|
+
await holdCompeting(id, candidate, rumor, receivedAt, undefined, ctx);
|
|
821
|
+
return { kind: 'open' };
|
|
822
|
+
}
|
|
823
|
+
/** Re-decides one open `competing` record on the inbox queue; never throws (a failure is counted against the record). */
|
|
824
|
+
async function redecideCompeting(id) {
|
|
825
|
+
try {
|
|
826
|
+
const record = await readRecord(id);
|
|
827
|
+
if (record?.status !== 'competing' || record.rumor === undefined || record.pinned === undefined)
|
|
828
|
+
return;
|
|
829
|
+
if (record.groupId !== undefined && !(await deps.hasGroup(record.groupId))) {
|
|
830
|
+
await abandonCompeting(id);
|
|
831
|
+
return;
|
|
832
|
+
}
|
|
833
|
+
const evaluation = await evaluate(decodeWelcomeRumor(record.rumor), pinnedOf(record));
|
|
834
|
+
if (evaluation.kind === 'no-key')
|
|
835
|
+
return;
|
|
836
|
+
if (evaluation.kind === 'rejected') {
|
|
837
|
+
// The pinned key no longer joins it (re-evaluation rejected): terminal, like a pending invitation's join.
|
|
838
|
+
await deps.transaction(async (tx) => {
|
|
839
|
+
const view = tx.artifact(INVITATIONS);
|
|
840
|
+
const current = await readInvitation(view, id);
|
|
841
|
+
if (current?.status !== 'competing' || current.adoption !== undefined)
|
|
842
|
+
return;
|
|
843
|
+
const { rumor: _rumor, pinned: _pinned, switching: _switching, ...rest } = current;
|
|
844
|
+
await writeInvitation(view, { ...rest, status: 'rejected', reason: evaluation.reason });
|
|
845
|
+
});
|
|
846
|
+
return;
|
|
847
|
+
}
|
|
848
|
+
await settleHeld(id, evaluation, record.rumor, record.receivedAt, record);
|
|
849
|
+
}
|
|
850
|
+
catch (error) {
|
|
851
|
+
// A marked record whose state is written is retried without counting (see runSwitch).
|
|
852
|
+
const marked = (await readRecord(id).catch(() => undefined))?.switching;
|
|
853
|
+
if (marked !== undefined && (await switchStateOf((await readRecord(id))?.groupId ?? '', marked, id)) === 'written')
|
|
854
|
+
deps.onOutstanding();
|
|
855
|
+
else
|
|
856
|
+
await failed(id, 'join', error);
|
|
857
|
+
}
|
|
858
|
+
}
|
|
859
|
+
async function processWelcome(rumor, _wrap, ctx) {
|
|
860
|
+
let welcome;
|
|
861
|
+
let id;
|
|
862
|
+
try {
|
|
863
|
+
welcome = decodeWelcomeRumor(rumor);
|
|
864
|
+
id = await welcomeIdOf(rumor);
|
|
865
|
+
}
|
|
866
|
+
catch {
|
|
867
|
+
return { kind: 'rejected', reason: 'malformed-welcome' };
|
|
868
|
+
}
|
|
869
|
+
const record = await readRecord(id);
|
|
870
|
+
// A record decides for every copy, whoever wrapped it: the evaluation depends on the Welcome's content
|
|
871
|
+
// (its signer included) and the local key only. `joining` (a join a crash interrupted) proceeds like no
|
|
872
|
+
// record: the join below completes it.
|
|
873
|
+
if (record?.status === 'joined')
|
|
874
|
+
return { kind: 'already-member', invitationId: id, ...(record.groupId === undefined ? {} : { groupId: record.groupId }) };
|
|
875
|
+
if (record?.status === 'declined')
|
|
876
|
+
return { kind: 'rejected', reason: 'declined', invitationId: id };
|
|
877
|
+
if (record?.status === 'rejected')
|
|
878
|
+
return { kind: 'rejected', reason: record.reason ?? 'rejected', invitationId: id };
|
|
879
|
+
if (record?.status === 'pending')
|
|
880
|
+
return { kind: 'pending', invitationId: id, groupId: record.groupId ?? '' };
|
|
881
|
+
// An open `competing` record answers for every copy: no second evaluation, the wrap marked seen. One with a
|
|
882
|
+
// `switching` marker is completed first (below), reporting the switch from this dispatch.
|
|
883
|
+
if (record?.status === 'competing' && record.switching === undefined) {
|
|
884
|
+
await deps.transaction((tx) => ctx.markSeen(tx));
|
|
885
|
+
return { kind: 'already-member', invitationId: id, ...(record.groupId === undefined ? {} : { groupId: record.groupId }) };
|
|
886
|
+
}
|
|
887
|
+
const receivedAt = record?.receivedAt ?? deps.clock.now();
|
|
888
|
+
// A `joining` or `competing` record pinned the consumed key: its slot may have been rotated since.
|
|
889
|
+
const evaluation = await evaluate(welcome, record?.status === 'joining' || record?.status === 'competing' ? pinnedOf(record) : undefined);
|
|
890
|
+
if (evaluation.kind === 'no-key')
|
|
891
|
+
return { kind: 'no-matching-keypackage', invitationId: id };
|
|
892
|
+
if (evaluation.kind === 'rejected') {
|
|
893
|
+
await deps.transaction(async (tx) => {
|
|
894
|
+
const view = tx.artifact(INVITATIONS);
|
|
895
|
+
if ((await readInvitation(view, id)) === undefined) {
|
|
896
|
+
await writeInvitation(view, {
|
|
897
|
+
v: 1,
|
|
898
|
+
id,
|
|
899
|
+
status: 'rejected',
|
|
900
|
+
receivedAt,
|
|
901
|
+
reason: evaluation.reason,
|
|
902
|
+
...(evaluation.groupId === undefined ? {} : { groupId: evaluation.groupId }),
|
|
903
|
+
...(evaluation.keyPackageRef === undefined ? {} : { keyPackageRef: evaluation.keyPackageRef }),
|
|
904
|
+
});
|
|
905
|
+
}
|
|
906
|
+
await ctx.markSeen(tx);
|
|
907
|
+
});
|
|
908
|
+
return { kind: 'rejected', reason: evaluation.reason, invitationId: id };
|
|
909
|
+
}
|
|
910
|
+
// A group this client already holds (a join interrupted before its record, or a second
|
|
911
|
+
// invitation into it) is joined through the same path: adoptJoinedGroup never overwrites it.
|
|
912
|
+
const known = await deps.hasGroup(evaluation.groupId);
|
|
913
|
+
// A second valid Welcome for a held group is classified and decided (`settleHeld`): the same branch, a lower
|
|
914
|
+
// epoch, the joiner's own lineage, a non-member sponsor or a lower-ranked branch is `already-member`; a gated or
|
|
915
|
+
// undecidable one is a durable `competing` record; a higher-ranked branch switches the group. A Welcome alone
|
|
916
|
+
// is evidence for the members' own tie-break, never a statement of the converged branch.
|
|
917
|
+
if (!known && record?.status === 'competing') {
|
|
918
|
+
// The group this marked record was to switch is gone (torn down meanwhile): nothing can join it any more.
|
|
919
|
+
await abandonCompeting(id, ctx);
|
|
920
|
+
return { kind: 'rejected', reason: 'abandoned', invitationId: id };
|
|
921
|
+
}
|
|
922
|
+
if (known) {
|
|
923
|
+
const settled = await settleHeld(id, evaluation, rumor, receivedAt, record, ctx);
|
|
924
|
+
if (settled.kind === 'switched')
|
|
925
|
+
return { kind: 'branch-switched', invitationId: id, groupId: evaluation.groupId, from: settled.from, to: settled.to };
|
|
926
|
+
if (settled.kind !== 'legacy')
|
|
927
|
+
return { kind: 'already-member', invitationId: id, groupId: evaluation.groupId };
|
|
928
|
+
}
|
|
929
|
+
const manifest = await deps.transaction((tx) => readManifest(tx, evaluation.groupId, evaluation.keyPackageRef));
|
|
930
|
+
const match = matchManifest(manifest, evaluation, deps.clock.now());
|
|
931
|
+
// A `joining` record: the join was decided before (an interrupted auto-accept or accept) — complete it,
|
|
932
|
+
// whatever the manifest's deadline says now.
|
|
933
|
+
if (known || match === 'accept' || record?.status === 'joining') {
|
|
934
|
+
const outcome = await join(id, evaluation, rumor, receivedAt, ctx);
|
|
935
|
+
if (outcome === 'abandoned')
|
|
936
|
+
return { kind: 'rejected', reason: 'abandoned', invitationId: id };
|
|
937
|
+
// AC-MX-2: deferred while the group is being restored — not joined yet; completes on its own (a pass).
|
|
938
|
+
if (outcome === 'deferred')
|
|
939
|
+
return { kind: 'pending', invitationId: id, groupId: evaluation.groupId };
|
|
940
|
+
return outcome === 'joined' ? { kind: 'joined', invitationId: id, groupId: evaluation.groupId } : { kind: 'already-member', invitationId: id, groupId: evaluation.groupId };
|
|
941
|
+
}
|
|
942
|
+
// AC-WEL-5: surfaced, not joined. AC-WEL-1: a manifest past its deadline expires here.
|
|
943
|
+
await deps.transaction(async (tx) => {
|
|
944
|
+
const view = tx.artifact(INVITATIONS);
|
|
945
|
+
const current = await readInvitation(view, id);
|
|
946
|
+
if (current === undefined) {
|
|
947
|
+
await writeInvitation(view, {
|
|
948
|
+
v: 1,
|
|
949
|
+
id,
|
|
950
|
+
status: 'pending',
|
|
951
|
+
receivedAt,
|
|
952
|
+
groupId: evaluation.groupId,
|
|
953
|
+
sponsorAccount: evaluation.sponsorAccount,
|
|
954
|
+
keyPackageRef: evaluation.keyPackageRef,
|
|
955
|
+
rumor,
|
|
956
|
+
pinned: { event: evaluation.local.event, privatePackage: evaluation.local.privatePackage },
|
|
957
|
+
rotation: 'pending',
|
|
958
|
+
});
|
|
959
|
+
}
|
|
960
|
+
if (match === 'expired') {
|
|
961
|
+
const current = await readManifest(tx, evaluation.groupId, evaluation.keyPackageRef);
|
|
962
|
+
if (current?.status === 'waiting')
|
|
963
|
+
await writeManifest(tx, { ...current, status: 'expired' });
|
|
964
|
+
}
|
|
965
|
+
await ctx.markSeen(tx);
|
|
966
|
+
});
|
|
967
|
+
// Rotate-after-consume on arrival (off the inbox queue): other inviters stop selecting the consumed KeyPackage.
|
|
968
|
+
rotateInBackground(id);
|
|
969
|
+
return { kind: 'pending', invitationId: id, groupId: evaluation.groupId };
|
|
970
|
+
}
|
|
971
|
+
/** A `joining` record that still carries what its join needs (the Welcome and the pinned key). */
|
|
972
|
+
function isStuckJoin(record) {
|
|
973
|
+
return record.status === 'joining' && record.rumor !== undefined && record.pinned !== undefined && record.joinFailed === undefined;
|
|
974
|
+
}
|
|
975
|
+
/** Re-runs the join of a stuck `joining` record (on the inbox queue); `join()` reports it `joined` once. */
|
|
976
|
+
async function completeStuckJoin(id) {
|
|
977
|
+
const record = await readRecord(id);
|
|
978
|
+
if (record === undefined || !isStuckJoin(record))
|
|
979
|
+
return;
|
|
980
|
+
try {
|
|
981
|
+
await joinPending(record, 'resume');
|
|
982
|
+
}
|
|
983
|
+
catch (error) {
|
|
984
|
+
if (isMarmotError(error, 'invalid-options'))
|
|
985
|
+
return; // rejected on re-evaluation: terminal, recorded by joinPending
|
|
986
|
+
await failed(id, 'join', error);
|
|
987
|
+
}
|
|
988
|
+
}
|
|
989
|
+
/** Joins pending record `record` (accept, or a manifest registered after it arrived). */
|
|
990
|
+
async function joinPending(record, operation) {
|
|
991
|
+
if (record.rumor === undefined)
|
|
992
|
+
throw new MarmotError('store-failed', `invitations.${operation}: pending invitation ${record.id} has no Welcome`, { details: { id: record.id } });
|
|
993
|
+
const evaluation = await evaluate(decodeWelcomeRumor(record.rumor), pinnedOf(record));
|
|
994
|
+
if (evaluation.kind === 'no-key') {
|
|
995
|
+
throw invalid(operation, `the KeyPackage invitation ${record.id} consumed is no longer held`, 'no-matching-keypackage', { id: record.id });
|
|
996
|
+
}
|
|
997
|
+
if (evaluation.kind === 'rejected') {
|
|
998
|
+
await deps.transaction(async (tx) => {
|
|
999
|
+
const view = tx.artifact(INVITATIONS);
|
|
1000
|
+
const current = await readInvitation(view, record.id);
|
|
1001
|
+
if ((current?.status !== 'pending' && current?.status !== 'joining') || current.adoption !== undefined)
|
|
1002
|
+
return;
|
|
1003
|
+
const { rumor: _rumor, pinned: _pinned, deferred: _deferred, ...rest } = current;
|
|
1004
|
+
await writeInvitation(view, { ...rest, status: 'rejected', reason: evaluation.reason });
|
|
1005
|
+
});
|
|
1006
|
+
throw invalid(operation, `invitation ${record.id} was rejected (${evaluation.reason})`, evaluation.reason, { id: record.id });
|
|
1007
|
+
}
|
|
1008
|
+
// Design Decision 14: a held group's Welcome meets the same classification and decision here (accept, a late
|
|
1009
|
+
// manifest, a stuck join), never the plain join, which would answer `already-member` blindly.
|
|
1010
|
+
if (await deps.hasGroup(evaluation.groupId)) {
|
|
1011
|
+
const settled = await settleHeld(record.id, evaluation, record.rumor, record.receivedAt, record);
|
|
1012
|
+
if (settled.kind !== 'legacy')
|
|
1013
|
+
return 'already-member';
|
|
1014
|
+
}
|
|
1015
|
+
const outcome = await join(record.id, evaluation, record.rumor, record.receivedAt);
|
|
1016
|
+
if (outcome === 'abandoned')
|
|
1017
|
+
throw invalid(operation, `invitation ${record.id} names a group this client left or abandoned`, 'abandoned', { id: record.id });
|
|
1018
|
+
// Without a dispatch context a deferral throws (join() above); this narrows the type only.
|
|
1019
|
+
if (outcome === 'deferred')
|
|
1020
|
+
throw new MarmotError('commit-pending', `invitations.${operation}: invitation ${record.id} was deferred`, { details: { id: record.id, reason: 'restore-in-flight', retryable: true } });
|
|
1021
|
+
return outcome;
|
|
1022
|
+
}
|
|
1023
|
+
return {
|
|
1024
|
+
processWelcome,
|
|
1025
|
+
async expectWelcome(raw) {
|
|
1026
|
+
const manifest = validateManifest(raw, deps.clock.now());
|
|
1027
|
+
await deps.serialize(async () => {
|
|
1028
|
+
const recorded = await deps.transaction((tx) => recordManifest(tx, manifest));
|
|
1029
|
+
if (recorded.status !== 'waiting')
|
|
1030
|
+
return;
|
|
1031
|
+
// A matching Welcome that arrived before the manifest is pending: it is accepted now.
|
|
1032
|
+
const pendingMatch = await deps.transaction(async (tx) => {
|
|
1033
|
+
const view = tx.artifact(INVITATIONS);
|
|
1034
|
+
for (const key of await view.keys()) {
|
|
1035
|
+
const record = await readInvitation(view, key);
|
|
1036
|
+
if (record?.status === 'pending' && record.groupId === manifest.groupId && record.keyPackageRef === manifest.keyPackageRef)
|
|
1037
|
+
return record;
|
|
1038
|
+
}
|
|
1039
|
+
return undefined;
|
|
1040
|
+
});
|
|
1041
|
+
if (pendingMatch?.sponsorAccount === undefined)
|
|
1042
|
+
return;
|
|
1043
|
+
// The pending record's sponsor is its GroupInfo signer's account (the join re-derives it).
|
|
1044
|
+
const manifestRecord = recorded;
|
|
1045
|
+
if (matchManifest(manifestRecord, { sponsorAccount: pendingMatch.sponsorAccount }, deps.clock.now()) !== 'accept')
|
|
1046
|
+
return;
|
|
1047
|
+
try {
|
|
1048
|
+
await joinPending(pendingMatch, 'expectWelcome');
|
|
1049
|
+
}
|
|
1050
|
+
catch (error) {
|
|
1051
|
+
// AC-MX-2: the group is being restored — the join stays `joining` and the restore's release completes it.
|
|
1052
|
+
if (!isRestoreInFlight(error))
|
|
1053
|
+
throw error;
|
|
1054
|
+
}
|
|
1055
|
+
});
|
|
1056
|
+
},
|
|
1057
|
+
async pending() {
|
|
1058
|
+
const records = await deps.transaction(async (tx) => {
|
|
1059
|
+
const view = tx.artifact(INVITATIONS);
|
|
1060
|
+
const out = [];
|
|
1061
|
+
for (const key of await view.keys()) {
|
|
1062
|
+
const record = await readInvitation(view, key);
|
|
1063
|
+
if (record?.status === 'pending')
|
|
1064
|
+
out.push(record);
|
|
1065
|
+
}
|
|
1066
|
+
return out;
|
|
1067
|
+
});
|
|
1068
|
+
return Object.freeze(records
|
|
1069
|
+
.sort((a, b) => a.receivedAt - b.receivedAt || (a.id < b.id ? -1 : 1))
|
|
1070
|
+
.map((r) => Object.freeze({
|
|
1071
|
+
id: r.id,
|
|
1072
|
+
groupId: r.groupId ?? '',
|
|
1073
|
+
sponsorAccount: r.sponsorAccount ?? '',
|
|
1074
|
+
sponsors: Object.freeze(r.sponsorAccount === undefined ? [] : [r.sponsorAccount]),
|
|
1075
|
+
keyPackageRef: r.keyPackageRef ?? '',
|
|
1076
|
+
receivedAt: r.receivedAt,
|
|
1077
|
+
})));
|
|
1078
|
+
},
|
|
1079
|
+
accept(id) {
|
|
1080
|
+
if (typeof id !== 'string' || id.length === 0)
|
|
1081
|
+
return Promise.reject(invalid('accept', 'id must be a non-empty string', 'invalid-id'));
|
|
1082
|
+
return deps.serialize(async () => {
|
|
1083
|
+
const record = await readRecord(id);
|
|
1084
|
+
if (record === undefined)
|
|
1085
|
+
throw invalid('accept', `no invitation ${id}`, 'not-found', { id });
|
|
1086
|
+
if (record.status === 'joined' && record.groupId !== undefined)
|
|
1087
|
+
return record.groupId;
|
|
1088
|
+
// `joining`: a join a crash interrupted — accepting completes it.
|
|
1089
|
+
if (record.status !== 'pending' && record.status !== 'joining')
|
|
1090
|
+
throw invalid('accept', `invitation ${id} is ${record.status}`, record.status, { id });
|
|
1091
|
+
await joinPending(record, 'accept');
|
|
1092
|
+
return record.groupId;
|
|
1093
|
+
});
|
|
1094
|
+
},
|
|
1095
|
+
decline(id, options) {
|
|
1096
|
+
if (typeof id !== 'string' || id.length === 0)
|
|
1097
|
+
return Promise.reject(invalid('decline', 'id must be a non-empty string', 'invalid-id'));
|
|
1098
|
+
if (options !== undefined && (typeof options !== 'object' || options === null))
|
|
1099
|
+
return Promise.reject(invalid('decline', 'options must be an object', 'invalid-options'));
|
|
1100
|
+
const declineRumor = options?.declineRumor;
|
|
1101
|
+
if (declineRumor !== undefined && typeof declineRumor !== 'boolean')
|
|
1102
|
+
return Promise.reject(invalid('decline', 'options.declineRumor must be a boolean', 'invalid-options'));
|
|
1103
|
+
const declining = deps.serialize(async () => {
|
|
1104
|
+
const record = await readRecord(id);
|
|
1105
|
+
if (record === undefined)
|
|
1106
|
+
throw invalid('decline', `no invitation ${id}`, 'not-found', { id });
|
|
1107
|
+
if (record.status === 'declined')
|
|
1108
|
+
return false;
|
|
1109
|
+
if (record.status !== 'pending')
|
|
1110
|
+
throw invalid('decline', `invitation ${id} is ${record.status}`, record.status, { id });
|
|
1111
|
+
const author = declineRumor === true ? await deps.signer.getPublicKey() : undefined;
|
|
1112
|
+
const declined = await deps.transaction(async (tx) => {
|
|
1113
|
+
const view = tx.artifact(INVITATIONS);
|
|
1114
|
+
const current = await readInvitation(view, id);
|
|
1115
|
+
if (current?.status !== 'pending' || current.adoption !== undefined)
|
|
1116
|
+
return false;
|
|
1117
|
+
// The pinned key goes with the rumor: nothing can join this invitation any more.
|
|
1118
|
+
const { rumor: _rumor, pinned: _pinned, deferred: _deferred, ...rest } = current;
|
|
1119
|
+
const decline = author === undefined || current.sponsorAccount === undefined
|
|
1120
|
+
? undefined
|
|
1121
|
+
: {
|
|
1122
|
+
rumor: buildDeclineRumor({ author, welcomeId: id, groupId: current.groupId ?? '', nowSeconds: Math.floor(deps.clock.now() / 1000), ...(current.keyPackageRef === undefined ? {} : { keyPackageRef: current.keyPackageRef }) }),
|
|
1123
|
+
recipient: current.sponsorAccount,
|
|
1124
|
+
status: 'pending',
|
|
1125
|
+
attempts: 0,
|
|
1126
|
+
};
|
|
1127
|
+
await writeInvitation(view, { ...rest, status: 'declined', rotation: current.rotation === 'done' || current.rotation === 'failed' ? current.rotation : 'pending', ...(decline === undefined ? {} : { decline }) });
|
|
1128
|
+
return true;
|
|
1129
|
+
});
|
|
1130
|
+
return declined;
|
|
1131
|
+
});
|
|
1132
|
+
// Terminal locally once `declining` resolved. The rumor's first delivery attempt (awaited by the caller)
|
|
1133
|
+
// and the rotation run OFF the inbox queue: a remote signer awaiting approval must not stall the inbox.
|
|
1134
|
+
return declining.then(async (declined) => {
|
|
1135
|
+
if (!declined)
|
|
1136
|
+
return;
|
|
1137
|
+
rotateInBackground(id);
|
|
1138
|
+
if (declineRumor === true)
|
|
1139
|
+
await deliverDeclineInBackground(id);
|
|
1140
|
+
});
|
|
1141
|
+
},
|
|
1142
|
+
async resume() {
|
|
1143
|
+
// S4's grace purge on every pass; a failure is retried by the next one and never blocks the rest.
|
|
1144
|
+
await deps.purgeKeyPackages().catch(() => undefined);
|
|
1145
|
+
// S4's durable KeyPackage intents (a rotation whose publish failed): republished off the queue.
|
|
1146
|
+
const intents = once('keypackage-intents', () => deps.resumeKeyPackageIntents());
|
|
1147
|
+
const open = await deps.transaction(async (tx) => {
|
|
1148
|
+
const view = tx.artifact(INVITATIONS);
|
|
1149
|
+
const out = [];
|
|
1150
|
+
for (const key of await view.keys()) {
|
|
1151
|
+
const record = await readInvitation(view, key);
|
|
1152
|
+
if (record !== undefined && (record.rotation === 'pending' || record.decline?.status === 'pending'))
|
|
1153
|
+
out.push(record);
|
|
1154
|
+
}
|
|
1155
|
+
return out;
|
|
1156
|
+
});
|
|
1157
|
+
// Started, not awaited: resume() runs on the inbox queue (before the pass's backfill).
|
|
1158
|
+
for (const record of open) {
|
|
1159
|
+
if (record.rotation === 'pending')
|
|
1160
|
+
rotateInBackground(record.id, intents);
|
|
1161
|
+
if (record.decline?.status === 'pending')
|
|
1162
|
+
void deliverDeclineInBackground(record.id);
|
|
1163
|
+
}
|
|
1164
|
+
return open.length > 0;
|
|
1165
|
+
},
|
|
1166
|
+
async hasCompeting(groupId) {
|
|
1167
|
+
// A seed that failed is not memoised: the next call scans again.
|
|
1168
|
+
seeded ??= deps
|
|
1169
|
+
.transaction(async (tx) => {
|
|
1170
|
+
const view = tx.artifact(INVITATIONS);
|
|
1171
|
+
for (const key of await view.keys()) {
|
|
1172
|
+
const record = await readInvitation(view, key);
|
|
1173
|
+
if (record?.status === 'competing' && record.groupId !== undefined)
|
|
1174
|
+
groupsWithCompeting.add(record.groupId);
|
|
1175
|
+
}
|
|
1176
|
+
})
|
|
1177
|
+
.catch((error) => {
|
|
1178
|
+
seeded = undefined;
|
|
1179
|
+
throw error;
|
|
1180
|
+
});
|
|
1181
|
+
await seeded;
|
|
1182
|
+
return groupsWithCompeting.has(groupId);
|
|
1183
|
+
},
|
|
1184
|
+
// A join that crashed between its `joining` intent and its `joined` record — an accept whose wrap was
|
|
1185
|
+
// marked seen long before, or an auto-accept whose wrap is gone — is completed here, after the pass's
|
|
1186
|
+
// backfill (a redelivered wrap completes its own first, reporting it). Runs on the inbox queue.
|
|
1187
|
+
async completeStuckJoins() {
|
|
1188
|
+
const stuck = await deps.transaction(async (tx) => {
|
|
1189
|
+
const view = tx.artifact(INVITATIONS);
|
|
1190
|
+
const out = [];
|
|
1191
|
+
for (const key of await view.keys()) {
|
|
1192
|
+
const record = await readInvitation(view, key);
|
|
1193
|
+
if (record !== undefined && isStuckJoin(record))
|
|
1194
|
+
out.push(record.id);
|
|
1195
|
+
}
|
|
1196
|
+
return out;
|
|
1197
|
+
});
|
|
1198
|
+
for (const id of stuck)
|
|
1199
|
+
await completeStuckJoin(id);
|
|
1200
|
+
// Every open `competing` record is re-decided against the pass's current group state (after the backfill and
|
|
1201
|
+
// the stuck joins). A gate that is still closed or a comparison still undecidable keeps the record as it is and
|
|
1202
|
+
// is not "outstanding": the events that clear a gate request their own pass (AC-FWJ-31).
|
|
1203
|
+
const open = await deps.transaction(async (tx) => {
|
|
1204
|
+
const view = tx.artifact(INVITATIONS);
|
|
1205
|
+
const out = [];
|
|
1206
|
+
for (const key of await view.keys()) {
|
|
1207
|
+
const record = await readInvitation(view, key);
|
|
1208
|
+
if (record?.status === 'competing')
|
|
1209
|
+
out.push(record.id);
|
|
1210
|
+
}
|
|
1211
|
+
return out;
|
|
1212
|
+
});
|
|
1213
|
+
for (const id of open)
|
|
1214
|
+
await redecideCompeting(id);
|
|
1215
|
+
// The pass's own scan is authoritative: the in-memory set of groups with an open record is rebuilt from it.
|
|
1216
|
+
const remaining = await deps.transaction(async (tx) => {
|
|
1217
|
+
const view = tx.artifact(INVITATIONS);
|
|
1218
|
+
const groups = [];
|
|
1219
|
+
for (const key of await view.keys()) {
|
|
1220
|
+
const record = await readInvitation(view, key);
|
|
1221
|
+
if (record?.status === 'competing' && record.groupId !== undefined)
|
|
1222
|
+
groups.push(record.groupId);
|
|
1223
|
+
}
|
|
1224
|
+
return groups;
|
|
1225
|
+
});
|
|
1226
|
+
groupsWithCompeting.clear();
|
|
1227
|
+
for (const group of remaining)
|
|
1228
|
+
groupsWithCompeting.add(group);
|
|
1229
|
+
const left = await deps.transaction(async (tx) => {
|
|
1230
|
+
const view = tx.artifact(INVITATIONS);
|
|
1231
|
+
for (const key of await view.keys()) {
|
|
1232
|
+
const record = await readInvitation(view, key);
|
|
1233
|
+
if (record !== undefined && isStuckJoin(record))
|
|
1234
|
+
return true;
|
|
1235
|
+
}
|
|
1236
|
+
return false;
|
|
1237
|
+
});
|
|
1238
|
+
return left;
|
|
1239
|
+
},
|
|
1240
|
+
};
|
|
1241
|
+
}
|