#!/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 `
${f}
${changes ? `${value(f, was)} → ` : ''}${value(f, home[f])}${then && !changes ? ' stays' : ''}
`; }) .join(''); const line = peerHome ? before ? `${esc(p.name)} is the home: say yes and your name, hue and role here follow it.` : `${esc(p.name)} is the home: your name, hue and role here follow it.` : before ? `${esc(store.name)} is the home: say yes and ${esc(p.name)}’s ${esc(other.name)} takes your name, hue and role.` : `${esc(store.name)} is the home: your name, hue and role in ${esc(p.name)} follow this app.`; return `

${line}

${rows}
`; } function storeLink(ownId, c) { // a link replaces any link either member had here (§5 step 3, §5.2) for (const [k, l] of store.links) if (k === ownId || l.peerId === c.member_id) store.links.delete(k); store.links.set(ownId, { peerId: c.member_id, peerName: c.name, peerHue: c.hue, peerRole: c.role, linkedAt: new Date(now()).toISOString() }); } function forget() { store.peer = null; store.links.clear(); store.nonces.clear(); store.intents.clear(); store.pending.clear(); } const apiRefuse = (reply, where, reason, extra = {}) => { refuse(where, reason); return reply.code(STATUS[reason]).send({ error: LINES[reason], reason, ...extra }); }; const bearer = (req) => /^HouseLink ([A-Za-z0-9_.-]+)$/.exec(req.headers.authorization ?? '')?.[1] ?? ''; // ---- the API (§2, §5.3, §8) --------------------------------------------------------------------------------------- app.get('/api/health', async () => ({ ok: true, name: store.name, contract: 1 })); app.post('/api/house-link/pair', async (req, reply) => { const b = req.body ?? {}; if (typeof b !== 'object' || typeof b.code !== 'string' || !normalizeOrigin(b.origin) || typeof b.name !== 'string' || !b.name || !Array.isArray(b.capabilities)) { return apiRefuse(reply, 'pair', 'bad_request'); } if (store.peer) return apiRefuse(reply, 'pair', 'already_paired'); if (b.contract !== 1) return apiRefuse(reply, 'pair', 'contract'); const code = b.code.toUpperCase().replace(/[\s-]+/g, '').replace(/[IL]/g, '1').replace(/O/g, '0'); const showing = store.code; if (!showing || showing.code !== code) { if (showing && ++showing.tries >= 5) store.code = null; return apiRefuse(reply, 'pair', 'bad_code'); } if (now() > showing.expiresAt) { store.code = null; return apiRefuse(reply, 'pair', 'expired_code'); } store.code = null; const key = randomBytes(32); store.peer = { origin: normalizeOrigin(b.origin), name: b.name.slice(0, 80), capabilities: b.capabilities.filter((x) => typeof x === 'string'), key, pairedAt: new Date(now()).toISOString(), selfOrigin: showing.origin }; return { contract: 1, key: key.toString('base64url'), origin: showing.origin, name: store.name, capabilities }; }); app.delete('/api/house-link/pair', async (req, reply) => { const r = check(bearer(req), 'unpair'); if (r.reason) return apiRefuse(reply, 'unpair', r.reason); forget(); return { ok: true }; }); app.delete('/api/house-link/link', async (req, reply) => { const r = check(bearer(req), 'unlink', linkFor); if (r.reason) return apiRefuse(reply, 'unlink', r.reason); store.links.delete(r.claims.sub); return { ok: true }; }); app.post('/api/house-link/games/install', async (req, reply) => { const body = Buffer.isBuffer(req.body) ? req.body : Buffer.alloc(0); const r = check(bearer(req), 'install', linkFor); const no = (status, code, reason) => { refuse('install', code); return reply.code(status).send({ installed: false, code, reason }); }; if (r.reason) return no(STATUS[r.reason], r.reason, LINES[r.reason]); const c = r.claims; if (createHash('sha256').update(body).digest('hex') !== c.sha256) return no(400, 'bad_body', LINES.bad_body); sync(c.sub, c); const member = store.members.get(c.sub); // this peer's own rule: a parent installs if (!member?.parent) return no(403, 'policy', `only a parent can install games in ${store.name} — ${member?.name ?? 'this member'} isn’t one here`); const manifest = readManifest(body); if (!manifest) return no(400, 'invalid', 'that zip has no manifest.json the contract can read'); store.installs.push({ id: manifest.id, version: manifest.version, by: c.sub, bytes: body.length, at: new Date(now()).toISOString() }); return { installed: true, id: manifest.id, version: manifest.version }; }); // the body's sha256 is over the bytes as sent, so this route keeps them (its own JSON parser) app.register(async (sub) => { sub.addContentTypeParser('application/json', { parseAs: 'buffer' }, (_req, body, done) => { try { done(null, { raw: body, json: JSON.parse(body.toString('utf8')) }); } catch { done(null, { raw: body, json: null }); } }); sub.post('/api/house-link/songs/make', async (req, reply) => { const r = check(bearer(req), 'songs', linkFor); const no = (status, code, reason) => { refuse('songs', code); return reply.code(status).send({ queued: 0, code, reason }); }; if (r.reason) return no(STATUS[r.reason], r.reason, LINES[r.reason]); if (createHash('sha256').update(req.body?.raw ?? Buffer.alloc(0)).digest('hex') !== r.claims.sha256) return no(400, 'bad_body', LINES.bad_body); const b = req.body.json; if (!b || typeof b.package !== 'string' || !Array.isArray(b.songs)) return no(400, 'bad_request', LINES.bad_request); sync(r.claims.sub, r.claims); store.songs.push({ package: b.package, n: b.songs.length, by: r.claims.sub }); return { queued: b.songs.length }; }); }); // ---- the browser's routes (§5, §6) --------------------------------------------------------------------------------- app.post('/house-link/link', async (req, reply) => { const r = check(req.body?.token, 'link'); if (r.reason) return refusalPage(reply, 'link', r.reason); const id = randomBytes(16).toString('base64url'); store.pending.set(id, r.claims); return reply.code(303).header('location', `/confirm/${id}`).send(); }); app.get('/confirm/:id', async (req, reply) => { const c = store.pending.get(req.params.id); if (!c || secs() > c.exp + SKEW) return refusalPage(reply, 'link', 'expired'); const s = signedIn(req); if (!s) return html(reply, 'Sign in to link', `

