Download server/dms.js from abr00kx/taper: direct link, hf CLI and curl.
- Browser
- Download file 14.1 kB
-
https://huggingface.co/abr00kx/taper/resolve/main/server/dms.js
- Command line
-
hf download hf://abr00kx/taper/server/dms.js
-
curl -L -o dms.js https://huggingface.co/abr00kx/taper/resolve/main/server/dms.js
14.1 kB
| // Dead man's switch: destroy everything this server holds and take it out of | |
| // service. Documented for operators in docs/dead-mans-switch.md. | |
| // | |
| // Four ways to set it off, one way to carry it out: | |
| // | |
| // command an operator on the machine runs `admin.js decommission <server name>` | |
| // quorum M of N operators each send a signed `decommission` order | |
| // dead hand no operator has checked in for TAPER_DMS_DEADHAND_MS, and nobody | |
| // did during the grace period that followed | |
| // duress an operator checks in with their duress key: the check-in looks | |
| // accepted, and the wipe follows after TAPER_DMS_DURESS_DELAY_MS | |
| // | |
| // The wipe is crypto-shredding first (every key overwritten and deleted, so | |
| // any copy of the data, backups included, is unreadable), then the data files | |
| // themselves, then any extra paths the operator listed (TLS key, onion | |
| // service keys). It leaves a DECOMMISSIONED marker so the server won't start | |
| // again on an empty database as if nothing happened. | |
| // | |
| // Signed orders use Ed25519 from node:crypto. An order is: | |
| // taper-dms-v1 \n <server name> \n <action> \n <time, ms> \n <random nonce> | |
| // and is accepted only within ORDER_MAX_AGE_MS of its time, once. | |
| import { generateKeyPairSync, createPrivateKey, createPublicKey, sign, verify, randomBytes } from 'node:crypto'; | |
| import { | |
| existsSync, lstatSync, openSync, writeSync, fsyncSync, closeSync, unlinkSync, readdirSync, rmdirSync, | |
| readFileSync, writeFileSync, renameSync, accessSync, constants as fsc, | |
| } from 'node:fs'; | |
| import { join, dirname } from 'node:path'; | |
| export const MARKER = 'DECOMMISSIONED'; | |
| export const ORDER_MAX_AGE_MS = 10 * 60_000; | |
| const ACTIONS = new Set(['checkin', 'decommission']); | |
| const b64u = (buf) => Buffer.from(buf).toString('base64url'); | |
| // --- keys and orders --------------------------------------------------------- | |
| /** A new operator key pair: the private key as PEM, the public key as base64url (raw 32 bytes). */ | |
| export function generateOperatorKey() { | |
| const { privateKey, publicKey } = generateKeyPairSync('ed25519'); | |
| const raw = publicKey.export({ format: 'jwk' }).x; | |
| return { privatePem: privateKey.export({ format: 'pem', type: 'pkcs8' }), publicKey: raw }; | |
| } | |
| const publicFromRaw = (x) => createPublicKey({ key: { kty: 'OKP', crv: 'Ed25519', x }, format: 'jwk' }); | |
| /** | |
| * The operators file: one operator per line, | |
| * <name> <public key> [<duress public key>] | |
| * Blank lines and lines starting with # are ignored. | |
| */ | |
| export function parseOperators(text) { | |
| const ops = new Map(); // public key -> { name, duress } | |
| const names = new Set(); | |
| for (const [i, line] of text.split('\n').entries()) { | |
| const t = line.trim(); | |
| if (!t || t.startsWith('#')) continue; | |
| const [name, key, duressKey, extra] = t.split(/\s+/); | |
| if (!key || extra) throw new Error(`operators file, line ${i + 1}: expected "<name> <public key> [<duress public key>]"`); | |
| if (names.has(name)) throw new Error(`operators file, line ${i + 1}: ${name} is listed twice`); | |
| names.add(name); | |
| for (const [k, duress] of [[key, false], [duressKey, true]]) { | |
| if (!k) continue; | |
| if (!/^[A-Za-z0-9_-]{43}$/.test(k)) throw new Error(`operators file, line ${i + 1}: not an Ed25519 public key`); | |
| if (ops.has(k)) throw new Error(`operators file, line ${i + 1}: a key is listed twice`); | |
| publicFromRaw(k); // throws if it isn't a valid point | |
| ops.set(k, { name, duress }); | |
| } | |
| } | |
| return ops; | |
| } | |
| /** Sign an order. The result is one opaque string to hand to the server. */ | |
| export function signOrder({ privatePem, server, action, ts = Date.now(), nonce = b64u(randomBytes(16)) }) { | |
| if (!ACTIONS.has(action)) throw new Error(`action is one of: ${[...ACTIONS].join(', ')}`); | |
| const key = createPrivateKey(privatePem); | |
| const publicKey = createPublicKey(key).export({ format: 'jwk' }).x; | |
| const message = `taper-dms-v1\n${server}\n${action}\n${ts}\n${nonce}`; | |
| return b64u(JSON.stringify({ k: publicKey, a: action, t: ts, n: nonce, s: b64u(sign(null, Buffer.from(message), key)) })); | |
| } | |
| /** | |
| * Check an order. Returns { name, duress, action, nonce } or throws. | |
| * Does not remember nonces: the switch does that. | |
| */ | |
| export function verifyOrder(token, { operators, server, now = Date.now() }) { | |
| let o; | |
| try { o = JSON.parse(Buffer.from(String(token), 'base64url').toString('utf8')); } catch { throw new Error('Not an order'); } | |
| if (!o || typeof o !== 'object' || typeof o.k !== 'string' || typeof o.a !== 'string' || !Number.isSafeInteger(o.t) | |
| || typeof o.n !== 'string' || !/^[A-Za-z0-9_-]{16,64}$/.test(o.n) || typeof o.s !== 'string') throw new Error('Not an order'); | |
| if (!ACTIONS.has(o.a)) throw new Error('Unknown action'); | |
| const op = operators.get(o.k); | |
| if (!op) throw new Error('Unknown key'); | |
| if (Math.abs(now - o.t) > ORDER_MAX_AGE_MS) throw new Error('Order too old or from the future'); | |
| const message = `taper-dms-v1\n${server}\n${o.a}\n${o.t}\n${o.n}`; | |
| if (!verify(null, Buffer.from(message), publicFromRaw(o.k), Buffer.from(o.s, 'base64url'))) throw new Error('Bad signature'); | |
| return { name: op.name, duress: op.duress, action: o.a, nonce: o.n }; | |
| } | |
| // --- the wipe ---------------------------------------------------------------- | |
| /** Overwrite a file with random bytes, flush it to disk and delete it. */ | |
| function shredFile(path) { | |
| const size = lstatSync(path).size; | |
| const fd = openSync(path, 'r+'); | |
| try { | |
| const chunk = randomBytes(Math.min(size, 1 << 20) || 1); | |
| for (let off = 0; off < size; off += chunk.length) writeSync(fd, chunk, 0, Math.min(chunk.length, size - off), off); | |
| fsyncSync(fd); | |
| } finally { closeSync(fd); } | |
| unlinkSync(path); | |
| } | |
| /** Shred a file, or everything in a directory and then the directory. Symbolic links are removed, never followed. */ | |
| function shredPath(path, destroyed, keepDir = false) { | |
| let st; | |
| try { st = lstatSync(path); } catch { return; } | |
| try { | |
| if (st.isDirectory()) { | |
| for (const name of readdirSync(path)) shredPath(join(path, name), destroyed); // each entry fails alone | |
| if (!keepDir) rmdirSync(path); | |
| destroyed.push(`${path}/`); | |
| return; | |
| } | |
| if (st.isFile()) { try { shredFile(path); } catch { unlinkSync(path); } } else unlinkSync(path); | |
| destroyed.push(path); | |
| } catch { /* one failure must not stop the rest of the wipe */ } | |
| } | |
| /** | |
| * What a wipe would destroy, without touching it, and what it couldn't | |
| * (deleting needs write access to the containing directory). | |
| */ | |
| export function plan({ dataDir, keyDir, extraPaths = [] }) { | |
| const list = []; | |
| const blocked = []; | |
| const writable = (p) => { try { accessSync(p, fsc.W_OK); return true; } catch { return false; } }; | |
| const walk = (p) => { | |
| let st; | |
| try { st = lstatSync(p); } catch { return; } | |
| if (!writable(dirname(p)) || (st.isFile() && !writable(p))) blocked.push(p); | |
| if (st.isDirectory() && !st.isSymbolicLink()) { | |
| try { for (const n of readdirSync(p)) walk(join(p, n)); } catch { blocked.push(p); } | |
| } else list.push(p); | |
| }; | |
| // Keys first: once they are gone the data is unreadable, even if the rest is interrupted. | |
| for (const p of [keyDir, dataDir]) if (p) walk(p); | |
| for (const p of extraPaths) { if (existsSync(p)) walk(p); else blocked.push(`${p} (does not exist)`); } | |
| return { list, blocked }; | |
| } | |
| /** | |
| * Destroy everything. Order matters: keys, then data, then extra paths. Each | |
| * step goes on if an earlier one failed, and the errors are returned. | |
| */ | |
| export function wipe({ dataDir, keyDir, extraPaths = [], before = () => {} }) { | |
| const destroyed = []; | |
| const errors = []; | |
| const attempt = (fn) => { try { fn(); } catch (e) { errors.push(e.message); } }; | |
| attempt(before); // close the database, drop connections | |
| if (keyDir) attempt(() => shredPath(keyDir, destroyed, true)); | |
| if (dataDir) attempt(() => shredPath(dataDir, destroyed, true)); | |
| for (const p of extraPaths) attempt(() => shredPath(p, destroyed)); | |
| if (dataDir) { | |
| attempt(() => writeFileSync(join(dataDir, MARKER), `This Taper server was decommissioned at ${new Date().toISOString()}.\n`, { mode: 0o600 })); | |
| } | |
| return { destroyed, errors }; | |
| } | |
| export const isDecommissioned = (dataDir) => Boolean(dataDir) && existsSync(join(dataDir, MARKER)); | |
| // --- the switch -------------------------------------------------------------- | |
| export class DeadMansSwitch { | |
| /** | |
| * @param server server name (part of every signed order) | |
| * @param operators Map from parseOperators (may be empty: command mode only) | |
| * @param quorum signed decommission orders needed (M of N) | |
| * @param windowMs how long collected orders count towards the quorum | |
| * @param deadhandMs no check-in for this long starts the grace period (0: off) | |
| * @param graceMs grace period after a missed deadline, before the wipe | |
| * @param duressDelayMs time between a duress check-in and the wipe | |
| * @param statePath where the last check-in is kept (in the key directory) | |
| * @param onWipe (reason) => void: carries out the wipe | |
| */ | |
| constructor({ server, operators = new Map(), quorum = 1, windowMs = 3_600_000, deadhandMs = 0, graceMs = 86_400_000, | |
| duressDelayMs = 15 * 60_000, statePath = null, onWipe, log = console.log, now = Date.now }) { | |
| const names = new Set([...operators.values()].map((o) => o.name)); | |
| if (names.size && (quorum < 1 || quorum > names.size)) throw new Error(`TAPER_DMS_QUORUM must be from 1 to ${names.size} (the number of operators)`); | |
| if (deadhandMs && !names.size) throw new Error('The dead hand needs operators who can check in (TAPER_DMS_OPERATORS)'); | |
| Object.assign(this, { server, operators, quorum, windowMs, deadhandMs, graceMs, duressDelayMs, statePath, onWipe, log, now }); | |
| this.votes = new Map(); // operator name -> time of their decommission order | |
| this.seen = new Map(); // nonce -> time, to refuse replays | |
| this.fired = false; | |
| this.duressTimer = null; | |
| this.lastCheckin = this.loadState() ?? now(); | |
| this.saveState(); | |
| } | |
| loadState() { | |
| if (!this.statePath || !existsSync(this.statePath)) return null; | |
| try { const ts = JSON.parse(readFileSync(this.statePath, 'utf8')).last_checkin_ts; return Number.isSafeInteger(ts) ? ts : null; } catch { return null; } | |
| } | |
| saveState() { | |
| if (!this.statePath) return; | |
| const tmp = `${this.statePath}.tmp`; | |
| writeFileSync(tmp, JSON.stringify({ last_checkin_ts: this.lastCheckin }), { mode: 0o600 }); | |
| renameSync(tmp, this.statePath); | |
| } | |
| fire(reason) { | |
| if (this.fired) return; | |
| this.fired = true; | |
| this.stop(); | |
| this.log(`dead man's switch: ${reason}; wiping`); | |
| this.onWipe(reason); | |
| } | |
| checkin() { | |
| this.lastCheckin = this.now(); | |
| this.saveState(); | |
| } | |
| /** The command mode: an operator on the machine, who must type the server name. */ | |
| command(confirm) { | |
| if (confirm !== this.server) throw new Error(`To decommission, confirm with the server name: decommission ${this.server}`); | |
| setImmediate(() => this.fire('decommissioned by command')); | |
| return { decommissioning: true }; | |
| } | |
| /** | |
| * A signed order, from the admin socket or the network. The answer to a | |
| * duress check-in is the same as to a real one. | |
| */ | |
| submit(token) { | |
| const t = this.now(); | |
| const order = verifyOrder(token, { operators: this.operators, server: this.server, now: t }); | |
| for (const [n, ts] of this.seen) if (t - ts > 2 * ORDER_MAX_AGE_MS) this.seen.delete(n); | |
| if (this.seen.has(order.nonce)) throw new Error('Order already used'); | |
| this.seen.set(order.nonce, t); | |
| if (order.duress) { | |
| // Looks like the action was accepted; the wipe follows, and no check-in can stop it. | |
| if (!this.duressTimer && !this.fired) { | |
| this.duressTimer = setTimeout(() => this.fire('duress'), this.duressDelayMs); | |
| this.duressTimer.unref?.(); | |
| } | |
| if (order.action !== 'checkin') return { votes: this.voteCount(t), quorum: this.quorum }; | |
| } | |
| if (order.action === 'checkin') { | |
| this.checkin(); // a duress check-in records one too, so the state file can't tell them apart | |
| return { checked_in: true }; | |
| } | |
| this.votes.set(order.name, t); | |
| const votes = this.voteCount(t); | |
| this.log(`dead man's switch: decommission order ${votes} of ${this.quorum}`); | |
| if (votes >= this.quorum) setImmediate(() => this.fire(`decommissioned by ${votes} of ${this.operatorCount()} operators`)); | |
| return { votes, quorum: this.quorum }; | |
| } | |
| operatorCount() { return new Set([...this.operators.values()].map((o) => o.name)).size; } | |
| voteCount(t = this.now()) { | |
| for (const [name, ts] of this.votes) if (t - ts > this.windowMs) this.votes.delete(name); | |
| return this.votes.size; | |
| } | |
| /** The dead hand's clock. Call often (start() does, every checkMs). */ | |
| tick() { | |
| if (this.fired || !this.deadhandMs) return; | |
| const late = this.now() - this.lastCheckin - this.deadhandMs; | |
| if (late >= this.graceMs) this.fire('no operator checked in'); | |
| else if (late >= 0 && !this.warned) { this.warned = true; this.log(`dead man's switch: no check-in for ${Math.round((this.deadhandMs + late) / 3_600_000)} h; wiping in ${Math.round((this.graceMs - late) / 60_000)} min unless an operator checks in`); } | |
| else if (late < 0) this.warned = false; | |
| } | |
| status() { | |
| const t = this.now(); | |
| return { | |
| operators: this.operatorCount(), | |
| quorum: this.quorum, | |
| decommission_votes: this.voteCount(t), | |
| dead_hand: this.deadhandMs | |
| ? { last_checkin: new Date(this.lastCheckin).toISOString(), deadline: new Date(this.lastCheckin + this.deadhandMs).toISOString(), wipe_at: new Date(this.lastCheckin + this.deadhandMs + this.graceMs).toISOString() } | |
| : 'off', | |
| // Deliberately absent: whether a duress wipe is pending. Whoever can run this command may be the one applying the pressure. | |
| }; | |
| } | |
| start(checkMs = 60_000) { | |
| this.tick(); | |
| this.timer = setInterval(() => this.tick(), checkMs); | |
| this.timer.unref?.(); | |
| } | |
| stop() { clearInterval(this.timer); } | |
| } | |