File size: 7,974 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 | // 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;
},
};
}
|