${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?', `

Link ${esc(store.peer.name)}’s ${esc(c.name)} to you?

${esc(c.name)} · ${esc(c.role)} in ${esc(store.peer.name)}. You are ${esc(s.member.name)} here.

${follows(c, s.member, true)}
`, ); }); app.post('/confirm/:id', async (req, reply) => { const c = store.pending.get(req.params.id); const s = signedIn(req); if (!s) return reply.code(303).header('location', `/confirm/${req.params.id}`).send(); store.pending.delete(req.params.id); if (!c || !store.peer || secs() > c.exp + SKEW) return refusalPage(reply, 'link', 'expired'); if (req.body?.answer !== 'yes') return reply.code(303).header('location', '/').send(); storeLink(s.member.id, c); sync(s.member.id, c); const { token } = mint('linked', { ...memberClaims(s.member), intent: c.nonce, for: c.member_id }); return autopost(reply, `${store.peer.origin}/house-link/linked`, token); }); app.post('/house-link/linked', async (req, reply) => { const r = check(req.body?.token, 'linked', (c) => { const i = store.intents.get(c.intent); return i && i.memberId === c.for && secs() <= i.exp + SKEW ? null : 'unknown_intent'; }); if (r.reason) return refusalPage(reply, 'linked', r.reason); const c = r.claims; store.intents.delete(c.intent); storeLink(c.for, c); sync(c.for, c); return reply.code(303).header('location', '/').send(); }); app.post('/house-link/assert', async (req, reply) => { const r = check(req.body?.token, 'assert', linkFor); if (r.reason === 'unknown_link') { refuse('assert', r.reason); return html(reply, 'Not linked here', `

Not linked here

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('/')}
`, 404); } if (r.reason) return refusalPage(reply, 'assert', r.reason); sync(r.claims.sub, r.claims); startSession(reply, r.claims.sub); return reply.code(303).header('location', '/').send(); }); // ---- this app's own pages ------------------------------------------------------------------------------------------ app.get('/', async (req, reply) => { const s = signedIn(req); if (!s) return html(reply, store.name, `

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 = `

${esc(m.name)} ${esc(m.role)}${m.parent ? ' · parent' : ''}

`; if (!p) 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 += `
`; let house = ''; if (m.parent) { house = `

House

`; if (p) { house += `

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 += `
`; if (store.installs.length) house += `

Installed over the link

${store.installs.map((i) => `

${esc(i.id)} ${esc(i.version)} · ${i.bytes.toLocaleString('en-US')} bytes · ${esc(i.at)}

`).join('')}
`; } return html(reply, store.name, `${flash ? `

${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 `
${[...store.members.values()] .map((m) => ``) .join('')}
`; } function refusalPage(reply, where, reason) { refuse(where, reason); return html(reply, 'Refused', `

${esc(LINES[reason])}

${esc(reason)}

${esc(store.name)}

`, 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(`${esc(title)} · ${esc(store.name)}
${esc(store.name)} house-link reference peer · contract 1
${body}
`); } return { app, store, async listen(port = 8397, host = '0.0.0.0') { await app.listen({ port, host }); return app; }, close: () => app.close(), }; } /** The manifest of a zip, by its central directory (stored or deflated), or null. */ function readManifest(zip) { try { let eocd = -1; for (let i = zip.length - 22; i >= Math.max(0, zip.length - 65557); i--) if (zip.readUInt32LE(i) === 0x06054b50) { eocd = i; break; } if (eocd < 0) return null; let p = zip.readUInt32LE(eocd + 16); const n = zip.readUInt16LE(eocd + 10); for (let k = 0; k < n; k++) { if (zip.readUInt32LE(p) !== 0x02014b50) return null; const method = zip.readUInt16LE(p + 10); const size = zip.readUInt32LE(p + 20); const nameLen = zip.readUInt16LE(p + 28); const extra = zip.readUInt16LE(p + 30); const comment = zip.readUInt16LE(p + 32); const local = zip.readUInt32LE(p + 42); const name = zip.subarray(p + 46, p + 46 + nameLen).toString('utf8'); if (name === 'manifest.json') { const start = local + 30 + zip.readUInt16LE(local + 26) + zip.readUInt16LE(local + 28); const data = zip.subarray(start, start + size); const m = JSON.parse((method === 8 ? inflateRawSync(data) : data).toString('utf8')); return typeof m.id === 'string' && typeof m.version === 'string' ? { id: m.id, version: m.version } : null; } p += 46 + nameLen + extra + comment; } } catch { return null; } return null; } const CSS = ` :root{color-scheme:light dark;--bg:#f6f5f1;--bg2:#ffffff;--fg:#1c1f28;--dim:#5d6270;--line:#dcd9d0;--acc:#0f7b6c;--l:54%;--c:0.16} @media (prefers-color-scheme:dark){:root{--bg:#0e0f13;--bg2:#16181e;--fg:#e6e3dc;--dim:#8a90a0;--line:#262a33;--acc:#4fd1b5;--l:76%;--c:0.15}} *{box-sizing:border-box}body{margin:0;background:var(--bg);color:var(--fg);font:15px/1.5 system-ui,sans-serif} header{padding:12px 16px;border-bottom:1px solid var(--line)}header small,small{color:var(--dim);font-weight:400} main{max-width:560px;margin:0 auto;padding:16px;display:flex;flex-direction:column;gap:14px} .card{background:var(--bg2);border:1px solid var(--line);border-radius:12px;padding:14px 16px} h2{font-size:17px;font-weight:500;margin:0 0 6px;display:flex;align-items:center;gap:8px;flex-wrap:wrap} .help{color:var(--dim);font-size:13px;margin:4px 0}.mono{font-family:ui-monospace,monospace} .code{font-size:30px;letter-spacing:.12em;margin:6px 0} .sw{display:inline-block;width:12px;height:12px;border-radius:50%;background:oklch(var(--l) var(--c) var(--h));margin-right:6px;vertical-align:-1px} button{font:inherit;padding:8px 14px;border-radius:9px;border:1px solid var(--line);background:var(--bg2);color:var(--fg);cursor:pointer;text-align:left} button.primary{background:var(--acc);border-color:var(--acc);color:var(--bg)}button.sm{padding:4px 10px;font-size:13px} input{font:inherit;padding:8px 10px;border-radius:8px;border:1px solid var(--line);background:var(--bg);color:var(--fg);width:100%} label{display:flex;flex-direction:column;gap:4px;font-size:13px;color:var(--dim)} .row{display:flex;gap:8px;flex-wrap:wrap}.col{display:flex;flex-direction:column;gap:8px;margin-top:8px} .chip{display:inline-block;border:1px solid var(--line);border-radius:999px;padding:0 8px;font-size:12px} .flash{background:var(--bg2);border-left:3px solid var(--acc);padding:8px 12px;margin:0} .follows{display:grid;grid-template-columns:auto 1fr;gap:4px 12px;margin:6px 0;padding-left:10px;border-left:2px solid var(--acc)} .follows dt{color:var(--dim);font-size:13px}.follows dd{margin:0} `; // ---- run it ----------------------------------------------------------------------------------------------------------- if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) { const args = process.argv.slice(2); const opt = (name) => (args.includes(name) ? args[args.indexOf(name) + 1] : undefined); const port = Number(opt('--port') ?? 8397); const peer = createPeer({ name: opt('--name'), origin: opt('--origin'), home: !args.includes('--not-home'), log: args.includes('--log') }); await peer.listen(port); console.log(`house-link reference peer "${peer.store.name}" on :${port} (contract 1; ${peer.store.capabilities.join(', ')})`); const stop = () => peer.close().finally(() => process.exit(0)); process.on('SIGINT', stop); process.on('SIGTERM', stop); }