Repository Public
1/**2 * Thin wrapper around ts-mls (RFC 9420). One MLS group per conversation; every device is a leaf.3 * Ciphersuite 1: DHKEM-X25519, AES-128-GCM, SHA-256, Ed25519 (all provided by WebCrypto).4 */5import {6 acceptAll,7 createApplicationMessage,8 createCommit,9 createGroup,10 decodeGroupState,11 decodeMlsMessage,12 defaultCapabilities,13 defaultLifetime,14 emptyPskIndex,15 encodeGroupState,16 encodeMlsMessage,17 generateKeyPackageWithKey,18 getCiphersuiteFromName,19 getCiphersuiteImpl,20 joinGroup,21 processMessage,22 zeroOutUint8Array,23 type CiphersuiteImpl,24 type ClientConfig,25 type ClientState,26 type Credential,27 type KeyPackage,28 type PrivateKeyPackage,29 type Proposal,30 type RatchetTree,31} from "ts-mls"32import { defaultClientConfig } from "ts-mls/clientConfig.js"33import { makeKeyPackageRef } from "ts-mls/keyPackage.js"34import { unprotectPrivateMessage } from "ts-mls/messageProtection.js"35import { b64, fromUtf8, unb64, utf8 } from "./bytes"36import { edPublic, verifyCert } from "./crypto"3738export type GroupState = ClientState39export type LeafIdentity = { userId: string; deviceId: string; identityKey: Uint8Array; signatureKey: Uint8Array }40export type Member = LeafIdentity & { leafIndex: number }4142let csPromise: Promise<CiphersuiteImpl> | undefined43const suite = () => (csPromise ??= getCiphersuiteImpl(getCiphersuiteFromName("MLS_128_DHKEMX25519_AES128GCM_SHA256_Ed25519")))4445// ---- credentials: a basic credential carrying the device certificate chain to the account identity key46export function encodeCredential(userId: string, deviceId: string, identityKey: Uint8Array, cert: Uint8Array): Credential {47 return { credentialType: "basic", identity: utf8(JSON.stringify({ u: userId, d: deviceId, ik: b64(identityKey), c: b64(cert) })) }48}49function parseCredential(c: Credential): { u: string; d: string; ik: Uint8Array; c: Uint8Array } | null {50 if (c.credentialType !== "basic") return null51 try {52 const j = JSON.parse(fromUtf8(c.identity))53 if (typeof j.u !== "string" || typeof j.d !== "string") return null54 return { u: j.u, d: j.d, ik: unb64(j.ik), c: unb64(j.c) }55 } catch {56 return null57 }58}59/**60 * Called by ts-mls for every leaf it accepts (key packages, updates, commits, welcomes): a leaf is61 * valid only if its signature key is certified by the identity key named in the credential.62 * Whether that identity key is the one pinned for the user is checked by the engine.63 */64const authService = {65 async validateCredential(credential: Credential, signaturePublicKey: Uint8Array): Promise<boolean> {66 const p = parseCredential(credential)67 if (!p) return false68 return verifyCert(p.ik, p.u, p.d, signaturePublicKey, p.c)69 },70}71const clientConfig: ClientConfig = { ...defaultClientConfig, authService }7273function wipe(consumed: Uint8Array[]) {74 consumed.forEach(zeroOutUint8Array)75}7677export type DeviceKeys = { userId: string; deviceId: string; signatureSeed: Uint8Array; identityKey: Uint8Array; cert: Uint8Array }78export type StoredKeyPackage = { ref: string; publicBytes: Uint8Array; priv: PrivateKeyPackage }7980const encodeKp = (kp: KeyPackage) => encodeMlsMessage({ keyPackage: kp, wireformat: "mls_key_package", version: "mls10" })81function decodeKp(bytes: Uint8Array): KeyPackage {82 const m = decodeMlsMessage(bytes, 0)?.[0]83 if (!m || m.wireformat !== "mls_key_package") throw new Error("not a key package")84 return m.keyPackage85}8687export async function newKeyPackage(dev: DeviceKeys): Promise<StoredKeyPackage> {88 const cs = await suite()89 const kp = await generateKeyPackageWithKey(90 encodeCredential(dev.userId, dev.deviceId, dev.identityKey, dev.cert),91 defaultCapabilities(),92 defaultLifetime,93 [],94 { signKey: dev.signatureSeed, publicKey: edPublic(dev.signatureSeed) },95 cs,96 )97 return { ref: b64(await makeKeyPackageRef(kp.publicPackage, cs.hash)), publicBytes: encodeKp(kp.publicPackage), priv: kp.privatePackage }98}99100export async function newGroup(groupId: Uint8Array, dev: DeviceKeys): Promise<GroupState> {101 const cs = await suite()102 const kp = await newKeyPackage(dev)103 return createGroup(groupId, decodeKp(kp.publicBytes), kp.priv, [], cs, clientConfig)104}105106/** Identity carried by a key package, after verifying its certificate. Returns null when invalid. */107export async function keyPackageIdentity(bytes: Uint8Array): Promise<LeafIdentity | null> {108 try {109 const kp = decodeKp(bytes)110 const p = parseCredential(kp.leafNode.credential)111 if (!p || !(await verifyCert(p.ik, p.u, p.d, kp.leafNode.signaturePublicKey, p.c))) return null112 return { userId: p.u, deviceId: p.d, identityKey: p.ik, signatureKey: kp.leafNode.signaturePublicKey }113 } catch {114 return null115 }116}117118export type CommitOut = { state: GroupState; commit: Uint8Array; welcome: Uint8Array | null }119120/** Builds a commit that adds key packages and/or removes leaves. The new state must only be kept once the server accepted the commit. */121export async function commit(state: GroupState, add: Uint8Array[], removeLeaves: number[]): Promise<CommitOut> {122 const cs = await suite()123 const proposals: Proposal[] = [124 ...removeLeaves.map((l): Proposal => ({ proposalType: "remove", remove: { removed: l } })),125 ...add.map((b): Proposal => ({ proposalType: "add", add: { keyPackage: decodeKp(b) } })),126 ]127 const r = await createCommit({ state, cipherSuite: cs }, { extraProposals: proposals, ratchetTreeExtension: true })128 return {129 state: r.newState,130 commit: encodeMlsMessage(r.commit),131 welcome: r.welcome ? encodeMlsMessage({ welcome: r.welcome, wireformat: "mls_welcome", version: "mls10" }) : null,132 }133}134135/** Finds which of our stored key packages a welcome was addressed to. */136export function welcomeRefs(welcome: Uint8Array): string[] {137 const m = decodeMlsMessage(welcome, 0)?.[0]138 if (!m || m.wireformat !== "mls_welcome") throw new Error("not a welcome")139 return m.welcome.secrets.map((s) => b64(s.newMember))140}141export async function join(welcome: Uint8Array, kp: StoredKeyPackage): Promise<GroupState> {142 const cs = await suite()143 const m = decodeMlsMessage(welcome, 0)?.[0]144 if (!m || m.wireformat !== "mls_welcome") throw new Error("not a welcome")145 return joinGroup(m.welcome, decodeKp(kp.publicBytes), kp.priv, emptyPskIndex, cs, undefined, undefined, clientConfig)146}147148export async function encrypt(state: GroupState, plaintext: Uint8Array): Promise<{ state: GroupState; data: Uint8Array }> {149 const cs = await suite()150 const r = await createApplicationMessage(state, plaintext, cs)151 wipe(r.consumed)152 return { state: r.newState, data: encodeMlsMessage({ privateMessage: r.privateMessage, wireformat: "mls_private_message", version: "mls10" }) }153}154155function leafAt(tree: RatchetTree, leafIndex: number): LeafIdentity | null {156 const n = tree[leafIndex * 2]157 if (!n || n.nodeType !== "leaf") return null158 const p = parseCredential(n.leaf.credential)159 return p ? { userId: p.u, deviceId: p.d, identityKey: p.ik, signatureKey: n.leaf.signaturePublicKey } : null160}161162export function members(state: GroupState): Member[] {163 const out: Member[] = []164 for (let i = 0; i * 2 < state.ratchetTree.length; i++) {165 const l = leafAt(state.ratchetTree, i)166 if (l) out.push({ ...l, leafIndex: i })167 }168 return out169}170export const groupId = (state: GroupState): Uint8Array => state.groupContext.groupId171export const epochOf = (state: GroupState) => Number(state.groupContext.epoch)172export const isActive = (state: GroupState) => state.groupActiveState.kind === "active"173174export type Incoming =175 | { kind: "application"; state: GroupState; plaintext: Uint8Array; sender: LeafIdentity }176 | { kind: "commit"; state: GroupState; removedSelf: boolean }177178/**179 * Processes one MLS message. For application messages the authenticated sender leaf is returned:180 * ts-mls verifies the content signature against that leaf, we only read which leaf it was.181 */182export async function receive(state: GroupState, bytes: Uint8Array): Promise<Incoming> {183 const cs = await suite()184 const m = decodeMlsMessage(bytes, 0)?.[0]185 if (!m) throw new Error("undecodable MLS message")186 if (m.wireformat === "mls_private_message" && m.privateMessage.contentType === "application") {187 const pm = m.privateMessage188 const cfg = state.clientConfig.keyRetentionConfig189 if (pm.epoch < state.groupContext.epoch) {190 const old = state.historicalReceiverData.get(pm.epoch)191 if (!old) throw new Error("epoch too old")192 const r = await unprotectPrivateMessage(old.senderDataSecret, pm, old.secretTree, old.ratchetTree, old.groupContext, cfg, cs)193 const c = r.content.content194 if (c.contentType !== "application" || c.sender.senderType !== "member") throw new Error("unexpected content")195 const sender = leafAt(old.ratchetTree, c.sender.leafIndex)196 if (!sender) throw new Error("unknown sender leaf")197 const hist = new Map(state.historicalReceiverData)198 hist.set(pm.epoch, { ...old, secretTree: r.tree })199 wipe(r.consumed)200 return { kind: "application", state: { ...state, historicalReceiverData: hist }, plaintext: c.applicationData, sender }201 }202 const r = await unprotectPrivateMessage(state.keySchedule.senderDataSecret, pm, state.secretTree, state.ratchetTree, state.groupContext, cfg, cs)203 const c = r.content.content204 if (c.contentType !== "application" || c.sender.senderType !== "member") throw new Error("unexpected content")205 const sender = leafAt(state.ratchetTree, c.sender.leafIndex)206 if (!sender) throw new Error("unknown sender leaf")207 wipe(r.consumed)208 return { kind: "application", state: { ...state, secretTree: r.tree }, plaintext: c.applicationData, sender }209 }210 if (m.wireformat !== "mls_private_message" && m.wireformat !== "mls_public_message") throw new Error("unexpected wire format")211 const r = await processMessage(m, state, emptyPskIndex, acceptAll, cs)212 if (r.kind !== "newState") throw new Error("expected a handshake message")213 wipe(r.consumed)214 return { kind: "commit", state: r.newState, removedSelf: r.newState.groupActiveState.kind !== "active" }215}216217export const serialize = (state: GroupState): Uint8Array => encodeGroupState(state)218export function deserialize(bytes: Uint8Array): GroupState {219 const d = decodeGroupState(bytes, 0)?.[0]220 if (!d) throw new Error("corrupt group state")221 return { ...d, clientConfig }222}223