#!/usr/bin/env node // The house-link reference peer (LINK.md §12): both roles of contract 1, written from LINK.md alone, in memory, with a // tiny sign-in (pick a member). For checking an implementation — never for a house to run. // // node spec/house-link/reference-peer.mjs [--port 8397] [--name "Reference peer"] [--origin http://peer.home.arpa:8397] // [--not-home] [--log] // // Node 22 and Fastify 5, nothing else. `createPeer(options)` is the same app for a test: it returns {app, store, listen, // close}, and `store` is the whole state. import Fastify from 'fastify'; import { createHash, createHmac, randomBytes, timingSafeEqual } from 'node:crypto'; import { inflateRawSync } from 'node:zlib'; import { pathToFileURL } from 'node:url'; // --------------------------------------------------------------------------------------------------------------------- // §3: canonical JSON, signing, checking export function canonical(v) { if (v === null || typeof v === 'boolean' || typeof v === 'string') return JSON.stringify(v); if (typeof v === 'number') { if (!Number.isSafeInteger(v)) throw new Error('integers only'); return String(v); } if (Array.isArray(v)) return '[' + v.map(canonical).join(',') + ']'; if (typeof v === 'object') { const keys = Object.keys(v).filter((k) => v[k] !== undefined).sort(); return '{' + keys.map((k) => JSON.stringify(k) + ':' + canonical(v[k])).join(',') + '}'; } throw new Error('not JSON'); } const hmac = (key, bytes) => createHmac('sha256', key).update(bytes).digest(); export const sign = (claims, key) => { const bytes = Buffer.from(canonical(claims), 'utf8'); return bytes.toString('base64url') + '.' + hmac(key, bytes).toString('base64url'); }; const nonce = () => randomBytes(16).toString('base64url'); const LIFETIME = { link: 300, linked: 300, assert: 60, install: 60, songs: 60, unlink: 60, unpair: 60 }; const SKEW = 30; const MEMBER = ['member_id', 'name', 'hue', 'role']; const NEEDS = { link: MEMBER, linked: [...MEMBER, 'intent', 'for'], assert: [...MEMBER, 'sub'], install: [...MEMBER, 'sub', 'sha256'], songs: [...MEMBER, 'sub', 'sha256'], unlink: ['member_id', 'sub'], unpair: [], }; /** §9's plain lines. */ export const LINES = { bad_request: 'the request isn’t one the house-link text describes', contract: 'the other app speaks another contract', already_paired: 'already paired — unpair first', bad_code: 'that code isn’t the one showing', expired_code: 'that code has expired — show a new one', malformed: 'that isn’t a house-link token', not_paired: 'this app isn’t paired', bad_signature: 'the signature doesn’t hold', wrong_type: 'that token is for another step', wrong_issuer: 'that token comes from another app', wrong_audience: 'that token is for another app', too_long: 'that token lasts longer than this step allows', skewed: 'that token is from the future — check both clocks', expired: 'that token has expired — try again', replayed: 'that token was already used', unknown_link: 'not linked here', unknown_intent: 'that link wasn’t asked for here, or it has expired', bad_body: 'the body isn’t the one the token signed', }; const STATUS = { bad_request: 400, contract: 400, already_paired: 409, bad_code: 403, expired_code: 403, malformed: 400, not_paired: 409, bad_signature: 403, wrong_type: 400, wrong_issuer: 403, wrong_audience: 403, too_long: 403, skewed: 403, expired: 403, replayed: 403, unknown_link: 404, unknown_intent: 404, bad_body: 400 }; function claimsOk(c) { // lengths in code points (§4) const str = (v, max = 512) => typeof v === 'string' && v.length > 0 && [...v].length <= max; const int = (v) => Number.isSafeInteger(v); const origin = (v) => str(v) && /^https?:\/\/[^/\s]+$/.test(v); const nonceOk = (v) => typeof v === 'string' && /^[A-Za-z0-9_-]{22}$/.test(v); if (!(c.typ in NEEDS) || !origin(c.iss) || !origin(c.aud) || !int(c.iat) || !int(c.exp) || !nonceOk(c.nonce)) return false; return NEEDS[c.typ].every((k) => { const v = c[k]; if (k === 'hue') return int(v) && v >= 0 && v <= 359; if (k === 'role') return v === 'adult' || v === 'minor'; if (k === 'name') return str(v, 80); if (k === 'sha256') return typeof v === 'string' && /^[0-9a-f]{64}$/.test(v); if (k === 'intent') return nonceOk(v); return str(v, 64); }); } // --------------------------------------------------------------------------------------------------------------------- // The app const CODE_ALPHABET = '0123456789ABCDEFGHJKMNPQRSTVWXYZ'; const esc = (s) => String(s).replace(/[&<>"']/g, (ch) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[ch]); const roleOf = (m) => m.role; export function normalizeOrigin(input) { const s = String(input ?? '').trim().replace(/\/+$/, ''); if (!/^https?:\/\//i.test(s)) return null; try { const u = new URL(s); if (u.pathname !== '/' || u.search || u.hash || u.username || u.password) return null; return u.origin; } catch { return null; } } const DEFAULT_MEMBERS = [ { id: 'p-mika', name: 'Mika', hue: 150, role: 'adult', parent: true }, { id: 'p-tomo', name: 'Tomo', hue: 260, role: 'adult', parent: false }, { id: 'p-noa', name: 'Noa', hue: 40, role: 'minor', parent: false }, ]; /** * options: {name, origin, home (default true), members, now (ms), log} */ export function createPeer(options = {}) { const now = options.now ?? Date.now; const capabilities = [...(options.home === false ? [] : ['home']), 'games.install', 'songs.make']; const store = { name: options.name ?? 'Reference peer', capabilities, /** the origin set on the command line, else each request's */ origin: options.origin ? normalizeOrigin(options.origin) : null, members: new Map((options.members ?? DEFAULT_MEMBERS).map((m) => [m.id, { ...m }])), /** {origin, name, capabilities, key, pairedAt, selfOrigin} */ peer: null, /** {code, origin, expiresAt, tries} */ code: null, /** own member id → {peerId, peerName, peerHue, peerRole, linkedAt} */ links: new Map(), /** nonce → exp, every nonce accepted */ nonces: new Map(), /** the link tokens this app signed: nonce → {memberId, exp} */ intents: new Map(), /** checked link tokens waiting for a yes: id → claims */ pending: new Map(), sessions: new Map(), /** session id → a line to show once */ flash: new Map(), installs: [], songs: [], refusals: [], }; const secs = () => Math.floor(now() / 1000); const app = Fastify({ logger: options.log ? { level: 'info' } : false, bodyLimit: 64 * 1024 }); app.addContentTypeParser('application/x-www-form-urlencoded', { parseAs: 'string' }, (_req, body, done) => done(null, Object.fromEntries(new URLSearchParams(body))), ); app.addContentTypeParser('application/zip', { parseAs: 'buffer', bodyLimit: 12 * 1024 * 1024 }, (_req, body, done) => done(null, body)); const selfOrigin = (req) => store.origin ?? `${req.protocol}://${req.headers.host}`; const cookie = (req) => /(?:^|;\s*)peer_session=([A-Za-z0-9_-]+)/.exec(req.headers.cookie ?? '')?.[1] ?? null; const signedIn = (req) => { const sid = cookie(req); const id = sid ? store.sessions.get(sid) : null; return id ? { sid, member: store.members.get(id) } : null; }; const startSession = (reply, memberId) => { const sid = randomBytes(16).toString('base64url'); store.sessions.set(sid, memberId); reply.header('set-cookie', `peer_session=${sid}; Path=/; HttpOnly; SameSite=Lax`); return sid; }; const say = (req, line) => { const s = signedIn(req); if (s) store.flash.set(s.sid, line); }; const refuse = (where, reason) => { // a refusal is a line in the log, never the token (§3.3) store.refusals.push({ where, reason }); app.log.warn({ where, reason }, 'house-link: refused'); }; const memberClaims = (m) => ({ member_id: m.id, name: m.name, hue: m.hue, role: roleOf(m) }); const mint = (typ, rest) => { const iat = secs(); const claims = { ...rest, typ, iss: store.peer.selfOrigin, aud: store.peer.origin, iat, exp: iat + LIFETIME[typ], nonce: nonce() }; return { claims, token: sign(claims, store.peer.key) }; }; /** §3.3, steps 1–8; `step8(claims)` returns a reason or null. */ function check(token, typ, step8) { const parts = typeof token === 'string' ? token.split('.') : []; if (parts.length !== 2 || !/^[A-Za-z0-9_-]+$/.test(parts[0]) || !/^[A-Za-z0-9_-]+$/.test(parts[1])) return { reason: 'malformed' }; const bytes = Buffer.from(parts[0], 'base64url'); const mac = Buffer.from(parts[1], 'base64url'); if (mac.length !== 32 || !bytes.length) return { reason: 'malformed' }; if (!store.peer) return { reason: 'not_paired' }; if (!timingSafeEqual(hmac(store.peer.key, bytes), mac)) return { reason: 'bad_signature' }; let c; try { c = JSON.parse(bytes.toString('utf8')); if (!c || typeof c !== 'object' || Array.isArray(c) || canonical(c) !== bytes.toString('utf8') || !claimsOk(c)) return { reason: 'malformed' }; } catch { return { reason: 'malformed' }; } if (c.typ !== typ) return { reason: 'wrong_type' }; if (c.iss !== store.peer.origin) return { reason: 'wrong_issuer' }; if (c.aud !== store.peer.selfOrigin) return { reason: 'wrong_audience' }; const t = secs(); if (c.exp <= c.iat || c.exp - c.iat > LIFETIME[typ]) return { reason: 'too_long' }; if (c.iat > t + SKEW) return { reason: 'skewed' }; if (t > c.exp + SKEW) return { reason: 'expired' }; for (const [n, exp] of store.nonces) if (t > exp + SKEW) store.nonces.delete(n); if (store.nonces.has(c.nonce)) return { reason: 'replayed' }; store.nonces.set(c.nonce, c.exp); const r = step8 ? step8(c) : null; return r ? { reason: r } : { claims: c }; } const linkFor = (c) => { const l = store.links.get(c.sub); return l && l.peerId === c.member_id ? null : 'unknown_link'; }; /** §7: the link's copy of the peer member always; our member only when the peer is home and we are not. */ function sync(ownId, c) { const l = store.links.get(ownId); if (l) Object.assign(l, { peerName: c.name, peerHue: c.hue, peerRole: c.role }); const peerHome = store.peer.capabilities.includes('home'); if (peerHome && !capabilities.includes('home')) { const m = store.members.get(ownId); if (m) Object.assign(m, { name: c.name, hue: c.hue, role: c.role }); } } /** * §5 step 2: what follows the home, shown before yes (`before`) and kept on the member's page after. `other` is the * other app's member (a token's claims, or the link's copy), `m` this app's. The home's name, hue and role are the ones * that hold; the other side's become them. */ function follows(other, m, before) { const p = store.peer; const peerHome = p.capabilities.includes('home') && !capabilities.includes('home'); const ownHome = capabilities.includes('home') && !p.capabilities.includes('home'); if (!peerHome && !ownHome) return `
Neither app is the home: names, hues and roles stay as they are in each.
`; const home = peerHome ? other : { name: m.name, hue: m.hue, role: roleOf(m) }; const then = before ? (peerHome ? { name: m.name, hue: m.hue, role: roleOf(m) } : other) : null; const value = (f, v) => (f === 'hue' ? `${v}` : esc(v)); const rows = ['name', 'hue', 'role'] .map((f) => { const was = then?.[f]; const changes = then && was !== home[f]; return `${line}
${esc(store.peer.name)} asks to link one of its members to you. Sign in first.
${signInForm(`/confirm/${req.params.id}`)}`); return html( reply, 'Link?', `${esc(c.name)} · ${esc(c.role)} in ${esc(store.peer.name)}. You are ${esc(s.member.name)} here.
${follows(c, s.member, true)}That member of ${esc(store.peer?.name ?? 'the other app')} isn’t linked to anyone in ${esc(store.name)}. Sign in here and link from your page.
${signInForm('/')}The house-link reference peer (contract 1). Pick a member to sign in.
${signInForm('/')}`); const flash = store.flash.get(s.sid); store.flash.delete(s.sid); const m = s.member; const link = store.links.get(m.id); const p = store.peer; let me = `Not paired: a parent pairs below.
`; else if (!link) me += `Opens ${esc(p.name)} in a new tab to confirm there.
`; else me += `Linked to ${esc(link.peerName)} · ${esc(link.peerRole)} in ${esc(p.name)} since ${esc(link.linkedAt.slice(0, 10))}
${follows({ name: link.peerName, hue: link.peerHue, role: link.peerRole }, m, false)} `; me += `Paired with ${esc(p.name)} · ${esc(p.origin)} since ${esc(p.pairedAt.slice(0, 10))}
Its capabilities: ${p.capabilities.map((x) => `${esc(x)}`).join(' ') || 'none'} · ours: ${capabilities.map((x) => `${esc(x)}`).join(' ')}
`; } else if (store.code && now() <= store.code.expiresAt) { const c = store.code.code; house += `${c.slice(0, 4)} ${c.slice(4)}
Enter it in the other app with this address: ${esc(store.code.origin)}. Good for 10 minutes, once.
`; } else { house += ` `; } house += `${esc(i.id)} ${esc(i.version)} · ${i.bytes.toLocaleString('en-US')} bytes · ${esc(i.at)}
`).join('')}${esc(flash)}
` : ''}${me}${house}`); }); app.post('/signin', async (req, reply) => { const id = req.body?.member; const next = typeof req.body?.next === 'string' && req.body.next.startsWith('/') && !req.body.next.startsWith('//') ? req.body.next : '/'; if (!store.members.has(id)) return reply.code(303).header('location', '/').send(); startSession(reply, id); return reply.code(303).header('location', next).send(); }); app.post('/signout', async (req, reply) => { const sid = cookie(req); if (sid) store.sessions.delete(sid); return reply.code(303).header('location', '/').send(); }); const parent = (req) => { const s = signedIn(req); return s?.member.parent ? s : null; }; const home = (reply) => reply.code(303).header('location', '/').send(); app.post('/house/code', async (req, reply) => { if (parent(req) && !store.peer) { const bytes = randomBytes(8); store.code = { code: [...bytes].map((b) => CODE_ALPHABET[b & 31]).join(''), origin: selfOrigin(req), expiresAt: now() + 10 * 60 * 1000, tries: 0 }; } return home(reply); }); app.post('/house/code/cancel', async (req, reply) => { if (parent(req)) store.code = null; return home(reply); }); app.post('/house/pair', async (req, reply) => { if (!parent(req)) return home(reply); const origin = normalizeOrigin(req.body?.origin); if (!origin || store.peer) { say(req, store.peer ? LINES.already_paired : 'that isn’t an address like http://sumi.home.arpa:8395'); return reply.code(303).header('location', '/').send(); } const own = selfOrigin(req); try { const res = await fetch(`${origin}/api/house-link/pair`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ contract: 1, code: String(req.body?.code ?? ''), origin: own, name: store.name, capabilities }), signal: AbortSignal.timeout(10_000), }); const a = await res.json().catch(() => ({})); if (!res.ok) { say(req, `${origin} refused: ${a.error ?? res.status}`); } else { const key = /^[A-Za-z0-9_-]{43}$/.test(a.key ?? '') ? Buffer.from(a.key, 'base64url') : null; if (a.contract !== 1 || normalizeOrigin(a.origin) !== origin || !key || key.length !== 32) say(req, `${origin} answered with something this text doesn’t describe — its admin should unpair`); else { store.peer = { origin, name: String(a.name).slice(0, 80), capabilities: Array.isArray(a.capabilities) ? a.capabilities : [], key, pairedAt: new Date(now()).toISOString(), selfOrigin: own }; say(req, `paired with ${store.peer.name}`); } } } catch { say(req, `${origin} didn’t answer`); } return reply.code(303).header('location', '/').send(); }); app.post('/house/unpair', async (req, reply) => { if (!parent(req)) return home(reply); if (store.peer) { const { token } = mint('unpair', {}); await notify('DELETE', `${store.peer.origin}/api/house-link/pair`, token); forget(); say(req, 'unpaired'); } return reply.code(303).header('location', '/').send(); }); const me = (req) => { const s = signedIn(req); return s && store.peer ? s : null; }; app.post('/me/link', async (req, reply) => { const s = me(req); if (!s) return home(reply); const { token, claims } = mint('link', memberClaims(s.member)); store.intents.set(claims.nonce, { memberId: s.member.id, exp: claims.exp }); return autopost(reply, `${store.peer.origin}/house-link/link`, token); }); app.post('/me/open', async (req, reply) => { const s = me(req); if (!s) return home(reply); const link = store.links.get(s.member.id); if (!link) return home(reply); const { token } = mint('assert', { ...memberClaims(s.member), sub: link.peerId }); return autopost(reply, `${store.peer.origin}/house-link/assert`, token); }); app.post('/me/unlink', async (req, reply) => { const s = me(req); if (!s) return home(reply); const link = store.links.get(s.member.id); if (link) { store.links.delete(s.member.id); const { token } = mint('unlink', { member_id: s.member.id, sub: link.peerId }); await notify('DELETE', `${store.peer.origin}/api/house-link/link`, token); say(req, 'unlinked'); } return reply.code(303).header('location', '/').send(); }); async function notify(method, url, token) { try { await fetch(url, { method, headers: { authorization: `HouseLink ${token}` }, signal: AbortSignal.timeout(10_000) }); } catch { // best effort (§2.3, §5.3): this side is gone whatever the answer } } // ---- pages ---------------------------------------------------------------------------------------------------------- function signInForm(next) { return ``; } function refusalPage(reply, where, reason) { refuse(where, reason); return html(reply, 'Refused', ``, STATUS[reason]); } /** A page that posts the token on, in its body (§6: never in a URL). */ function autopost(reply, action, token) { return html( reply, 'Continue', ``, ); } function html(reply, title, body, status = 200) { return reply .code(status) .header('content-type', 'text/html; charset=utf-8') .header('cache-control', 'no-store') .header('referrer-policy', 'no-referrer') .send(`