// The background host: `daemon start` spawns `ruflo-phone daemon run`, which serves until stopped // and records itself in /daemon.json (0600). Pairing, listing and revoking work against // it from any process through the shared state directory; the daemon re-reads the device list on // every request. import { spawn } from 'node:child_process'; import { closeSync, existsSync, mkdirSync, openSync, readFileSync, rmSync, writeFileSync } from 'node:fs'; import { dirname, join } from 'node:path'; import { fileURLToPath } from 'node:url'; import { mintPairing, parseAppChoice } from './pairing.mjs'; import { openStore, defaultStateDir, PAIRING_TTL_MS } from './store.mjs'; import { openLocalFile, writePairingPage } from './qr-page.mjs'; const BIN = join(dirname(fileURLToPath(import.meta.url)), '..', 'bin', 'ruflo-phone.mjs'); const STATE_FILE = 'daemon.json'; const LOG_FILE = 'daemon.log'; const fail = (code, message) => Object.assign(new Error(message), { code }); const sleep = (ms) => new Promise((r) => setTimeout(r, ms)); function alive(pid) { if (!Number.isSafeInteger(pid) || pid <= 1) return false; try { process.kill(pid, 0); return true; } catch (e) { return e.code === 'EPERM'; } } function readState(dir) { try { return JSON.parse(readFileSync(join(dir, STATE_FILE), 'utf8')); } catch { return null; } } /** Written by the daemon itself once it is listening. */ export function writeDaemonState(dir, state) { mkdirSync(dir, { recursive: true, mode: 0o700 }); writeFileSync(join(dir, STATE_FILE), JSON.stringify(state), { mode: 0o600 }); } export function clearDaemonState(dir, pid) { const s = readState(dir); if (s && (pid === undefined || s.pid === pid)) rmSync(join(dir, STATE_FILE), { force: true }); } /** @returns {Promise<{ running: boolean, pid?: number, endpoint?: string, full?: boolean, bundle?: string|null, startedAt?: string, shared?: string[], logFile: string }>} */ export async function daemonStatus({ stateDir = defaultStateDir() } = {}) { const logFile = join(stateDir, LOG_FILE); const s = readState(stateDir); if (!s || !alive(s.pid)) return { running: false, logFile }; return { running: true, pid: s.pid, endpoint: s.endpoint, full: Boolean(s.full), bundle: s.bundle ?? null, startedAt: s.startedAt, shared: s.shared ?? [], logFile }; } /** Argument list for `daemon run` (and `start`) from validated options. */ export function hostArgs({ full, bind, port, projects = [], workspaces = [], bundle } = {}) { const a = []; if (full) a.push('--full'); if (bind) a.push('--bind', String(bind)); if (port !== undefined && port !== null) { if (!Number.isInteger(Number(port)) || Number(port) < 1024 || Number(port) > 65535) throw fail('invalid_argument', 'port must be 1024-65535'); a.push('--port', String(port)); } for (const p of projects) a.push('--project', String(p)); for (const w of workspaces) a.push('--workspace', String(w)); if (bundle) a.push('--bundle', String(bundle)); return a; } /** * Starts the background host if it is not running. Its output goes to daemon.log (0600), which * never contains a pairing code: the daemon mints none itself. */ export async function startDaemon({ stateDir = defaultStateDir(), cwd = process.cwd(), timeoutMs = 15000, ...opts } = {}) { const now = await daemonStatus({ stateDir }); if (now.running) return { ...now, alreadyRunning: true }; mkdirSync(stateDir, { recursive: true, mode: 0o700 }); const logFile = join(stateDir, LOG_FILE); const fd = openSync(logFile, 'a', 0o600); let child; try { child = spawn(process.execPath, [BIN, 'daemon', 'run', '--state', stateDir, ...hostArgs(opts)], { cwd, detached: true, stdio: ['ignore', fd, fd], env: process.env, }); } finally { closeSync(fd); } child.unref(); let exited = null; child.once('exit', (code) => { exited = code ?? -1; }); const until = Date.now() + timeoutMs; while (Date.now() < until) { const s = await daemonStatus({ stateDir }); if (s.running && s.pid === child.pid) return s; if (exited !== null) break; await sleep(100); } if (alive(child.pid)) { try { process.kill(child.pid, 'SIGTERM'); } catch { /* gone */ } } throw fail('daemon_start_failed', `The phone host did not start; see ${logFile}`); } export async function stopDaemon({ stateDir = defaultStateDir(), timeoutMs = 10000 } = {}) { const s = await daemonStatus({ stateDir }); if (!s.running) { clearDaemonState(stateDir); return { stopped: false }; } process.kill(s.pid, 'SIGTERM'); const until = Date.now() + timeoutMs; while (Date.now() < until && alive(s.pid)) await sleep(100); if (alive(s.pid)) process.kill(s.pid, 'SIGKILL'); clearDaemonState(stateDir, s.pid); return { stopped: true }; } /** * Pairs one phone against the running daemon and shows the QR code to the person at this * computer: `window` opens a local page, `file` only writes it. The result never holds the code, * link or QR text, so it is safe to hand to an agent or log. */ export async function pairDevice({ stateDir = defaultStateDir(), name = 'Phone', access = 'read', apps = ['ruflo', 'orca'], show = 'window' } = {}) { if (access !== 'read' && access !== 'full') throw fail('invalid_argument', 'access must be read or full'); if (show !== 'window' && show !== 'file') throw fail('invalid_argument', 'show must be window or file'); const chosen = Array.isArray(apps) ? apps : parseAppChoice(apps); if (!chosen.length || chosen.some((a) => a !== 'ruflo' && a !== 'orca')) throw fail('invalid_argument', 'apps must be ruflo and/or orca'); const label = String(name).replace(/[\u0000-\u001f]/g, '').slice(0, 64) || 'Phone'; const s = await daemonStatus({ stateDir }); if (!s.running) throw fail('daemon_not_running', 'The phone host is not running: start it with `ruflo phone daemon start`'); if (access === 'full' && !s.full) throw fail('daemon_not_full', 'The phone host was started without --full, so it cannot serve a full-access phone. Restart it with `ruflo phone daemon start --full`.'); const store = openStore({ dir: stateDir }); const p = mintPairing({ store, endpoint: s.endpoint, name: label, apps: chosen, access }); const qrFile = writePairingPage(stateDir, p, label); const opened = show === 'window' ? await openLocalFile(qrFile) : false; return { deviceId: p.deviceId, access, expiresAt: new Date(p.expiresAt).toISOString(), shownIn: opened ? 'window' : 'file', qrFile }; } export async function listDevices({ stateDir = defaultStateDir() } = {}) { return openStore({ dir: stateDir }).list().map((d) => ({ deviceId: d.deviceId, name: d.name, access: d.access === 'full' ? 'full' : 'read', pending: Boolean(d.pending), lastSeenAt: d.lastSeenAt ? new Date(d.lastSeenAt).toISOString() : null, })); } export async function revokeDevice(deviceId, { stateDir = defaultStateDir() } = {}) { if (typeof deviceId !== 'string' || !/^dev_[A-Za-z0-9_-]{8,64}$/.test(deviceId)) throw fail('invalid_argument', 'deviceId looks wrong'); const revoked = openStore({ dir: stateDir }).revoke(deviceId); // The pairing page of an unscanned device holds its credential: remove it with the device. rmSync(join(stateDir, 'pairing', `${deviceId}.html`), { force: true }); return { revoked: Boolean(revoked) }; } export const DAEMON_FILES = { STATE_FILE, LOG_FILE, PAGE_MAX_AGE_MS: PAIRING_TTL_MS }; export const daemonStateExists = (dir) => existsSync(join(dir, STATE_FILE));