Download client/crypto.js from abr00kx/taper: direct link, hf CLI and curl.
- Browser
- Download file 42.9 kB
-
https://huggingface.co/abr00kx/taper/resolve/main/client/crypto.js
- Command line
-
hf download hf://abr00kx/taper/client/crypto.js
-
curl -L -o crypto.js https://huggingface.co/abr00kx/taper/resolve/main/client/crypto.js
42.9 kB
| // End-to-end encryption for the Taper dev client. | |
| // | |
| // Wraps @matrix-org/matrix-sdk-crypto-wasm (vodozemac plus the Matrix Rust | |
| // SDK's crypto state machine). The library never talks to a server itself: | |
| // it hands us requests, we carry them over the Taper gateway, and we feed the | |
| // responses back. On top of it we add the room version 13 rules the library | |
| // doesn't know about: the `binding`, Padme padding, and checking that the | |
| // Megolm session belongs to the event's sender. | |
| // | |
| // The library speaks Matrix names (`m.room.encrypted`, `m.megolm.v1.aes-sha2`). | |
| // Taper uses `t.*`. We translate only event `type` fields and the outer | |
| // `algorithm` field of encrypted content, which aren't covered by any | |
| // signature. Signed objects such as device keys pass through untouched. | |
| // | |
| // The SDK module is passed in, so this file works in the browser and in Node. | |
| const TAPER_ALGORITHM = 't.megolm.v1.aes-sha2'; | |
| const DAY_MICROS = 86_400_000_000n; | |
| const RETENTION_CEILING_MS = 1_814_400_000; // 21 days | |
| const MAX_KEY_AGE_MS = RETENTION_CEILING_MS + 86_400_000; // 21d + 1d margin (spec: message_retention.md) | |
| const MAX_CLOCK_SKEW_MS = 5 * 60_000; | |
| const KEY_REFRESHES_PER_MIN = 20; // on-demand device-key queries in decrypt(), all senders together | |
| function canonicalJson(value) { | |
| if (Array.isArray(value)) return `[${value.map(canonicalJson).join(',')}]`; | |
| if (value && typeof value === 'object') { | |
| return `{${Object.keys(value).sort().map((k) => `${JSON.stringify(k)}:${canonicalJson(value[k])}`).join(',')}}`; | |
| } | |
| return JSON.stringify(value); | |
| } | |
| /** | |
| * Verify room state invariants on the client so a malicious homeserver cannot | |
| * forge room creation, spoof the room creator, or downgrade encryption/history. | |
| */ | |
| export async function verifyRoomState(roomId, stateEvents) { | |
| const warnings = []; | |
| const list = Array.isArray(stateEvents) ? stateEvents : []; | |
| const create = list.find((e) => e?.type === 't.room.create' && e.state_key === ''); | |
| if (!create) { | |
| warnings.push('Room is missing its creation event (t.room.create).'); | |
| return { ok: false, fatal: true, warnings }; | |
| } | |
| // A forged or wrong-version room is fatal: the client refuses to send in it. | |
| let fatal = create.content?.room_version !== '13'; | |
| if (fatal) { | |
| warnings.push(`Room uses unsupported version '${create.content?.room_version ?? 'unknown'}' (expected 13).`); | |
| } | |
| const redacted = { | |
| sender: create.sender, | |
| type: create.type, | |
| origin_server_ts: create.origin_server_ts, | |
| depth: create.depth, | |
| prev_events: create.prev_events, | |
| auth_events: Array.isArray(create.auth_events) ? create.auth_events : [], | |
| content: create.content, | |
| state_key: create.state_key, | |
| }; | |
| try { | |
| const hash = new Uint8Array(await crypto.subtle.digest('SHA-256', utf8(canonicalJson(redacted)))); | |
| const expectedId = `!${toB64(hash).replace(/\+/g, '-').replace(/\//g, '_')}`; | |
| if (expectedId !== roomId) { | |
| fatal = true; | |
| warnings.push('Room ID does not match the hash of its creation event (possible server forgery).'); | |
| } | |
| } catch { | |
| fatal = true; | |
| warnings.push('Could not verify room ID hash.'); | |
| } | |
| const hv = list.find((e) => e?.type === 't.room.history_visibility' && e.state_key === ''); | |
| if (hv?.content?.history_visibility !== 'joined') { | |
| warnings.push(`History visibility is '${hv?.content?.history_visibility ?? 'missing'}' instead of 'joined'.`); | |
| } | |
| const enc = list.find((e) => e?.type === 't.room.encryption' && e.state_key === ''); | |
| if (!enc) { | |
| warnings.push('Room has no encryption settings (t.room.encryption).'); | |
| } else { | |
| if (enc.content?.algorithm !== TAPER_ALGORITHM) warnings.push(`Unexpected encryption algorithm '${enc.content?.algorithm}'.`); | |
| if ((enc.content?.rotation_period_ms ?? 0) > 86_400_000 || (enc.content?.rotation_period_msgs ?? 0) > 100) { | |
| warnings.push('Room encryption rotation limits exceed Taper maximums; client enforces 1 day / 100 messages.'); | |
| } | |
| } | |
| return { ok: warnings.length === 0, fatal, warnings }; | |
| } | |
| // --- Name translation ------------------------------------------------------- | |
| const toTaperName = (s) => (typeof s === 'string' && s.startsWith('m.') ? `t.${s.slice(2)}` : s); | |
| const toMatrixName = (s) => (typeof s === 'string' && s.startsWith('t.') ? `m.${s.slice(2)}` : s); | |
| function translateContent(content, fn) { | |
| if (!content || typeof content !== 'object' || typeof content.algorithm !== 'string') return content; | |
| return { ...content, algorithm: fn(content.algorithm) }; | |
| } | |
| export function toMatrixEvent(ev) { | |
| return { ...ev, type: toMatrixName(ev.type), content: translateContent(ev.content, toMatrixName) }; | |
| } | |
| // --- Padding (Padme, Nikitin et al., PETS 2019) ----------------------------- | |
| export function padme(length) { | |
| const L = Math.max(length, 256); | |
| const E = Math.floor(Math.log2(L)); | |
| const S = Math.floor(Math.log2(E)) + 1; | |
| const Z = E - S; | |
| const mask = 2 ** Z - 1; | |
| return Math.ceil(L / (mask + 1)) * (mask + 1); | |
| } | |
| // Add a `pad` property so the JSON serialization reaches its Padme bucket. | |
| export function padJson(obj) { | |
| const base = JSON.stringify({ ...obj, pad: '' }); | |
| const bytes = new TextEncoder().encode(base).length; | |
| return { ...obj, pad: '0'.repeat(padme(bytes) - bytes) }; | |
| } | |
| // --------------------------------------------------------------------------- | |
| // Identity recovery (Cryptography and Transport, "Identity recovery"). The | |
| // cross-signing private keys are sealed with AES-256-GCM under a key derived | |
| // from the OPAQUE export_key, which the server never learns. | |
| // --------------------------------------------------------------------------- | |
| export const SECRETS_ALGORITHM = 't.secrets.v1.aes-gcm'; | |
| const utf8 = (s) => new TextEncoder().encode(s); | |
| const fromB64any = (s) => Uint8Array.from(atob(s.replace(/-/g, '+').replace(/_/g, '/')), (c) => c.charCodeAt(0)); | |
| const toB64 = (bytes) => { | |
| let s = ''; | |
| for (let i = 0; i < bytes.length; i += 8192) s += String.fromCharCode(...bytes.subarray(i, i + 8192)); // spreading a big array throws | |
| return btoa(s).replace(/=+$/, ''); | |
| }; | |
| async function secretsKey(exportKey, userId) { | |
| const ikm = await crypto.subtle.importKey('raw', fromB64any(exportKey), 'HKDF', false, ['deriveKey']); | |
| return crypto.subtle.deriveKey( | |
| { name: 'HKDF', hash: 'SHA-512', salt: utf8(SECRETS_ALGORITHM), info: utf8(`identity recovery|${userId}`) }, | |
| ikm, { name: 'AES-GCM', length: 256 }, false, ['encrypt', 'decrypt'], | |
| ); | |
| } | |
| /** Seal a JSON object for the server to keep. */ | |
| export async function sealSecrets(exportKey, userId, obj) { | |
| const iv = crypto.getRandomValues(new Uint8Array(12)); | |
| const key = await secretsKey(exportKey, userId); | |
| const ct = await crypto.subtle.encrypt({ name: 'AES-GCM', iv, additionalData: utf8(userId) }, key, utf8(JSON.stringify(padJson(obj)))); | |
| return { algorithm: SECRETS_ALGORITHM, iv: toB64(iv), ciphertext: toB64(new Uint8Array(ct)) }; | |
| } | |
| /** Open what sealSecrets sealed; throws if it was tampered with or the key is wrong. */ | |
| export async function openSecrets(exportKey, userId, blob) { | |
| if (blob?.algorithm !== SECRETS_ALGORITHM) throw new Error('Unknown secrets format'); | |
| const key = await secretsKey(exportKey, userId); | |
| const pt = await crypto.subtle.decrypt({ name: 'AES-GCM', iv: fromB64any(blob.iv), additionalData: utf8(userId) }, key, fromB64any(blob.ciphertext)); | |
| const { pad: _pad, ...obj } = JSON.parse(new TextDecoder().decode(pt)); | |
| return obj; | |
| } | |
| // --------------------------------------------------------------------------- | |
| // Room-key backup. Megolm keys for the last 21 days, sealed under a key from | |
| // the OPAQUE export key (a different one from the identity key above), kept | |
| // by the server in daily parts that expire with the messages they open. | |
| // --------------------------------------------------------------------------- | |
| export const BACKUP_ALGORITHM = 't.backup.v1.aes-gcm'; | |
| /** The raw backup key (32 bytes) for this account and password. */ | |
| export async function deriveBackupKey(exportKey, userId) { | |
| const ikm = await crypto.subtle.importKey('raw', fromB64any(exportKey), 'HKDF', false, ['deriveBits']); | |
| return new Uint8Array(await crypto.subtle.deriveBits( | |
| { name: 'HKDF', hash: 'SHA-512', salt: utf8(BACKUP_ALGORITHM), info: utf8(`room key backup|${userId}`) }, ikm, 256)); | |
| } | |
| const backupAesKey = (raw) => crypto.subtle.importKey('raw', raw, 'AES-GCM', false, ['encrypt', 'decrypt']); | |
| /** Seal a JSON object as backup part `part` ("2026-01-31.0"); the part name is authenticated. */ | |
| export async function sealBackup(rawKey, userId, part, obj) { | |
| const iv = crypto.getRandomValues(new Uint8Array(12)); | |
| const ct = await crypto.subtle.encrypt({ name: 'AES-GCM', iv, additionalData: utf8(`${userId}|${part}`) }, | |
| await backupAesKey(rawKey), utf8(JSON.stringify(padJson(obj)))); | |
| return { algorithm: BACKUP_ALGORITHM, iv: toB64(iv), ciphertext: toB64(new Uint8Array(ct)) }; | |
| } | |
| export async function openBackup(rawKey, userId, part, blob) { | |
| if (blob?.algorithm !== BACKUP_ALGORITHM) throw new Error('Unknown backup format'); | |
| const pt = await crypto.subtle.decrypt({ name: 'AES-GCM', iv: fromB64any(blob.iv), additionalData: utf8(`${userId}|${part}`) }, | |
| await backupAesKey(rawKey), fromB64any(blob.ciphertext)); | |
| const { pad: _pad, ...obj } = JSON.parse(new TextDecoder().decode(pt)); | |
| return obj; | |
| } | |
| // Read the Megolm message index from a ciphertext. This parses the message | |
| // framing (Megolm spec, "Message format"); it does no cryptography. The | |
| // payload after the version byte starts with tag 0x08 and a varint index. | |
| export function megolmMessageIndex(ciphertextB64) { | |
| let bytes; | |
| try { bytes = Uint8Array.from(atob(ciphertextB64), (c) => c.charCodeAt(0)); } catch { return null; } | |
| if (bytes.length < 3 || bytes[0] !== 0x03 || bytes[1] !== 0x08) return null; | |
| let index = 0; | |
| for (let i = 2, shift = 0; i < bytes.length && shift < 35; i++, shift += 7) { | |
| index += (bytes[i] & 0x7f) * 2 ** shift; | |
| if (!(bytes[i] & 0x80)) return index; | |
| } | |
| return null; | |
| } | |
| function randomB64(bytes) { | |
| const buf = crypto.getRandomValues(new Uint8Array(bytes)); | |
| let bin = ''; | |
| for (const b of buf) bin += String.fromCharCode(b); | |
| return btoa(bin).replace(/=+$/, ''); | |
| } | |
| // --- The adapter ------------------------------------------------------------ | |
| export class TaperCrypto { | |
| /** | |
| * @param sdk the @matrix-org/matrix-sdk-crypto-wasm module (already initialised) | |
| * @param request async (method, body) => response body, over the gateway | |
| */ | |
| static async create(sdk, { userId, deviceId, request, storeName, storePassphrase, maxKeyAgeMs = MAX_KEY_AGE_MS }) { | |
| const machine = await sdk.OlmMachine.initialize( | |
| new sdk.UserId(userId), new sdk.DeviceId(deviceId), storeName, storePassphrase, | |
| ); | |
| // Close the Matrix in-band key-forwarding attack surface (Albrecht et al. | |
| // IEEE S&P 2023) and enforce joined-only / 21-day retention: room keys are | |
| // never forwarded or requested over to-device messages. | |
| machine.roomKeyForwardingEnabled = false; | |
| machine.roomKeyRequestsEnabled = false; | |
| const c = new TaperCrypto(sdk, machine, request, userId, { maxKeyAgeMs }); | |
| await c.flush(); | |
| return c; | |
| } | |
| constructor(sdk, machine, request, userId, { maxKeyAgeMs = MAX_KEY_AGE_MS } = {}) { | |
| this.sdk = sdk; | |
| this.machine = machine; | |
| this.request = request; | |
| this.userId = userId; | |
| this.maxKeyAgeMs = maxKeyAgeMs; | |
| this.queue = Promise.resolve(); | |
| // (room, sender, Megolm session ID, message index) -> event ID, to reject | |
| // replays. Scoped by room and sender so one room can't DoS another. | |
| this.seenIndices = new Map(); | |
| this.seenAt = new Map(); // same keys -> when we saw it, to forget after the retention period | |
| // session_id -> timestamp first seen on this device (or 0 for an expired | |
| // tombstone), to enforce client-side retention (21d + 1d margin). | |
| this.sessionSeenAt = new Map(); | |
| // On-demand key refreshes in decrypt(): at most one per sender per minute | |
| // and KEY_REFRESHES_PER_MIN overall, so spam from unsigned devices can't | |
| // burn our t.keys.query budget. Concurrent decrypts share one refresh. | |
| this.lastKeyRefresh = new Map(); | |
| this.keyRefreshInFlight = new Map(); | |
| this.refreshTimes = []; | |
| this.onSeenChanged = null; | |
| this.onTrustChanged = null; // (userId) when decrypt() finds an identity changed since verification | |
| // Called with a TaperVerification when another user asks to verify us. | |
| this.onVerificationRequest = null; | |
| this.onHardwareKeys = null; | |
| this.onKeysChanged = null; // new room keys may need backing up | |
| this.verificationRequests = new WeakSet(); | |
| } | |
| /** The replay table as a list, without entries older than `maxAgeMs`. */ | |
| exportSeen(maxAgeMs = this.maxKeyAgeMs) { | |
| const out = []; | |
| const cutoff = Date.now() - maxAgeMs; | |
| for (const [k, eventId] of this.seenIndices) { | |
| const t = this.seenAt.get(k) ?? 0; | |
| if (t >= cutoff) out.push([k, eventId, t]); | |
| } | |
| return out; | |
| } | |
| /** First-seen timestamps of Megolm sessions plus expired tombstones (`0`). */ | |
| exportSessionAges(maxAgeMs = this.maxKeyAgeMs) { | |
| const out = []; | |
| const cutoff = Date.now() - maxAgeMs; | |
| for (const [sid, t] of this.sessionSeenAt) { | |
| out.push([sid, t === 0 || t < cutoff ? 0 : t]); | |
| } | |
| return out; | |
| } | |
| restoreSeen(list, sessions = []) { | |
| for (const [k, eventId, t] of Array.isArray(list) ? list : []) { | |
| if (typeof k === 'string' && typeof eventId === 'string' && Number.isFinite(t)) { this.seenIndices.set(k, eventId); this.seenAt.set(k, t); } | |
| } | |
| for (const [sid, t] of Array.isArray(sessions) ? sessions : []) { | |
| if (typeof sid === 'string' && Number.isFinite(t)) this.sessionSeenAt.set(sid, t); | |
| } | |
| } | |
| /** Tombstone Megolm sessions older than retention and drop expired replay indices. */ | |
| pruneExpiredSessions(nowMs = Date.now()) { | |
| const cutoff = nowMs - this.maxKeyAgeMs; | |
| let changed = false; | |
| for (const [k, t] of this.seenAt) { | |
| if (t < cutoff) { this.seenAt.delete(k); this.seenIndices.delete(k); changed = true; } | |
| } | |
| // Keep a `0` tombstone for expired sessions instead of deleting the entry: | |
| // deleting would cause decrypt() to treat an existing IndexedDB key as new. | |
| for (const [sid, t] of this.sessionSeenAt) { | |
| if (t > 0 && t < cutoff) { this.sessionSeenAt.set(sid, 0); changed = true; } | |
| } | |
| if (changed) this.onSeenChanged?.(); | |
| } | |
| /** Room keys whose session IDs aren't in `skip` and have a valid unexpired age. */ | |
| async exportNewRoomKeys(skip) { | |
| const ids = []; | |
| const cutoff = Date.now() - this.maxKeyAgeMs; | |
| const json = await this.serial(() => this.machine.exportRoomKeys((s) => { | |
| if (skip.has(s.sessionId)) return false; | |
| const seen = this.sessionSeenAt.get(s.sessionId); | |
| // Treat unknown (`undefined`) or tombstoned (`0`) or expired ages as ineligible. | |
| if (seen === undefined || seen === 0 || seen < cutoff) return false; | |
| ids.push(s.sessionId); | |
| return true; | |
| })); | |
| return { json, ids }; | |
| } | |
| /** | |
| * Import room keys exported by exportNewRoomKeys. `seenAtMs` is when they | |
| * were backed up (the start of the backup part's day): keys older than | |
| * retention, or already tombstoned here, are skipped. Returns their session IDs. | |
| */ | |
| async importRoomKeys(json, { seenAtMs = Date.now() } = {}) { | |
| const cutoff = Date.now() - this.maxKeyAgeMs; | |
| if (!Number.isFinite(seenAtMs) || seenAtMs < cutoff) return []; | |
| const fresh = JSON.parse(json).filter((k) => { | |
| const seen = this.sessionSeenAt.get(k.session_id); | |
| return seen === undefined || (seen > 0 && seen >= cutoff); | |
| }); | |
| if (!fresh.length) return []; | |
| await this.serial(() => this.machine.importExportedRoomKeys(JSON.stringify(fresh), () => {})); | |
| // Never refresh an existing age: only stamp sessions we didn't know. | |
| for (const k of fresh) if (!this.sessionSeenAt.has(k.session_id)) this.sessionSeenAt.set(k.session_id, seenAtMs); | |
| this.onSeenChanged?.(); | |
| return fresh.map((k) => k.session_id); | |
| } | |
| /** Immediately rotate the outbound Megolm session for `roomId` (e.g. on leave, kick, ban, or device change). */ | |
| async invalidateRoomSession(roomId) { | |
| return this.serial(() => this.machine.invalidateGroupSession(new this.sdk.RoomId(roomId))); | |
| } | |
| // Serialise everything that touches the machine; it isn't re-entrant with | |
| // respect to outgoing requests. | |
| serial(fn) { | |
| const run = this.queue.then(fn, fn); | |
| this.queue = run.catch(() => {}); | |
| return run; | |
| } | |
| async sendRequest(req) { | |
| const { RequestType } = this.sdk; | |
| const body = JSON.parse(req.body); | |
| let response; | |
| switch (req.type) { | |
| case RequestType.KeysUpload: response = await this.request('t.keys.upload', body); break; | |
| case RequestType.KeysQuery: | |
| response = await this.request('t.keys.query', body); | |
| // What each user's server says about their security keys (opt-in). | |
| this.onHardwareKeys?.(response.hardware_keys ?? {}, Object.keys(body.device_keys ?? {})); | |
| break; | |
| case RequestType.KeysClaim: response = await this.request('t.keys.claim', body); break; | |
| case RequestType.SignatureUpload: response = await this.request('t.keys.signatures.upload', body); break; | |
| case RequestType.ToDevice: { | |
| const messages = {}; | |
| for (const [user, devices] of Object.entries(body.messages)) { | |
| messages[user] = {}; | |
| for (const [device, content] of Object.entries(devices)) { | |
| messages[user][device] = translateContent(content, toTaperName); | |
| } | |
| } | |
| response = await this.request('t.to_device.send', { | |
| event_type: toTaperName(req.event_type), txn_id: req.txn_id, messages, | |
| }); | |
| break; | |
| } | |
| default: | |
| return; // room messages for verification, key backup: not supported yet | |
| } | |
| try { | |
| await this.machine.markRequestAsSent(req.id, req.type, JSON.stringify(response)); | |
| } catch (e) { | |
| if (!this.verificationRequests?.has(req)) throw e; | |
| } | |
| } | |
| // Send everything the machine wants sent (key uploads, queries, ...). | |
| flush() { | |
| return this.serial(async () => { | |
| for (let round = 0; round < 10; round++) { | |
| const reqs = await this.machine.outgoingRequests(); | |
| if (!reqs.length) return; | |
| for (const req of reqs) await this.sendRequest(req); | |
| } | |
| }); | |
| } | |
| /** Feed gateway dispatches to the machine: to-device events, device list changes, key counts. */ | |
| async receive({ toDevice = [], changed = [], left = [], oneTimeKeyCounts = null } = {}) { | |
| const { UserId, DeviceLists, DecryptionSettings, TrustRequirement } = this.sdk; | |
| const incoming = toDevice.filter((e) => e.type === 't.key.verification.request'); | |
| await this.serial(async () => { | |
| const events = toDevice.map(toMatrixEvent); | |
| const counts = new Map(Object.entries(oneTimeKeyCounts ?? {})); | |
| await this.machine.receiveSyncChanges( | |
| JSON.stringify(events), | |
| new DeviceLists(changed.map((u) => new UserId(u)), left.map((u) => new UserId(u))), | |
| counts, | |
| new Set(), | |
| new DecryptionSettings(TrustRequirement.CrossSigned), | |
| ); | |
| if (toDevice.length) { | |
| // Stamp newly received inbound room keys immediately so exportNewRoomKeys | |
| // can strictly require a known, unexpired age for every backed-up key. | |
| const nowMs = Date.now(); | |
| let stamped = false; | |
| await this.machine.exportRoomKeys((s) => { | |
| if (!this.sessionSeenAt.has(s.sessionId)) { this.sessionSeenAt.set(s.sessionId, nowMs); stamped = true; } | |
| return false; | |
| }); | |
| if (stamped) this.onSeenChanged?.(); | |
| } | |
| }); | |
| await this.flush(); | |
| if (toDevice.length) this.onKeysChanged?.(); | |
| for (const e of incoming) { | |
| const request = this.machine.getVerificationRequest(new UserId(e.sender), e.content?.transaction_id); | |
| if (request && this.onVerificationRequest) this.onVerificationRequest(new TaperVerification(this, request, e.sender)); | |
| } | |
| } | |
| /** Start tracking users' devices and identities, and fetch them now. */ | |
| async trackUsers(userIds) { | |
| const { UserId } = this.sdk; | |
| await this.serial(() => this.machine.updateTrackedUsers(userIds.map((u) => new UserId(u)))); | |
| await this.flush(); | |
| } | |
| /** Ask another user to verify, using one of their cross-signed devices. */ | |
| async startVerification(userId) { | |
| const { UserId, VerificationMethod } = this.sdk; | |
| await this.serial(() => this.machine.updateTrackedUsers([new UserId(userId)])); | |
| await this.flush(); | |
| const devices = await this.serial(() => this.machine.getUserDevices(new UserId(userId))); | |
| const target = devices.devices().find((d) => d.isCrossSignedByOwner()); | |
| if (!target) throw new Error(`${userId} has no cross-signed device to verify`); | |
| const [request, outgoing] = target.requestVerification([VerificationMethod.SasV1]); | |
| await this.sendVerification(outgoing); | |
| return new TaperVerification(this, request, userId); | |
| } | |
| async sendVerification(req) { | |
| if (!req) return; | |
| this.verificationRequests.add(req); | |
| await this.serial(() => this.sendRequest(req)); | |
| await this.flush(); | |
| } | |
| /** Track room members, open Olm sessions to their devices and share the room key. */ | |
| async shareRoomKey(roomId, members, { verifiedOnly = false } = {}) { | |
| const { UserId, RoomId, EncryptionSettings, HistoryVisibility, CollectStrategy } = this.sdk; | |
| const users = () => members.map((u) => new UserId(u)); | |
| await this.serial(() => this.machine.updateTrackedUsers(users())); | |
| await this.flush(); | |
| if (verifiedOnly) { | |
| const unverified = []; | |
| for (const u of members) { | |
| if (u === this.userId) continue; | |
| if ((await this.identityTrust(u)) !== 'verified') unverified.push(u); | |
| } | |
| if (unverified.length) { | |
| throw new Error(`Verified-only room: refusing to send to unverified member(s): ${unverified.join(', ')}`); | |
| } | |
| } | |
| await this.serial(async () => { | |
| const claim = await this.machine.getMissingSessions(users()); | |
| if (claim) await this.sendRequest(claim); | |
| const settings = new EncryptionSettings(); | |
| settings.historyVisibility = HistoryVisibility.Joined; | |
| settings.rotationPeriod = DAY_MICROS; | |
| settings.rotationPeriodMessages = 100n; | |
| // In verified-only mode, only verified users' cross-signed devices get keys | |
| // (stops a malicious server injecting an unverified spy into the room). | |
| // Otherwise share only with devices their owner has cross-signed. | |
| settings.sharingStrategy = verifiedOnly ? CollectStrategy.onlyTrustedDevices() : CollectStrategy.identityBasedStrategy(); | |
| settings.encryptStateEvents = true; | |
| const reqs = await this.machine.shareRoomKey(new RoomId(roomId), users(), settings); | |
| for (const req of reqs) await this.sendRequest(req); | |
| }); | |
| } | |
| /** | |
| * Make sure the account has a cross-signing identity and that this device | |
| * is signed by it. Returns 'ok', 'created', 'reset', or 'needs-password' | |
| * when another device created the identity and we can't co-sign without | |
| * replacing it. Replacing needs `reauth`, an async function returning fresh | |
| * proof of the password (an OPAQUE `auth` object, see opaque.js). | |
| * | |
| * Pass `forceReset: true` (with `reauth`) to intentionally replace a | |
| * compromised cross-signing identity. | |
| */ | |
| async ensureCrossSigning({ reauth, exportKey, forceReset = false } = {}) { | |
| const { UserId } = this.sdk; | |
| const status = await this.serial(() => this.machine.crossSigningStatus()); | |
| await this.serial(() => this.machine.updateTrackedUsers([new UserId(this.userId)])); | |
| await this.flush(); | |
| const existing = await this.serial(() => this.machine.getIdentity(new UserId(this.userId))); | |
| // Local private keys only count if they belong to the identity the server | |
| // holds: a failed upload leaves keys here that nobody else knows about. | |
| const complete = status.hasMaster && status.hasSelfSigning && status.hasUserSigning; | |
| if (!forceReset && complete && existing && await existing.trustsOurOwnDevice()) return 'ok'; | |
| if (!forceReset && existing && exportKey && await this.recoverIdentity(exportKey)) return 'recovered'; | |
| if (existing && !reauth) return 'needs-password'; | |
| // Prove the password before creating any keys, so a wrong password | |
| // changes nothing. | |
| const auth = existing ? await reauth() : undefined; | |
| await this.serial(async () => { | |
| const reqs = await this.machine.bootstrapCrossSigning(true); | |
| if (reqs.uploadKeysRequest) await this.sendRequest(reqs.uploadKeysRequest); | |
| const signing = JSON.parse(reqs.uploadSigningKeysRequest.body); | |
| await this.request('t.keys.device_signing.upload', auth ? { ...signing, auth } : signing); | |
| // Bootstrap requests have no request ID, so they are sent, not marked. | |
| const res = await this.request('t.keys.signatures.upload', JSON.parse(reqs.uploadSignaturesRequest.body)); | |
| if (Object.keys(res.failures ?? {}).length) throw new Error(`Signature upload failed: ${JSON.stringify(res.failures)}`); | |
| // Refresh our own device record so local cross-signing status is up to date immediately. | |
| await this.sendRequest(this.machine.queryKeysForUsers([new UserId(this.userId)])); | |
| }); | |
| await this.flush(); | |
| // Store the new identity, sealed. Replacing a stored copy needs another | |
| // proof: each one is single use. | |
| if (exportKey) await this.saveIdentity(exportKey, existing ? { auth: await reauth() } : {}); | |
| return existing ? 'reset' : 'created'; | |
| } | |
| /** This account's cross-signing private keys, sealed under `exportKey`. */ | |
| async sealIdentity(exportKey) { | |
| const keys = await this.serial(() => this.machine.exportCrossSigningKeys()); | |
| if (!keys?.masterKey || !keys.self_signing_key || !keys.userSigningKey) throw new Error('No complete cross-signing identity to save'); | |
| return sealSecrets(exportKey, this.userId, { | |
| master: keys.masterKey, self_signing: keys.self_signing_key, user_signing: keys.userSigningKey, | |
| }); | |
| } | |
| /** Seal this account's cross-signing private keys and store them on the server. */ | |
| async saveIdentity(exportKey, { auth } = {}) { | |
| const secrets = await this.sealIdentity(exportKey); | |
| await this.request('t.secrets.put', auth ? { secrets, auth } : { secrets }); | |
| } | |
| /** | |
| * Recover the cross-signing identity from the server's sealed copy and sign | |
| * this device with it. Returns true if this device is now trusted by the | |
| * identity, false if there is no copy or it can't be opened. | |
| */ | |
| async recoverIdentity(exportKey) { | |
| const { secrets } = await this.request('t.secrets.get', {}); | |
| if (!secrets) return false; | |
| let keys; | |
| try { keys = await openSecrets(exportKey, this.userId, secrets); } catch { return false; } | |
| const { UserId } = this.sdk; | |
| return this.serial(async () => { | |
| // The library checks that the keys match the published identity. | |
| const status = await this.machine.importCrossSigningKeys(keys.master, keys.self_signing, keys.user_signing); | |
| if (!status.hasMaster || !status.hasSelfSigning || !status.hasUserSigning) return false; | |
| const device = await this.machine.getDevice(new UserId(this.userId), this.machine.deviceId); | |
| const req = await device.verify(); | |
| // Like the bootstrap requests, this one has no request ID: send it. | |
| const res = await this.request('t.keys.signatures.upload', JSON.parse(req.body)); | |
| return !Object.keys(res.failures ?? {}).length; | |
| }).then(async (ok) => { | |
| if (!ok) return false; | |
| // Re-query our own keys, which now carry the new signature. | |
| await this.serial(() => this.machine.markAllTrackedUsersAsDirty()); | |
| await this.flush(); | |
| const identity = await this.serial(() => this.machine.getIdentity(new this.sdk.UserId(this.userId))); | |
| return Boolean(identity && await identity.trustsOurOwnDevice()); | |
| }); | |
| } | |
| /** | |
| * Trust in a user's identity: | |
| * 'verified' we verified it (emoji) and it hasn't changed | |
| * 'violation' we verified it, and it has since changed: verify again | |
| * 'changed' it changed since we first saw it (unverified): approve or verify | |
| * 'unverified' seen, never verified | |
| * 'none' no cross-signing identity | |
| */ | |
| async identityTrust(userId) { | |
| const id = await this.serial(() => this.machine.getIdentity(new this.sdk.UserId(userId))); | |
| if (!id) return 'none'; | |
| if (typeof id.hasVerificationViolation !== 'function') return id.isVerified() ? 'verified' : 'unverified'; | |
| if (id.hasVerificationViolation()) return 'violation'; | |
| if (id.isVerified()) return 'verified'; | |
| if (id.identityNeedsUserApproval()) return 'changed'; | |
| return 'unverified'; | |
| } | |
| /** Accept a changed identity for a user we haven't verified (trust on first use again). */ | |
| async approveIdentity(userId) { | |
| const id = await this.serial(() => this.machine.getIdentity(new this.sdk.UserId(userId))); | |
| if (id && typeof id.pinCurrentMasterKey === 'function') await this.serial(() => id.pinCurrentMasterKey()); | |
| } | |
| /** | |
| * Encrypt a message for a room. Returns `t.room.encrypted` content, with the | |
| * room version 13 `binding` inside and outside the ciphertext, an encrypted | |
| * `sender_ts` to detect server timestamp manipulation, and the plaintext | |
| * padded to its Padme bucket. | |
| */ | |
| async encrypt(roomId, members, type, content, { attachments, verifiedOnly = false, relatesTo } = {}) { | |
| await this.shareRoomKey(roomId, members, { verifiedOnly }); | |
| const binding = randomB64(16); | |
| const sender_ts = Date.now(); | |
| const rel = relatesTo ?? content?.['t.relates_to']; | |
| const plaintext = padJson({ ...content, ...(rel !== undefined ? { 't.relates_to': rel } : {}), binding, sender_ts }); | |
| const json = await this.serial(() => this.machine.encryptRoomEvent( | |
| new this.sdk.RoomId(roomId), type, JSON.stringify(plaintext), | |
| )); | |
| const outer = JSON.parse(json); | |
| if (typeof outer.session_id === 'string' && !this.sessionSeenAt.has(outer.session_id)) { | |
| this.sessionSeenAt.set(outer.session_id, sender_ts); | |
| this.onSeenChanged?.(); | |
| } | |
| this.onKeysChanged?.(); | |
| return { | |
| ...translateContent(outer, toTaperName), | |
| binding, | |
| ...(attachments?.length ? { attachments } : {}), | |
| ...(rel !== undefined ? { 't.relates_to': rel } : {}), | |
| }; | |
| } | |
| /** | |
| * Encrypt a state event (room version 13 encrypted state, MSC4362 format). | |
| * Returns { type: 't.room.encrypted', state_key: '{type}:{state_key}', content }. | |
| */ | |
| async encryptState(roomId, members, type, stateKey, content, { verifiedOnly = false } = {}) { | |
| await this.shareRoomKey(roomId, members, { verifiedOnly }); | |
| const binding = randomB64(16); | |
| const sender_ts = Date.now(); | |
| const plaintext = padJson({ ...content, binding, sender_ts }); | |
| const json = await this.serial(() => this.machine.encryptStateEvent( | |
| new this.sdk.RoomId(roomId), type, stateKey, JSON.stringify(plaintext), | |
| )); | |
| const outer = JSON.parse(json); | |
| if (typeof outer.session_id === 'string' && !this.sessionSeenAt.has(outer.session_id)) { | |
| this.sessionSeenAt.set(outer.session_id, sender_ts); | |
| this.onSeenChanged?.(); | |
| } | |
| this.onKeysChanged?.(); | |
| return { type: 't.room.encrypted', state_key: `${type}:${stateKey}`, content: { ...translateContent(outer, toTaperName), binding } }; | |
| } | |
| /** | |
| * Decrypt an `t.room.encrypted` event and apply the room version 13 checks. | |
| * Returns { type, content } or throws with a reason. | |
| */ | |
| async decrypt(ev) { | |
| const { RoomId, UserId, DecryptionSettings, TrustRequirement } = this.sdk; | |
| if (ev.content?.algorithm !== TAPER_ALGORITHM) throw new Error('Unsupported encryption algorithm'); | |
| // Client-side retention enforcement on inbound Megolm sessions. | |
| const sid = ev.content?.session_id; | |
| const nowMs = Date.now(); | |
| if (typeof sid === 'string') { | |
| const firstSeen = this.sessionSeenAt.get(sid); | |
| if (firstSeen === 0 || (firstSeen !== undefined && nowMs - firstSeen > this.maxKeyAgeMs)) { | |
| if (firstSeen !== 0) { this.sessionSeenAt.set(sid, 0); this.onSeenChanged?.(); } | |
| throw new Error('Room key has expired past retention'); | |
| } | |
| } | |
| if (ev.state_key === undefined) { | |
| if (!Number.isFinite(ev.origin_server_ts)) throw new Error('Message has no valid timestamp'); | |
| if (nowMs - ev.origin_server_ts > this.maxKeyAgeMs) throw new Error('Message has expired past retention'); | |
| } | |
| let res; | |
| try { | |
| res = await this.serial(() => this.machine.decryptRoomEvent( | |
| JSON.stringify(toMatrixEvent(ev)), new RoomId(ev.room_id), new DecryptionSettings(TrustRequirement.Untrusted), | |
| )); | |
| } catch (e) { | |
| // The library throws plain objects for decryption failures. | |
| throw e instanceof Error ? e : new Error(e?.description ?? e?.message ?? 'Unable to decrypt'); | |
| } | |
| const payload = JSON.parse(res.event); | |
| const { ShieldStateCode } = this.sdk; | |
| const code = res.shieldState(true).code; | |
| // 1. The session must belong to a cross-signed device of the event's sender. | |
| // Rejecting non-cross-signed devices stops malicious homeserver ghost | |
| // device impersonation (Albrecht et al. IEEE S&P 2023). | |
| // `res.sender` only echoes ev.sender back; the shield compares the | |
| // session's real owner. Check it before any key refresh for ev.sender. | |
| if (code === ShieldStateCode.MismatchedSender) throw new Error('Session belongs to someone else'); | |
| if (code === ShieldStateCode.VerificationViolation) throw this.violation(ev.sender); | |
| const findDevice = async () => { | |
| const devices = await this.serial(() => this.machine.getUserDevices(new UserId(ev.sender))); | |
| // A key restored from the backup carries no device ID, only the sender's | |
| // Curve25519 key: find the device that owns it. | |
| return (res.senderDevice ? devices.get(res.senderDevice) : undefined) | |
| ?? devices.devices().find((d) => d.curve25519Key?.toBase64() === res.senderCurve25519Key); | |
| }; | |
| let device = await findDevice(); | |
| if (!device || !device.isCrossSignedByOwner()) { | |
| let pendingRefresh = this.keyRefreshInFlight.get(ev.sender); | |
| this.refreshTimes = this.refreshTimes.filter((t) => nowMs - t < 60_000); | |
| if (!pendingRefresh && nowMs - (this.lastKeyRefresh.get(ev.sender) ?? 0) >= 60_000 && this.refreshTimes.length < KEY_REFRESHES_PER_MIN) { | |
| this.lastKeyRefresh.set(ev.sender, nowMs); | |
| this.refreshTimes.push(nowMs); | |
| pendingRefresh = (async () => { | |
| await this.serial(async () => { | |
| await this.machine.updateTrackedUsers([new UserId(ev.sender)]); | |
| await this.sendRequest(this.machine.queryKeysForUsers([new UserId(ev.sender)])); | |
| }); | |
| await this.flush(); | |
| })().finally(() => { this.keyRefreshInFlight.delete(ev.sender); }); | |
| this.keyRefreshInFlight.set(ev.sender, pendingRefresh); | |
| } | |
| if (pendingRefresh) { | |
| await pendingRefresh; | |
| device = await findDevice(); | |
| } | |
| } | |
| if (!device || device.curve25519Key?.toBase64() !== res.senderCurve25519Key) { | |
| throw new Error('Session does not belong to a known device of the sender'); | |
| } | |
| if (!device.isCrossSignedByOwner()) { | |
| throw new Error('Message sent from an unsigned device'); | |
| } | |
| if (res.senderClaimedEd25519Key && res.senderClaimedEd25519Key !== device.ed25519Key?.toBase64()) { | |
| throw new Error('Session does not belong to a known device of the sender'); | |
| } | |
| const identity = await this.identityTrust(ev.sender); | |
| if (identity === 'violation') throw this.violation(ev.sender); | |
| // Encrypted state: the packed state_key must match what was encrypted. | |
| if (ev.state_key !== undefined) { | |
| const sep = ev.state_key.indexOf(':'); | |
| if (sep <= 0 || payload.state_key === undefined) throw new Error('Malformed encrypted state'); | |
| if (ev.state_key.slice(0, sep) !== payload.type || ev.state_key.slice(sep + 1) !== payload.state_key) { | |
| throw new Error('Encrypted state does not match its state key'); | |
| } | |
| } else if (payload.state_key !== undefined) { | |
| throw new Error('Encrypted state sent as a message'); | |
| } | |
| // 2. Room (mandatory check, never skipped when undefined). | |
| if (payload.room_id !== ev.room_id) throw new Error('Message belongs to another room'); | |
| // 3. Binding (must be a non-empty >=128-bit string matching both inside and outside). | |
| if (typeof ev.content?.binding !== 'string' || ev.content.binding.length < 22 || payload.content?.binding !== ev.content.binding) { | |
| throw new Error('Message was moved from another event'); | |
| } | |
| // Relations (Room v13): unencrypted `t.relates_to` must match the encrypted copy. | |
| const outerRel = ev.content?.['t.relates_to']; | |
| const innerRel = payload.content?.['t.relates_to']; | |
| if (outerRel !== undefined || innerRel !== undefined) { | |
| if (canonicalJson(outerRel ?? null) !== canonicalJson(innerRel ?? null)) { | |
| throw new Error('Event relation does not match encrypted payload'); | |
| } | |
| } | |
| // Media: every content URI the message mentions must be listed in the | |
| // cleartext `attachments` (Scraping Resistance, "Media bound to rooms"). | |
| const listed = new Set(Array.isArray(ev.content.attachments) ? ev.content.attachments : []); | |
| const mentioned = []; | |
| const walk = (v) => { | |
| if (typeof v === 'string') { if (v.startsWith('runit://')) mentioned.push(v); } else if (v && typeof v === 'object') Object.values(v).forEach(walk); | |
| }; | |
| walk(payload.content); | |
| if (mentioned.some((u) => !listed.has(u))) throw new Error('Message refers to media it does not list in attachments'); | |
| // 4. Replay: the same (room, sender, session, index) may only ever appear in one event. | |
| const index = megolmMessageIndex(ev.content.ciphertext); | |
| if (index === null) throw new Error('Malformed Megolm message'); | |
| const replayKey = `${ev.room_id}|${ev.sender}|${ev.content.session_id}|${index}`; | |
| const seen = this.seenIndices.get(replayKey); | |
| if (seen !== undefined && seen !== ev.event_id) throw new Error('Replayed message'); | |
| let stateDirty = false; | |
| if (!this.seenIndices.has(replayKey)) { | |
| this.seenIndices.set(replayKey, ev.event_id); | |
| this.seenAt.set(replayKey, nowMs); | |
| stateDirty = true; | |
| } | |
| if (typeof sid === 'string' && !this.sessionSeenAt.has(sid)) { | |
| this.sessionSeenAt.set(sid, nowMs); | |
| stateDirty = true; | |
| this.onKeysChanged?.(); | |
| } | |
| if (stateDirty) this.onSeenChanged?.(); | |
| const { binding: _b, pad: _p, sender_ts: senderTs, ...content } = payload.content; | |
| if (Number.isFinite(senderTs) && nowMs - senderTs > this.maxKeyAgeMs) throw new Error('Message has expired past retention'); | |
| // Detect server-side timestamp tampering (backdating / forward-dating). | |
| const tsWarning = typeof senderTs === 'number' && Number.isFinite(ev.origin_server_ts) | |
| && Math.abs(ev.origin_server_ts - senderTs) > MAX_CLOCK_SKEW_MS | |
| ? 'server timestamp differs from sender clock' | |
| : undefined; | |
| // Strict shield: no code means a verified sender on a device they | |
| // signed. UnverifiedIdentity is ordinary; anything else is a warning. | |
| const reasons = { | |
| [ShieldStateCode.AuthenticityNotGuaranteed]: 'authenticity not guaranteed', | |
| [ShieldStateCode.UnknownDevice]: 'sent from an unknown device', | |
| [ShieldStateCode.UnsignedDevice]: 'sent from a device its owner never signed', | |
| }; | |
| let trust = code === undefined ? 'verified' : code === ShieldStateCode.UnverifiedIdentity ? 'unverified' : 'warning'; | |
| // The shield reflects trust when the room key arrived. If we have since | |
| // verified the sender, and this device is one they signed, it's verified. | |
| if (trust === 'unverified' && identity === 'verified') { | |
| trust = 'verified'; | |
| } | |
| if (tsWarning) trust = 'warning'; | |
| return { | |
| type: payload.type, state_key: payload.state_key, content, senderDevice: device.deviceId.toString(), | |
| trust, trustMessage: tsWarning ?? reasons[code] ?? (trust === 'unverified' ? 'sender not verified by you' : undefined), | |
| }; | |
| } | |
| /** The error for a sender whose identity changed since we verified them; tells the UI too. */ | |
| violation(userId) { | |
| this.onTrustChanged?.(userId); | |
| return new Error('Sender changed identity since you verified them'); | |
| } | |
| close() { | |
| this.machine.close(); | |
| } | |
| } | |
| /** | |
| * One emoji (SAS) verification with another user. Either side can drive it: | |
| * the requester calls start() once the other side has accepted; the other | |
| * side calls accept(). Both compare emoji() and then call confirm() or | |
| * cancel(). onChange is called whenever the state may have changed. | |
| */ | |
| export class TaperVerification { | |
| constructor(tc, request, userId) { | |
| this.tc = tc; | |
| this.request = request; | |
| this.userId = userId; | |
| this.onChange = null; | |
| this.sasHooked = false; | |
| request.registerChangesCallback(async () => { await this.hookSas(); this.onChange?.(); }); | |
| } | |
| get sas() { | |
| const v = this.request.getVerification(); | |
| return v && typeof v.emoji === 'function' ? v : null; | |
| } | |
| async hookSas() { | |
| const sas = this.sas; | |
| if (!sas || this.sasHooked) return; | |
| this.sasHooked = true; | |
| sas.registerChangesCallback(async () => { this.onChange?.(); }); | |
| // The side that didn't start SAS accepts it automatically; both sides | |
| // still have to compare and confirm the emoji. | |
| if (!sas.hasBeenAccepted() && !this.request.weStarted()) await this.tc.sendVerification(sas.accept()); | |
| } | |
| /** 'waiting', 'ready', 'emoji', 'confirmed', 'done' or 'cancelled'. */ | |
| state() { | |
| const r = this.request; | |
| if (r.isCancelled() || this.sas?.isCancelled()) return 'cancelled'; | |
| if (r.isDone() || this.sas?.isDone()) return 'done'; | |
| if (this.sas?.haveWeConfirmed()) return 'confirmed'; | |
| if (this.sas?.canBePresented()) return 'emoji'; | |
| if (r.isReady()) return 'ready'; | |
| return 'waiting'; | |
| } | |
| async accept() { await this.tc.sendVerification(this.request.accept()); } | |
| async start() { | |
| const res = await this.request.startSas(); | |
| if (!res) return; | |
| const [, outgoing] = res; | |
| await this.tc.sendVerification(outgoing); | |
| await this.hookSas(); | |
| } | |
| /** The seven emoji to compare: [{ symbol, description }]. */ | |
| emoji() { | |
| return (this.sas?.emoji() ?? []).map((e) => ({ symbol: e.symbol, description: e.description })); | |
| } | |
| async confirm() { | |
| const outgoing = await this.sas.confirm(); | |
| for (const req of outgoing) await this.tc.sendVerification(req); | |
| await this.tc.flush(); | |
| } | |
| async cancel() { | |
| await this.tc.sendVerification(this.sas?.cancel() ?? this.request.cancel()); | |
| } | |
| } | |