@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,223 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The competing-Welcome decision (epic `marmot-welcome-race-joiner`, S3; spec Design Decisions 2, 3, 5, 13).
|
|
3
|
+
*
|
|
4
|
+
* A second valid Welcome C for a group this device holds (the held branch H, the stored tip) is a genuine fork when
|
|
5
|
+
* it names a different confirmation tag at the join epoch or a state above H's tip. The device then runs the members'
|
|
6
|
+
* own rule on (epoch, committer, digest): `compareBranchScores` over a score built from each side, never a
|
|
7
|
+
* re-implementation of it. Everything here is pure; `welcome-processor.ts` reads the held side through the
|
|
8
|
+
* {@link CompetingWelcomePorts} the group runtime implements (S4) and acts on the verdict.
|
|
9
|
+
*
|
|
10
|
+
* Missing evidence is never encoded as an empty byte array (empty bytes sort lowest and would win): a comparison that
|
|
11
|
+
* reaches a field one side cannot supply is `undecidable`, and the device stays put.
|
|
12
|
+
*/
|
|
13
|
+
import { type BranchScore } from '@941design/marmot-engine/core';
|
|
14
|
+
import { type ClientState } from '@941design/marmot-engine/mls';
|
|
15
|
+
/** The fields of a held branch's score that can be missing (same names as `heldBranchScore`'s `missing`). */
|
|
16
|
+
export type MissingEvidence = 'digest' | 'committer';
|
|
17
|
+
/**
|
|
18
|
+
* The held side's score as the window derives it (`heldBranchScore`): `complete: true` carries every key;
|
|
19
|
+
* `complete: false` names what is missing. A caller that knows a present field of an incomplete score may pass it
|
|
20
|
+
* (`committer` / `digest`); the window-derived union carries none, which only makes the decision more conservative.
|
|
21
|
+
*/
|
|
22
|
+
export type HeldScore = {
|
|
23
|
+
readonly complete: true;
|
|
24
|
+
readonly score: BranchScore;
|
|
25
|
+
} | {
|
|
26
|
+
readonly complete: false;
|
|
27
|
+
readonly missing: readonly MissingEvidence[];
|
|
28
|
+
readonly committer?: Uint8Array;
|
|
29
|
+
readonly digest?: Uint8Array;
|
|
30
|
+
};
|
|
31
|
+
/** What the group runtime reports about the branch this device holds (`CompetingWelcomePorts.heldBranch`). */
|
|
32
|
+
export interface HeldBranch {
|
|
33
|
+
/** The stored tip's epoch (also both depths of its score). */
|
|
34
|
+
readonly epoch: number;
|
|
35
|
+
/** `tagOf(tip)`: hex confirmation tag of the stored tip. */
|
|
36
|
+
readonly tag: string;
|
|
37
|
+
/**
|
|
38
|
+
* The epoch at which this device joined the held group, while the join root is still in the retained window;
|
|
39
|
+
* `undefined` when it is not (or never was) — the eligibility horizon is then exceeded (Design Decision 13).
|
|
40
|
+
*/
|
|
41
|
+
readonly joinEpoch: number | undefined;
|
|
42
|
+
/**
|
|
43
|
+
* The confirmation tag of that join root, `undefined` when unknown. With `joinEpoch` it tells a group this very
|
|
44
|
+
* Welcome adopted (both equal C's epoch and tag) from one it merely belongs to, whatever the tip is by now.
|
|
45
|
+
*/
|
|
46
|
+
readonly joinTag: string | undefined;
|
|
47
|
+
/**
|
|
48
|
+
* The id of the invitation whose Welcome adopted the held group (persisted with the group's index entry at
|
|
49
|
+
* adoption), or `undefined` when unknown (a group created here, adopted by an older build, restored). An interrupted
|
|
50
|
+
* join of the very Welcome that adopted the group matches its record's id whatever the tip is by now (the join root
|
|
51
|
+
* may long have left the window).
|
|
52
|
+
*/
|
|
53
|
+
readonly adoptedBy?: string | undefined;
|
|
54
|
+
/**
|
|
55
|
+
* The confirmation tags of the window's canonical path (root to tip). A switch whose target is on it has been
|
|
56
|
+
* written, whatever the tip has become since (see {@link carriesBranch}).
|
|
57
|
+
*/
|
|
58
|
+
readonly pathTags?: ReadonlySet<string> | undefined;
|
|
59
|
+
/** The rewind horizon the members select with and the window retains (`REWIND_HORIZON`). */
|
|
60
|
+
readonly horizon: number;
|
|
61
|
+
/** The held branch's score (window-derived). */
|
|
62
|
+
readonly score: HeldScore;
|
|
63
|
+
/** Hex signature public key of the leaf this device operates at the tip, `undefined` when unknown. */
|
|
64
|
+
readonly ownLeafSignatureKey: string | undefined;
|
|
65
|
+
/**
|
|
66
|
+
* Hex signature public keys of THIS device's directed ancestry (epic marmot-device-key-rotation): the key it holds at the
|
|
67
|
+
* tip, `deviceRegistry/self`, and every key from which either is reached along the recorded rotation links. A Welcome whose
|
|
68
|
+
* tree holds any of them at another index carries a retired key of the same device (a late Welcome on a KeyPackage minted
|
|
69
|
+
* before a rotation): the held lineage, like the current key. Never the whole lineage component: a live sibling
|
|
70
|
+
* installation sharing an origin key is another device. Absent when the held key is `self` and has no ancestors, and when
|
|
71
|
+
* the lineage could not be read (the check then compares only {@link ownLeafSignatureKey}).
|
|
72
|
+
*/
|
|
73
|
+
readonly ownLeafChain?: ReadonlySet<string> | undefined;
|
|
74
|
+
/** Hex account pubkeys that hold a leaf in the tip state. */
|
|
75
|
+
readonly memberAccounts: ReadonlySet<string>;
|
|
76
|
+
}
|
|
77
|
+
/**
|
|
78
|
+
* The ONE predicate "the held group already carries the branch `tag`": the tip is it, it is on the stored window's
|
|
79
|
+
* canonical path (the device ingested a commit of that branch since), or it is the join root. Used by the rebase (a
|
|
80
|
+
* crash after the transaction), the processor's written-state check and its give-up rule — tip equality alone breaks
|
|
81
|
+
* once the branch moves on.
|
|
82
|
+
*/
|
|
83
|
+
export declare function carriesBranch(held: HeldBranch | undefined, tag: string): boolean;
|
|
84
|
+
/** What a competing Welcome says about its branch. */
|
|
85
|
+
export interface CompetingBranch {
|
|
86
|
+
/** The GroupInfo epoch of the state the Welcome joins. */
|
|
87
|
+
readonly epoch: number;
|
|
88
|
+
/** `tagOf(C)`: hex confirmation tag of the state the Welcome joins. */
|
|
89
|
+
readonly tag: string;
|
|
90
|
+
/** The `commit` tag of the Welcome rumor (hex digest), `undefined` when the sponsor did not tag it. */
|
|
91
|
+
readonly digest: string | undefined;
|
|
92
|
+
/** The account of the leaf that signed the Welcome's GroupInfo (the committer on C). */
|
|
93
|
+
readonly sponsorAccount: string;
|
|
94
|
+
/** Hex signature public keys of every leaf in C's ratchet tree except the joiner's own leaf in C. */
|
|
95
|
+
readonly otherLeafSignatureKeys: ReadonlySet<string>;
|
|
96
|
+
}
|
|
97
|
+
/** Why a competing Welcome is kept out (the branch H stays). */
|
|
98
|
+
export type KeepReason = 'same-branch' | 'lower-epoch' | 'same-lineage' | 'sponsor-not-a-member' | 'beyond-horizon' | 'lower-ranked';
|
|
99
|
+
export type CompetingVerdict = {
|
|
100
|
+
readonly decision: 'keep';
|
|
101
|
+
readonly reason: KeepReason;
|
|
102
|
+
} | {
|
|
103
|
+
readonly decision: 'switch';
|
|
104
|
+
} | {
|
|
105
|
+
readonly decision: 'undecidable';
|
|
106
|
+
readonly missing: readonly MissingEvidence[];
|
|
107
|
+
};
|
|
108
|
+
export type CompetingDecision = CompetingVerdict['decision'];
|
|
109
|
+
/**
|
|
110
|
+
* The hex signature public keys of the leaves of `state`'s ratchet tree OTHER than the state's own leaf (a blank
|
|
111
|
+
* node holds none). The joiner's own leaf in C was added from the very KeyPackage that added it to H, so its key
|
|
112
|
+
* equals the joiner's leaf key at H in every genuine fork; only a leaf at ANOTHER index can show that C descends
|
|
113
|
+
* from the joiner's own lineage (an admin re-inviting a current member's fresh KeyPackage).
|
|
114
|
+
*/
|
|
115
|
+
export declare function otherLeafSignatureKeysOf(state: ClientState): ReadonlySet<string>;
|
|
116
|
+
/** The state's epoch as a JS number (epochs are far below 2^53 in any real group). */
|
|
117
|
+
export declare function epochOf(state: ClientState): number;
|
|
118
|
+
/**
|
|
119
|
+
* The classification that needs neither the gate nor any ancestry: C below H's tip epoch cannot win (lower depth,
|
|
120
|
+
* whatever its history), and C at H's epoch with H's tag is the very branch H is on. `undefined`: C must be decided.
|
|
121
|
+
*/
|
|
122
|
+
export declare function terminalClassOf(held: HeldBranch, competing: CompetingBranch): 'lower-epoch' | 'same-branch' | undefined;
|
|
123
|
+
/**
|
|
124
|
+
* The verdict for a competing Welcome C against the held branch H, with the reason a kept Welcome is kept:
|
|
125
|
+
*
|
|
126
|
+
* 1. C below H's tip epoch cannot win (lower depth, whatever its ancestry): `lower-epoch`; C at H's epoch with
|
|
127
|
+
* H's tag is the same branch: `same-branch`.
|
|
128
|
+
* 2. a C whose tree holds the joiner's CURRENT leaf signature key, or a retired key of the same device
|
|
129
|
+
* ({@link HeldBranch.ownLeafChain}: its directed ancestry, never a sibling installation's key), is H's own lineage
|
|
130
|
+
* (an admin re-inviting a current member's fresh KeyPackage, a sibling top-up, a late Welcome on a KeyPackage minted
|
|
131
|
+
* before a rotation): `same-lineage` — never a switch.
|
|
132
|
+
* 3. only an account that holds a leaf in H's tip may sponsor a switch: `sponsor-not-a-member`.
|
|
133
|
+
* 4. the eligibility horizon, the members' own bound (`isBranchEligible`: tip epoch minus the FORK epoch, the parent of
|
|
134
|
+
* the join commit, i.e. `joinEpoch - 1`): `tipEpoch(H) - (joinEpoch - 1) <= horizon`, else `beyond-horizon`.
|
|
135
|
+
* 5. rank by (depth, committer, digest) with `compareBranchScores`; an undecidable comparison keeps H and is
|
|
136
|
+
* reported as such (the caller holds the Welcome as a durable `competing` record).
|
|
137
|
+
*/
|
|
138
|
+
export declare function judgeCompetingWelcome(held: HeldBranch, competing: CompetingBranch): CompetingVerdict;
|
|
139
|
+
/** `judgeCompetingWelcome` without the reason: `switch`, `keep` or `undecidable` (spec: `decideCompetingWelcome`). */
|
|
140
|
+
export declare function decideCompetingWelcome(held: HeldBranch, competing: CompetingBranch): CompetingDecision;
|
|
141
|
+
/** See {@link CompetingWelcomePorts.switchState}. */
|
|
142
|
+
export type SwitchState = 'written' | 'foreign' | 'absent';
|
|
143
|
+
/** `competingGate(groupId)`: open only when nothing is changing the group's state under the decision. */
|
|
144
|
+
export type CompetingGate = {
|
|
145
|
+
readonly open: true;
|
|
146
|
+
} | {
|
|
147
|
+
readonly open: false;
|
|
148
|
+
readonly reason: 'not-loaded' | 'fenced' | 'restoring' | 'purging' | 'abandoned' | 'syncing' | 'own-commit-pending';
|
|
149
|
+
};
|
|
150
|
+
/** What `rebaseToWelcome` is asked to switch the group to. */
|
|
151
|
+
export interface RebaseRequest {
|
|
152
|
+
readonly groupId: string;
|
|
153
|
+
/** The competing Welcome's invitation id (its record is the switch's intent). */
|
|
154
|
+
readonly invitationId: string;
|
|
155
|
+
/** C's joined, proof-checked state. */
|
|
156
|
+
readonly state: ClientState;
|
|
157
|
+
/** C as the decision saw it: re-run {@link judgeCompetingWelcome} against the CURRENT tip before writing anything. */
|
|
158
|
+
readonly competing: CompetingBranch;
|
|
159
|
+
/** The join evidence C's window root carries: its commit tag and the GroupInfo signer's account (absent when untagged). */
|
|
160
|
+
readonly joinEvidence?: {
|
|
161
|
+
readonly digest: string;
|
|
162
|
+
readonly committer: string;
|
|
163
|
+
};
|
|
164
|
+
/** `tag(H)` when the decision was made (`switching.from`). */
|
|
165
|
+
readonly from: string;
|
|
166
|
+
/** `tag(C)` (`switching.to`). */
|
|
167
|
+
readonly to: string;
|
|
168
|
+
/** The competing Welcome rumor's `created_at` in milliseconds: the group's pre-join ingest floor is lowered to it. */
|
|
169
|
+
readonly welcomeCreatedAtMs: number;
|
|
170
|
+
}
|
|
171
|
+
/**
|
|
172
|
+
* The ports `WelcomeServiceDeps.competing` takes. The Welcome service calls them; the group runtime
|
|
173
|
+
* (`client/group-runtime.ts`) implements them.
|
|
174
|
+
*/
|
|
175
|
+
export interface CompetingWelcomePorts {
|
|
176
|
+
/**
|
|
177
|
+
* Whether the group's live state allows a decision now; re-run inside `rebaseToWelcome`. It may answer
|
|
178
|
+
* asynchronously: whether an own commit is pending is a store read (S4 amendment of the 2026-10-24 S3 contract).
|
|
179
|
+
*/
|
|
180
|
+
competingGate(groupId: string): CompetingGate | Promise<CompetingGate>;
|
|
181
|
+
/**
|
|
182
|
+
* The held branch, read from the STORED group (no gate needed: a lower-epoch Welcome is terminal without one).
|
|
183
|
+
* `undefined` when nothing is stored, and while a restore of the group is in flight or marked unfinished or the
|
|
184
|
+
* group was torn down (nothing comparable): the caller then falls back to the plain join path, which defers or
|
|
185
|
+
* abandons. Every other stored group, loaded or not, MUST yield a view
|
|
186
|
+
* (load on demand): an `undefined` for any other group would silently restore the pre-epic `already-member`.
|
|
187
|
+
*/
|
|
188
|
+
heldBranch(groupId: string): Promise<HeldBranch | undefined>;
|
|
189
|
+
/**
|
|
190
|
+
* `held` with {@link HeldBranch.ownLeafChain} attached (two account-store reads, never throwing: a failed read answers `held`
|
|
191
|
+
* unchanged). Asked for only where the chain decides — right before {@link judgeCompetingWelcome} — so the paths that
|
|
192
|
+
* never reach the check (a terminal class, a closed gate, a joining record's own-adoption test) pay no account read.
|
|
193
|
+
* Absent: the decision compares the held key alone.
|
|
194
|
+
*/
|
|
195
|
+
withOwnLeafChain?(groupId: string, held: HeldBranch): Promise<HeldBranch>;
|
|
196
|
+
/**
|
|
197
|
+
* Switches the group to `request.state`: re-runs the gate, the classification and the decision against the
|
|
198
|
+
* current tip INSIDE the group's queued operation and answers `stale` (nothing changed) when they no longer
|
|
199
|
+
* hold; otherwise one group transaction (state, window, cleared per-state extensions, withdrawals, rewind
|
|
200
|
+
* marker, `onConfirm` hooks), then the engine rebuild and a history sync, and `switched`.
|
|
201
|
+
*
|
|
202
|
+
* MUST be idempotent over a crash: when the stored tip already carries `request.to` (the transaction committed
|
|
203
|
+
* before the crash) it skips the validation and the transaction and finishes the rebuild and the sync, answering
|
|
204
|
+
* `switched`. A throw leaves the group exactly as the throw found it; the caller retries on the next pass.
|
|
205
|
+
*/
|
|
206
|
+
rebaseToWelcome(request: RebaseRequest): Promise<'switched' | 'stale'>;
|
|
207
|
+
/**
|
|
208
|
+
* Whether the switch of invitation `invitationId` to the branch `to` was written, answered from the STORED group
|
|
209
|
+
* (never the live runtime, which may still hold the abandoned state after a failed rebuild):
|
|
210
|
+
* - `written`: the switch transaction of that invitation committed (its durable proof exists), whatever the tip is by now;
|
|
211
|
+
* - `foreign`: the stored group carries `to` (tip, canonical path or join root) but that invitation's switch did not
|
|
212
|
+
* write it — the branch was reached by ordinary ingest, so the Welcome is the group's own lineage;
|
|
213
|
+
* - `absent`: neither.
|
|
214
|
+
*/
|
|
215
|
+
switchState(groupId: string, to: string, invitationId: string): Promise<SwitchState>;
|
|
216
|
+
/** The switch is confirmed (the client's `groupBranchSwitched` event); called once per switch. */
|
|
217
|
+
onBranchSwitched(switched: {
|
|
218
|
+
readonly invitationId: string;
|
|
219
|
+
readonly groupId: string;
|
|
220
|
+
readonly from: string;
|
|
221
|
+
readonly to: string;
|
|
222
|
+
}): void;
|
|
223
|
+
}
|
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The competing-Welcome decision (epic `marmot-welcome-race-joiner`, S3; spec Design Decisions 2, 3, 5, 13).
|
|
3
|
+
*
|
|
4
|
+
* A second valid Welcome C for a group this device holds (the held branch H, the stored tip) is a genuine fork when
|
|
5
|
+
* it names a different confirmation tag at the join epoch or a state above H's tip. The device then runs the members'
|
|
6
|
+
* own rule on (epoch, committer, digest): `compareBranchScores` over a score built from each side, never a
|
|
7
|
+
* re-implementation of it. Everything here is pure; `welcome-processor.ts` reads the held side through the
|
|
8
|
+
* {@link CompetingWelcomePorts} the group runtime implements (S4) and acts on the verdict.
|
|
9
|
+
*
|
|
10
|
+
* Missing evidence is never encoded as an empty byte array (empty bytes sort lowest and would win): a comparison that
|
|
11
|
+
* reaches a field one side cannot supply is `undecidable`, and the device stays put.
|
|
12
|
+
*/
|
|
13
|
+
import { compareBranchScores } from '@941design/marmot-engine/core';
|
|
14
|
+
import { nodeTypes } from '@941design/marmot-engine/mls';
|
|
15
|
+
import { bytesOfHex64, hexOfBytes } from '../shared/index.js';
|
|
16
|
+
/**
|
|
17
|
+
* The ONE predicate "the held group already carries the branch `tag`": the tip is it, it is on the stored window's
|
|
18
|
+
* canonical path (the device ingested a commit of that branch since), or it is the join root. Used by the rebase (a
|
|
19
|
+
* crash after the transaction), the processor's written-state check and its give-up rule — tip equality alone breaks
|
|
20
|
+
* once the branch moves on.
|
|
21
|
+
*/
|
|
22
|
+
export function carriesBranch(held, tag) {
|
|
23
|
+
return held !== undefined && (held.tag === tag || held.joinTag === tag || held.pathTags?.has(tag) === true);
|
|
24
|
+
}
|
|
25
|
+
/**
|
|
26
|
+
* The hex signature public keys of the leaves of `state`'s ratchet tree OTHER than the state's own leaf (a blank
|
|
27
|
+
* node holds none). The joiner's own leaf in C was added from the very KeyPackage that added it to H, so its key
|
|
28
|
+
* equals the joiner's leaf key at H in every genuine fork; only a leaf at ANOTHER index can show that C descends
|
|
29
|
+
* from the joiner's own lineage (an admin re-inviting a current member's fresh KeyPackage).
|
|
30
|
+
*/
|
|
31
|
+
export function otherLeafSignatureKeysOf(state) {
|
|
32
|
+
const keys = new Set();
|
|
33
|
+
const ownNode = Number(state.privatePath.leafIndex) * 2;
|
|
34
|
+
state.ratchetTree.forEach((node, index) => {
|
|
35
|
+
if (index !== ownNode && node !== undefined && node !== null && node.nodeType === nodeTypes.leaf)
|
|
36
|
+
keys.add(hexOfBytes(node.leaf.signaturePublicKey));
|
|
37
|
+
});
|
|
38
|
+
return keys;
|
|
39
|
+
}
|
|
40
|
+
/** The state's epoch as a JS number (epochs are far below 2^53 in any real group). */
|
|
41
|
+
export function epochOf(state) {
|
|
42
|
+
return Number(state.groupContext.epoch);
|
|
43
|
+
}
|
|
44
|
+
function scoreOf(depth, committer, digest) {
|
|
45
|
+
return { validCommitDepth: depth, effectiveCommitDepth: depth, witnessQuorumMet: false, appWitnessScore: 0, tipDigest: digest, tipCommitter: committer };
|
|
46
|
+
}
|
|
47
|
+
/** Never read for its value: both sides of a comparison that cannot reach the field it stands in for carry the same one. */
|
|
48
|
+
const UNREACHED = new Uint8Array(32);
|
|
49
|
+
function sign(n) {
|
|
50
|
+
return n > 0 ? 1 : n < 0 ? -1 : 0;
|
|
51
|
+
}
|
|
52
|
+
/** Compares C to H at equal depth with `compareBranchScores`, staging the fields so a missing one is never compared. */
|
|
53
|
+
function rankAtEqualDepth(held, competing) {
|
|
54
|
+
const depth = held.epoch;
|
|
55
|
+
const cCommitter = bytesOfHex64(competing.sponsorAccount);
|
|
56
|
+
const cDigest = bytesOfHex64(competing.digest);
|
|
57
|
+
const h = held.score;
|
|
58
|
+
const hCommitter = h.complete ? h.score.tipCommitter : h.committer;
|
|
59
|
+
const hDigest = h.complete ? h.score.tipDigest : h.digest;
|
|
60
|
+
if (hCommitter === undefined || cCommitter === undefined)
|
|
61
|
+
return { decision: 'undecidable', missing: ['committer', ...(hDigest === undefined || cDigest === undefined ? ['digest'] : [])] };
|
|
62
|
+
// Committers first: when they differ the digest step is not reached, so the shared filler cannot matter.
|
|
63
|
+
const byCommitter = compareBranchScores(scoreOf(depth, cCommitter, UNREACHED), scoreOf(depth, hCommitter, UNREACHED));
|
|
64
|
+
if (byCommitter !== 0)
|
|
65
|
+
return rankVerdict(byCommitter);
|
|
66
|
+
if (hDigest === undefined || cDigest === undefined)
|
|
67
|
+
return { decision: 'undecidable', missing: ['digest'] };
|
|
68
|
+
return rankVerdict(compareBranchScores(scoreOf(depth, cCommitter, cDigest), scoreOf(depth, hCommitter, hDigest)));
|
|
69
|
+
}
|
|
70
|
+
function rankVerdict(comparison) {
|
|
71
|
+
return sign(comparison) > 0 ? { decision: 'switch' } : { decision: 'keep', reason: 'lower-ranked' };
|
|
72
|
+
}
|
|
73
|
+
/**
|
|
74
|
+
* The classification that needs neither the gate nor any ancestry: C below H's tip epoch cannot win (lower depth,
|
|
75
|
+
* whatever its history), and C at H's epoch with H's tag is the very branch H is on. `undefined`: C must be decided.
|
|
76
|
+
*/
|
|
77
|
+
export function terminalClassOf(held, competing) {
|
|
78
|
+
if (competing.epoch < held.epoch)
|
|
79
|
+
return 'lower-epoch';
|
|
80
|
+
if (competing.epoch === held.epoch && competing.tag === held.tag)
|
|
81
|
+
return 'same-branch';
|
|
82
|
+
return undefined;
|
|
83
|
+
}
|
|
84
|
+
/** Whether C's tree holds, at an index other than the joiner's own, the key H's leaf operates or a key of this device's chain. */
|
|
85
|
+
function holdsOwnLineage(held, competing) {
|
|
86
|
+
const others = competing.otherLeafSignatureKeys;
|
|
87
|
+
if (held.ownLeafSignatureKey !== undefined && others.has(held.ownLeafSignatureKey))
|
|
88
|
+
return true;
|
|
89
|
+
if (held.ownLeafChain !== undefined)
|
|
90
|
+
for (const key of held.ownLeafChain)
|
|
91
|
+
if (others.has(key))
|
|
92
|
+
return true;
|
|
93
|
+
return false;
|
|
94
|
+
}
|
|
95
|
+
/**
|
|
96
|
+
* The verdict for a competing Welcome C against the held branch H, with the reason a kept Welcome is kept:
|
|
97
|
+
*
|
|
98
|
+
* 1. C below H's tip epoch cannot win (lower depth, whatever its ancestry): `lower-epoch`; C at H's epoch with
|
|
99
|
+
* H's tag is the same branch: `same-branch`.
|
|
100
|
+
* 2. a C whose tree holds the joiner's CURRENT leaf signature key, or a retired key of the same device
|
|
101
|
+
* ({@link HeldBranch.ownLeafChain}: its directed ancestry, never a sibling installation's key), is H's own lineage
|
|
102
|
+
* (an admin re-inviting a current member's fresh KeyPackage, a sibling top-up, a late Welcome on a KeyPackage minted
|
|
103
|
+
* before a rotation): `same-lineage` — never a switch.
|
|
104
|
+
* 3. only an account that holds a leaf in H's tip may sponsor a switch: `sponsor-not-a-member`.
|
|
105
|
+
* 4. the eligibility horizon, the members' own bound (`isBranchEligible`: tip epoch minus the FORK epoch, the parent of
|
|
106
|
+
* the join commit, i.e. `joinEpoch - 1`): `tipEpoch(H) - (joinEpoch - 1) <= horizon`, else `beyond-horizon`.
|
|
107
|
+
* 5. rank by (depth, committer, digest) with `compareBranchScores`; an undecidable comparison keeps H and is
|
|
108
|
+
* reported as such (the caller holds the Welcome as a durable `competing` record).
|
|
109
|
+
*/
|
|
110
|
+
export function judgeCompetingWelcome(held, competing) {
|
|
111
|
+
const terminal = terminalClassOf(held, competing);
|
|
112
|
+
if (terminal !== undefined)
|
|
113
|
+
return { decision: 'keep', reason: terminal };
|
|
114
|
+
if (holdsOwnLineage(held, competing))
|
|
115
|
+
return { decision: 'keep', reason: 'same-lineage' };
|
|
116
|
+
if (!held.memberAccounts.has(competing.sponsorAccount))
|
|
117
|
+
return { decision: 'keep', reason: 'sponsor-not-a-member' };
|
|
118
|
+
if (held.joinEpoch === undefined || held.epoch - (held.joinEpoch - 1) > held.horizon)
|
|
119
|
+
return { decision: 'keep', reason: 'beyond-horizon' };
|
|
120
|
+
// Depth is the first key of the ordering: a higher C wins outright (equal depth falls through to the committer).
|
|
121
|
+
if (competing.epoch > held.epoch)
|
|
122
|
+
return { decision: 'switch' };
|
|
123
|
+
return rankAtEqualDepth(held, competing);
|
|
124
|
+
}
|
|
125
|
+
/** `judgeCompetingWelcome` without the reason: `switch`, `keep` or `undecidable` (spec: `decideCompetingWelcome`). */
|
|
126
|
+
export function decideCompetingWelcome(held, competing) {
|
|
127
|
+
return judgeCompetingWelcome(held, competing).decision;
|
|
128
|
+
}
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Invitee-side decline (S6, AC-WEL-6): the optional application-level
|
|
3
|
+
* decline rumor to the sponsor (ADR-008 — there is no protocol decline) and
|
|
4
|
+
* its durable delivery.
|
|
5
|
+
*
|
|
6
|
+
* The rumor (kind `RUMOR_KINDS.DECLINE`, content `{ v: 1, welcome, groupId, keyPackageRef? }`,
|
|
7
|
+
* no tags — the group id stays inside the gift wrap) is stored with the
|
|
8
|
+
* invitation's `declined` record before anything is signed. A delivery
|
|
9
|
+
* attempt is intent -> publish -> confirm, like S5's Welcome delivery:
|
|
10
|
+
*
|
|
11
|
+
* 1. resolve the sponsor's inbox relays (`relay-planes.ts`, the inbox
|
|
12
|
+
* plane); a transient lookup leaves it pending with nothing published;
|
|
13
|
+
* 2. gift-wrap outside any transaction (the seal is signed by the account
|
|
14
|
+
* key) and store the wrap before publishing it — a wrap already stored
|
|
15
|
+
* may be live, so it is re-published as is, never replaced;
|
|
16
|
+
* 3. publish; the classified outcome is written back after re-reading the
|
|
17
|
+
* state and checking it still holds the wrap that was published.
|
|
18
|
+
*
|
|
19
|
+
* `welcome-processor.ts` owns the invitation record; this module works on
|
|
20
|
+
* its `decline` part through `read`/`update` closures.
|
|
21
|
+
*/
|
|
22
|
+
import { type NostrEvent, type Rumor } from '@941design/nostr-events/event';
|
|
23
|
+
import type { Signer } from '@941design/nostr-events/signer';
|
|
24
|
+
import type { Storable } from '../storage/index.js';
|
|
25
|
+
import { type InboxRelayDeps } from './relay-planes.js';
|
|
26
|
+
export type DeclineStatus = 'pending' | 'delivered' | 'failed';
|
|
27
|
+
export interface DeclineState {
|
|
28
|
+
readonly rumor: Rumor;
|
|
29
|
+
/** The sponsor account the rumor goes to. */
|
|
30
|
+
readonly recipient: string;
|
|
31
|
+
readonly wrap?: NostrEvent;
|
|
32
|
+
readonly relays?: readonly string[];
|
|
33
|
+
readonly status: DeclineStatus;
|
|
34
|
+
/** Failed publishes (they count toward `maxPublishAttempts`). */
|
|
35
|
+
readonly attempts: number;
|
|
36
|
+
readonly reason?: string;
|
|
37
|
+
}
|
|
38
|
+
/**
|
|
39
|
+
* The decline rumor for invitation `welcomeId` of `groupId`, authored by `author`. `keyPackageRef` (epic
|
|
40
|
+
* marmot-invitation-outcomes S3, spec DD3) is the KeyPackageRef the Welcome was consumed with: an optional extra field
|
|
41
|
+
* of the same v1 content that selects this device's delivery at an upgraded inviter; a reader that predates it
|
|
42
|
+
* ignores it. Omitted, the content is exactly `{ v: 1, welcome, groupId }` (an unqualified decline).
|
|
43
|
+
*/
|
|
44
|
+
export declare function buildDeclineRumor(opts: {
|
|
45
|
+
readonly author: string;
|
|
46
|
+
readonly welcomeId: string;
|
|
47
|
+
readonly groupId: string;
|
|
48
|
+
readonly nowSeconds: number;
|
|
49
|
+
readonly keyPackageRef?: string;
|
|
50
|
+
}): Rumor;
|
|
51
|
+
export declare function encodeRumor(rumor: Rumor): Storable;
|
|
52
|
+
/** Decodes a stored rumor; `kind` pins the only kind the record may hold. */
|
|
53
|
+
export declare function decodeRumor(where: string, raw: unknown, kind: number): Rumor;
|
|
54
|
+
export declare function encodeDecline(state: DeclineState): Storable;
|
|
55
|
+
export declare function decodeDecline(where: string, raw: unknown): DeclineState;
|
|
56
|
+
export interface DeclineDeliveryDeps extends InboxRelayDeps {
|
|
57
|
+
/** The account-key signer (seals the gift wrap), already routed through the re-entrancy guard. */
|
|
58
|
+
readonly signer: Signer;
|
|
59
|
+
readonly maxPublishAttempts: number;
|
|
60
|
+
}
|
|
61
|
+
export interface DeclineStore {
|
|
62
|
+
read(): Promise<DeclineState | undefined>;
|
|
63
|
+
/** Re-reads the state and applies `change` in one account transaction (`undefined` leaves it as stored); returns the state as stored afterwards. */
|
|
64
|
+
update(change: (current: DeclineState) => DeclineState | undefined): Promise<DeclineState | undefined>;
|
|
65
|
+
}
|
|
66
|
+
/** One delivery attempt of a pending decline. Returns the state as stored afterwards. */
|
|
67
|
+
export declare function attemptDeclineDelivery(deps: DeclineDeliveryDeps, store: DeclineStore): Promise<DeclineState | undefined>;
|
|
@@ -0,0 +1,149 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Invitee-side decline (S6, AC-WEL-6): the optional application-level
|
|
3
|
+
* decline rumor to the sponsor (ADR-008 — there is no protocol decline) and
|
|
4
|
+
* its durable delivery.
|
|
5
|
+
*
|
|
6
|
+
* The rumor (kind `RUMOR_KINDS.DECLINE`, content `{ v: 1, welcome, groupId, keyPackageRef? }`,
|
|
7
|
+
* no tags — the group id stays inside the gift wrap) is stored with the
|
|
8
|
+
* invitation's `declined` record before anything is signed. A delivery
|
|
9
|
+
* attempt is intent -> publish -> confirm, like S5's Welcome delivery:
|
|
10
|
+
*
|
|
11
|
+
* 1. resolve the sponsor's inbox relays (`relay-planes.ts`, the inbox
|
|
12
|
+
* plane); a transient lookup leaves it pending with nothing published;
|
|
13
|
+
* 2. gift-wrap outside any transaction (the seal is signed by the account
|
|
14
|
+
* key) and store the wrap before publishing it — a wrap already stored
|
|
15
|
+
* may be live, so it is re-published as is, never replaced;
|
|
16
|
+
* 3. publish; the classified outcome is written back after re-reading the
|
|
17
|
+
* state and checking it still holds the wrap that was published.
|
|
18
|
+
*
|
|
19
|
+
* `welcome-processor.ts` owns the invitation record; this module works on
|
|
20
|
+
* its `decline` part through `read`/`update` closures.
|
|
21
|
+
*/
|
|
22
|
+
import { getEventHash } from '@941design/nostr-events/event';
|
|
23
|
+
import { wrap as giftWrap } from '@941design/nostr-events/gift-wrap';
|
|
24
|
+
import { classifyPublish, MarmotError, RUMOR_KINDS } from '../shared/index.js';
|
|
25
|
+
import { resolveInboxRelays } from './relay-planes.js';
|
|
26
|
+
/**
|
|
27
|
+
* The decline rumor for invitation `welcomeId` of `groupId`, authored by `author`. `keyPackageRef` (epic
|
|
28
|
+
* marmot-invitation-outcomes S3, spec DD3) is the KeyPackageRef the Welcome was consumed with: an optional extra field
|
|
29
|
+
* of the same v1 content that selects this device's delivery at an upgraded inviter; a reader that predates it
|
|
30
|
+
* ignores it. Omitted, the content is exactly `{ v: 1, welcome, groupId }` (an unqualified decline).
|
|
31
|
+
*/
|
|
32
|
+
export function buildDeclineRumor(opts) {
|
|
33
|
+
const body = { v: 1, welcome: opts.welcomeId, groupId: opts.groupId, ...(opts.keyPackageRef === undefined ? {} : { keyPackageRef: opts.keyPackageRef }) };
|
|
34
|
+
const draft = { kind: RUMOR_KINDS.DECLINE, pubkey: opts.author, created_at: opts.nowSeconds, tags: [], content: JSON.stringify(body) };
|
|
35
|
+
return { ...draft, id: getEventHash(draft) };
|
|
36
|
+
}
|
|
37
|
+
// ---------------------------------------------------------------------------
|
|
38
|
+
// Codec (stored inside the invitation record)
|
|
39
|
+
// ---------------------------------------------------------------------------
|
|
40
|
+
function malformed(where, detail) {
|
|
41
|
+
return new MarmotError('store-failed', `${where}: malformed record (${detail})`, { details: { where, malformed: true } });
|
|
42
|
+
}
|
|
43
|
+
function isObject(value) {
|
|
44
|
+
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
45
|
+
}
|
|
46
|
+
function isStringTags(tags) {
|
|
47
|
+
return Array.isArray(tags) && tags.every((t) => Array.isArray(t) && t.every((v) => typeof v === 'string'));
|
|
48
|
+
}
|
|
49
|
+
export function encodeRumor(rumor) {
|
|
50
|
+
return { id: rumor.id, pubkey: rumor.pubkey, kind: rumor.kind, created_at: rumor.created_at, tags: rumor.tags.map((t) => [...t]), content: rumor.content };
|
|
51
|
+
}
|
|
52
|
+
/** Decodes a stored rumor; `kind` pins the only kind the record may hold. */
|
|
53
|
+
export function decodeRumor(where, raw, kind) {
|
|
54
|
+
if (!isObject(raw))
|
|
55
|
+
throw malformed(where, 'rumor not an object');
|
|
56
|
+
const { id, pubkey, kind: k, created_at: createdAt, tags, content } = raw;
|
|
57
|
+
if (typeof id !== 'string' || typeof pubkey !== 'string' || k !== kind || typeof createdAt !== 'number' || typeof content !== 'string' || !isStringTags(tags)) {
|
|
58
|
+
throw malformed(where, 'rumor fields');
|
|
59
|
+
}
|
|
60
|
+
return { id, pubkey, kind: k, created_at: createdAt, tags, content };
|
|
61
|
+
}
|
|
62
|
+
function decodeWrap(where, raw) {
|
|
63
|
+
if (!isObject(raw))
|
|
64
|
+
throw malformed(where, 'wrap not an object');
|
|
65
|
+
const { id, pubkey, kind, created_at: createdAt, tags, content, sig } = raw;
|
|
66
|
+
if (typeof id !== 'string' || typeof pubkey !== 'string' || typeof kind !== 'number' || typeof createdAt !== 'number' || typeof content !== 'string' || typeof sig !== 'string' || !isStringTags(tags)) {
|
|
67
|
+
throw malformed(where, 'wrap fields');
|
|
68
|
+
}
|
|
69
|
+
return { id, pubkey, kind, created_at: createdAt, tags, content, sig };
|
|
70
|
+
}
|
|
71
|
+
export function encodeDecline(state) {
|
|
72
|
+
return {
|
|
73
|
+
rumor: encodeRumor(state.rumor),
|
|
74
|
+
recipient: state.recipient,
|
|
75
|
+
...(state.wrap === undefined ? {} : { wrap: { ...state.wrap, tags: state.wrap.tags.map((t) => [...t]) } }),
|
|
76
|
+
...(state.relays === undefined ? {} : { relays: [...state.relays] }),
|
|
77
|
+
status: state.status,
|
|
78
|
+
attempts: state.attempts,
|
|
79
|
+
...(state.reason === undefined ? {} : { reason: state.reason }),
|
|
80
|
+
};
|
|
81
|
+
}
|
|
82
|
+
export function decodeDecline(where, raw) {
|
|
83
|
+
if (!isObject(raw))
|
|
84
|
+
throw malformed(where, 'decline not an object');
|
|
85
|
+
const { recipient, status, attempts, reason, relays } = raw;
|
|
86
|
+
if (typeof recipient !== 'string' || (status !== 'pending' && status !== 'delivered' && status !== 'failed') || typeof attempts !== 'number')
|
|
87
|
+
throw malformed(where, 'decline fields');
|
|
88
|
+
if (reason !== undefined && typeof reason !== 'string')
|
|
89
|
+
throw malformed(where, 'decline reason');
|
|
90
|
+
if (relays !== undefined && (!Array.isArray(relays) || !relays.every((r) => typeof r === 'string')))
|
|
91
|
+
throw malformed(where, 'decline relays');
|
|
92
|
+
return {
|
|
93
|
+
rumor: decodeRumor(where, raw.rumor, RUMOR_KINDS.DECLINE),
|
|
94
|
+
recipient,
|
|
95
|
+
...(raw.wrap === undefined ? {} : { wrap: decodeWrap(where, raw.wrap) }),
|
|
96
|
+
...(relays === undefined ? {} : { relays: [...relays] }),
|
|
97
|
+
status,
|
|
98
|
+
attempts,
|
|
99
|
+
...(reason === undefined ? {} : { reason }),
|
|
100
|
+
};
|
|
101
|
+
}
|
|
102
|
+
function withoutReason(state) {
|
|
103
|
+
const { reason: _reason, ...rest } = state;
|
|
104
|
+
return rest;
|
|
105
|
+
}
|
|
106
|
+
/** One delivery attempt of a pending decline. Returns the state as stored afterwards. */
|
|
107
|
+
export async function attemptDeclineDelivery(deps, store) {
|
|
108
|
+
const stored = await store.read();
|
|
109
|
+
if (stored === undefined || stored.status !== 'pending')
|
|
110
|
+
return stored;
|
|
111
|
+
const resolution = await resolveInboxRelays(deps, stored.recipient);
|
|
112
|
+
if (resolution.kind !== 'relays') {
|
|
113
|
+
const transient = resolution.kind === 'transient';
|
|
114
|
+
return store.update((current) => {
|
|
115
|
+
if (current.status !== 'pending')
|
|
116
|
+
return undefined;
|
|
117
|
+
return transient ? { ...current, reason: resolution.reason } : { ...current, status: 'failed', reason: 'no-inbox-relays' };
|
|
118
|
+
});
|
|
119
|
+
}
|
|
120
|
+
const relays = [...resolution.relays];
|
|
121
|
+
let wrap = stored.wrap;
|
|
122
|
+
if (wrap === undefined) {
|
|
123
|
+
// Signed outside any transaction (a remote signer may wait on its user).
|
|
124
|
+
const fresh = await giftWrap({ senderSigner: deps.signer, recipientPubkey: stored.recipient, rumor: stored.rumor });
|
|
125
|
+
const installed = await store.update((current) => (current.status !== 'pending' || current.wrap !== undefined ? undefined : { ...withoutReason(current), wrap: fresh, relays }));
|
|
126
|
+
if (installed?.status !== 'pending' || installed.wrap === undefined)
|
|
127
|
+
return installed;
|
|
128
|
+
wrap = installed.wrap;
|
|
129
|
+
}
|
|
130
|
+
let responses;
|
|
131
|
+
try {
|
|
132
|
+
responses = await deps.transport.publish(relays, wrap);
|
|
133
|
+
}
|
|
134
|
+
catch {
|
|
135
|
+
responses = undefined; // a thrown network error is transient
|
|
136
|
+
}
|
|
137
|
+
const outcome = responses === undefined ? 'retryable' : classifyPublish(relays, responses).outcome;
|
|
138
|
+
const published = wrap;
|
|
139
|
+
return store.update((current) => {
|
|
140
|
+
if (current.wrap?.id !== published.id || current.status !== 'pending')
|
|
141
|
+
return undefined;
|
|
142
|
+
if (outcome === 'accepted')
|
|
143
|
+
return { ...withoutReason(current), relays, status: 'delivered' };
|
|
144
|
+
if (outcome === 'terminal')
|
|
145
|
+
return { ...current, relays, status: 'failed', reason: 'publish-refused' };
|
|
146
|
+
const attempts = current.attempts + 1;
|
|
147
|
+
return attempts >= deps.maxPublishAttempts ? { ...current, relays, attempts, status: 'failed', reason: 'max-attempts' } : { ...current, relays, attempts, reason: 'publish-failed' };
|
|
148
|
+
});
|
|
149
|
+
}
|