@kumiai/mls 0.10.6 → 0.10.8
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 +18 -1
- package/lib/codec.js +97 -41
- package/lib/errors.d.ts +3 -0
- package/lib/errors.js +6 -0
- package/lib/group-commit.js +12 -1
- package/lib/index.d.ts +2 -1
- package/lib/index.js +2 -1
- package/lib/lifecycle.js +17 -1
- package/lib/stale-leaf.d.ts +35 -0
- package/lib/stale-leaf.js +75 -0
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -12,10 +12,27 @@ Serialise reserve, build and consume against the source handle. Adopt the derive
|
|
|
12
12
|
Persistence must complete durably and leave storage unchanged on rejection.
|
|
13
13
|
The `@kumiai/mls-rpc` adapter supplies both reservation hooks to the RPC peer.
|
|
14
14
|
|
|
15
|
+
## Persisted client state
|
|
16
|
+
|
|
17
|
+
`encodeClientState` and `decodeClientState` support only format v2. Other versions throw an unsupported-version error.
|
|
18
|
+
Malformed or truncated v2 blobs return `undefined`, as does empty input.
|
|
19
|
+
There is no migration path from another client-state format.
|
|
20
|
+
|
|
21
|
+
The layout is a version byte (`2`), flags byte (`0` or `1`), optional reservation, body, and proposal references.
|
|
22
|
+
Flag `1` includes a uint64 epoch, uint32 generation, and consumed byte (`0` or `1`).
|
|
23
|
+
The ts-mls body has a uint32 byte length and a 64,000,000-byte decoding limit.
|
|
24
|
+
A uint32 count precedes UTF-8 references, each with a uint32 byte length.
|
|
25
|
+
References ascend strictly by JS string (UTF-16 code unit) ordering.
|
|
26
|
+
References preserve unapplied proposals whose sender is exactly leaf zero, working around ts-mls rc.13 dropping optional numeric zero.
|
|
27
|
+
All integers are big-endian. Invalid flags, consumed bytes, references, or trailing bytes make the blob malformed.
|
|
28
|
+
Decoding copies the body so ratcheting cannot zero secrets in stored bytes.
|
|
29
|
+
Decoding requires the body's canonical re-encoding to match its stored bytes before restoring leaf-zero senders.
|
|
30
|
+
`encodeClientState` throws `ClientStateReservationError` unless the reservation epoch is a uint64 bigint and its generation a uint32 integer.
|
|
31
|
+
|
|
15
32
|
## Capabilities
|
|
16
33
|
|
|
17
34
|
- `createGroup` — creator opens a new group as its sole member and first admin
|
|
18
|
-
- `createInvite` + `commitInvite` — an admin signs the invitee's role entry and produces the MLS Commit + Welcome
|
|
35
|
+
- `createInvite` + `commitInvite` — an admin signs the invitee's role entry and produces the MLS Commit + Welcome. In a lifecycle group, admitting a DID that still holds a stale leaf removes that leaf in the same commit when the new key package carries a strictly newer binding; two leaves for the DID throw `DuplicateMemberLeafError`
|
|
19
36
|
- `processWelcome` — invitee joins after folding the ledger the invite carries and checking its head
|
|
20
37
|
- `commitLedgerEntries` — an admin promotes or demotes by committing signed `kumiai.role` entries
|
|
21
38
|
- `removeMember` — an admin evicts a leaf and rotates keys
|
package/lib/codec.js
CHANGED
|
@@ -1,56 +1,112 @@
|
|
|
1
|
-
import { clientStateDecoder, clientStateEncoder,
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
*
|
|
5
|
-
*
|
|
6
|
-
|
|
7
|
-
|
|
1
|
+
import { clientStateDecoder, clientStateEncoder, encode } from 'ts-mls';
|
|
2
|
+
import { ClientStateReservationError } from './errors.js';
|
|
3
|
+
/** v2: flags, optional reservation, length-prefixed ts-mls body, then sorted leaf-zero refs.
|
|
4
|
+
* Reservation fields are epoch (uint64), generation (uint32), consumed (uint8).
|
|
5
|
+
* Body length, ref count and UTF-8 ref lengths are uint32. All integers are big-endian.
|
|
6
|
+
* Refs ascend by JS string (UTF-16 code unit) ordering.
|
|
7
|
+
* This is the only supported client-state format.
|
|
8
|
+
*/ const CLIENT_STATE_VERSION = 2;
|
|
8
9
|
const RESERVATION_BYTES = 13;
|
|
10
|
+
// Match ts-mls decode()'s default input limit, even though we call the decoder directly.
|
|
11
|
+
const MAX_BODY_BYTES = 64_000_000;
|
|
9
12
|
export function decodeClientState(encoded) {
|
|
10
|
-
// Too short to hold the version byte is a TRUNCATED read, not a version this build does not
|
|
11
|
-
// speak, and the two are separate diagnoses — the same split `@kumiai/mls-rpc`'s `openEntries`
|
|
12
|
-
// makes ("not a sealed blob" before "unsupported blob version"). Without this guard `encoded[0]`
|
|
13
|
-
// is `undefined` on an empty buffer, which falls into the version branch below and reports
|
|
14
|
-
// "unsupported client-state version undefined": the loudest possible way to misdescribe an
|
|
15
|
-
// empty store as a format from the future. Truncated bytes return `undefined`, as every other
|
|
16
|
-
// truncated read here does.
|
|
17
13
|
if (encoded.length === 0) return undefined;
|
|
18
|
-
//
|
|
19
|
-
|
|
20
|
-
// byte is not that kind of failure, so it throws instead of returning the same `undefined`
|
|
21
|
-
// a decode failure would. Without this, a version mismatch and a corrupted store are the
|
|
22
|
-
// same value of the same type and a caller cannot tell them apart.
|
|
23
|
-
if (encoded[0] !== CLIENT_STATE_VERSION && encoded[0] !== RESERVATION_STATE_VERSION) {
|
|
14
|
+
// Unsupported versions remain distinguishable from malformed storage.
|
|
15
|
+
if (encoded[0] !== CLIENT_STATE_VERSION) {
|
|
24
16
|
throw new Error(`decodeClientState: unsupported client-state version ${encoded[0]}`);
|
|
25
17
|
}
|
|
26
|
-
|
|
27
|
-
if (
|
|
28
|
-
if (encoded.length < 1 + RESERVATION_BYTES || encoded[13] !== 0 && encoded[13] !== 1) return undefined;
|
|
18
|
+
const flags = encoded[1];
|
|
19
|
+
if (flags !== 0 && flags !== 1) return undefined;
|
|
29
20
|
const view = new DataView(encoded.buffer, encoded.byteOffset, encoded.byteLength);
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
epoch: view.getBigUint64(
|
|
36
|
-
generation: view.getUint32(
|
|
37
|
-
consumed: encoded[
|
|
38
|
-
}
|
|
21
|
+
let offset = 2;
|
|
22
|
+
let reservation;
|
|
23
|
+
if (flags === 1) {
|
|
24
|
+
if (encoded.length < offset + RESERVATION_BYTES || encoded[14] !== 0 && encoded[14] !== 1) return undefined;
|
|
25
|
+
reservation = {
|
|
26
|
+
epoch: view.getBigUint64(offset),
|
|
27
|
+
generation: view.getUint32(offset + 8),
|
|
28
|
+
consumed: encoded[14] === 1
|
|
29
|
+
};
|
|
30
|
+
offset += RESERVATION_BYTES;
|
|
31
|
+
}
|
|
32
|
+
const readLength = ()=>{
|
|
33
|
+
if (encoded.length - offset < 4) return undefined;
|
|
34
|
+
const length = view.getUint32(offset);
|
|
35
|
+
offset += 4;
|
|
36
|
+
return length;
|
|
39
37
|
};
|
|
38
|
+
const bodyLength = readLength();
|
|
39
|
+
if (bodyLength === undefined || bodyLength > MAX_BODY_BYTES || bodyLength > encoded.length - offset - 4) {
|
|
40
|
+
return undefined;
|
|
41
|
+
}
|
|
42
|
+
// ts-mls secrets are views. Even Buffer inputs must be copied before ratcheting zeroes them.
|
|
43
|
+
const bodyCopy = new Uint8Array(encoded.subarray(offset, offset + bodyLength));
|
|
44
|
+
offset += bodyLength;
|
|
45
|
+
const refCount = readLength();
|
|
46
|
+
if (refCount === undefined || refCount > Math.floor((encoded.length - offset) / 4)) {
|
|
47
|
+
return undefined;
|
|
48
|
+
}
|
|
49
|
+
try {
|
|
50
|
+
const result = clientStateDecoder(bodyCopy, 0);
|
|
51
|
+
if (result === undefined || result[1] !== bodyCopy.length) return undefined;
|
|
52
|
+
const state = result[0];
|
|
53
|
+
// rc.13 accepts invalid optional tags and elements extending past an inner vector boundary.
|
|
54
|
+
const canonicalBody = encode(clientStateEncoder, state);
|
|
55
|
+
if (canonicalBody.length !== bodyCopy.length || !canonicalBody.every((byte, index)=>byte === bodyCopy[index])) {
|
|
56
|
+
return undefined;
|
|
57
|
+
}
|
|
58
|
+
const textDecoder = new TextDecoder('utf-8', {
|
|
59
|
+
fatal: true,
|
|
60
|
+
ignoreBOM: true
|
|
61
|
+
});
|
|
62
|
+
let previousRef;
|
|
63
|
+
for(let index = 0; index < refCount; index++){
|
|
64
|
+
const refLength = readLength();
|
|
65
|
+
if (refLength === undefined || refLength > encoded.length - offset) return undefined;
|
|
66
|
+
const ref = textDecoder.decode(encoded.subarray(offset, offset + refLength));
|
|
67
|
+
offset += refLength;
|
|
68
|
+
if (previousRef !== undefined && ref <= previousRef) return undefined;
|
|
69
|
+
if (!Object.hasOwn(state.unappliedProposals, ref)) return undefined;
|
|
70
|
+
const proposal = state.unappliedProposals[ref];
|
|
71
|
+
if (proposal === undefined || proposal.senderLeafIndex !== undefined) return undefined;
|
|
72
|
+
proposal.senderLeafIndex = 0;
|
|
73
|
+
previousRef = ref;
|
|
74
|
+
}
|
|
75
|
+
if (offset !== encoded.length) return undefined;
|
|
76
|
+
if (reservation !== undefined) state.handshakeReservation = reservation;
|
|
77
|
+
return state;
|
|
78
|
+
} catch {
|
|
79
|
+
return undefined;
|
|
80
|
+
}
|
|
40
81
|
}
|
|
41
82
|
export function encodeClientState(state) {
|
|
42
|
-
const body = encode(clientStateEncoder, state);
|
|
43
83
|
const reservation = state.handshakeReservation;
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
84
|
+
if (reservation != null && (typeof reservation.epoch !== 'bigint' || reservation.epoch < 0n || reservation.epoch > 0xffffffffffffffffn || !Number.isInteger(reservation.generation) || reservation.generation < 0 || reservation.generation > 0xffffffff)) {
|
|
85
|
+
throw new ClientStateReservationError();
|
|
86
|
+
}
|
|
87
|
+
const body = encode(clientStateEncoder, state);
|
|
88
|
+
// rc.13 optionalEncoder drops numeric zero. Preserve only exact zero senders separately.
|
|
89
|
+
const textEncoder = new TextEncoder();
|
|
90
|
+
const refs = Object.keys(state.unappliedProposals).filter((ref)=>state.unappliedProposals[ref]?.senderLeafIndex === 0).sort().map((ref)=>textEncoder.encode(ref));
|
|
91
|
+
const header = reservation == null ? 2 : 2 + RESERVATION_BYTES;
|
|
92
|
+
const out = new Uint8Array(header + 8 + body.length + refs.reduce((length, ref)=>length + 4 + ref.length, 0));
|
|
93
|
+
const view = new DataView(out.buffer);
|
|
94
|
+
out[0] = CLIENT_STATE_VERSION;
|
|
95
|
+
out[1] = reservation == null ? 0 : 1;
|
|
47
96
|
if (reservation != null) {
|
|
48
|
-
|
|
49
|
-
view.
|
|
50
|
-
|
|
51
|
-
|
|
97
|
+
view.setBigUint64(2, reservation.epoch);
|
|
98
|
+
view.setUint32(10, reservation.generation);
|
|
99
|
+
out[14] = reservation.consumed ? 1 : 0;
|
|
100
|
+
}
|
|
101
|
+
view.setUint32(header, body.length);
|
|
102
|
+
out.set(body, header + 4);
|
|
103
|
+
view.setUint32(header + 4 + body.length, refs.length);
|
|
104
|
+
let offset = header + 8 + body.length;
|
|
105
|
+
for (const ref of refs){
|
|
106
|
+
view.setUint32(offset, ref.length);
|
|
107
|
+
out.set(ref, offset + 4);
|
|
108
|
+
offset += 4 + ref.length;
|
|
52
109
|
}
|
|
53
|
-
out.set(body, header);
|
|
54
110
|
return out;
|
|
55
111
|
}
|
|
56
112
|
export function sanitizeRatchetTree(tree) {
|
package/lib/errors.d.ts
CHANGED
package/lib/errors.js
CHANGED
|
@@ -49,3 +49,9 @@ export class HandshakeReservationError extends Error {
|
|
|
49
49
|
this.name = 'HandshakeReservationError';
|
|
50
50
|
}
|
|
51
51
|
}
|
|
52
|
+
export class ClientStateReservationError extends Error {
|
|
53
|
+
constructor(){
|
|
54
|
+
super('Handshake reservation epoch must be a uint64 bigint and generation a uint32 integer');
|
|
55
|
+
this.name = 'ClientStateReservationError';
|
|
56
|
+
}
|
|
57
|
+
}
|
package/lib/group-commit.js
CHANGED
|
@@ -12,6 +12,7 @@ import { ledgerEntryDigest, signLedgerEntry, verifyLedgerEntry } from './ledger.
|
|
|
12
12
|
import { prepareLifecycleGate, rejectionReason, validateEntry } from './lifecycle.js';
|
|
13
13
|
import { authority, controllerOf, DEVICE_ENTRY_TYPE } from './registry.js';
|
|
14
14
|
import { ROLE_ENTRY_TYPE } from './roster.js';
|
|
15
|
+
import { staleLeafIndex } from './stale-leaf.js';
|
|
15
16
|
/** The supplied key package names a different identity from the invite's recipient. */ export class InviteRecipientMismatchError extends Error {
|
|
16
17
|
#groupID;
|
|
17
18
|
#expectedDID;
|
|
@@ -367,9 +368,19 @@ import { ROLE_ENTRY_TYPE } from './roster.js';
|
|
|
367
368
|
keyPackage
|
|
368
369
|
}
|
|
369
370
|
};
|
|
371
|
+
// A lifecycle group re-admitting a device replaces the leaf it still holds for that DID.
|
|
372
|
+
const stale = group.anchor.controller == null ? undefined : staleLeafIndex(group.state.ratchetTree, keyPackage.leafNode);
|
|
370
373
|
const result = await commitWithEntries({
|
|
371
374
|
group,
|
|
372
|
-
extraProposals: [
|
|
375
|
+
extraProposals: stale == null ? [
|
|
376
|
+
addProposal
|
|
377
|
+
] : [
|
|
378
|
+
{
|
|
379
|
+
proposalType: defaultProposalTypes.remove,
|
|
380
|
+
remove: {
|
|
381
|
+
removed: stale
|
|
382
|
+
}
|
|
383
|
+
},
|
|
373
384
|
addProposal
|
|
374
385
|
],
|
|
375
386
|
enacted,
|
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 { HandshakeReservationError, HandshakeWindowConfigError, HandshakeWindowError, LeafBindingError, type LeafBindingReason, LeafLapsedError, type LeafLapsedReason, RevokeProofError, type RevokeProofReason, } from './errors.js';
|
|
13
|
+
export { ClientStateReservationError, 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';
|
|
@@ -25,5 +25,6 @@ export { confirmationKey, confirmationTag, type OpenedRecoveryVerdict, openRecov
|
|
|
25
25
|
export { authority, beaconOf, type ControllerBeacon, type ControllerProjection, controllerOf, DEVICE_ENTRY_TYPE, type DeviceOp, type DeviceRecord, type DeviceRegistry, type DeviceValue, denySetOf, foldControl, type Revocation, type RevokedEffect, registrySeed, revocationOf, } from './registry.js';
|
|
26
26
|
export { adminCount, foldRoster, type GroupPermission, ROLE_ENTRY_TYPE, type RoleValue, type RosterState, roleReducer, } from './roster.js';
|
|
27
27
|
export { mergeReceiveSecretTree } from './secret-tree.js';
|
|
28
|
+
export { DuplicateMemberLeafError } from './stale-leaf.js';
|
|
28
29
|
export type { GroupOptions, Invite, KeyPackageBundle } from './types.js';
|
|
29
30
|
export { welcomeKeyPackageRefs } from './welcome-refs.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 { HandshakeReservationError, HandshakeWindowConfigError, HandshakeWindowError, LeafBindingError, LeafLapsedError, RevokeProofError } from './errors.js';
|
|
10
|
+
export { ClientStateReservationError, 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';
|
|
@@ -22,4 +22,5 @@ export { confirmationKey, confirmationTag, openRecoveryVerdict, recoverySignerEl
|
|
|
22
22
|
export { authority, beaconOf, controllerOf, DEVICE_ENTRY_TYPE, denySetOf, foldControl, registrySeed, revocationOf } from './registry.js';
|
|
23
23
|
export { adminCount, foldRoster, ROLE_ENTRY_TYPE, roleReducer } from './roster.js';
|
|
24
24
|
export { mergeReceiveSecretTree } from './secret-tree.js';
|
|
25
|
+
export { DuplicateMemberLeafError } from './stale-leaf.js';
|
|
25
26
|
export { welcomeKeyPackageRefs } from './welcome-refs.js';
|
package/lib/lifecycle.js
CHANGED
|
@@ -12,6 +12,7 @@ import { HISTORY_HORIZON, historySize } from './history.js';
|
|
|
12
12
|
import { isEvidencedChild, verifyLifecycleProof } from './lifecycle-proof.js';
|
|
13
13
|
import { evaluateGroupContextExtensions } from './policy.js';
|
|
14
14
|
import { DEVICE_ENTRY_TYPE, denySetOf, mayReadmitResetDevice } from './registry.js';
|
|
15
|
+
import { assertNewerBinding, stalePairedAdd } from './stale-leaf.js';
|
|
15
16
|
export function rejectionReason(error) {
|
|
16
17
|
if (error instanceof LeafLapsedError) return 'lapse';
|
|
17
18
|
if (error instanceof LeafBindingError) {
|
|
@@ -303,7 +304,22 @@ export async function validateWelcomeTree(group) {
|
|
|
303
304
|
// A self-removal proposal is honoured only when another member commits it.
|
|
304
305
|
const selfRemoval = proposalSender === target && (incoming.kind === 'proposal' || incoming.senderLeafIndex !== target);
|
|
305
306
|
const authorised = proofs.length > 0 || lapsed.has(target) || selfRemoval;
|
|
306
|
-
|
|
307
|
+
// Admitting a fresh key package may replace its DID's one stale leaf in the same commit.
|
|
308
|
+
const replacement = controller == null || authorised || old == null || incoming.kind !== 'commit' || incoming.senderLeafIndex == null ? undefined : stalePairedAdd({
|
|
309
|
+
before,
|
|
310
|
+
target,
|
|
311
|
+
proposals,
|
|
312
|
+
committer: incoming.senderLeafIndex,
|
|
313
|
+
denied: [
|
|
314
|
+
denySetOf(group.registry),
|
|
315
|
+
denySetOf(candidateRegistry)
|
|
316
|
+
]
|
|
317
|
+
});
|
|
318
|
+
if (replacement != null && old != null) {
|
|
319
|
+
checkEntry(group, replacement, old);
|
|
320
|
+
assertNewerBinding(replacement, old);
|
|
321
|
+
}
|
|
322
|
+
if (controller != null && (old == null || !(authorised || replacement != null))) throw new Error('Unauthorised Remove');
|
|
307
323
|
tree[target * 2] = undefined;
|
|
308
324
|
break;
|
|
309
325
|
}
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import { type ClientState, type LeafNode, type ProposalWithSender } from 'ts-mls';
|
|
2
|
+
/** More than one leaf of a lifecycle group names the DID an admission would replace. */
|
|
3
|
+
export declare class DuplicateMemberLeafError extends Error {
|
|
4
|
+
#private;
|
|
5
|
+
constructor(did: string);
|
|
6
|
+
get did(): string;
|
|
7
|
+
}
|
|
8
|
+
/**
|
|
9
|
+
* A replacement carries a controller grant issued strictly after the replaced leaf's, so a key
|
|
10
|
+
* package published under the leaf's current grant cannot evict that leaf.
|
|
11
|
+
*/
|
|
12
|
+
export declare function assertNewerBinding(leaf: LeafNode, replaced: LeafNode): void;
|
|
13
|
+
/**
|
|
14
|
+
* The leaf an admission of `leaf` replaces: the one leaf the tree already holds for the same DID,
|
|
15
|
+
* or `undefined` when it holds none. Two or more such leaves are ambiguous and refused.
|
|
16
|
+
*/
|
|
17
|
+
export declare function staleLeafIndex(tree: ClientState['ratchetTree'], leaf: LeafNode): number | undefined;
|
|
18
|
+
export type StaleLeafReplacementParams = {
|
|
19
|
+
/** The tree before the commit. */
|
|
20
|
+
before: ClientState['ratchetTree'];
|
|
21
|
+
/** The leaf a Remove targets. */
|
|
22
|
+
target: number;
|
|
23
|
+
/** Every proposal the commit carries. */
|
|
24
|
+
proposals: Array<ProposalWithSender>;
|
|
25
|
+
/** The committer's leaf. */
|
|
26
|
+
committer: number;
|
|
27
|
+
/** The deny sets the replaced DID must be absent from. */
|
|
28
|
+
denied: Array<ReadonlySet<string>>;
|
|
29
|
+
};
|
|
30
|
+
/**
|
|
31
|
+
* The added leaf that replaces `target` in the same commit, when the commit is an admission of a
|
|
32
|
+
* fresh key package for the DID whose only leaf `target` is. The caller still judges that leaf as
|
|
33
|
+
* the replacement of `target`; this only finds the pairing.
|
|
34
|
+
*/
|
|
35
|
+
export declare function stalePairedAdd(params: StaleLeafReplacementParams): LeafNode | undefined;
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
import { normalizeDID } from '@kokuin/token';
|
|
2
|
+
import { defaultCredentialTypes, defaultProposalTypes, isDefaultCredential, isDefaultProposal, nodeTypes } from 'ts-mls';
|
|
3
|
+
import { readCapability } from './capability.js';
|
|
4
|
+
import { parseMLSCredentialIdentity } from './credential.js';
|
|
5
|
+
import { LeafBindingError } from './errors.js';
|
|
6
|
+
/** More than one leaf of a lifecycle group names the DID an admission would replace. */ export class DuplicateMemberLeafError extends Error {
|
|
7
|
+
#did;
|
|
8
|
+
constructor(did){
|
|
9
|
+
super(`The group holds more than one leaf for ${did}`);
|
|
10
|
+
this.name = 'DuplicateMemberLeafError';
|
|
11
|
+
this.#did = did;
|
|
12
|
+
}
|
|
13
|
+
get did() {
|
|
14
|
+
return this.#did;
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
function leafDID(leaf) {
|
|
18
|
+
if (!isDefaultCredential(leaf.credential) || leaf.credential.credentialType !== defaultCredentialTypes.basic) return undefined;
|
|
19
|
+
try {
|
|
20
|
+
const { id } = parseMLSCredentialIdentity(leaf.credential.identity);
|
|
21
|
+
return id === '' ? undefined : normalizeDID(id);
|
|
22
|
+
} catch {
|
|
23
|
+
return undefined;
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
function bindingTime(leaf) {
|
|
27
|
+
if (!isDefaultCredential(leaf.credential) || leaf.credential.credentialType !== defaultCredentialTypes.basic) return undefined;
|
|
28
|
+
const binding = parseMLSCredentialIdentity(leaf.credential.identity).controller;
|
|
29
|
+
return binding == null ? undefined : readCapability(binding.capability).payload.iat;
|
|
30
|
+
}
|
|
31
|
+
/**
|
|
32
|
+
* A replacement carries a controller grant issued strictly after the replaced leaf's, so a key
|
|
33
|
+
* package published under the leaf's current grant cannot evict that leaf.
|
|
34
|
+
*/ export function assertNewerBinding(leaf, replaced) {
|
|
35
|
+
const next = bindingTime(leaf);
|
|
36
|
+
const previous = bindingTime(replaced);
|
|
37
|
+
if (next == null || previous == null || next <= previous) throw new LeafBindingError('renewal-order');
|
|
38
|
+
}
|
|
39
|
+
function leafIndicesOf(tree, did) {
|
|
40
|
+
const indices = [];
|
|
41
|
+
for (const [position, node] of tree.entries()){
|
|
42
|
+
if (node?.nodeType === nodeTypes.leaf && leafDID(node.leaf) === did) indices.push(position / 2);
|
|
43
|
+
}
|
|
44
|
+
return indices;
|
|
45
|
+
}
|
|
46
|
+
/**
|
|
47
|
+
* The leaf an admission of `leaf` replaces: the one leaf the tree already holds for the same DID,
|
|
48
|
+
* or `undefined` when it holds none. Two or more such leaves are ambiguous and refused.
|
|
49
|
+
*/ export function staleLeafIndex(tree, leaf) {
|
|
50
|
+
const did = leafDID(leaf);
|
|
51
|
+
if (did == null) return undefined;
|
|
52
|
+
const indices = leafIndicesOf(tree, did);
|
|
53
|
+
if (indices.length > 1) throw new DuplicateMemberLeafError(did);
|
|
54
|
+
return indices[0];
|
|
55
|
+
}
|
|
56
|
+
/**
|
|
57
|
+
* The added leaf that replaces `target` in the same commit, when the commit is an admission of a
|
|
58
|
+
* fresh key package for the DID whose only leaf `target` is. The caller still judges that leaf as
|
|
59
|
+
* the replacement of `target`; this only finds the pairing.
|
|
60
|
+
*/ export function stalePairedAdd(params) {
|
|
61
|
+
const { before, target, proposals, committer, denied } = params;
|
|
62
|
+
if (target === committer) return undefined;
|
|
63
|
+
const node = before[target * 2];
|
|
64
|
+
if (node?.nodeType !== nodeTypes.leaf) return undefined;
|
|
65
|
+
const did = leafDID(node.leaf);
|
|
66
|
+
if (did == null || leafIndicesOf(before, did).length !== 1) return undefined;
|
|
67
|
+
if (denied.some((set)=>[
|
|
68
|
+
...set
|
|
69
|
+
].some((held)=>normalizeDID(held) === did))) return undefined;
|
|
70
|
+
const removes = proposals.filter(({ proposal })=>isDefaultProposal(proposal) && proposal.proposalType === defaultProposalTypes.remove && proposal.remove.removed === target);
|
|
71
|
+
const adds = proposals.flatMap(({ proposal })=>isDefaultProposal(proposal) && proposal.proposalType === defaultProposalTypes.add && leafDID(proposal.add.keyPackage.leafNode) === did ? [
|
|
72
|
+
proposal.add.keyPackage.leafNode
|
|
73
|
+
] : []);
|
|
74
|
+
return removes.length === 1 && adds.length === 1 ? adds[0] : undefined;
|
|
75
|
+
}
|