@941design/marmot 0.0.0-stage → 0.2.0-alpha.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +709 -0
- package/LICENSE +21 -0
- package/README.md +33 -2
- package/dist/account/admin.d.ts +72 -0
- package/dist/account/admin.js +209 -0
- package/dist/account/device-deps.d.ts +379 -0
- package/dist/account/device-deps.js +36 -0
- package/dist/account/device-lineage.d.ts +199 -0
- package/dist/account/device-lineage.js +390 -0
- package/dist/account/device-registry.d.ts +93 -0
- package/dist/account/device-registry.js +1290 -0
- package/dist/account/device-rotation.d.ts +61 -0
- package/dist/account/device-rotation.js +827 -0
- package/dist/account/enrolment.d.ts +339 -0
- package/dist/account/enrolment.js +1247 -0
- package/dist/account/identity-proof.d.ts +79 -0
- package/dist/account/identity-proof.js +264 -0
- package/dist/account/index.d.ts +17 -0
- package/dist/account/index.js +16 -0
- package/dist/account/restore-rotation.d.ts +21 -0
- package/dist/account/restore-rotation.js +22 -0
- package/dist/account/same-account-authorization.d.ts +86 -0
- package/dist/account/same-account-authorization.js +180 -0
- package/dist/account/teardown.d.ts +127 -0
- package/dist/account/teardown.js +856 -0
- package/dist/client/before-create-group.d.ts +18 -0
- package/dist/client/before-create-group.js +65 -0
- package/dist/client/before-publish-hooks.d.ts +121 -0
- package/dist/client/before-publish-hooks.js +180 -0
- package/dist/client/client-config.d.ts +42 -0
- package/dist/client/client-config.js +13 -0
- package/dist/client/commit-redrive.d.ts +68 -0
- package/dist/client/commit-redrive.js +221 -0
- package/dist/client/component-update.d.ts +43 -0
- package/dist/client/component-update.js +53 -0
- package/dist/client/confirm-hooks.d.ts +50 -0
- package/dist/client/confirm-hooks.js +59 -0
- package/dist/client/create-client.d.ts +1022 -0
- package/dist/client/create-client.js +1125 -0
- package/dist/client/group-disband.d.ts +28 -0
- package/dist/client/group-disband.js +64 -0
- package/dist/client/group-history.d.ts +435 -0
- package/dist/client/group-history.js +1295 -0
- package/dist/client/group-profile.d.ts +31 -0
- package/dist/client/group-profile.js +62 -0
- package/dist/client/group-records.d.ts +485 -0
- package/dist/client/group-records.js +1034 -0
- package/dist/client/group-removal.d.ts +36 -0
- package/dist/client/group-removal.js +127 -0
- package/dist/client/group-remove-member.d.ts +49 -0
- package/dist/client/group-remove-member.js +163 -0
- package/dist/client/group-runtime.d.ts +388 -0
- package/dist/client/group-runtime.js +2701 -0
- package/dist/client/group-snapshot.d.ts +98 -0
- package/dist/client/group-snapshot.js +453 -0
- package/dist/client/history-pages.d.ts +107 -0
- package/dist/client/history-pages.js +194 -0
- package/dist/client/inbox-send.d.ts +19 -0
- package/dist/client/inbox-send.js +71 -0
- package/dist/client/index.d.ts +21 -0
- package/dist/client/index.js +13 -0
- package/dist/client/ingest.d.ts +82 -0
- package/dist/client/ingest.js +1550 -0
- package/dist/client/lifecycle-events.d.ts +63 -0
- package/dist/client/lifecycle-events.js +35 -0
- package/dist/client/opaque-candidates.d.ts +81 -0
- package/dist/client/opaque-candidates.js +169 -0
- package/dist/client/own-change-outbox.d.ts +66 -0
- package/dist/client/own-change-outbox.js +156 -0
- package/dist/client/pending-leaf.d.ts +116 -0
- package/dist/client/pending-leaf.js +378 -0
- package/dist/client/permissions.d.ts +9 -0
- package/dist/client/permissions.js +12 -0
- package/dist/client/pipeline.d.ts +554 -0
- package/dist/client/pipeline.js +3545 -0
- package/dist/client/reentrancy-guard.d.ts +96 -0
- package/dist/client/reentrancy-guard.js +153 -0
- package/dist/client/rekey.d.ts +58 -0
- package/dist/client/rekey.js +149 -0
- package/dist/client/transport-policy.d.ts +181 -0
- package/dist/client/transport-policy.js +214 -0
- package/dist/history/equivocation.d.ts +55 -0
- package/dist/history/equivocation.js +113 -0
- package/dist/history/fencing.d.ts +25 -0
- package/dist/history/fencing.js +61 -0
- package/dist/history/hex.d.ts +3 -0
- package/dist/history/hex.js +10 -0
- package/dist/history/index.d.ts +73 -0
- package/dist/history/index.js +31 -0
- package/dist/history/notifications.d.ts +270 -0
- package/dist/history/notifications.js +264 -0
- package/dist/history/ordering-key.d.ts +24 -0
- package/dist/history/ordering-key.js +101 -0
- package/dist/history/own-change-fork.d.ts +112 -0
- package/dist/history/own-change-fork.js +196 -0
- package/dist/history/own-change.d.ts +106 -0
- package/dist/history/own-change.js +146 -0
- package/dist/history/policy.d.ts +48 -0
- package/dist/history/policy.js +52 -0
- package/dist/history/retained-window.d.ts +215 -0
- package/dist/history/retained-window.js +565 -0
- package/dist/inbox/demux.d.ts +90 -0
- package/dist/inbox/demux.js +78 -0
- package/dist/inbox/handler-registry.d.ts +42 -0
- package/dist/inbox/handler-registry.js +37 -0
- package/dist/inbox/index.d.ts +11 -0
- package/dist/inbox/index.js +10 -0
- package/dist/inbox/seen-set.d.ts +82 -0
- package/dist/inbox/seen-set.js +202 -0
- package/dist/inbox/subscription.d.ts +236 -0
- package/dist/inbox/subscription.js +644 -0
- package/dist/index.d.ts +10 -0
- package/dist/index.js +9 -0
- package/dist/invitations/competing-welcome.d.ts +223 -0
- package/dist/invitations/competing-welcome.js +128 -0
- package/dist/invitations/decline.d.ts +61 -0
- package/dist/invitations/decline.js +143 -0
- package/dist/invitations/expect-welcome.d.ts +66 -0
- package/dist/invitations/expect-welcome.js +138 -0
- package/dist/invitations/index.d.ts +16 -0
- package/dist/invitations/index.js +16 -0
- package/dist/invitations/invite.d.ts +303 -0
- package/dist/invitations/invite.js +966 -0
- package/dist/invitations/offers.d.ts +79 -0
- package/dist/invitations/offers.js +115 -0
- package/dist/invitations/on-proposal.d.ts +47 -0
- package/dist/invitations/on-proposal.js +40 -0
- package/dist/invitations/pending-proposal-policy.d.ts +52 -0
- package/dist/invitations/pending-proposal-policy.js +139 -0
- package/dist/invitations/proposal-deadline.d.ts +133 -0
- package/dist/invitations/proposal-deadline.js +164 -0
- package/dist/invitations/relay-planes.d.ts +43 -0
- package/dist/invitations/relay-planes.js +70 -0
- package/dist/invitations/welcome-processor.d.ts +253 -0
- package/dist/invitations/welcome-processor.js +1180 -0
- package/dist/key-packages/device-key.d.ts +131 -0
- package/dist/key-packages/device-key.js +272 -0
- package/dist/key-packages/device-rotation-records.d.ts +83 -0
- package/dist/key-packages/device-rotation-records.js +173 -0
- package/dist/key-packages/group-refs.d.ts +40 -0
- package/dist/key-packages/group-refs.js +79 -0
- package/dist/key-packages/index.d.ts +18 -0
- package/dist/key-packages/index.js +18 -0
- package/dist/key-packages/key-package-ref.d.ts +16 -0
- package/dist/key-packages/key-package-ref.js +21 -0
- package/dist/key-packages/observation-stream.d.ts +4 -0
- package/dist/key-packages/observation-stream.js +120 -0
- package/dist/key-packages/offer-rumor.d.ts +26 -0
- package/dist/key-packages/offer-rumor.js +69 -0
- package/dist/key-packages/publisher.d.ts +174 -0
- package/dist/key-packages/publisher.js +1247 -0
- package/dist/key-packages/select-key-package.d.ts +24 -0
- package/dist/key-packages/select-key-package.js +90 -0
- package/dist/key-packages/slot-manager.d.ts +167 -0
- package/dist/key-packages/slot-manager.js +327 -0
- package/dist/key-packages/validate-key-package-event.d.ts +3 -0
- package/dist/key-packages/validate-key-package-event.js +49 -0
- package/dist/media/cache.d.ts +14 -0
- package/dist/media/cache.js +10 -0
- package/dist/media/index.d.ts +52 -0
- package/dist/media/index.js +71 -0
- package/dist/mls.d.ts +15 -0
- package/dist/mls.js +15 -0
- package/dist/shared/account-pubkey.d.ts +4 -0
- package/dist/shared/account-pubkey.js +10 -0
- package/dist/shared/errors.d.ts +21 -0
- package/dist/shared/errors.js +85 -0
- package/dist/shared/hex.d.ts +4 -0
- package/dist/shared/hex.js +13 -0
- package/dist/shared/index.d.ts +14 -0
- package/dist/shared/index.js +14 -0
- package/dist/shared/kinds.d.ts +8 -0
- package/dist/shared/kinds.js +28 -0
- package/dist/shared/publish-classification.d.ts +26 -0
- package/dist/shared/publish-classification.js +31 -0
- package/dist/storage/envelope.d.ts +39 -0
- package/dist/storage/envelope.js +201 -0
- package/dist/storage/index.d.ts +227 -0
- package/dist/storage/index.js +459 -0
- package/dist/storage/indexeddb/idb-types.d.ts +68 -0
- package/dist/storage/indexeddb/idb-types.js +1 -0
- package/dist/storage/indexeddb/index.d.ts +17 -0
- package/dist/storage/indexeddb/index.js +141 -0
- package/dist/storage/lease.d.ts +41 -0
- package/dist/storage/lease.js +117 -0
- package/dist/storage/memory/deterministic-signer.d.ts +27 -0
- package/dist/storage/memory/deterministic-signer.js +65 -0
- package/dist/storage/memory/index.d.ts +32 -0
- package/dist/storage/memory/index.js +87 -0
- package/dist/storage/memory/lock-manager.d.ts +8 -0
- package/dist/storage/memory/lock-manager.js +71 -0
- package/package.json +66 -3
|
@@ -0,0 +1,164 @@
|
|
|
1
|
+
/** Group extension namespace of the deferral records, keyed by proposal ref. */
|
|
2
|
+
export const DEFERRED_PROPOSALS_EXTENSION = 'marmot.deferredProposals';
|
|
3
|
+
/** Default `ClientOptions.proposalDeferralTimeoutMs`: 24 h. */
|
|
4
|
+
export const DEFAULT_PROPOSAL_DEFERRAL_TIMEOUT_MS = 86_400_000;
|
|
5
|
+
/** Whether `record`'s deadline has passed at `nowMs` (`timeoutMs` 0 = never), or it is already marked expired. */
|
|
6
|
+
export function deferralExpired(record, nowMs, timeoutMs) {
|
|
7
|
+
if (record.expiredAt !== undefined)
|
|
8
|
+
return true;
|
|
9
|
+
return timeoutMs > 0 && nowMs >= record.deferredAt + timeoutMs;
|
|
10
|
+
}
|
|
11
|
+
/** Partitions the staged foreign proposals and the stored deferral records at `nowMs`. */
|
|
12
|
+
export function planDeferrals(stagedForeignRefs, records, nowMs, timeoutMs) {
|
|
13
|
+
const staged = new Set(stagedForeignRefs);
|
|
14
|
+
const byRef = new Map(records.map((r) => [r.proposalRef, r]));
|
|
15
|
+
const expired = [];
|
|
16
|
+
const owed = [];
|
|
17
|
+
const stale = [];
|
|
18
|
+
for (const record of byRef.values()) {
|
|
19
|
+
if (staged.has(record.proposalRef))
|
|
20
|
+
continue;
|
|
21
|
+
if (record.expiredAt !== undefined)
|
|
22
|
+
owed.push(record);
|
|
23
|
+
else
|
|
24
|
+
stale.push(record.proposalRef);
|
|
25
|
+
}
|
|
26
|
+
const live = [];
|
|
27
|
+
const recorded = new Map();
|
|
28
|
+
for (const ref of staged) {
|
|
29
|
+
const record = byRef.get(ref);
|
|
30
|
+
if (record !== undefined && deferralExpired(record, nowMs, timeoutMs)) {
|
|
31
|
+
expired.push(record);
|
|
32
|
+
continue;
|
|
33
|
+
}
|
|
34
|
+
live.push(ref);
|
|
35
|
+
if (record !== undefined)
|
|
36
|
+
recorded.set(ref, record);
|
|
37
|
+
}
|
|
38
|
+
return { expired, owed, stale, live, recorded };
|
|
39
|
+
}
|
|
40
|
+
function decodeRecord(key, raw) {
|
|
41
|
+
if (typeof raw !== 'object' || raw === null || Array.isArray(raw) || raw instanceof Uint8Array)
|
|
42
|
+
return undefined;
|
|
43
|
+
const r = raw;
|
|
44
|
+
if (typeof r.deferredAt !== 'number' || !Number.isFinite(r.deferredAt))
|
|
45
|
+
return undefined;
|
|
46
|
+
if (r.expiredAt !== undefined && (typeof r.expiredAt !== 'number' || !Number.isFinite(r.expiredAt)))
|
|
47
|
+
return undefined;
|
|
48
|
+
return { proposalRef: key, deferredAt: r.deferredAt, ...(r.expiredAt === undefined ? {} : { expiredAt: r.expiredAt }) };
|
|
49
|
+
}
|
|
50
|
+
/** Every stored deferral record of the group (a malformed row reads as absent). */
|
|
51
|
+
export async function readDeferrals(view) {
|
|
52
|
+
const out = [];
|
|
53
|
+
for (const key of await view.keys()) {
|
|
54
|
+
const record = decodeRecord(key, await view.get(key));
|
|
55
|
+
if (record !== undefined)
|
|
56
|
+
out.push(record);
|
|
57
|
+
}
|
|
58
|
+
return out;
|
|
59
|
+
}
|
|
60
|
+
export async function writeDeferral(view, record) {
|
|
61
|
+
await view.put(record.proposalRef, { deferredAt: record.deferredAt, ...(record.expiredAt === undefined ? {} : { expiredAt: record.expiredAt }) });
|
|
62
|
+
}
|
|
63
|
+
export async function deleteDeferral(view, proposalRef) {
|
|
64
|
+
await view.delete(proposalRef);
|
|
65
|
+
}
|
|
66
|
+
// ---------------------------------------------------------------------------
|
|
67
|
+
// Exclusions: proposals dropped by application policy (`reject`, or an expired deferral)
|
|
68
|
+
// ---------------------------------------------------------------------------
|
|
69
|
+
/**
|
|
70
|
+
* Group extension namespace of the proposals this client dropped from its
|
|
71
|
+
* staged set by application policy.
|
|
72
|
+
*
|
|
73
|
+
* The drop only keeps the proposal out of OWN commits. ts-mls builds every
|
|
74
|
+
* own commit over all staged proposals (the engine has no per-commit
|
|
75
|
+
* selection), so the drop must remove it from the persisted staged set — and
|
|
76
|
+
* that same set is what a PEER's commit is resolved against: a peer admin
|
|
77
|
+
* that accepted the proposal commits it by reference, and without it that
|
|
78
|
+
* commit could never apply (the engine defers it as `missing_parent` for
|
|
79
|
+
* good). The same holds for a peer commit at an EARLIER epoch that fork
|
|
80
|
+
* recovery replays against a retained state (this client committed past the
|
|
81
|
+
* drop meanwhile).
|
|
82
|
+
*
|
|
83
|
+
* So each drop is recorded — `ref:<proposalRef>` → `{ epoch, tag, reason }`,
|
|
84
|
+
* `tag` being the hex confirmation tag of the state it was dropped from (its
|
|
85
|
+
* BRANCH: same-epoch fork siblings share the epoch, never the tag) — with ONE
|
|
86
|
+
* state snapshot per branch node, `snap:<tag>`: a serialized ClientState of
|
|
87
|
+
* that node staging every proposal dropped at it (merged on each drop). It
|
|
88
|
+
* holds no secret the retained window's state of that node does not. The
|
|
89
|
+
* client re-stages the proposals — into the current state, or into the
|
|
90
|
+
* retained window node, whose tag matches; never into a sibling of the same
|
|
91
|
+
* epoch, whose members never validated them — when a commit waits for a
|
|
92
|
+
* missing proposal, then retries the commit (client/ingest.ts). At the current epoch
|
|
93
|
+
* an exclusion is authoritative: a re-staged excluded proposal (that retry, a
|
|
94
|
+
* rewind) is dropped again before the next own commit, never asked about or
|
|
95
|
+
* deferred anew. Records and snapshots are kept for the rollback horizon
|
|
96
|
+
* (epochs older than `current - horizon` are deleted).
|
|
97
|
+
*/
|
|
98
|
+
export const EXCLUDED_PROPOSALS_EXTENSION = 'marmot.excludedProposals';
|
|
99
|
+
const REF_PREFIX = 'ref:';
|
|
100
|
+
const SNAP_PREFIX = 'snap:';
|
|
101
|
+
/** Every stored exclusion and snapshot of the group (a malformed row reads as absent). */
|
|
102
|
+
export async function readExclusions(view) {
|
|
103
|
+
const records = [];
|
|
104
|
+
const snapshots = new Map();
|
|
105
|
+
for (const key of await view.keys()) {
|
|
106
|
+
const raw = await view.get(key);
|
|
107
|
+
if (key.startsWith(SNAP_PREFIX)) {
|
|
108
|
+
if (raw instanceof Uint8Array)
|
|
109
|
+
snapshots.set(key.slice(SNAP_PREFIX.length), raw);
|
|
110
|
+
continue;
|
|
111
|
+
}
|
|
112
|
+
if (!key.startsWith(REF_PREFIX) || typeof raw !== 'object' || raw === null || Array.isArray(raw) || raw instanceof Uint8Array)
|
|
113
|
+
continue;
|
|
114
|
+
const r = raw;
|
|
115
|
+
if (typeof r.epoch !== 'string' || !/^\d+$/.test(r.epoch) || typeof r.tag !== 'string' || (r.reason !== 'rejected' && r.reason !== 'expired'))
|
|
116
|
+
continue;
|
|
117
|
+
records.push({ proposalRef: key.slice(REF_PREFIX.length), epoch: r.epoch, tag: r.tag, reason: r.reason });
|
|
118
|
+
}
|
|
119
|
+
return { records, snapshots };
|
|
120
|
+
}
|
|
121
|
+
export async function writeExclusion(view, record) {
|
|
122
|
+
await view.put(REF_PREFIX + record.proposalRef, { epoch: record.epoch, tag: record.tag, reason: record.reason });
|
|
123
|
+
}
|
|
124
|
+
/** Stores the (merged) snapshot of the branch node `tag`. */
|
|
125
|
+
export async function writeExclusionSnapshot(view, tag, snapshot) {
|
|
126
|
+
await view.put(SNAP_PREFIX + tag, snapshot);
|
|
127
|
+
}
|
|
128
|
+
/** Deletes the exclusions of every epoch in `epochs`, and every snapshot no kept exclusion names. */
|
|
129
|
+
export async function deleteExclusionEpochs(view, exclusions, epochs) {
|
|
130
|
+
const keptTags = new Set();
|
|
131
|
+
for (const record of exclusions.records) {
|
|
132
|
+
if (epochs.has(record.epoch))
|
|
133
|
+
await view.delete(REF_PREFIX + record.proposalRef);
|
|
134
|
+
else
|
|
135
|
+
keptTags.add(record.tag);
|
|
136
|
+
}
|
|
137
|
+
for (const tag of exclusions.snapshots.keys())
|
|
138
|
+
if (!keptTags.has(tag))
|
|
139
|
+
await view.delete(SNAP_PREFIX + tag);
|
|
140
|
+
}
|
|
141
|
+
/**
|
|
142
|
+
* Splits exclusions for the current state (epoch `currentEpoch`, tag
|
|
143
|
+
* `currentTag`): `current` — those dropped from THIS state (authoritative;
|
|
144
|
+
* a same-epoch sibling's never apply here), `byTag` — every kept exclusion by
|
|
145
|
+
* the branch node it was dropped from, and `outdated` — epochs older than
|
|
146
|
+
* `current - horizon`, or newer than current (a rewind left them behind), to
|
|
147
|
+
* delete. A snapshot no kept exclusion names is deleted with them.
|
|
148
|
+
*/
|
|
149
|
+
export function exclusionsAt(exclusions, currentEpoch, currentTag, horizon) {
|
|
150
|
+
const keep = (epoch) => {
|
|
151
|
+
const e = BigInt(epoch);
|
|
152
|
+
return e <= currentEpoch && e >= currentEpoch - BigInt(horizon);
|
|
153
|
+
};
|
|
154
|
+
const byTag = new Map();
|
|
155
|
+
const outdated = new Set();
|
|
156
|
+
for (const record of exclusions.records) {
|
|
157
|
+
if (!keep(record.epoch))
|
|
158
|
+
outdated.add(record.epoch);
|
|
159
|
+
else
|
|
160
|
+
byTag.set(record.tag, [...(byTag.get(record.tag) ?? []), record]);
|
|
161
|
+
}
|
|
162
|
+
const current = (byTag.get(currentTag) ?? []).filter((r) => r.epoch === String(currentEpoch));
|
|
163
|
+
return { current, byTag, outdated };
|
|
164
|
+
}
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The inbox relay plane (ADR-008, AC-INVITE-5/6, AC-PIPE-8): where a gift-
|
|
3
|
+
* wrapped rumor for one recipient is published. Kind-445 group traffic uses
|
|
4
|
+
* the group's relay plane (`client/transport-policy.ts`); nothing here ever
|
|
5
|
+
* sees a group relay, so the two planes cannot mix.
|
|
6
|
+
*
|
|
7
|
+
* Precedence is `marmot` policy composed over `nostr-events`' fact-returning
|
|
8
|
+
* `lookupInboxRelays` (spec Design Decision 12): the recipient's kind-10050
|
|
9
|
+
* list, else its kind-10002 read set, else `relays.defaults`. A timed-out
|
|
10
|
+
* lookup is an unknown, not an absence: it never falls through to a lower
|
|
11
|
+
* tier (the delivery stays retryable). Single-relay mode (`fixed`) never
|
|
12
|
+
* looks anything up. Relay URLs are raw strings (ADR-014).
|
|
13
|
+
*/
|
|
14
|
+
import { type NostrEvent } from '@941design/nostr-events/event';
|
|
15
|
+
import type { TransportContract } from '@941design/nostr-events/transport/contract';
|
|
16
|
+
export interface InboxRelayDeps {
|
|
17
|
+
readonly relays: {
|
|
18
|
+
readonly defaults: readonly string[];
|
|
19
|
+
readonly mode: 'discover' | 'fixed';
|
|
20
|
+
};
|
|
21
|
+
/** Deadline of each relay-list lookup. */
|
|
22
|
+
readonly lookupTimeoutMs: number;
|
|
23
|
+
/** The client's transport, already routed through the re-entrancy guard. */
|
|
24
|
+
readonly transport: TransportContract;
|
|
25
|
+
/** The consumer verifier, already routed through the re-entrancy guard. */
|
|
26
|
+
readonly verifier: ((event: NostrEvent) => Promise<boolean>) | undefined;
|
|
27
|
+
}
|
|
28
|
+
export type InboxRelayResolution = {
|
|
29
|
+
readonly kind: 'relays';
|
|
30
|
+
readonly relays: readonly string[];
|
|
31
|
+
readonly source: 'nip17' | 'nip65Read' | 'defaults';
|
|
32
|
+
}
|
|
33
|
+
/** The lookup timed out on a tier that would otherwise decide: retry later, publish nothing now. */
|
|
34
|
+
| {
|
|
35
|
+
readonly kind: 'transient';
|
|
36
|
+
readonly reason: 'nip17-timed-out' | 'nip65-timed-out';
|
|
37
|
+
}
|
|
38
|
+
/** Every tier is empty: code `no-inbox-relays`. */
|
|
39
|
+
| {
|
|
40
|
+
readonly kind: 'none';
|
|
41
|
+
};
|
|
42
|
+
/** The relays a gift-wrapped rumor for `recipient` goes to. */
|
|
43
|
+
export declare function resolveInboxRelays(deps: InboxRelayDeps, recipient: string): Promise<InboxRelayResolution>;
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The inbox relay plane (ADR-008, AC-INVITE-5/6, AC-PIPE-8): where a gift-
|
|
3
|
+
* wrapped rumor for one recipient is published. Kind-445 group traffic uses
|
|
4
|
+
* the group's relay plane (`client/transport-policy.ts`); nothing here ever
|
|
5
|
+
* sees a group relay, so the two planes cannot mix.
|
|
6
|
+
*
|
|
7
|
+
* Precedence is `marmot` policy composed over `nostr-events`' fact-returning
|
|
8
|
+
* `lookupInboxRelays` (spec Design Decision 12): the recipient's kind-10050
|
|
9
|
+
* list, else its kind-10002 read set, else `relays.defaults`. A timed-out
|
|
10
|
+
* lookup is an unknown, not an absence: it never falls through to a lower
|
|
11
|
+
* tier (the delivery stays retryable). Single-relay mode (`fixed`) never
|
|
12
|
+
* looks anything up. Relay URLs are raw strings (ADR-014).
|
|
13
|
+
*/
|
|
14
|
+
import { verifyEvent } from '@941design/nostr-events/event';
|
|
15
|
+
import { lookupInboxRelays } from '@941design/nostr-events/transport/inbox-relays';
|
|
16
|
+
function distinct(relays) {
|
|
17
|
+
return [...new Set(relays)];
|
|
18
|
+
}
|
|
19
|
+
/**
|
|
20
|
+
* The transport `lookupInboxRelays` runs over: its answers pass
|
|
21
|
+
* verify-before-trust (signature, then the consumer verifier) before the
|
|
22
|
+
* helper picks the newest list, so a relay cannot hand us a forged list.
|
|
23
|
+
*/
|
|
24
|
+
function verifiedLookupTransport(deps) {
|
|
25
|
+
return {
|
|
26
|
+
publish: (relays, event, opts) => deps.transport.publish(relays, event, opts),
|
|
27
|
+
subscription: (relays, filters) => deps.transport.subscription(relays, filters),
|
|
28
|
+
async requestWithDeadline(relays, filters, opts) {
|
|
29
|
+
const result = await deps.transport.requestWithDeadline(relays, filters, opts);
|
|
30
|
+
const events = [];
|
|
31
|
+
for (const event of result.events) {
|
|
32
|
+
if (!verifyEvent(event))
|
|
33
|
+
continue;
|
|
34
|
+
if (deps.verifier !== undefined) {
|
|
35
|
+
let trusted;
|
|
36
|
+
try {
|
|
37
|
+
trusted = await deps.verifier(event);
|
|
38
|
+
}
|
|
39
|
+
catch {
|
|
40
|
+
trusted = false;
|
|
41
|
+
}
|
|
42
|
+
if (!trusted)
|
|
43
|
+
continue;
|
|
44
|
+
}
|
|
45
|
+
events.push(event);
|
|
46
|
+
}
|
|
47
|
+
return { ...result, events };
|
|
48
|
+
},
|
|
49
|
+
};
|
|
50
|
+
}
|
|
51
|
+
/** The relays a gift-wrapped rumor for `recipient` goes to. */
|
|
52
|
+
export async function resolveInboxRelays(deps, recipient) {
|
|
53
|
+
const defaults = distinct(deps.relays.defaults);
|
|
54
|
+
if (deps.relays.mode === 'fixed') {
|
|
55
|
+
return defaults.length > 0 ? { kind: 'relays', relays: defaults, source: 'defaults' } : { kind: 'none' };
|
|
56
|
+
}
|
|
57
|
+
// No bootstrap relay to ask: nothing can be looked up (and defaults are empty too).
|
|
58
|
+
if (defaults.length === 0)
|
|
59
|
+
return { kind: 'none' };
|
|
60
|
+
const found = await lookupInboxRelays(verifiedLookupTransport(deps), recipient, { sourceRelays: defaults, timeoutMs: deps.lookupTimeoutMs });
|
|
61
|
+
if (found.nip17TimedOut)
|
|
62
|
+
return { kind: 'transient', reason: 'nip17-timed-out' };
|
|
63
|
+
if (found.nip17.length > 0)
|
|
64
|
+
return { kind: 'relays', relays: distinct(found.nip17), source: 'nip17' };
|
|
65
|
+
if (found.nip65TimedOut)
|
|
66
|
+
return { kind: 'transient', reason: 'nip65-timed-out' };
|
|
67
|
+
if (found.nip65Read.length > 0)
|
|
68
|
+
return { kind: 'relays', relays: distinct(found.nip65Read), source: 'nip65Read' };
|
|
69
|
+
return { kind: 'relays', relays: defaults, source: 'defaults' };
|
|
70
|
+
}
|
|
@@ -0,0 +1,253 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Invitee side of the invitation flow (S6): the Welcome processor behind the
|
|
3
|
+
* inbox's rumor dispatch point, `expectWelcome`, `pending()`, `accept(id)`,
|
|
4
|
+
* `decline(id)` and the maintenance every inbox pass runs.
|
|
5
|
+
*
|
|
6
|
+
* A Welcome is identified by its CONTENT — {@link welcomeIdOf}, the SHA-256
|
|
7
|
+
* of the serialized MLS Welcome — not by the gift wrap that carried it:
|
|
8
|
+
* `retryWelcome` re-wraps the same rumor, so one Welcome may arrive under
|
|
9
|
+
* several wrap ids (AC-WEL-2). Every Welcome that got as far as a decision
|
|
10
|
+
* has a record in the account `pendingInvitations` artifact, kept after it
|
|
11
|
+
* is terminal (without the rumor), so a redelivery under any wrap — also one
|
|
12
|
+
* the bounded seen-set has evicted (AC-INBOX-4) — resolves from the record,
|
|
13
|
+
* with no second join.
|
|
14
|
+
*
|
|
15
|
+
* Processing one Welcome rumor (always on the inbox's serial queue):
|
|
16
|
+
*
|
|
17
|
+
* 1. decode the MLS Welcome from the rumor content directly — never the
|
|
18
|
+
* engine's `getWelcome`, which requires the optional `e` tag;
|
|
19
|
+
* 2. an existing record decides: joined → `already-member`, pending →
|
|
20
|
+
* `pending`, declined/rejected → `rejected`;
|
|
21
|
+
* 3. find a local KeyPackage for one of the KeyPackageRefs in the
|
|
22
|
+
* Welcome's secrets (`findPrivateKeyPackage` + the event carrying the
|
|
23
|
+
* public half) — none → `no-matching-keypackage`, nothing touched
|
|
24
|
+
* (AC-WEL-4);
|
|
25
|
+
* 4. join IN MEMORY, then the ADR-012 proof check on every leaf of the
|
|
26
|
+
* joined tree (`checkJoinedState`) → `rejected('proof-missing')`,
|
|
27
|
+
* nothing persisted but the rejection record (AC-WEL-7). The join
|
|
28
|
+
* recovers the leaf that signed the Welcome's GroupInfo (the engine's
|
|
29
|
+
* `joinGroupFromWelcomeWithSigner`): the sponsor is that leaf's account
|
|
30
|
+
* (its credential identity — every leaf of one account shares it);
|
|
31
|
+
* 5. a group this client already holds → the Welcome is a possible
|
|
32
|
+
* competing branch of a same-epoch race and is classified and decided
|
|
33
|
+
* (`settleHeld`, epic `marmot-welcome-race-joiner`): kept out
|
|
34
|
+
* (`already-member`, with the reason on a terminal `joined` record), held as
|
|
35
|
+
* a durable `competing` record while the group's gate is closed or the
|
|
36
|
+
* comparison is undecidable, or switched to (`branch-switched`);
|
|
37
|
+
* 6. a waiting manifest matching group id, KeyPackageRef and sponsor before
|
|
38
|
+
* its deadline → join; else the Welcome is surfaced as `pending` (a
|
|
39
|
+
* manifest past its deadline is marked `expired` in the same transaction)
|
|
40
|
+
* (AC-WEL-1, AC-WEL-5).
|
|
41
|
+
*
|
|
42
|
+
* Who gift-wrapped a copy (the NIP-59 seal author) decides nothing: the seal
|
|
43
|
+
* authenticates the sender of the envelope, the GroupInfo signature the
|
|
44
|
+
* member that built the commit, and it is the same for every copy. Any
|
|
45
|
+
* holder of the Welcome — every new member of the commit — may forward it;
|
|
46
|
+
* a copy from anyone joins as its signer's Welcome, never as the forwarder's.
|
|
47
|
+
*
|
|
48
|
+
* A join persists the group (`adoptJoinedGroup`: group state, then the
|
|
49
|
+
* account group index with the join time — group → account), then the
|
|
50
|
+
* `joined` record (+ the wrap's seen mark, + the manifest's `fulfilled`) in
|
|
51
|
+
* one account transaction, then rotates the consumed KeyPackage
|
|
52
|
+
* (rotate-after-consume, S4 `rotateKeyPackage`). A crash anywhere in between
|
|
53
|
+
* is repaired by redelivery: the persisted group turns the next join into
|
|
54
|
+
* `already-member`, and a `rotation: 'pending'` record is rotated by the
|
|
55
|
+
* next pass's {@link WelcomeService.resume}.
|
|
56
|
+
*/
|
|
57
|
+
import type { NostrEvent, Rumor } from '@941design/nostr-events/event';
|
|
58
|
+
import type { Signer } from '@941design/nostr-events/signer';
|
|
59
|
+
import { type ClientConfig, type ClientState, type Welcome } from '@941design/marmot-engine/mls';
|
|
60
|
+
import { type DispatchContext, type RumorDisposition } from '../inbox/index.js';
|
|
61
|
+
import type { AccountStoreTx, KeyValueView, Storable } from '../storage/index.js';
|
|
62
|
+
import { type CompetingWelcomePorts } from './competing-welcome.js';
|
|
63
|
+
import { type DeclineDeliveryDeps, type DeclineState } from './decline.js';
|
|
64
|
+
import { type ManifestRecord } from './expect-welcome.js';
|
|
65
|
+
/** The MLS Welcome of a Welcome rumor, decoded from its base64 content (no tag is required). Throws on anything else. */
|
|
66
|
+
export declare function decodeWelcomeRumor(rumor: Rumor): Welcome;
|
|
67
|
+
/** The Welcome identity: hex SHA-256 of the serialized MLS Welcome (the rumor content, base64-decoded). */
|
|
68
|
+
export declare function welcomeIdOf(rumor: Rumor): Promise<string>;
|
|
69
|
+
/**
|
|
70
|
+
* `joining`: a join's intent, written before the group is persisted (a crash leaves it for the redelivery to finish).
|
|
71
|
+
* `competing`: a second valid Welcome for a group this client holds that could not be decided yet (the group's
|
|
72
|
+
* gate was closed, or the comparison was undecidable): it holds the rumor and the pinned consumed key like `pending`,
|
|
73
|
+
* is re-decided on every inbox pass, and is not a `pending` invitation (`pending()` omits it, `accept` rejects it).
|
|
74
|
+
*/
|
|
75
|
+
export type InvitationStatus = 'pending' | 'joining' | 'joined' | 'declined' | 'rejected' | 'competing';
|
|
76
|
+
export interface InvitationRecord {
|
|
77
|
+
readonly v: 1;
|
|
78
|
+
readonly id: string;
|
|
79
|
+
readonly status: InvitationStatus;
|
|
80
|
+
/** Client clock (ms) of the first decision. */
|
|
81
|
+
readonly receivedAt: number;
|
|
82
|
+
readonly groupId?: string;
|
|
83
|
+
/** The sponsor: the account of the leaf that signed the Welcome's GroupInfo (absent when the join failed). */
|
|
84
|
+
readonly sponsorAccount?: string;
|
|
85
|
+
/** The consumed local KeyPackage (hex KeyPackageRef from the Welcome's secrets). */
|
|
86
|
+
readonly keyPackageRef?: string;
|
|
87
|
+
/** The Welcome rumor (the first copy), while `pending` or `joining` only. */
|
|
88
|
+
readonly rumor?: Rumor;
|
|
89
|
+
/**
|
|
90
|
+
* While `pending` only: the consumed KeyPackage's two halves, copied from
|
|
91
|
+
* the slot on arrival — the slot is rotated right away (other inviters stop
|
|
92
|
+
* selecting it) and its grace window may expire before `accept`.
|
|
93
|
+
*/
|
|
94
|
+
readonly pinned?: {
|
|
95
|
+
readonly event: NostrEvent;
|
|
96
|
+
readonly privatePackage: Storable;
|
|
97
|
+
};
|
|
98
|
+
/** Rotate-after-consume progress (joined / declined); `failed` after {@link MAX_MAINTENANCE_FAILURES} permanent failures. */
|
|
99
|
+
readonly rotation?: 'pending' | 'done' | 'failed';
|
|
100
|
+
/** Permanent (non-transient) failures of this invitation's maintenance so far, per item. */
|
|
101
|
+
readonly failures?: {
|
|
102
|
+
readonly rotation?: number;
|
|
103
|
+
readonly decline?: number;
|
|
104
|
+
readonly join?: number;
|
|
105
|
+
};
|
|
106
|
+
/** Set when completing an interrupted join failed permanently {@link MAX_MAINTENANCE_FAILURES} times (the reason). */
|
|
107
|
+
readonly joinFailed?: string;
|
|
108
|
+
/**
|
|
109
|
+
* While `joining` only: the join was deferred before anything was adopted — its group was being restored
|
|
110
|
+
* (AC-MX-2). Completing it then reports `joined` only when it adopts the group itself (a restore that
|
|
111
|
+
* succeeded holds it: `already-member`), unlike a join a crash interrupted after adopting.
|
|
112
|
+
*/
|
|
113
|
+
readonly deferred?: 'restore-in-flight';
|
|
114
|
+
/**
|
|
115
|
+
* Why it was `rejected`; on a `joined` record, why a second Welcome for a held group was kept out (a
|
|
116
|
+
* {@link KeepReason}, or `expired`) — the Welcome is terminal and answers `already-member`.
|
|
117
|
+
*/
|
|
118
|
+
readonly reason?: string;
|
|
119
|
+
readonly decline?: DeclineState;
|
|
120
|
+
/**
|
|
121
|
+
* While `competing` only: the switch to this Welcome's branch is under way (confirmation tags). Written BEFORE the
|
|
122
|
+
* group transaction; a record that carries it is completed (rebuild, sync, report, confirm) before anything is
|
|
123
|
+
* classified, so a crash after the state write is never classified against a tip that already equals `to`.
|
|
124
|
+
*/
|
|
125
|
+
readonly switching?: {
|
|
126
|
+
readonly from: string;
|
|
127
|
+
readonly to: string;
|
|
128
|
+
};
|
|
129
|
+
}
|
|
130
|
+
export declare function decodeInvitation(id: string, raw: unknown): InvitationRecord;
|
|
131
|
+
/** A pending (unexpected) invitation as `client.invitations.pending()` lists it. */
|
|
132
|
+
/**
|
|
133
|
+
* S9 teardown: the consumed KeyPackageRefs of the invitations that named
|
|
134
|
+
* `groupId` (their retained keys are purged with the group); deletes the
|
|
135
|
+
* still-`pending` ones among them and turns an interrupted `joining` one
|
|
136
|
+
* terminal (`rejected`, reason `abandoned`, pinned key and Welcome dropped). Decided invitations (joined, declined,
|
|
137
|
+
* rejected) are kept: they are what makes a redelivered Welcome of the
|
|
138
|
+
* abandoned group a no-op rather than a re-join (at-most-once join).
|
|
139
|
+
*/
|
|
140
|
+
export declare function purgeGroupInvitations(tx: {
|
|
141
|
+
artifact(name: 'pendingInvitations'): KeyValueView;
|
|
142
|
+
}, groupId: string): Promise<string[]>;
|
|
143
|
+
export interface PendingInvitation {
|
|
144
|
+
/** The Welcome identity: `accept(id)` / `decline(id)`. */
|
|
145
|
+
readonly id: string;
|
|
146
|
+
readonly groupId: string;
|
|
147
|
+
/**
|
|
148
|
+
* The account of the member that signed the Welcome's GroupInfo — the
|
|
149
|
+
* author of the commit that added this client (AC-WEL-1). A decline rumor
|
|
150
|
+
* goes to it.
|
|
151
|
+
*/
|
|
152
|
+
readonly sponsorAccount: string;
|
|
153
|
+
/** `[sponsorAccount]`: a Welcome has exactly one signer (kept for API compatibility). */
|
|
154
|
+
readonly sponsors: readonly string[];
|
|
155
|
+
/** The local KeyPackage the Welcome consumed. */
|
|
156
|
+
readonly keyPackageRef: string;
|
|
157
|
+
/** Client clock (ms) at which it was surfaced. */
|
|
158
|
+
readonly receivedAt: number;
|
|
159
|
+
}
|
|
160
|
+
export interface WelcomeServiceDeps extends DeclineDeliveryDeps {
|
|
161
|
+
readonly clock: {
|
|
162
|
+
now(): number;
|
|
163
|
+
};
|
|
164
|
+
/** The account-key signer (decline wraps), every member already routed through the re-entrancy guard. */
|
|
165
|
+
readonly signer: Signer;
|
|
166
|
+
/** `AccountStore.transaction`, already routed through the re-entrancy guard. */
|
|
167
|
+
transaction<T>(fn: (tx: AccountStoreTx) => Promise<T> | T): Promise<T>;
|
|
168
|
+
/** Runs `task` on the inbox's serial queue. */
|
|
169
|
+
serialize<T>(task: () => Promise<T>): Promise<T>;
|
|
170
|
+
/** The ts-mls `ClientConfig` every group engine of this client runs with (S8: same-account equality). */
|
|
171
|
+
readonly clientConfig: ClientConfig;
|
|
172
|
+
/** ADR-012 check of a joined state: the failures (empty = every leaf carries a valid proof). */
|
|
173
|
+
checkJoinedState(state: ClientState): readonly unknown[];
|
|
174
|
+
/**
|
|
175
|
+
* Persists a joined, checked state: group state (never overwriting an
|
|
176
|
+
* existing one), then the account group index entry stamped `joinedAtMs`
|
|
177
|
+
* (the Welcome's arrival: ingest's pre-join floor). `already-member` when
|
|
178
|
+
* the group was already stored.
|
|
179
|
+
*/
|
|
180
|
+
/** Rejects `not-a-member` for a group this client tore down whose state the Welcome would bring back (S9). */
|
|
181
|
+
adoptJoinedGroup(groupId: string, state: ClientState, joinedAtMs: number, joinEvidence?: JoinEvidenceOfWelcome, invitationId?: string, welcomeCreatedAtMs?: number): Promise<'joined' | 'already-member'>;
|
|
182
|
+
/** Whether this client already holds the group. */
|
|
183
|
+
hasGroup(groupId: string): Promise<boolean>;
|
|
184
|
+
/**
|
|
185
|
+
* The ports of the competing-Welcome decision (epic `marmot-welcome-race-joiner`): the group's gate, its held
|
|
186
|
+
* branch, the rebase and the report. Implemented by the group runtime.
|
|
187
|
+
*/
|
|
188
|
+
readonly competing: CompetingWelcomePorts;
|
|
189
|
+
/** How long a consumed KeyPackage's key stays retrievable (the client's `graceWindowMs`): a `competing` record never expires by manifest deadline before it. */
|
|
190
|
+
readonly graceWindowMs: number;
|
|
191
|
+
/** S4 `rotateKeyPackage` over the client's KeyPackage deps. */
|
|
192
|
+
rotateKeyPackage(ref: string): Promise<unknown>;
|
|
193
|
+
/** S4's grace purge (`purgeAllExpiredSuperseded`). */
|
|
194
|
+
purgeKeyPackages(): Promise<void>;
|
|
195
|
+
/**
|
|
196
|
+
* Inside the account transaction that marks a waiting manifest `fulfilled` (a join, or a confirmed switch to the
|
|
197
|
+
* Welcome): the device was admitted under that manifest. Optional; the client wires the device registry's
|
|
198
|
+
* supersede of the own device's settled forget (the manifest's `recordedAt` is when it asked to be admitted).
|
|
199
|
+
*/
|
|
200
|
+
onManifestFulfilled?(tx: AccountStoreTx, manifest: ManifestRecord): Promise<void>;
|
|
201
|
+
/** Called after a join committed. */
|
|
202
|
+
onJoined(joined: {
|
|
203
|
+
readonly groupId: string;
|
|
204
|
+
readonly invitationId: string;
|
|
205
|
+
}): void;
|
|
206
|
+
/** Durable maintenance (a rotation, a decline delivery) is still outstanding after an attempt: schedule a retry pass. */
|
|
207
|
+
onOutstanding(): void;
|
|
208
|
+
/** Run an inbox pass now (the blocker of a held Welcome cleared between a gate read and the record becoming durable). */
|
|
209
|
+
passNow(): void;
|
|
210
|
+
/** A maintenance item failed permanently {@link MAX_MAINTENANCE_FAILURES} times and is given up (after the write committed). */
|
|
211
|
+
onMaintenanceFailed(failure: {
|
|
212
|
+
readonly invitationId: string;
|
|
213
|
+
readonly kind: MaintenanceKind;
|
|
214
|
+
readonly reason: string;
|
|
215
|
+
}): void;
|
|
216
|
+
/** S4's durable KeyPackage intent resume (`resumePendingIntents`): republishes a rotation whose publish failed. */
|
|
217
|
+
resumeKeyPackageIntents(): Promise<void>;
|
|
218
|
+
}
|
|
219
|
+
export type MaintenanceKind = 'rotation' | 'decline' | 'join';
|
|
220
|
+
/** Permanent failures after which one maintenance item of an invitation is given up (`maintenanceFailed`). */
|
|
221
|
+
export declare const MAX_MAINTENANCE_FAILURES = 10;
|
|
222
|
+
export interface WelcomeService {
|
|
223
|
+
/** The inbox dispatch for a Welcome rumor (runs on the inbox queue). */
|
|
224
|
+
processWelcome(rumor: Rumor, wrap: NostrEvent, ctx: DispatchContext): Promise<RumorDisposition>;
|
|
225
|
+
expectWelcome(manifest: unknown): Promise<void>;
|
|
226
|
+
pending(): Promise<readonly PendingInvitation[]>;
|
|
227
|
+
/** Joins a pending invitation; resolves with its group id. */
|
|
228
|
+
accept(id: string): Promise<string>;
|
|
229
|
+
decline(id: string, options?: unknown): Promise<void>;
|
|
230
|
+
/**
|
|
231
|
+
* Maintenance at the start of every inbox pass: S4 grace purge, then every
|
|
232
|
+
* pending rotation and decline delivery started OFF the inbox queue (one
|
|
233
|
+
* attempt in flight per invitation). Resolves `true` while any is outstanding.
|
|
234
|
+
*/
|
|
235
|
+
resume(): Promise<boolean>;
|
|
236
|
+
/** Completes every join a crash left `joining` (runs on the inbox queue, after the pass's backfill). Resolves `true` while one is outstanding. */
|
|
237
|
+
completeStuckJoins(): Promise<boolean>;
|
|
238
|
+
/**
|
|
239
|
+
* Whether an open `competing` record waits for `groupId`'s gate or comparison: what the events that clear a gate
|
|
240
|
+
* condition (the group's first sync ended, an own commit confirmed, a restore released) ask before they request an
|
|
241
|
+
* inbox pass (AC-FWJ-31). Not on the inbox queue: a plain read.
|
|
242
|
+
*/
|
|
243
|
+
hasCompeting(groupId: string): Promise<boolean>;
|
|
244
|
+
}
|
|
245
|
+
/**
|
|
246
|
+
* What the device records about the commit that produced the state it joined (the window root's join evidence): the
|
|
247
|
+
* Welcome's `commit` tag and the account of the GroupInfo signer. Structurally the history module's `JoinEvidence`.
|
|
248
|
+
*/
|
|
249
|
+
export interface JoinEvidenceOfWelcome {
|
|
250
|
+
readonly digest: string;
|
|
251
|
+
readonly committer: string;
|
|
252
|
+
}
|
|
253
|
+
export declare function createWelcomeService(deps: WelcomeServiceDeps): WelcomeService;
|