@kumiai/mls 0.10.5 → 0.10.6
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/README.md +17 -9
- package/lib/codec.d.ts +9 -2
- package/lib/codec.js +31 -17
- package/lib/errors.d.ts +10 -0
- package/lib/errors.js +18 -0
- package/lib/group-commit.d.ts +7 -4
- package/lib/group-commit.js +7 -4
- package/lib/group-handle.d.ts +17 -6
- package/lib/group-handle.js +154 -28
- package/lib/index.d.ts +1 -1
- package/lib/index.js +1 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -2,6 +2,16 @@
|
|
|
2
2
|
|
|
3
3
|
Credential-aware MLS (RFC 9420) group lifecycle for enkaku. Wraps [`ts-mls`](https://github.com/LukaJCB/ts-mls) with DID-based identity and a signed control ledger, giving every member a `MemberCredential` that ties their MLS leaf to their DID, and a group-wide roster that decides who may add, remove, and rotate.
|
|
4
4
|
|
|
5
|
+
## Publishing commits directly
|
|
6
|
+
|
|
7
|
+
Commit builders return a derived handle without advancing the source handle's epoch.
|
|
8
|
+
Call `group.reserveHandshakeGeneration(persist)` before each build.
|
|
9
|
+
After the build returns, call `group.consumeHandshakeReservation(persist)` before any journalling or publication.
|
|
10
|
+
Reserve alone reuses an unconsumed generation, including after restart.
|
|
11
|
+
Serialise reserve, build and consume against the source handle. Adopt the derived handle only after acceptance.
|
|
12
|
+
Persistence must complete durably and leave storage unchanged on rejection.
|
|
13
|
+
The `@kumiai/mls-rpc` adapter supplies both reservation hooks to the RPC peer.
|
|
14
|
+
|
|
5
15
|
## Capabilities
|
|
6
16
|
|
|
7
17
|
- `createGroup` — creator opens a new group as its sole member and first admin
|
|
@@ -41,11 +51,10 @@ may be held while awaiting a handle or peer operation. The real `@kumiai/mls-rpc
|
|
|
41
51
|
## Authority model
|
|
42
52
|
|
|
43
53
|
Authority is a **roster**, folded from a signed **control ledger** and rooted at a genesis anchor installed in the GroupContext when the group is created. There is no capability chain: a member's right to act is decided by the roster every peer computes independently, not by a token the member carries.
|
|
44
|
-
|
|
45
54
|
- **The ledger is an ordered log of enactments.** Each entry is a token signed by its issuer (a `kumiai.role` entry names a subject DID and grants it `admin` or `member` of the group). The log is replayable and position-dependent: the same claim recurring later is meaningful — a demotion back to a previously-held role is exactly that.
|
|
46
|
-
- **The roster is the fold.** `foldRoster` applies each entry only if its issuer was an admin
|
|
55
|
+
- **The roster is the fold.** `foldRoster` applies each entry only if its issuer was an admin _in the state so far, at that entry's own position_. A token signed by a since-demoted admin is dead paper whoever carries it. The fold starts from the anchor (`{creator: 'admin'}`), so no one can promote themselves by padding an invite.
|
|
47
56
|
- **Enactment is admin-only, structurally.** Entries reach the group inside a commit, and a commit that enacts entries must extend the GroupContext ledger-head extension by exactly those ids, in order. Moving the head needs a `group_context_extensions` proposal, which needs admin. A plain member's only permitted proposal is `update`; attaching an envelope to it fails for want of a head move. The write path runs the receivers' own fold before authoring, so it never builds a commit the group would reject.
|
|
48
|
-
- **`GroupPermission` is `'admin' | 'member'` — there is no read-only tier.** It cannot exist: a group member holds the epoch secrets, which is what membership
|
|
57
|
+
- **`GroupPermission` is `'admin' | 'member'` — there is no read-only tier.** It cannot exist: a group member holds the epoch secrets, which is what membership _is_ in MLS. A `read` member derives the same application keys as any other member and can decrypt everything. Read-only observers do not belong in the group; gate them outside MLS, at the transport or storage layer.
|
|
49
58
|
|
|
50
59
|
The invite carries the full ordered ledger plus the invitee's new role entry last, so a joiner folds the same roster the group holds and cannot fork from a role change made before it joined.
|
|
51
60
|
|
|
@@ -64,9 +73,9 @@ const { groupInfo } = await exportGroupInfo({ group: aliceGroup })
|
|
|
64
73
|
// On the stale device:
|
|
65
74
|
import { joinGroupExternal } from '@kumiai/mls'
|
|
66
75
|
const { commitMessage, group } = await joinGroupExternal({
|
|
67
|
-
identity: bob,
|
|
68
|
-
groupInfo,
|
|
69
|
-
credential: bobStoredCredential,
|
|
76
|
+
identity: bob, // OwnIdentity from @kokuin/token
|
|
77
|
+
groupInfo, // bytes received from the healthy member
|
|
78
|
+
credential: bobStoredCredential, // cached from the original processWelcome
|
|
70
79
|
resync: true,
|
|
71
80
|
})
|
|
72
81
|
// Broadcast commitMessage (Uint8Array) to the other members; each decodes and calls
|
|
@@ -93,8 +102,7 @@ An external commit is enforced as a **resync of an existing roster member**, nev
|
|
|
93
102
|
|
|
94
103
|
### ⚠️ Security: removal is not revocation
|
|
95
104
|
|
|
96
|
-
MLS has no cryptographic member revocation. `removeMember` evicts a leaf; it does not erase the removed DID's `kumiai.role` grant — its role in the group — which lives in the roster independently of MLS membership. So a device that retains its `MemberCredential` can rejoin via `joinGroupExternal` **even after being removed** — its DID is still a roster member, so the external-commit policy admits the resync — provided it can still obtain a fresh `GroupInfo`. (The policy stops
|
|
97
|
-
|
|
105
|
+
MLS has no cryptographic member revocation. `removeMember` evicts a leaf; it does not erase the removed DID's `kumiai.role` grant — its role in the group — which lives in the roster independently of MLS membership. So a device that retains its `MemberCredential` can rejoin via `joinGroupExternal` **even after being removed** — its DID is still a roster member, so the external-commit policy admits the resync — provided it can still obtain a fresh `GroupInfo`. (The policy stops _strangers_, who are in no roster; it does not stop a removed member.) Consumers must assume a removed member can rejoin until role revocation lands in a follow-up spec. Mitigations available today:
|
|
98
106
|
- Rotate the group: create a new group, migrate non-removed members via fresh invites, abandon the old group.
|
|
99
107
|
- Enforce access control outside MLS: block the removed device at the transport layer (e.g. hub auth).
|
|
100
108
|
|
|
@@ -106,6 +114,6 @@ The follow-up revocation work will introduce a ledger entry that removes a DID's
|
|
|
106
114
|
|
|
107
115
|
### ⚠️ Security: rotate the last-resort bundle before it expires
|
|
108
116
|
|
|
109
|
-
A last-resort key package carries an MLS lifetime of `LAST_RESORT_LIFETIME_DAYS` (90). The inviter validates that lifetime when building the Add, so an expired package is refused at the far end with `Current time not within Lifetime` — and refused
|
|
117
|
+
A last-resort key package carries an MLS lifetime of `LAST_RESORT_LIFETIME_DAYS` (90). The inviter validates that lifetime when building the Add, so an expired package is refused at the far end with `Current time not within Lifetime` — and refused _no matter what the hub does_, because the hub stores opaque bytes and cannot see the expiry.
|
|
110
118
|
|
|
111
119
|
That makes the failure worse than an empty slot: the hub goes on reporting the slot as full and serving the dead package, so the availability floor looks healthy while every join through it fails. A host must generate and upload a fresh last-resort bundle before the window elapses, and keep the new private half. Uploading once at enrolment buys 90 days, not forever.
|
package/lib/codec.d.ts
CHANGED
|
@@ -1,5 +1,12 @@
|
|
|
1
|
-
import { type ClientState, type RatchetTree } from 'ts-mls';
|
|
2
|
-
|
|
1
|
+
import { type ClientState as MLSClientState, type RatchetTree } from 'ts-mls';
|
|
2
|
+
/** Local reservation evidence travels with every durable MLS checkpoint. */
|
|
3
|
+
export type ClientState = MLSClientState & {
|
|
4
|
+
handshakeReservation?: {
|
|
5
|
+
epoch: bigint;
|
|
6
|
+
generation: number;
|
|
7
|
+
consumed: boolean;
|
|
8
|
+
};
|
|
9
|
+
};
|
|
3
10
|
export declare function decodeClientState(encoded: Uint8Array): ClientState | undefined;
|
|
4
11
|
export declare function encodeClientState(state: ClientState): Uint8Array;
|
|
5
12
|
export declare function sanitizeRatchetTree(tree: ReadonlyArray<unknown>): RatchetTree;
|
package/lib/codec.js
CHANGED
|
@@ -1,17 +1,11 @@
|
|
|
1
1
|
import { clientStateDecoder, clientStateEncoder, decode, encode } from 'ts-mls';
|
|
2
|
-
/**
|
|
3
|
-
*
|
|
4
|
-
*
|
|
5
|
-
*
|
|
6
|
-
* are one process serializing its own state to itself (to disk, to storage, wherever), never a
|
|
7
|
-
* wire format another peer or another build reads. So there is no peer to stay compatible with —
|
|
8
|
-
* an unknown version is refused outright, not migrated.
|
|
9
|
-
*
|
|
10
|
-
* It buys diagnosis, not compatibility. There is no version of this a v1 build can read, and a
|
|
11
|
-
* format change is a flag day whatever this byte says. What it changes is that the failure reads
|
|
12
|
-
* as "this blob is v2 and I speak v1" rather than an opaque decode failure indistinguishable from
|
|
13
|
-
* truncated bytes or a corrupted store.
|
|
2
|
+
/** v1 stores bare ts-mls state. v3 prefixes epoch (uint64), generation (uint32),
|
|
3
|
+
* and consumed (uint8) before that state. v1 has no evidence permitting reuse.
|
|
4
|
+
* v2 belongs to an incompatible layout and is refused, as are unknown versions.
|
|
5
|
+
* Older readers refuse v3.
|
|
14
6
|
*/ const CLIENT_STATE_VERSION = 1;
|
|
7
|
+
const RESERVATION_STATE_VERSION = 3;
|
|
8
|
+
const RESERVATION_BYTES = 13;
|
|
15
9
|
export function decodeClientState(encoded) {
|
|
16
10
|
// Too short to hold the version byte is a TRUNCATED read, not a version this build does not
|
|
17
11
|
// speak, and the two are separate diagnoses — the same split `@kumiai/mls-rpc`'s `openEntries`
|
|
@@ -26,17 +20,37 @@ export function decodeClientState(encoded) {
|
|
|
26
20
|
// byte is not that kind of failure, so it throws instead of returning the same `undefined`
|
|
27
21
|
// a decode failure would. Without this, a version mismatch and a corrupted store are the
|
|
28
22
|
// same value of the same type and a caller cannot tell them apart.
|
|
29
|
-
if (encoded[0] !== CLIENT_STATE_VERSION) {
|
|
23
|
+
if (encoded[0] !== CLIENT_STATE_VERSION && encoded[0] !== RESERVATION_STATE_VERSION) {
|
|
30
24
|
throw new Error(`decodeClientState: unsupported client-state version ${encoded[0]}`);
|
|
31
25
|
}
|
|
32
26
|
// A copy: ts-mls decodes secrets as views, and ratcheting zeroes consumed ones in place.
|
|
33
|
-
return decode(clientStateDecoder, encoded.slice(1));
|
|
27
|
+
if (encoded[0] === CLIENT_STATE_VERSION) return decode(clientStateDecoder, encoded.slice(1));
|
|
28
|
+
if (encoded.length < 1 + RESERVATION_BYTES || encoded[13] !== 0 && encoded[13] !== 1) return undefined;
|
|
29
|
+
const view = new DataView(encoded.buffer, encoded.byteOffset, encoded.byteLength);
|
|
30
|
+
const state = decode(clientStateDecoder, encoded.slice(1 + RESERVATION_BYTES));
|
|
31
|
+
if (state == null) return undefined;
|
|
32
|
+
return {
|
|
33
|
+
...state,
|
|
34
|
+
handshakeReservation: {
|
|
35
|
+
epoch: view.getBigUint64(1),
|
|
36
|
+
generation: view.getUint32(9),
|
|
37
|
+
consumed: encoded[13] === 1
|
|
38
|
+
}
|
|
39
|
+
};
|
|
34
40
|
}
|
|
35
41
|
export function encodeClientState(state) {
|
|
36
42
|
const body = encode(clientStateEncoder, state);
|
|
37
|
-
const
|
|
38
|
-
|
|
39
|
-
out
|
|
43
|
+
const reservation = state.handshakeReservation;
|
|
44
|
+
const header = reservation == null ? 1 : 1 + RESERVATION_BYTES;
|
|
45
|
+
const out = new Uint8Array(header + body.length);
|
|
46
|
+
out[0] = reservation == null ? CLIENT_STATE_VERSION : RESERVATION_STATE_VERSION;
|
|
47
|
+
if (reservation != null) {
|
|
48
|
+
const view = new DataView(out.buffer);
|
|
49
|
+
view.setBigUint64(1, reservation.epoch);
|
|
50
|
+
view.setUint32(9, reservation.generation);
|
|
51
|
+
out[13] = reservation.consumed ? 1 : 0;
|
|
52
|
+
}
|
|
53
|
+
out.set(body, header);
|
|
40
54
|
return out;
|
|
41
55
|
}
|
|
42
56
|
export function sanitizeRatchetTree(tree) {
|
package/lib/errors.d.ts
CHANGED
|
@@ -16,3 +16,13 @@ export declare class RevokeProofError extends Error {
|
|
|
16
16
|
constructor(reason: RevokeProofReason);
|
|
17
17
|
get reason(): RevokeProofReason;
|
|
18
18
|
}
|
|
19
|
+
/** The sender must wait for an epoch advance before building another private commit. */
|
|
20
|
+
export declare class HandshakeWindowError extends Error {
|
|
21
|
+
constructor();
|
|
22
|
+
}
|
|
23
|
+
export declare class HandshakeWindowConfigError extends Error {
|
|
24
|
+
constructor();
|
|
25
|
+
}
|
|
26
|
+
export declare class HandshakeReservationError extends Error {
|
|
27
|
+
constructor();
|
|
28
|
+
}
|
package/lib/errors.js
CHANGED
|
@@ -31,3 +31,21 @@ export class RevokeProofError extends Error {
|
|
|
31
31
|
return this.#reason;
|
|
32
32
|
}
|
|
33
33
|
}
|
|
34
|
+
/** The sender must wait for an epoch advance before building another private commit. */ export class HandshakeWindowError extends Error {
|
|
35
|
+
constructor(){
|
|
36
|
+
super('Handshake sender generation reached the safe receiver window for this epoch');
|
|
37
|
+
this.name = 'HandshakeWindowError';
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
export class HandshakeWindowConfigError extends Error {
|
|
41
|
+
constructor(){
|
|
42
|
+
super('Handshake receiver window must be at least 2');
|
|
43
|
+
this.name = 'HandshakeWindowConfigError';
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
export class HandshakeReservationError extends Error {
|
|
47
|
+
constructor(){
|
|
48
|
+
super('No matching handshake reservation for the current epoch and generation');
|
|
49
|
+
this.name = 'HandshakeReservationError';
|
|
50
|
+
}
|
|
51
|
+
}
|
package/lib/group-commit.d.ts
CHANGED
|
@@ -84,10 +84,13 @@ export type CommitLedgerEntriesResult = {
|
|
|
84
84
|
* empty `tokens` list.
|
|
85
85
|
*
|
|
86
86
|
* Reads `group` and returns a NEW derived handle (`newGroup`); it never advances
|
|
87
|
-
* `group
|
|
88
|
-
*
|
|
89
|
-
*
|
|
90
|
-
*
|
|
87
|
+
* `group`'s epoch. Adopt `newGroup` only after publication is accepted.
|
|
88
|
+
* Before each build, call `group.reserveHandshakeGeneration(persist)`.
|
|
89
|
+
* After the build returns, call `group.consumeHandshakeReservation(persist)` before
|
|
90
|
+
* any journalling or publication. Reserve alone reuses an unconsumed generation.
|
|
91
|
+
* Serialise reserve, build and consume against the source handle.
|
|
92
|
+
* The mutex only serializes concurrent calls against one handle. A source whose commit
|
|
93
|
+
* was accepted is superseded and must never be reused.
|
|
91
94
|
*/
|
|
92
95
|
export declare function commitLedgerEntries(group: GroupHandle, tokens: Array<string>): Promise<CommitLedgerEntriesResult>;
|
|
93
96
|
export type CommitInviteResult = {
|
package/lib/group-commit.js
CHANGED
|
@@ -270,10 +270,13 @@ import { ROLE_ENTRY_TYPE } from './roster.js';
|
|
|
270
270
|
* empty `tokens` list.
|
|
271
271
|
*
|
|
272
272
|
* Reads `group` and returns a NEW derived handle (`newGroup`); it never advances
|
|
273
|
-
* `group
|
|
274
|
-
*
|
|
275
|
-
*
|
|
276
|
-
*
|
|
273
|
+
* `group`'s epoch. Adopt `newGroup` only after publication is accepted.
|
|
274
|
+
* Before each build, call `group.reserveHandshakeGeneration(persist)`.
|
|
275
|
+
* After the build returns, call `group.consumeHandshakeReservation(persist)` before
|
|
276
|
+
* any journalling or publication. Reserve alone reuses an unconsumed generation.
|
|
277
|
+
* Serialise reserve, build and consume against the source handle.
|
|
278
|
+
* The mutex only serializes concurrent calls against one handle. A source whose commit
|
|
279
|
+
* was accepted is superseded and must never be reused.
|
|
277
280
|
*/ export async function commitLedgerEntries(group, tokens) {
|
|
278
281
|
return mutexFor(group).run(async ()=>{
|
|
279
282
|
if (tokens.length === 0) {
|
package/lib/group-handle.d.ts
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { EventEmitter, type EventsSource } from '@sozai/event';
|
|
2
|
-
import { type
|
|
2
|
+
import { type IncomingMessageCallback, type MlsContext, type MlsFramedMessage, type ProposalWithSender } from 'ts-mls';
|
|
3
3
|
import { type GroupAnchor } from './anchor.js';
|
|
4
|
+
import { type ClientState } from './codec.js';
|
|
4
5
|
import { type GroupMember, type MemberCredential } from './credential.js';
|
|
5
6
|
import { type LeafBinding } from './device-proof.js';
|
|
6
7
|
import { type VerifiedLedgerEntry } from './ledger.js';
|
|
@@ -104,9 +105,8 @@ export declare class GroupHandle {
|
|
|
104
105
|
get ledger(): ReadonlyArray<LedgerLogEntry>;
|
|
105
106
|
/** The ordered signed tokens this handle holds, repeats included — the ledger's
|
|
106
107
|
* canonical persistent/wire form, and the list the authenticated head folds over.
|
|
107
|
-
* Feeds createInvite, restoreGroup, and host persistence.
|
|
108
|
-
*
|
|
109
|
-
* which re-verifies. */
|
|
108
|
+
* Feeds createInvite, restoreGroup, and host persistence. In-process clones inherit
|
|
109
|
+
* verification through the returned array; serialised tokens must verify afresh. */
|
|
110
110
|
get ledgerTokens(): Array<string>;
|
|
111
111
|
/** The control roster folded from the anchor and every applied ledger entry. */
|
|
112
112
|
get roster(): RosterState;
|
|
@@ -142,8 +142,8 @@ export declare class GroupHandle {
|
|
|
142
142
|
* Verify signed ledger tokens, append the valid ones in the order given, and
|
|
143
143
|
* refold the roster. Tokens that fail verification or whose groupID mismatches are
|
|
144
144
|
* dropped (defensive — the strict admin-issuer enforcement is the commit pre-pass).
|
|
145
|
-
*
|
|
146
|
-
*
|
|
145
|
+
* Exact token bytes can reuse verification on the same array or a handle's export.
|
|
146
|
+
* did:key and embedded peer:4 keys are immutable; time claims still check on reuse.
|
|
147
147
|
*
|
|
148
148
|
* A token the log already holds is appended again, not skipped: the log records
|
|
149
149
|
* what each commit enacted, not a set of claims, and a repeat is the only way to
|
|
@@ -305,6 +305,17 @@ export declare class GroupHandle {
|
|
|
305
305
|
advanceSenderGeneration(target: number, opts?: {
|
|
306
306
|
maxSteps?: number;
|
|
307
307
|
}): Promise<void>;
|
|
308
|
+
/**
|
|
309
|
+
* Reserve a handshake generation before building a commit from this handle.
|
|
310
|
+
* Reuse only a persisted, unconsumed reservation at the current epoch and generation.
|
|
311
|
+
* The epoch, application ratchet, ledger and pending proposals remain unchanged.
|
|
312
|
+
* `persist` runs under the handle mutex and must not re-enter this handle.
|
|
313
|
+
* A failed persist restores the source and wipes newly derived secrets.
|
|
314
|
+
* Consume the reservation durably before journalling any returned commit for publication.
|
|
315
|
+
*/
|
|
316
|
+
reserveHandshakeGeneration(persist: (handle: GroupHandle) => Promise<void> | void): Promise<void>;
|
|
317
|
+
/** Persist consumption before any commit journal can permit publication. */
|
|
318
|
+
consumeHandshakeReservation(persist: (handle: GroupHandle) => Promise<void> | void): Promise<void>;
|
|
308
319
|
/**
|
|
309
320
|
* Open an application message sealed for the group and recover WHO SENT IT — the
|
|
310
321
|
* counterpart to {@link encrypt}, and the read half of the group's application lane.
|
package/lib/group-handle.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { normalizeDID } from '@kokuin/token';
|
|
1
|
+
import { assertTimeClaimsValid, decodeSignedToken, normalizeDID } from '@kokuin/token';
|
|
2
2
|
import { EventEmitter } from '@sozai/event';
|
|
3
|
-
import { contentTypes, createApplicationMessage, createProposal, decode, defaultCredentialTypes, defaultProposalTypes, encode, isDefaultCredential, mlsExporter, mlsMessageDecoder, mlsMessageEncoder, processMessage as mlsProcessMessage, nodeTypes, senderTypes, UsageError, wireformats } from 'ts-mls';
|
|
3
|
+
import { contentTypes, createApplicationMessage, createProposal, decode, defaultCredentialTypes, defaultKeyRetentionConfig, defaultProposalTypes, encode, isDefaultCredential, mlsExporter, mlsMessageDecoder, mlsMessageEncoder, processMessage as mlsProcessMessage, nodeTypes, senderTypes, UsageError, wireformats } from 'ts-mls';
|
|
4
4
|
import { readGroupAnchor } from './anchor.js';
|
|
5
5
|
import { verifyLeafCredential } from './authentication.js';
|
|
6
6
|
import { encodeClientState } from './codec.js';
|
|
@@ -8,7 +8,7 @@ import { didFromCredential, parseMLSCredentialIdentity } from './credential.js';
|
|
|
8
8
|
import { verifyDeviceEntry } from './device-proof.js';
|
|
9
9
|
import { decodeControlEnvelope } from './envelope.js';
|
|
10
10
|
import { foldEnvelope, GROUP_TYPE_PREFIX } from './envelope-fold.js';
|
|
11
|
-
import { LeafBindingError, LeafLapsedError, RevokeProofError } from './errors.js';
|
|
11
|
+
import { HandshakeReservationError, HandshakeWindowConfigError, HandshakeWindowError, LeafBindingError, LeafLapsedError, RevokeProofError } from './errors.js';
|
|
12
12
|
import { createMlsContext, deviceDenyHolderFor } from './group-context.js';
|
|
13
13
|
import { readMessageEpoch } from './group-info.js';
|
|
14
14
|
import { assertHeadMatches, computeHead, decodeLedgerHead, encodeLedgerHead, extendHead, headsMatch, readLedgerHead, readLedgerHeadExtension } from './head.js';
|
|
@@ -22,6 +22,7 @@ import { readSenderLeafIndex } from './sender-data.js';
|
|
|
22
22
|
/** One serializer per live handle, so its state-mutating operations run one at a
|
|
23
23
|
* time in issue order. Keyed weakly: the entry is collected with the handle, and
|
|
24
24
|
* the handle carries no reference back to it. */ const MUTEXES = new WeakMap();
|
|
25
|
+
/** Leave half the configured receiver window unused. */ const HANDSHAKE_WINDOW_DIVISOR = 2;
|
|
25
26
|
export function mutexFor(handle) {
|
|
26
27
|
let mutex = MUTEXES.get(handle);
|
|
27
28
|
if (mutex === undefined) {
|
|
@@ -42,15 +43,18 @@ export function mutexFor(handle) {
|
|
|
42
43
|
* material does not linger in the heap after the state that used it is replaced. */ function zeroAll(buffers) {
|
|
43
44
|
for (const buffer of buffers)buffer.fill(0);
|
|
44
45
|
}
|
|
45
|
-
/** Zero the secrets `next` holds that `prior` does not: what a discarded derivation produced. */ function zeroFreshSecrets(prior, next) {
|
|
46
|
+
/** Zero the secrets `next` holds that `prior` does not: what a discarded derivation produced. */ function zeroFreshSecrets(prior, next, consumed = []) {
|
|
46
47
|
const held = new Set();
|
|
47
48
|
for (const secret of Object.values(prior.intermediateNodes))held.add(secret);
|
|
48
49
|
for (const leaf of Object.values(prior.leafNodes)){
|
|
49
50
|
held.add(leaf.application.secret);
|
|
50
51
|
held.add(leaf.handshake.secret);
|
|
52
|
+
for (const secret of Object.values(leaf.application.unusedGenerations))held.add(secret);
|
|
53
|
+
for (const secret of Object.values(leaf.handshake.unusedGenerations))held.add(secret);
|
|
51
54
|
}
|
|
52
55
|
const fresh = [
|
|
53
|
-
...Object.values(next.intermediateNodes)
|
|
56
|
+
...Object.values(next.intermediateNodes),
|
|
57
|
+
...consumed
|
|
54
58
|
];
|
|
55
59
|
for (const leaf of Object.values(next.leafNodes)){
|
|
56
60
|
fresh.push(leaf.application.secret, leaf.handshake.secret);
|
|
@@ -199,6 +203,21 @@ export function mutexFor(handle) {
|
|
|
199
203
|
};
|
|
200
204
|
}
|
|
201
205
|
}
|
|
206
|
+
const VERIFIED_LEDGER_ENTRIES = new WeakMap();
|
|
207
|
+
const VERIFIED_LEDGER_TOKENS = new WeakMap();
|
|
208
|
+
// Record provenance before exposing claims; re-enactments keep the original snapshot.
|
|
209
|
+
function ledgerLogEntry(entryID, token, verified) {
|
|
210
|
+
const held = {
|
|
211
|
+
entryID,
|
|
212
|
+
token,
|
|
213
|
+
verified
|
|
214
|
+
};
|
|
215
|
+
VERIFIED_LEDGER_ENTRIES.set(verified, {
|
|
216
|
+
token,
|
|
217
|
+
verified: structuredClone(verified)
|
|
218
|
+
});
|
|
219
|
+
return held;
|
|
220
|
+
}
|
|
202
221
|
/** Project lifecycle tree re-admissions from the full ledger fold, never a previous projection.
|
|
203
222
|
* A lapsed re-admitted leaf and a leaf inserted after expiry are indistinguishable here;
|
|
204
223
|
* a genuine expired post-reset package can activate a leaf for a Welcome joiner or an
|
|
@@ -357,10 +376,11 @@ export function mutexFor(handle) {
|
|
|
357
376
|
}
|
|
358
377
|
/** The ordered signed tokens this handle holds, repeats included — the ledger's
|
|
359
378
|
* canonical persistent/wire form, and the list the authenticated head folds over.
|
|
360
|
-
* Feeds createInvite, restoreGroup, and host persistence.
|
|
361
|
-
*
|
|
362
|
-
|
|
363
|
-
|
|
379
|
+
* Feeds createInvite, restoreGroup, and host persistence. In-process clones inherit
|
|
380
|
+
* verification through the returned array; serialised tokens must verify afresh. */ get ledgerTokens() {
|
|
381
|
+
const tokens = this.#ledger.map(({ token })=>token);
|
|
382
|
+
VERIFIED_LEDGER_TOKENS.set(tokens, this.#ledger.map(({ verified })=>VERIFIED_LEDGER_ENTRIES.get(verified)));
|
|
383
|
+
return tokens;
|
|
364
384
|
}
|
|
365
385
|
/** The control roster folded from the anchor and every applied ledger entry. */ get roster() {
|
|
366
386
|
return this.#roster;
|
|
@@ -458,8 +478,8 @@ export function mutexFor(handle) {
|
|
|
458
478
|
* Verify signed ledger tokens, append the valid ones in the order given, and
|
|
459
479
|
* refold the roster. Tokens that fail verification or whose groupID mismatches are
|
|
460
480
|
* dropped (defensive — the strict admin-issuer enforcement is the commit pre-pass).
|
|
461
|
-
*
|
|
462
|
-
*
|
|
481
|
+
* Exact token bytes can reuse verification on the same array or a handle's export.
|
|
482
|
+
* did:key and embedded peer:4 keys are immutable; time claims still check on reuse.
|
|
463
483
|
*
|
|
464
484
|
* A token the log already holds is appended again, not skipped: the log records
|
|
465
485
|
* what each commit enacted, not a set of claims, and a repeat is the only way to
|
|
@@ -469,21 +489,33 @@ export function mutexFor(handle) {
|
|
|
469
489
|
*/ async applyLedgerEntries(tokens) {
|
|
470
490
|
return mutexFor(this).run(async ()=>{
|
|
471
491
|
const appended = [];
|
|
472
|
-
|
|
473
|
-
|
|
492
|
+
const memo = VERIFIED_LEDGER_TOKENS.get(tokens);
|
|
493
|
+
const nextMemo = [];
|
|
494
|
+
for (const [index, token] of tokens.entries()){
|
|
495
|
+
const held = memo?.[index];
|
|
496
|
+
let verified;
|
|
497
|
+
if (held?.token === token) {
|
|
498
|
+
try {
|
|
499
|
+
assertTimeClaimsValid(decodeSignedToken(token).payload);
|
|
500
|
+
} catch {
|
|
501
|
+
continue;
|
|
502
|
+
}
|
|
503
|
+
verified = structuredClone(held.verified);
|
|
504
|
+
} else {
|
|
505
|
+
verified = await verifyLedgerEntry(token);
|
|
506
|
+
}
|
|
474
507
|
if (verified == null || verified.entry.groupID !== this.groupID) continue;
|
|
475
508
|
const entryID = ledgerEntryDigest(token);
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
verified
|
|
480
|
-
});
|
|
509
|
+
const entry = ledgerLogEntry(entryID, token, verified);
|
|
510
|
+
this.#ledger.push(entry);
|
|
511
|
+
nextMemo[index] = VERIFIED_LEDGER_ENTRIES.get(verified);
|
|
481
512
|
this.#entryBodies.set(entryID, {
|
|
482
513
|
token,
|
|
483
514
|
verified
|
|
484
515
|
});
|
|
485
516
|
appended.push(verified);
|
|
486
517
|
}
|
|
518
|
+
VERIFIED_LEDGER_TOKENS.set(tokens, nextMemo);
|
|
487
519
|
const folded = foldLedgerControl(this.#ledger, this.#anchor, this.groupID);
|
|
488
520
|
this.#roster = folded.roster;
|
|
489
521
|
this.#registry = registryWithTreeBindings(folded.registry, this.#state.ratchetTree, this.#anchor);
|
|
@@ -568,11 +600,7 @@ export function mutexFor(handle) {
|
|
|
568
600
|
// covers. Fails closed anyway.
|
|
569
601
|
throw new Error('bootstrapLedger: the gathered ledger holds an unverifiable or cross-group entry');
|
|
570
602
|
}
|
|
571
|
-
log.push(
|
|
572
|
-
entryID: entryIDs[index],
|
|
573
|
-
token,
|
|
574
|
-
verified
|
|
575
|
-
});
|
|
603
|
+
log.push(ledgerLogEntry(entryIDs[index], token, verified));
|
|
576
604
|
}
|
|
577
605
|
// What this bootstrap ADDS, in log order, minus the reserved `kumiai.*` types the fold
|
|
578
606
|
// consumes itself — the same rule the commit path surfaces by.
|
|
@@ -886,6 +914,108 @@ export function mutexFor(handle) {
|
|
|
886
914
|
});
|
|
887
915
|
}
|
|
888
916
|
/**
|
|
917
|
+
* Reserve a handshake generation before building a commit from this handle.
|
|
918
|
+
* Reuse only a persisted, unconsumed reservation at the current epoch and generation.
|
|
919
|
+
* The epoch, application ratchet, ledger and pending proposals remain unchanged.
|
|
920
|
+
* `persist` runs under the handle mutex and must not re-enter this handle.
|
|
921
|
+
* A failed persist restores the source and wipes newly derived secrets.
|
|
922
|
+
* Consume the reservation durably before journalling any returned commit for publication.
|
|
923
|
+
*/ async reserveHandshakeGeneration(persist) {
|
|
924
|
+
return mutexFor(this).run(async ()=>{
|
|
925
|
+
const prior = this.#state;
|
|
926
|
+
if (prior.groupActiveState.kind === 'suspendedPendingReinit') {
|
|
927
|
+
throw new UsageError('Cannot send messages while Group is suspended pending reinit');
|
|
928
|
+
}
|
|
929
|
+
if (prior.groupActiveState.kind === 'removedFromGroup') {
|
|
930
|
+
throw new UsageError('Cannot send messages after being removed from group');
|
|
931
|
+
}
|
|
932
|
+
const node = Number(prior.privatePath.leafIndex) * 2;
|
|
933
|
+
const leaf = prior.secretTree.leafNodes[node];
|
|
934
|
+
const current = leaf?.handshake.generation ?? 0;
|
|
935
|
+
const reservation = prior.handshakeReservation;
|
|
936
|
+
if (reservation?.epoch === this.epoch && reservation.generation === current && !reservation.consumed) {
|
|
937
|
+
await persist(this);
|
|
938
|
+
return;
|
|
939
|
+
}
|
|
940
|
+
// Every accepted MLS handshake commit moves the epoch. Epoch start is therefore a
|
|
941
|
+
// conservative baseline, even when a receiver refused or missed earlier frames.
|
|
942
|
+
// rc.13: MlsContext.clientConfig.keyRetentionConfig.maximumForwardRatchetSteps
|
|
943
|
+
// defaults to defaultKeyRetentionConfig.maximumForwardRatchetSteps (200).
|
|
944
|
+
const window = this.#context.clientConfig?.keyRetentionConfig?.maximumForwardRatchetSteps ?? defaultKeyRetentionConfig.maximumForwardRatchetSteps;
|
|
945
|
+
const limit = Math.floor(Math.min(window, defaultKeyRetentionConfig.maximumForwardRatchetSteps) / HANDSHAKE_WINDOW_DIVISOR);
|
|
946
|
+
if (limit < 1) throw new HandshakeWindowConfigError();
|
|
947
|
+
if (current + 1 > limit) throw new HandshakeWindowError();
|
|
948
|
+
if (current >= 0xfffffffe) throw new RangeError('handshake sender generation exhausted');
|
|
949
|
+
let tree;
|
|
950
|
+
let consumed;
|
|
951
|
+
if (leaf == null) {
|
|
952
|
+
// ts-mls does not export leaf derivation. Discard an unsent proposal and retain
|
|
953
|
+
// only its advanced tree, without adding the proposal to the source state.
|
|
954
|
+
const result = await createProposal({
|
|
955
|
+
context: this.#context,
|
|
956
|
+
state: prior,
|
|
957
|
+
proposal: {
|
|
958
|
+
proposalType: defaultProposalTypes.remove,
|
|
959
|
+
remove: {
|
|
960
|
+
removed: prior.privatePath.leafIndex
|
|
961
|
+
}
|
|
962
|
+
}
|
|
963
|
+
});
|
|
964
|
+
tree = result.newState.secretTree;
|
|
965
|
+
consumed = result.consumed;
|
|
966
|
+
} else {
|
|
967
|
+
const advanced = await advanceSendingRatchet(this.#context, leaf.handshake, current + 1);
|
|
968
|
+
tree = {
|
|
969
|
+
...prior.secretTree,
|
|
970
|
+
leafNodes: {
|
|
971
|
+
...prior.secretTree.leafNodes,
|
|
972
|
+
[node]: {
|
|
973
|
+
...leaf,
|
|
974
|
+
handshake: advanced.ratchet
|
|
975
|
+
}
|
|
976
|
+
}
|
|
977
|
+
};
|
|
978
|
+
consumed = advanced.consumed;
|
|
979
|
+
}
|
|
980
|
+
this.#state = {
|
|
981
|
+
...prior,
|
|
982
|
+
secretTree: tree,
|
|
983
|
+
handshakeReservation: {
|
|
984
|
+
epoch: this.epoch,
|
|
985
|
+
generation: current + 1,
|
|
986
|
+
consumed: false
|
|
987
|
+
}
|
|
988
|
+
};
|
|
989
|
+
try {
|
|
990
|
+
await persist(this);
|
|
991
|
+
} catch (error) {
|
|
992
|
+
this.#state = prior;
|
|
993
|
+
zeroFreshSecrets(prior.secretTree, tree, consumed);
|
|
994
|
+
throw error;
|
|
995
|
+
}
|
|
996
|
+
zeroAll(consumed);
|
|
997
|
+
});
|
|
998
|
+
}
|
|
999
|
+
/** Persist consumption before any commit journal can permit publication. */ async consumeHandshakeReservation(persist) {
|
|
1000
|
+
return mutexFor(this).run(async ()=>{
|
|
1001
|
+
const prior = this.#state;
|
|
1002
|
+
const reservation = prior.handshakeReservation;
|
|
1003
|
+
const current = prior.secretTree.leafNodes[Number(prior.privatePath.leafIndex) * 2]?.handshake.generation;
|
|
1004
|
+
if (reservation == null || reservation.epoch !== this.epoch || reservation.generation !== current) {
|
|
1005
|
+
throw new HandshakeReservationError();
|
|
1006
|
+
}
|
|
1007
|
+
this.#state = {
|
|
1008
|
+
...prior,
|
|
1009
|
+
handshakeReservation: {
|
|
1010
|
+
...reservation,
|
|
1011
|
+
consumed: true
|
|
1012
|
+
}
|
|
1013
|
+
};
|
|
1014
|
+
// Keep consumed evidence in memory on failure. No journal write can follow rejection.
|
|
1015
|
+
await persist(this);
|
|
1016
|
+
});
|
|
1017
|
+
}
|
|
1018
|
+
/**
|
|
889
1019
|
* Open an application message sealed for the group and recover WHO SENT IT — the
|
|
890
1020
|
* counterpart to {@link encrypt}, and the read half of the group's application lane.
|
|
891
1021
|
*
|
|
@@ -1062,11 +1192,7 @@ export function mutexFor(handle) {
|
|
|
1062
1192
|
if (resolved.has(id) || !missing.includes(id)) continue;
|
|
1063
1193
|
const verified = await verifyLedgerEntry(token);
|
|
1064
1194
|
if (verified == null) continue;
|
|
1065
|
-
resolved.set(id,
|
|
1066
|
-
token,
|
|
1067
|
-
verified,
|
|
1068
|
-
entryID: id
|
|
1069
|
-
});
|
|
1195
|
+
resolved.set(id, ledgerLogEntry(id, token, verified));
|
|
1070
1196
|
}
|
|
1071
1197
|
const stillMissing = missing.filter((id)=>!resolved.has(id));
|
|
1072
1198
|
if (stillMissing.length > 0) {
|
package/lib/index.d.ts
CHANGED
|
@@ -10,7 +10,7 @@ export { createNobleCryptoProvider, type NobleCryptoProviderOptions, nobleCrypto
|
|
|
10
10
|
export type { LeafBinding } from './device-proof.js';
|
|
11
11
|
export { CONTROL_ENVELOPE_VERSION, type ControlEnvelope, type DecodeResult, decodeControlEnvelope, encodeControlEnvelope, } from './envelope.js';
|
|
12
12
|
export { type EnvelopeFoldResult, type FoldEnvelopeContext, type FoldEnvelopeParams, foldEnvelope, } from './envelope-fold.js';
|
|
13
|
-
export { LeafBindingError, type LeafBindingReason, LeafLapsedError, type LeafLapsedReason, RevokeProofError, type RevokeProofReason, } from './errors.js';
|
|
13
|
+
export { HandshakeReservationError, HandshakeWindowConfigError, HandshakeWindowError, LeafBindingError, type LeafBindingReason, LeafLapsedError, type LeafLapsedReason, RevokeProofError, type RevokeProofReason, } from './errors.js';
|
|
14
14
|
export { type FoldDrop, type FoldInput, foldLedger, type LedgerReducer, } from './fold.js';
|
|
15
15
|
export { addDevice, announceControllerBeacon, type CommitInviteResult, type CommitLedgerEntriesResult, CommitRejectedError, type CreateGroupResult, type CreateInviteParams, type CreateInviteResult, commitInvite, commitLedgerEntries, createGroup, createInvite, createKeyPackageBundle, createLastResortKeyPackageBundle, type DeviceWriteResult, type ExportGroupInfoParams, type ExportGroupInfoResult, exportGroupInfo, GroupHandle, type GroupHandleEvents, type GroupHandleParams, type HeldLedgerEntry, type InspectGroupInfoResult, InviteRecipientMismatchError, type InviteRecipientMismatchErrorParams, inspectGroupInfo, type JoinGroupExternalParams, type JoinGroupExternalResult, joinGroupExternal, LAST_RESORT_EXTENSION_TYPE, LAST_RESORT_LIFETIME_DAYS, type LedgerLogEntry, labelDevice, makeMLSCredential, ORDINARY_KEY_PACKAGE_LIFETIME_DAYS, type ProcessWelcomeOnceParams, type ProcessWelcomeParams, type ProcessWelcomeResult, processWelcome, processWelcomeOnce, type RemoveMemberResult, type RestoreGroupParams, readCommitEntryIDs, readMessageAAD, readMessageEpoch, registerDevice, removeMember, restoreGroup, revokeDevice, type SendAdmission, } from './group.js';
|
|
16
16
|
export { type CommitResult, commitSelfRemovals, proposeSelfRemoval, type RemoveLapsedLeavesResult, type RevokeBuildResult, type RevokeWithProofParams, removeLapsedLeaves, renewLeaf, revokeWithProof, } from './group-lifecycle.js';
|
package/lib/index.js
CHANGED
|
@@ -7,7 +7,7 @@ export { didFromCredential, parseMLSCredentialIdentity } from './credential.js';
|
|
|
7
7
|
export { createNobleCryptoProvider, nobleCryptoProvider } from './crypto.js';
|
|
8
8
|
export { CONTROL_ENVELOPE_VERSION, decodeControlEnvelope, encodeControlEnvelope } from './envelope.js';
|
|
9
9
|
export { foldEnvelope } from './envelope-fold.js';
|
|
10
|
-
export { LeafBindingError, LeafLapsedError, RevokeProofError } from './errors.js';
|
|
10
|
+
export { HandshakeReservationError, HandshakeWindowConfigError, HandshakeWindowError, LeafBindingError, LeafLapsedError, RevokeProofError } from './errors.js';
|
|
11
11
|
export { foldLedger } from './fold.js';
|
|
12
12
|
export { addDevice, announceControllerBeacon, CommitRejectedError, commitInvite, commitLedgerEntries, createGroup, createInvite, createKeyPackageBundle, createLastResortKeyPackageBundle, exportGroupInfo, GroupHandle, InviteRecipientMismatchError, inspectGroupInfo, joinGroupExternal, LAST_RESORT_EXTENSION_TYPE, LAST_RESORT_LIFETIME_DAYS, labelDevice, makeMLSCredential, ORDINARY_KEY_PACKAGE_LIFETIME_DAYS, processWelcome, processWelcomeOnce, readCommitEntryIDs, readMessageAAD, readMessageEpoch, registerDevice, removeMember, restoreGroup, revokeDevice } from './group.js';
|
|
13
13
|
export { commitSelfRemovals, proposeSelfRemoval, removeLapsedLeaves, renewLeaf, revokeWithProof } from './group-lifecycle.js';
|