// Gateway sessions and dispatch: the live (or resumable) sessions of signed-in // devices, their resume buffers and batched delivery. Owns `state.sessions` // and the per-user index. Trust boundary: everything handed to dispatch() // goes to that user's devices as is; callers decide who may see what. import { randomBytes } from 'node:crypto'; import { b64url, send } from './util.js'; // Close codes (4000-4999 are application-defined). export const CLOSE = { RECONNECT: 4000, UNKNOWN_OP: 4001, DECODE_ERROR: 4002, NOT_AUTHENTICATED: 4003, AUTH_FAILED: 4004, ALREADY_AUTHENTICATED: 4005, INVALID_RESUME: 4007, TIMED_OUT: 4009, }; const RESUME_WINDOW_MS = 5 * 60_000; const RESUME_BUFFER_MAX = 1000; const MAX_SESSIONS_PER_TOKEN = 4; const MAX_SESSIONS_PER_USER = 16; export function create(app) { const { sessions } = app.state; const { DISPATCH_BATCH_MS } = app.cfg; const byUser = new Map(); // user_id -> Set class Session { constructor(user_id, device_id, tokenHash = null) { this.session_id = b64url(randomBytes(16)); this.user_id = user_id; this.device_id = device_id; this.tokenHash = tokenHash; this.seq = 0; this.buffer = []; // recent dispatch frames, for resume this.ws = null; this.expiryTimer = null; this.outbox = []; // dispatches waiting for the batch window this.batchTimer = null; } attach(ws) { clearTimeout(this.expiryTimer); // Anything still in the outbox is in `buffer`, and resume replays it. clearTimeout(this.batchTimer); this.batchTimer = null; this.outbox = []; this.ws = ws; } detach() { this.ws = null; this.expiryTimer = setTimeout(() => remove(this.session_id), RESUME_WINDOW_MS); this.expiryTimer.unref(); } dispatch(type, body) { const frame = { op: 'dispatch', seq: ++this.seq, type, body }; const ev = body?.event; if (ev && ev.state_key === undefined) frame.expires_ts = ev.unsigned?.expires_ts; this.buffer.push(frame); if (this.buffer.length > RESUME_BUFFER_MAX) this.buffer.shift(); if (!this.ws) return; if (DISPATCH_BATCH_MS <= 0) return send(this.ws, frame); this.outbox.push(frame); this.batchTimer ??= setTimeout(() => this.flush(), DISPATCH_BATCH_MS * (0.25 + 0.75 * Math.random())); } flush() { this.batchTimer = null; const frames = this.outbox.splice(0); if (this.ws) for (const f of frames) send(this.ws, f); } } function add(session) { const userSet = byUser.get(session.user_id) ?? byUser.set(session.user_id, new Set()).get(session.user_id); // Over a limit, a detached session goes first, else the oldest. const evict = (list) => { const victim = list.find((s) => !s.ws) ?? list[0]; closeSessions(victim.user_id, (s) => s === victim, 'Session limit reached'); }; let forToken; while ((forToken = [...userSet].filter((s) => s.tokenHash === session.tokenHash)).length >= MAX_SESSIONS_PER_TOKEN) evict(forToken); while (userSet.size >= MAX_SESSIONS_PER_USER) evict([...userSet]); sessions.set(session.session_id, session); userSet.add(session); } function remove(session_id) { const s = sessions.get(session_id); if (!s) return; clearTimeout(s.expiryTimer); clearTimeout(s.batchTimer); sessions.delete(session_id); const set = byUser.get(s.user_id); if (set) { set.delete(s); if (!set.size) byUser.delete(s.user_id); } } // Close the live sessions of `user_id` that match `pred` (after the current // response has gone out). function closeSessions(user_id, pred, reason) { for (const s of [...(byUser.get(user_id) ?? [])]) { if (!pred(s)) continue; remove(s.session_id); if (s.ws) setImmediate(() => s.ws?.close(CLOSE.AUTH_FAILED, reason)); } } return { Session, add, closeSessions, dispatchToUser: (user_id, type, body) => { for (const s of byUser.get(user_id) ?? []) s.dispatch(type, body); }, ofDevice: (user_id, device_id) => [...(byUser.get(user_id) ?? [])].filter((s) => s.device_id === device_id), purge(t) { for (const s of sessions.values()) s.buffer = s.buffer.filter((d) => !d.expires_ts || d.expires_ts > t); }, }; }