@kumiai/mls 0.13.5 → 0.13.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md 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
 
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,5 @@
1
1
  import { assertTimeClaimsValid, decodeSignedToken, normalizeDID } from '@kokuin/token';
2
- import { maybeYield } from '@sozai/async';
2
+ import { createMutex, maybeYield } from '@sozai/async';
3
3
  import { toB64 } from '@sozai/codec';
4
4
  import { EventEmitter } from '@sozai/event';
5
5
  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 +17,6 @@ import { assertHeadMatches, computeHead, decodeLedgerHead, encodeLedgerHead, ext
17
17
  import { settleAdvisory } from './history.js';
18
18
  import { ledgerEntryDigest, verifyLedgerEntry } from './ledger.js';
19
19
  import { assertSenderNotLapsed, isLapsed, isUnchangedLeaf, leafAt, prepareLifecycleGate, rejectionReason } from './lifecycle.js';
20
- import { createMutex } from './mutex.js';
21
20
  import { defaultCommitPolicy, MissingLedgerEntriesError } from './policy.js';
22
21
  import { beaconOf, controllerOf, DEVICE_ENTRY_TYPE, denySetOf, foldControl, isDeviceValue, mayReadmitResetDevice, recordedLogOf, revocationOf } from './registry.js';
23
22
  import { advanceSendingRatchet } from './secret-tree.js';
@@ -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/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/recovery.js CHANGED
@@ -1,10 +1,11 @@
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 { decode, encode, mlsMessageDecoder, mlsMessageEncoder, wireformats } from 'ts-mls';
4
4
  import { LEDGER_HEAD_EXTENSION_TYPE, readGroupAnchorExtension } from './anchor.js';
5
- import { exportGroupInfo, inspectGroupInfo, readGroupInfoBinding } from './group.js';
5
+ import { exportGroupInfo, readGroupInfoBinding } from './group.js';
6
6
  import { assertHeadMatches, computeHead, decodeLedgerHead } from './head.js';
7
7
  import { ledgerEntryDigest } from './ledger.js';
8
+ import { varLen } from './sender-data.js';
8
9
  const utf8 = new TextEncoder();
9
10
  /** `type` tag on every recovery-request token. Domain-separates it, so a token
10
11
  * minted for another purpose can never pose as a request for group state. */ export const RECOVERY_REQUEST_TYPE = 'kumiai.recovery-request';
@@ -351,6 +352,37 @@ export async function sealToRequest(params) {
351
352
  plaintext
352
353
  });
353
354
  }
