/** * Durable pairing state for LAN Share: devices that survived a restart and * short-lived, single-use QR tickets. * * A device record stores only a SHA-256 digest of its cookie secret; the * secret itself lives in the tablet's HttpOnly cookie and is never written to * disk or logged. Tickets are memory-only by design: a QR code is a one-time * grant, not a durable credential. */ import { createHash, randomBytes, timingSafeEqual } from 'node:crypto'; import { mkdir, open, readFile, rename, stat, unlink, writeFile } from 'node:fs/promises'; import { dirname } from 'node:path'; /** Current on-disk state format. */ const STATE_VERSION = 1; /** How long an online device may go without a request before the list calls it idle. */ export const ONLINE_WINDOW_MS = 30_000; /** Maximum number of simultaneously valid QR tickets. */ const MAX_TICKETS = 8; /** * SHA-256 of a secret, as lowercase hex. * @param {string} secret cookie secret. * @returns {string} digest. */ function digest(secret) { return createHash('sha256').update(secret, 'utf8').digest('hex'); } /** * Compare two hex digests without leaking where they differ. * @param {string} left first digest. * @param {string} right second digest. * @returns {boolean} true only for equal digests. */ function digestEquals(left, right) { if (typeof left !== 'string' || typeof right !== 'string' || left.length !== right.length) return false; const a = Buffer.from(left, 'hex'); const b = Buffer.from(right, 'hex'); return a.length === b.length && timingSafeEqual(a, b); } /** * Write a file atomically with owner-only permissions. * @param {string} file destination. * @param {string} text content. */ async function writeAtomic(file, text) { await mkdir(dirname(file), { recursive: true, mode: 0o700 }); const temporary = file + '.tmp-' + String(process.pid) + '-' + randomBytes(4).toString('hex'); await writeFile(temporary, text, { mode: 0o600 }); await rename(temporary, file); } /** * Serialize writes between two Harness processes that happen to share a home. * @template T * @param {string} file destination whose lock guards the write. * @param {() => Promise} work write to perform. * @returns {Promise} the write result. */ async function withFileLock(file, work) { await mkdir(dirname(file), { recursive: true, mode: 0o700 }); const lockFile = file + '.lock'; for (let attempt = 0; attempt < 40; attempt++) { let handle; try { handle = await open(lockFile, 'wx', 0o600); } catch (error) { if (error?.code !== 'EEXIST') throw error; try { const info = await stat(lockFile); if (Date.now() - info.mtimeMs > 5_000) { await unlink(lockFile).catch(() => {}); continue; } } catch { /* the holder removed it between our open and stat */ } await new Promise((resolveDelay) => setTimeout(resolveDelay, 25)); continue; } try { return await work(); } finally { await handle.close().catch(() => {}); await unlink(lockFile).catch(() => {}); } } return work(); } /** * One paired device. * @typedef {{ id: string, secretHash: string, label: string, ip: string, sessionId: string | null, createdAt: number, lastSeenAt: number, expiresAt: number }} DeviceRecord */ /** * The durable device registry. */ export class DeviceStore { /** * @param {string} file absolute state-file path. * @param {{ ttlMs: number, maxDevices: number, logger?: (level: string, message: unknown) => void }} options lifetime and capacity. */ constructor(file, options) { this.file = file; this.ttlMs = options.ttlMs; this.maxDevices = options.maxDevices; this.log = options.logger ?? (() => {}); /** @type {Map} */ this.records = new Map(); this.flushTimer = null; this.writeChain = Promise.resolve(); this.loaded = false; } /** Read the state file; a missing or unreadable file starts empty. */ async load() { let parsed; try { parsed = JSON.parse(await readFile(this.file, 'utf8')); } catch (error) { if (error?.code !== 'ENOENT') this.log('warn', error); parsed = undefined; } if (parsed !== undefined && parsed !== null && typeof parsed === 'object' && Array.isArray(parsed.devices)) { const now = Date.now(); for (const raw of parsed.devices) { if (raw === null || typeof raw === 'object' === false) continue; if (typeof raw.id !== 'string' || typeof raw.secretHash !== 'string') continue; if (typeof raw.expiresAt !== 'number' || raw.expiresAt <= now) continue; this.records.set(raw.id, { id: raw.id, secretHash: raw.secretHash, label: typeof raw.label === 'string' ? raw.label : 'Browser', ip: typeof raw.ip === 'string' ? raw.ip : 'unknown', sessionId: typeof raw.sessionId === 'string' ? raw.sessionId : null, createdAt: typeof raw.createdAt === 'number' ? raw.createdAt : now, lastSeenAt: typeof raw.lastSeenAt === 'number' ? raw.lastSeenAt : 0, expiresAt: raw.expiresAt, }); } } this.loaded = true; this.prune(); } /** Drop expired records. */ prune() { const now = Date.now(); for (const [id, record] of this.records) if (record.expiresAt <= now) this.records.delete(id); } /** * Register a paired device. * @param {{ label: string, ip: string, sessionId: string | null }} facts pairing facts. * @returns {Promise<{ record: DeviceRecord, cookie: string }>} the record and its cookie value. */ async add(facts) { this.prune(); if (this.records.size >= this.maxDevices) { const error = new Error('lan-share: device limit reached'); error.code = 'DEVICE_LIMIT'; throw error; } const id = randomBytes(9).toString('base64url'); const secret = randomBytes(32).toString('base64url'); const now = Date.now(); /** @type {DeviceRecord} */ const record = { id, secretHash: digest(secret), label: facts.label, ip: facts.ip, sessionId: facts.sessionId ?? null, createdAt: now, lastSeenAt: now, expiresAt: now + this.ttlMs, }; this.records.set(id, record); try { await this.flush(); } catch (error) { this.records.delete(id); throw error; } return { record, cookie: id + '.' + secret }; } /** * Validate a device cookie and record activity. * @param {string | undefined} value cookie value \`.\`. * @returns {DeviceRecord | undefined} the live record. */ verify(value) { if (typeof value !== 'string') return undefined; const dot = value.indexOf('.'); if (dot <= 0 || dot === value.length - 1) return undefined; const record = this.records.get(value.slice(0, dot)); if (record === undefined) return undefined; if (record.expiresAt <= Date.now()) { this.records.delete(record.id); this.scheduleFlush(); return undefined; } if (!digestEquals(record.secretHash, digest(value.slice(dot + 1)))) return undefined; record.lastSeenAt = Date.now(); return record; } /** * Public view of every device, newest first. * @returns {Array & { online: boolean }>} device list. */ list() { this.prune(); const now = Date.now(); return [...this.records.values()] .sort((left, right) => right.createdAt - left.createdAt) .map(({ secretHash, ...rest }) => ({ ...rest, online: now - rest.lastSeenAt < ONLINE_WINDOW_MS, })); } /** * Remember the Session this device last opened. * @param {string} id device id. * @param {string | null} sessionId Session id. */ setSession(id, sessionId) { const record = this.records.get(id); if (record === undefined) return; record.sessionId = sessionId; this.scheduleFlush(); } /** * Revoke one device. * @param {string} id device id. * @returns {Promise} whether a record was removed. */ async revoke(id) { const removed = this.records.delete(id); if (removed) await this.flush(); return removed; } /** * Revoke every device. * @returns {Promise} how many records were removed. */ async revokeAll() { const count = this.records.size; this.records.clear(); if (count > 0) await this.flush(); return count; } /** Persist after a short quiet period, so navigation does not rewrite the file per keystroke. */ scheduleFlush() { if (this.flushTimer !== null) return; this.flushTimer = setTimeout(() => { this.flushTimer = null; this.flush().catch((error) => this.log('warn', error)); }, 1500); if (typeof this.flushTimer.unref === 'function') this.flushTimer.unref(); } /** Write the current registry atomically. */ flush() { const payload = JSON.stringify({ version: STATE_VERSION, devices: [...this.records.values()], }, null, 2); this.writeChain = this.writeChain .catch(() => {}) .then(() => withFileLock(this.file, () => writeAtomic(this.file, payload + '\n'))); return this.writeChain; } /** Stop the pending debounce and write once more. */ async close() { if (this.flushTimer !== null) { clearTimeout(this.flushTimer); this.flushTimer = null; } await this.flush(); } } /** * Single-use QR tickets. A ticket grants exactly one device pairing and dies * with the process; nothing durable ever contains its secret. */ export class TicketStore { /** * @param {{ ttlMs: number }} options ticket lifetime. */ constructor(options) { this.ttlMs = options.ttlMs; /** @type {Map} */ this.tickets = new Map(); } /** * Mint one ticket. * @param {string | null | undefined} sessionId Session the new device should open. * @returns {{ token: string, sessionId: string | null, expiresAt: number, ticketId: string }} ticket facts. */ mint(sessionId) { this.prune(); while (this.tickets.size >= MAX_TICKETS) { const oldest = this.tickets.keys().next().value; if (oldest === undefined) break; this.tickets.delete(oldest); } const token = randomBytes(32).toString('base64url'); const now = Date.now(); const expiresAt = now + this.ttlMs; this.tickets.set(digest(token), { token, sessionId: sessionId ?? null, createdAt: now, expiresAt, }); return { token, sessionId: sessionId ?? null, expiresAt, ticketId: digest(token).slice(0, 12) }; } /** * Consume a ticket exactly once. * @param {string} token ticket from the QR URL. * @returns {{ sessionId: string | null } | undefined} the bound Session, or undefined when invalid, expired or already used. */ consume(token) { if (typeof token !== 'string' || token.length < 16) return undefined; const key = digest(token); const ticket = this.tickets.get(key); if (ticket === undefined) return undefined; this.tickets.delete(key); if (ticket.expiresAt <= Date.now()) return undefined; return { sessionId: ticket.sessionId }; } /** * The tickets still valid, with their raw tokens, so a reconnected relay can * be told about them again. Never persisted. * @returns {Array<{ token: string, sessionId: string | null, expiresAt: number }>} active tickets. */ active() { this.prune(); return [...this.tickets.values()].map(({ token, sessionId, expiresAt }) => ({ token, sessionId, expiresAt })); } /** Drop expired tickets. */ prune() { const now = Date.now(); for (const [key, ticket] of this.tickets) if (ticket.expiresAt <= now) this.tickets.delete(key); } }