@kumiai/mls 0.9.0 → 0.10.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +23 -0
- package/lib/codec.js +2 -1
- package/lib/group-handle.d.ts +39 -16
- package/lib/group-handle.js +129 -26
- package/lib/group-info.d.ts +8 -0
- package/lib/group-info.js +29 -1
- package/lib/group-welcome.d.ts +3 -3
- package/lib/group.d.ts +1 -1
- package/lib/group.js +1 -1
- package/lib/index.d.ts +1 -1
- package/lib/index.js +1 -1
- package/lib/policy.js +1 -0
- package/lib/welcome-refs.d.ts +2 -1
- package/package.json +3 -3
package/README.md
CHANGED
|
@@ -10,10 +10,33 @@ Credential-aware MLS (RFC 9420) group lifecycle for enkaku. Wraps [`ts-mls`](htt
|
|
|
10
10
|
- `commitLedgerEntries` — an admin promotes or demotes by committing signed `kumiai.role` entries
|
|
11
11
|
- `removeMember` — an admin evicts a leaf and rotates keys
|
|
12
12
|
- `restoreGroup` — rehydrate a `GroupHandle` from persisted `ClientState` and the stored ledger tokens
|
|
13
|
+
- `GroupHandle.processMessage(message, { persist? })` and `bootstrapLedger(tokens, { persist? })` — persist accepted commits, proposals, or a ledger bootstrap before notifications; a rejected persist restores the prior in-memory state. Application-message receive ratchets are not persisted by this option. Persist runs under the handle mutex, so it must not call back into that handle. Writes must be atomic: rejection must leave storage unchanged.
|
|
13
14
|
- `encodeKeyPackage` + `decodeKeyPackage` — convert a key package to and from the opaque string a hub stores; decode is strict and returns `null` rather than throwing
|
|
14
15
|
- `encodePrivateKeyPackage` + `decodePrivateKeyPackage` — the canonical string form of a key package's **private** half, for a host that must persist it across restarts (a reusable last-resort package outlives the process that made it). Secret material: never publish or log it.
|
|
15
16
|
- `keyPackageRef` — the base64 KeyPackageRef a Welcome names, stable across a codec round trip. Use it as the identity of a stored package.
|
|
16
17
|
- `exportGroupInfo` + `joinGroupExternal` — stale-device self-rejoin (see below)
|
|
18
|
+
- `GroupHandle.decryptStaged` — open an app frame while withholding its consumed-key state until
|
|
19
|
+
a host has atomically saved that state and its pending delivery record
|
|
20
|
+
- `readMessageAAD(bytes)` — read a PrivateMessage's cleartext authenticated data without a key;
|
|
21
|
+
returns `null` for unreadable bytes and never throws
|
|
22
|
+
|
|
23
|
+
## Persisting a staged app open
|
|
24
|
+
|
|
25
|
+
`await group.decryptStaged(message, { expectedAAD }, async (stagedState, opened) => { ... })`
|
|
26
|
+
computes the post-open state under the handle mutex but does not adopt it until the callback
|
|
27
|
+
resolves. `stagedState` is encoded `ClientState`, in the same format the host already stores for
|
|
28
|
+
`restoreGroup`; save these bytes as the group's handle state, together with the pending record,
|
|
29
|
+
in one atomic transaction. `opened` contains `payload`, authenticated `senderDID`, and `aad`.
|
|
30
|
+
An unnamed sender is rejected before the callback. If opening or persistence fails, the live
|
|
31
|
+
state and its message key remain available for retry. After persistence succeeds, the handle
|
|
32
|
+
adopts the staged state and the same frame cannot open again.
|
|
33
|
+
|
|
34
|
+
The callback runs while the handle mutex is held. It must not call this handle or its peer.
|
|
35
|
+
The host must order earlier handle saves before the staged write and reject older writes at the
|
|
36
|
+
same epoch using a monotonic state version; otherwise an earlier delayed save can overwrite the
|
|
37
|
+
consumed-key state while leaving the pending record. No database transaction or single connection
|
|
38
|
+
may be held while awaiting a handle or peer operation. The real `@kumiai/mls-rpc` port's optional
|
|
39
|
+
`pending` adapter calls `decryptStaged` for durable logged events.
|
|
17
40
|
|
|
18
41
|
## Authority model
|
|
19
42
|
|
package/lib/codec.js
CHANGED
|
@@ -29,7 +29,8 @@ export function decodeClientState(encoded) {
|
|
|
29
29
|
if (encoded[0] !== CLIENT_STATE_VERSION) {
|
|
30
30
|
throw new Error(`decodeClientState: unsupported client-state version ${encoded[0]}`);
|
|
31
31
|
}
|
|
32
|
-
|
|
32
|
+
// A copy: ts-mls decodes secrets as views, and ratcheting zeroes consumed ones in place.
|
|
33
|
+
return decode(clientStateDecoder, encoded.slice(1));
|
|
33
34
|
}
|
|
34
35
|
export function encodeClientState(state) {
|
|
35
36
|
const body = encode(clientStateEncoder, state);
|
package/lib/group-handle.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { EventEmitter, type EventsSource } from '@sozai/event';
|
|
2
|
-
import { type ClientState, type IncomingMessageCallback, type MlsContext, type ProposalWithSender } from 'ts-mls';
|
|
2
|
+
import { type ClientState, type IncomingMessageCallback, type MlsContext, type MlsFramedMessage, type ProposalWithSender } from 'ts-mls';
|
|
3
3
|
import { type GroupAnchor } from './anchor.js';
|
|
4
4
|
import { type GroupMember, type MemberCredential } from './credential.js';
|
|
5
5
|
import { type LeafBinding } from './device-proof.js';
|
|
@@ -177,9 +177,13 @@ export declare class GroupHandle {
|
|
|
177
177
|
* signatures do not. The bound: **a lying responder can withhold, never rewrite.**
|
|
178
178
|
*
|
|
179
179
|
* Throws {@link LedgerIncompleteError} on a head mismatch; the caller drops that
|
|
180
|
-
* responder and tries the next.
|
|
180
|
+
* responder and tries the next. `persist` runs under this handle's mutex and must not
|
|
181
|
+
* call back into it. It must write atomically: rejection means nothing was stored.
|
|
182
|
+
* Host callbacks run after successful persist; a callback throw does not undo bootstrap.
|
|
181
183
|
*/
|
|
182
|
-
bootstrapLedger(tokens: Array<string
|
|
184
|
+
bootstrapLedger(tokens: Array<string>, opts?: {
|
|
185
|
+
persist?: (handle: GroupHandle) => Promise<void> | void;
|
|
186
|
+
}): Promise<void>;
|
|
183
187
|
get memberCount(): number;
|
|
184
188
|
findMemberLeafIndex(id: string): number | undefined;
|
|
185
189
|
/**
|
|
@@ -200,10 +204,10 @@ export declare class GroupHandle {
|
|
|
200
204
|
* The diff sees MEMBERSHIP, and only membership: an Add, a Remove, or both in
|
|
201
205
|
* one commit (compare as a set — a count misses that last case). It does NOT
|
|
202
206
|
* see an external-commit REJOIN by a member the group still holds. That member
|
|
203
|
-
* keeps its id, so the id set is unchanged;
|
|
204
|
-
*
|
|
205
|
-
*
|
|
206
|
-
*
|
|
207
|
+
* keeps its id, so the id set is unchanged; the new leaf takes the leftmost blank, which is the
|
|
208
|
+
* just-vacated slot only when no earlier blank exists — otherwise the rejoiner's `leafIndex`
|
|
209
|
+
* moves. Only the id-set projection of this result is guaranteed unchanged across a rejoin;
|
|
210
|
+
* `leafIndex` is not, so a before/after diff on `leafIndex` cannot be relied on either.
|
|
207
211
|
* A caller that must detect a rejoin reads the COMMIT instead — an external
|
|
208
212
|
* commit is structurally one: a public message from a non-member carrying a
|
|
209
213
|
* commit, recognizable from its own bytes before it is applied, and carrying
|
|
@@ -254,12 +258,10 @@ export declare class GroupHandle {
|
|
|
254
258
|
* Open an application message sealed for the group and recover WHO SENT IT — the
|
|
255
259
|
* counterpart to {@link encrypt}, and the read half of the group's application lane.
|
|
256
260
|
*
|
|
257
|
-
* Throws for bytes this handle cannot open
|
|
258
|
-
*
|
|
259
|
-
*
|
|
260
|
-
*
|
|
261
|
-
* — it is how a frame says "not mine" — and such a caller must not read the throw as
|
|
262
|
-
* corruption. Use {@link readMessageEpoch} to tell those two cases apart before trying.
|
|
261
|
+
* Throws for bytes this handle cannot open. A future-epoch frame cannot open yet;
|
|
262
|
+
* ts-mls can open some past-epoch frames while their retained key material lasts.
|
|
263
|
+
* That window is bounded by epoch transitions. Use {@link readMessageEpoch} to
|
|
264
|
+
* distinguish an epoch mismatch from malformed bytes before trying.
|
|
263
265
|
*
|
|
264
266
|
* WHY THE SENDER IS AUTHENTICATED and not merely claimed: the leaf index comes from the
|
|
265
267
|
* message's sender-data, encrypted under this epoch's sender-data secret, and the
|
|
@@ -286,6 +288,23 @@ export declare class GroupHandle {
|
|
|
286
288
|
senderDID?: string;
|
|
287
289
|
aad: Uint8Array;
|
|
288
290
|
}>;
|
|
291
|
+
/**
|
|
292
|
+
* Open an application frame, but make its post-open state durable before adopting it.
|
|
293
|
+
* The callback runs under this handle's mutex and must store `stagedState` as the
|
|
294
|
+
* group's handle state. It must not call this handle or the peer. If opening or
|
|
295
|
+
* persistence fails, the live state and its ratchet secrets remain untouched.
|
|
296
|
+
*/
|
|
297
|
+
decryptStaged(message: Uint8Array, opts: {
|
|
298
|
+
expectedAAD?: Uint8Array;
|
|
299
|
+
}, persist: (stagedState: Uint8Array, opened: {
|
|
300
|
+
payload: Uint8Array;
|
|
301
|
+
senderDID: string;
|
|
302
|
+
aad: Uint8Array;
|
|
303
|
+
}) => Promise<void>): Promise<{
|
|
304
|
+
payload: Uint8Array;
|
|
305
|
+
senderDID: string;
|
|
306
|
+
aad: Uint8Array;
|
|
307
|
+
}>;
|
|
289
308
|
/**
|
|
290
309
|
* The device-proof binding at the leaf naming `did`: its bound controller (if any), the embedded
|
|
291
310
|
* controller-log prefix (if bound), and the leaf signature key. Reads the CURRENT ratchet tree —
|
|
@@ -335,11 +354,15 @@ export declare class GroupHandle {
|
|
|
335
354
|
/**
|
|
336
355
|
* Process a received MLS message (Commit, Proposal, or application). Accepts
|
|
337
356
|
* wire-form bytes (preferred, e.g. from commitInvite/removeMember) or a pre-decoded
|
|
338
|
-
* ts-mls
|
|
339
|
-
*
|
|
357
|
+
* ts-mls framed message (legacy). The runtime `instanceof` selects the decode path.
|
|
358
|
+
* `persist` covers accepted commits and proposals, not application messages or their
|
|
359
|
+
* receive ratchet. It runs under this handle's mutex and must not call back into it.
|
|
360
|
+
* It must write atomically: rejection means nothing was stored. Host callbacks run
|
|
361
|
+
* after successful persist; a callback throw does not undo an advance.
|
|
340
362
|
*/
|
|
341
|
-
processMessage(message: Uint8Array |
|
|
363
|
+
processMessage(message: Uint8Array | MlsFramedMessage, opts?: {
|
|
342
364
|
commitPolicy?: IncomingMessageCallback;
|
|
365
|
+
persist?: (handle: GroupHandle) => Promise<void> | void;
|
|
343
366
|
}): Promise<Uint8Array | null>;
|
|
344
367
|
}
|
|
345
368
|
/** Build the CommitPolicyContext both the receive gate and the send-side pending
|
package/lib/group-handle.js
CHANGED
|
@@ -2,6 +2,7 @@ import { normalizeDID } from '@kokuin/token';
|
|
|
2
2
|
import { EventEmitter } from '@sozai/event';
|
|
3
3
|
import { contentTypes, createApplicationMessage, decode, encode, mlsExporter, mlsMessageDecoder, mlsMessageEncoder, processMessage as mlsProcessMessage, nodeTypes, senderTypes, wireformats } from 'ts-mls';
|
|
4
4
|
import { readGroupAnchor } from './anchor.js';
|
|
5
|
+
import { encodeClientState } from './codec.js';
|
|
5
6
|
import { parseMLSCredentialIdentity } from './credential.js';
|
|
6
7
|
import { verifyDeviceEntry } from './device-proof.js';
|
|
7
8
|
import { decodeControlEnvelope } from './envelope.js';
|
|
@@ -328,6 +329,21 @@ export function mutexFor(handle) {
|
|
|
328
329
|
}
|
|
329
330
|
if (revoked.length > 0) emitter.fire('deviceRevoked', revoked);
|
|
330
331
|
}
|
|
332
|
+
/** Deliver independent host notifications after acceptance and any requested persist. */ #notifyAccepted(surfaced, enactedDevice) {
|
|
333
|
+
const errors = [];
|
|
334
|
+
try {
|
|
335
|
+
if (surfaced.length > 0) this.#onLedgerEntries?.(surfaced);
|
|
336
|
+
} catch (error) {
|
|
337
|
+
errors.push(error);
|
|
338
|
+
}
|
|
339
|
+
try {
|
|
340
|
+
this.emitControlEvents(enactedDevice);
|
|
341
|
+
} catch (error) {
|
|
342
|
+
errors.push(error);
|
|
343
|
+
}
|
|
344
|
+
if (errors.length === 1) throw errors[0];
|
|
345
|
+
if (errors.length > 1) throw new AggregateError(errors, 'host notifications failed');
|
|
346
|
+
}
|
|
331
347
|
/**
|
|
332
348
|
* Verify signed ledger tokens, append the valid ones in the order given, and
|
|
333
349
|
* refold the roster. Tokens that fail verification or whose groupID mismatches are
|
|
@@ -415,8 +431,10 @@ export function mutexFor(handle) {
|
|
|
415
431
|
* signatures do not. The bound: **a lying responder can withhold, never rewrite.**
|
|
416
432
|
*
|
|
417
433
|
* Throws {@link LedgerIncompleteError} on a head mismatch; the caller drops that
|
|
418
|
-
* responder and tries the next.
|
|
419
|
-
|
|
434
|
+
* responder and tries the next. `persist` runs under this handle's mutex and must not
|
|
435
|
+
* call back into it. It must write atomically: rejection means nothing was stored.
|
|
436
|
+
* Host callbacks run after successful persist; a callback throw does not undo bootstrap.
|
|
437
|
+
*/ async bootstrapLedger(tokens, opts) {
|
|
420
438
|
return mutexFor(this).run(async ()=>{
|
|
421
439
|
const authenticated = readLedgerHead(this);
|
|
422
440
|
if (authenticated == null) {
|
|
@@ -448,6 +466,14 @@ export function mutexFor(handle) {
|
|
|
448
466
|
// Same dedupe as `surfaced`, narrowed to device entries — feeds emitControlEvents below so a
|
|
449
467
|
// heal fires deviceRevoked for entries this bootstrap actually adds, not ones already held.
|
|
450
468
|
const enactedDevice = log.filter(({ entryID, verified })=>!this.#entryBodies.has(entryID) && verified.entry.type === DEVICE_ENTRY_TYPE).map(({ verified })=>verified);
|
|
469
|
+
const previous = {
|
|
470
|
+
state: this.#state,
|
|
471
|
+
ledger: this.#ledger,
|
|
472
|
+
entryBodies: this.#entryBodies,
|
|
473
|
+
roster: this.#roster,
|
|
474
|
+
registry: this.#registry
|
|
475
|
+
};
|
|
476
|
+
const folded = foldLedgerControl(log, this.#anchor, this.groupID);
|
|
451
477
|
this.#ledger = log;
|
|
452
478
|
this.#entryBodies = new Map(log.map(({ entryID, token, verified })=>[
|
|
453
479
|
entryID,
|
|
@@ -456,9 +482,18 @@ export function mutexFor(handle) {
|
|
|
456
482
|
verified
|
|
457
483
|
}
|
|
458
484
|
]));
|
|
459
|
-
const folded = foldLedgerControl(log, this.#anchor, this.groupID);
|
|
460
485
|
this.#roster = folded.roster;
|
|
461
486
|
this.#registry = folded.registry;
|
|
487
|
+
try {
|
|
488
|
+
await opts?.persist?.(this);
|
|
489
|
+
} catch (error) {
|
|
490
|
+
this.#state = previous.state;
|
|
491
|
+
this.#ledger = previous.ledger;
|
|
492
|
+
this.#entryBodies = previous.entryBodies;
|
|
493
|
+
this.#roster = previous.roster;
|
|
494
|
+
this.#registry = previous.registry;
|
|
495
|
+
throw error;
|
|
496
|
+
}
|
|
462
497
|
// SURFACED HERE TOO, not only on the commit path. A heal is how a peer that missed commits
|
|
463
498
|
// catches up — it rejoins, gathers the whole ledger, and lands here — so a bootstrap that
|
|
464
499
|
// said nothing left a host consuming `onLedgerEntries` as an event stream permanently
|
|
@@ -467,8 +502,7 @@ export function mutexFor(handle) {
|
|
|
467
502
|
//
|
|
468
503
|
// Deduped against what this handle already held, so a peer bootstrapping over a partial
|
|
469
504
|
// ledger is not re-notified of entries it has already seen.
|
|
470
|
-
|
|
471
|
-
this.emitControlEvents(enactedDevice);
|
|
505
|
+
this.#notifyAccepted(surfaced, enactedDevice);
|
|
472
506
|
});
|
|
473
507
|
}
|
|
474
508
|
get memberCount() {
|
|
@@ -539,10 +573,10 @@ export function mutexFor(handle) {
|
|
|
539
573
|
* The diff sees MEMBERSHIP, and only membership: an Add, a Remove, or both in
|
|
540
574
|
* one commit (compare as a set — a count misses that last case). It does NOT
|
|
541
575
|
* see an external-commit REJOIN by a member the group still holds. That member
|
|
542
|
-
* keeps its id, so the id set is unchanged;
|
|
543
|
-
*
|
|
544
|
-
*
|
|
545
|
-
*
|
|
576
|
+
* keeps its id, so the id set is unchanged; the new leaf takes the leftmost blank, which is the
|
|
577
|
+
* just-vacated slot only when no earlier blank exists — otherwise the rejoiner's `leafIndex`
|
|
578
|
+
* moves. Only the id-set projection of this result is guaranteed unchanged across a rejoin;
|
|
579
|
+
* `leafIndex` is not, so a before/after diff on `leafIndex` cannot be relied on either.
|
|
546
580
|
* A caller that must detect a rejoin reads the COMMIT instead — an external
|
|
547
581
|
* commit is structurally one: a public message from a non-member carrying a
|
|
548
582
|
* commit, recognizable from its own bytes before it is applied, and carrying
|
|
@@ -606,12 +640,10 @@ export function mutexFor(handle) {
|
|
|
606
640
|
* Open an application message sealed for the group and recover WHO SENT IT — the
|
|
607
641
|
* counterpart to {@link encrypt}, and the read half of the group's application lane.
|
|
608
642
|
*
|
|
609
|
-
* Throws for bytes this handle cannot open
|
|
610
|
-
*
|
|
611
|
-
*
|
|
612
|
-
*
|
|
613
|
-
* — it is how a frame says "not mine" — and such a caller must not read the throw as
|
|
614
|
-
* corruption. Use {@link readMessageEpoch} to tell those two cases apart before trying.
|
|
643
|
+
* Throws for bytes this handle cannot open. A future-epoch frame cannot open yet;
|
|
644
|
+
* ts-mls can open some past-epoch frames while their retained key material lasts.
|
|
645
|
+
* That window is bounded by epoch transitions. Use {@link readMessageEpoch} to
|
|
646
|
+
* distinguish an epoch mismatch from malformed bytes before trying.
|
|
615
647
|
*
|
|
616
648
|
* WHY THE SENDER IS AUTHENTICATED and not merely claimed: the leaf index comes from the
|
|
617
649
|
* message's sender-data, encrypted under this epoch's sender-data secret, and the
|
|
@@ -665,6 +697,42 @@ export function mutexFor(handle) {
|
|
|
665
697
|
});
|
|
666
698
|
}
|
|
667
699
|
/**
|
|
700
|
+
* Open an application frame, but make its post-open state durable before adopting it.
|
|
701
|
+
* The callback runs under this handle's mutex and must store `stagedState` as the
|
|
702
|
+
* group's handle state. It must not call this handle or the peer. If opening or
|
|
703
|
+
* persistence fails, the live state and its ratchet secrets remain untouched.
|
|
704
|
+
*/ async decryptStaged(message, opts, persist) {
|
|
705
|
+
const decoded = decode(mlsMessageDecoder, message);
|
|
706
|
+
if (decoded == null) throw new Error('decryptStaged: failed to decode MLSMessage');
|
|
707
|
+
return mutexFor(this).run(async ()=>{
|
|
708
|
+
const pm = readPrivateFrame(decoded, contentTypes.application);
|
|
709
|
+
if (pm == null) throw new Error('decryptStaged: not a PrivateMessage application frame');
|
|
710
|
+
if (opts.expectedAAD != null && !bytesEqual(pm.authenticatedData, opts.expectedAAD)) {
|
|
711
|
+
throw new Error('decryptStaged: frame authenticated data does not match expected AAD');
|
|
712
|
+
}
|
|
713
|
+
const leafIndex = await readSenderLeafIndex(this.#context, this.#state.keySchedule.senderDataSecret, pm);
|
|
714
|
+
const result = await mlsProcessMessage({
|
|
715
|
+
context: this.#context,
|
|
716
|
+
state: this.#state,
|
|
717
|
+
message: decoded
|
|
718
|
+
});
|
|
719
|
+
if (result.kind !== 'applicationMessage') {
|
|
720
|
+
throw new Error('decryptStaged: frame was not an application message');
|
|
721
|
+
}
|
|
722
|
+
const senderDID = leafIndex == null ? undefined : this.#didOfLeaf(leafIndex);
|
|
723
|
+
if (senderDID == null) throw new Error('decryptStaged: unnamed sender');
|
|
724
|
+
const opened = {
|
|
725
|
+
payload: result.message,
|
|
726
|
+
senderDID,
|
|
727
|
+
aad: result.aad
|
|
728
|
+
};
|
|
729
|
+
await persist(encodeClientState(result.newState), opened);
|
|
730
|
+
this.#state = result.newState;
|
|
731
|
+
zeroAll(result.consumed);
|
|
732
|
+
return opened;
|
|
733
|
+
});
|
|
734
|
+
}
|
|
735
|
+
/**
|
|
668
736
|
* The async pre-pass feeding the synchronous ts-mls commit callback, run before
|
|
669
737
|
* mlsProcessMessage. For anything that is not a PrivateMessage commit it just
|
|
670
738
|
* resolves the caller policy, wraps it for rejected-proposal capture, and applies
|
|
@@ -802,7 +870,7 @@ export function mutexFor(handle) {
|
|
|
802
870
|
if (callerPolicy != null) return callerPolicy(incoming);
|
|
803
871
|
return defaultCommitPolicy(incoming, context);
|
|
804
872
|
};
|
|
805
|
-
const applyOnAccept = ()=>{
|
|
873
|
+
const applyOnAccept = (notify = true)=>{
|
|
806
874
|
// Appended, never deduped: the log records what this commit enacted, at the
|
|
807
875
|
// position the head chained it.
|
|
808
876
|
for (const { token, verified, entryID } of acceptedEntries){
|
|
@@ -818,8 +886,11 @@ export function mutexFor(handle) {
|
|
|
818
886
|
}
|
|
819
887
|
this.#roster = candidateRoster;
|
|
820
888
|
this.#registry = candidateRegistry;
|
|
821
|
-
|
|
822
|
-
|
|
889
|
+
const emit = ()=>{
|
|
890
|
+
this.#notifyAccepted(surfaced, acceptedEntries.filter(({ verified })=>verified.entry.type === DEVICE_ENTRY_TYPE).map(({ verified })=>verified));
|
|
891
|
+
};
|
|
892
|
+
if (notify) emit();
|
|
893
|
+
return emit;
|
|
823
894
|
};
|
|
824
895
|
return {
|
|
825
896
|
callback: wrapCommitPolicy(combined, capture),
|
|
@@ -960,10 +1031,10 @@ export function mutexFor(handle) {
|
|
|
960
1031
|
//
|
|
961
1032
|
// `external: true` is reported, not just consumed to find the committer: a resync rejoin
|
|
962
1033
|
// is invisible to every before/after diff a caller could run — it changes no member DID
|
|
963
|
-
// (the roster already held it)
|
|
964
|
-
//
|
|
965
|
-
//
|
|
966
|
-
//
|
|
1034
|
+
// (the roster already held it); its leaf lands on the leftmost blank and may shift, but
|
|
1035
|
+
// the DID set is unchanged. A caller that must know the group's membership shifted has no
|
|
1036
|
+
// other way to see it, so the fact is surfaced here rather than discarded. Absent means a
|
|
1037
|
+
// member commit.
|
|
967
1038
|
const external = readExternalCommit(decoded);
|
|
968
1039
|
if (external != null) {
|
|
969
1040
|
// It IS a commit, so it gets a header even when the leaf credential will not parse to a
|
|
@@ -1008,8 +1079,11 @@ export function mutexFor(handle) {
|
|
|
1008
1079
|
/**
|
|
1009
1080
|
* Process a received MLS message (Commit, Proposal, or application). Accepts
|
|
1010
1081
|
* wire-form bytes (preferred, e.g. from commitInvite/removeMember) or a pre-decoded
|
|
1011
|
-
* ts-mls
|
|
1012
|
-
*
|
|
1082
|
+
* ts-mls framed message (legacy). The runtime `instanceof` selects the decode path.
|
|
1083
|
+
* `persist` covers accepted commits and proposals, not application messages or their
|
|
1084
|
+
* receive ratchet. It runs under this handle's mutex and must not call back into it.
|
|
1085
|
+
* It must write atomically: rejection means nothing was stored. Host callbacks run
|
|
1086
|
+
* after successful persist; a callback throw does not undo an advance.
|
|
1013
1087
|
*/ async processMessage(message, opts) {
|
|
1014
1088
|
let decoded = message;
|
|
1015
1089
|
if (message instanceof Uint8Array) {
|
|
@@ -1021,6 +1095,7 @@ export function mutexFor(handle) {
|
|
|
1021
1095
|
}
|
|
1022
1096
|
return mutexFor(this).run(async ()=>{
|
|
1023
1097
|
const { callback, capture, applyOnAccept } = await this.#prepareCommitPipeline(decoded, opts);
|
|
1098
|
+
const previousState = this.#state;
|
|
1024
1099
|
const result = await mlsProcessMessage({
|
|
1025
1100
|
context: this.#context,
|
|
1026
1101
|
state: this.#state,
|
|
@@ -1030,14 +1105,42 @@ export function mutexFor(handle) {
|
|
|
1030
1105
|
}
|
|
1031
1106
|
});
|
|
1032
1107
|
this.#state = result.newState;
|
|
1033
|
-
zeroAll(result.consumed);
|
|
1034
1108
|
if (result.kind === 'newState' && result.actionTaken === 'reject') {
|
|
1109
|
+
zeroAll(result.consumed);
|
|
1035
1110
|
throw new CommitRejectedError(capture.rejected?.proposals ?? [], capture.rejected?.senderLeafIndex);
|
|
1036
1111
|
}
|
|
1037
1112
|
if (result.kind === 'applicationMessage') {
|
|
1113
|
+
zeroAll(result.consumed);
|
|
1038
1114
|
return result.message;
|
|
1039
1115
|
}
|
|
1040
|
-
|
|
1116
|
+
if (opts?.persist != null) {
|
|
1117
|
+
const previousLedger = this.#ledger;
|
|
1118
|
+
const previousEntryBodies = this.#entryBodies;
|
|
1119
|
+
const previousRoster = this.#roster;
|
|
1120
|
+
const previousRegistry = this.#registry;
|
|
1121
|
+
// The accept callback appends to these collections. Give the tentative
|
|
1122
|
+
// state its own copies so rollback restores the exact old objects.
|
|
1123
|
+
this.#ledger = [
|
|
1124
|
+
...previousLedger
|
|
1125
|
+
];
|
|
1126
|
+
this.#entryBodies = new Map(previousEntryBodies);
|
|
1127
|
+
const notify = applyOnAccept(false);
|
|
1128
|
+
try {
|
|
1129
|
+
await opts.persist(this);
|
|
1130
|
+
} catch (error) {
|
|
1131
|
+
this.#state = previousState;
|
|
1132
|
+
this.#ledger = previousLedger;
|
|
1133
|
+
this.#entryBodies = previousEntryBodies;
|
|
1134
|
+
this.#roster = previousRoster;
|
|
1135
|
+
this.#registry = previousRegistry;
|
|
1136
|
+
throw error;
|
|
1137
|
+
}
|
|
1138
|
+
zeroAll(result.consumed);
|
|
1139
|
+
notify();
|
|
1140
|
+
} else {
|
|
1141
|
+
zeroAll(result.consumed);
|
|
1142
|
+
applyOnAccept();
|
|
1143
|
+
}
|
|
1041
1144
|
return null;
|
|
1042
1145
|
});
|
|
1043
1146
|
}
|
package/lib/group-info.d.ts
CHANGED
|
@@ -10,6 +10,14 @@ import type { GroupHandle } from './group-handle.js';
|
|
|
10
10
|
* caught and treated as "not a message".
|
|
11
11
|
*/
|
|
12
12
|
export declare function readMessageEpoch(bytes: Uint8Array): bigint | undefined;
|
|
13
|
+
/**
|
|
14
|
+
* Read an app PrivateMessage's cleartext authenticated data without an epoch key.
|
|
15
|
+
* This is an untrusted routing hint until decrypt authenticates the complete AAD.
|
|
16
|
+
* Total over arbitrary bytes: malformed or non-app frames return null.
|
|
17
|
+
*/
|
|
18
|
+
export declare function readMessageAAD(bytes: Uint8Array): Uint8Array | null;
|
|
19
|
+
/** Cleartext entry IDs are only a fetch hint; processMessage verifies every body. */
|
|
20
|
+
export declare function readCommitEntryIDs(bytes: Uint8Array): Array<string>;
|
|
13
21
|
export type InspectGroupInfoResult = {
|
|
14
22
|
/** The GroupInfo's epoch, read from its groupContext. */
|
|
15
23
|
epoch: bigint;
|
package/lib/group-info.js
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
|
-
import { createGroupInfoWithExternalPubAndRatchetTree, decode, encode, mlsMessageDecoder, mlsMessageEncoder, protocolVersions, wireformats } from 'ts-mls';
|
|
1
|
+
import { contentTypes, createGroupInfoWithExternalPubAndRatchetTree, decode, encode, mlsMessageDecoder, mlsMessageEncoder, protocolVersions, wireformats } from 'ts-mls';
|
|
2
2
|
import { GROUP_ANCHOR_EXTENSION_TYPE } from './anchor.js';
|
|
3
|
+
import { decodeControlEnvelope } from './envelope.js';
|
|
3
4
|
/**
|
|
4
5
|
* Read the MLS epoch from a framed message's cleartext header without decrypting.
|
|
5
6
|
* Advisory only — the header epoch is unauthenticated; use it to drop stale / buffer
|
|
@@ -26,6 +27,33 @@ import { GROUP_ANCHOR_EXTENSION_TYPE } from './anchor.js';
|
|
|
26
27
|
}
|
|
27
28
|
return undefined;
|
|
28
29
|
}
|
|
30
|
+
/**
|
|
31
|
+
* Read an app PrivateMessage's cleartext authenticated data without an epoch key.
|
|
32
|
+
* This is an untrusted routing hint until decrypt authenticates the complete AAD.
|
|
33
|
+
* Total over arbitrary bytes: malformed or non-app frames return null.
|
|
34
|
+
*/ export function readMessageAAD(bytes) {
|
|
35
|
+
try {
|
|
36
|
+
const message = decode(mlsMessageDecoder, bytes);
|
|
37
|
+
if (message?.wireformat !== wireformats.mls_private_message) return null;
|
|
38
|
+
const frame = message.privateMessage;
|
|
39
|
+
if (frame.contentType !== contentTypes.application) return null;
|
|
40
|
+
return frame.authenticatedData instanceof Uint8Array ? frame.authenticatedData : null;
|
|
41
|
+
} catch {
|
|
42
|
+
return null;
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
/** Cleartext entry IDs are only a fetch hint; processMessage verifies every body. */ export function readCommitEntryIDs(bytes) {
|
|
46
|
+
try {
|
|
47
|
+
const message = decode(mlsMessageDecoder, bytes);
|
|
48
|
+
if (message?.wireformat !== wireformats.mls_private_message) return [];
|
|
49
|
+
const frame = message.privateMessage;
|
|
50
|
+
if (frame.contentType !== contentTypes.commit) return [];
|
|
51
|
+
const envelope = decodeControlEnvelope(frame.authenticatedData);
|
|
52
|
+
return envelope.ok ? envelope.envelope.entries ?? [] : [];
|
|
53
|
+
} catch {
|
|
54
|
+
return [];
|
|
55
|
+
}
|
|
56
|
+
}
|
|
29
57
|
/**
|
|
30
58
|
* Read a framed MLSMessage(GroupInfo)'s epoch and ratchet-tree hash without joining
|
|
31
59
|
* or mutating state. Used to confirm an external-resync Commit was canonically
|
package/lib/group-welcome.d.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { type OwnIdentity } from '@kokuin/token';
|
|
2
|
+
import { type Welcome } from 'ts-mls';
|
|
2
3
|
import type { MemberCredential } from './credential.js';
|
|
3
4
|
import { GroupHandle } from './group-handle.js';
|
|
4
5
|
import type { GroupOptions, Invite, KeyPackageBundle } from './types.js';
|
|
@@ -10,9 +11,8 @@ export type ProcessWelcomeParams = {
|
|
|
10
11
|
identity: OwnIdentity;
|
|
11
12
|
invite: Invite;
|
|
12
13
|
/** Wire-form framed MLSMessage(Welcome) bytes (preferred), or a pre-decoded
|
|
13
|
-
* ts-mls Welcome object (legacy).
|
|
14
|
-
|
|
15
|
-
welcome: Uint8Array | unknown;
|
|
14
|
+
* ts-mls Welcome object (legacy). */
|
|
15
|
+
welcome: Uint8Array | Welcome;
|
|
16
16
|
keyPackageBundle: KeyPackageBundle;
|
|
17
17
|
ratchetTree?: unknown;
|
|
18
18
|
options?: GroupOptions;
|
package/lib/group.d.ts
CHANGED
|
@@ -3,6 +3,6 @@ export { type CreateGroupResult, createGroup, type RestoreGroupParams, restoreGr
|
|
|
3
3
|
export { createKeyPackageBundle, createLastResortKeyPackageBundle, LAST_RESORT_EXTENSION_TYPE, LAST_RESORT_LIFETIME_DAYS, makeMLSCredential, ORDINARY_KEY_PACKAGE_LIFETIME_DAYS, } from './group-credential.js';
|
|
4
4
|
export { addDevice, announceControllerBeacon, type DeviceWriteResult, labelDevice, registerDevice, revokeDevice, } from './group-device.js';
|
|
5
5
|
export { CommitRejectedError, GroupHandle, type GroupHandleEvents, type GroupHandleParams, type HeldLedgerEntry, type LedgerLogEntry, } from './group-handle.js';
|
|
6
|
-
export { type ExportGroupInfoParams, type ExportGroupInfoResult, exportGroupInfo, type GroupInfoBinding, type InspectGroupInfoResult, inspectGroupInfo, readGroupInfoBinding, readMessageEpoch, } from './group-info.js';
|
|
6
|
+
export { type ExportGroupInfoParams, type ExportGroupInfoResult, exportGroupInfo, type GroupInfoBinding, type InspectGroupInfoResult, inspectGroupInfo, readCommitEntryIDs, readGroupInfoBinding, readMessageAAD, readMessageEpoch, } from './group-info.js';
|
|
7
7
|
export { type RemoveMemberResult, removeMember } from './group-membership.js';
|
|
8
8
|
export { type JoinGroupExternalParams, type JoinGroupExternalResult, joinGroupExternal, type ProcessWelcomeOnceParams, type ProcessWelcomeParams, type ProcessWelcomeResult, processWelcome, processWelcomeOnce, } from './group-welcome.js';
|
package/lib/group.js
CHANGED
|
@@ -3,6 +3,6 @@ export { createGroup, restoreGroup } from './group-create.js';
|
|
|
3
3
|
export { createKeyPackageBundle, createLastResortKeyPackageBundle, LAST_RESORT_EXTENSION_TYPE, LAST_RESORT_LIFETIME_DAYS, makeMLSCredential, ORDINARY_KEY_PACKAGE_LIFETIME_DAYS } from './group-credential.js';
|
|
4
4
|
export { addDevice, announceControllerBeacon, labelDevice, registerDevice, revokeDevice } from './group-device.js';
|
|
5
5
|
export { CommitRejectedError, GroupHandle } from './group-handle.js';
|
|
6
|
-
export { exportGroupInfo, inspectGroupInfo, readGroupInfoBinding, readMessageEpoch } from './group-info.js';
|
|
6
|
+
export { exportGroupInfo, inspectGroupInfo, readCommitEntryIDs, readGroupInfoBinding, readMessageAAD, readMessageEpoch } from './group-info.js';
|
|
7
7
|
export { removeMember } from './group-membership.js';
|
|
8
8
|
export { joinGroupExternal, processWelcome, processWelcomeOnce } from './group-welcome.js';
|
package/lib/index.d.ts
CHANGED
|
@@ -10,7 +10,7 @@ export type { LeafBinding } from './device-proof.js';
|
|
|
10
10
|
export { CONTROL_ENVELOPE_VERSION, type ControlEnvelope, type DecodeResult, decodeControlEnvelope, encodeControlEnvelope, } from './envelope.js';
|
|
11
11
|
export { type EnvelopeFoldResult, foldEnvelope } from './envelope-fold.js';
|
|
12
12
|
export { type FoldDrop, type FoldInput, foldLedger, type LedgerReducer, } from './fold.js';
|
|
13
|
-
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, readMessageEpoch, registerDevice, removeMember, restoreGroup, revokeDevice, } from './group.js';
|
|
13
|
+
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, } from './group.js';
|
|
14
14
|
export { assertHeadMatches, buildLedgerHeadExtension, computeHead, decodeLedgerHead, encodeLedgerHead, extendHead, genesisHead, headsMatch, LEDGER_HEAD_VERSION, type LedgerHead, LedgerIncompleteError, readLedgerHead, readLedgerHeadExtension, } from './head.js';
|
|
15
15
|
export { decodeKeyPackage, decodePrivateKeyPackage, encodeKeyPackage, encodePrivateKeyPackage, keyPackageRef, } from './key-package-codec.js';
|
|
16
16
|
export { type LedgerEntry, ledgerEntryDigest, signLedgerEntry, type VerifiedLedgerEntry, verifyLedgerEntry, } from './ledger.js';
|
package/lib/index.js
CHANGED
|
@@ -7,7 +7,7 @@ export { createNobleCryptoProvider, nobleCryptoProvider } from './crypto.js';
|
|
|
7
7
|
export { CONTROL_ENVELOPE_VERSION, decodeControlEnvelope, encodeControlEnvelope } from './envelope.js';
|
|
8
8
|
export { foldEnvelope } from './envelope-fold.js';
|
|
9
9
|
export { foldLedger } from './fold.js';
|
|
10
|
-
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, readMessageEpoch, registerDevice, removeMember, restoreGroup, revokeDevice } from './group.js';
|
|
10
|
+
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';
|
|
11
11
|
export { assertHeadMatches, buildLedgerHeadExtension, computeHead, decodeLedgerHead, encodeLedgerHead, extendHead, genesisHead, headsMatch, LEDGER_HEAD_VERSION, LedgerIncompleteError, readLedgerHead, readLedgerHeadExtension } from './head.js';
|
|
12
12
|
export { decodeKeyPackage, decodePrivateKeyPackage, encodeKeyPackage, encodePrivateKeyPackage, keyPackageRef } from './key-package-codec.js';
|
|
13
13
|
export { ledgerEntryDigest, signLedgerEntry, verifyLedgerEntry } from './ledger.js';
|
package/lib/policy.js
CHANGED
|
@@ -76,6 +76,7 @@ function bytesEqual(a, b) {
|
|
|
76
76
|
for(let i = 0; i < expected.length; i++){
|
|
77
77
|
const got = candidate[i];
|
|
78
78
|
const want = expected[i];
|
|
79
|
+
if (got === undefined || want === undefined) return 'reject';
|
|
79
80
|
if (got.extensionType !== want.extensionType) return 'reject';
|
|
80
81
|
// Both sides must be raw bytes to compare. ts-mls's extensionsEqual isn't re-exported, so
|
|
81
82
|
// this hand-rolled compare only handles Uint8Array data; a decoded-object extension (e.g.
|
package/lib/welcome-refs.d.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { type Welcome } from 'ts-mls';
|
|
1
2
|
/**
|
|
2
3
|
* The KeyPackageRefs a Welcome names, base64 — one per set of encrypted group secrets it carries.
|
|
3
4
|
*
|
|
@@ -7,4 +8,4 @@
|
|
|
7
8
|
* Accepts framed `MLSMessage(Welcome)` bytes or a pre-decoded ts-mls Welcome, exactly as
|
|
8
9
|
* `processWelcome` does — the same value reaches both.
|
|
9
10
|
*/
|
|
10
|
-
export declare function welcomeKeyPackageRefs(welcome: Uint8Array |
|
|
11
|
+
export declare function welcomeKeyPackageRefs(welcome: Uint8Array | Welcome): Array<string>;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@kumiai/mls",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.10.0",
|
|
4
4
|
"description": "E2EE group identity and membership for Enkaku using MLS",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"mls",
|
|
@@ -42,8 +42,8 @@
|
|
|
42
42
|
"scripts": {
|
|
43
43
|
"build": "pnpm run build:clean && pnpm run build:js && pnpm run build:types",
|
|
44
44
|
"build:clean": "del lib",
|
|
45
|
-
"build:js": "swc src -d ./lib --config-file ../../node_modules/@kigu/dev/swc.json --strip-leading-paths",
|
|
46
|
-
"build:types": "tsc --emitDeclarationOnly --skipLibCheck",
|
|
45
|
+
"build:js": "del 'lib/**/*.js' && swc src -d ./lib --config-file ../../node_modules/@kigu/dev/swc.json --strip-leading-paths",
|
|
46
|
+
"build:types": "del 'lib/**/*.d.ts' 'lib/**/*.d.ts.map' && tsc --emitDeclarationOnly --skipLibCheck",
|
|
47
47
|
"test": "pnpm run test:types && pnpm run test:unit",
|
|
48
48
|
"test:types": "tsc --noEmit --skipLibCheck -p tsconfig.test.json",
|
|
49
49
|
"test:unit": "vitest run"
|