355
+ const GROUP_INFO_TBS_LABEL = utf8.encode('MLS 1.0 GroupInfoTBS');
356
+ /**
357
+ * Decode a framed MLSMessage(GroupInfo), refusing any encoding but the canonical one.
358
+ * ts-mls accepts nonminimal lengths and ignores trailing bytes; requiring the
359
+ * re-encoding to equal the input makes the bytes the attestation digests the bytes
360
+ * the signature covers.
361
+ */ function decodeCanonicalGroupInfo(bytes) {
362
+ const message = decode(mlsMessageDecoder, bytes);
363
+ if (message?.wireformat !== wireformats.mls_group_info) throw new Error('Invalid GroupInfo');
364
+ if (!bytesEqual(encode(mlsMessageEncoder, message), bytes)) throw new Error('GroupInfo is not canonically encoded');
365
+ return message.groupInfo;
366
+ }
367
+ /**
368
+ * Whether `publicKey` signed this canonical framed GroupInfo (RFC 9420 §12.4.3).
369
+ * ts-mls exports no GroupInfoTBS encoder; the TBS is the frame minus its 4-byte
370
+ * MLSMessage header and trailing `signature<V>` field.
371
+ */ async function isSignedBy(groupInfo, signature, publicKey, group) {
372
+ const tail = varLen(signature);
373
+ if (groupInfo.length < 4 + tail.length) return false;
374
+ const tbsEnd = groupInfo.length - tail.length;
375
+ if (!bytesEqual(groupInfo.subarray(tbsEnd), tail)) return false;
376
+ const content = concat([
377
+ varLen(GROUP_INFO_TBS_LABEL),
378
+ varLen(groupInfo.subarray(4, tbsEnd))
379
+ ]);
380
+ try {
381
+ return await group.context.cipherSuite.signature.verify(publicKey, content, signature);
382
+ } catch {
383
+ return false;
384
+ }
385
+ }
354
386
  /**
355
387
  * Verify the responder's membership attestation and require the signer to hold a
356
388
  * leaf in the requester's own last-known ratchet tree — the authentication the AEAD
@@ -364,7 +396,7 @@ export async function sealToRequest(params) {
364
396
  * joined, or removed before the requester's last-known epoch) is refused; one still
365
397
  * in it (including one removed AFTER that epoch) is accepted.
366
398
  */ async function assertResponderIsMember(params) {
367
- const { attestation, group, requestID, groupInfo, ledger } = params;
399
+ const { attestation, group, requestID, groupInfo, signature, ledger } = params;
368
400
  let verified;
369
401
  try {
370
402
  verified = await verifyToken({
@@ -392,6 +424,14 @@ export async function sealToRequest(params) {
392
424
  message: 'responder attestation does not bind this group, request, and GroupInfo'
393
425
  });
394
426
  }
427
+ // The attester must have signed the GroupInfo itself: otherwise the membership and
428
+ // eligibility checks judge one leaf while the join trusts another.
429
+ if (!await isSignedBy(groupInfo, signature, verified.verifiedPublicKey, group)) {
430
+ throw new SealedGroupInfoError({
431
+ reason: 'unauthenticated',
432
+ message: 'responder attestation signer did not sign the GroupInfo'
433
+ });
434
+ }
395
435
  // Lifecycle authority is judged against the derived pending tree and joined registry.
396
436
  if (group.anchor.controller == null && group.findMemberLeafIndex(normalizeDID(iss)) === undefined) {
397
437
  throw new SealedGroupInfoError({
@@ -458,14 +498,15 @@ export async function sealToRequest(params) {
458
498
  cause
459
499
  });
460
500
  }
461
- // Parse as a GroupInfo before anything trusts its fields.
501
+ // Parse as a canonical GroupInfo before anything trusts its fields.
502
+ let decoded;
462
503
  try {
463
- inspectGroupInfo(groupInfo);
504
+ decoded = decodeCanonicalGroupInfo(groupInfo);
464
505
  } catch (cause) {
465
506
  // biome-ignore lint/style/useErrorCause: cause IS passed; the rule only reads argument 1, and these take (reason, message, options).
466
507
  throw new SealedGroupInfoError({
467
508
  reason: 'malformed',
468
- message: 'sealed plaintext is not a framed MLSMessage(GroupInfo)',
509
+ message: 'sealed plaintext is not a canonical framed MLSMessage(GroupInfo)',
469
510
  cause
470
511
  });
471
512
  }
@@ -475,6 +516,7 @@ export async function sealToRequest(params) {
475
516
  group,
476
517
  requestID,
477
518
  groupInfo,
519
+ signature: decoded.signature,
478
520
  ledger
479
521
  });
480
522
  assertGroupInfoBoundToGroup(groupInfo, group);
@@ -486,9 +528,7 @@ export async function sealToRequest(params) {
486
528
  let tokens;
487
529
  try {
488
530
  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);
531
+ const extension = decoded.groupContext.extensions.find((held)=>held.extensionType === LEDGER_HEAD_EXTENSION_TYPE);
492
532
  const head = extension?.extensionData instanceof Uint8Array ? decodeLedgerHead(extension.extensionData) : null;
493
533
  if (head == null) throw new SealedGroupInfoError({
494
534
  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> }`.
@@ -25,7 +25,7 @@ function uint64(n) {
25
25
  }
26
26
  return out;
27
27
  }
28
- /** RFC 9420 opaque<V>: QUIC-style variable-length prefix (RFC 9000 §16), then the bytes. */ function varLen(data) {
28
+ /** RFC 9420 opaque<V>: QUIC-style variable-length prefix (RFC 9000 §16), then the bytes. */ export function varLen(data) {
29
29
  const len = data.length;
30
30
  let prefix;
31
31
  if (len < 64) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kumiai/mls",
3
- "version": "0.13.5",
3
+ "version": "0.13.6",
4
4
  "description": "E2EE group identity and membership for Enkaku using MLS",
5
5
  "keywords": [
6
6
  "mls",
@@ -26,20 +26,21 @@
26
26
  ],
27
27
  "dependencies": {
28
28
  "@kokuin/capability": "^0.7.2",
29
- "@kokuin/controller": "^0.7.1",
29
+ "@kokuin/controller": "^0.7.2",
30
30
  "@kokuin/crypto": "^0.7.1",
31
31
  "@kokuin/token": "^0.7.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/codec": "^0.4.5",
37
+ "@sozai/event": "^0.1.7",
38
38
  "@sozai/runtime": "^0.1.1",
39
39
  "ts-mls": "2.0.0-rc.13"
40
40
  },
41
41
  "devDependencies": {
42
- "@kokuin/crypto-napi": "^0.7.4"
42
+ "@kokuin/crypto-napi": "^0.7.4",
43
+ "yaml": "^2.9.1"
43
44
  },
44
45
  "publishConfig": {
45
46
  "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
- }