Download server/federation.js from abr00kx/taper: direct link, hf CLI and curl.
- Browser
- Download file 29.4 kB
-
https://huggingface.co/abr00kx/taper/resolve/main/server/federation.js
- Command line
-
hf download hf://abr00kx/taper/server/federation.js
-
curl -L -o federation.js https://huggingface.co/abr00kx/taper/resolve/main/server/federation.js
29.4 kB
| // Federation over WebSockets (server-server API, "WebSocket federation"), | |
| // on top of the pure transport and pinning helpers in fed.js. | |
| // | |
| // Allowlist mode only: TAPER_FEDERATION_PEERS names the servers we federate | |
| // with and where to reach them. Each connection is authenticated once, by | |
| // both sides, with short-lived request keys whose private halves are | |
| // published when retired. Events carry their server's Ed25519 signature over | |
| // the redacted form (room version 13). EXPERIMENTAL: media does not cross | |
| // servers, and delivery has no retry queue or backfill yet. | |
| // | |
| // Owns the signing and request keys, peer key pins, peer connections and the | |
| // pending invites from other servers (`state.remoteInvites`). Trust boundary: | |
| // everything a peer sends is untrusted until verifyRemoteEvent() and | |
| // authorizeRemote() pass; only allowlisted peers get past the handshake. | |
| import { randomBytes, createPublicKey, createPrivateKey, generateKeyPairSync } from 'node:crypto'; | |
| import WS, { WebSocketServer } from 'ws'; | |
| import { paddedJson } from './padding.js'; | |
| import { SocksAgent } from './socks.js'; | |
| import { selectAuthEvents, checkAuthRules, powerLevelOf, actionLevel, serverAllowedByAcl, stateKeyOf } from './state-res.js'; | |
| import { | |
| RETENTION_CEILING_MS, MAX_EVENT_DEPTH, TaperError, fail, isPlainObject, requireString, requireObject, | |
| unpadded, signWith, verifyWith, redactedForm, computeEventId, validateStateEvent, checkEnvelope, isIdList, sanitizeRemoteEvent, checkJoinState, | |
| } from './events.js'; | |
| import { authorizedPeerKey, verifyEventWithKeys, getJson, nextFrame, channelBinding, FedConn } from './fed.js'; | |
| import { MAX_ROOM_STATE_KEYS } from './rooms.js'; | |
| import { one } from './quota.js'; | |
| import { b64url, now, dropWhere, errorBody, send } from './util.js'; | |
| export const MAX_FED_FRAME_BYTES = 2 * 1024 * 1024; // a large room's send_join answer | |
| const CLOCK_SKEW_MS = 5 * 60_000; | |
| const MAX_FED_CONNS = 64; | |
| const MAX_FED_EARLY_REQUESTS = 16; // requests held while the peer's signature is checked | |
| const MAX_DEPTH_STEP = 1000; // how far past our deepest event a peer's event may claim to be | |
| const MAX_JOIN_AUTH_CHAIN = 2000; | |
| const rawPublic = (key) => unpadded(Buffer.from(key.export({ format: 'jwk' }).x, 'base64url')); | |
| const rawPrivate = (key) => unpadded(Buffer.from(key.export({ format: 'jwk' }).d, 'base64url')); | |
| function makeSigningKey() { | |
| const { publicKey, privateKey } = generateKeyPairSync('ed25519'); | |
| return { id: `ed25519:${b64url(randomBytes(4))}`, publicKey, privateKey, jwk: privateKey.export({ format: 'jwk' }) }; | |
| } | |
| const newRequestKey = () => ({ id: `ed25519:req_${b64url(randomBytes(4))}`, ...generateKeyPairSync('ed25519'), created_ts: now() }); | |
| export function create(app) { | |
| const { cfg, disk } = app; | |
| const { rooms, users, remoteInvites } = app.state; | |
| const { SERVER_NAME, PEERS, TOR_SOCKS, TLS_OPTIONS, REQUEST_KEY_PERIOD_MS, RETENTION_MS } = cfg; | |
| const serverOf = app.serverOf; | |
| const dispatchToUser = (...a) => app.sessions.dispatchToUser(...a); | |
| const SOCKS_PASSWORD = b64url(randomBytes(16)); // with the peer name, the isolation key | |
| const peerAgents = new Map(); | |
| function peerAgent(server) { | |
| if (!TOR_SOCKS) return undefined; | |
| if (!peerAgents.has(server)) { | |
| const secure = new URL(PEERS.get(server)).protocol === 'wss:'; | |
| peerAgents.set(server, new SocksAgent({ proxy: TOR_SOCKS, isolation: `taper:${server}`, password: SOCKS_PASSWORD, secure, tlsOptions: TLS_OPTIONS })); | |
| } | |
| return peerAgents.get(server); | |
| } | |
| // The server's event signing key (persisted in TAPER_KEY_DIR when storage is | |
| // on, so restarts keep key continuity; rotatable via `admin.js rotate-signing-key` | |
| // with a cryptographic transition proof in `old_verify_keys`) and short-lived | |
| // deniable request keys (memory only, published on retirement). | |
| const bundle = JSON.parse(disk.secret('signing', () => { | |
| const cur = makeSigningKey(); | |
| return JSON.stringify({ current: { id: cur.id, jwk: cur.jwk }, old: [] }); | |
| })); | |
| const signingPrivate = createPrivateKey({ key: bundle.current.jwk, format: 'jwk' }); | |
| let SIGNING = { id: bundle.current.id, publicKey: createPublicKey(signingPrivate), privateKey: signingPrivate, jwk: bundle.current.jwk }; | |
| const oldSigningKeys = Array.isArray(bundle.old) ? bundle.old : []; // [{ id, key, expired_ts, rotated_to? }] | |
| function rotateSigningKey() { | |
| const prev = SIGNING; | |
| const next = makeSigningKey(); | |
| const ts = now(); | |
| const nextPub = rawPublic(next.publicKey); | |
| // Before discarding the old private key, sign a transition proof binding the | |
| // old key to the new one so peers that pinned the old key can verify continuity. | |
| const sig = signWith(prev.privateKey, { server_name: SERVER_NAME, old_key_id: prev.id, new_key_id: next.id, new_key: nextPub, ts }); | |
| oldSigningKeys.push({ id: prev.id, key: rawPublic(prev.publicKey), expired_ts: ts, rotated_to: { key_id: next.id, key: nextPub, ts, sig } }); | |
| // Keep old verify keys within the retention ceiling OR while any stored event | |
| // (e.g. indefinite room state / auth chain) is still signed by them. | |
| const referenced = new Set(); | |
| for (const room of rooms.values()) { | |
| for (const ev of room.byId.values()) { | |
| const sigs = ev.signatures?.[SERVER_NAME]; | |
| if (sigs && typeof sigs === 'object') for (const kid of Object.keys(sigs)) referenced.add(kid); | |
| } | |
| } | |
| // Only the oldest keys go, so every kept key's chain of rotation proofs | |
| // to the current key stays whole (K1 -> K2 -> K3). | |
| const cutoff = ts - RETENTION_CEILING_MS; | |
| while (oldSigningKeys.length && oldSigningKeys[0].expired_ts < cutoff && !referenced.has(oldSigningKeys[0].id)) oldSigningKeys.shift(); | |
| SIGNING = next; | |
| disk.setSecret('signing', JSON.stringify({ current: { id: next.id, jwk: next.jwk }, old: oldSigningKeys })); | |
| return { old_key_id: prev.id, new_key_id: next.id, rotated_ts: ts }; | |
| } | |
| let requestKey = newRequestKey(); | |
| const retiredRequestKeys = []; | |
| function rotateRequestKey() { | |
| if (now() - requestKey.created_ts < REQUEST_KEY_PERIOD_MS) return; | |
| retiredRequestKeys.push({ ...requestKey, expired_ts: now() }); | |
| while (retiredRequestKeys.length && retiredRequestKeys[0].expired_ts < now() - RETENTION_CEILING_MS) retiredRequestKeys.shift(); | |
| requestKey = newRequestKey(); | |
| } | |
| // GET {FED_PATH}/keys. Retired request keys are published with their private | |
| // keys at once, so signatures made with them prove nothing. | |
| function serverKeysDoc() { | |
| rotateRequestKey(); | |
| const doc = { | |
| server_name: SERVER_NAME, | |
| verify_keys: { [SIGNING.id]: { key: rawPublic(SIGNING.publicKey) } }, | |
| old_verify_keys: Object.fromEntries(oldSigningKeys.map((k) => [k.id, { | |
| expired_ts: k.expired_ts, key: k.key, ...(k.rotated_to ? { rotated_to: k.rotated_to } : {}), | |
| }])), | |
| request_keys: { [requestKey.id]: { key: rawPublic(requestKey.publicKey) } }, | |
| old_request_keys: Object.fromEntries(retiredRequestKeys.map((k) => [k.id, { expired_ts: k.expired_ts, key: rawPublic(k.publicKey), private_key: rawPrivate(k.privateKey) }])), | |
| valid_until_ts: requestKey.created_ts + REQUEST_KEY_PERIOD_MS, | |
| }; | |
| doc.signatures = { [SERVER_NAME]: { [SIGNING.id]: signWith(SIGNING.privateKey, doc) } }; | |
| return doc; | |
| } | |
| const signEvent = (ev) => { ev.signatures = { [SERVER_NAME]: { [SIGNING.id]: signWith(SIGNING.privateKey, redactedForm(ev)) } }; }; | |
| const peerKeys = new Map(); // server -> { doc, fetched } | |
| const pinnedPeerKeys = new Map(); // server -> { key_id, key } (TOFU + chained rotation pinning) | |
| async function fetchPeerKeys(server, { fresh = false } = {}) { | |
| const cached = peerKeys.get(server); | |
| if (cached && !fresh && now() - cached.fetched < 60_000) return cached.doc; | |
| const url = new URL(PEERS.get(server)); | |
| url.protocol = url.protocol === 'wss:' ? 'https:' : 'http:'; | |
| url.pathname = `${url.pathname.replace(/\/$/, '')}/keys`; | |
| const doc = await getJson(url, { agent: peerAgent(server), tls: TLS_OPTIONS, timeoutMs: TOR_SOCKS ? 60_000 : 15_000 }); | |
| const pinned = pinnedPeerKeys.get(server); | |
| const pin = authorizedPeerKey(server, doc, pinned, { trustRotation: cfg.ALLOW_UNPINNED_PEER_ROTATION }); | |
| if (pinned?.key_id !== pin.key_id || pinned?.key !== pin.key) { | |
| pinnedPeerKeys.set(server, pin); | |
| disk.put('peer_keys', server, pin); | |
| } | |
| peerKeys.set(server, { doc, fetched: now() }); | |
| return doc; | |
| } | |
| // The ID of the key that signed `ev` for `server`; throws if none did. | |
| async function verifyEventSignature(ev, server) { | |
| if (server === SERVER_NAME) return verifyEventWithKeys(ev, server, serverKeysDoc(), CLOCK_SKEW_MS) ?? fail('T_INVALID_SIGNATURE', 'Event signature does not verify'); | |
| if (!PEERS.has(server)) fail('T_FORBIDDEN', `Server ${server} is not on the federation allowlist`); | |
| return verifyEventWithKeys(ev, server, await fetchPeerKeys(server), CLOCK_SKEW_MS) | |
| ?? verifyEventWithKeys(ev, server, await fetchPeerKeys(server, { fresh: true }), CLOCK_SKEW_MS) | |
| ?? fail('T_INVALID_SIGNATURE', 'Event signature does not verify'); | |
| } | |
| // Check an event from another server and return it rebuilt from its known | |
| // fields only (see sanitizeRemoteEvent). | |
| async function verifyRemoteEvent(ev, origin, { allowOldState = false } = {}) { | |
| checkEnvelope(ev); | |
| const server = serverOf(ev.sender); | |
| // Events reach us from their own server unless verifying historical room state on join. | |
| if (origin && server !== origin) fail('T_FORBIDDEN', `${origin} cannot send events for ${server}`); | |
| const keyId = await verifyEventSignature(ev, server); | |
| if (computeEventId(ev) !== ev.event_id) fail('T_INVALID_PARAM', 'Event ID does not match the event'); | |
| // A peer chooses its events' timestamps. Retention counts from them, so an | |
| // event dated far ahead would outlive 21 days here, and one dated far back | |
| // would be expired the moment it arrived. | |
| const ts = ev.origin_server_ts; | |
| if (ts > now() + CLOCK_SKEW_MS) fail('T_INVALID_PARAM', 'Event timestamp is in the future'); | |
| if (!allowOldState && ts < now() - RETENTION_MS) fail('T_INVALID_PARAM', 'Event timestamp is outside the retention window'); | |
| return sanitizeRemoteEvent(ev, server, keyId); | |
| } | |
| async function checkPeerAuth(peer, hello, auth, transcript) { | |
| let keys = await fetchPeerKeys(peer); | |
| if (!keys.request_keys?.[hello.key]) keys = await fetchPeerKeys(peer, { fresh: true }); | |
| const key = keys.request_keys?.[hello.key]; | |
| if (!key || !verifyWith(key.key, { ...transcript, signer: peer }, auth.sig)) throw new Error(`handshake with ${peer} failed`); | |
| } | |
| // Our half of the handshake: a hello with a fresh nonce under the current request key. | |
| function sendHello(ws, destination) { | |
| rotateRequestKey(); | |
| const key = requestKey; // the key named in the hello signs the auth, even if it rotates meanwhile | |
| const nonce = unpadded(randomBytes(32)); | |
| ws.send(paddedJson({ op: 'fed.hello', origin: SERVER_NAME, destination, nonce, key: key.id })); | |
| return { key, nonce }; | |
| } | |
| const sendAuth = (ws, key, transcript) => ws.send(paddedJson({ op: 'fed.auth', sig: signWith(key.privateKey, { ...transcript, signer: SERVER_NAME }) })); | |
| const fedConns = new Map(); // server -> Promise<FedConn> | |
| function connectPeer(server) { | |
| if (!PEERS.has(server)) return Promise.reject(new TaperError('T_FORBIDDEN', `Not federating with ${server}`)); | |
| let conn = fedConns.get(server); | |
| if (!conn) { | |
| conn = openPeer(server); | |
| fedConns.set(server, conn); | |
| conn.catch(() => fedConns.delete(server)); | |
| } | |
| return conn; | |
| } | |
| async function openPeer(server) { | |
| const agent = peerAgent(server); | |
| const ws = new WS(PEERS.get(server), { | |
| perMessageDeflate: false, maxPayload: MAX_FED_FRAME_BYTES, ...(agent ? { agent, handshakeTimeout: 60_000 } : { ...TLS_OPTIONS, handshakeTimeout: 15_000 }), | |
| }); | |
| await new Promise((resolve, reject) => { ws.once('open', resolve); ws.once('error', reject); }); | |
| const { key, nonce } = sendHello(ws, server); | |
| const hello = await nextFrame(ws, 'fed.hello'); | |
| if (hello.origin !== server || hello.destination !== SERVER_NAME) throw new Error(`unexpected hello from ${hello.origin}`); | |
| const transcript = { client_nonce: nonce, server_nonce: hello.nonce, client: SERVER_NAME, server, channel: channelBinding(ws._socket) }; | |
| sendAuth(ws, key, transcript); | |
| await checkPeerAuth(server, hello, await nextFrame(ws, 'fed.auth'), transcript); | |
| const conn = new FedConn(ws, server); | |
| ws.on('message', (data, isBinary) => { | |
| if (isBinary) return; | |
| try { const f = JSON.parse(String(data)); if (f.op === 'response') conn.onResponse(f); } catch { /* ignore */ } | |
| }); | |
| ws.on('close', () => { fedConns.delete(server); conn.fail(new Error(`connection to ${server} closed`)); }); | |
| ws.on('error', () => {}); // 'close' follows, and fails the pending requests | |
| return conn; | |
| } | |
| // Inbound federation connections: handshake, then serve the method table. | |
| const fedWss = new WebSocketServer({ noServer: true, perMessageDeflate: false, maxPayload: MAX_FED_FRAME_BYTES }); | |
| fedWss.on('connection', async (ws, req) => { | |
| // A frame over the limit, a bad frame header or a reset raises 'error'; unhandled, it would end the whole process. | |
| ws.on('error', () => ws.terminate()); | |
| try { | |
| const hello = await nextFrame(ws, 'fed.hello'); | |
| // Servers we don't federate with get nothing but a closed connection. | |
| if (!PEERS.has(hello.origin) || hello.destination !== SERVER_NAME) { ws.terminate(); return; } | |
| const origin = hello.origin; | |
| const { key, nonce } = sendHello(ws, origin); | |
| const transcript = { client_nonce: hello.nonce, server_nonce: nonce, client: origin, server: SERVER_NAME, channel: channelBinding(req.socket) }; | |
| const auth = await nextFrame(ws, 'fed.auth'); | |
| // The peer may send requests as soon as it has checked our signature, | |
| // while we are still fetching its keys (slow over Tor). Listen now, and | |
| // hold requests until its signature has been checked too. | |
| let authenticated; | |
| let early = 0; | |
| const ready = new Promise((resolve, reject) => { authenticated = { resolve, reject }; }); | |
| ready.then(() => { early = -Infinity; }, () => {}); | |
| ws.on('message', async (data, isBinary) => { | |
| if (isBinary) return; | |
| let f; | |
| try { f = JSON.parse(String(data)); } catch { return; } | |
| if (f?.op !== 'request') return; | |
| if (++early > MAX_FED_EARLY_REQUESTS) { ws.terminate(); return; } | |
| try { await ready; } catch { return; } | |
| const reply = (payload) => send(ws, { op: 'response', id: f.id, ...payload }); | |
| try { | |
| if (!Object.hasOwn(fedMethods, f.method)) return reply({ ok: false, error: { errcode: 'T_UNRECOGNIZED', error: `Unknown method ${f.method}` } }); | |
| const spec = fedMethods[f.method]; | |
| if (spec.budget) app.quota.meterPeer(origin, spec.budget, f.body ?? {}); | |
| reply({ ok: true, body: await spec.run(f.body ?? {}, { origin }) }); | |
| } catch (err) { | |
| reply({ ok: false, error: errorBody(err, f.method) }); | |
| } | |
| }); | |
| sendAuth(ws, key, transcript); | |
| try { | |
| await checkPeerAuth(origin, hello, auth, transcript); | |
| } catch (e) { | |
| authenticated.reject(e); | |
| throw e; | |
| } | |
| authenticated.resolve(); | |
| } catch { | |
| ws.terminate(); | |
| } | |
| }); | |
| // Servers with members in a room (and the target of a membership event). | |
| function residentServers(room, ev) { | |
| const servers = new Set(); | |
| for (const u of [...room.members('join'), ...room.members('invite')]) servers.add(serverOf(u)); | |
| if (ev?.type === 't.room.member') servers.add(serverOf(ev.state_key)); | |
| servers.delete(SERVER_NAME); | |
| return servers; | |
| } | |
| function federateEvent(room, ev, except) { | |
| if (room.createEvent()?.content?.['t.federate'] === false) return; | |
| const acl = room.serverAcl(); | |
| for (const server of residentServers(room, ev)) { | |
| if (server === except || !PEERS.has(server)) continue; | |
| if (!serverAllowedByAcl(server, acl)) continue; | |
| connectPeer(server).then((c) => c.request('t.fed.send', { pdus: [ev], edus: [] })) | |
| .catch((e) => console.error(`sending ${ev.event_id} to ${server} failed: ${e.message}`)); | |
| } | |
| } | |
| // Authorise an event from another server (verified and sanitized) against | |
| // Room v13 rules, Server ACLs, its own auth_events, its parents, the | |
| // resolved state before it, and (soft-fail) current room state. | |
| function authorizeRemote(room, ev, origin) { | |
| if (origin && !serverAllowedByAcl(origin, room.serverAcl())) fail('T_FORBIDDEN', 'Server denied by room ACL'); | |
| if (ev.type === 't.room.create') fail('T_FORBIDDEN', 'The room already exists'); | |
| if (ev.state_key !== undefined) { | |
| app.rooms.requireStateRoom(room, stateKeyOf(ev)); | |
| validateStateEvent(ev.type, ev.state_key, ev.content, cfg.RETENTION_RANGE); | |
| } | |
| // A parent we know, a depth past every known parent, and no leap that | |
| // would carry the room towards MAX_EVENT_DEPTH (which would brick it). | |
| const known = ev.prev_events.filter((id) => room.byId.has(id) || room.stateAfter.has(id)); | |
| if (!known.length) fail('T_INVALID_PARAM', 'Event has no known parent events'); | |
| const maxParentDepth = Math.max(-1, ...known.map((id) => room.byId.get(id)?.depth ?? -1)); | |
| if (ev.depth <= maxParentDepth || ev.depth > room.depth + MAX_DEPTH_STEP) fail('T_INVALID_PARAM', 'Event depth does not follow its parent events'); | |
| const createEv = room.createEvent(); | |
| const authorized = (state, prefix = '') => { | |
| const check = checkAuthRules(ev, state, createEv, { eventsById: room.byId }); | |
| if (!check.ok) fail('T_FORBIDDEN', prefix + check.reason); | |
| }; | |
| const preState = app.rooms.stateBefore(room, ev); | |
| authorized(preState); | |
| // Also against the event's own declared auth_events when all are present. | |
| const authMap = new Map(); | |
| for (const id of ev.auth_events) { | |
| const ae = room.byId.get(id); | |
| if (ae?.state_key !== undefined) authMap.set(stateKeyOf(ae), ae); | |
| } | |
| if (ev.auth_events.length && authMap.size === ev.auth_events.length) authorized(authMap); | |
| // Soft-fail: someone banned or gone now can't act by citing older parents. | |
| if (ev.state_key === undefined) authorized(room.state, 'Soft-failed against current room state: '); | |
| else if (room.membership(ev.sender) === 'ban') fail('T_FORBIDDEN', 'Soft-failed against current room state: sender is banned'); | |
| // Redacting another's event needs the redact level, before the event and now. | |
| const target = ev.type === 't.room.redaction' ? room.byId.get(ev.content.redacts) : null; | |
| if (target && target.sender !== ev.sender) { | |
| for (const plEv of [preState.get('t.room.power_levels|'), room.powerLevels()]) { | |
| if (powerLevelOf(ev.sender, plEv, createEv) < actionLevel(plEv, 'redact', 50)) fail('T_FORBIDDEN', 'Cannot redact that event'); | |
| } | |
| } | |
| return preState; | |
| } | |
| const joiningRooms = new Map(); // room_id -> Promise (serializes concurrent remoteJoin calls) | |
| async function remoteJoin(room_id, user_id, via) { | |
| while (joiningRooms.has(room_id)) { | |
| try { await joiningRooms.get(room_id); } catch { /* previous join failed */ } | |
| if (rooms.has(room_id)) return app.rooms.join(rooms.get(room_id), user_id); | |
| } | |
| const run = (async () => { | |
| const conn = await connectPeer(via); | |
| const { event: template } = await conn.request('t.fed.make_join', { room_id, user_id }); | |
| if (!isPlainObject(template) || !Number.isSafeInteger(template.depth) || template.depth < 1 || template.depth > MAX_EVENT_DEPTH | |
| || !isIdList(template.prev_events, 20) || !isIdList(template.auth_events ?? [], 20)) { | |
| fail('T_BAD_JSON', 'Invalid make_join template from peer'); | |
| } | |
| // Use OUR clock for our join event — never let a peer date it into the future. | |
| const ev = { | |
| room_id, sender: user_id, type: 't.room.member', state_key: user_id, content: { membership: 'join' }, | |
| origin_server_ts: now(), depth: template.depth, prev_events: template.prev_events, auth_events: template.auth_events ?? [], | |
| }; | |
| ev.event_id = computeEventId(ev); | |
| signEvent(ev); | |
| const res = await conn.request('t.fed.send_join', { event: ev }); | |
| const stateIn = res?.state; | |
| const chainIn = res?.auth_chain ?? []; | |
| if (!Array.isArray(stateIn) || !stateIn.length || stateIn.length > MAX_ROOM_STATE_KEYS) fail('T_INVALID_PARAM', 'Peer returned invalid room state'); | |
| if (!Array.isArray(chainIn) || chainIn.length > MAX_JOIN_AUTH_CHAIN) fail('T_INVALID_PARAM', 'Peer returned an invalid auth chain'); | |
| // Cheap first: the room ID must be the hash of a create event in the state. | |
| if (!stateIn.some((e) => isPlainObject(e) && e.type === 't.room.create' && `!${computeEventId(e).slice(1)}` === room_id)) { | |
| fail('T_INVALID_PARAM', 'room_id does not match t.room.create hash'); | |
| } | |
| // Every event's envelope, ID and origin signature, before trusting any of it. | |
| const events = new Map(); | |
| for (const raw of [...chainIn, ...stateIn]) { | |
| if (events.has(raw?.event_id)) continue; | |
| const clean = await verifyRemoteEvent(raw, null, { allowOldState: true }); | |
| events.set(clean.event_id, clean); | |
| } | |
| const { createEv, state } = checkJoinState(room_id, events, stateIn.map((e) => e.event_id), cfg.RETENTION_RANGE); | |
| if (!template.prev_events.length) fail('T_BAD_JSON', 'The make_join template names no parent events'); | |
| const candidate = new app.rooms.Room(room_id); | |
| for (const e of [...events.values()].sort((a, b) => a.depth - b.depth || a.origin_server_ts - b.origin_server_ts)) { | |
| candidate.events.push(e); | |
| candidate.byId.set(e.event_id, e); | |
| candidate.depth = Math.max(candidate.depth, e.depth); | |
| } | |
| candidate.state = state; | |
| for (const s of state.values()) if (s.type === 't.room.member' && s.content.membership === 'join') candidate.joinDepth.set(s.state_key, s.depth); | |
| for (const pid of template.prev_events) { | |
| candidate.heads.add(pid); | |
| candidate.stateAfter.set(pid, new Map(state)); | |
| } | |
| const joinCheck = checkAuthRules(ev, state, createEv, { eventsById: candidate.byId }); | |
| if (!joinCheck.ok) fail('T_FORBIDDEN', `Join not authorized by verified room state: ${joinCheck.reason}`); | |
| if (rooms.has(room_id)) return rooms.get(room_id); | |
| for (const s of candidate.events) app.rooms.persistEvent(s); | |
| app.rooms.persistMeta(candidate); | |
| rooms.set(room_id, candidate); | |
| remoteInvites.get(room_id)?.delete(user_id); | |
| app.rooms.commit(candidate, ev, { preState: state }); | |
| dispatchToUser(user_id, 't.room.joined', { room_id, state: candidate.stateList() }); | |
| return candidate; | |
| })(); | |
| joiningRooms.set(room_id, run); | |
| try { | |
| return await run; | |
| } finally { | |
| joiningRooms.delete(room_id); | |
| } | |
| } | |
| // Split a {user_id: ...} request into this server's part and each peer's. | |
| function splitByServer(wanted) { | |
| const local = {}; | |
| const remote = new Map(); | |
| for (const [user_id, v] of Object.entries(wanted)) { | |
| const server = serverOf(user_id); | |
| if (server === SERVER_NAME) local[user_id] = v; | |
| else if (PEERS.has(server)) (remote.get(server) ?? remote.set(server, {}).get(server))[user_id] = v; | |
| } | |
| return { local, remote }; | |
| } | |
| // Current state and its auth chain, for a server whose user joins. | |
| function joinAnswer(room, exceptId) { | |
| const state = [...room.state.values()].filter((e) => e.event_id !== exceptId); | |
| const inState = new Set(state.map((e) => e.event_id)); | |
| return { state, auth_chain: [...app.rooms.authChainIds(room)].filter((id) => !inState.has(id)).map((id) => room.byId.get(id)) }; | |
| } | |
| // The part of a peer's request that is about this server's users. | |
| function localPart(body, key, origin) { | |
| if (serverOf(requireString(body, 'requester')) !== origin) fail('T_FORBIDDEN', 'Requester is not on the requesting server'); | |
| const entries = Object.entries(requireObject(body, key)); | |
| if (entries.length > 1000) fail('T_LIMIT_EXCEEDED', 'Too many users in one request'); | |
| return Object.fromEntries(entries.filter(([u]) => app.isLocalUser(u))); | |
| } | |
| const aclCheck = (origin, room) => serverAllowedByAcl(origin, room.serverAcl()) || fail('T_FORBIDDEN', 'Server denied by room ACL'); | |
| // Requests from peers: each declares its per-peer budget ([counter, cost]). | |
| const fedMethods = { | |
| 't.fed.send': { budget: ['send', (b) => Math.max((Array.isArray(b?.pdus) ? b.pdus.length : 0) + (Array.isArray(b?.edus) ? b.edus.length : 0), 1)], async run(body, { origin }) { | |
| const results = Object.create(null); | |
| for (const pdu of Array.isArray(body.pdus) ? body.pdus.slice(0, 50) : []) { | |
| try { | |
| const ev = await verifyRemoteEvent(pdu, origin); | |
| const room = rooms.get(ev.room_id); | |
| if (!room) { | |
| // An invite to a room we don't have yet. | |
| if (ev.type === 't.room.member' && ev.content.membership === 'invite' && app.isLocalUser(ev.state_key) && users.has(ev.state_key) | |
| && ev.room_id.startsWith('!') && (remoteInvites.has(ev.room_id) || remoteInvites.size < 10_000)) { | |
| if (!remoteInvites.has(ev.room_id)) remoteInvites.set(ev.room_id, new Map()); | |
| remoteInvites.get(ev.room_id).set(ev.state_key, { inviter: ev.sender, via: origin, ts: now() }); | |
| dispatchToUser(ev.state_key, 't.room.invite', { room_id: ev.room_id, inviter: ev.sender, state: [] }); | |
| } | |
| continue; | |
| } | |
| if (room.byId.has(ev.event_id)) continue; | |
| app.rooms.commit(room, ev, { preState: authorizeRemote(room, ev, origin) }); | |
| } catch (e) { | |
| results[typeof pdu?.event_id === 'string' ? pdu.event_id : '?'] = { error: e.message }; | |
| } | |
| } | |
| for (const edu of Array.isArray(body.edus) ? body.edus.slice(0, 100) : []) { | |
| if (edu?.type !== 't.device_list_update' || typeof edu.user_id !== 'string' || serverOf(edu.user_id) !== origin) continue; | |
| for (const u of app.rooms.peersOf(edu.user_id)) if (app.isLocalUser(u)) dispatchToUser(u, 't.device_lists', { changed: [edu.user_id] }); | |
| } | |
| return { pdus: results }; | |
| } }, | |
| 't.fed.make_join': { budget: ['joins', one], run(body, { origin }) { | |
| const room = app.rooms.get(requireString(body, 'room_id')); | |
| aclCheck(origin, room); | |
| const user_id = requireString(body, 'user_id'); | |
| if (serverOf(user_id) !== origin) fail('T_FORBIDDEN', 'User is not on the requesting server'); | |
| const draft = { room_id: room.room_id, sender: user_id, type: 't.room.member', state_key: user_id, content: { membership: 'join' } }; | |
| app.rooms.authorizeLocal(room, draft); | |
| return { event: { room_id: room.room_id, origin_server_ts: now(), depth: room.depth + 1, prev_events: room.head, auth_events: selectAuthEvents(room.state, draft) } }; | |
| } }, | |
| 't.fed.send_join': { budget: ['joins', one], async run(body, { origin }) { | |
| const ev = await verifyRemoteEvent(requireObject(body, 'event'), origin); | |
| const room = app.rooms.get(ev.room_id); | |
| aclCheck(origin, room); | |
| if (ev.type !== 't.room.member' || ev.content.membership !== 'join' || ev.sender !== ev.state_key) fail('T_INVALID_PARAM', 'Not a join event'); | |
| if (!room.byId.has(ev.event_id)) { | |
| const preState = authorizeRemote(room, ev, origin); | |
| const answer = joinAnswer(room); | |
| app.rooms.commit(room, ev, { preState }); | |
| federateEvent(room, ev, origin); | |
| return answer; | |
| } | |
| // A join we already have: only while it is still the user's current membership. | |
| if (room.state.get(`t.room.member|${ev.sender}`)?.event_id !== ev.event_id) fail('T_FORBIDDEN', 'That join is no longer current'); | |
| return joinAnswer(room, ev.event_id); | |
| } }, | |
| }; | |
| return { | |
| signEvent, federateEvent, connectPeer, remoteJoin, splitByServer, localPart, serverKeysDoc, rotateSigningKey, | |
| addMethods: (more) => Object.assign(fedMethods, more), | |
| // Upgrade an inbound federation connection (null: too many already). | |
| accept(req, socket, head) { | |
| if (fedWss.clients.size >= MAX_FED_CONNS) return false; | |
| fedWss.handleUpgrade(req, socket, head, (ws) => fedWss.emit('connection', ws, req)); | |
| return true; | |
| }, | |
| closeAll: () => { for (const ws of fedWss.clients) ws.close(1001, 'Server shutting down'); }, | |
| // Forget a peer's pinned key (admin `repin-peer`); a connection under the old pin closes too. | |
| repinPeer(server) { | |
| const had = pinnedPeerKeys.delete(server); | |
| peerKeys.delete(server); | |
| disk.del('peer_keys', server); | |
| fedConns.get(server)?.then((c) => c.ws.close(1001, 'Peer re-pinned'), () => {}); | |
| fedConns.delete(server); | |
| return had; | |
| }, | |
| purge(t) { | |
| for (const byUser of remoteInvites.values()) dropWhere(byUser, (inv) => (inv.ts ?? 0) <= t - RETENTION_MS); | |
| dropWhere(remoteInvites, (byUser) => !byUser.size); | |
| }, | |
| restore() { for (const [server, pin] of disk.all('peer_keys')) pinnedPeerKeys.set(server, pin); }, | |
| }; | |
| } | |