@kumiai/mls 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md ADDED
@@ -0,0 +1,63 @@
1
+ # @kumiai/mls
2
+
3
+ Credential-aware MLS (RFC 9420) group lifecycle for enkaku. Wraps [`ts-mls`](https://github.com/LukaJCB/ts-mls) with DID-based capabilities, giving every member a `MemberCredential` that ties their MLS leaf to a signed capability chain.
4
+
5
+ ## Capabilities
6
+
7
+ - `createGroup` — admin creates a new group with themselves as sole member
8
+ - `createInvite` + `commitInvite` — admin delegates a capability and produces the MLS Commit + Welcome
9
+ - `processWelcome` — invitee joins after validating the capability chain
10
+ - `removeMember` — admin evicts a leaf and rotates keys
11
+ - `restoreGroup` — rehydrate a `GroupHandle` from persisted `ClientState`
12
+ - `exportGroupInfo` + `joinGroupExternal` — stale-device self-rejoin (see below)
13
+
14
+ ## External rejoin (stale device recovery)
15
+
16
+ Each device owns its MLS leaf and ratchet state. A device that stays offline long enough for the group to advance epochs (adds, removes, key rotations) can no longer decrypt current application messages. Replaying every missed commit sequentially is expensive and may be impossible if intermediate commits are no longer available.
17
+
18
+ RFC 9420 §11.2.1 defines an external commit: a non-member (or stale member) builds a Commit using only the group's `GroupInfo` (carrying an `external_pub` key). `@kumiai/mls` wraps this for the stale-member case — same DID, cached `MemberCredential`, `resync: true` so the joiner's old leaf is removed in the same commit.
19
+
20
+ ```ts
21
+ // On any healthy member (online, current epoch):
22
+ import { exportGroupInfo } from '@kumiai/mls'
23
+ const { groupInfo } = await exportGroupInfo({ group: aliceGroup })
24
+ // groupInfo is a Uint8Array framed as MLSMessage(GroupInfo). Ship it to the stale device.
25
+
26
+ // On the stale device:
27
+ import { joinGroupExternal } from '@kumiai/mls'
28
+ const { commitMessage, group } = await joinGroupExternal({
29
+ identity: bob, // OwnIdentity from @kokuin/token
30
+ groupInfo, // bytes received from the healthy member
31
+ credential: bobStoredCredential, // cached from the original processWelcome
32
+ resync: true,
33
+ })
34
+ // Broadcast commitMessage (Uint8Array) to the other members; each decodes and calls
35
+ // group.processMessage(decoded). The returned `group` is already at the post-commit
36
+ // epoch — ready to encrypt/decrypt.
37
+ ```
38
+
39
+ ### Trust model
40
+
41
+ Stale rejoin reuses the caller's previously accepted credential. The capability chain is **not** re-validated during `joinGroupExternal` — we trust what the caller already stored from `processWelcome`. Existing members validate the commit sender's identity as part of normal MLS processing.
42
+
43
+ ### Transport
44
+
45
+ `@kumiai/mls` ships bytes, not channels. Callers own:
46
+ - Delivering `groupInfo` bytes from a healthy member to the stale device (e.g. via a hub, directory service, or DM).
47
+ - Broadcasting `commitMessage` bytes to every other member.
48
+ - Rebuilding application state (message backlog, per-member projections) — enkaku does not replay missed application messages.
49
+
50
+ ### Not yet supported
51
+
52
+ - **Fresh external join by a new DID.** Requires deciding how a non-member acquires a `MemberCredential` without a live inviter.
53
+ - **Member-proposed external add.** `proposeAddExternal` is not wrapped yet.
54
+ - **Non-resync external join.** `joinGroupExternal` accepts only `resync: true` (enforced via a literal type in `JoinGroupExternalParams`). Non-resync external join requires a separate API.
55
+
56
+ ### ⚠️ Security: removal is not revocation
57
+
58
+ MLS has no cryptographic member revocation. A device that retains its `MemberCredential` can rejoin via `joinGroupExternal` **even after being removed from the group**, provided it can still obtain a fresh `GroupInfo`. Consumers must assume a removed member can rejoin until capability-level revocation lands in a follow-up spec. Mitigations available today:
59
+
60
+ - Rotate the group: create a new group, migrate non-removed members via fresh invites, abandon the old group.
61
+ - Enforce access control outside MLS: block the removed device at the transport layer (e.g. hub auth).
62
+
63
+ The follow-up capability-revocation work will introduce signed `RevokeMember` tokens synced via a GroupContext extension, with member-side enforcement in `processMessage`.
@@ -0,0 +1,2 @@
1
+ import type { AuthenticationService } from 'ts-mls';
2
+ export declare function createDIDAuthenticationService(): AuthenticationService;
@@ -0,0 +1,67 @@
1
+ import { decodeMultibase, decodePeer4, getAlgorithmAndPublicKey, getSignatureInfo, isPeer4 } from '@kokuin/token';
2
+ import { defaultCredentialTypes } from 'ts-mls';
3
+ import { parseMLSCredentialIdentity } from './credential.js';
4
+ function constantTimeEqual(a, b) {
5
+ if (a.length !== b.length) return false;
6
+ let diff = 0;
7
+ for(let i = 0; i < a.length; i++){
8
+ // biome-ignore lint/style/noNonNullAssertion: index is within bounds
9
+ diff |= a[i] ^ b[i];
10
+ }
11
+ return diff === 0;
12
+ }
13
+ export function createDIDAuthenticationService() {
14
+ return {
15
+ async validateCredential (credential, signaturePublicKey) {
16
+ if (credential.credentialType !== defaultCredentialTypes.basic) {
17
+ return false;
18
+ }
19
+ let parsed;
20
+ try {
21
+ parsed = parseMLSCredentialIdentity(credential.identity);
22
+ } catch {
23
+ return false;
24
+ }
25
+ if (isPeer4(parsed.id)) {
26
+ if (parsed.longForm == null) return false;
27
+ let decoded;
28
+ try {
29
+ decoded = decodePeer4(parsed.longForm);
30
+ } catch {
31
+ return false;
32
+ }
33
+ if (decoded.shortForm !== parsed.id) return false;
34
+ // Only verification methods referenced by `authentication` are
35
+ // permitted to sign for authentication — per DID Core. Reject MLS
36
+ // leaves bound to keys outside that set (KEM keys, assertion-only
37
+ // keys, etc.) even if the byte comparison would otherwise match.
38
+ const authIDs = new Set(decoded.doc.authentication ?? []);
39
+ if (authIDs.size === 0) return false;
40
+ for (const vm of decoded.doc.verificationMethod ?? []){
41
+ if (!authIDs.has(vm.id)) continue;
42
+ if (typeof vm.publicKeyMultibase !== 'string') continue;
43
+ let vmBytes;
44
+ try {
45
+ vmBytes = decodeMultibase(vm.publicKeyMultibase);
46
+ } catch {
47
+ continue;
48
+ }
49
+ // Validate multicodec prefix and strip it; rejects unknown codecs
50
+ // (e.g. X25519 KEM keys, future PQ codecs) instead of blindly
51
+ // comparing 2-byte-truncated bytes.
52
+ const stripped = getAlgorithmAndPublicKey(vmBytes);
53
+ if (stripped == null) continue;
54
+ const [, publicKeyBytes] = stripped;
55
+ if (constantTimeEqual(publicKeyBytes, signaturePublicKey)) return true;
56
+ }
57
+ return false;
58
+ }
59
+ try {
60
+ const [, publicKeyFromDID] = getSignatureInfo(parsed.id);
61
+ return constantTimeEqual(publicKeyFromDID, signaturePublicKey);
62
+ } catch {
63
+ return false;
64
+ }
65
+ }
66
+ };
67
+ }
@@ -0,0 +1,47 @@
1
+ import { type CapabilityPayload, type CapabilityToken, type DelegationChainOptions } from '@kokuin/capability';
2
+ import { type SigningIdentity } from '@kokuin/token';
3
+ export type GroupPermission = 'admin' | 'member' | 'read';
4
+ export type GroupCapabilityPayload = CapabilityPayload & {
5
+ act: Array<GroupPermission>;
6
+ res: Array<string>;
7
+ };
8
+ /**
9
+ * Creates a root admin capability for a group.
10
+ * The signer becomes the group creator and root admin (iss === sub).
11
+ */
12
+ export declare function createGroupCapability(identity: SigningIdentity, groupID: string): Promise<CapabilityToken>;
13
+ export type DelegateGroupMembershipParams = {
14
+ identity: SigningIdentity;
15
+ groupID: string;
16
+ recipientDID: string;
17
+ permission: GroupPermission;
18
+ expiration?: number;
19
+ parentCapability?: string;
20
+ };
21
+ /**
22
+ * Creates a delegated membership capability for a group.
23
+ * The signer must be an admin with a valid capability chain.
24
+ */
25
+ export declare function delegateGroupMembership(params: DelegateGroupMembershipParams): Promise<CapabilityToken>;
26
+ export type ValidateGroupCapabilityParams = {
27
+ tokenData: string;
28
+ groupID: string;
29
+ delegationChain?: Array<string>;
30
+ options?: DelegationChainOptions;
31
+ };
32
+ /**
33
+ * Validates that a capability token grants the specified permission for a group.
34
+ *
35
+ * Resource matching accepts three forms:
36
+ * - `group/<groupID>/*` — full access to a single group (what
37
+ * {@link createGroupCapability} and {@link delegateGroupMembership} issue)
38
+ * - `group/<groupID>/<suffix>` — scoped access within a single group
39
+ * - `*` — **global wildcard**: grants access to EVERY group, and to every
40
+ * other resource type in the stack that honours `*`. This is intentionally
41
+ * supported so root identities holding a stack-wide capability can operate
42
+ * on any group, but its blast radius is total: a leaked, stolen or
43
+ * over-delegated `res: ['*']` token compromises all groups at once. Never
44
+ * issue `*` to regular members or services — delegate `group/<groupID>/*`
45
+ * (or narrower) instead, with an `exp` and a verifiable delegation chain.
46
+ */
47
+ export declare function validateGroupCapability(params: ValidateGroupCapabilityParams): Promise<CapabilityToken>;
@@ -0,0 +1,79 @@
1
+ import { assertCapabilityToken, checkDelegationChain, createCapability } from '@kokuin/capability';
2
+ import { normalizeDID, verifyToken } from '@kokuin/token';
3
+ /**
4
+ * Creates a root admin capability for a group.
5
+ * The signer becomes the group creator and root admin (iss === sub).
6
+ */ export async function createGroupCapability(identity, groupID) {
7
+ return await createCapability(identity, {
8
+ sub: identity.id,
9
+ aud: identity.id,
10
+ act: '*',
11
+ res: [
12
+ `group/${groupID}/*`
13
+ ]
14
+ });
15
+ }
16
+ /**
17
+ * Creates a delegated membership capability for a group.
18
+ * The signer must be an admin with a valid capability chain.
19
+ */ export async function delegateGroupMembership(params) {
20
+ const { identity, groupID, recipientDID, permission, expiration, parentCapability } = params;
21
+ // In Enkaku's capability model, `sub` is the resource owner (stays the same
22
+ // through the chain) and `aud` is who can exercise the capability (the recipient).
23
+ const payload = {
24
+ sub: identity.id,
25
+ aud: recipientDID,
26
+ act: [
27
+ permission
28
+ ],
29
+ res: [
30
+ `group/${groupID}/*`
31
+ ]
32
+ };
33
+ if (expiration != null) {
34
+ payload.exp = expiration;
35
+ }
36
+ return await createCapability(identity, payload, undefined, parentCapability != null ? {
37
+ parentCapability
38
+ } : undefined);
39
+ }
40
+ /**
41
+ * Validates that a capability token grants the specified permission for a group.
42
+ *
43
+ * Resource matching accepts three forms:
44
+ * - `group/<groupID>/*` — full access to a single group (what
45
+ * {@link createGroupCapability} and {@link delegateGroupMembership} issue)
46
+ * - `group/<groupID>/<suffix>` — scoped access within a single group
47
+ * - `*` — **global wildcard**: grants access to EVERY group, and to every
48
+ * other resource type in the stack that honours `*`. This is intentionally
49
+ * supported so root identities holding a stack-wide capability can operate
50
+ * on any group, but its blast radius is total: a leaked, stolen or
51
+ * over-delegated `res: ['*']` token compromises all groups at once. Never
52
+ * issue `*` to regular members or services — delegate `group/<groupID>/*`
53
+ * (or narrower) instead, with an `exp` and a verifiable delegation chain.
54
+ */ export async function validateGroupCapability(params) {
55
+ const { tokenData, groupID, delegationChain, options } = params;
56
+ const token = await verifyToken(tokenData, {
57
+ cache: options?.cache,
58
+ resolver: options?.resolver
59
+ });
60
+ assertCapabilityToken(token);
61
+ // Verify the resource matches the group. `res === '*'` is the global
62
+ // wildcard intentionally kept for root identities — see the JSDoc above
63
+ // for its blast radius before touching this condition.
64
+ const expectedResource = `group/${groupID}/`;
65
+ const resources = Array.isArray(token.payload.res) ? token.payload.res : [
66
+ token.payload.res
67
+ ];
68
+ const matchesGroup = resources.some((res)=>res === `group/${groupID}/*` || res.startsWith(expectedResource) || res === '*');
69
+ if (!matchesGroup) {
70
+ throw new Error(`Invalid capability: does not grant access to group ${groupID}`);
71
+ }
72
+ // Verify delegation chain if provided
73
+ if (delegationChain != null && delegationChain.length > 0) {
74
+ await checkDelegationChain(token.payload, delegationChain, options);
75
+ } else if (normalizeDID(token.payload.iss) !== normalizeDID(token.payload.sub)) {
76
+ throw new Error('Invalid capability: delegation chain required for delegated capabilities');
77
+ }
78
+ return token;
79
+ }
package/lib/codec.d.ts ADDED
@@ -0,0 +1,5 @@
1
+ import { type ClientState, type RatchetTree } from 'ts-mls';
2
+ export type { ClientState };
3
+ export declare function decodeClientState(encoded: Uint8Array): ClientState | undefined;
4
+ export declare function encodeClientState(state: ClientState): Uint8Array;
5
+ export declare function sanitizeRatchetTree(tree: ReadonlyArray<unknown>): RatchetTree;
package/lib/codec.js ADDED
@@ -0,0 +1,10 @@
1
+ import { clientStateDecoder, clientStateEncoder, decode, encode } from 'ts-mls';
2
+ export function decodeClientState(encoded) {
3
+ return decode(clientStateDecoder, encoded);
4
+ }
5
+ export function encodeClientState(state) {
6
+ return encode(clientStateEncoder, state);
7
+ }
8
+ export function sanitizeRatchetTree(tree) {
9
+ return tree.map((node)=>node == null ? undefined : node);
10
+ }
@@ -0,0 +1,43 @@
1
+ import type { CapabilityToken } from '@kokuin/capability';
2
+ import { type DIDCache, type SignedToken } from '@kokuin/token';
3
+ import type { GroupPermission } from './capability.js';
4
+ /**
5
+ * Local member state (never serialized to the MLS leaf). Tracks the capability
6
+ * chain proving group membership.
7
+ */
8
+ export type MemberCredential = {
9
+ id: string;
10
+ capabilityChain: Array<string>;
11
+ capability: CapabilityToken;
12
+ permission: GroupPermission;
13
+ groupID: string;
14
+ };
15
+ /**
16
+ * Wire shape for the MLS basic credential `identity` field. Identity binding
17
+ * only — group membership state lives elsewhere.
18
+ *
19
+ * - did:key identities omit `longForm`.
20
+ * - did:peer:4 identities MUST carry `longForm`; the auth service decodes it
21
+ * inline and binds the MLS leaf signature key to a verification method.
22
+ */
23
+ export type MLSCredentialIdentity = {
24
+ id: string;
25
+ longForm?: string;
26
+ };
27
+ export type GroupMember = {
28
+ /** MLS leaf index (ratchet-tree array position / 2, matching findMemberLeafIndex). */
29
+ leafIndex: number;
30
+ /** DID parsed from the leaf's MLS credential identity. */
31
+ id: string;
32
+ };
33
+ export declare function parseMLSCredentialIdentity(identity: Uint8Array): MLSCredentialIdentity;
34
+ /**
35
+ * If the parsed credential carries a did:peer:4 long form, decode it and write
36
+ * to the cache. Hash binding is enforced (decoded short form must equal `id`).
37
+ * No-op for did:key.
38
+ */
39
+ export declare function populateCacheFromCredential(parsed: MLSCredentialIdentity, cache: DIDCache): Promise<void>;
40
+ /**
41
+ * Extracts the permission level from a capability token's actions.
42
+ */
43
+ export declare function extractPermission(token: SignedToken): GroupPermission;
@@ -0,0 +1,53 @@
1
+ import { decodePeer4, isPeer4 } from '@kokuin/token';
2
+ export function parseMLSCredentialIdentity(identity) {
3
+ const text = new TextDecoder().decode(identity);
4
+ let parsed;
5
+ try {
6
+ parsed = JSON.parse(text);
7
+ } catch {
8
+ throw new Error('Invalid MLS credential: identity bytes are not valid JSON');
9
+ }
10
+ if (parsed == null || typeof parsed !== 'object') {
11
+ throw new Error('Invalid MLS credential: identity must be a JSON object');
12
+ }
13
+ const candidate = parsed;
14
+ if (typeof candidate.id !== 'string') {
15
+ throw new Error('Invalid MLS credential: id must be a string');
16
+ }
17
+ if ('longForm' in candidate && typeof candidate.longForm !== 'string') {
18
+ throw new Error('Invalid MLS credential: longForm must be a string when present');
19
+ }
20
+ const result = {
21
+ id: candidate.id
22
+ };
23
+ if (typeof candidate.longForm === 'string') {
24
+ result.longForm = candidate.longForm;
25
+ }
26
+ return result;
27
+ }
28
+ /**
29
+ * If the parsed credential carries a did:peer:4 long form, decode it and write
30
+ * to the cache. Hash binding is enforced (decoded short form must equal `id`).
31
+ * No-op for did:key.
32
+ */ export async function populateCacheFromCredential(parsed, cache) {
33
+ if (parsed.longForm == null) return;
34
+ if (!isPeer4(parsed.id)) return;
35
+ const { shortForm, doc } = decodePeer4(parsed.longForm);
36
+ if (shortForm !== parsed.id) {
37
+ throw new Error('Credential longForm does not match credential.id');
38
+ }
39
+ await cache.set(shortForm, doc);
40
+ }
41
+ /**
42
+ * Extracts the permission level from a capability token's actions.
43
+ */ export function extractPermission(token) {
44
+ const payload = token.payload;
45
+ const actions = Array.isArray(payload.act) ? payload.act : [
46
+ payload.act
47
+ ];
48
+ if (actions.includes('*')) return 'admin';
49
+ if (actions.includes('admin')) return 'admin';
50
+ if (actions.includes('member')) return 'member';
51
+ if (actions.includes('read')) return 'read';
52
+ throw new Error('Invalid capability: no recognized permission level');
53
+ }
@@ -0,0 +1,21 @@
1
+ /**
2
+ * Pure @noble/* CryptoProvider for ts-mls.
3
+ *
4
+ * Replaces @hpke/core (which requires crypto.subtle) with direct use of:
5
+ * - @noble/curves for X25519 ECDH and Ed25519 signatures
6
+ * - @noble/hashes for SHA-256/384/512 and HKDF
7
+ * - @noble/ciphers for AES-GCM and ChaCha20-Poly1305
8
+ *
9
+ * This enables ts-mls to run on Hermes (React Native) where crypto.subtle is unavailable.
10
+ */
11
+ import { type Runtime } from '@sozai/runtime';
12
+ import type { CryptoProvider } from 'ts-mls';
13
+ export type NobleCryptoProviderOptions = {
14
+ /** Custom random bytes function. Defaults to runtime.getRandomValues. */
15
+ randomBytes?: (n: number) => Uint8Array;
16
+ /** Runtime providing platform primitives. Defaults to createRuntime(). */
17
+ runtime?: Runtime;
18
+ };
19
+ export declare function createNobleCryptoProvider(options?: NobleCryptoProviderOptions): CryptoProvider;
20
+ /** Default noble CryptoProvider using the default runtime for RNG. */
21
+ export declare const nobleCryptoProvider: CryptoProvider;