@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,92 @@
|
|
|
1
|
+
import { type ClientState } from '@941design/marmot-engine/mls';
|
|
2
|
+
import { type AdmissionDerivation, type OwnChange, type OwnChangeLostReason, type RetainedWindow } from '../history/index.js';
|
|
3
|
+
import type { AdmissionTarget, StorableIntent, StoredOwnChange } from './group-records.js';
|
|
4
|
+
/** The facts the checks read: the tip the commit will be built on and the window the lineage evidence lives in. */
|
|
5
|
+
export interface RedriveFacts {
|
|
6
|
+
/** The engine's tip state: the tree the commit is built on. */
|
|
7
|
+
readonly state: ClientState;
|
|
8
|
+
/** The retained rewind window, and its own tip state (the exposed one). */
|
|
9
|
+
readonly window: RetainedWindow;
|
|
10
|
+
readonly windowTip: ClientState;
|
|
11
|
+
/** Whether the author's ACCOUNT is an active admin at `state` (`isActiveAdmin`, rotation-proof). */
|
|
12
|
+
readonly authorIsAdmin: boolean;
|
|
13
|
+
/** The fork-point epoch the record's changes were captured at. */
|
|
14
|
+
readonly forkEpoch: number;
|
|
15
|
+
/**
|
|
16
|
+
* The refs (`inviteeRef`) of the stored KeyPackages the invitations path no longer accepts at build time (`validateInvitees`:
|
|
17
|
+
* expired, rejected by the verifier, ineligible for the group). Decided by the drive, which owns the clock and the verifier; the
|
|
18
|
+
* ladder only reads it. Required: a caller that cannot say must not look as if every KeyPackage is valid.
|
|
19
|
+
*/
|
|
20
|
+
readonly invalidKeyPackages: ReadonlySet<string>;
|
|
21
|
+
/**
|
|
22
|
+
* Epic marmot-invitation-outcomes S5 (SC-5 I15): what the selected path proves about a cleanup target's admission at the build
|
|
23
|
+
* state (its stored lineage derived over the window). Decided by the drive, which owns the store; absent (or `undefined` for a
|
|
24
|
+
* target) proves nothing, so an `admission-removed` change is then lost `concurrent-change` (fail closed).
|
|
25
|
+
*/
|
|
26
|
+
readonly admissionOf?: (target: AdmissionTarget) => AdmissionDerivation | undefined;
|
|
27
|
+
}
|
|
28
|
+
/** What the surviving changes of one kind add to the intent the commit is built from (never stored: DD15). */
|
|
29
|
+
export type RedriveContribution = Partial<Pick<Extract<StorableIntent, {
|
|
30
|
+
type: 'commit';
|
|
31
|
+
}>, 'removeAccounts' | 'removeAccountLeafKeys' | 'admins' | 'components' | 'invite' | 'removeAdmission'>>;
|
|
32
|
+
/**
|
|
33
|
+
* Epic marmot-invitation-outcomes S5 (SC-11 D8, I14): why a scoped cleanup of the leaf at `leafIndex` cannot be built on `state`
|
|
34
|
+
* now, or `undefined`. A staged Remove or SelfRemove of that leaf would be carried by reference (a by-reference end is never
|
|
35
|
+
* attributed, I14) and a second Remove of it is invalid; a staged Add may refill the vacated position in the same commit (a
|
|
36
|
+
* `replaced` end, never attributed). Either way the consumer commits the staged proposals first and retries. Pure.
|
|
37
|
+
*/
|
|
38
|
+
export declare function stagedCleanupConflict(state: ClientState, leafIndex: number): 'staged-removal-of-target' | 'staged-add-conflict' | undefined;
|
|
39
|
+
/**
|
|
40
|
+
* Epic marmot-invitation-outcomes S5 (SC-5 I15): why `target` may not be removed by a commit built on `state` (the actual parent),
|
|
41
|
+
* given what the selected path proves about its admission there (`admission`), or `undefined` when the proven original admission
|
|
42
|
+
* occupies the target position under the derived key and nothing staged interferes. Pure; shared by the build recheck and the re-drive
|
|
43
|
+
* check. `already-applied`: the admission ended or its Add is off the path; `concurrent-change`: nothing proves it (a gap), the leaf
|
|
44
|
+
* changed under it, the position is the committer's own, or a staged proposal conflicts.
|
|
45
|
+
*/
|
|
46
|
+
export declare function cleanupTargetRefusal(target: AdmissionTarget, admission: AdmissionDerivation | undefined, state: ClientState): {
|
|
47
|
+
readonly lost: OwnChangeLostReason;
|
|
48
|
+
readonly reason: string;
|
|
49
|
+
} | undefined;
|
|
50
|
+
/** The part of the ladder that is specific to one kind of change. */
|
|
51
|
+
export interface RedriveChangeKind<C extends StoredOwnChange> {
|
|
52
|
+
/** The reason `change` is lost at `facts`, or `undefined` when it still applies. Decided from the change's fork-point values and the current state. */
|
|
53
|
+
readonly check: (change: C, facts: RedriveFacts) => OwnChangeLostReason | undefined;
|
|
54
|
+
/**
|
|
55
|
+
* For a kind whose survivors depend on one another: the further changes of `survivors` (all of this kind that passed `check`) that
|
|
56
|
+
* cannot be applied TOGETHER, with their reasons. Optional; run once, before `contribute`, over the survivors of `check`.
|
|
57
|
+
*/
|
|
58
|
+
readonly checkSet?: (survivors: readonly C[], facts: RedriveFacts) => ReadonlyMap<C, OwnChangeLostReason>;
|
|
59
|
+
/** What `survivors` (all of this kind, at least one) add to the commit to build. */
|
|
60
|
+
readonly contribute: (survivors: readonly C[], facts: RedriveFacts) => RedriveContribution;
|
|
61
|
+
}
|
|
62
|
+
type OfKind<K extends OwnChange['type']> = Extract<StoredOwnChange, {
|
|
63
|
+
readonly change: {
|
|
64
|
+
readonly type: K;
|
|
65
|
+
};
|
|
66
|
+
}>;
|
|
67
|
+
/**
|
|
68
|
+
* The invite changes whose KeyPackage the drive must still check (the facts' `invalidKeyPackages`): undecided, the author an
|
|
69
|
+
* admin, and neither already applied nor reversed -- the ladder would reach the validity rung for exactly these, so a consumer
|
|
70
|
+
* verifier is never called for a change that is lost anyway. Pure.
|
|
71
|
+
*/
|
|
72
|
+
export declare function changesNeedingKeyPackageCheck(stored: readonly StoredOwnChange[], facts: Omit<RedriveFacts, 'invalidKeyPackages'>): readonly OfKind<'member-added'>[];
|
|
73
|
+
/** The handlers by change type: every kind has one, so a change is never lost for want of a handler. */
|
|
74
|
+
export declare const REDRIVE_CHANGE_KINDS: {
|
|
75
|
+
readonly [K in OwnChange['type']]: RedriveChangeKind<OfKind<K>>;
|
|
76
|
+
};
|
|
77
|
+
/** The verdicts of one ladder run. */
|
|
78
|
+
export interface LadderOutcome {
|
|
79
|
+
/** Every change of the record, in order: those decided lost in an EARLIER run keep their verdict; those lost now gain it; survivors have none. */
|
|
80
|
+
readonly changes: readonly StoredOwnChange[];
|
|
81
|
+
/** The changes lost by THIS run (the ones to signal): earlier verdicts were persisted, and signalled, before. */
|
|
82
|
+
readonly newlyLost: readonly {
|
|
83
|
+
readonly change: OwnChange;
|
|
84
|
+
readonly reason: OwnChangeLostReason;
|
|
85
|
+
}[];
|
|
86
|
+
readonly survivors: readonly StoredOwnChange[];
|
|
87
|
+
/** The kinds' contributions merged: the payload of the commit to build. Empty when nothing survives. */
|
|
88
|
+
readonly contribution: RedriveContribution;
|
|
89
|
+
}
|
|
90
|
+
/** Runs rungs 2 and 3 of the ladder over `stored` (rung 1, stranded, never reaches here). Pure. */
|
|
91
|
+
export declare function decideChanges(stored: readonly StoredOwnChange[], facts: RedriveFacts): LadderOutcome;
|
|
92
|
+
export {};
|
|
@@ -0,0 +1,274 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The build-time check ladder of a commit re-drive (epic marmot-rewound-own-commit-no-signal, spec Design Decision 11),
|
|
3
|
+
* and the per-change-kind extension point it runs the kind-specific part through.
|
|
4
|
+
*
|
|
5
|
+
* Pure: it reads a state, the retained window and the stored changes of a re-drive record and returns verdicts and a
|
|
6
|
+
* payload contribution. Everything that reads the runtime, writes the store or dispatches belongs to `pipeline.ts`.
|
|
7
|
+
*
|
|
8
|
+
* The ladder, in order (the first two are the whole record's; the rest are per change):
|
|
9
|
+
* 1. stranded (the author's device removed for good, or the group fenced): decided by the drive, which owns the runtime;
|
|
10
|
+
* 2. not-admin (the author's ACCOUNT is not an active admin, AC-DRIVE-9): every undecided change is lost `not-admin`;
|
|
11
|
+
* 3. each undecided change through its kind's {@link RedriveChangeKind.check}: a lost reason, or `undefined` (survives).
|
|
12
|
+
* The surviving changes of a kind then each contribute to the one commit that is built ({@link RedriveChangeKind.contribute}).
|
|
13
|
+
*
|
|
14
|
+
* Extension point: {@link REDRIVE_CHANGE_KINDS} maps a change type to its handler. A story adding a kind adds ONE
|
|
15
|
+
* entry; the ladder, the drive and the durability around them are unchanged. A kind whose survivors are not independent of one
|
|
16
|
+
* another (the admin list) also gives {@link RedriveChangeKind.checkSet}, which runs over the survivors of the per-change check.
|
|
17
|
+
*/
|
|
18
|
+
import { GROUP_ADMIN_POLICY_COMPONENT_ID } from '@941design/marmot-engine/core';
|
|
19
|
+
import { defaultProposalTypes, selfRemoveProposalType } from '@941design/marmot-engine/mls';
|
|
20
|
+
import { validateAdminList } from '../account/index.js';
|
|
21
|
+
import { adminsOf, commitViewOf, holdsLeafKey, leafKeyAt, sameBytes, winnerHeldLeaf, winnerRemovedAccount } from '../history/index.js';
|
|
22
|
+
import { stagesComponentUpdate } from './component-update.js';
|
|
23
|
+
import { stagedAddLeafKeys } from '../invitations/index.js';
|
|
24
|
+
import { holdsLeafOfAny } from './group-remove-member.js';
|
|
25
|
+
/**
|
|
26
|
+
* Epic marmot-invitation-outcomes S5 (SC-11 D8, I14): why a scoped cleanup of the leaf at `leafIndex` cannot be built on `state`
|
|
27
|
+
* now, or `undefined`. A staged Remove or SelfRemove of that leaf would be carried by reference (a by-reference end is never
|
|
28
|
+
* attributed, I14) and a second Remove of it is invalid; a staged Add may refill the vacated position in the same commit (a
|
|
29
|
+
* `replaced` end, never attributed). Either way the consumer commits the staged proposals first and retries. Pure.
|
|
30
|
+
*/
|
|
31
|
+
export function stagedCleanupConflict(state, leafIndex) {
|
|
32
|
+
let add = false;
|
|
33
|
+
for (const { proposal, senderLeafIndex } of Object.values(state.unappliedProposals)) {
|
|
34
|
+
if (proposal.proposalType === defaultProposalTypes.remove && 'remove' in proposal && Number(proposal.remove.removed) === leafIndex)
|
|
35
|
+
return 'staged-removal-of-target';
|
|
36
|
+
if (proposal.proposalType === selfRemoveProposalType && senderLeafIndex !== undefined && Number(senderLeafIndex) === leafIndex)
|
|
37
|
+
return 'staged-removal-of-target';
|
|
38
|
+
if (proposal.proposalType === defaultProposalTypes.add)
|
|
39
|
+
add = true;
|
|
40
|
+
}
|
|
41
|
+
return add ? 'staged-add-conflict' : undefined;
|
|
42
|
+
}
|
|
43
|
+
/**
|
|
44
|
+
* Epic marmot-invitation-outcomes S5 (SC-5 I15): why `target` may not be removed by a commit built on `state` (the actual parent),
|
|
45
|
+
* given what the selected path proves about its admission there (`admission`), or `undefined` when the proven original admission
|
|
46
|
+
* occupies the target position under the derived key and nothing staged interferes. Pure; shared by the build recheck and the re-drive
|
|
47
|
+
* check. `already-applied`: the admission ended or its Add is off the path; `concurrent-change`: nothing proves it (a gap), the leaf
|
|
48
|
+
* changed under it, the position is the committer's own, or a staged proposal conflicts.
|
|
49
|
+
*/
|
|
50
|
+
export function cleanupTargetRefusal(target, admission, state) {
|
|
51
|
+
const occupancy = admission?.occupancy;
|
|
52
|
+
if (occupancy === undefined || occupancy.kind === 'gap')
|
|
53
|
+
return { lost: 'concurrent-change', reason: 'admission-unproven' };
|
|
54
|
+
if (occupancy.kind === 'ended' || occupancy.kind === 'add-off-path')
|
|
55
|
+
return { lost: 'already-applied', reason: 'admission-ended' };
|
|
56
|
+
const leafIndex = target.anchor.leafIndex;
|
|
57
|
+
if (leafKeyAt(state, leafIndex) !== occupancy.leafKey)
|
|
58
|
+
return { lost: 'concurrent-change', reason: 'admission-changed' };
|
|
59
|
+
if (Number(state.privatePath.leafIndex) === leafIndex)
|
|
60
|
+
return { lost: 'concurrent-change', reason: 'self' };
|
|
61
|
+
const conflict = stagedCleanupConflict(state, leafIndex);
|
|
62
|
+
return conflict === undefined ? undefined : { lost: 'concurrent-change', reason: conflict };
|
|
63
|
+
}
|
|
64
|
+
/**
|
|
65
|
+
* Member removal (DD4 as amended, DD5, DD12). Already applied: the account holds no leaf. Reversed: the winning branch above
|
|
66
|
+
* the fork point REMOVED the account (captured at withdrawal as `winnerRemovedTarget`, extended with the current window's canonical
|
|
67
|
+
* edges) and the account holds a leaf now -- a deliberate re-add, also under the same device key (device keys are stable across
|
|
68
|
+
* KeyPackages). A target that merely rotated was never removed by the winner, so it is still removed (lineage needs no check of
|
|
69
|
+
* its own: the commit removes every leaf the account holds when it is built, `removeProposalsForAccounts`; `fork.leafKeys`
|
|
70
|
+
* only feeds the commit's leaf-key snapshot). When the window floor passed the fork point and nothing was captured the
|
|
71
|
+
* evidence is inconclusive: the standing decision wins (re-remove).
|
|
72
|
+
*/
|
|
73
|
+
const memberRemoved = {
|
|
74
|
+
check: ({ change, winnerRemovedTarget }, { state, window, windowTip, forkEpoch }) => {
|
|
75
|
+
if (!holdsLeafOfAny(state, [change.account]))
|
|
76
|
+
return 'already-applied';
|
|
77
|
+
if (winnerRemovedTarget === true || winnerRemovedAccount(change.account, forkEpoch, [window], windowTip))
|
|
78
|
+
return 'reversed';
|
|
79
|
+
return undefined;
|
|
80
|
+
},
|
|
81
|
+
contribute: (survivors) => ({
|
|
82
|
+
removeAccounts: survivors.map((s) => s.change.account),
|
|
83
|
+
removeAccountLeafKeys: [...new Set(survivors.flatMap((s) => s.fork.leafKeys))].sort(),
|
|
84
|
+
}),
|
|
85
|
+
};
|
|
86
|
+
/** `state`'s app-data dictionary; `undefined` when it cannot be read (never true of a state the engine accepted, but the ladder must not throw inside the drive). */
|
|
87
|
+
function dictionaryOf(state) {
|
|
88
|
+
try {
|
|
89
|
+
return commitViewOf(state).dictionary;
|
|
90
|
+
}
|
|
91
|
+
catch {
|
|
92
|
+
return undefined;
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
/** Bytes, or absence (`null`), of one component compared as the fork-point value is. */
|
|
96
|
+
const sameComponentBytes = (a, b) => (a === null || b === null ? a === b : sameBytes(a, b));
|
|
97
|
+
/**
|
|
98
|
+
* A component (the group profile `0x8001`, a generic one by id; DD3, DD11). Unchanged since the fork point (bytes, or absence, equal
|
|
99
|
+
* the fork-point value: a winner that changed it and changed it back counts as unchanged, AC-COMP-9) and no foreign update of it
|
|
100
|
+
* staged on the build state (AC-COMP-7, which keeps the build's `guardedComponentUpdate` from throwing): the change is re-applied
|
|
101
|
+
* with the withdrawn commit's bytes (or its deletion). Otherwise someone else's value stands (AC-COMP-2).
|
|
102
|
+
*/
|
|
103
|
+
const componentChanged = {
|
|
104
|
+
check: ({ change, fork }, { state }) => {
|
|
105
|
+
const dictionary = dictionaryOf(state);
|
|
106
|
+
if (dictionary === undefined || !sameComponentBytes(dictionary.get(change.componentId) ?? null, fork.component))
|
|
107
|
+
return 'concurrent-change';
|
|
108
|
+
return stagesComponentUpdate(state, change.componentId) ? 'concurrent-change' : undefined;
|
|
109
|
+
},
|
|
110
|
+
contribute: (survivors) => ({ components: survivors.map((s) => ({ id: s.change.componentId, data: s.data })) }),
|
|
111
|
+
};
|
|
112
|
+
/** The tip's admin list, lowercase and in list order; `undefined` when its policy does not decode (never true of a state the engine accepted). An absent policy is an empty list. */
|
|
113
|
+
function tipAdmins(state) {
|
|
114
|
+
const dictionary = dictionaryOf(state);
|
|
115
|
+
const admins = dictionary === undefined ? 'unreadable' : adminsOf(dictionary);
|
|
116
|
+
return admins === 'unreadable' ? undefined : [...(admins ?? [])];
|
|
117
|
+
}
|
|
118
|
+
/** The re-drive's admin list (DD3): the tip's list with each surviving per-member flip applied, a grant appended and a revoke dropped. */
|
|
119
|
+
function rebuiltAdmins(tip, survivors) {
|
|
120
|
+
const revoked = new Set(survivors.filter((s) => !s.change.admin).map((s) => s.change.account.toLowerCase()));
|
|
121
|
+
return [...new Set([...tip, ...survivors.filter((s) => s.change.admin).map((s) => s.change.account.toLowerCase())])].filter((a) => !revoked.has(a));
|
|
122
|
+
}
|
|
123
|
+
/**
|
|
124
|
+
* Admin flips, per member (DD3, DD11). A flip survives when the account's status at the tip is still its fork-point status (the
|
|
125
|
+
* winner flipped it, or flipped it and back: AC-COMP-3, AC-COMP-9), no foreign update of the admin list is staged (AC-COMP-7), and
|
|
126
|
+
* a grant names an account that still holds a leaf (AC-COMP-6). Together the survivors must give a list `validateAdminList` accepts
|
|
127
|
+
* (never empty): revokes that would empty it are lost, and so is the whole set if the rebuilt list is invalid for any other reason --
|
|
128
|
+
* decided here, before the budget gate, so no publish is spent on it and `validateAdminList` never throws inside the drive.
|
|
129
|
+
*/
|
|
130
|
+
const adminFlipped = {
|
|
131
|
+
check: ({ change, fork }, { state }) => {
|
|
132
|
+
const tip = tipAdmins(state);
|
|
133
|
+
if (tip === undefined || tip.includes(change.account.toLowerCase()) !== fork.admin)
|
|
134
|
+
return 'concurrent-change';
|
|
135
|
+
if (stagesComponentUpdate(state, GROUP_ADMIN_POLICY_COMPONENT_ID))
|
|
136
|
+
return 'concurrent-change';
|
|
137
|
+
if (change.admin && !holdsLeafOfAny(state, [change.account]))
|
|
138
|
+
return 'concurrent-change';
|
|
139
|
+
return undefined;
|
|
140
|
+
},
|
|
141
|
+
checkSet: (survivors, { state }) => {
|
|
142
|
+
const lost = new Map();
|
|
143
|
+
const tip = tipAdmins(state) ?? [];
|
|
144
|
+
let kept = survivors;
|
|
145
|
+
if (rebuiltAdmins(tip, kept).length === 0) {
|
|
146
|
+
for (const s of kept.filter((c) => !c.change.admin))
|
|
147
|
+
lost.set(s, 'concurrent-change');
|
|
148
|
+
kept = kept.filter((c) => !lost.has(c));
|
|
149
|
+
}
|
|
150
|
+
if (kept.length > 0) {
|
|
151
|
+
try {
|
|
152
|
+
validateAdminList(state.ratchetTree, rebuiltAdmins(tip, kept));
|
|
153
|
+
}
|
|
154
|
+
catch {
|
|
155
|
+
for (const s of kept)
|
|
156
|
+
lost.set(s, 'concurrent-change');
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
return lost;
|
|
160
|
+
},
|
|
161
|
+
contribute: (survivors, { state }) => ({ admins: rebuiltAdmins(tipAdmins(state) ?? [], survivors) }),
|
|
162
|
+
};
|
|
163
|
+
/** The rungs of an invite that need no KeyPackage check: already applied, then reversed. */
|
|
164
|
+
function memberAddedEvidence({ change, winnerHeldInvitee }, { state, window, windowTip, forkEpoch }) {
|
|
165
|
+
if (holdsLeafKey(commitViewOf(state), change.leafKey))
|
|
166
|
+
return 'already-applied';
|
|
167
|
+
if (winnerHeldInvitee === true || winnerHeldLeaf(change.leafKey, forkEpoch, [window], windowTip))
|
|
168
|
+
return 'reversed';
|
|
169
|
+
return undefined;
|
|
170
|
+
}
|
|
171
|
+
/**
|
|
172
|
+
* The invite changes whose KeyPackage the drive must still check (the facts' `invalidKeyPackages`): undecided, the author an
|
|
173
|
+
* admin, and neither already applied nor reversed -- the ladder would reach the validity rung for exactly these, so a consumer
|
|
174
|
+
* verifier is never called for a change that is lost anyway. Pure.
|
|
175
|
+
*/
|
|
176
|
+
export function changesNeedingKeyPackageCheck(stored, facts) {
|
|
177
|
+
if (!facts.authorIsAdmin)
|
|
178
|
+
return [];
|
|
179
|
+
return stored.filter((c) => c.verdict === undefined && c.change.type === 'member-added' && memberAddedEvidence(c, facts) === undefined);
|
|
180
|
+
}
|
|
181
|
+
/**
|
|
182
|
+
* An invite (DD16, AC-INV-3/4/6). The change names the invitee LEAF (`leafKey`), not only the account, so a second-device invite
|
|
183
|
+
* of an account that is already a member is told from the account itself. Ladder, in order:
|
|
184
|
+
* - already applied: the tip holds that leaf key (a re-invite, or the original back on the path);
|
|
185
|
+
* - reversed: the winning branch above the fork point held the leaf (captured at withdrawal as `winnerHeldInvitee`, extended
|
|
186
|
+
* with the current window) and the tip does not any more -- somebody removed the invitee, which the re-drive must not undo.
|
|
187
|
+
* Past the horizon with nothing captured the evidence is inconclusive and the standing decision wins (Add);
|
|
188
|
+
* - invalid KeyPackage: the stored KeyPackage is no longer accepted by the invitations path (AC-INV-4); decided here, before the
|
|
189
|
+
* budget gate, so no publish attempt is spent on it;
|
|
190
|
+
* - concurrent change: an Add of the same leaf is already staged on the build state (the commit would carry it by reference
|
|
191
|
+
* and the re-drive's own Add would be a second one).
|
|
192
|
+
* The survivors Add from the KeyPackage event the RECORD retained (never from the original marker, which may be pruned).
|
|
193
|
+
*/
|
|
194
|
+
const memberAdded = {
|
|
195
|
+
check: (stored, facts) => {
|
|
196
|
+
const { change, keyPackage } = stored;
|
|
197
|
+
const { state, invalidKeyPackages } = facts;
|
|
198
|
+
const evidence = memberAddedEvidence(stored, facts);
|
|
199
|
+
if (evidence !== undefined)
|
|
200
|
+
return evidence;
|
|
201
|
+
if (invalidKeyPackages.has(keyPackage.inviteeRef))
|
|
202
|
+
return 'invalid-keypackage';
|
|
203
|
+
if (stagedAddLeafKeys(state).has(change.leafKey))
|
|
204
|
+
return 'concurrent-change';
|
|
205
|
+
return undefined;
|
|
206
|
+
},
|
|
207
|
+
contribute: (survivors) => ({ invite: { invitees: survivors.map((s) => ({ event: s.keyPackage.event, inviteeRef: s.keyPackage.inviteeRef })) } }),
|
|
208
|
+
};
|
|
209
|
+
/**
|
|
210
|
+
* A scoped cleanup (epic marmot-invitation-outcomes S5, SC-6 I16/I17). The change names the target ADMISSION, never the account: the
|
|
211
|
+
* re-drive removes that one leaf position again, inline, and only while the proven original admission still occupies it on the actual
|
|
212
|
+
* parent ({@link cleanupTargetRefusal} over the drive's lineage derivation). Already applied: the admission ended (whoever removed it)
|
|
213
|
+
* or its Add left the path. Concurrent change: a lineage gap, a changed leaf, or a staged proposal in the way. Never re-driven as an
|
|
214
|
+
* account-wide removal (`removeAccounts`).
|
|
215
|
+
*/
|
|
216
|
+
const admissionRemoved = {
|
|
217
|
+
check: ({ target }, { state, admissionOf }) => cleanupTargetRefusal(target, admissionOf?.(target), state)?.lost,
|
|
218
|
+
// One cleanup per record (the intent is exclusive): the first survivor's target is the commit's.
|
|
219
|
+
contribute: (survivors) => ({ removeAdmission: survivors[0].target }),
|
|
220
|
+
};
|
|
221
|
+
/** The handlers by change type: every kind has one, so a change is never lost for want of a handler. */
|
|
222
|
+
export const REDRIVE_CHANGE_KINDS = {
|
|
223
|
+
'member-removed': memberRemoved,
|
|
224
|
+
'member-added': memberAdded,
|
|
225
|
+
admin: adminFlipped,
|
|
226
|
+
component: componentChanged,
|
|
227
|
+
'admission-removed': admissionRemoved,
|
|
228
|
+
};
|
|
229
|
+
function handlerOf(change) {
|
|
230
|
+
return REDRIVE_CHANGE_KINDS[change.change.type];
|
|
231
|
+
}
|
|
232
|
+
/** Runs rungs 2 and 3 of the ladder over `stored` (rung 1, stranded, never reaches here). Pure. */
|
|
233
|
+
export function decideChanges(stored, facts) {
|
|
234
|
+
// Pass 1: each undecided change alone (not-admin, then its kind's check).
|
|
235
|
+
const lostNow = new Map();
|
|
236
|
+
for (const change of stored) {
|
|
237
|
+
if (change.verdict !== undefined)
|
|
238
|
+
continue;
|
|
239
|
+
const handler = handlerOf(change);
|
|
240
|
+
const reason = !facts.authorIsAdmin ? 'not-admin' : handler.check(change, facts);
|
|
241
|
+
if (reason !== undefined)
|
|
242
|
+
lostNow.set(change, reason);
|
|
243
|
+
}
|
|
244
|
+
// Pass 2: a kind whose survivors depend on one another decides over them together.
|
|
245
|
+
const undecided = () => stored.filter((c) => c.verdict === undefined && !lostNow.has(c));
|
|
246
|
+
for (const type of new Set(undecided().map((c) => c.change.type))) {
|
|
247
|
+
const ofKind = undecided().filter((c) => c.change.type === type);
|
|
248
|
+
const lost = handlerOf(ofKind[0]).checkSet?.(ofKind, facts);
|
|
249
|
+
for (const [change, reason] of lost ?? [])
|
|
250
|
+
lostNow.set(change, reason);
|
|
251
|
+
}
|
|
252
|
+
const newlyLost = [];
|
|
253
|
+
const changes = [];
|
|
254
|
+
const survivors = [];
|
|
255
|
+
for (const change of stored) {
|
|
256
|
+
const reason = lostNow.get(change);
|
|
257
|
+
if (change.verdict !== undefined)
|
|
258
|
+
changes.push(change);
|
|
259
|
+
else if (reason !== undefined) {
|
|
260
|
+
newlyLost.push({ change: change.change, reason });
|
|
261
|
+
changes.push({ ...change, verdict: reason });
|
|
262
|
+
}
|
|
263
|
+
else {
|
|
264
|
+
changes.push(change);
|
|
265
|
+
survivors.push(change);
|
|
266
|
+
}
|
|
267
|
+
}
|
|
268
|
+
let contribution = {};
|
|
269
|
+
for (const type of new Set(survivors.map((s) => s.change.type))) {
|
|
270
|
+
const ofKind = survivors.filter((s) => s.change.type === type);
|
|
271
|
+
contribution = { ...contribution, ...handlerOf(ofKind[0]).contribute(ofKind, facts) };
|
|
272
|
+
}
|
|
273
|
+
return { changes, newlyLost, survivors, contribution };
|
|
274
|
+
}
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* "One AppDataUpdate per component" for an own commit that must not carry two. A commit carries every staged proposal by
|
|
3
|
+
* reference (first) and its own by value (after them), and the engine and ts-mls accept two updates of one component
|
|
4
|
+
* (receivers resolve to the last, the committer's own). Where that is harmless it is allowed: the admin list
|
|
5
|
+
* (`setAdmins`, the demotion of `departAsAdmin`), because teardown never commits a staged proposal, so a refusal there
|
|
6
|
+
* would block it for good (test/client/group-single-component-op.test.ts). Where AC-RENAME-9 requires it, the client
|
|
7
|
+
* refuses instead: `rename` (`0x8001`), before recording (a typed `send-rejected`, nothing written) and, for a record
|
|
8
|
+
* resumed after the staged proposal arrived, at build time.
|
|
9
|
+
*/
|
|
10
|
+
import { type ClientState, type Proposal } from '@941design/marmot-engine/mls';
|
|
11
|
+
import { MarmotError } from '../shared/index.js';
|
|
12
|
+
/** What a refusal names: the operation, the component in words, and the `details.reason` the caller reads. */
|
|
13
|
+
export interface ComponentUpdateGuard {
|
|
14
|
+
readonly componentId: number;
|
|
15
|
+
readonly groupId: string;
|
|
16
|
+
readonly operation: string;
|
|
17
|
+
/** e.g. `'group-profile'`. */
|
|
18
|
+
readonly what: string;
|
|
19
|
+
/** e.g. `'staged-profile-update'`. */
|
|
20
|
+
readonly reason: string;
|
|
21
|
+
}
|
|
22
|
+
/** Whether a proposal of `componentId`'s AppDataUpdate is staged in `state` — another member's or the local account's own. */
|
|
23
|
+
export declare function stagesComponentUpdate(state: ClientState, componentId: number): boolean;
|
|
24
|
+
/** The `send-rejected` of an own commit that would hold a second update of the guarded component. */
|
|
25
|
+
export declare function stagedComponentUpdateError(guard: ComponentUpdateGuard): MarmotError;
|
|
26
|
+
/** Throws {@link stagedComponentUpdateError} when `state` stages the guarded component's update. */
|
|
27
|
+
export declare function assertNoStagedComponentUpdate(state: ClientState, guard: ComponentUpdateGuard): void;
|
|
28
|
+
/**
|
|
29
|
+
* `build()` as a build-time engine action: evaluated against the state the commit is built on, it fails when the
|
|
30
|
+
* guarded component's update is staged there — the backstop of the pre-record check for a proposal that arrived
|
|
31
|
+
* after the call was recorded (a record resumed after a reload).
|
|
32
|
+
*/
|
|
33
|
+
export declare function guardedComponentUpdate(guard: ComponentUpdateGuard, build: () => Proposal): (context: {
|
|
34
|
+
readonly state: ClientState;
|
|
35
|
+
}) => Promise<Proposal>;
|
|
36
|
+
/**
|
|
37
|
+
* The AppDataUpdate that sets component `componentId` to `data` (`null`: removes its dictionary entry). The generic form of the
|
|
38
|
+
* typed builders (`groupProfileProposal`, `adminPolicyProposal`): what a commit's internal `components` field and a component
|
|
39
|
+
* change's re-drive are applied with. The bytes are not interpreted here; the engine validates them like any update.
|
|
40
|
+
*/
|
|
41
|
+
export declare function componentUpdateProposal(componentId: number, data: Uint8Array | null): Proposal;
|
|
42
|
+
/** The guard of an own commit's generic component update (the internal `components` field): a staged update of the same component is refused. */
|
|
43
|
+
export declare function genericComponentGuard(componentId: number, groupId: string): ComponentUpdateGuard;
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* "One AppDataUpdate per component" for an own commit that must not carry two. A commit carries every staged proposal by
|
|
3
|
+
* reference (first) and its own by value (after them), and the engine and ts-mls accept two updates of one component
|
|
4
|
+
* (receivers resolve to the last, the committer's own). Where that is harmless it is allowed: the admin list
|
|
5
|
+
* (`setAdmins`, the demotion of `departAsAdmin`), because teardown never commits a staged proposal, so a refusal there
|
|
6
|
+
* would block it for good (test/client/group-single-component-op.test.ts). Where AC-RENAME-9 requires it, the client
|
|
7
|
+
* refuses instead: `rename` (`0x8001`), before recording (a typed `send-rejected`, nothing written) and, for a record
|
|
8
|
+
* resumed after the staged proposal arrived, at build time.
|
|
9
|
+
*/
|
|
10
|
+
import { appDataUpdateProposalType } from '@941design/marmot-engine/mls';
|
|
11
|
+
import { MarmotError } from '../shared/index.js';
|
|
12
|
+
/** Whether a proposal of `componentId`'s AppDataUpdate is staged in `state` — another member's or the local account's own. */
|
|
13
|
+
export function stagesComponentUpdate(state, componentId) {
|
|
14
|
+
return Object.values(state.unappliedProposals).some(({ proposal }) => proposal.proposalType === appDataUpdateProposalType && 'appDataUpdate' in proposal && proposal.appDataUpdate.componentId === componentId);
|
|
15
|
+
}
|
|
16
|
+
/** The `send-rejected` of an own commit that would hold a second update of the guarded component. */
|
|
17
|
+
export function stagedComponentUpdateError(guard) {
|
|
18
|
+
return new MarmotError('send-rejected', `${guard.operation}: a ${guard.what} proposal is staged on group ${guard.groupId}; a commit never carries two ${guard.what} updates — commit that proposal first`, {
|
|
19
|
+
details: { groupId: guard.groupId, reason: guard.reason },
|
|
20
|
+
});
|
|
21
|
+
}
|
|
22
|
+
/** Throws {@link stagedComponentUpdateError} when `state` stages the guarded component's update. */
|
|
23
|
+
export function assertNoStagedComponentUpdate(state, guard) {
|
|
24
|
+
if (stagesComponentUpdate(state, guard.componentId))
|
|
25
|
+
throw stagedComponentUpdateError(guard);
|
|
26
|
+
}
|
|
27
|
+
/**
|
|
28
|
+
* `build()` as a build-time engine action: evaluated against the state the commit is built on, it fails when the
|
|
29
|
+
* guarded component's update is staged there — the backstop of the pre-record check for a proposal that arrived
|
|
30
|
+
* after the call was recorded (a record resumed after a reload).
|
|
31
|
+
*/
|
|
32
|
+
export function guardedComponentUpdate(guard, build) {
|
|
33
|
+
return (context) => {
|
|
34
|
+
if (stagesComponentUpdate(context.state, guard.componentId))
|
|
35
|
+
return Promise.reject(stagedComponentUpdateError(guard));
|
|
36
|
+
return Promise.resolve(build());
|
|
37
|
+
};
|
|
38
|
+
}
|
|
39
|
+
/**
|
|
40
|
+
* The AppDataUpdate that sets component `componentId` to `data` (`null`: removes its dictionary entry). The generic form of the
|
|
41
|
+
* typed builders (`groupProfileProposal`, `adminPolicyProposal`): what a commit's internal `components` field and a component
|
|
42
|
+
* change's re-drive are applied with. The bytes are not interpreted here; the engine validates them like any update.
|
|
43
|
+
*/
|
|
44
|
+
export function componentUpdateProposal(componentId, data) {
|
|
45
|
+
return {
|
|
46
|
+
proposalType: appDataUpdateProposalType,
|
|
47
|
+
appDataUpdate: data === null ? { componentId, operation: 'remove' } : { componentId, operation: 'update', update: data },
|
|
48
|
+
};
|
|
49
|
+
}
|
|
50
|
+
/** The guard of an own commit's generic component update (the internal `components` field): a staged update of the same component is refused. */
|
|
51
|
+
export function genericComponentGuard(componentId, groupId) {
|
|
52
|
+
return { componentId, groupId, operation: 'commit', what: `component 0x${componentId.toString(16)}`, reason: 'staged-component-update' };
|
|
53
|
+
}
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The one runner of `extensions.onConfirm` hooks (AC-PIPE-13, AC-MX-1): every site that persists a group state
|
|
3
|
+
* a hook must see — a confirmation (pipeline.ts `confirmRecord`), `groups.create` (`kind: 'create'`) and a
|
|
4
|
+
* Welcome adoption (`kind: 'join'`, group-runtime.ts) — calls it INSIDE the persisting group transaction, so a
|
|
5
|
+
* hook's writes through `tx` commit atomically with the state and a throw rolls the whole transaction back.
|
|
6
|
+
*
|
|
7
|
+
* `ConfirmContext.snapshot` is a lazy, memoized getter: the state is serialized and sealed only when a hook first
|
|
8
|
+
* reads it, so a transaction whose hooks never read it (and every transaction with no hook at all) pays no
|
|
9
|
+
* serialization. The ingest cursor's floor it carries is read once per run, and only when a hook is registered.
|
|
10
|
+
* The getter is readable only while the run's hooks are running — inside the transaction: the state objects it
|
|
11
|
+
* describes belong to the engine afterwards (ts-mls mutates them in place), so a later first read would describe
|
|
12
|
+
* whatever they had become. Read after that, it throws `transaction-closed`, like a settled transaction's views.
|
|
13
|
+
*/
|
|
14
|
+
import type { ClientState } from '@941design/marmot-engine/mls';
|
|
15
|
+
import { type AdmissionLineageRecord, type AppliedNotification } from '../history/index.js';
|
|
16
|
+
import type { RetainedWindow } from '../history/index.js';
|
|
17
|
+
import type { GroupStoreTx } from '../storage/index.js';
|
|
18
|
+
import type { ConfirmHook, ConfirmKind } from './create-client.js';
|
|
19
|
+
import type { ReentrancyGuard } from './reentrancy-guard.js';
|
|
20
|
+
export interface ConfirmHookSite {
|
|
21
|
+
readonly groupId: string;
|
|
22
|
+
readonly guard: ReentrancyGuard;
|
|
23
|
+
/** The registry's live hook list (read once per run, in registration order). */
|
|
24
|
+
readonly hooks: readonly ConfirmHook[];
|
|
25
|
+
}
|
|
26
|
+
/** What the transaction persists: the group state and the rewind window whose tip it is. */
|
|
27
|
+
export interface PersistedGroup {
|
|
28
|
+
readonly state: ClientState;
|
|
29
|
+
readonly window: RetainedWindow;
|
|
30
|
+
}
|
|
31
|
+
export interface ConfirmHookRun {
|
|
32
|
+
readonly intentId: string;
|
|
33
|
+
readonly kind: ConfirmKind;
|
|
34
|
+
/** `ConfirmContext.epoch`: the epoch of the persisted state. */
|
|
35
|
+
readonly epoch: bigint;
|
|
36
|
+
readonly tx: GroupStoreTx;
|
|
37
|
+
/** What the transaction persists — called at most once, on the first `snapshot` read, while the hooks run. */
|
|
38
|
+
readonly persisted: () => PersistedGroup;
|
|
39
|
+
readonly notifications: readonly AppliedNotification[];
|
|
40
|
+
/** The group's account-index `createdAt` (client-clock ms), when known. */
|
|
41
|
+
readonly createdAt: number | undefined;
|
|
42
|
+
/** `ConfirmContext.forgetting` (AC-MX-6): the leaf keys a `devices.forget` commit removes; absent otherwise. */
|
|
43
|
+
readonly forgetting?: {
|
|
44
|
+
readonly leafKeys: readonly string[];
|
|
45
|
+
};
|
|
46
|
+
}
|
|
47
|
+
/** The ingest cursor's floor as the transaction sees it; a missing or unreadable cursor is simply not carried. */
|
|
48
|
+
export declare function cursorFloor(tx: GroupStoreTx): Promise<number | undefined>;
|
|
49
|
+
/**
|
|
50
|
+
* The group's admission lineage as the transaction sees it — what a sealed snapshot carries (epic
|
|
51
|
+
* marmot-invitation-outcomes S4). Unreadable lineage is simply not carried: the restore then reads a gap (fail closed).
|
|
52
|
+
*/
|
|
53
|
+
export declare function snapshotLineage(tx: GroupStoreTx): Promise<readonly AdmissionLineageRecord[]>;
|
|
54
|
+
/** Runs every registered hook, in order, each in the group's `onConfirm` re-entrancy frame. A throw propagates. */
|
|
55
|
+
export declare function runConfirmHooks(site: ConfirmHookSite, run: ConfirmHookRun): Promise<void>;
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
import { ADMISSION_LINEAGE_EXTENSION, readLineageRecords } from '../history/index.js';
|
|
2
|
+
import { MarmotError } from '../shared/index.js';
|
|
3
|
+
import { readIngestCursor } from './group-records.js';
|
|
4
|
+
import { sealGroupSnapshot } from './group-snapshot.js';
|
|
5
|
+
/** The ingest cursor's floor as the transaction sees it; a missing or unreadable cursor is simply not carried. */
|
|
6
|
+
export async function cursorFloor(tx) {
|
|
7
|
+
try {
|
|
8
|
+
return (await readIngestCursor(tx.artifact('ingestCursor')))?.since;
|
|
9
|
+
}
|
|
10
|
+
catch {
|
|
11
|
+
return undefined;
|
|
12
|
+
}
|
|
13
|
+
}
|
|
14
|
+
/**
|
|
15
|
+
* The group's admission lineage as the transaction sees it — what a sealed snapshot carries (epic
|
|
16
|
+
* marmot-invitation-outcomes S4). Unreadable lineage is simply not carried: the restore then reads a gap (fail closed).
|
|
17
|
+
*/
|
|
18
|
+
export async function snapshotLineage(tx) {
|
|
19
|
+
try {
|
|
20
|
+
return await readLineageRecords(tx.extension(ADMISSION_LINEAGE_EXTENSION));
|
|
21
|
+
}
|
|
22
|
+
catch {
|
|
23
|
+
return [];
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
/** Runs every registered hook, in order, each in the group's `onConfirm` re-entrancy frame. A throw propagates. */
|
|
27
|
+
export async function runConfirmHooks(site, run) {
|
|
28
|
+
const hooks = [...site.hooks];
|
|
29
|
+
if (hooks.length === 0)
|
|
30
|
+
return;
|
|
31
|
+
const since = await cursorFloor(run.tx);
|
|
32
|
+
const lineage = await snapshotLineage(run.tx);
|
|
33
|
+
let open = true;
|
|
34
|
+
let sealed;
|
|
35
|
+
const snapshotOf = () => {
|
|
36
|
+
if (sealed !== undefined)
|
|
37
|
+
return sealed;
|
|
38
|
+
if (!open) {
|
|
39
|
+
throw new MarmotError('transaction-closed', 'ConfirmContext.snapshot: read after the confirming transaction\'s hooks returned; read it inside the hook', {
|
|
40
|
+
details: { groupId: site.groupId, intentId: run.intentId },
|
|
41
|
+
});
|
|
42
|
+
}
|
|
43
|
+
const { state, window } = run.persisted();
|
|
44
|
+
sealed = sealGroupSnapshot({
|
|
45
|
+
groupId: site.groupId,
|
|
46
|
+
state,
|
|
47
|
+
window,
|
|
48
|
+
...(run.createdAt === undefined ? {} : { createdAt: run.createdAt }),
|
|
49
|
+
...(since === undefined ? {} : { since }),
|
|
50
|
+
...(lineage.length === 0 ? {} : { lineage }),
|
|
51
|
+
});
|
|
52
|
+
return sealed;
|
|
53
|
+
};
|
|
54
|
+
try {
|
|
55
|
+
for (const hook of hooks) {
|
|
56
|
+
const context = {
|
|
57
|
+
groupId: site.groupId,
|
|
58
|
+
intentId: run.intentId,
|
|
59
|
+
kind: run.kind,
|
|
60
|
+
epoch: run.epoch,
|
|
61
|
+
tx: run.tx,
|
|
62
|
+
notifications: run.notifications,
|
|
63
|
+
get snapshot() {
|
|
64
|
+
return snapshotOf();
|
|
65
|
+
},
|
|
66
|
+
...(run.forgetting === undefined ? {} : { forgetting: { leafKeys: [...run.forgetting.leafKeys] } }),
|
|
67
|
+
};
|
|
68
|
+
await site.guard.call(site.groupId, 'onConfirm', () => hook(context));
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
finally {
|
|
72
|
+
open = false;
|
|
73
|
+
}
|
|
74
|
+
}
|