@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,104 @@
|
|
|
1
|
+
import { type CiphersuiteImpl, type ClientConfig, type ClientState } from '@941design/marmot-engine/mls';
|
|
2
|
+
import { type AdmissionLineageRecord, type RestoredHistory, type RetainedWindow } from '../history/index.js';
|
|
3
|
+
import { type CodecVersions } from '../storage/index.js';
|
|
4
|
+
declare const GROUP_SNAPSHOT_BRAND: unique symbol;
|
|
5
|
+
/**
|
|
6
|
+
* An opaque, branded `Storable` (marmot's versioned envelope: `{ v, engine, tsMls, payload }`) holding what
|
|
7
|
+
* `groups.restore` needs to resume as the leaf it was taken from. Persist it as it is (any ADR-007 store view
|
|
8
|
+
* accepts it); never build or edit one — only `ConfirmContext.snapshot` mints it.
|
|
9
|
+
*
|
|
10
|
+
* NOT ENCRYPTED: `payload` is plain JSON in marmot's envelope and holds live key material — the leaf's signature
|
|
11
|
+
* and path secrets, and the retained past-epoch secrets of the rewind window. A caller MUST encrypt it before
|
|
12
|
+
* anything of it leaves the device (a backup, a relay, any other store not under the device's own protection).
|
|
13
|
+
* `ConfirmContext.snapshot` is readable only while the `onConfirm` hook runs (a first read after it returned throws
|
|
14
|
+
* `transaction-closed`; likewise `BeforePublishContext.snapshot` for the `onBeforePublish` hook); what the hook keeps of it stays plaintext key material until the caller encrypts it.
|
|
15
|
+
*/
|
|
16
|
+
export type GroupSnapshot = {
|
|
17
|
+
readonly v: 1;
|
|
18
|
+
readonly engine: string;
|
|
19
|
+
readonly tsMls: string;
|
|
20
|
+
readonly payload: string;
|
|
21
|
+
} & {
|
|
22
|
+
readonly [GROUP_SNAPSHOT_BRAND]: 'GroupSnapshot';
|
|
23
|
+
};
|
|
24
|
+
/**
|
|
25
|
+
* Payload discriminator of a pending-tagged snapshot (AC-SNAP-1): the state an own commit produces, taken BEFORE a
|
|
26
|
+
* relay accepted that commit. A distinct kind, not a marker on {@link SNAPSHOT_KIND}: a build that predates it (same
|
|
27
|
+
* `engine` and `tsMls` stamps) checks `kind === 'marmot.groupSnapshot'` and refuses this payload `envelope-mismatch`,
|
|
28
|
+
* where an unknown marker on the old kind would be ignored and the tip adopted blindly — a dead branch if no member
|
|
29
|
+
* ever received the commit (AC-SNAP-3, ADR-016 D6).
|
|
30
|
+
*/
|
|
31
|
+
export declare const PENDING_SNAPSHOT_KIND = "marmot.groupSnapshot.pending";
|
|
32
|
+
/**
|
|
33
|
+
* The marker of a pending-tagged snapshot: the commit it depends on. `digest` is the hex SHA-256 of the commit's MLS
|
|
34
|
+
* wire bytes (`commitDigest`) and `parentTag` the hex confirmation tag of the state the commit was built from. It
|
|
35
|
+
* binds to commit BYTES only — never an event id, a `created_at` or an arrival order (ADR-016 determinism), so a
|
|
36
|
+
* re-encrypted copy of the same commit is the same commit.
|
|
37
|
+
*/
|
|
38
|
+
export interface PendingMarker {
|
|
39
|
+
readonly digest: string;
|
|
40
|
+
readonly parentTag: string;
|
|
41
|
+
}
|
|
42
|
+
/** The decoded content of a {@link GroupSnapshot}. */
|
|
43
|
+
export interface GroupSnapshotContent {
|
|
44
|
+
readonly groupId: string;
|
|
45
|
+
readonly state: ClientState;
|
|
46
|
+
/** The account group-index entry's `createdAt` (client-clock ms), when known. */
|
|
47
|
+
readonly createdAt?: number;
|
|
48
|
+
/** The ingest cursor's floor (`IngestCursor.since`, unix seconds), when there is one: after a sync, or from a join (its join floor, owner decision 20). */
|
|
49
|
+
readonly since?: number;
|
|
50
|
+
/**
|
|
51
|
+
* The retained rewind window whose tip is `state` (absent, or a tip-only window: the tip alone). Sealing a
|
|
52
|
+
* window whose tip is not `state` throws (it would be a divergence between a group's persisted state and
|
|
53
|
+
* window — never papered over as a tip-only snapshot), and an opened one that names another tip is malformed.
|
|
54
|
+
*/
|
|
55
|
+
readonly window?: RetainedWindow;
|
|
56
|
+
/**
|
|
57
|
+
* Set only on a pending-tagged snapshot (payload kind {@link PENDING_SNAPSHOT_KIND}): `state` is the result of an
|
|
58
|
+
* own commit no relay is known to hold yet. The window's tip edge IS that commit from `pending.parentTag`, and the
|
|
59
|
+
* parent node carries its serialized state, so a restore that finds the commit unpublished can land at the parent.
|
|
60
|
+
*/
|
|
61
|
+
readonly pending?: PendingMarker;
|
|
62
|
+
/**
|
|
63
|
+
* Epic marmot-invitation-outcomes S4 (SC-4): the group's admission lineage when the snapshot was taken (additive on
|
|
64
|
+
* v1: a snapshot without it opens as before). Opened as well-formed records only; `groups.restore` keeps a record
|
|
65
|
+
* only where the snapshot's own window proves it (`validateRestoredLineage`), every other one restores as a gap.
|
|
66
|
+
*/
|
|
67
|
+
readonly lineage?: readonly AdmissionLineageRecord[];
|
|
68
|
+
}
|
|
69
|
+
/**
|
|
70
|
+
* Seals `content` as a {@link GroupSnapshot} stamped with `versions` (default: this build). Throws
|
|
71
|
+
* `store-failed` (`details.reason: 'window-tip-mismatch'`) when `content.window`'s tip is not `content.state`.
|
|
72
|
+
* That is an internal invariant, never a caller-input fault: marmot itself hands over the state and window a
|
|
73
|
+
* confirmation persists (`ConfirmContext.snapshot`), so a mismatch signals a marmot bug — a divergence of the
|
|
74
|
+
* persisted records — surfaced (the reading `onConfirm` hook throws, so the confirmation is blocked and
|
|
75
|
+
* retried, `confirmBlocked`) rather than dropped to a tip-only snapshot that could not rewind.
|
|
76
|
+
*/
|
|
77
|
+
export declare function sealGroupSnapshot(content: GroupSnapshotContent, versions?: CodecVersions): GroupSnapshot;
|
|
78
|
+
/**
|
|
79
|
+
* Opens a snapshot: the envelope stamp is checked against `versions` BEFORE the payload is decoded
|
|
80
|
+
* (`envelope-mismatch`, `details.reason: 'version'`); a payload that is not a well-formed group snapshot is
|
|
81
|
+
* `envelope-mismatch` with `details.reason: 'malformed'`. Pure — no store, no engine, no transport.
|
|
82
|
+
*
|
|
83
|
+
* Validated in full before anything is returned, because what is returned is adopted as is (`groups.restore`
|
|
84
|
+
* writes it before the engine ever sees it) and a snapshot may come from anywhere the caller kept it — a relay, a
|
|
85
|
+
* backup, another client of the account. Malformed (AC-BAK-10 and the window's ancestry included):
|
|
86
|
+
* - the serialized state's own group id is not the payload's `groupId` (a re-sealed or mislabelled snapshot);
|
|
87
|
+
* - the window ({@link decodeWindow}) is not a tree rooted below its tip within the rollback horizon, every link one
|
|
88
|
+
* epoch (one commit), or a node of it
|
|
89
|
+
* lacks what restoring it needs (its own serialized state — at its epoch, under its tag — its commit from its parent).
|
|
90
|
+
* A node's sender `l` is opened as a well-formed claim only; {@link authenticateWindowSenders} (async: it re-resolves
|
|
91
|
+
* every link) replaces it with the commit's authenticated sender before `groups.restore` adopts anything.
|
|
92
|
+
*/
|
|
93
|
+
export declare function openGroupSnapshot(raw: unknown, versions?: CodecVersions): GroupSnapshotContent;
|
|
94
|
+
export declare function authenticateWindowSenders(content: GroupSnapshotContent, ciphersuite: CiphersuiteImpl, clientConfig?: ClientConfig): Promise<GroupSnapshotContent>;
|
|
95
|
+
/**
|
|
96
|
+
* The engine history (`restoreHistory`) an opened snapshot's window hands the restored engine — built before the
|
|
97
|
+
* adoption writes anything. `undefined` only for a snapshot without a window beyond its tip; a window that names
|
|
98
|
+
* more yet restores to no history (a cut canonical path, a root without its state — anything {@link decodeWindow}
|
|
99
|
+
* let through that `restoreHistory` cannot use) is refused `envelope-mismatch` (`reason: 'malformed'`), never adopted
|
|
100
|
+
* as a window-less state: the restored client would then fence on a competing commit within the window it was
|
|
101
|
+
* handed, instead of rewinding.
|
|
102
|
+
*/
|
|
103
|
+
export declare function snapshotHistory(content: GroupSnapshotContent): RestoredHistory | undefined;
|
|
104
|
+
export {};
|
|
@@ -0,0 +1,474 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `GroupSnapshot` (AC-MX-1/2): everything `groups.restore` needs to resume as one leaf of
|
|
3
|
+
* one group, sealed in the ADR-007 versioned envelope (`storage/envelope.ts`) so a snapshot written by another
|
|
4
|
+
* `marmot-engine` / ts-mls build is refused (`envelope-mismatch`) before its payload is decoded — a snapshot is
|
|
5
|
+
* therefore restorable only by the exact build that took it (carrying a snapshot across builds is left to the
|
|
6
|
+
* consumer that stores it).
|
|
7
|
+
*
|
|
8
|
+
* The payload carries the group id, the serialized `ClientState` (it holds the leaf's signature and path
|
|
9
|
+
* secrets), the account group-index entry's `createdAt` (the pre-join floor ingest applies to undecryptable
|
|
10
|
+
* events), the ingest cursor's floor `since` (the cursor's own floor already sits below every held event, so
|
|
11
|
+
* the restored client's first sync re-fetches every commit after it) and the retained rewind window persisted
|
|
12
|
+
* with that state — the canonical path back to the rollback horizon (`REWIND_HORIZON` commits below the tip),
|
|
13
|
+
* each node's serialized state and commit (an own commit with its convergence stamp), and every fork node
|
|
14
|
+
* hanging off it. The window is what lets the restored client rewind when a competing commit at a parent epoch
|
|
15
|
+
* wins convergence (AC-RACE-1) — a tip-only restore could not, and would fork for good. It holds prior-epoch
|
|
16
|
+
* states, i.e. past secrets, within that horizon: recoverability is chosen over forward secrecy of a backup
|
|
17
|
+
* (forward secrecy is a nice-to-have for this product). The window is bounded exactly as the persisted
|
|
18
|
+
* `rewindTree` artifact is, so a snapshot is at most that horizon's states larger than the tip alone.
|
|
19
|
+
*
|
|
20
|
+
* A snapshot is confirmed (`ConfirmContext.snapshot`, payload kind `marmot.groupSnapshot`) or pending-tagged
|
|
21
|
+
* (`BeforePublishContext.snapshot`, kind `marmot.groupSnapshot.pending`, carrying the own commit it depends on —
|
|
22
|
+
* AC-SNAP-1..3); `openGroupSnapshot` is the single validator of both.
|
|
23
|
+
*
|
|
24
|
+
* The type is opaque and branded: only marmot mints one (`ConfirmContext.snapshot`, `BeforePublishContext.snapshot`); a plain object of the same
|
|
25
|
+
* shape does not type-check as a `GroupSnapshot`, and `openGroupSnapshot` re-validates whatever it is handed.
|
|
26
|
+
*/
|
|
27
|
+
import { deserializeClientState, getGroupIdHex, serializeClientState } from '@941design/marmot-engine/core';
|
|
28
|
+
import { authenticatedSenderOf, resolveCandidateParent } from '@941design/marmot-engine/engine';
|
|
29
|
+
import { acceptAll, nodeTypes, wireformats } from '@941design/marmot-engine/mls';
|
|
30
|
+
import { commitOf, decodeLineageRecord, encodeLineageRecord, linkRestorable, restoreHistory, REWIND_HORIZON, senderOfStored, tagOf, } from '../history/index.js';
|
|
31
|
+
import { isMalformedRowError, MarmotError } from '../shared/index.js';
|
|
32
|
+
import { CURRENT_CODEC_VERSIONS, openEnvelope, sealEnvelope } from '../storage/index.js';
|
|
33
|
+
/** Payload discriminator: an envelope of any other content is not a group snapshot. */
|
|
34
|
+
const SNAPSHOT_KIND = 'marmot.groupSnapshot';
|
|
35
|
+
/**
|
|
36
|
+
* Payload discriminator of a pending-tagged snapshot (AC-SNAP-1): the state an own commit produces, taken BEFORE a
|
|
37
|
+
* relay accepted that commit. A distinct kind, not a marker on {@link SNAPSHOT_KIND}: a build that predates it (same
|
|
38
|
+
* `engine` and `tsMls` stamps) checks `kind === 'marmot.groupSnapshot'` and refuses this payload `envelope-mismatch`,
|
|
39
|
+
* where an unknown marker on the old kind would be ignored and the tip adopted blindly — a dead branch if no member
|
|
40
|
+
* ever received the commit (AC-SNAP-3, ADR-016 D6).
|
|
41
|
+
*/
|
|
42
|
+
export const PENDING_SNAPSHOT_KIND = 'marmot.groupSnapshot.pending';
|
|
43
|
+
/** One window node in the payload (the tip carries no snapshot: `clientState` is it). */
|
|
44
|
+
function encodeNode(node) {
|
|
45
|
+
return {
|
|
46
|
+
t: node.tag,
|
|
47
|
+
e: node.epoch,
|
|
48
|
+
...(node.parentTag === undefined ? {} : { p: node.parentTag }),
|
|
49
|
+
...(node.snapshot === undefined ? {} : { s: node.snapshot }),
|
|
50
|
+
...(node.commit === undefined ? {} : { c: node.commit }),
|
|
51
|
+
...(node.digest === undefined ? {} : { d: node.digest }),
|
|
52
|
+
...(node.sender === undefined ? {} : { l: node.sender }),
|
|
53
|
+
};
|
|
54
|
+
}
|
|
55
|
+
function decodeNode(raw) {
|
|
56
|
+
if (typeof raw !== 'object' || raw === null || raw instanceof Uint8Array || Array.isArray(raw))
|
|
57
|
+
return undefined;
|
|
58
|
+
const r = raw;
|
|
59
|
+
const { t, e, p, s, c, d, l } = r;
|
|
60
|
+
if (typeof t !== 'string' || typeof e !== 'number' || !Number.isSafeInteger(e))
|
|
61
|
+
return undefined;
|
|
62
|
+
if ((p !== undefined && typeof p !== 'string') || (s !== undefined && !(s instanceof Uint8Array)) || (c !== undefined && !(c instanceof Uint8Array)) || (d !== undefined && typeof d !== 'string')) {
|
|
63
|
+
return undefined;
|
|
64
|
+
}
|
|
65
|
+
// The commit's claimed sender (optional: absent on a snapshot taken before it was stored). A snapshot is external
|
|
66
|
+
// input, so a malformed sender refuses the whole snapshot rather than being guessed; a well-formed one is still only
|
|
67
|
+
// a claim, checked against the commit itself before anything is adopted (`authenticateWindowSenders`). The device's
|
|
68
|
+
// own window store (retained-window.ts decodeNode) is lenient and drops a malformed one instead, like its other
|
|
69
|
+
// optional fields — the split is deliberate.
|
|
70
|
+
if (l !== undefined && senderOfStored(l) === undefined)
|
|
71
|
+
return undefined;
|
|
72
|
+
return {
|
|
73
|
+
tag: t,
|
|
74
|
+
epoch: e,
|
|
75
|
+
...(p === undefined ? {} : { parentTag: p }),
|
|
76
|
+
...(s === undefined ? {} : { snapshot: s }),
|
|
77
|
+
...(c === undefined ? {} : { commit: c }),
|
|
78
|
+
...(d === undefined ? {} : { digest: d }),
|
|
79
|
+
...(l === undefined ? {} : { sender: l }),
|
|
80
|
+
};
|
|
81
|
+
}
|
|
82
|
+
/**
|
|
83
|
+
* Seals `content` as a {@link GroupSnapshot} stamped with `versions` (default: this build). Throws
|
|
84
|
+
* `store-failed` (`details.reason: 'window-tip-mismatch'`) when `content.window`'s tip is not `content.state`.
|
|
85
|
+
* That is an internal invariant, never a caller-input fault: marmot itself hands over the state and window a
|
|
86
|
+
* confirmation persists (`ConfirmContext.snapshot`), so a mismatch signals a marmot bug — a divergence of the
|
|
87
|
+
* persisted records — surfaced (the reading `onConfirm` hook throws, so the confirmation is blocked and
|
|
88
|
+
* retried, `confirmBlocked`) rather than dropped to a tip-only snapshot that could not rewind.
|
|
89
|
+
*/
|
|
90
|
+
export function sealGroupSnapshot(content, versions = CURRENT_CODEC_VERSIONS) {
|
|
91
|
+
const payload = {
|
|
92
|
+
kind: content.pending === undefined ? SNAPSHOT_KIND : PENDING_SNAPSHOT_KIND,
|
|
93
|
+
groupId: content.groupId,
|
|
94
|
+
clientState: serializeClientState(content.state),
|
|
95
|
+
};
|
|
96
|
+
if (content.createdAt !== undefined)
|
|
97
|
+
payload['createdAt'] = content.createdAt;
|
|
98
|
+
if (content.since !== undefined)
|
|
99
|
+
payload['since'] = content.since;
|
|
100
|
+
const window = content.window;
|
|
101
|
+
if (window !== undefined && window.tipTag !== tagOf(content.state)) {
|
|
102
|
+
throw new MarmotError('store-failed', `group snapshot: internal invariant broken (a marmot bug) — the window's tip ${window.tipTag} is not the state's ${tagOf(content.state)} (group ${content.groupId})`, {
|
|
103
|
+
details: { groupId: content.groupId, reason: 'window-tip-mismatch' },
|
|
104
|
+
});
|
|
105
|
+
}
|
|
106
|
+
if (content.pending !== undefined) {
|
|
107
|
+
const mismatch = pendingWindowMismatch(window, content.pending);
|
|
108
|
+
if (mismatch !== undefined) {
|
|
109
|
+
throw new MarmotError('store-failed', `group snapshot: internal invariant broken (a marmot bug) — a pending snapshot's window ${mismatch} (group ${content.groupId})`, {
|
|
110
|
+
details: { groupId: content.groupId, reason: 'pending-window-mismatch' },
|
|
111
|
+
});
|
|
112
|
+
}
|
|
113
|
+
payload['pending'] = { digest: content.pending.digest, parentTag: content.pending.parentTag };
|
|
114
|
+
}
|
|
115
|
+
if (window !== undefined && window.nodes.size > 1) {
|
|
116
|
+
// The tip node carries no snapshot of its own (`clientState` is it), exactly as the stored window's tip.
|
|
117
|
+
payload['window'] = { tip: window.tipTag, nodes: [...window.nodes.values()].map(encodeNode) };
|
|
118
|
+
}
|
|
119
|
+
if (content.lineage !== undefined && content.lineage.length > 0)
|
|
120
|
+
payload['lineage'] = content.lineage.map(encodeLineageRecord);
|
|
121
|
+
return sealEnvelope(payload, versions);
|
|
122
|
+
}
|
|
123
|
+
/**
|
|
124
|
+
* Why `window` does not carry the commit `pending` names, or `undefined` when it does: the tip edge is the commit
|
|
125
|
+
* (its digest) from `pending.parentTag`, and that parent node is in the window with its serialized state. The one
|
|
126
|
+
* rule both the sealer (an internal invariant) and the opener (external input) apply.
|
|
127
|
+
*/
|
|
128
|
+
function pendingWindowMismatch(window, pending) {
|
|
129
|
+
if (window === undefined || window.nodes.size <= 1)
|
|
130
|
+
return 'has no parent node (a tip-only window)';
|
|
131
|
+
const tip = window.nodes.get(window.tipTag);
|
|
132
|
+
if (tip === undefined)
|
|
133
|
+
return 'has no tip node';
|
|
134
|
+
if (tip.parentTag !== pending.parentTag)
|
|
135
|
+
return `tip edge comes from ${tip.parentTag ?? 'no node'}, not the marker's parent ${pending.parentTag}`;
|
|
136
|
+
if (tip.digest !== pending.digest)
|
|
137
|
+
return `tip edge commit digest ${tip.digest ?? 'none'} is not the marker's ${pending.digest}`;
|
|
138
|
+
const parent = window.nodes.get(pending.parentTag);
|
|
139
|
+
if (parent === undefined)
|
|
140
|
+
return `lacks the parent node ${pending.parentTag}`;
|
|
141
|
+
if (parent.snapshot === undefined)
|
|
142
|
+
return `parent node ${pending.parentTag} carries no serialized state`;
|
|
143
|
+
return undefined;
|
|
144
|
+
}
|
|
145
|
+
function malformed(message, cause) {
|
|
146
|
+
return new MarmotError('envelope-mismatch', `group snapshot: ${message}`, {
|
|
147
|
+
...(cause === undefined ? {} : { cause }),
|
|
148
|
+
details: { key: 'groupSnapshot', reason: 'malformed' },
|
|
149
|
+
});
|
|
150
|
+
}
|
|
151
|
+
/**
|
|
152
|
+
* Opens a snapshot: the envelope stamp is checked against `versions` BEFORE the payload is decoded
|
|
153
|
+
* (`envelope-mismatch`, `details.reason: 'version'`); a payload that is not a well-formed group snapshot is
|
|
154
|
+
* `envelope-mismatch` with `details.reason: 'malformed'`. Pure — no store, no engine, no transport.
|
|
155
|
+
*
|
|
156
|
+
* Validated in full before anything is returned, because what is returned is adopted as is (`groups.restore`
|
|
157
|
+
* writes it before the engine ever sees it) and a snapshot may come from anywhere the caller kept it — a relay, a
|
|
158
|
+
* backup, another client of the account. Malformed (AC-BAK-10 and the window's ancestry included):
|
|
159
|
+
* - the serialized state's own group id is not the payload's `groupId` (a re-sealed or mislabelled snapshot);
|
|
160
|
+
* - the window ({@link decodeWindow}) is not a tree rooted below its tip within the rollback horizon, every link one
|
|
161
|
+
* epoch (one commit), or a node of it
|
|
162
|
+
* lacks what restoring it needs (its own serialized state — at its epoch, under its tag — its commit from its parent).
|
|
163
|
+
* A node's sender `l` is opened as a well-formed claim only; {@link authenticateWindowSenders} (async: it re-resolves
|
|
164
|
+
* every link) replaces it with the commit's authenticated sender before `groups.restore` adopts anything.
|
|
165
|
+
*/
|
|
166
|
+
export function openGroupSnapshot(raw, versions = CURRENT_CODEC_VERSIONS) {
|
|
167
|
+
const value = openEnvelope('groupSnapshot', raw, versions);
|
|
168
|
+
if (typeof value !== 'object' || value === null || Array.isArray(value) || value instanceof Uint8Array)
|
|
169
|
+
throw malformed('payload is not an object');
|
|
170
|
+
const r = value;
|
|
171
|
+
const kind = r['kind'];
|
|
172
|
+
if (kind !== SNAPSHOT_KIND && kind !== PENDING_SNAPSHOT_KIND)
|
|
173
|
+
throw malformed('payload is not a group snapshot');
|
|
174
|
+
const rawPending = r['pending'];
|
|
175
|
+
const groupId = r['groupId'];
|
|
176
|
+
const bytes = r['clientState'];
|
|
177
|
+
const createdAt = r['createdAt'];
|
|
178
|
+
const since = r['since'];
|
|
179
|
+
if (typeof groupId !== 'string' || groupId.length === 0)
|
|
180
|
+
throw malformed('groupId is missing');
|
|
181
|
+
if (!(bytes instanceof Uint8Array))
|
|
182
|
+
throw malformed('clientState is not bytes');
|
|
183
|
+
if (createdAt !== undefined && (typeof createdAt !== 'number' || !Number.isFinite(createdAt)))
|
|
184
|
+
throw malformed('createdAt is not a number');
|
|
185
|
+
if (since !== undefined && (typeof since !== 'number' || !Number.isFinite(since)))
|
|
186
|
+
throw malformed('since is not a number');
|
|
187
|
+
let state;
|
|
188
|
+
try {
|
|
189
|
+
state = deserializeClientState(bytes);
|
|
190
|
+
}
|
|
191
|
+
catch (error) {
|
|
192
|
+
throw malformed('clientState does not decode', error);
|
|
193
|
+
}
|
|
194
|
+
const stateGroupId = getGroupIdHex(state);
|
|
195
|
+
if (stateGroupId !== groupId)
|
|
196
|
+
throw malformed(`the serialized state is of group ${stateGroupId}, not the payload's ${groupId}`);
|
|
197
|
+
const window = r['window'] === undefined ? undefined : decodeWindow(r['window'], state, groupId);
|
|
198
|
+
const pending = decodePending(kind === PENDING_SNAPSHOT_KIND, rawPending, window);
|
|
199
|
+
const lineage = decodeLineage(r['lineage']);
|
|
200
|
+
return {
|
|
201
|
+
groupId,
|
|
202
|
+
state,
|
|
203
|
+
...(createdAt === undefined ? {} : { createdAt }),
|
|
204
|
+
...(since === undefined ? {} : { since }),
|
|
205
|
+
...(window === undefined ? {} : { window }),
|
|
206
|
+
...(pending === undefined ? {} : { pending }),
|
|
207
|
+
...(lineage === undefined ? {} : { lineage }),
|
|
208
|
+
};
|
|
209
|
+
}
|
|
210
|
+
/** The payload's admission lineage: absent, or a list of well-formed records (anything else is a malformed snapshot). */
|
|
211
|
+
function decodeLineage(raw) {
|
|
212
|
+
if (raw === undefined)
|
|
213
|
+
return undefined;
|
|
214
|
+
if (!Array.isArray(raw))
|
|
215
|
+
throw malformed('lineage is not a list');
|
|
216
|
+
return raw.map((entry, i) => {
|
|
217
|
+
try {
|
|
218
|
+
return decodeLineageRecord(`groupSnapshot.lineage[${i}]`, entry);
|
|
219
|
+
}
|
|
220
|
+
catch (error) {
|
|
221
|
+
if (isMalformedRowError(error))
|
|
222
|
+
throw malformed(`lineage record ${i} is malformed`, error);
|
|
223
|
+
throw error;
|
|
224
|
+
}
|
|
225
|
+
});
|
|
226
|
+
}
|
|
227
|
+
/**
|
|
228
|
+
* The payload's pending marker. A confirmed-kind payload carries none (a `pending` field on it is malformed: it would
|
|
229
|
+
* be a pending claim an older build would not see as one); a pending-kind payload carries a well-formed marker whose
|
|
230
|
+
* commit the window holds — the single validation of a pending snapshot, so `groups.restore` refuses an inconsistent
|
|
231
|
+
* one, a missing parent state included, before anything is written (no restore-time refusal exists).
|
|
232
|
+
*/
|
|
233
|
+
function decodePending(isPendingKind, raw, window) {
|
|
234
|
+
if (!isPendingKind) {
|
|
235
|
+
if (raw !== undefined)
|
|
236
|
+
throw malformed('a confirmed snapshot carries a pending marker');
|
|
237
|
+
return undefined;
|
|
238
|
+
}
|
|
239
|
+
if (typeof raw !== 'object' || raw === null || raw instanceof Uint8Array || Array.isArray(raw))
|
|
240
|
+
throw malformed('a pending snapshot carries no pending marker');
|
|
241
|
+
const { digest, parentTag, ...extra } = raw;
|
|
242
|
+
if (typeof digest !== 'string' || digest.length === 0 || typeof parentTag !== 'string' || parentTag.length === 0 || Object.keys(extra).length > 0) {
|
|
243
|
+
throw malformed('the pending marker is not { digest, parentTag }');
|
|
244
|
+
}
|
|
245
|
+
const marker = { digest, parentTag };
|
|
246
|
+
const mismatch = pendingWindowMismatch(window, marker);
|
|
247
|
+
if (mismatch !== undefined)
|
|
248
|
+
throw malformed(`the pending snapshot's window ${mismatch}`);
|
|
249
|
+
return marker;
|
|
250
|
+
}
|
|
251
|
+
/**
|
|
252
|
+
* The payload's window, accepted only in the shape every persisted window has (`retained-window.ts`, `bounded`):
|
|
253
|
+
* every node well-formed and unique; the tip among them, naming `state` at `state`'s epoch; every parent link
|
|
254
|
+
* resolving to a node of the window exactly one epoch below its node (one commit: an MLS commit advances one epoch, and
|
|
255
|
+
* a fork's sibling commit is one epoch above the same parent) — the window's root, and only a root, carries no link; and no node more than `REWIND_HORIZON` epochs below the tip
|
|
256
|
+
* (a snapshot is restorable only by the build that took it, so the horizon is the one it was bounded by); and exactly
|
|
257
|
+
* one root — every node in the tip's one tree, hanging off its canonical path (`bounded` keeps nothing else). Epochs
|
|
258
|
+
* decreasing by one along every link make the window acyclic: a parent walk from any node ends at a root in at
|
|
259
|
+
* most `REWIND_HORIZON` steps below the tip, never loops (`canonicalPath`, `restoreHistory` walk it after the
|
|
260
|
+
* adoption is written).
|
|
261
|
+
*
|
|
262
|
+
* And every node carries what restoring it needs, exactly as every window marmot writes does (`captureWindow` drops a
|
|
263
|
+
* node without a snapshot and cuts the link of one without a commit; `readWindow` drops a stored node without a
|
|
264
|
+
* snapshot): every node but the tip a serialized state that decodes, of this group, and is the node's own — at the
|
|
265
|
+
* node's epoch `e`, under the node's tag `t` (`tagOf`, the window's node identity); every node with a parent link its
|
|
266
|
+
* commit from that parent — a record that decodes to an MLS message — and that commit's digest. A link without them
|
|
267
|
+
* would open, and `restoreHistory` would then hand the engine no history for the path at all (the canonical path) or
|
|
268
|
+
* silently drop the fork: the restored client could not rewind within the window the snapshot advertises. A node
|
|
269
|
+
* carrying another valid state of the group would open, and the engine history would be built from — and a later
|
|
270
|
+
* fork rewind return to — a state that is not the one the node names.
|
|
271
|
+
* The node states are deserialized here (once more when `restoreHistory` builds the engine's history): at most the
|
|
272
|
+
* horizon's states plus the forks off them — the same bound the window itself has — for a refusal before anything
|
|
273
|
+
* is written instead of a window-less adoption after it.
|
|
274
|
+
*/
|
|
275
|
+
function decodeWindow(raw, state, groupId) {
|
|
276
|
+
if (typeof raw !== 'object' || raw === null || raw instanceof Uint8Array || Array.isArray(raw))
|
|
277
|
+
throw malformed('window is not an object');
|
|
278
|
+
const { tip, nodes: rawNodes } = raw;
|
|
279
|
+
if (typeof tip !== 'string' || !Array.isArray(rawNodes))
|
|
280
|
+
throw malformed('window has no tip or nodes');
|
|
281
|
+
const nodes = new Map();
|
|
282
|
+
for (const entry of rawNodes) {
|
|
283
|
+
const node = decodeNode(entry);
|
|
284
|
+
if (node === undefined || nodes.has(node.tag))
|
|
285
|
+
throw malformed('window node is malformed');
|
|
286
|
+
nodes.set(node.tag, node);
|
|
287
|
+
}
|
|
288
|
+
const tipNode = nodes.get(tip);
|
|
289
|
+
if (tipNode === undefined || tip !== tagOf(state))
|
|
290
|
+
throw malformed('window tip is not the snapshot state');
|
|
291
|
+
if (tipNode.epoch !== Number(state.groupContext.epoch))
|
|
292
|
+
throw malformed('window tip is not at the snapshot state\'s epoch');
|
|
293
|
+
const floor = tipNode.epoch - REWIND_HORIZON;
|
|
294
|
+
for (const node of nodes.values()) {
|
|
295
|
+
if (node.epoch < floor)
|
|
296
|
+
throw malformed(`window node ${node.tag} is below the rollback horizon (epoch ${node.epoch} < ${floor})`);
|
|
297
|
+
if (node.parentTag === undefined)
|
|
298
|
+
continue;
|
|
299
|
+
const parent = nodes.get(node.parentTag);
|
|
300
|
+
if (parent === undefined)
|
|
301
|
+
throw malformed(`window node ${node.tag} names a parent ${node.parentTag} outside the window`);
|
|
302
|
+
// One commit per link: an MLS commit advances its group exactly one epoch, so a parent at any other epoch is no
|
|
303
|
+
// commit's parent — a cycle or same-epoch link (no lower epoch), or a fabricated rewind edge skipping epochs that
|
|
304
|
+
// `restoreHistory` would record the node's commit against. Forks satisfy it too (a sibling commit is one epoch up).
|
|
305
|
+
if (parent.epoch !== node.epoch - 1)
|
|
306
|
+
throw malformed(`window node ${node.tag} (epoch ${node.epoch}) names a parent ${node.parentTag} at epoch ${parent.epoch}, not one epoch below it (a cycle, a broken link or a skipped epoch)`);
|
|
307
|
+
}
|
|
308
|
+
// One tree, the tip's: links strictly descend in epoch and resolve within the window, so every node's parent walk
|
|
309
|
+
// ends at a root — with exactly one root every node reaches it, i.e. hangs off the tip's canonical path. A second
|
|
310
|
+
// root (a lone node, a detached branch, a fork whose link was cut) is history `restoreHistory` would silently drop.
|
|
311
|
+
const roots = [...nodes.values()].filter((node) => node.parentTag === undefined);
|
|
312
|
+
if (roots.length !== 1)
|
|
313
|
+
throw malformed(`window has ${roots.length} roots (${roots.map((node) => node.tag).join(', ')}), not one: a node is not connected to the tip's tree`);
|
|
314
|
+
// The shape is a tree: now what each node needs to be restored (after the shape, so a cycle is reported as one).
|
|
315
|
+
for (const node of nodes.values()) {
|
|
316
|
+
if (node.tag !== tip) {
|
|
317
|
+
if (node.snapshot === undefined)
|
|
318
|
+
throw malformed(`window node ${node.tag} carries no serialized state`);
|
|
319
|
+
let nodeState;
|
|
320
|
+
try {
|
|
321
|
+
nodeState = deserializeClientState(node.snapshot);
|
|
322
|
+
}
|
|
323
|
+
catch (error) {
|
|
324
|
+
throw malformed(`window node ${node.tag}'s serialized state does not decode`, error);
|
|
325
|
+
}
|
|
326
|
+
const nodeGroupId = getGroupIdHex(nodeState);
|
|
327
|
+
if (nodeGroupId !== groupId)
|
|
328
|
+
throw malformed(`window node ${node.tag}'s serialized state is of group ${nodeGroupId}, not ${groupId}`);
|
|
329
|
+
// The node's own state, not another valid one of the group: `restoreHistory` keys the engine history by the
|
|
330
|
+
// node's tag and rewinds to the state it carries.
|
|
331
|
+
const nodeEpoch = Number(nodeState.groupContext.epoch);
|
|
332
|
+
if (nodeEpoch !== node.epoch)
|
|
333
|
+
throw malformed(`window node ${node.tag}'s serialized state is at epoch ${nodeEpoch}, not the node's own ${node.epoch}`);
|
|
334
|
+
const nodeTag = tagOf(nodeState);
|
|
335
|
+
if (nodeTag !== node.tag)
|
|
336
|
+
throw malformed(`window node ${node.tag}'s serialized state is ${nodeTag}, not the node's own`);
|
|
337
|
+
}
|
|
338
|
+
if (node.parentTag !== undefined && !linkRestorable(node))
|
|
339
|
+
throw malformed(`window node ${node.tag} carries no decodable commit (with its digest) from its parent ${node.parentTag}`);
|
|
340
|
+
}
|
|
341
|
+
return { tipTag: tip, nodes };
|
|
342
|
+
}
|
|
343
|
+
/**
|
|
344
|
+
* An opened snapshot whose window carries, at every link, the commit's authenticated sender re-derived at its parent —
|
|
345
|
+
* never the stored `l` it was handed (ADR-016 D4a framing independence). A snapshot is attacker-influenceable input
|
|
346
|
+
* (an account-sync leaf backup is writable by any holder of the sync key, a forgotten device included), and the
|
|
347
|
+
* restored engine's history-tree edges take their sender from the window (`restoreHistory`): a trusted `l` naming
|
|
348
|
+
* another leaf for a commit would move equivocation credit and the canonical branch. Each link's commit is resolved
|
|
349
|
+
* against its parent node's state exactly as the engine re-resolves a held removal (`resolveCandidateParent`, sender
|
|
350
|
+
* via `authenticatedSenderOf`):
|
|
351
|
+
* - resolved: the processing result's sender — read from the verified framing of a `PublicMessage` and from the
|
|
352
|
+
* decrypted sender data of a `PrivateMessage` alike;
|
|
353
|
+
* - fenced (ts-mls "No overlap": the framing verified at the parent, and the commit's `UpdatePath` encrypts to no
|
|
354
|
+
* key the parent holds — an `UpdatePath` never encrypts to its committer, so this is the restoring leaf's own
|
|
355
|
+
* commit, or its stale clone's): a `PublicMessage`'s verified framing sender; a `PrivateMessage`'s, whose sender
|
|
356
|
+
* data cannot be read back from the failure, the parent's own leaf;
|
|
357
|
+
* - not resolved (any other refusal): a `PrivateMessage` link keeps no sender (no credit, no evidence — what a held
|
|
358
|
+
* removal whose replay fails gets, ADR-016 AR-9 iii: a later-consumed generation can fail a genuine replay); a
|
|
359
|
+
* `PublicMessage` link is refused, since its framing — the restore's fallback — would be unauthenticated.
|
|
360
|
+
* A stored `l` that disagrees with the derived sender (or names one where none resolves to a member) refuses the
|
|
361
|
+
* snapshot `envelope-mismatch` (`reason: 'malformed'`): it was altered, and a mismatch is never papered over. A
|
|
362
|
+
* window without `l` (sealed before senders were stored, ADR-016 AR-7) gains its authenticated senders here. What is
|
|
363
|
+
* returned — and written to the device's own window store by `groups.restore` — holds only derived senders, so the
|
|
364
|
+
* local store's lenient decoder never reads an imported claim back.
|
|
365
|
+
*/
|
|
366
|
+
/** A fixed HPKE probe: the `info` and plaintext of the key-consistency check below (no secret, no protocol use). */
|
|
367
|
+
const KEY_PROBE_INFO = new TextEncoder().encode('marmot window privatePath probe');
|
|
368
|
+
const KEY_PROBE = new Uint8Array([0x6d, 0x61, 0x72, 0x6d, 0x6f, 0x74]);
|
|
369
|
+
/**
|
|
370
|
+
* marmot-imported-window-state-authentication (default part; ADR-016 AR-13): whether `state.privatePath` holds the
|
|
371
|
+
* private key of its own leaf's encryption key in `state.ratchetTree` — the leaf at `privatePath.leafIndex` occupied,
|
|
372
|
+
* and an HPKE seal to that leaf's `hpkePublicKey` opening with the path's private key at the leaf's node index. The
|
|
373
|
+
* fenced PrivateMessage rule of {@link authenticateWindowSenders} attributes a link to its parent state's
|
|
374
|
+
* `privatePath.leafIndex`, so a forged path (its leaf index redirected to another member's leaf, or its leaf key
|
|
375
|
+
* replaced) would redirect that attribution; passing this check needs that leaf's private key. Corrupted epoch
|
|
376
|
+
* secrets are not detected here (only re-applying each stored commit could tell; the finding's open question).
|
|
377
|
+
*/
|
|
378
|
+
async function privatePathMatchesTree(state, ciphersuite) {
|
|
379
|
+
const leafIndex = Number(state.privatePath.leafIndex);
|
|
380
|
+
const nodeIndex = 2 * leafIndex;
|
|
381
|
+
const node = state.ratchetTree[nodeIndex];
|
|
382
|
+
const privateKey = state.privatePath.privateKeys[nodeIndex];
|
|
383
|
+
if (node === undefined || node.nodeType !== nodeTypes.leaf || privateKey === undefined)
|
|
384
|
+
return false;
|
|
385
|
+
try {
|
|
386
|
+
const publicKey = await ciphersuite.hpke.importPublicKey(node.leaf.hpkePublicKey);
|
|
387
|
+
const sealed = await ciphersuite.hpke.seal(publicKey, KEY_PROBE, KEY_PROBE_INFO);
|
|
388
|
+
const opened = await ciphersuite.hpke.open(await ciphersuite.hpke.importPrivateKey(privateKey), sealed.enc, sealed.ct, KEY_PROBE_INFO);
|
|
389
|
+
return opened.length === KEY_PROBE.length && opened.every((byte, i) => byte === KEY_PROBE[i]);
|
|
390
|
+
}
|
|
391
|
+
catch {
|
|
392
|
+
return false;
|
|
393
|
+
}
|
|
394
|
+
}
|
|
395
|
+
export async function authenticateWindowSenders(content, ciphersuite, clientConfig) {
|
|
396
|
+
const window = content.window;
|
|
397
|
+
if (window === undefined || window.nodes.size <= 1)
|
|
398
|
+
return content;
|
|
399
|
+
// Every window state's own key path first (the tip's is the snapshot state): a link's fenced attribution below reads
|
|
400
|
+
// its parent's `privatePath.leafIndex`, which must be the leaf whose private key the path actually holds.
|
|
401
|
+
for (const node of window.nodes.values()) {
|
|
402
|
+
const state = node.tag === window.tipTag ? content.state : deserializeClientState(node.snapshot);
|
|
403
|
+
if (!(await privatePathMatchesTree(state, ciphersuite))) {
|
|
404
|
+
throw malformed(`window node ${node.tag}'s privatePath does not hold the private key of its own leaf (${Number(state.privatePath.leafIndex)}) in its ratchet tree`);
|
|
405
|
+
}
|
|
406
|
+
}
|
|
407
|
+
const nodes = new Map();
|
|
408
|
+
for (const node of window.nodes.values()) {
|
|
409
|
+
const parentNode = node.parentTag === undefined ? undefined : window.nodes.get(node.parentTag);
|
|
410
|
+
const commit = commitOf(node);
|
|
411
|
+
if (parentNode === undefined || commit === undefined) {
|
|
412
|
+
if (node.sender !== undefined)
|
|
413
|
+
throw malformed(`window node ${node.tag} names a sender for no commit`);
|
|
414
|
+
nodes.set(node.tag, node);
|
|
415
|
+
continue;
|
|
416
|
+
}
|
|
417
|
+
const message = commit.message;
|
|
418
|
+
if (message.wireformat !== wireformats.mls_public_message && message.wireformat !== wireformats.mls_private_message) {
|
|
419
|
+
throw malformed(`window node ${node.tag}'s link is no framed commit`);
|
|
420
|
+
}
|
|
421
|
+
// A fresh copy per resolution: ts-mls mutates some state in place, and the window's own bytes stay untouched.
|
|
422
|
+
const parent = parentNode.tag === window.tipTag ? deserializeClientState(serializeClientState(content.state)) : deserializeClientState(parentNode.snapshot);
|
|
423
|
+
const resolution = await resolveCandidateParent({
|
|
424
|
+
ciphersuite,
|
|
425
|
+
...(clientConfig === undefined ? {} : { clientConfig }),
|
|
426
|
+
parent,
|
|
427
|
+
message: message,
|
|
428
|
+
callback: acceptAll,
|
|
429
|
+
});
|
|
430
|
+
const isPublic = message.wireformat === wireformats.mls_public_message;
|
|
431
|
+
let derived;
|
|
432
|
+
if (resolution.kind === 'resolved')
|
|
433
|
+
derived = authenticatedSenderOf(resolution.result, message);
|
|
434
|
+
else if (resolution.kind === 'fenced')
|
|
435
|
+
derived = isPublic ? authenticatedSenderOf(undefined, message) : Number(parent.privatePath.leafIndex);
|
|
436
|
+
else if (isPublic)
|
|
437
|
+
throw malformed(`window node ${node.tag}'s commit does not authenticate at its parent ${parentNode.tag} (${resolution.kind})`);
|
|
438
|
+
else {
|
|
439
|
+
// Unresolvable PrivateMessage: no sender can be derived, and the claim is not evidence of one.
|
|
440
|
+
const { sender: _claimed, ...rest } = node;
|
|
441
|
+
nodes.set(node.tag, rest);
|
|
442
|
+
continue;
|
|
443
|
+
}
|
|
444
|
+
if (node.sender !== undefined && node.sender !== derived) {
|
|
445
|
+
throw malformed(`window node ${node.tag} names sender ${node.sender}, but its commit's authenticated sender at ${parentNode.tag} is ${derived ?? 'no member'}`);
|
|
446
|
+
}
|
|
447
|
+
const { sender: _claimed, ...rest } = node;
|
|
448
|
+
nodes.set(node.tag, derived === undefined ? rest : { ...rest, sender: derived });
|
|
449
|
+
}
|
|
450
|
+
return { ...content, window: { tipTag: window.tipTag, nodes } };
|
|
451
|
+
}
|
|
452
|
+
/**
|
|
453
|
+
* The engine history (`restoreHistory`) an opened snapshot's window hands the restored engine — built before the
|
|
454
|
+
* adoption writes anything. `undefined` only for a snapshot without a window beyond its tip; a window that names
|
|
455
|
+
* more yet restores to no history (a cut canonical path, a root without its state — anything {@link decodeWindow}
|
|
456
|
+
* let through that `restoreHistory` cannot use) is refused `envelope-mismatch` (`reason: 'malformed'`), never adopted
|
|
457
|
+
* as a window-less state: the restored client would then fence on a competing commit within the window it was
|
|
458
|
+
* handed, instead of rewinding.
|
|
459
|
+
*/
|
|
460
|
+
export function snapshotHistory(content) {
|
|
461
|
+
const window = content.window;
|
|
462
|
+
if (window === undefined || window.nodes.size <= 1)
|
|
463
|
+
return undefined;
|
|
464
|
+
let history;
|
|
465
|
+
try {
|
|
466
|
+
history = restoreHistory(window, content.state);
|
|
467
|
+
}
|
|
468
|
+
catch (error) {
|
|
469
|
+
throw malformed('the rewind window does not restore', error);
|
|
470
|
+
}
|
|
471
|
+
if (history === undefined)
|
|
472
|
+
throw malformed('the rewind window restores no history');
|
|
473
|
+
return history;
|
|
474
|
+
}
|