File size: 27,245 Bytes
42128a6 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 | // End-to-end encryption support: device keys, one-time and fallback keys
// (with the claim quota that stops one-time-key exhaustion), cross-signing,
// user signatures and to-device messages. The server stores public keys and
// relays ciphertext; it never sees message plaintext or private keys.
// Owns all of those maps. Trust boundary: every key and signature a client
// uploads is verified here; who may see or claim keys, or send to-device
// messages, is limited to users who share a joined room.
import { fail, isPlainObject, requireObject, requireString, canonicalJson, verifySigned } from './events.js';
import { isValidUserId } from './state-res.js';
import { fromPeer, claimFromPeer } from './fed.js';
import { devicesIn, sizeOf, one } from './quota.js';
import { now, dropWhere } from './util.js';
const MAX_ONE_TIME_KEYS = 100;
const MAX_TO_DEVICE_MESSAGES = 1000;
const MAX_TO_DEVICE_QUEUE = 200;
// One-time key exhaustion defense: cap how many OTKs a single requester OR all
// requesters combined can drain from a target device within a rolling 5-minute
// window, stopping both single-account and sybil/federated fallback-key forcing.
const OTK_CLAIM_WINDOW_MS = 5 * 60_000;
const devKey = (user_id, device_id) => `${user_id}|${device_id}`;
export function create(app) {
const { cfg, disk } = app;
const { txnIds } = app.state;
const { OTK_CLAIM_LIMIT, OTK_DEVICE_LIMIT } = cfg;
const dispatchToUser = (...a) => app.sessions.dispatchToUser(...a);
const sharesRoom = (a, b) => app.rooms.sharesRoom(a, b);
const deviceKeys = new Map(); // `${user}|${device}` -> signed device keys
const oneTimeKeys = new Map(); // `${user}|${device}` -> Map(key ID -> signed key)
const fallbackKeys = new Map(); // `${user}|${device}` -> { id, key }
// Cross-signing: user -> { master, self_signing, user_signing } (Matrix
// CrossSigningKey objects). Signatures that one user makes on another
// user's master key are visible only to the signer:
// target user -> signer -> { key ID -> signature }.
const crossSigning = new Map();
const userSignatures = new Map();
const toDeviceQueue = new Map(); // `${user}|${device}` -> [{ sender, type, content, ts }]
const otkClaims = new Map(); // `${requester}|${targetUser}|${targetDevice}` -> { count, since }
const otkDeviceClaims = new Map(); // `${targetUser}|${targetDevice}` -> { count, since }
function devicesOf(user_id) {
const out = [];
for (const [k, keys] of deviceKeys) if (k.startsWith(`${user_id}|`)) out.push(keys.device_id);
return out;
}
const oneTimeKeyCounts = (k) => ({ signed_curve25519: oneTimeKeys.get(k)?.size ?? 0 });
// Tell everyone who shares a joined room with user_id to fetch their keys again.
function notifyDeviceListChange(user_id) {
const peers = app.rooms.peersOf(user_id);
const servers = app.isLocalUser(user_id) ? new Set([...peers].filter((u) => !app.isLocalUser(u)).map(app.serverOf)) : [];
for (const server of servers) {
app.fed.connectPeer(server).then((c) => c.request('t.fed.send', { pdus: [], edus: [{ type: 't.device_list_update', user_id }] }))
.catch((e) => console.error(`device list update to ${server} failed: ${e.message}`));
}
for (const member of peers) dispatchToUser(member, 't.device_lists', { changed: [user_id] });
}
function persistQueue(k) {
const queue = toDeviceQueue.get(k);
if (queue?.length) disk.seal('to_device', k, queue);
else disk.delSealed('to_device', k);
}
function deliverToDevice(user_id, device_id, message) {
const live = app.sessions.ofDevice(user_id, device_id);
if (live.length) {
for (const s of live) s.dispatch('t.to_device', { events: [message] });
return;
}
const k = devKey(user_id, device_id);
const queue = toDeviceQueue.get(k) ?? [];
queue.push({ ...message, ts: now() });
while (queue.length > MAX_TO_DEVICE_QUEUE) queue.shift();
toDeviceQueue.set(k, queue);
persistQueue(k);
}
// Deliver `devices` ({ device_id or '*': content }) to a local user's devices
// that exist. `count` tallies messages across one request.
function sendToDevices(sender, type, user_id, devices, count) {
for (const [device_id, content] of Object.entries(devices)) {
const targets = device_id === '*' ? devicesOf(user_id) : deviceKeys.has(devKey(user_id, device_id)) ? [device_id] : [];
for (const target of targets) {
if (++count.n > MAX_TO_DEVICE_MESSAGES) fail('T_LIMIT_EXCEEDED', 'Too many to-device messages in one request');
deliverToDevice(user_id, target, { sender, type, content });
}
}
}
function flushToDevice(session) {
const k = devKey(session.user_id, session.device_id);
const queue = toDeviceQueue.get(k);
if (!queue?.length) return;
toDeviceQueue.delete(k);
persistQueue(k);
session.dispatch('t.to_device', { events: queue.map(({ ts: _ts, ...m }) => m) });
}
function forgetDevice(user_id, device_id) {
const k = devKey(user_id, device_id);
const had = deviceKeys.delete(k);
oneTimeKeys.delete(k);
fallbackKeys.delete(k);
toDeviceQueue.delete(k);
for (const ns of ['device_keys', 'one_time_keys', 'fallback_keys']) disk.del(ns, k);
disk.delSealed('to_device', k);
if (had) notifyDeviceListChange(user_id);
}
function takeOtkQuota(requester, targetUser, targetDevice) {
const t = now();
let reqRec = null;
const reqKey = `${requester}|${targetUser}|${targetDevice}`;
if (OTK_CLAIM_LIMIT > 0) {
reqRec = otkClaims.get(reqKey);
if (!reqRec || t - reqRec.since >= OTK_CLAIM_WINDOW_MS) reqRec = { count: 0, since: t };
if (reqRec.count >= OTK_CLAIM_LIMIT) return false;
}
let devRec = null;
const dKey = `${targetUser}|${targetDevice}`;
if (OTK_DEVICE_LIMIT > 0) {
devRec = otkDeviceClaims.get(dKey);
if (!devRec || t - devRec.since >= OTK_CLAIM_WINDOW_MS) devRec = { count: 0, since: t };
if (devRec.count >= OTK_DEVICE_LIMIT) return false;
}
if (reqRec) { reqRec.count++; otkClaims.set(reqKey, reqRec); }
if (devRec) { devRec.count++; otkDeviceClaims.set(dKey, devRec); }
return true;
}
// A master key as `requester` sees it: with the signatures they made on it
// (visible only to them).
function withOwnSignatures(master, user_id, requester) {
const own = userSignatures.get(user_id)?.get(requester);
return own ? { ...master, signatures: { ...master.signatures, [requester]: { ...master.signatures?.[requester], ...own } } } : master;
}
// Local parts of key queries and claims; also serve other servers.
function queryLocal(body, ctx) {
const wanted = requireObject(body, 'device_keys');
const out = { device_keys: {}, failures: {}, master_keys: {}, self_signing_keys: {}, user_signing_keys: {}, hardware_keys: {} };
for (const user_id of Object.keys(wanted)) {
out.device_keys[user_id] = {};
// Users who share no room with the requester look like users with no devices.
if (!sharesRoom(ctx.user_id, user_id)) continue;
const only = Array.isArray(wanted[user_id]) && wanted[user_id].length ? new Set(wanted[user_id]) : null;
for (const device_id of devicesOf(user_id)) {
if (!only || only.has(device_id)) out.device_keys[user_id][device_id] = deviceKeys.get(devKey(user_id, device_id));
}
const cs = crossSigning.get(user_id);
if (cs) {
out.master_keys[user_id] = withOwnSignatures(cs.master, user_id, ctx.user_id);
out.self_signing_keys[user_id] = cs.self_signing;
if (user_id === ctx.user_id) out.user_signing_keys[user_id] = cs.user_signing;
}
// What each user's own server says about their security keys (opt-in).
const level = app.isLocalUser(user_id) ? app.auth.hardwareKeyLevel(user_id) : null;
if (level) out.hardware_keys[user_id] = level;
}
return out;
}
function claimLocal(body, ctx) {
const wanted = requireObject(body, 'one_time_keys');
const one_time_keys = {};
let attempted = 0;
let throttled = 0;
for (const [user_id, devices] of Object.entries(wanted)) {
if (!sharesRoom(ctx.user_id, user_id) || !isPlainObject(devices)) continue;
for (const [device_id, algorithm] of Object.entries(devices)) {
const k = devKey(user_id, device_id);
// Only real devices and the one algorithm draw on a device's claim quota.
if (algorithm !== 'signed_curve25519' || !deviceKeys.has(k)) continue;
attempted++;
if (!takeOtkQuota(ctx.user_id, user_id, device_id)) { throttled++; continue; }
const store = oneTimeKeys.get(k);
let claimed = null;
for (const [id, key] of store ?? []) {
if (id.startsWith(`${algorithm}:`)) {
claimed = { [id]: key };
store.delete(id);
disk.put('one_time_keys', k, Object.fromEntries(store));
break;
}
}
if (!claimed && fallbackKeys.has(k)) {
const fb = fallbackKeys.get(k);
claimed = { [fb.id]: fb.key };
}
if (!claimed) continue;
(one_time_keys[user_id] ??= {})[device_id] = claimed;
for (const s of app.sessions.ofDevice(user_id, device_id)) s.dispatch('t.keys.counts', { one_time_key_counts: oneTimeKeyCounts(k) });
}
}
if (attempted > 0 && throttled === attempted) {
fail('T_LIMIT_EXCEEDED', 'Too many one-time key claims for this device', { retry_after_ms: OTK_CLAIM_WINDOW_MS });
}
return { one_time_keys, failures: {} };
}
// Ask the peers for their users' part of a query or claim.
async function askPeers(wanted, method, field, ctx, merge) {
const { local, remote } = app.fed.splitByServer(wanted);
const result = (method === 't.fed.keys.query' ? queryLocal : claimLocal)({ [field]: local }, ctx);
for (const [server, subset] of remote) {
try {
merge(result, await (await app.fed.connectPeer(server)).request(method, { requester: ctx.user_id, [field]: subset }), server, subset);
} catch (e) {
result.failures[server] = { errcode: 'T_UNAVAILABLE', error: e.message };
}
}
return result;
}
const methods = {
't.keys.upload': { budget: ['keys', one], run(_p, ctx, body) {
const k = devKey(ctx.user_id, ctx.device_id);
const edId = `ed25519:${ctx.device_id}`;
const cvId = `curve25519:${ctx.device_id}`;
let changed = false;
if (body.device_keys !== undefined) {
const { unsigned: _unsigned, ...dk } = requireObject(body, 'device_keys');
for (const f of Object.keys(dk)) if (!['user_id', 'device_id', 'algorithms', 'keys', 'signatures'].includes(f)) fail('T_INVALID_PARAM', `Field '${f}' is not allowed in device_keys`);
if (dk.user_id !== ctx.user_id || dk.device_id !== ctx.device_id) fail('T_INVALID_PARAM', 'device_keys must describe this device');
if (sizeOf(dk.keys) !== 2 || typeof dk.keys[edId] !== 'string' || typeof dk.keys[cvId] !== 'string') {
fail('T_INVALID_PARAM', 'device_keys needs an ed25519 and a curve25519 key for this device, and nothing else');
}
if (!verifySigned(dk, ctx.user_id, edId, dk.keys[edId])) fail('T_INVALID_SIGNATURE', 'device_keys signature does not verify');
const existing = deviceKeys.get(k);
// The same keys again change nothing (and keep the cross-signing
// signature already on them); different keys are a different device.
if (existing && canonicalJson({ ...existing, signatures: {} }) !== canonicalJson({ ...dk, signatures: {} })) {
fail('T_INVALID_PARAM', 'A device\'s keys cannot change; log in as a new device');
}
if (!existing) {
changed = true;
deviceKeys.set(k, dk);
disk.put('device_keys', k, dk);
}
}
const edKey = deviceKeys.get(k)?.keys[edId];
const check = (id, key) => {
if (!edKey) fail('T_INVALID_PARAM', 'Upload device_keys before one-time keys');
if (!id.startsWith('signed_curve25519:') || typeof key?.key !== 'string') fail('T_INVALID_PARAM', `Unsupported key ${id}`);
if (!verifySigned(key, ctx.user_id, edId, edKey)) fail('T_INVALID_SIGNATURE', `Signature on ${id} does not verify`);
};
if (body.one_time_keys) {
const entries = Object.entries(requireObject(body, 'one_time_keys'));
if (entries.length > MAX_ONE_TIME_KEYS) fail('T_LIMIT_EXCEEDED', `At most ${MAX_ONE_TIME_KEYS} one-time keys per upload`);
const store = oneTimeKeys.get(k) ?? new Map();
for (const [id, key] of entries) {
if (store.size >= MAX_ONE_TIME_KEYS && !store.has(id)) break;
check(id, key);
store.set(id, key);
}
oneTimeKeys.set(k, store);
disk.put('one_time_keys', k, Object.fromEntries(store));
}
if (body.fallback_keys) {
const fbs = Object.entries(requireObject(body, 'fallback_keys'));
if (fbs.length > 4) fail('T_LIMIT_EXCEEDED', 'Too many fallback keys in one upload');
for (const [id, key] of fbs) {
check(id, key);
fallbackKeys.set(k, { id, key });
disk.put('fallback_keys', k, { id, key });
}
}
if (changed) notifyDeviceListChange(ctx.user_id);
return { one_time_key_counts: oneTimeKeyCounts(k) };
} },
't.keys.query': { budget: ['lookups', (b) => Math.max(sizeOf(b?.device_keys), 1)], params: { device_keys: 'object' }, run({ device_keys: wanted }, ctx) {
if (Object.keys(wanted).length > 1000) fail('T_LIMIT_EXCEEDED', 'Too many users in one query');
return askPeers(wanted, 't.fed.keys.query', 'device_keys', ctx, (result, r, server, subset) => {
for (const field of ['device_keys', 'self_signing_keys']) Object.assign(result[field], fromPeer(r?.[field], server, subset));
for (const [u, mk] of Object.entries(fromPeer(r?.master_keys, server, subset))) result.master_keys[u] = withOwnSignatures(mk, u, ctx.user_id);
// Only in the two known levels.
for (const [u, level] of Object.entries(isPlainObject(r?.hardware_keys) ? r.hardware_keys : {})) {
if (app.serverOf(u) === server && Object.hasOwn(subset, u) && (level === 'attested' || level === 'unattested')) result.hardware_keys[u] = level;
}
});
} },
't.keys.claim': { budget: ['claims', (b) => devicesIn(b, 'one_time_keys', devicesOf)], params: { one_time_keys: 'object' }, run({ one_time_keys: wanted }, ctx) {
if (Object.keys(wanted).length > 1000) fail('T_LIMIT_EXCEEDED', 'Too many users in one claim');
return askPeers(wanted, 't.fed.keys.claim', 'one_time_keys', ctx, (result, r, server, subset) => {
Object.assign(result.one_time_keys, claimFromPeer(r?.one_time_keys, server, subset));
});
} },
't.keys.device_signing.upload': { run(_p, ctx, body) {
const keys = {};
for (const [field, usage] of [['master_key', 'master'], ['self_signing_key', 'self_signing'], ['user_signing_key', 'user_signing']]) {
const k = requireObject(body, field);
if (k.user_id !== ctx.user_id || !Array.isArray(k.usage) || !k.usage.includes(usage)) fail('T_INVALID_PARAM', `${field} is not a ${usage} key for this user`);
const pubs = Object.entries(isPlainObject(k.keys) ? k.keys : {});
if (pubs.length !== 1 || !pubs[0][0].startsWith('ed25519:') || pubs[0][0] !== `ed25519:${pubs[0][1]}`) fail('T_INVALID_PARAM', `${field} must hold exactly one ed25519 key`);
keys[usage] = { obj: k, id: pubs[0][0], pub: pubs[0][1] };
}
for (const usage of ['self_signing', 'user_signing']) {
if (!verifySigned(keys[usage].obj, ctx.user_id, keys.master.id, keys.master.pub)) fail('T_INVALID_SIGNATURE', `${usage} key is not signed by the master key`);
}
const existing = crossSigning.get(ctx.user_id);
const same = (usage) => existing && canonicalJson({ ...existing[usage], signatures: {} }) === canonicalJson({ ...keys[usage].obj, signatures: {} });
if (existing && !['master', 'self_signing', 'user_signing'].every(same)) {
// Replacing any part of an identity needs fresh proof of the password,
// so a stolen token can't do it: a completed OPAQUE login
// (t.opaque.login.start, then KE3 here instead of t.opaque.login.finish).
app.auth.requireStrong(ctx, body, 'Replacing your cross-signing identity');
if (!same('master')) {
userSignatures.delete(ctx.user_id);
disk.del('user_signatures', ctx.user_id);
}
}
// The same master key again keeps the signatures already on it.
const master = same('master')
? { ...keys.master.obj, signatures: { ...existing.master.signatures, [ctx.user_id]: { ...existing.master.signatures?.[ctx.user_id], ...keys.master.obj.signatures?.[ctx.user_id] } } }
: keys.master.obj;
crossSigning.set(ctx.user_id, { master, self_signing: keys.self_signing.obj, user_signing: keys.user_signing.obj });
disk.put('cross_signing', ctx.user_id, crossSigning.get(ctx.user_id));
notifyDeviceListChange(ctx.user_id);
dispatchToUser(ctx.user_id, 't.device_lists', { changed: [ctx.user_id] });
return {};
} },
't.keys.signatures.upload': { budget: ['keys', (b) => Math.max(sizeOf(b), 1)], async run(_p, ctx, body) {
const entries = Object.entries(isPlainObject(body) ? body : {});
if (entries.length > 100) fail('T_LIMIT_EXCEEDED', 'Too many users in one upload');
// Keyed by names from the request: no prototype, so no name can reach Object.prototype.
const failures = Object.create(null);
const failed = (user_id, key_id, error) => { (failures[user_id] ??= Object.create(null))[key_id] = { errcode: 'T_INVALID_SIGNATURE', error }; };
const mine = crossSigning.get(ctx.user_id);
const keyOf = (obj) => Object.entries(obj?.keys ?? {})[0] ?? [];
const sameObject = (a, b) => canonicalJson({ ...a, signatures: {} }) === canonicalJson({ ...b, signatures: {} });
for (const [user_id, objects] of entries) {
if (!isValidUserId(user_id) || !isPlainObject(objects)) continue;
for (const [key_id, obj] of Object.entries(objects)) {
if (key_id.length > 255 || ['__proto__', 'constructor', 'prototype'].includes(key_id)) continue;
if (!isPlainObject(obj)) { failed(user_id, key_id, 'Invalid key object'); continue; }
const sigs = obj.signatures?.[ctx.user_id] ?? {};
if (!isPlainObject(sigs)) { failed(user_id, key_id, 'Invalid signatures'); continue; }
if (user_id === ctx.user_id) {
const device = deviceKeys.get(devKey(user_id, key_id));
if (device) {
// Our own device, signed by our self-signing key.
const [sskId, sskPub] = keyOf(mine?.self_signing);
if (!sskId || !verifySigned(obj, user_id, sskId, sskPub)) { failed(user_id, key_id, 'Not signed by your self-signing key'); continue; }
if (!sameObject(obj, device)) { failed(user_id, key_id, 'Device keys differ'); continue; }
device.signatures[user_id] = { ...device.signatures[user_id], [sskId]: sigs[sskId] };
disk.put('device_keys', devKey(user_id, key_id), device);
notifyDeviceListChange(user_id);
continue;
}
if (mine && key_id === keyOf(mine.master)[1]) {
// Our master key, signed by our own uploaded devices: every signature must verify.
if (!sameObject(obj, mine.master)) { failed(user_id, key_id, 'Master key differs'); continue; }
const verified = {};
const good = Object.entries(sigs).every(([sigKeyId, sigVal]) => {
const devPub = sigKeyId.startsWith('ed25519:') ? deviceKeys.get(devKey(user_id, sigKeyId.slice(8)))?.keys?.[sigKeyId] : undefined;
if (typeof sigVal !== 'string' || !devPub || !verifySigned(obj, user_id, sigKeyId, devPub)) return false;
verified[sigKeyId] = sigVal;
return true;
});
if (!good || !Object.keys(verified).length) { failed(user_id, key_id, 'Device signature on master key does not verify'); continue; }
mine.master.signatures = { ...mine.master.signatures, [user_id]: { ...mine.master.signatures?.[user_id], ...verified } };
disk.put('cross_signing', user_id, mine);
continue;
}
failed(user_id, key_id, 'Unknown key');
continue;
}
// Another user's master key (local or federated), signed by our user-signing key.
if (!sharesRoom(ctx.user_id, user_id)) { failed(user_id, key_id, 'Unknown master key'); continue; }
let theirMaster = crossSigning.get(user_id)?.master ?? null;
const server = app.serverOf(user_id);
if (!theirMaster && !app.isLocalUser(user_id) && cfg.PEERS.has(server)) {
try {
const r = await (await app.fed.connectPeer(server)).request('t.fed.keys.query', { requester: ctx.user_id, device_keys: { [user_id]: [] } });
theirMaster = fromPeer(r?.master_keys, server, { [user_id]: [] })[user_id] ?? null;
} catch { theirMaster = null; }
}
const [uskId, uskPub] = keyOf(mine?.user_signing);
if (!theirMaster || key_id !== keyOf(theirMaster)[1]) { failed(user_id, key_id, 'Unknown master key'); continue; }
if (!sameObject(obj, theirMaster)) { failed(user_id, key_id, 'Master key differs'); continue; }
if (!uskId || !verifySigned(obj, ctx.user_id, uskId, uskPub)) { failed(user_id, key_id, 'Not signed by your user-signing key'); continue; }
const bySigner = userSignatures.get(user_id) ?? new Map();
bySigner.set(ctx.user_id, { [uskId]: sigs[uskId] });
userSignatures.set(user_id, bySigner);
disk.put('user_signatures', user_id, Object.fromEntries(bySigner));
// Only the signer sees this signature, so only the signer's devices
// need to fetch the key again.
dispatchToUser(ctx.user_id, 't.device_lists', { changed: [user_id] });
}
}
return { failures };
} },
't.to_device.send': {
budget: ['to_device', (b) => devicesIn(b, 'messages', devicesOf)], params: { event_type: 'string', txn_id: 'string', messages: 'object' },
run({ event_type: type, txn_id, messages }, ctx, body) {
const key = `td|${ctx.user_id}|${ctx.device_id}|${txn_id}`;
if (txnIds.has(key)) return {};
if (devicesIn(body, 'messages', devicesOf) > MAX_TO_DEVICE_MESSAGES) fail('T_LIMIT_EXCEEDED', 'Too many to-device messages in one request');
const { local, remote } = app.fed.splitByServer(Object.fromEntries(Object.entries(messages).filter(([u, d]) => isPlainObject(d) && sharesRoom(ctx.user_id, u))));
const count = { n: 0 };
for (const [user_id, devices] of Object.entries(local)) sendToDevices(ctx.user_id, type, user_id, devices, count);
txnIds.set(key, '');
for (const [server, subset] of remote) {
app.fed.connectPeer(server).then((c) => c.request('t.fed.to_device', { sender: ctx.user_id, type, messages: subset }))
.catch((e) => console.error(`to-device to ${server} failed: ${e.message}`));
}
return {};
},
},
};
// Federation's side of the same: requests from a peer about our users.
const fedMethods = {
't.fed.keys.query': { budget: ['lookups', (b) => Math.max(sizeOf(b?.device_keys), 1)], run(body, { origin }) {
const r = queryLocal({ device_keys: app.fed.localPart(body, 'device_keys', origin) }, { user_id: body.requester });
return { device_keys: r.device_keys, master_keys: r.master_keys, self_signing_keys: r.self_signing_keys, hardware_keys: r.hardware_keys, failures: {} };
} },
't.fed.keys.claim': {
budget: ['claims', (b) => devicesIn(b, 'one_time_keys', devicesOf)],
run: (body, { origin }) => claimLocal({ one_time_keys: app.fed.localPart(body, 'one_time_keys', origin) }, { user_id: body.requester }),
},
't.fed.to_device': { budget: ['to_device', (b) => devicesIn(b, 'messages', devicesOf)], run(body, { origin }) {
const sender = requireString(body, 'sender');
const type = requireString(body, 'type');
if (app.serverOf(sender) !== origin) fail('T_FORBIDDEN', 'Sender is not on the requesting server');
const count = { n: 0 };
for (const [user_id, devices] of Object.entries(requireObject(body, 'messages'))) {
if (app.isLocalUser(user_id) && sharesRoom(sender, user_id) && isPlainObject(devices)) sendToDevices(sender, type, user_id, devices, count);
}
return {};
} },
};
return {
methods, fedMethods, devicesOf, notifyDeviceListChange, flushToDevice, forgetDevice,
hasDevice: (user_id, device_id) => deviceKeys.has(devKey(user_id, device_id)),
countsFor: (user_id, device_id) => oneTimeKeyCounts(devKey(user_id, device_id)),
purge(t) {
for (const m of [otkClaims, otkDeviceClaims]) dropWhere(m, (rec) => t - rec.since >= OTK_CLAIM_WINDOW_MS);
for (const [k, queue] of toDeviceQueue) {
const kept = queue.filter((m) => m.ts > t - cfg.RETENTION_MS);
if (kept.length === queue.length) continue;
if (kept.length) toDeviceQueue.set(k, kept); else toDeviceQueue.delete(k);
persistQueue(k);
}
},
// Everything about an account's keys (account deletion; devices go with its tokens).
forgetUser(user_id) {
for (const [k] of toDeviceQueue) if (k.startsWith(`${user_id}|`)) { toDeviceQueue.delete(k); disk.delSealed('to_device', k); }
crossSigning.delete(user_id); disk.del('cross_signing', user_id);
userSignatures.delete(user_id); disk.del('user_signatures', user_id);
// Signatures this user made on others' keys go too.
for (const [target, bySigner] of userSignatures) {
if (!bySigner.delete(user_id)) continue;
if (bySigner.size) disk.put('user_signatures', target, Object.fromEntries(bySigner));
else { userSignatures.delete(target); disk.del('user_signatures', target); }
}
},
restore() {
for (const [k, dk] of disk.all('device_keys')) deviceKeys.set(k, dk);
for (const [k, otks] of disk.all('one_time_keys')) oneTimeKeys.set(k, new Map(Object.entries(otks)));
for (const [k, fb] of disk.all('fallback_keys')) fallbackKeys.set(k, fb);
for (const [user_id, cs] of disk.all('cross_signing')) crossSigning.set(user_id, cs);
for (const [user_id, sigs] of disk.all('user_signatures')) userSignatures.set(user_id, new Map(Object.entries(sigs)));
for (const [k, queue] of disk.unsealAll('to_device')) toDeviceQueue.set(k, queue);
},
// Devices whose every token has expired can never connect again: their keys go too.
forgetOrphans(hasToken) {
for (const k of [...deviceKeys.keys()]) {
const [user_id, device_id] = k.split('|');
if (!hasToken(user_id, device_id)) forgetDevice(user_id, device_id);
}
},
};
}
|