// Operator tools and the dead man's switch. A local command line (admin.js) // talks to this process over a Unix socket that only the operator's account // can open (TAPER_ADMIN_SOCKET). Operators can't read messages (they are // end-to-end encrypted); they can remove accounts, change limits and drive // the dead man's switch (dms.js, docs/dead-mans-switch.md). The log says what // was done, never to whom. Owns the switch. Trust boundary: the admin socket // is never reachable from the network; the switch's network path (dmsHttp) // accepts only signed orders and otherwise answers as the cover site. import net from 'node:net'; import { unlinkSync } from 'node:fs'; import { resolve as resolvePath } from 'node:path'; import { DeadMansSwitch, wipe as dmsWipe, plan as dmsPlan } from './dms.js'; import { die } from './config.js'; const LIMIT_RANGES = { rate_burst: [1, 1000], rate_per_sec: [1, 1000], budget_scale: [0.01, 100], register_pow_bits: [0, 28] }; const QUIET = ['users', 'stats', 'dms', 'drill']; export function create(app) { const { cfg, disk } = app; const { users, rooms, sessions } = app.state; const LIMITS = cfg.limits; const paths = { dataDir: cfg.DATA_DIR, keyDir: cfg.KEY_DIR, extraPaths: cfg.DMS.wipePaths }; const unlinkSocket = () => { if (cfg.ADMIN_SOCKET) { try { unlinkSync(cfg.ADMIN_SOCKET); } catch { /* already gone */ } } }; // Carry out the wipe, then exit with status 0 so a supervisor doesn't restart it. function decommission() { const { destroyed, errors } = dmsWipe({ ...paths, before: () => { app.gateway.terminateAll(); disk.close(); unlinkSocket(); }, }); console.log(`Decommissioned: ${destroyed.length} paths destroyed${errors.length ? `; ${errors.length} errors: ${errors.join('; ')}` : ''}`); process.exit(errors.length ? 3 : 0); } let dms; try { const { readOperators, quorum, windowMs, deadhandMs, graceMs, duressDelayMs } = cfg.DMS; dms = new DeadMansSwitch({ server: cfg.SERVER_NAME, operators: readOperators(), quorum, windowMs, deadhandMs, graceMs, duressDelayMs, statePath: disk.enabled ? resolvePath(cfg.KEY_DIR, 'dms-state.json') : null, onWipe: decommission, }); } catch (e) { die(`Dead man's switch: ${e.message}`); } const adminUser = (args) => { const raw = String(args?.user ?? '').trim().toLowerCase(); if (!raw) throw new Error('Name a user'); const user_id = raw.startsWith('@') ? raw : `@${raw}:${cfg.SERVER_NAME}`; if (!app.isLocalUser(user_id)) throw new Error('That is not an account on this server'); if (!users.has(user_id)) throw new Error('No such account'); return user_id; }; // Sign every device of an account out and forget its device keys. function revokeAll(user_id) { app.auth.dropFlows(user_id); app.auth.revokeDevices(user_id, 'Signed out by the operator'); } const ADMIN = { users: () => [...users.values()].map((u) => ({ user_id: u.user_id, created_ts: u.created_ts, suspended: app.auth.isSuspended(u.user_id), security_keys: app.auth.securityKeyCount(u.user_id), })), stats: () => ({ users: users.size, rooms: rooms.size, sessions: sessions.size, suspended: app.auth.suspendedCount(), limits: { ...LIMITS } }), suspend(args) { const user_id = adminUser(args); app.auth.setSuspended(user_id, true); revokeAll(user_id); return { suspended: true }; }, unsuspend(args) { app.auth.setSuspended(adminUser(args), false); return { suspended: false }; }, revoke(args) { revokeAll(adminUser(args)); return { revoked: true }; }, // For a user who lost every security key: clear them and the login rule, and // sign every device out. This is a way round the keys, so it is the // operator's decision, made after checking who is asking. unlock(args) { const user_id = adminUser(args); app.auth.dropSecurityKeys(user_id); revokeAll(user_id); app.keys.notifyDeviceListChange(user_id); return { unlocked: true }; }, delete(args) { app.account.deleteAccount(adminUser(args)); return { deleted: true }; }, invite(args) { return app.quota.createInvite(args?.ttl_hours === undefined ? 168 : Number(args.ttl_hours)); }, 'rotate-signing-key': () => app.fed.rotateSigningKey(), 'repin-peer'(args) { const server = String(args?.server ?? '').trim(); if (!server || !cfg.PEERS.has(server)) throw new Error(`Unknown peer '${server}'`); return { server, unpinned: app.fed.repinPeer(server) }; }, limits(args) { const [name, value] = [args?.name, args?.value]; if (name === undefined) return { ...LIMITS }; if (name === 'registration_open' || name === 'invite_only') { if (typeof value !== 'boolean') throw new Error(`${name} is true or false`); LIMITS[name] = value; return { ...LIMITS }; } const range = LIMIT_RANGES[name]; if (!range) throw new Error(`Unknown limit '${name}'. Known: registration_open, invite_only, ${Object.keys(LIMIT_RANGES).join(', ')}`); if (typeof value !== 'number' || !Number.isFinite(value) || value < range[0] || value > range[1]) throw new Error(`${name} is a number from ${range[0]} to ${range[1]}`); LIMITS[name] = value; return { ...LIMITS }; }, dms: () => dms.status(), checkin: () => { dms.checkin(); return { checked_in: true }; }, order: (args) => dms.submit(String(args?.token ?? '')), decommission: (args) => dms.command(args?.confirm), drill: () => { const { list, blocked } = dmsPlan(paths); return { would_destroy: list, cannot_destroy: blocked, memory_only: !disk.enabled }; }, }; function startAdminSocket(path) { const server = net.createServer((socket) => { let buf = ''; socket.setTimeout(10_000, () => socket.destroy()); socket.on('error', () => socket.destroy()); socket.on('data', (d) => { buf += d; if (buf.length > 4096) return socket.destroy(); const nl = buf.indexOf('\n'); if (nl < 0) return undefined; let out; try { const req = JSON.parse(buf.slice(0, nl)); if (!Object.hasOwn(ADMIN, req.cmd)) throw new Error(`Unknown command '${req.cmd}'`); out = { ok: true, result: ADMIN[req.cmd](req.args ?? {}) }; if (!QUIET.includes(req.cmd) && !(req.cmd === 'limits' && req.args?.name === undefined)) console.log(`admin: ${req.cmd}`); } catch (e) { out = { ok: false, error: e.message }; } socket.end(`${JSON.stringify(out)}\n`); return undefined; }); }); // A bad path (too long for a socket, missing directory) must say so, not die with a stack trace. server.on('error', (e) => die(`Can't open the admin socket ${path}: ${e.code ?? e.message}. Unix socket paths are limited to about 100 characters.`)); try { unlinkSync(path); } catch { /* nothing left over */ } const previous = process.umask(0o177); // created as 0600 server.listen(path, () => console.log('Admin socket ready')); process.umask(previous); } return { unlinkSocket, start() { if (cfg.ADMIN_SOCKET) startAdminSocket(cfg.ADMIN_SOCKET); // After everything else exists: a deadline that passed while the server was down fires now. dms.start(cfg.DMS.checkMs); }, // A signed order over the network. Anything that isn't a valid order gets the // cover site's answer, so the path looks like it doesn't exist. async dmsHttp(req, res) { let body = ''; for await (const chunk of req) { body += chunk; if (body.length > 2048) return false; } let result; try { result = dms.submit(body.trim()); } catch { return false; } res.writeHead(200, { 'content-type': 'application/json', 'cache-control': 'no-store' }); res.end(JSON.stringify(result)); return true; }, }; }