@kumiai/mls 0.13.5 → 0.13.7

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 CHANGED
@@ -46,6 +46,11 @@ Decoding requires the body's canonical re-encoding to match its stored bytes bef
46
46
  a host has atomically saved that state and its pending delivery record
47
47
  - `readMessageAAD(bytes)` — read a PrivateMessage's cleartext authenticated data without a key;
48
48
  returns `null` for unreadable bytes and never throws
49
+ - `decryptFramed(handle, { message, expectedAAD })` — `GroupHandle.decrypt` that throws when the
50
+ authenticated leaf has no nameable sender, so `senderDID` is always a string
51
+ - `foldAdminRoster({ entries, anchor, groupID, throughPosition })` + `selectRoleEntries(ledger)` —
52
+ the admin set folded from a handle's ledger, optionally as it stood at a ledger position.
53
+ Positions index the whole ledger, so they compare with non-role entries
49
54
 
50
55
  ## Persisting a staged app open
51
56
 
@@ -1,5 +1,6 @@
1
1
  import { assertCapabilityToken, assertNonExpired, assertValidDelegation, assertValidIssuedAt, assertValidNotBefore, checkCapability, hasPermission } from '@kokuin/capability';
2
2
  import { decodeMultibase, decodePeer4, getAlgorithmAndPublicKey, getSignatureInfo, getVerifier, isPeer4, normalizeDID, verifyToken } from '@kokuin/token';
3
+ import { constantTimeEqual } from '@sozai/bytes';
3
4
  import { fromB64U, fromUTF } from '@sozai/codec';
4
5
  import { defaultCredentialTypes } from 'ts-mls';
5
6
  import { assertCapabilityLifetime, assertControllerGrant, capabilityKey, MAX_LEAF_LIFETIME, MAX_TRUSTED_GRANT_LIFETIME, MLS_LEAF_ACT, MLS_LEAF_RES, readCapability } from './capability.js';
@@ -14,15 +15,6 @@ export { MLS_LEAF_ACT, MLS_LEAF_RES } from './capability.js';
14
15
  /** The action a management capability must grant to mutate a profile's device registry. */ export const MLS_DEVICES_ACT = 'manage';
15
16
  /** The resource half — kumiai-namespaced and group-independent. */ export const MLS_DEVICES_RES = 'kumiai/devices';
16
17
  const EMPTY_DENY = new Set();
17
- function constantTimeEqual(a, b) {
18
- if (a.length !== b.length) return false;
19
- let diff = 0;
20
- for(let i = 0; i < a.length; i++){
21
- // biome-ignore lint/style/noNonNullAssertion: index is within bounds
22
- diff |= a[i] ^ b[i];
23
- }
24
- return diff === 0;
25
- }
26
18
  /**
27
19
  * Whether `signaturePublicKey` is the key the parsed identity's DID authenticates with — the
28
20
  * floating-leaf binding, shared by floating validation and the bound branch (a bound leaf is a
package/lib/capability.js CHANGED
@@ -1,7 +1,8 @@
1
1
  import { audienceConfirmation, hasPermission } from '@kokuin/capability';
2
2
  import { tryDecodeKey } from '@kokuin/controller';
3
3
  import { isSignedToken, normalizeDID, stringifyToken } from '@kokuin/token';
4
- import { b64uToJSON } from '@sozai/codec';
4
+ import { equalBytes } from '@sozai/bytes';
5
+ import { b64uToJSON } from '@sozai/json';
5
6
  import { LeafBindingError } from './errors.js';
6
7
  /** The action a device capability must grant for a leaf to authenticate as a kumiai MLS leaf. */ export const MLS_LEAF_ACT = 'authenticate';
7
8
  /** The resource half of that grant — kumiai-namespaced, group-independent. */ export const MLS_LEAF_RES = 'kumiai/mls-leaf';
@@ -127,7 +128,7 @@ export async function mintLeafCapability(params) {
127
128
  throw new LeafBindingError('issuer-mismatch');
128
129
  }
129
130
  const key = capabilityKey(parent.payload);
130
- if (!key.publicKey.every((byte, index)=>byte === params.signer.publicKey[index]) || key.publicKey.length !== params.signer.publicKey.length) {
131
+ if (!equalBytes(key.publicKey, params.signer.publicKey)) {
131
132
  throw new LeafBindingError('issuer-mismatch');
132
133
  }
133
134
  if (payload.exp > parent.payload.exp) throw new LeafBindingError('child-outlives-parent');
package/lib/codec.js CHANGED
@@ -1,3 +1,4 @@
1
+ import { equalBytes } from '@sozai/bytes';
1
2
  import { clientStateDecoder, clientStateEncoder, encode } from 'ts-mls';
2
3
  import { ClientStateReservationError } from './errors.js';
3
4
  /** v2: flags, optional reservation, length-prefixed ts-mls body, then sorted leaf-zero refs.
@@ -52,7 +53,7 @@ export function decodeClientState(encoded) {
52
53
  const state = result[0];
53
54
  // rc.13 accepts invalid optional tags and elements extending past an inner vector boundary.
54
55
  const canonicalBody = encode(clientStateEncoder, state);
55
- if (canonicalBody.length !== bodyCopy.length || !canonicalBody.every((byte, index)=>byte === bodyCopy[index])) {
56
+ if (!equalBytes(canonicalBody, bodyCopy)) {
56
57
  return undefined;
57
58
  }
58
59
  const textDecoder = new TextDecoder('utf-8', {
package/lib/crypto.js CHANGED
@@ -16,19 +16,11 @@ import { expand as hkdfExpand, extract as hkdfExtract } from '@noble/hashes/hkdf
16
16
  import { hmac } from '@noble/hashes/hmac.js';
17
17
  import { sha256, sha384, sha512 } from '@noble/hashes/sha2.js';
18
18
  import { concatBytes } from '@noble/hashes/utils.js';
19
+ import { constantTimeEqual } from '@sozai/bytes';
19
20
  import { createRuntime } from '@sozai/runtime';
20
21
  // ---------------------------------------------------------------------------
21
22
  // Helpers
22
23
  // ---------------------------------------------------------------------------
23
- function constantTimeEqual(a, b) {
24
- if (a.length !== b.length) return false;
25
- let diff = 0;
26
- for(let i = 0; i < a.length; i++){
27
- // biome-ignore lint/style/noNonNullAssertion: index is within bounds
28
- diff |= a[i] ^ b[i];
29
- }
30
- return diff === 0;
31
- }
32
24
  function i2osp(value, w) {
33
25
  const result = new Uint8Array(w);
34
26
  let n = value;
package/lib/frame.d.ts ADDED
@@ -0,0 +1,15 @@
1
+ import type { GroupHandle } from './group-handle.js';
2
+ export type DecryptFramedParams = {
3
+ message: Uint8Array;
4
+ expectedAAD?: Uint8Array;
5
+ };
6
+ export type DecryptedFrame = {
7
+ payload: Uint8Array;
8
+ senderDID: string;
9
+ };
10
+ /**
11
+ * Open an application frame and require a nameable sender. `GroupHandle.decrypt` omits
12
+ * `senderDID` when the authenticated leaf holds no parsable credential; any placeholder
13
+ * would pass an unnamed author off as an authenticated one, so this throws instead.
14
+ */
15
+ export declare function decryptFramed(handle: GroupHandle, params: DecryptFramedParams): Promise<DecryptedFrame>;
package/lib/frame.js ADDED
@@ -0,0 +1,14 @@
1
+ /**
2
+ * Open an application frame and require a nameable sender. `GroupHandle.decrypt` omits
3
+ * `senderDID` when the authenticated leaf holds no parsable credential; any placeholder
4
+ * would pass an unnamed author off as an authenticated one, so this throws instead.
5
+ */ export async function decryptFramed(handle, params) {
6
+ const { payload, senderDID } = await handle.decrypt(params);
7
+ if (senderDID == null) {
8
+ throw new Error('MLS application message opened at a leaf with no nameable sender');
9
+ }
10
+ return {
11
+ payload,
12
+ senderDID
13
+ };
14
+ }
@@ -32,6 +32,12 @@ import type { GroupOptions, YieldOptions } from './types.js';
32
32
  * A step is one KDF expansion, so the bound on a forged generation stays cheap.
33
33
  */
34
34
  export declare const KUMIAI_KEY_RETENTION_CONFIG: Readonly<KeyRetentionConfig>;
35
+ /**
36
+ * Whether a decrypt failed because the frame's generation fell out of the retained keys, or
37
+ * the frame already opened once: no later state opens it either. ts-mls raises a bare
38
+ * `ValidationError` with no code, so this matches the message.
39
+ */
40
+ export declare function isGenerationExpired(error: unknown): boolean;
35
41
  /** A context's client config, with kumiai's key retention when none is given. */
36
42
  export declare function kumiaiClientConfig(): ClientConfig;
37
43
  /** Copy a client config without sharing its mutable parts with the source context. */
@@ -36,6 +36,13 @@ const EMPTY_DENY = new Set();
36
36
  retainKeysForEpochs: 1,
37
37
  maximumForwardRatchetSteps: 512
38
38
  });
39
+ /**
40
+ * Whether a decrypt failed because the frame's generation fell out of the retained keys, or
41
+ * the frame already opened once: no later state opens it either. ts-mls raises a bare
42
+ * `ValidationError` with no code, so this matches the message.
43
+ */ export function isGenerationExpired(error) {
44
+ return error instanceof Error && error.name === 'ValidationError' && error.message === 'Desired gen in the past';
45
+ }
39
46
  /** A context's client config, with kumiai's key retention when none is given. */ export function kumiaiClientConfig() {
40
47
  return {
41
48
  keyRetentionConfig: {
@@ -1,10 +1,10 @@
1
- import { type OwnIdentity } from '@kokuin/token';
1
+ import { type MultiKeyIdentity, type OwnIdentity } from '@kokuin/token';
2
2
  import type { Now } from '@sozai/runtime';
3
3
  import { type Credential } from 'ts-mls';
4
4
  import type { ControllerBinding } from './credential.js';
5
5
  import type { GroupOptions, KeyPackageBundle } from './types.js';
6
6
  export type MakeMLSCredentialParams = {
7
- identity: OwnIdentity;
7
+ identity: OwnIdentity | MultiKeyIdentity;
8
8
  controller?: ControllerBinding;
9
9
  };
10
10
  export declare function makeMLSCredential({ identity, controller }: MakeMLSCredentialParams): Credential;
@@ -10,15 +10,15 @@ import { registryForLog } from './registry.js';
10
10
  export function makeMLSCredential({ identity, controller }) {
11
11
  const id = identity.id;
12
12
  const isPeer = isPeer4(id);
13
- if (isPeer && !('longForm' in identity && typeof identity.longForm === 'string')) {
14
- throw new Error('peer:4 identity is missing longForm; only identities from createIdentity can be used as MLS members');
15
- }
16
13
  const payload = {
17
14
  v: 1,
18
15
  id
19
16
  };
20
17
  if (controller != null) payload.controller = controller;
21
18
  if (isPeer) {
19
+ if (!('longForm' in identity) || typeof identity.longForm !== 'string') {
20
+ throw new Error('peer:4 identity is missing longForm; only identities from createIdentity can be used as MLS members');
21
+ }
22
22
  payload.longForm = identity.longForm;
23
23
  }
24
24
  return {
@@ -1,5 +1,6 @@
1
1
  import type { CryptoProvider } from '@kokuin/crypto';
2
2
  import { type CryptoOptions } from '@kokuin/token';
3
+ import { type Mutex } from '@sozai/async';
3
4
  import { EventEmitter, type EventsSource } from '@sozai/event';
4
5
  import { type IncomingMessageCallback, type MlsContext, type MlsFramedMessage, type ProposalWithSender } from 'ts-mls';
5
6
  import { type GroupAnchor } from './anchor.js';
@@ -9,7 +10,6 @@ import { type LeafBinding } from './device-proof.js';
9
10
  import { type VerifiedLedgerEntry } from './ledger.js';
10
11
  import { type CommitRejectionReason } from './lifecycle.js';
11
12
  import type { ProofRef } from './member-root.js';
12
- import { type Mutex } from './mutex.js';
13
13
  import { type CommitPolicyContext } from './policy.js';
14
14
  import { type DeviceOp, type DeviceRegistry } from './registry.js';
15
15
  import type { RosterState } from './roster.js';
@@ -1,5 +1,6 @@
1
1
  import { assertTimeClaimsValid, decodeSignedToken, normalizeDID } from '@kokuin/token';
2
- import { maybeYield } from '@sozai/async';
2
+ import { createMutex, maybeYield } from '@sozai/async';
3
+ import { equalBytes } from '@sozai/bytes';
3
4
  import { toB64 } from '@sozai/codec';
4
5
  import { EventEmitter } from '@sozai/event';
5
6
  import { contentTypes, createApplicationMessage, createProposal, decode, defaultCredentialTypes, defaultKeyRetentionConfig, defaultProposalTypes, encode, isDefaultCredential, isDefaultProposal, leafNodeSources, mlsExporter, mlsMessageDecoder, mlsMessageEncoder, processMessage as mlsProcessMessage, nodeTypes, senderTypes, UsageError, wireformats } from 'ts-mls';
@@ -17,7 +18,6 @@ import { assertHeadMatches, computeHead, decodeLedgerHead, encodeLedgerHead, ext
17
18
  import { settleAdvisory } from './history.js';
18
19
  import { ledgerEntryDigest, verifyLedgerEntry } from './ledger.js';
19
20
  import { assertSenderNotLapsed, isLapsed, isUnchangedLeaf, leafAt, prepareLifecycleGate, rejectionReason } from './lifecycle.js';
20
- import { createMutex } from './mutex.js';
21
21
  import { defaultCommitPolicy, MissingLedgerEntriesError } from './policy.js';
22
22
  import { beaconOf, controllerOf, DEVICE_ENTRY_TYPE, denySetOf, foldControl, isDeviceValue, mayReadmitResetDevice, recordedLogOf, revocationOf } from './registry.js';
23
23
  import { advanceSendingRatchet } from './secret-tree.js';
@@ -131,11 +131,6 @@ export function mutexFor(handle) {
131
131
  throw new UsageError('Cannot send messages after being removed from group');
132
132
  }
133
133
  }
134
- /** AAD is not secret, so a length/byte compare is enough — no constant-time need. */ function bytesEqual(a, b) {
135
- if (a.length !== b.length) return false;
136
- for(let i = 0; i < a.length; i++)if (a[i] !== b[i]) return false;
137
- return true;
138
- }
139
134
  /** Thrown by GroupHandle.processMessage when the commit policy rejects an incoming
140
135
  * commit. The handle is left at its pre-commit epoch. */ export class CommitRejectedError extends Error {
141
136
  #proposals;
@@ -1360,7 +1355,7 @@ function ledgerLogEntry(entryID, token, verified) {
1360
1355
  if (pm == null) throw new Error('decrypt: not a PrivateMessage application frame');
1361
1356
  // Pre-open: reject a wrong-topic frame from its CLEARTEXT authenticatedData before
1362
1357
  // mlsProcessMessage consumes a ratchet generation. Same lane as the sender-leaf read below.
1363
- if (opts?.expectedAAD != null && !bytesEqual(pm.authenticatedData, opts.expectedAAD)) {
1358
+ if (opts?.expectedAAD != null && !equalBytes(pm.authenticatedData, opts.expectedAAD)) {
1364
1359
  throw new Error('decrypt: frame authenticated data does not match expected AAD');
1365
1360
  }
1366
1361
  // Read the sender BEFORE opening: the sender-data secret is epoch-level and this
@@ -1406,7 +1401,7 @@ function ledgerLogEntry(entryID, token, verified) {
1406
1401
  return mutexFor(this).run(async ()=>{
1407
1402
  const pm = readPrivateFrame(decoded, contentTypes.application);
1408
1403
  if (pm == null) throw new Error('decryptStaged: not a PrivateMessage application frame');
1409
- if (opts.expectedAAD != null && !bytesEqual(pm.authenticatedData, opts.expectedAAD)) {
1404
+ if (opts.expectedAAD != null && !equalBytes(pm.authenticatedData, opts.expectedAAD)) {
1410
1405
  throw new Error('decryptStaged: frame authenticated data does not match expected AAD');
1411
1406
  }
1412
1407
  const historical = this.#state.historicalReceiverData.get(pm.epoch);
@@ -0,0 +1,42 @@
1
+ import type { CryptoProvider } from '@kokuin/crypto';
2
+ import { type ClientState } from './codec.js';
3
+ import type { MemberCredential } from './credential.js';
4
+ import type { GroupHandle } from './group-handle.js';
5
+ import type { VerifiedLedgerEntry } from './ledger.js';
6
+ /** A GroupHandle's persisted form: opaque ClientState bytes, credential and ledger as JSON. */
7
+ export type SerializedGroupState = {
8
+ mlsState: Uint8Array;
9
+ credential: string;
10
+ epoch: number;
11
+ /** Ledger tokens, JSON-encoded. */
12
+ ledgerEntries: string;
13
+ };
14
+ export type DeserializedGroupState = {
15
+ state: ClientState;
16
+ credential: MemberCredential;
17
+ ledgerEntries: Array<string>;
18
+ };
19
+ /**
20
+ * Fetch ledger entry bodies a handle lacks, by content id. The answer is untrusted: only tokens
21
+ * whose digest matches and whose signature verifies are kept. Pass none to let
22
+ * `MissingLedgerEntriesError` surface instead of an empty answer.
23
+ */
24
+ export type LedgerEntryResolver = (ids: Array<string>) => Promise<Array<string>>;
25
+ /** Synchronous, so it can only collect: store writes must run after `processMessage` returns. */
26
+ export type LedgerEntrySink = (entries: Array<VerifiedLedgerEntry>) => void;
27
+ export type RestoreGroupStateParams = {
28
+ crypto?: CryptoProvider;
29
+ yield?: boolean;
30
+ serialized: SerializedGroupState;
31
+ /** Supplied only while the restored handle applies a commit, from that commit's frame. */
32
+ resolveLedgerEntries?: LedgerEntryResolver;
33
+ onLedgerEntries?: LedgerEntrySink;
34
+ };
35
+ export declare function serializeGroupState(group: GroupHandle): SerializedGroupState;
36
+ /**
37
+ * Fold a volatile state's receive ratchets into a durable one. Only the secret tree changes; the
38
+ * credential and ledger pass through as the durable side stored them.
39
+ */
40
+ export declare function mergeReceiveState(durable: SerializedGroupState, volatile: Uint8Array): SerializedGroupState;
41
+ export declare function deserializeGroupState(serialized: SerializedGroupState): DeserializedGroupState;
42
+ export declare function restoreGroupState(params: RestoreGroupStateParams): Promise<GroupHandle>;
@@ -0,0 +1,65 @@
1
+ import { decodeClientState, encodeClientState } from './codec.js';
2
+ import { restoreGroup } from './group-create.js';
3
+ import { mergeReceiveSecretTree } from './secret-tree.js';
4
+ export function serializeGroupState(group) {
5
+ return {
6
+ mlsState: encodeClientState(group.state),
7
+ credential: JSON.stringify(group.credential),
8
+ epoch: Number(group.epoch),
9
+ // Tokens are the ledger's only export form: a restored handle refolds its roster from them.
10
+ ledgerEntries: JSON.stringify(group.ledgerTokens)
11
+ };
12
+ }
13
+ /**
14
+ * Fold a volatile state's receive ratchets into a durable one. Only the secret tree changes; the
15
+ * credential and ledger pass through as the durable side stored them.
16
+ */ export function mergeReceiveState(durable, volatile) {
17
+ const state = decodeState(durable.mlsState);
18
+ state.secretTree = mergeReceiveSecretTree({
19
+ target: state.secretTree,
20
+ source: decodeState(volatile).secretTree
21
+ });
22
+ return {
23
+ ...durable,
24
+ mlsState: encodeClientState(state),
25
+ epoch: Number(state.groupContext.epoch)
26
+ };
27
+ }
28
+ export function deserializeGroupState(serialized) {
29
+ // Order matches the source: state, then ledger, then credential, so a bad row fails the same way.
30
+ const state = decodeState(serialized.mlsState);
31
+ // An empty column (no entry enacted yet) folds to the anchor-seeded roster.
32
+ const ledgerEntries = parseLedgerEntries(serialized.ledgerEntries === '' ? [] : JSON.parse(serialized.ledgerEntries));
33
+ return {
34
+ state,
35
+ credential: JSON.parse(serialized.credential),
36
+ ledgerEntries
37
+ };
38
+ }
39
+ export async function restoreGroupState(params) {
40
+ const { state, credential, ledgerEntries } = deserializeGroupState(params.serialized);
41
+ return await restoreGroup({
42
+ yield: params.yield,
43
+ state,
44
+ credential,
45
+ ledgerEntries,
46
+ options: {
47
+ crypto: params.crypto,
48
+ ...params.resolveLedgerEntries != null ? {
49
+ resolveLedgerEntries: params.resolveLedgerEntries
50
+ } : {},
51
+ ...params.onLedgerEntries != null ? {
52
+ onLedgerEntries: params.onLedgerEntries
53
+ } : {}
54
+ }
55
+ });
56
+ }
57
+ function decodeState(encoded) {
58
+ const state = decodeClientState(encoded);
59
+ if (state == null) throw new Error('Could not decode ClientState');
60
+ return state;
61
+ }
62
+ function parseLedgerEntries(value) {
63
+ if (!Array.isArray(value) || value.some((token)=>typeof token !== 'string')) throw new Error('Could not decode persisted control-ledger tokens');
64
+ return value;
65
+ }
package/lib/head.js CHANGED
@@ -1,5 +1,6 @@
1
1
  import { sha256 } from '@noble/hashes/sha2.js';
2
2
  import { concatBytes } from '@noble/hashes/utils.js';
3
+ import { equalBytes } from '@sozai/bytes';
3
4
  import { makeCustomExtension } from 'ts-mls';
4
5
  import { LEDGER_HEAD_EXTENSION_TYPE } from './anchor.js';
5
6
  /** Binary version tag for the encoded ledger-head extension. */ export const LEDGER_HEAD_VERSION = 1;
@@ -125,23 +126,12 @@ function findHeadExtension(handle) {
125
126
  }
126
127
  return head;
127
128
  }
128
- function bytesEqual(a, b) {
129
- if (a.length !== b.length) {
130
- return false;
131
- }
132
- for(let i = 0; i < a.length; i++){
133
- if (a[i] !== b[i]) {
134
- return false;
135
- }
136
- }
137
- return true;
138
- }
139
129
  /**
140
130
  * Whether a recomputed head equals the authenticated one — the predicate form of
141
131
  * {@link assertHeadMatches}. Two entry points on one comparison: a fail-closed gate
142
132
  * throws, a local invariant check reads the boolean.
143
133
  */ export function headsMatch({ expected, actual }) {
144
- return bytesEqual(expected, actual);
134
+ return equalBytes(expected, actual);
145
135
  }
146
136
  /**
147
137
  * Assert a recomputed head matches the authenticated one, or throw
package/lib/index.d.ts CHANGED
@@ -21,9 +21,10 @@ export { type EnvelopeFoldResult, type FoldEnvelopeContext, type FoldEnvelopePar
21
21
  export { ClientStateReservationError, HandshakeReservationError, HandshakeWindowConfigError, HandshakeWindowError, LeafBindingError, type LeafBindingReason, LeafLapsedError, type LeafLapsedReason, RecoveryKnowledgeError, type RecoveryKnowledgeReason, RevokeProofError, type RevokeProofReason, } from './errors.js';
22
22
  export type { FoldLedgerParams, LedgerReducerApplyParams, LedgerReducerVerifyAuthorityParams, } from './fold.js';
23
23
  export { type FoldDrop, type FoldInput, foldLedger, type LedgerReducer, } from './fold.js';
24
+ export { type DecryptedFrame, type DecryptFramedParams, decryptFramed, } from './frame.js';
24
25
  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';
25
26
  export type { CommitInviteParams, CommitLedgerEntriesParams } from './group-commit.js';
26
- export { KUMIAI_KEY_RETENTION_CONFIG } from './group-context.js';
27
+ export { isGenerationExpired, KUMIAI_KEY_RETENTION_CONFIG } from './group-context.js';
27
28
  export type { CreateGroupParams } from './group-create.js';
28
29
  export type { CreateKeyPackageBundleParams, CreateLastResortKeyPackageBundleParams, MakeMLSCredentialParams, } from './group-credential.js';
29
30
  export type { AddDeviceParams, AnnounceControllerBeaconParams, LabelDeviceParams, RegisterDeviceParams, RevokeDeviceParams, } from './group-device.js';
@@ -32,6 +33,7 @@ export { registryAt } from './group-handle.js';
32
33
  export type { AttestTreeTimeParams, ControllerLogDeltaParams, PreservationClockParams, PublishControllerLogParams, RemovalEvidenceParams, RenewLeafParams, SurvivorTargetsParams, } from './group-lifecycle.js';
33
34
  export { attestTreeTime, type CommitResult, commitSelfRemovals, controllerLogDelta, preservationClock, proposeSelfRemoval, publishControllerLog, type RemovalEvidence, type RemoveLapsedLeavesResult, type RevokeBuildResult, type RevokeProofInput, type RevokeWithProofParams, removalEvidence, removeLapsedLeaves, renewLeaf, revokeWithProof, survivorTargets, } from './group-lifecycle.js';
34
35
  export type { RemoveMemberParams } from './group-membership.js';
36
+ export { type DeserializedGroupState, deserializeGroupState, type LedgerEntryResolver, type LedgerEntrySink, mergeReceiveState, type RestoreGroupStateParams, restoreGroupState, type SerializedGroupState, serializeGroupState, } from './group-state.js';
35
37
  export type { JoinGroupExternalParamsBeforeBindingParams } from './group-welcome.js';
36
38
  export type { AssertHeadMatchesParams, ComputeHeadParams, ExtendHeadParams, HeadsMatchParams, LedgerIncompleteErrorParams, } from './head.js';
37
39
  export { assertHeadMatches, buildLedgerHeadExtension, computeHead, decodeLedgerHead, encodeLedgerHead, extendHead, genesisHead, headsMatch, LEDGER_HEAD_VERSION, type LedgerHead, LedgerIncompleteError, readLedgerHead, readLedgerHeadExtension, } from './head.js';
@@ -53,8 +55,8 @@ export type { ConfirmationKeyParams, ConfirmationTagParams } from './recovery-ve
53
55
  export { confirmationKey, confirmationTag, type OpenedRecoveryVerdict, openRecoveryVerdict, type RecoveryRefusalReason, type RecoverySignerEligibleParams, type RecoveryVerdict, recoverySignerEligible, type SealRecoveryVerdictParams, sealRecoveryVerdict, } from './recovery-verdict.js';
54
56
  export type { AssertRetainsKnownEffectsParams, AuthorityParams, BeaconOfParams, ControllerOfParams, FoldControlParams, RecordedLogOfParams, RegistryForLogParams, RevocationOfParams, } from './registry.js';
55
57
  export { assertRetainsKnownEffects, authority, beaconOf, type ControllerBeacon, type ControllerProjection, controllerOf, DEVICE_ENTRY_TYPE, type DeviceOp, type DeviceRecord, type DeviceRegistry, type DeviceValue, denySetOf, foldControl, type Revocation, type RevokedEffect, recordedLogOf, registryForLog, registrySeed, revocationOf, } from './registry.js';
56
- export type { FoldRosterParams } from './roster.js';
57
- export { adminCount, foldRoster, type GroupPermission, ROLE_ENTRY_TYPE, type RoleValue, type RosterState, roleReducer, } from './roster.js';
58
+ export type { FoldAdminRosterParams, FoldRosterParams } from './roster.js';
59
+ export { type AdminRosterState, adminCount, foldAdminRoster, foldRoster, type GroupPermission, type PositionedFoldInput, ROLE_ENTRY_TYPE, type RoleValue, type RosterState, roleReducer, selectRoleEntries, } from './roster.js';
58
60
  export type { MergeReceiveSecretTreeParams } from './secret-tree.js';
59
61
  export { mergeReceiveSecretTree } from './secret-tree.js';
60
62
  export { bindingIssuedAt, DuplicateMemberLeafError } from './stale-leaf.js';
package/lib/index.js CHANGED
@@ -12,10 +12,12 @@ export { CONTROL_ENVELOPE_VERSION, decodeControlEnvelope, encodeControlEnvelope
12
12
  export { foldEnvelope } from './envelope-fold.js';
13
13
  export { ClientStateReservationError, HandshakeReservationError, HandshakeWindowConfigError, HandshakeWindowError, LeafBindingError, LeafLapsedError, RecoveryKnowledgeError, RevokeProofError } from './errors.js';
14
14
  export { foldLedger } from './fold.js';
15
+ export { decryptFramed } from './frame.js';
15
16
  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';
16
- export { KUMIAI_KEY_RETENTION_CONFIG } from './group-context.js';
17
+ export { isGenerationExpired, KUMIAI_KEY_RETENTION_CONFIG } from './group-context.js';
17
18
  export { registryAt } from './group-handle.js';
18
19
  export { attestTreeTime, commitSelfRemovals, controllerLogDelta, preservationClock, proposeSelfRemoval, publishControllerLog, removalEvidence, removeLapsedLeaves, renewLeaf, revokeWithProof, survivorTargets } from './group-lifecycle.js';
20
+ export { deserializeGroupState, mergeReceiveState, restoreGroupState, serializeGroupState } from './group-state.js';
19
21
  export { assertHeadMatches, buildLedgerHeadExtension, computeHead, decodeLedgerHead, encodeLedgerHead, extendHead, genesisHead, headsMatch, LEDGER_HEAD_VERSION, LedgerIncompleteError, readLedgerHead, readLedgerHeadExtension } from './head.js';
20
22
  export { epochEventCount, HISTORY_HORIZON, historySize, MAX_EPOCH_EVENTS_FOR_LEAVES, proofSize, SETTLE_PROMPT_EPOCH_EVENTS, settleAdvisory } from './history.js';
21
23
  export { decodeKeyPackage, decodePrivateKeyPackage, encodeKeyPackage, encodePrivateKeyPackage, keyPackageRef } from './key-package-codec.js';
@@ -26,7 +28,7 @@ export { defaultCommitPolicy, MissingLedgerEntriesError } from './policy.js';
26
28
  export { createRecoveryRequest, openRecoveryGroupInfo, openSealedGroupInfo, openSealedLedger, RECOVERY_REQUEST_TYPE, RecoveryRequestError, SEALED_GROUP_INFO_VERSION, SEALED_LEDGER_VERSION, SealedGroupInfoError, SealedLedgerError, sealGroupInfo, sealLedger, verifyRecoveryRequest } from './recovery.js';
27
29
  export { confirmationKey, confirmationTag, openRecoveryVerdict, recoverySignerEligible, sealRecoveryVerdict } from './recovery-verdict.js';
28
30
  export { assertRetainsKnownEffects, authority, beaconOf, controllerOf, DEVICE_ENTRY_TYPE, denySetOf, foldControl, recordedLogOf, registryForLog, registrySeed, revocationOf } from './registry.js';
29
- export { adminCount, foldRoster, ROLE_ENTRY_TYPE, roleReducer } from './roster.js';
31
+ export { adminCount, foldAdminRoster, foldRoster, ROLE_ENTRY_TYPE, roleReducer, selectRoleEntries } from './roster.js';
30
32
  export { mergeReceiveSecretTree } from './secret-tree.js';
31
33
  export { bindingIssuedAt, DuplicateMemberLeafError } from './stale-leaf.js';
32
34
  export { welcomeKeyPackageRefs } from './welcome-refs.js';
package/lib/lifecycle.js CHANGED
@@ -1,5 +1,6 @@
1
1
  import { decodeKey } from '@kokuin/controller';
2
2
  import { normalizeDID } from '@kokuin/token';
3
+ import { equalBytes } from '@sozai/bytes';
3
4
  import { defaultCredentialTypes, defaultProposalTypes, isDefaultCredential, isDefaultProposal, nodeTypes } from 'ts-mls';
4
5
  import { LEDGER_HEAD_EXTENSION_TYPE } from './anchor.js';
5
6
  import { checkHolderEvidence, verifyLeafCredential } from './authentication.js';
@@ -154,11 +155,8 @@ export async function leafExpiry({ binding, registry, controller, ...options })
154
155
  });
155
156
  return status.status === 'effective' ? status.lease : undefined;
156
157
  }
157
- function bytesEqual(a, b) {
158
- return a.length === b.length && a.every((byte, index)=>byte === b[index]);
159
- }
160
158
  function credentialEqual(a, b) {
161
- return isDefaultCredential(a.credential) && isDefaultCredential(b.credential) && a.credential.credentialType === defaultCredentialTypes.basic && b.credential.credentialType === defaultCredentialTypes.basic && bytesEqual(a.credential.identity, b.credential.identity);
159
+ return isDefaultCredential(a.credential) && isDefaultCredential(b.credential) && a.credential.credentialType === defaultCredentialTypes.basic && b.credential.credentialType === defaultCredentialTypes.basic && equalBytes(a.credential.identity, b.credential.identity);
162
160
  }
163
161
  /**
164
162
  * Whether a direct capability from the anchor's controller replaces a leaf whose issuer the group
@@ -198,7 +196,7 @@ async function checkBinding(group, leaf, previous, /** The leaf arrives in a Wel
198
196
  if (record != null && (binding == null || normalizeDID(binding.id) !== record.controller)) throw new LeafBindingError('controller-mismatch');
199
197
  if (previous != null) {
200
198
  const old = identity(previous);
201
- if (parsed.id !== old.id || parsed.longForm !== old.longForm || !bytesEqual(leaf.signaturePublicKey, previous.signaturePublicKey) || old.controller != null && (binding == null || binding.id !== old.controller.id)) throw new LeafBindingError('identity-change');
199
+ if (parsed.id !== old.id || parsed.longForm !== old.longForm || !equalBytes(leaf.signaturePublicKey, previous.signaturePublicKey) || old.controller != null && (binding == null || binding.id !== old.controller.id)) throw new LeafBindingError('identity-change');
202
200
  if (binding != null && old.controller != null && bindingIssuedAt(binding) < bindingIssuedAt(old.controller) && !replacesRevokedIssuer(group, binding, old.controller)) throw new LeafBindingError('renewal-order');
203
201
  }
204
202
  if (binding == null) return;
@@ -268,7 +266,7 @@ export async function validateEntry(group, leaf, previous, judging = {
268
266
  }
269
267
  /** The same credential and key a tree already holds at that leaf index. */ export function isUnchangedLeaf(tree, index, leaf) {
270
268
  const held = leafAt(tree, index);
271
- return held != null && credentialEqual(held, leaf) && bytesEqual(held.signaturePublicKey, leaf.signaturePublicKey);
269
+ return held != null && credentialEqual(held, leaf) && equalBytes(held.signaturePublicKey, leaf.signaturePublicKey);
272
270
  }
273
271
  async function checkSurvivors(group, tree, registry, origin, policy) {
274
272
  const denied = denySetOf(registry);
@@ -550,7 +548,7 @@ export async function validateWelcomeTree(group, judging = {
550
548
  if (!external && senderIndex != null) {
551
549
  const next = leafAt(state.ratchetTree, senderIndex);
552
550
  const old = leafAt(before, senderIndex);
553
- if (next != null && old != null && (!credentialEqual(next, old) || !bytesEqual(next.signaturePublicKey, old.signaturePublicKey))) {
551
+ if (next != null && old != null && (!credentialEqual(next, old) || !equalBytes(next.signaturePublicKey, old.signaturePublicKey))) {
554
552
  if (controller != null && (hasRemoves || proofs.length > 0)) throw new LeafBindingError('identity-change');
555
553
  await validateEntry(group, next, old, judging(senderIndex, next));
556
554
  }
package/lib/policy.js CHANGED
@@ -1,18 +1,8 @@
1
1
  import { normalizeDID } from '@kokuin/token';
2
+ import { equalBytes } from '@sozai/bytes';
2
3
  import { defaultProposalTypes, isDefaultProposal } from 'ts-mls';
3
4
  import { decodeGroupAnchor, GROUP_ANCHOR_EXTENSION_TYPE, LEDGER_HEAD_EXTENSION_TYPE, RESERVED_EXTENSION_TYPE } from './anchor.js';
4
5
  import { didFromCredential } from './credential.js';
5
- function bytesEqual(a, b) {
6
- if (a.length !== b.length) {
7
- return false;
8
- }
9
- for(let i = 0; i < a.length; i++){
10
- if (a[i] !== b[i]) {
11
- return false;
12
- }
13
- }
14
- return true;
15
- }
16
6
  /**
17
7
  * Fail-closed admin check: no DID, a DID absent from the roster, or any role but `admin`, is
18
8
  * not admin. An undefined leaf (external commit with no committer) is never admin.
@@ -86,7 +76,7 @@ function bytesEqual(a, b) {
86
76
  // external_senders, required_capabilities) fails the instanceof guard and is rejected even
87
77
  // if unmodified — fail-closed liveness, not a security gap, since no group here anchors one
88
78
  // today. Revisit if one is introduced.
89
- if (!(got.extensionData instanceof Uint8Array) || !(want.extensionData instanceof Uint8Array) || !bytesEqual(got.extensionData, want.extensionData)) {
79
+ if (!(got.extensionData instanceof Uint8Array) || !(want.extensionData instanceof Uint8Array) || !equalBytes(got.extensionData, want.extensionData)) {
90
80
  return 'reject';
91
81
  }
92
82
  }
package/lib/recovery.js CHANGED
@@ -1,10 +1,12 @@
1
1
  import { decodeMultibase, encodeMultibase, isVerifiedToken, normalizeDID, stringifyToken, verifyToken } from '@kokuin/token';
2
2
  import { sha256 } from '@noble/hashes/sha2.js';
3
- import { decode, mlsMessageDecoder, wireformats } from 'ts-mls';
3
+ import { concatBytes, equalBytes } from '@sozai/bytes';
4
+ import { decode, encode, mlsMessageDecoder, mlsMessageEncoder, wireformats } from 'ts-mls';
4
5
  import { LEDGER_HEAD_EXTENSION_TYPE, readGroupAnchorExtension } from './anchor.js';
5
- import { exportGroupInfo, inspectGroupInfo, readGroupInfoBinding } from './group.js';
6
+ import { exportGroupInfo, readGroupInfoBinding } from './group.js';
6
7
  import { assertHeadMatches, computeHead, decodeLedgerHead } from './head.js';
7
8
  import { ledgerEntryDigest } from './ledger.js';
9
+ import { varLen } from './sender-data.js';
8
10
  const utf8 = new TextEncoder();
9
11
  /** `type` tag on every recovery-request token. Domain-separates it, so a token
10
12
  * minted for another purpose can never pose as a request for group state. */ export const RECOVERY_REQUEST_TYPE = 'kumiai.recovery-request';
@@ -86,24 +88,6 @@ const LEDGER_REPLY = {
86
88
  framed.set(bytes, 4);
87
89
  return framed;
88
90
  }
89
- function concat(parts) {
90
- let length = 0;
91
- for (const part of parts)length += part.length;
92
- const out = new Uint8Array(length);
93
- let offset = 0;
94
- for (const part of parts){
95
- out.set(part, offset);
96
- offset += part.length;
97
- }
98
- return out;
99
- }
100
- function bytesEqual(a, b) {
101
- if (a.length !== b.length) return false;
102
- for(let i = 0; i < a.length; i++){
103
- if (a[i] !== b[i]) return false;
104
- }
105
- return true;
106
- }
107
91
  /** Lifecycle replies length-frame GroupInfo too, followed by the authenticated ledger. */ function frameAttestedGroupInfo(attestation, groupInfo, ledger) {
108
92
  const token = utf8.encode(attestation);
109
93
  if (ledger != null) {
@@ -148,7 +132,7 @@ function unframeAttestedGroupInfo(bytes, lifecycle) {
148
132
  * its own handle and request id. Any disagreement is an AEAD failure, not a
149
133
  * comparison a caller must remember to make.
150
134
  */ function recoveryAAD(kind, groupID, requesterDID, requestID) {
151
- return concat([
135
+ return concatBytes([
152
136
  kind.aadDomain,
153
137
  frameField(groupID),
154
138
  frameField(normalizeDID(requesterDID)),
@@ -351,6 +335,37 @@ export async function sealToRequest(params) {
351
335
  plaintext
352
336
  });
353
337
  }
338
+ const GROUP_INFO_TBS_LABEL = utf8.encode('MLS 1.0 GroupInfoTBS');
339
+ /**
340
+ * Decode a framed MLSMessage(GroupInfo), refusing any encoding but the canonical one.
341
+ * ts-mls accepts nonminimal lengths and ignores trailing bytes; requiring the
342
+ * re-encoding to equal the input makes the bytes the attestation digests the bytes
343
+ * the signature covers.
344
+ */ function decodeCanonicalGroupInfo(bytes) {
345
+ const message = decode(mlsMessageDecoder, bytes);
346
+ if (message?.wireformat !== wireformats.mls_group_info) throw new Error('Invalid GroupInfo');
347
+ if (!equalBytes(encode(mlsMessageEncoder, message), bytes)) throw new Error('GroupInfo is not canonically encoded');
348
+ return message.groupInfo;
349
+ }
350
+ /**
351
+ * Whether `publicKey` signed this canonical framed GroupInfo (RFC 9420 §12.4.3).
352
+ * ts-mls exports no GroupInfoTBS encoder; the TBS is the frame minus its 4-byte
353
+ * MLSMessage header and trailing `signature<V>` field.
354
+ */ async function isSignedBy(groupInfo, signature, publicKey, group) {
355
+ const tail = varLen(signature);
356
+ if (groupInfo.length < 4 + tail.length) return false;
357
+ const tbsEnd = groupInfo.length - tail.length;
358
+ if (!equalBytes(groupInfo.subarray(tbsEnd), tail)) return false;
359
+ const content = concatBytes([
360
+ varLen(GROUP_INFO_TBS_LABEL),
361
+ varLen(groupInfo.subarray(4, tbsEnd))
362
+ ]);
363
+ try {
364
+ return await group.context.cipherSuite.signature.verify(publicKey, content, signature);
365
+ } catch {
366
+ return false;
367
+ }
368
+ }
354
369
  /**
355
370
  * Verify the responder's membership attestation and require the signer to hold a
356
371
  * leaf in the requester's own last-known ratchet tree — the authentication the AEAD
@@ -364,7 +379,7 @@ export async function sealToRequest(params) {
364
379
  * joined, or removed before the requester's last-known epoch) is refused; one still
365
380
  * in it (including one removed AFTER that epoch) is accepted.
366
381
  */ async function assertResponderIsMember(params) {
367
- const { attestation, group, requestID, groupInfo, ledger } = params;
382
+ const { attestation, group, requestID, groupInfo, signature, ledger } = params;
368
383
  let verified;
369
384
  try {
370
385
  verified = await verifyToken({
@@ -392,6 +407,14 @@ export async function sealToRequest(params) {
392
407
  message: 'responder attestation does not bind this group, request, and GroupInfo'
393
408
  });
394
409
  }
410
+ // The attester must have signed the GroupInfo itself: otherwise the membership and
411
+ // eligibility checks judge one leaf while the join trusts another.
412
+ if (!await isSignedBy(groupInfo, signature, verified.verifiedPublicKey, group)) {
413
+ throw new SealedGroupInfoError({
414
+ reason: 'unauthenticated',
415
+ message: 'responder attestation signer did not sign the GroupInfo'
416
+ });
417
+ }
395
418
  // Lifecycle authority is judged against the derived pending tree and joined registry.
396
419
  if (group.anchor.controller == null && group.findMemberLeafIndex(normalizeDID(iss)) === undefined) {
397
420
  throw new SealedGroupInfoError({
@@ -416,7 +439,7 @@ export async function sealToRequest(params) {
416
439
  }
417
440
  const ownAnchor = readGroupAnchorExtension(group);
418
441
  const ownData = ownAnchor?.extensionData instanceof Uint8Array ? ownAnchor.extensionData : null;
419
- if (ownData == null || binding.anchorExtensionData == null || !bytesEqual(ownData, binding.anchorExtensionData)) {
442
+ if (ownData == null || binding.anchorExtensionData == null || !equalBytes(ownData, binding.anchorExtensionData)) {
420
443
  throw new SealedGroupInfoError({
421
444
  reason: 'group-mismatch',
422
445
  message: 'sealed GroupInfo carries a different genesis anchor than the group being healed'
@@ -458,14 +481,15 @@ export async function sealToRequest(params) {
458
481
  cause
459
482
  });
460
483
  }
461
- // Parse as a GroupInfo before anything trusts its fields.
484
+ // Parse as a canonical GroupInfo before anything trusts its fields.
485
+ let decoded;
462
486
  try {
463
- inspectGroupInfo(groupInfo);
487
+ decoded = decodeCanonicalGroupInfo(groupInfo);
464
488
  } catch (cause) {
465
489
  // biome-ignore lint/style/useErrorCause: cause IS passed; the rule only reads argument 1, and these take (reason, message, options).
466
490
  throw new SealedGroupInfoError({
467
491
  reason: 'malformed',
468
- message: 'sealed plaintext is not a framed MLSMessage(GroupInfo)',
492
+ message: 'sealed plaintext is not a canonical framed MLSMessage(GroupInfo)',
469
493
  cause
470
494
  });
471
495
  }
@@ -475,6 +499,7 @@ export async function sealToRequest(params) {
475
499
  group,
476
500
  requestID,
477
501
  groupInfo,
502
+ signature: decoded.signature,
478
503
  ledger
479
504
  });
480
505
  assertGroupInfoBoundToGroup(groupInfo, group);
@@ -486,9 +511,7 @@ export async function sealToRequest(params) {
486
511
  let tokens;
487
512
  try {
488
513
  tokens = decodeLedgerTokens(ledger);
489
- const message = decode(mlsMessageDecoder, groupInfo);
490
- if (message?.wireformat !== wireformats.mls_group_info) throw new Error('Invalid GroupInfo');
491
- const extension = message.groupInfo.groupContext.extensions.find((held)=>held.extensionType === LEDGER_HEAD_EXTENSION_TYPE);
514
+ const extension = decoded.groupContext.extensions.find((held)=>held.extensionType === LEDGER_HEAD_EXTENSION_TYPE);
492
515
  const head = extension?.extensionData instanceof Uint8Array ? decodeLedgerHead(extension.extensionData) : null;
493
516
  if (head == null) throw new SealedGroupInfoError({
494
517
  reason: 'malformed',
package/lib/roster.d.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  import type { GroupAnchor } from './anchor.js';
2
2
  import { type FoldDrop, type FoldInput, type LedgerReducer } from './fold.js';
3
+ import type { LedgerLogEntry } from './group-handle.js';
3
4
  /** The permission a DID holds in the group: full control, or membership only. */
4
5
  export type GroupPermission = 'admin' | 'member';
5
6
  /** The ledger entry `type` the roster projects. */
@@ -49,3 +50,35 @@ export type FoldRosterParams = {
49
50
  * {@link foldLedger} calls; only there does the fold surface a skip.
50
51
  */
51
52
  export declare function foldRoster({ entries, anchor, groupID, onDrop }: FoldRosterParams): RosterState;
53
+ /**
54
+ * A fold input paired with its slot in the group's control ledger. The slot, not the
55
+ * entry, orders: a repeated token (a demotion back to a held role) shares its
56
+ * `entryID` with the earlier one.
57
+ */
58
+ export type PositionedFoldInput<TValue> = FoldInput<TValue> & {
59
+ /** Index in the handle's ledger, in enactment order. */
60
+ position: number;
61
+ };
62
+ /** Folded admin set: the normalized DIDs holding the admin role. */
63
+ export type AdminRosterState = {
64
+ admins: Set<string>;
65
+ };
66
+ export type FoldAdminRosterParams = {
67
+ entries: Array<PositionedFoldInput<RoleValue>>;
68
+ anchor: GroupAnchor;
69
+ groupID: string;
70
+ /** Fold only entries at or before this ledger position. */
71
+ throughPosition?: number;
72
+ };
73
+ /**
74
+ * Fold role entries into the admin set, optionally as it stood at `throughPosition`.
75
+ * A position is assigned by the commit chain, not asserted by the signer, so it
76
+ * cannot be backdated.
77
+ */
78
+ export declare function foldAdminRoster({ entries, anchor, groupID, throughPosition, }: FoldAdminRosterParams): AdminRosterState;
79
+ /**
80
+ * Select the role entries of a handle's ledger as positioned fold inputs. The
81
+ * position indexes the WHOLE ledger, so a role entry's slot compares with any
82
+ * other entry's.
83
+ */
84
+ export declare function selectRoleEntries(ledger: ReadonlyArray<LedgerLogEntry>): Array<PositionedFoldInput<RoleValue>>;
package/lib/roster.js CHANGED
@@ -81,3 +81,43 @@ import { foldLedger } from './fold.js';
81
81
  onDrop
82
82
  });
83
83
  }
84
+ /**
85
+ * Fold role entries into the admin set, optionally as it stood at `throughPosition`.
86
+ * A position is assigned by the commit chain, not asserted by the signer, so it
87
+ * cannot be backdated.
88
+ */ export function foldAdminRoster({ entries, anchor, groupID, throughPosition }) {
89
+ const scoped = throughPosition == null ? entries : entries.filter(({ position })=>position <= throughPosition);
90
+ const roster = foldRoster({
91
+ entries: scoped,
92
+ anchor,
93
+ groupID
94
+ });
95
+ const admins = new Set();
96
+ for (const [did, permission] of roster.roles){
97
+ if (permission === 'admin') {
98
+ admins.add(did);
99
+ }
100
+ }
101
+ return {
102
+ admins
103
+ };
104
+ }
105
+ /**
106
+ * Select the role entries of a handle's ledger as positioned fold inputs. The
107
+ * position indexes the WHOLE ledger, so a role entry's slot compares with any
108
+ * other entry's.
109
+ */ export function selectRoleEntries(ledger) {
110
+ const entries = [];
111
+ for (const [position, held] of ledger.entries()){
112
+ if (held.verified.entry.type !== ROLE_ENTRY_TYPE) {
113
+ continue;
114
+ }
115
+ entries.push({
116
+ // The log is typed over an unknown value; the entry type says it is a role.
117
+ verified: held.verified,
118
+ entryID: held.entryID,
119
+ position
120
+ });
121
+ }
122
+ return entries;
123
+ }
@@ -17,6 +17,8 @@ export type PrivateCommitFrame = {
17
17
  ciphertext: Uint8Array;
18
18
  authenticatedData: Uint8Array;
19
19
  };
20
+ /** RFC 9420 opaque<V>: QUIC-style variable-length prefix (RFC 9000 §16), then the bytes. */
21
+ export declare function varLen(data: Uint8Array): Uint8Array;
20
22
  /**
21
23
  * MLS `ExpandWithLabel(Secret, Label, Context, Length)`: `KDF.Expand` over the KDFLabel
22
24
  * struct `{ uint16 length; opaque label<V> = "MLS 1.0 " + Label; opaque context<V> }`.
@@ -1,15 +1,5 @@
1
+ import { concatBytes } from '@sozai/bytes';
1
2
  const LABEL_PREFIX = new TextEncoder().encode('MLS 1.0 ');
2
- function concat(parts) {
3
- let length = 0;
4
- for (const part of parts)length += part.length;
5
- const out = new Uint8Array(length);
6
- let offset = 0;
7
- for (const part of parts){
8
- out.set(part, offset);
9
- offset += part.length;
10
- }
11
- return out;
12
- }
13
3
  function uint16(n) {
14
4
  return new Uint8Array([
15
5
  n >> 8 & 0xff,
@@ -25,7 +15,7 @@ function uint64(n) {
25
15
  }
26
16
  return out;
27
17
  }
28
- /** RFC 9420 opaque<V>: QUIC-style variable-length prefix (RFC 9000 §16), then the bytes. */ function varLen(data) {
18
+ /** RFC 9420 opaque<V>: QUIC-style variable-length prefix (RFC 9000 §16), then the bytes. */ export function varLen(data) {
29
19
  const len = data.length;
30
20
  let prefix;
31
21
  if (len < 64) {
@@ -47,7 +37,7 @@ function uint64(n) {
47
37
  } else {
48
38
  throw new Error('sender-data: length too large to encode');
49
39
  }
50
- return concat([
40
+ return concatBytes([
51
41
  prefix,
52
42
  data
53
43
  ]);
@@ -57,9 +47,9 @@ function uint64(n) {
57
47
  * struct `{ uint16 length; opaque label<V> = "MLS 1.0 " + Label; opaque context<V> }`.
58
48
  * Shared with the sender ratchet advance in `secret-tree.ts`.
59
49
  */ export function expandWithLabel(context, secret, label, labelContext, length) {
60
- const kdfLabel = concat([
50
+ const kdfLabel = concatBytes([
61
51
  uint16(length),
62
- varLen(concat([
52
+ varLen(concatBytes([
63
53
  LABEL_PREFIX,
64
54
  new TextEncoder().encode(label)
65
55
  ])),
@@ -81,7 +71,7 @@ function uint64(n) {
81
71
  const key = await expandWithLabel(context, senderDataSecret, 'key', sampled, hpke.keyLength);
82
72
  const nonce = await expandWithLabel(context, senderDataSecret, 'nonce', sampled, hpke.nonceLength);
83
73
  // SenderDataAAD = { opaque group_id<V>; uint64 epoch; ContentType content_type (uint8) }.
84
- const aad = concat([
74
+ const aad = concatBytes([
85
75
  varLen(pm.groupId),
86
76
  uint64(pm.epoch),
87
77
  new Uint8Array([
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kumiai/mls",
3
- "version": "0.13.5",
3
+ "version": "0.13.7",
4
4
  "description": "E2EE group identity and membership for Enkaku using MLS",
5
5
  "keywords": [
6
6
  "mls",
@@ -25,21 +25,24 @@
25
25
  "lib/*"
26
26
  ],
27
27
  "dependencies": {
28
- "@kokuin/capability": "^0.7.2",
29
- "@kokuin/controller": "^0.7.1",
28
+ "@kokuin/capability": "^0.7.3",
29
+ "@kokuin/controller": "^0.7.3",
30
30
  "@kokuin/crypto": "^0.7.1",
31
- "@kokuin/token": "^0.7.1",
31
+ "@kokuin/token": "^0.8.1",
32
32
  "@noble/ciphers": "^2.4.0",
33
33
  "@noble/curves": "^2.4.0",
34
34
  "@noble/hashes": "^2.4.0",
35
- "@sozai/async": "^0.4.4",
36
- "@sozai/codec": "^0.4.4",
37
- "@sozai/event": "^0.1.6",
35
+ "@sozai/async": "^0.4.6",
36
+ "@sozai/bytes": "^0.1.0",
37
+ "@sozai/codec": "^0.5.0",
38
+ "@sozai/event": "^0.1.7",
39
+ "@sozai/json": "^0.4.0",
38
40
  "@sozai/runtime": "^0.1.1",
39
41
  "ts-mls": "2.0.0-rc.13"
40
42
  },
41
43
  "devDependencies": {
42
- "@kokuin/crypto-napi": "^0.7.4"
44
+ "@kokuin/crypto-napi": "^0.7.4",
45
+ "yaml": "^2.9.1"
43
46
  },
44
47
  "publishConfig": {
45
48
  "access": "public"
package/lib/mutex.d.ts DELETED
@@ -1,14 +0,0 @@
1
- /**
2
- * A FIFO async serializer: `run` executes its callbacks one at a time, in the
3
- * order they were called. A callback's rejection is delivered to its own caller
4
- * but never stalls or poisons the queue for later callbacks — the chain always
5
- * advances. Order is not reprioritized: callers rely on it to preserve causal
6
- * order (e.g. the epoch at which an MLS message is produced).
7
- *
8
- * Deliberately dependency-free and generic, so it can move to `@sozai/async`
9
- * unchanged; this package's only per-instance glue is a WeakMap keyed by handle.
10
- */
11
- export type Mutex = {
12
- run: <T>(fn: () => Promise<T>) => Promise<T>;
13
- };
14
- export declare function createMutex(): Mutex;
package/lib/mutex.js DELETED
@@ -1,20 +0,0 @@
1
- /**
2
- * A FIFO async serializer: `run` executes its callbacks one at a time, in the
3
- * order they were called. A callback's rejection is delivered to its own caller
4
- * but never stalls or poisons the queue for later callbacks — the chain always
5
- * advances. Order is not reprioritized: callers rely on it to preserve causal
6
- * order (e.g. the epoch at which an MLS message is produced).
7
- *
8
- * Deliberately dependency-free and generic, so it can move to `@sozai/async`
9
- * unchanged; this package's only per-instance glue is a WeakMap keyed by handle.
10
- */ export function createMutex() {
11
- let chain = Promise.resolve();
12
- const noop = ()=>{};
13
- return {
14
- run (fn) {
15
- const result = chain.then(fn, fn);
16
- chain = result.then(noop, noop);
17
- return result;
18
- }
19
- };
20
- }