Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
test(home): cover the store, the roles, the privacy window and the runtime
nirholasc3132956ad76
diff --git a/packages/home-mcp/test/registration.test.mjs b/packages/home-mcp/test/registration.test.mjsnew file mode 100644index 000000000..fc0ccbd16--- /dev/null+++ b/packages/home-mcp/test/registration.test.mjs@@ -0,0 +1,85 @@+// Tool-surface invariants for @three-ws/home-mcp.+//+// Importing src/index.js is side-effect-free: the stdio transport only connects+// when the file is the process entry point, and buildServer() needs no house.+// These tests run offline and never open a socket.+//+// Run: node --test packages/home-mcp/test/registration.test.mjs++import { test } from 'node:test';+import assert from 'node:assert/strict';++import { TOOLS, INSTRUCTIONS, buildServer } from '../src/index.js';++const EXPECTED = {+ home_overview: { write: false },+ list_entities: { write: false },+ list_macros: { write: false },+ call_service: { write: true },+ run_macro: { write: true },+};++test('exactly the expected tools are registered', () => {+ assert.equal(TOOLS.length, Object.keys(EXPECTED).length);+ assert.deepEqual(new Set(TOOLS.map((t) => t.name)), new Set(Object.keys(EXPECTED)));+});++test('every tool has a title, description, input schema and complete annotations', () => {+ for (const tool of TOOLS) {+ assert.equal(typeof tool.title, 'string', `${tool.name} is missing a title`);+ assert.ok(tool.title.length > 0, `${tool.name} has an empty title`);+ assert.equal(typeof tool.description, 'string', `${tool.name} is missing a description`);+ assert.ok(tool.description.length > 0, `${tool.name} has an empty description`);+ assert.ok(tool.inputSchema && typeof tool.inputSchema === 'object', `${tool.name} is missing inputSchema`);+ assert.equal(typeof tool.handler, 'function', `${tool.name} is missing a handler`);+ assert.ok(tool.annotations, `${tool.name} is missing MCP ToolAnnotations`);+ assert.equal(typeof tool.annotations.readOnlyHint, 'boolean', `${tool.name} must set readOnlyHint`);+ assert.equal(typeof tool.annotations.idempotentHint, 'boolean', `${tool.name} must set idempotentHint`);+ assert.equal(typeof tool.annotations.openWorldHint, 'boolean', `${tool.name} must set openWorldHint`);+ }+});++test('the read tools are marked read-only and the write tools are not', () => {+ for (const tool of TOOLS) {+ const expected = EXPECTED[tool.name];+ assert.equal(tool.annotations.readOnlyHint, !expected.write, `${tool.name} readOnlyHint is wrong`);+ assert.equal(tool.annotations.openWorldHint, true, `${tool.name} talks to a live house`);+ if (expected.write) {+ assert.equal(tool.annotations.destructiveHint, true, `${tool.name} moves a physical object`);+ } else {+ // The spec ignores destructiveHint when readOnlyHint is true.+ assert.equal(tool.annotations.destructiveHint, undefined, `${tool.name} is read-only`);+ }+ }+});++test('no tool takes a confirmation argument, on any transport', () => {+ // The gate decision in src/lib/gate.js: `confirmed: true` is a human saying+ // yes, and this transport has no human in it. A schema that accepted one+ // would be model output wearing a person's clothes.+ for (const tool of TOOLS) {+ for (const key of Object.keys(tool.inputSchema)) {+ assert.ok(+ !/^confirm/i.test(key),+ `${tool.name} must not expose a confirmation argument, and exposes "${key}"`,+ );+ }+ }+});++test('the server instructions state the gate, so a client cannot claim it was not told', () => {+ assert.match(INSTRUCTIONS, /refused/i);+ assert.match(INSTRUCTIONS, /no argument overrides/i);+ assert.match(INSTRUCTIONS, /untrusted data/i);+});++test('buildServer registers every tool with its annotations, without a house', () => {+ const server = buildServer();+ const registered = server._registeredTools;+ assert.ok(registered, 'McpServer should expose its tool registry');+ for (const tool of TOOLS) {+ const entry = registered[tool.name];+ assert.ok(entry, `${tool.name} not registered on the server`);+ assert.deepEqual(entry.annotations, tool.annotations, `${tool.name} annotations must survive registration`);+ }+});diff --git a/scripts/audit-home-credential-health.mjs b/scripts/audit-home-credential-health.mjsnew file mode 100755index 000000000..6bb91b258--- /dev/null+++ b/scripts/audit-home-credential-health.mjs@@ -0,0 +1,133 @@+#!/usr/bin/env node+// Can we still open the homes people connected?+//+// `home_connections.access_token_enc` is the platform's SECOND class of at-rest+// ciphertext under WALLET_ENCRYPTION_KEY, alongside the custodial wallet secrets+// that scripts/audit-custodial-key-health.mjs measures. A key rotation that loses+// the outgoing value seals both, and the two failures look nothing alike:+//+// * a sealed wallet destroys custody. The SOL stays visible on chain and can+// never be signed for again (docs/ops/wallet-key-migration.md).+// * a sealed home token destroys REACH. No money is lost and nothing is+// unrecoverable: the house is simply unreachable until its owner pastes a+// fresh long-lived token. The cost is every connected home going dark at+// once, with no signal anywhere that says why.+//+// That second failure has no on-chain balance to notice it by, which is exactly+// why it needs its own reading. Run this alongside the wallet audit on every+// rotation (step 3 of the runbook).+//+// Read-only: it decrypts in memory to test the key and writes nothing.+//+// node scripts/audit-home-credential-health.mjs+// node scripts/audit-home-credential-health.mjs --json+//+// Env: DATABASE_URL, plus a decryption key (WALLET_ENCRYPTION_KEY, or a retired+// one in WALLET_ENCRYPTION_KEY_PREVIOUS). Reads .env.local then .env.+// Exit codes: 2 no DATABASE_URL, 3 no decryption key at all, 1 something sealed.++import { readFileSync } from 'node:fs';+import path from 'node:path';+import { fileURLToPath } from 'node:url';++const HERE = path.dirname(fileURLToPath(import.meta.url));+const ROOT = path.resolve(HERE, '..');++for (const file of ['.env.local', '.env']) {+ try {+ for (const line of readFileSync(path.join(ROOT, file), 'utf8').split('\n')) {+ const m = line.match(/^([A-Z_][A-Z0-9_]*)=(.*)$/);+ if (!m || process.env[m[1]]) continue;+ let value = m[2].trim();+ if ((value.startsWith('"') && value.endsWith('"')) || (value.startsWith("'") && value.endsWith("'"))) {+ value = value.slice(1, -1);+ }+ process.env[m[1]] = value;+ }+ } catch { /* not present */ }+}++const json = process.argv.includes('--json');++if (!process.env.DATABASE_URL) {+ console.error('DATABASE_URL is not set. Add it to .env.local or export it.');+ process.exit(2);+}++const { decryptSecret, secretBoxKeyCandidates } = await import('../api/_lib/secret-box.js');+const { sql } = await import('../api/_lib/db.js');++// The same guard the custodial audit learned to carry: a run with no key at all+// reports 100% sealed and means nothing. Say so instead of printing a verdict.+const keyCount = secretBoxKeyCandidates().length;+if (keyCount === 0) {+ console.error('No decryption key is configured, so every home would report as sealed regardless of');+ console.error('production state. Set WALLET_ENCRYPTION_KEY (Cloud Run service three-ws-api holds it:');+ console.error(" node scripts/read-service-env.mjs '^WALLET_ENCRYPTION_KEY$' --raw");+ process.exit(3);+}++const rows = await sql`+ select id, user_id, label, base_url, status, last_ok_at, access_token_enc+ from home_connections+ where revoked_at is null+ order by created_at asc+`;++const sealed = [];+let readable = 0;+for (const row of rows) {+ // A revoked home is filtered above; an empty ciphertext on a LIVE row would be+ // a bug in revokeConnection, so it counts as sealed rather than as fine.+ if (!row.access_token_enc) {+ sealed.push({ id: row.id, label: row.label, base_url: row.base_url, reason: 'empty ciphertext on a live row' });+ continue;+ }+ try {+ const plain = await decryptSecret(row.access_token_enc);+ if (plain) readable++;+ else sealed.push({ id: row.id, label: row.label, base_url: row.base_url, reason: 'decrypted to nothing' });+ } catch (err) {+ sealed.push({ id: row.id, label: row.label, base_url: row.base_url, reason: err?.message || 'decrypt failed' });+ }+}++const report = {+ homes: rows.length,+ readable,+ sealed: sealed.length,+ key_candidates: keyCount,+ // Never the token, never a prefix of it: this report is safe to paste.+ sealed_homes: sealed.slice(0, 20),+ measured_at: new Date().toISOString(),+};++if (json) {+ console.log(JSON.stringify(report, null, 2));+} else {+ console.log('Home credential health');+ console.log(` live homes ${report.homes}`);+ console.log(` openable ${report.readable}`);+ console.log(` sealed ${report.sealed}`);+ console.log(` keys tried ${report.key_candidates}`);+ for (const home of report.sealed_homes) {+ console.log(` ${home.base_url} "${home.label}" ${home.reason}`);+ }+ // "Every home is sealed" only means a wrong key when the failures are DECRYPT+ // failures. A live row with an empty ciphertext is a revoke bug, and telling an+ // operator to go hunt a retired key over one of those wastes the incident.+ const allDecryptFailures = sealed.length > 0 && sealed.every((h) => !h.reason.startsWith('empty ciphertext'));+ if (report.sealed === report.homes && allDecryptFailures) {+ console.log('');+ console.log('EVERY home is sealed. That is one wrong key for this deployment, not a fleet of');+ console.log('separately broken homes. Put the outgoing key in WALLET_ENCRYPTION_KEY_PREVIOUS');+ console.log('before concluding anything (docs/ops/wallet-key-migration.md).');+ } else if (report.sealed > 0) {+ console.log('');+ console.log('Sealed homes stay listed in the product and fail on connect. Nothing is lost:');+ console.log('their owners reconnect with a fresh long-lived token. Tell them, do not wait for');+ console.log('them to notice their lights stopped answering.');+ }+}++process.exit(report.sealed > 0 ? 1 : 0);diff --git a/scripts/home-load.mjs b/scripts/home-load.mjsnew file mode 100644index 000000000..cde5714ed--- /dev/null+++ b/scripts/home-load.mjs@@ -0,0 +1,666 @@+#!/usr/bin/env node+/**+ * The Home lane's load harness.+ *+ * Everything in docs/home-operations.md is a number this script printed. It+ * opens real WebSocket connections, with real long-lived access tokens, to real+ * Home Assistant containers started by scripts/home-fleet.mjs, and it measures+ * what they cost this process.+ *+ * It will only ever talk to the fleet manifest's containers, which live on+ * 127.0.0.1. Never point a load harness at somebody's house.+ *+ * node scripts/home-fleet.mjs up --homes 12 --big 1+ * node --expose-gc scripts/home-load.mjs all --out tasks/home/envelope-2026-09-03.json+ *+ * Individual measurements, all of which `all` runs:+ *+ * coldstart process start to first connected home, on a cold process+ * connections heap, RSS, file descriptors and action p95 at a connection count+ * burst CPU absorbed by a 100-entity update burst, and the coalescing+ * sse the cost of one SSE subscriber, separated from the connection+ * gate under saturation, a guarded action still demands a human+ */++import { readdirSync } from 'node:fs';+import { mkdir, writeFile } from 'node:fs/promises';+import { createServer } from 'node:http';+import os from 'node:os';+import path from 'node:path';+import process from 'node:process';+import { fileURLToPath } from 'node:url';++import { createAdmissionController, requiresConfirmation } from '../api/_lib/home/admission.js';+import { HomeBridge } from '../packages/home-bridge/src/index.js';+import { classifyCall } from '../packages/home-bridge/src/safety.js';+import { readFleet } from './home-fleet.mjs';++const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');+const sleep = (ms) => new Promise((r) => setTimeout(r, ms));++// ---------------------------------------------------------------- instruments++/**+ * A heap reading that means something.+ *+ * Without a forced collection this measures garbage as readily as it measures+ * connections, and the answer moves by tens of megabytes between runs. The+ * script refuses to report a heap number at all if it was started without+ * --expose-gc, because a number nobody can reproduce is worse than no number.+ */+function heapNow() {+ if (typeof global.gc !== 'function') {+ throw new Error('run this with --expose-gc, or the heap numbers are noise: node --expose-gc scripts/home-load.mjs ...');+ }+ global.gc();+ global.gc();+ const mem = process.memoryUsage();+ return { heapUsed: mem.heapUsed, rss: mem.rss, external: mem.external, arrayBuffers: mem.arrayBuffers };+}++/** Open file descriptors held by this process, which is where sockets show up. */+function fdCount() {+ try {+ return readdirSync('/proc/self/fd').length;+ } catch {+ return null;+ }+}++function percentile(sorted, p) {+ if (!sorted.length) return null;+ const index = Math.min(sorted.length - 1, Math.ceil((p / 100) * sorted.length) - 1);+ return sorted[Math.max(0, index)];+}++function summarize(samples) {+ const sorted = [...samples].sort((a, b) => a - b);+ return {+ n: sorted.length,+ min: sorted[0] ?? null,+ p50: percentile(sorted, 50),+ p95: percentile(sorted, 95),+ p99: percentile(sorted, 99),+ max: sorted[sorted.length - 1] ?? null,+ mean: sorted.length ? Number((sorted.reduce((a, b) => a + b, 0) / sorted.length).toFixed(2)) : null,+ };+}++const bytesPer = (delta, n) => (n ? Math.round(delta / n) : null);++// ---------------------------------------------------------------- fleet helpers++function pickHouses(fleet, { big = false } = {}) {+ const houses = fleet.houses.filter((h) => Boolean(h.big) === big);+ if (!houses.length) throw new Error(`the fleet has no ${big ? 'large' : 'small'} house. Re-run home-fleet.mjs up with --big 1.`);+ return houses;+}++/**+ * Open `count` bridges spread round robin across `houses`.+ *+ * Round robin rather than one-house-per-connection because the thing being+ * measured is what a connection costs THIS process. Which container answers is+ * the fixture; how many sockets, states maps and room graphs we hold is the+ * product. Where a measurement does depend on the far side (action latency,+ * chaos isolation) the script says so.+ */+async function openBridges(houses, count, { onOpen } = {}) {+ const bridges = [];+ const failures = [];+ // A storm of simultaneous handshakes measures the handshake, not the steady+ // state. Twenty at a time keeps the containers honest without serializing.+ const WAVE = 20;+ for (let i = 0; i < count; i += WAVE) {+ const wave = [];+ for (let j = i; j < Math.min(i + WAVE, count); j++) {+ const house = houses[j % houses.length];+ const bridge = new HomeBridge({ baseUrl: house.baseUrl, token: house.token });+ wave.push(+ bridge.connect().then(+ () => {+ bridges.push(bridge);+ onOpen?.(bridges.length);+ },+ (err) => {+ failures.push(err.message);+ bridge.close();+ },+ ),+ );+ }+ await Promise.all(wave);+ }+ return { bridges, failures };+}++function closeAll(bridges) {+ for (const bridge of bridges) {+ try {+ bridge.close();+ } catch {+ // A bridge whose socket already died still has to be released.+ }+ }+}++function firstEntity(bridge, prefix) {+ return Object.keys(bridge.states).find((id) => id.startsWith(prefix)) || null;+}++// ---------------------------------------------------------------- measurements++/**+ * Cold start: how long a brand new instance takes to have one live home.+ *+ * This is the number that decides whether the lane needs minScale above zero, so+ * it is measured on a genuinely cold process (the caller re-execs this script)+ * and split into the two halves that have different fixes: our module graph+ * loading, and the Home Assistant handshake.+ */+async function measureColdStart(fleet) {+ const house = pickHouses(fleet)[0];+ const processStart = performance.now() - Math.round(process.uptime() * 1000);+ const moduleReady = performance.now();++ const t0 = performance.now();+ const bridge = new HomeBridge({ baseUrl: house.baseUrl, token: house.token });+ await bridge.connect();+ const connectMs = performance.now() - t0;+ const entities = Object.keys(bridge.states).length;+ const rooms = bridge.graph.rooms.length;+ bridge.close();++ return {+ bootToModulesReadyMs: Number((moduleReady - processStart).toFixed(1)),+ connectMs: Number(connectMs.toFixed(1)),+ totalToFirstConnectedHomeMs: Number((moduleReady - processStart + connectMs).toFixed(1)),+ entities,+ rooms,+ note: 'Measured in a freshly spawned node process. bootToModulesReadyMs covers node start plus this harness module graph; the API container loads more than this and its own cold start is measured separately in docs/home-operations.md.',+ };+}++/**+ * The per-connection cost at one connection count.+ *+ * Reports the delta from an idle baseline taken in the same process moments+ * earlier, so the answer is "what did these connections add", not "how big is+ * node".+ */+async function measureConnections(fleet, { count, big = false, actionSamples = 40 }) {+ const houses = pickHouses(fleet, { big });+ const before = heapNow();+ const fdBefore = fdCount();+ const cpuBefore = process.cpuUsage();++ const t0 = performance.now();+ const { bridges, failures } = await openBridges(houses, count);+ const openMs = performance.now() - t0;++ // Let the state subscriptions settle and the graph coalescing quiesce, so the+ // heap reading is of a steady connection rather than of a handshake.+ await sleep(4000);++ const after = heapNow();+ const fdAfter = fdCount();+ const idleCpu = process.cpuUsage(cpuBefore);++ // Steady-state cost: what these connections consume while nothing is asked of+ // them. The demo integration pushes state on its own, so this is not zero and+ // should not be.+ const idleWindowStart = process.cpuUsage();+ await sleep(10_000);+ const idleWindow = process.cpuUsage(idleWindowStart);++ const entities = bridges.reduce((n, b) => n + Object.keys(b.states).length, 0);+ const rooms = bridges.reduce((n, b) => n + b.graph.rooms.length, 0);++ const actions = await measureActionLatency(bridges, actionSamples);++ closeAll(bridges);+ await sleep(1500);+ const afterClose = heapNow();++ return {+ requested: count,+ connected: bridges.length,+ failures: failures.slice(0, 5),+ house: big ? 'large' : 'small',+ entitiesHeld: entities,+ entitiesPerConnection: bridges.length ? Math.round(entities / bridges.length) : null,+ roomsHeld: rooms,+ openMs: Number(openMs.toFixed(1)),+ openMsPerConnection: bridges.length ? Number((openMs / bridges.length).toFixed(2)) : null,+ heapUsedDelta: after.heapUsed - before.heapUsed,+ heapPerConnection: bytesPer(after.heapUsed - before.heapUsed, bridges.length),+ rssDelta: after.rss - before.rss,+ rssPerConnection: bytesPer(after.rss - before.rss, bridges.length),+ externalDelta: after.external - before.external,+ fdBefore,+ fdAfter,+ fdPerConnection: bridges.length && fdAfter != null && fdBefore != null ? Number(((fdAfter - fdBefore) / bridges.length).toFixed(2)) : null,+ openCpuMs: Number(((idleCpu.user + idleCpu.system) / 1000).toFixed(1)),+ idleCpuMsPer10s: Number(((idleWindow.user + idleWindow.system) / 1000).toFixed(1)),+ idleCpuMsPerConnectionPerMinute: bridges.length+ ? Number((((idleWindow.user + idleWindow.system) / 1000 / bridges.length) * 6).toFixed(3))+ : null,+ actionLatencyMs: actions,+ heapAfterCloseDelta: afterClose.heapUsed - before.heapUsed,+ fdAfterClose: fdCount(),+ };+}++/**+ * Action latency, measured the way a user experiences it: the call goes out over+ * the same socket the state comes back on, and the sample is the round trip Home+ * Assistant took to acknowledge it.+ */+async function measureActionLatency(bridges, samples) {+ const usable = bridges.filter((b) => firstEntity(b, 'light.'));+ if (!usable.length) return { n: 0, note: 'no light entity in this fleet' };+ const durations = [];+ for (let i = 0; i < samples; i++) {+ const bridge = usable[i % usable.length];+ const entityId = firstEntity(bridge, 'light.');+ const t = performance.now();+ try {+ await bridge.call('light', 'turn_on', { entity_id: entityId, brightness: 20 + (i % 200) });+ durations.push(Number((performance.now() - t).toFixed(2)));+ } catch {+ // A refused or failed call is not a latency sample.+ }+ }+ return summarize(durations);+}++/**+ * CPU absorbed by a burst of 100 entity updates.+ *+ * The big house carries 500 helper entities precisely so this can drive a known+ * number of real state changes rather than waiting for the demo integration to+ * produce some. The interesting output is not only the CPU: it is how many graph+ * rebuilds 100 updates collapsed into, which is the coalescing window doing its+ * job or failing to.+ */+async function measureBurst(fleet, { updates = 100, connections = 1 } = {}) {+ const houses = pickHouses(fleet, { big: true });+ const { bridges } = await openBridges(houses, connections);+ if (!bridges.length) throw new Error('could not open a bridge to the large house');+ const driver = bridges[0];+ await sleep(2000);++ const targets = Object.keys(driver.states)+ .filter((id) => id.startsWith('input_number.load_level_'))+ .slice(0, updates);+ if (targets.length < updates) {+ throw new Error(`the large house has ${targets.length} drivable helpers, need ${updates}. Re-run home-fleet.mjs up --big 1.`);+ }++ let rebuilds = 0;+ const stops = bridges.map((b) => b.on('graph', () => rebuilds++));+ const seen = new Set();+ const watchStops = bridges.map((b) =>+ b.on('graph', () => {+ for (const id of targets) if (b.states[id]?.state !== undefined) seen.add(id);+ }),+ );++ global.gc();+ const cpuBefore = process.cpuUsage();+ const heapBefore = process.memoryUsage().heapUsed;+ const t0 = performance.now();++ await Promise.all(+ targets.map((entityId, i) => driver.call('input_number', 'set_value', { entity_id: entityId, value: (i % 100) + 1 })),+ );+ const dispatchMs = performance.now() - t0;++ // Wait for the graph to stop moving, so the CPU number includes the rebuilds+ // the burst caused rather than only the calls that caused them.+ await sleep(3000);+ const cpu = process.cpuUsage(cpuBefore);+ const absorbMs = performance.now() - t0;+ global.gc();+ const heapAfter = process.memoryUsage().heapUsed;++ for (const stop of [...stops, ...watchStops]) stop();+ const entityCount = Object.keys(driver.states).length;+ const roomCount = driver.graph.rooms.length;++ // The pure cost of one rebuild, separated from everything around it, so the+ // extrapolation later has a real per-rebuild unit rather than a blended one.+ const { buildHomeGraph } = await import('../packages/home-bridge/src/rooms.js');+ const registries = driver.registries;+ const rebuildSamples = [];+ for (let i = 0; i < 30; i++) {+ const t = performance.now();+ buildHomeGraph({ ...registries, states: driver.states });+ rebuildSamples.push(Number((performance.now() - t).toFixed(3)));+ }++ closeAll(bridges);++ return {+ connectionsHeld: bridges.length,+ houseEntities: entityCount,+ houseRooms: roomCount,+ updates,+ dispatchMs: Number(dispatchMs.toFixed(1)),+ absorbMs: Number(absorbMs.toFixed(1)),+ cpuMs: Number(((cpu.user + cpu.system) / 1000).toFixed(1)),+ cpuMsPerUpdate: Number(((cpu.user + cpu.system) / 1000 / updates).toFixed(3)),+ graphRebuilds: rebuilds,+ coalescingRatio: Number((updates / Math.max(1, rebuilds)).toFixed(2)),+ heapDeltaAcrossBurst: heapAfter - heapBefore,+ graphRebuildMs: summarize(rebuildSamples),+ note: 'cpuMs covers the whole absorb window: the 100 outbound service calls, the state pushes they caused, and every graph rebuild that survived coalescing.',+ };+}++/**+ * The cost of an SSE subscriber, separated from the cost of a connection.+ *+ * These are two different resources and the envelope has to price them apart: a+ * house with twelve people watching it is one WebSocket and twelve HTTP+ * responses held open. This measures the second half, with a real HTTP server,+ * real client sockets and the real serialization of a real room graph, fed by a+ * real house. The production endpoint is api/home/*; the cost measured here is+ * the shape it has, which is what the sizing decision needs.+ */+async function measureSse(fleet, { subscribers = 200, seconds = 10 } = {}) {+ const houses = pickHouses(fleet);+ const { bridges } = await openBridges(houses, 1);+ if (!bridges.length) throw new Error('could not open a bridge for the SSE measurement');+ const source = bridges[0];+ await sleep(1500);++ const clients = new Set();+ let framesWritten = 0;+ let bytesWritten = 0;++ const server = createServer((req, res) => {+ res.writeHead(200, {+ 'content-type': 'text/event-stream',+ 'cache-control': 'no-cache',+ connection: 'keep-alive',+ });+ res.write(`event: ready\ndata: ${JSON.stringify({ rooms: source.graph.rooms.length })}\n\n`);+ clients.add(res);+ req.on('close', () => clients.delete(res));+ });+ await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve));+ const port = server.address().port;++ const stopFanout = source.on('graph', (graph) => {+ const frame = `event: graph\ndata: ${JSON.stringify(graph)}\n\n`;+ for (const res of clients) {+ res.write(frame);+ framesWritten++;+ bytesWritten += frame.length;+ }+ });++ const before = heapNow();+ const fdBefore = fdCount();+ const controllers = [];+ for (let i = 0; i < subscribers; i++) {+ const controller = new AbortController();+ controllers.push(controller);+ fetch(`http://127.0.0.1:${port}/home/stream`, { signal: controller.signal })+ .then((res) => res.body.pipeTo(new WritableStream({ write() {} }), { signal: controller.signal }))+ .catch(() => {+ // An aborted stream at teardown is the expected end, not a failure.+ });+ }+ // Give every subscriber time to actually be connected before reading a heap.+ for (let i = 0; i < 100 && clients.size < subscribers; i++) await sleep(100);++ const attached = clients.size;+ const after = heapNow();+ const fdAfter = fdCount();++ const cpuBefore = process.cpuUsage();+ await sleep(seconds * 1000);+ const cpu = process.cpuUsage(cpuBefore);++ stopFanout();+ for (const controller of controllers) controller.abort();+ for (const res of clients) res.end();+ await new Promise((resolve) => server.close(resolve));+ closeAll(bridges);++ return {+ subscribersRequested: subscribers,+ subscribersAttached: attached,+ heapDelta: after.heapUsed - before.heapUsed,+ heapPerSubscriber: bytesPer(after.heapUsed - before.heapUsed, attached),+ rssDelta: after.rss - before.rss,+ rssPerSubscriber: bytesPer(after.rss - before.rss, attached),+ fdPerSubscriber: attached && fdAfter != null ? Number(((fdAfter - fdBefore) / attached).toFixed(2)) : null,+ framesWritten,+ bytesWritten,+ windowSeconds: seconds,+ cpuMsInWindow: Number(((cpu.user + cpu.system) / 1000).toFixed(1)),+ cpuMsPerSubscriberPerMinute: attached ? Number((((cpu.user + cpu.system) / 1000 / attached) * (60 / seconds)).toFixed(3)) : null,+ note: 'One live house fanning its real room graph to N real HTTP subscribers over a real socket each. Both halves of the cost, the held response and the per-frame serialization, are in these numbers.',+ };+}++/**+ * The safety assertion: saturation must never buy an agent a free unlock.+ *+ * Drives the admission controller from empty to fully shed while a real guarded+ * call is classified against a real lock in a real house at every step, and+ * asserts that at no point does the verdict stop demanding a human.+ */+async function measureGateUnderSaturation(fleet, { steps = 400 } = {}) {+ const houses = pickHouses(fleet);+ const { bridges } = await openBridges(houses, 1);+ if (!bridges.length) throw new Error('could not open a bridge for the gate assertion');+ const bridge = bridges[0];+ const lock = firstEntity(bridge, 'lock.');+ if (!lock) throw new Error('the fixture house has no lock; the gate assertion needs one');++ const admission = createAdmissionController({ maxPooled: 20, maxUnpooled: 5, maxStreams: 30, maxInflightActions: 40 });+ const rungsSeen = new Set();+ const violations = [];+ let refusedByGate = 0;+ let shedByLoad = 0;++ for (let i = 0; i < steps; i++) {+ // Climb: take connection slots, open streams, start actions, and never+ // finish them, so the controller walks the whole ladder.+ if (i % 3 === 0) admission.acquire();+ if (i % 2 === 0) admission.admitStream();+ if (i % 5 === 0) admission.setDatabaseHealthy(false);++ const verdict = classifyCall({ domain: 'lock', service: 'unlock', entityId: lock, attributes: bridge.states[lock]?.attributes });+ const decision = admission.admitAction({ guarded: verdict.guarded, confirmed: false, allowed: bridge.allowList.has(lock) });+ rungsSeen.add(decision.rung);++ if (!decision.requiresConfirmation) {+ violations.push({ step: i, rung: decision.rung, snapshot: admission.snapshot() });+ }+ if (decision.admitted) {+ // The gate is what stops it, not the load: an admitted guarded action+ // still has to come back with requiresConfirmation and go no further.+ refusedByGate++;+ admission.finishAction();+ // Re-take the slot without releasing, to climb toward the shed rung.+ if (i > steps / 3) admission.admitAction({ guarded: false });+ } else {+ shedByLoad++;+ }+ }++ // The real call, at the top of the ladder, against the real lock: it must+ // still refuse, and the lock must still be locked afterwards.+ const stateBefore = bridge.states[lock]?.state;+ let liveRefusal = null;+ try {+ await bridge.call('lock', 'unlock', { entity_id: lock });+ liveRefusal = 'NOT REFUSED';+ } catch (err) {+ liveRefusal = err.code;+ }+ await sleep(1200);+ const stateAfter = bridge.states[lock]?.state;+ closeAll(bridges);++ return {+ steps,+ lock,+ rungsSeen: [...rungsSeen].sort(),+ guardedActionsSeen: steps,+ everWavedThrough: violations.length,+ violations: violations.slice(0, 3),+ refusedByGateWhileAdmitted: refusedByGate,+ shedByLoad,+ liveCallOutcome: liveRefusal,+ lockStateBefore: stateBefore,+ lockStateAfter: stateAfter,+ passed: violations.length === 0 && liveRefusal === 'needs_confirmation' && stateAfter === stateBefore,+ };+}++/** Each rung of the ladder, demonstrated rather than described. */+function demonstrateLadder() {+ const admission = createAdmissionController({ maxPooled: 4, maxUnpooled: 2, maxStreams: 6, maxInflightActions: 8, streamYieldRatio: 0.5 });+ const rows = [];+ const record = (label, verdict) =>+ rows.push({ label, admitted: verdict.admitted, rung: verdict.rung, connection: verdict.connection ?? null, source: verdict.source ?? null, requiresConfirmation: verdict.requiresConfirmation ?? null, retryAfterSeconds: verdict.retryAfterSeconds ?? null, reason: verdict.reason || null });++ record('rung 1: acquire under the cap', admission.acquire());+ for (let i = 0; i < 3; i++) admission.acquire();+ record('rung 2: acquire at the cap', admission.acquire());+ record('rung 2: read is still from the database', admission.admitRead());+ admission.setDatabaseHealthy(false);+ record('rung 3: read with the database down', admission.admitRead());+ rows.push({ label: 'rung 3: write policy with the database down', ...admission.writePolicy() });+ admission.setDatabaseHealthy(true);+ record('rung 4: stream while 3 of 8 actions are in flight', (() => {+ for (let i = 0; i < 3; i++) admission.admitAction({ guarded: false });+ return admission.admitStream();+ })());+ record('rung 4: stream once actions pass the yield floor', (() => {+ for (let i = 0; i < 2; i++) admission.admitAction({ guarded: false });+ return admission.admitStream();+ })());+ record('rung 4: an action at the same moment', admission.admitAction({ guarded: false }));+ record('rung 5: an action with every slot taken', (() => {+ for (let i = 0; i < 8; i++) admission.admitAction({ guarded: false });+ return admission.admitAction({ guarded: false });+ })());+ record('rung 5: a GUARDED action with every slot taken', admission.admitAction({ guarded: true, confirmed: false }));++ return { rows, finalSnapshot: admission.snapshot() };+}++// ---------------------------------------------------------------- runner++async function all({ out, counts, sseSubscribers }) {+ const fleet = await readFleet();+ const machine = {+ node: process.version,+ platform: `${os.platform()} ${os.release()}`,+ cpus: os.cpus().length,+ cpuModel: os.cpus()[0]?.model ?? null,+ totalMemBytes: os.totalmem(),+ ulimitNofile: Number(process.report?.getReport()?.userLimits?.open_files?.soft ?? 0) || null,+ };++ const result = {+ measuredAt: new Date().toISOString(),+ machine,+ fleet: {+ image: fleet.image,+ houses: fleet.houses.length,+ small: fleet.houses.filter((h) => !h.big).length,+ large: fleet.houses.filter((h) => h.big).length,+ entitiesPerSmallHouse: fleet.houses.find((h) => !h.big)?.entityCount ?? null,+ entitiesPerLargeHouse: fleet.houses.find((h) => h.big)?.entityCount ?? null,+ haBootMs: summarize(fleet.houses.map((h) => h.bootMs)),+ realNote: 'Every house is a real Home Assistant container with a real long-lived access token, started by scripts/home-fleet.mjs. Connections are real WebSocket sessions through home-assistant-js-websocket, the same client the product uses.',+ },+ coldStart: await measureColdStart(fleet),+ connections: [],+ ladder: demonstrateLadder(),+ };++ for (const count of counts) {+ process.stderr.write(` measuring ${count} connections...\n`);+ result.connections.push(await measureConnections(fleet, { count }));+ await sleep(2000);+ }++ process.stderr.write(' measuring the large house...\n');+ result.largeHouse = await measureConnections(fleet, { count: 10, big: true });++ process.stderr.write(' measuring a 100 entity update burst...\n');+ result.burst = await measureBurst(fleet, { updates: 100 });++ process.stderr.write(' measuring SSE subscribers...\n');+ result.sse = await measureSse(fleet, { subscribers: sseSubscribers });++ process.stderr.write(' asserting the gate under saturation...\n');+ result.gate = await measureGateUnderSaturation(fleet);++ if (out) {+ const file = path.resolve(ROOT, out);+ await mkdir(path.dirname(file), { recursive: true });+ await writeFile(file, `${JSON.stringify(result, null, 2)}\n`);+ process.stderr.write(`\nwrote ${path.relative(ROOT, file)}\n`);+ } else {+ process.stdout.write(`${JSON.stringify(result, null, 2)}\n`);+ }+ return result;+}++function parseArgs(argv) {+ const out = { _: [] };+ for (let i = 0; i < argv.length; i++) {+ const arg = argv[i];+ if (arg.startsWith('--')) out[arg.slice(2)] = argv[i + 1]?.startsWith('--') || argv[i + 1] === undefined ? true : argv[++i];+ else out._.push(arg);+ }+ return out;+}++export { demonstrateLadder, measureBurst, measureColdStart, measureConnections, measureGateUnderSaturation, measureSse, openBridges, closeAll, pickHouses, summarize, requiresConfirmation };++const isMain = process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url);+if (isMain) {+ const args = parseArgs(process.argv.slice(2));+ const command = args._[0] || 'all';+ const counts = String(args.counts || '10,50,100,200,400')+ .split(',')+ .map((n) => Number(n.trim()))+ .filter(Boolean);++ const commands = {+ all: () => all({ out: typeof args.out === 'string' ? args.out : null, counts, sseSubscribers: Number(args.subscribers || 200) }),+ coldstart: async () => measureColdStart(await readFleet()),+ connections: async () => measureConnections(await readFleet(), { count: Number(args.n || 50), big: Boolean(args.big) }),+ burst: async () => measureBurst(await readFleet(), { updates: Number(args.updates || 100) }),+ sse: async () => measureSse(await readFleet(), { subscribers: Number(args.subscribers || 200) }),+ gate: async () => measureGateUnderSaturation(await readFleet()),+ ladder: async () => demonstrateLadder(),+ };++ const run = commands[command];+ if (!run) {+ console.error(`unknown command "${command}". Use: ${Object.keys(commands).join(' | ')}`);+ process.exit(2);+ }+ run().then(+ (value) => {+ if (command !== 'all' || !args.out) process.stdout.write(`${JSON.stringify(value, null, 2)}\n`);+ process.exit(0);+ },+ (err) => {+ console.error(err.stack || err.message);+ process.exit(1);+ },+ );+}diff --git a/scripts/home-test-instance.mjs b/scripts/home-test-instance.mjsindex f30427cc9..576724fab 100755--- a/scripts/home-test-instance.mjs+++ b/scripts/home-test-instance.mjs@@ -64,19 +64,28 @@ async function main() {};try {- let state = readState(instance);-- if (opts.down) {- const removed = await down(instance, state);- emit({ action: 'down', name: instance.name, ...removed });- return;- }+ // Several vitest forks reach for the same named instance at once, and two+ // simultaneous `docker run --name` calls means one of them fails. The lock+ // makes the second caller wait for the first to finish building the house+ // and then reuse it, which is what "idempotent" has to mean under+ // concurrency.+ const state = await withLock(instance, async () => {+ let current = readState(instance);++ if (opts.down) {+ const removed = await down(instance, current);+ emit({ action: 'down', name: instance.name, ...removed });+ return null;+ }- if (opts.up) state = await up(instance, state, { seedNow: opts.seed });- if (!state) state = requireState(instance);+ if (opts.up) current = await up(instance, current, { seedNow: opts.seed });+ if (!current) current = requireState(instance);- if (opts.onboard) state = await onboard(instance, state);- if (opts.seed) state = await seed(instance, state, { alreadyInConfig: Boolean(opts.up) });+ if (opts.onboard) current = await onboard(instance, current);+ if (opts.seed) current = await seed(instance, current, { alreadyInConfig: Boolean(opts.up) });+ return current;+ });+ if (!state) return;emit({action: 'ready',@@ -88,6 +97,7 @@ async function main() {baseUrl: state.baseUrl,token: state.token || null,seeded: Boolean(state.seeded),+ seed: state.seedResult || null,configDir: path.relative(ROOT, instance.configDir),});} catch (err) {@@ -167,6 +177,18 @@ async function down(inst, state) {if (!path.basename(dir).startsWith('.ha-config-') || path.dirname(dir) !== ROOT) {throw new Error(`refusing to delete ${dir}: not a harness config directory`);}+ // Home Assistant runs as root in the container, so /config comes back+ // owned by root and an ordinary rm cannot clear it. Hand ownership back+ // through a throwaway container on the image we already have locally,+ // then delete from here. A config directory left behind is not litter:+ // it holds a working access token.+ await docker([+ 'run', '--rm',+ '-v', `${dir}:/target`,+ '--entrypoint', 'chown',+ inst.image,+ '-R', `${process.getuid()}:${process.getgid()}`, '/target',+ ]).catch((err) => log(`[down] could not reclaim ownership of ${path.relative(ROOT, dir)}: ${err.message}`));fs.rmSync(dir, { recursive: true, force: true });removedConfig = true;log(`[down] removed ${path.relative(ROOT, dir)}`);@@ -726,6 +748,39 @@ function describeInstance(name, version) {};}+/**+ * An exclusive lock around one named instance, held for the whole up/onboard/+ * seed sequence. `mkdir` is the atomic primitive here: it either creates the+ * directory or fails, with no window between the two.+ */+async function withLock(inst, fn) {+ const lock = `${inst.configDir}.lock`;+ const deadline = Date.now() + 900_000;+ for (;;) {+ try {+ fs.mkdirSync(lock);+ break;+ } catch (err) {+ if (err.code !== 'EEXIST') throw err;+ // A killed run leaves its lock behind. Nothing here takes longer than+ // a cold Home Assistant boot, so a much older lock is abandoned.+ const age = Date.now() - (fs.statSync(lock).mtimeMs || 0);+ if (age > 900_000) {+ fs.rmSync(lock, { recursive: true, force: true });+ continue;+ }+ if (Date.now() > deadline) throw new Error(`another run has held the lock on "${inst.name}" for 15 minutes`);+ log(`[lock] waiting for another run to finish with "${inst.name}"`);+ await new Promise((r) => setTimeout(r, 2000));+ }+ }+ try {+ return await fn();+ } finally {+ fs.rmSync(lock, { recursive: true, force: true });+ }+}+function statePath(inst) {return path.join(inst.configDir, '.harness.json');}diff --git a/tests/_helpers/home-instance.js b/tests/_helpers/home-instance.jsnew file mode 100644index 000000000..5bcc8e796--- /dev/null+++ b/tests/_helpers/home-instance.js@@ -0,0 +1,165 @@+/**+ * One way for a live test to get a real Home Assistant.+ *+ * Before this helper each live test in the home lane carried its own paragraph+ * of setup instructions, and the instances they described had drifted apart:+ * one had scenes, one had a lock exposed to Assist, one had neither, so a test+ * could pass for a reason nobody had written down. Every live test in the lane+ * now calls `acquireHomeInstance()` and gets the same seeded house.+ *+ * Two ways in, and neither runs by default, because `npm test` must not need+ * Docker:+ *+ * HOME_ASSISTANT_URL=... HOME_ASSISTANT_TOKEN=... point at a house you have+ * HOME_LIVE=1 let the harness make one+ *+ * The harness path shares ONE named container across every test file in the+ * run (vitest gives each file its own fork, and building a Home Assistant per+ * fork would cost minutes and a gigabyte each). Nothing here ever tears that+ * instance down: it is the caller's, and `npm run home:instance:down` removes+ * it when the run is over.+ */++import { spawn } from 'node:child_process';+import path from 'node:path';+import { fileURLToPath } from 'node:url';++const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..', '..');+const HARNESS = path.join(ROOT, 'scripts', 'home-test-instance.mjs');++/** The shared instance every live test in the lane reuses. */+const INSTANCE_NAME = process.env.HOME_LIVE_NAME || 'lane';++/**+ * Whether the live tier should run at all. Synchronous on purpose: vitest needs+ * the skip decision before any hook has had a chance to start a container.+ */+export function liveHomeAvailable() {+ if (process.env.HOME_ASSISTANT_URL && process.env.HOME_ASSISTANT_TOKEN) return true;+ return isTruthy(process.env.HOME_LIVE);+}++/**+ * A connected-ready house: `{ baseUrl, token, version, seed }`.+ *+ * Call it from `beforeAll` with a generous timeout. A cold Home Assistant boot+ * plus seeding is around two minutes; every subsequent caller in the same run+ * reuses the container and returns in about a second.+ */+export async function acquireHomeInstance({ timeout = 600_000 } = {}) {+ if (process.env.HOME_ASSISTANT_URL && process.env.HOME_ASSISTANT_TOKEN) {+ return {+ baseUrl: process.env.HOME_ASSISTANT_URL.replace(/\/+$/, ''),+ token: process.env.HOME_ASSISTANT_TOKEN,+ version: null,+ seed: null,+ managed: false,+ };+ }+ if (!isTruthy(process.env.HOME_LIVE)) {+ throw new Error('No live Home Assistant: set HOME_ASSISTANT_URL + HOME_ASSISTANT_TOKEN, or HOME_LIVE=1.');+ }++ const result = await runHarness(['--up', '--onboard', '--seed', '--json', '--name', INSTANCE_NAME], { timeout });+ if (!result.ok) throw new Error(`home-test-instance failed: ${result.error}`);+ return {+ baseUrl: result.baseUrl,+ token: result.token,+ version: result.haVersion,+ seed: result.seed || null,+ managed: true,+ };+}++/**+ * A live entity id of the given domain, read from the house itself rather than+ * assumed. A test that hardcodes `light.bed_light` is a test that breaks the+ * day someone points the lane at their own home.+ */+export async function pickEntity(instance, domain, predicate = () => true) {+ const states = await readStates(instance);+ const found = states.find((s) => s.entity_id.startsWith(`${domain}.`) && predicate(s));+ return found ? found.entity_id : null;+}++/** Every state in the house, straight from the REST API. */+export async function readStates(instance) {+ const res = await fetch(`${instance.baseUrl}/api/states`, {+ headers: { authorization: `Bearer ${instance.token}` },+ signal: AbortSignal.timeout(15_000),+ });+ if (!res.ok) throw new Error(`GET /api/states returned ${res.status}`);+ return res.json();+}++/**+ * One entity's state, read back from Home Assistant.+ *+ * The lane's confirmation tests assert on this and never on our own UI text: a+ * card that says "unlocked" proves nothing about a door.+ */+export async function readState(instance, entityId) {+ const res = await fetch(`${instance.baseUrl}/api/states/${encodeURIComponent(entityId)}`, {+ headers: { authorization: `Bearer ${instance.token}` },+ signal: AbortSignal.timeout(15_000),+ });+ if (!res.ok) throw new Error(`GET /api/states/${entityId} returned ${res.status}`);+ const body = await res.json();+ return body.state;+}++/**+ * Wait until an entity reaches one of the given states, polling Home Assistant.+ *+ * This is the only correct way to wait in this lane. A fixed sleep is how a+ * suite that guards a door becomes a suite people ignore.+ */+export async function waitForState(instance, entityId, expected, { timeout = 20_000, interval = 250 } = {}) {+ const wanted = new Set(Array.isArray(expected) ? expected : [expected]);+ const deadline = Date.now() + timeout;+ let last = null;+ while (Date.now() < deadline) {+ last = await readState(instance, entityId).catch(() => null);+ if (last && wanted.has(last)) return last;+ await new Promise((r) => setTimeout(r, interval));+ }+ throw new Error(`${entityId} was "${last}" after ${Math.round(timeout / 1000)}s, expected one of ${[...wanted].join(', ')}`);+}++/** Put an entity back the way the test found it, for the next test in the file. */+export async function setState(instance, domain, service, entityId) {+ const res = await fetch(`${instance.baseUrl}/api/services/${domain}/${service}`, {+ method: 'POST',+ headers: { authorization: `Bearer ${instance.token}`, 'content-type': 'application/json' },+ body: JSON.stringify({ entity_id: entityId }),+ signal: AbortSignal.timeout(15_000),+ });+ if (!res.ok) throw new Error(`${domain}.${service} on ${entityId} returned ${res.status}`);+}++function isTruthy(value) {+ return Boolean(value) && value !== '0' && value !== 'false';+}++function runHarness(args, { timeout }) {+ return new Promise((resolve, reject) => {+ const child = spawn(process.execPath, [HARNESS, ...args], { cwd: ROOT, stdio: ['ignore', 'pipe', 'pipe'] });+ let out = '';+ let err = '';+ const timer = setTimeout(() => {+ child.kill('SIGKILL');+ reject(new Error(`home-test-instance timed out after ${Math.round(timeout / 1000)}s`));+ }, timeout);+ child.stdout.on('data', (d) => (out += d));+ child.stderr.on('data', (d) => (err += d));+ child.on('error', reject);+ child.on('close', () => {+ clearTimeout(timer);+ try {+ resolve(JSON.parse(out));+ } catch {+ reject(new Error(`home-test-instance produced no JSON. stderr: ${err.trim().split('\n').slice(-4).join(' ')}`));+ }+ });+ });+}diff --git a/tests/home-privacy.test.js b/tests/home-privacy.test.jsnew file mode 100644index 000000000..bbd799119--- /dev/null+++ b/tests/home-privacy.test.js@@ -0,0 +1,474 @@+// The Home lane's privacy guarantees, asserted rather than documented.+//+// Three of these tests are structural, and they are the ones that will still be+// doing their job in six months:+//+// * INVENTORY COMPLETENESS re-derives the set of home_* tables from the+// migration files themselves. A future order that adds a table to this+// campaign and forgets to write down what it holds fails here, which is the+// only reliable defence against an undocumented data class.+// * NO PERSISTED STATE HISTORY reads the same migrations and fails if any of+// them creates a column that would store an entity's state over time. That+// promise is the most important line in docs/home-privacy.md and it is one+// careless migration away from being false.+// * LOG HYGIENE reads the lane's source and fails if a log call passes a base+// URL, a home label, or a friendly name. Logs go to a different system with+// a different retention and a different set of readers, so a leak there has+// the longest tail of any leak in the lane.+//+// The rest exercise real behaviour against the real database and are skipped,+// with a stated reason, when DATABASE_URL is absent (a fresh clone, CI without+// secrets). They are never replaced by a mock: a cascade that a mock "verifies"+// is a cascade nobody verified.++import { readFileSync, readdirSync } from 'node:fs';+import { join } from 'node:path';+import { afterAll, describe, expect, it } from 'vitest';++import {+ DEFAULT_ACTION_LOG_RETENTION_DAYS,+ INVENTORY,+ INVENTORY_TABLES,+ MAX_ACTION_LOG_RETENTION_DAYS,+ MIN_ACTION_LOG_RETENTION_DAYS,+} from '../api/_lib/home/privacy.js';+import { CONNECT_DISCLOSURE, DISCLOSURES, VOICE_DISCLOSURE, disclosureById } from '../api/_lib/home/disclosure.js';++const MIGRATIONS_DIR = join(process.cwd(), 'api/_lib/migrations');++function homeMigrations() {+ return readdirSync(MIGRATIONS_DIR)+ .filter((f) => f.endsWith('.sql'))+ .map((f) => ({ file: f, sql: readFileSync(join(MIGRATIONS_DIR, f), 'utf8') }))+ .filter((m) => /create table (if not exists )?home_/i.test(m.sql) || /alter table home_/i.test(m.sql));+}++/** Every `home_*` table any migration in the repo creates. */+function declaredHomeTables() {+ const found = new Set();+ for (const { sql } of homeMigrations()) {+ for (const m of sql.matchAll(/create table\s+(?:if not exists\s+)?(home_[a-z0-9_]+)/gi)) {+ found.add(m[1].toLowerCase());+ }+ }+ return [...found].sort();+}++describe('home privacy: the inventory is complete', () => {+ it('every home table a migration creates is written down in INVENTORY', () => {+ const declared = declaredHomeTables();+ expect(declared.length).toBeGreaterThan(0);+ const missing = declared.filter((t) => !INVENTORY_TABLES.includes(t));+ expect(+ missing,+ `These tables exist in the schema but no row of INVENTORY (api/_lib/home/privacy.js) says what they hold, why, or how long for. Add a row, and add it to docs/home-privacy.md, in the same change that created the table.`,+ ).toEqual([]);+ });++ it('the inventory never names a table that does not exist', () => {+ const declared = declaredHomeTables();+ // audit_log is the one non-home table the lane writes to, handled by its+ // own residue sweep rather than the inventory's table column.+ const phantom = INVENTORY_TABLES.filter((t) => !declared.includes(t));+ expect(phantom, 'INVENTORY names a table no migration creates').toEqual([]);+ });++ it('every inventory row answers all five questions a person would ask', () => {+ for (const row of INVENTORY) {+ expect(row.key, 'every row needs a stable key').toMatch(/^[a-z_]+$/);+ expect(row.data.length, `${row.key}: "what" must be a sentence`).toBeGreaterThan(10);+ expect(row.why.length, `${row.key}: "why" must be a sentence`).toBeGreaterThan(10);+ expect(row.retention.length, `${row.key}: "how long" must be a sentence`).toBeGreaterThan(10);+ expect(row.deletedBy.length, `${row.key}: "who removes it" must be a sentence`).toBeGreaterThan(4);+ }+ });++ it('states plainly that entity names, states and voice audio are not stored', () => {+ const promises = INVENTORY.filter((r) => r.table === null).map((r) => r.key);+ for (const key of ['entity_names', 'entity_states', 'voice_audio', 'voice_transcript']) {+ expect(promises, `${key} must be an explicit "we do not store this" row`).toContain(key);+ }+ });+});++describe('home privacy: no persisted entity-state history', () => {+ // The shapes a state history would take if somebody added one. Naming them+ // is the point: this test is a tripwire on a specific mistake, not a vague+ // gesture at good intentions.+ const BANNED = [+ /create table\s+(?:if not exists\s+)?home_(entity_)?stat(e|es|e_history)\b/i,+ /create table\s+(?:if not exists\s+)?home_[a-z_]*state_history/i,+ /create table\s+(?:if not exists\s+)?home_entity_snapshots?/i,+ /create table\s+(?:if not exists\s+)?home_occupancy/i,+ /create table\s+(?:if not exists\s+)?home_presence/i,+ ];++ it('no migration creates a table that would store entity state over time', () => {+ for (const { file, sql } of homeMigrations()) {+ for (const pattern of BANNED) {+ expect(+ pattern.test(sql),+ `${file} creates a persisted entity-state history. A record of when a household's lights go on and off is a record of when they are home. If there is a genuine product need it requires its own explicit opt-in, its own retention window and its own disclosure, and it is not part of this campaign.`,+ ).toBe(false);+ }+ }+ });++ it('the room graph is not persisted anywhere in the schema', () => {+ for (const { file, sql } of homeMigrations()) {+ expect(+ /create table\s+(?:if not exists\s+)?home_(rooms|areas|entities|devices)\b/i.test(sql),+ `${file} persists the room graph. It is a live projection of a live WebSocket and belongs in the bridge runtime's memory, where it dies with the instance.`,+ ).toBe(false);+ }+ });+});++describe('home privacy: log hygiene', () => {+ const SOURCES = [+ 'api/_lib/home/store.js',+ 'api/_lib/home/privacy.js',+ 'api/_lib/home/disclosure.js',+ 'api/home/privacy.js',+ ];++ function readIfPresent(path) {+ try {+ return readFileSync(join(process.cwd(), path), 'utf8');+ } catch {+ return null;+ }+ }++ it('no log call in the lane passes a base URL, a home label, or a friendly name', () => {+ // Match the ARGUMENTS of a log call, not the whole file: the modules talk+ // about base_url in comments and in SQL projections, which is correct, and+ // only what reaches a log sink is the leak.+ const LOG_CALL = /(?:console\.(?:log|warn|error|info|debug)|logAudit|logAuditNow|sendOpsAlert)\s*\(([\s\S]{0,600}?)\)\s*;/g;+ const LEAKY = /\b(base_?Url|baseUrl|friendly_?name|\blabel\b)\b/i;++ for (const path of SOURCES) {+ const src = readIfPresent(path);+ if (src === null) continue;+ for (const match of src.matchAll(LOG_CALL)) {+ expect(+ LEAKY.test(match[1]),+ `${path}: a log call carries a home address or a human-chosen name:\n${match[0].slice(0, 300)}\nLogs have their own retention and their own readers. Log the home id instead; it correlates and it says nothing.`,+ ).toBe(false);+ }+ }+ });++ it('the action log scrubs its detail blob before writing it', () => {+ const src = readIfPresent('api/_lib/home/store.js');+ expect(src, 'api/_lib/home/store.js must exist').not.toBeNull();+ expect(+ /JSON\.stringify\(scrubSecrets\(detail\)\)/.test(src),+ 'home_action_log.detail is written by a caller-supplied object and must go through scrubSecrets() first.',+ ).toBe(true);+ });+});++describe('home privacy: the disclosure copy', () => {+ it('both surfaces have copy, and it is the same copy everywhere', () => {+ expect(DISCLOSURES.map((d) => d.id).sort()).toEqual(['home.connect', 'home.voice']);+ expect(disclosureById('home.connect')).toBe(CONNECT_DISCLOSURE);+ expect(disclosureById('home.voice')).toBe(VOICE_DISCLOSURE);+ });++ it('the connect copy says what the token can actually do', () => {+ const text = CONNECT_DISCLOSURE.lines.join(' ').toLowerCase();+ // "full control" is the sentence that does not change anybody's mind.+ // "unlock your doors" is the one that does.+ expect(text).toContain('unlock');+ expect(text).toContain('encrypt');+ expect(text, 'must say we never store device states').toMatch(/never store their states|no record of which lights/);+ });++ it('the voice copy separates what stays on the device from what leaves it', () => {+ const text = VOICE_DISCLOSURE.lines.join(' ').toLowerCase();+ expect(text).toContain('wake word');+ expect(text).toContain('this device');+ expect(text, 'must say the audio is never stored').toMatch(/never store the audio/);+ });++ it('no disclosure hedges', () => {+ for (const d of DISCLOSURES) {+ for (const line of d.lines) {+ expect(+ /\bmay\b|\bmight\b|\bwe aim to\b|\bwe strive\b/i.test(line),+ `${d.id}: "${line}" hedges. Every sentence here is true of the code as it stands, or it does not ship.`,+ ).toBe(false);+ }+ }+ });++ it('every disclosure points somewhere a reader can actually go', () => {+ for (const d of DISCLOSURES) {+ expect(d.learnMoreHref).toBe('/docs/home-privacy');+ }+ });+});++describe('home privacy: retention bounds', () => {+ it('defaults to 90 days, inside its own bounds', () => {+ expect(DEFAULT_ACTION_LOG_RETENTION_DAYS).toBe(90);+ expect(MIN_ACTION_LOG_RETENTION_DAYS).toBeLessThan(DEFAULT_ACTION_LOG_RETENTION_DAYS);+ expect(MAX_ACTION_LOG_RETENTION_DAYS).toBeGreaterThan(DEFAULT_ACTION_LOG_RETENTION_DAYS);+ });++ it('the schema enforces the same bounds the module does', () => {+ const migration = readFileSync(+ join(MIGRATIONS_DIR, '20260903180000_home_privacy_retention.sql'),+ 'utf8',+ );+ expect(migration).toContain(+ `check (action_log_retention_days between ${MIN_ACTION_LOG_RETENTION_DAYS} and ${MAX_ACTION_LOG_RETENTION_DAYS})`,+ );+ expect(migration).toContain(`default ${DEFAULT_ACTION_LOG_RETENTION_DAYS}`);+ });++ it('a grant cannot pin a departed user in place', () => {+ const migration = readFileSync(+ join(MIGRATIONS_DIR, '20260903180000_home_privacy_retention.sql'),+ 'utf8',+ );+ expect(+ /foreign key \(granted_by\) references users\(id\) on delete cascade/i.test(migration),+ 'home_entity_grants.granted_by must cascade, or a member who granted an allowance on somebody else\'s home can never delete their account.',+ ).toBe(true);+ });+});++// ── Live database behaviour ──────────────────────────────────────────────────+// Real rows, real cascades, real counts. Skipped, loudly, without DATABASE_URL.++const LIVE = Boolean(process.env.DATABASE_URL);++describe.skipIf(!LIVE)('home privacy: deletion and purge against the real database', () => {+ /** @type {any} */ let sql;+ /** @type {any} */ let privacy;+ const created = { users: [], homes: [] };++ async function setup() {+ if (sql) return;+ ({ sql } = await import('../api/_lib/db.js'));+ privacy = await import('../api/_lib/home/privacy.js');+ }++ async function makeUser(tag) {+ const email = `home-privacy-${tag}-${Date.now()}-${Math.random().toString(36).slice(2, 8)}@test.invalid`;+ const [row] = await sql`+ insert into users (email, display_name) values (${email}, ${'home privacy test'})+ returning id, email+ `;+ created.users.push(row.id);+ return row;+ }++ async function makeHome(userId, label) {+ const [row] = await sql`+ insert into home_connections (user_id, label, base_url, access_token_enc, token_fingerprint)+ values (${userId}, ${label}, ${'https://ha-' + Math.random().toString(36).slice(2, 10) + '.test.invalid'},+ ${'enc'}, ${Math.random().toString(36).slice(2)})+ returning id+ `;+ created.homes.push(row.id);+ return row.id;+ }++ afterAll(async () => {+ if (!sql) return;+ for (const id of created.homes) await sql`delete from home_connections where id = ${id}`;+ for (const id of created.users) await sql`delete from users where id = ${id}`;+ });++ it('deleting one home removes every row of that home and touches no other', async () => {+ await setup();+ const owner = await makeUser('one');+ const doomed = await makeHome(owner.id, 'The one being deleted');+ const keeper = await makeHome(owner.id, 'The one that stays');++ for (const homeId of [doomed, keeper]) {+ await sql`insert into home_entity_grants (home_id, entity_id, granted_by) values (${homeId}, ${'lock.front_door'}, ${owner.id})`;+ await sql`insert into home_action_log (home_id, user_id, actor, channel, action, entity_ids, outcome)+ values (${homeId}, ${owner.id}, 'user', 'websocket', 'light.turn_on', ${['light.kitchen']}, 'ok')`;+ }++ const beforeDoomed = await privacy.countHomeRows(doomed);+ const beforeKeeper = await privacy.countHomeRows(keeper);+ expect(beforeDoomed.home_connections).toBe(1);+ expect(beforeDoomed.home_entity_grants).toBe(1);+ expect(beforeDoomed.home_action_log).toBe(1);+ // The order-12 trigger seeds an owner membership on insert.+ expect(beforeDoomed.home_members).toBeGreaterThanOrEqual(1);++ const result = await privacy.deleteHome(doomed, owner.id);+ expect(result.deleted).toBe(true);++ const afterDoomed = await privacy.countHomeRows(doomed);+ for (const [table, n] of Object.entries(afterDoomed)) {+ expect(n, `${table} still has rows for a deleted home`).toBe(0);+ }+ const afterKeeper = await privacy.countHomeRows(keeper);+ expect(afterKeeper).toEqual(beforeKeeper);+ });++ it('a home that is not yours cannot be deleted, and says nothing about existing', async () => {+ await setup();+ const owner = await makeUser('owner');+ const stranger = await makeUser('stranger');+ const homeId = await makeHome(owner.id, 'Not yours');++ const result = await privacy.deleteHome(homeId, stranger.id);+ expect(result.deleted).toBe(false);+ const still = await privacy.countHomeRows(homeId);+ expect(still.home_connections).toBe(1);+ });++ it('deleting an account leaves zero rows in every table, and is idempotent', async () => {+ await setup();+ const owner = await makeUser('acct');+ const other = await makeUser('other');+ const mine = await makeHome(owner.id, 'Mine');+ const theirs = await makeHome(other.id, 'Theirs');++ // Rows in every table, including the ones a naive cascade misses: a grant+ // and a membership on somebody else's home, and an action this user took+ // and confirmed there.+ await sql`insert into home_entity_grants (home_id, entity_id, granted_by) values (${mine}, ${'lock.front_door'}, ${owner.id})`;+ await sql`insert into home_members (home_id, user_id, role) values (${theirs}, ${owner.id}, 'member')`;+ await sql`insert into home_entity_grants (home_id, entity_id, granted_by) values (${theirs}, ${'lock.office_door'}, ${owner.id})`;+ await sql`insert into home_invites (home_id, email, role, token_hash, invited_by, expires_at)+ values (${theirs}, ${owner.email}, 'member', ${'h' + Math.random().toString(36).slice(2)}, ${other.id}, now() + interval '7 days')`;+ await sql`insert into home_action_log (home_id, user_id, actor, channel, action, entity_ids, guarded, confirmed_by, outcome)+ values (${theirs}, ${owner.id}, 'user', 'websocket', 'lock.unlock', ${['lock.office_door']}, true, ${owner.id}, 'ok')`;++ const before = await privacy.countUserRows(owner.id, owner.email);+ expect(before.home_connections).toBe(1);+ expect(before.home_members).toBe(2); // the owner seed on `mine`, plus `theirs`+ expect(before.home_entity_grants).toBe(2);+ expect(before.home_invites_to_email).toBe(1);+ expect(before.home_action_log_actor).toBe(1);+ expect(before.home_action_log_confirmed_by).toBe(1);++ const first = await privacy.deleteAllHomeDataForUser(owner.id, { email: owner.email });+ for (const [table, n] of Object.entries(first.after)) {+ expect(n, `${table} still holds rows for a deleted account`).toBe(0);+ }++ // Idempotent: a second run finds nothing and changes nothing.+ const second = await privacy.deleteAllHomeDataForUser(owner.id, { email: owner.email });+ expect(second.before).toEqual(second.after);+ expect(second.homes).toBe(0);++ // The other household keeps its own history, minus the pointer to a person+ // who is gone.+ const [{ n }] = await sql`select count(*)::int as n from home_action_log where home_id = ${theirs}`;+ expect(n).toBe(1);+ const [row] = await sql`select user_id, confirmed_by from home_action_log where home_id = ${theirs}`;+ expect(row.user_id).toBeNull();+ expect(row.confirmed_by).toBeNull();++ // And the account row itself can now actually be deleted, which the+ // pre-migration granted_by foreign key made impossible.+ await expect(sql`delete from users where id = ${owner.id}`).resolves.toBeDefined();+ created.users = created.users.filter((id) => id !== owner.id);+ });++ it('the purge deletes rows past a home\'s window and nothing else', async () => {+ await setup();+ const owner = await makeUser('purge');+ const short = await makeHome(owner.id, 'Seven day window');+ const long = await makeHome(owner.id, 'Default window');++ await sql`update home_connections set action_log_retention_days = 7 where id = ${short}`;++ // Two old rows and one new one in the short-window home; one old row in the+ // default-window home, which is inside its 90 days and must survive.+ await sql`insert into home_action_log (home_id, actor, channel, action, outcome, created_at)+ values (${short}, 'agent', 'websocket', 'light.turn_off', 'ok', now() - interval '30 days'),+ (${short}, 'agent', 'websocket', 'light.turn_on', 'ok', now() - interval '8 days'),+ (${short}, 'agent', 'websocket', 'light.turn_on', 'ok', now() - interval '1 day'),+ (${long}, 'agent', 'websocket', 'light.turn_on', 'ok', now() - interval '30 days')`;++ const beforeShort = await privacy.countHomeRows(short);+ const beforeLong = await privacy.countHomeRows(long);+ expect(beforeShort.home_action_log).toBe(3);+ expect(beforeLong.home_action_log).toBe(1);++ const swept = await privacy.purgeExpiredActionLog();+ expect(swept.deleted).toBeGreaterThanOrEqual(2);++ const afterShort = await privacy.countHomeRows(short);+ const afterLong = await privacy.countHomeRows(long);+ expect(afterShort.home_action_log, 'only the row inside the 7 day window survives').toBe(1);+ expect(afterLong.home_action_log, 'a 30 day old row is inside the 90 day default').toBe(1);++ // Idempotent: nothing left to take.+ const again = await privacy.purgeExpiredActionLog();+ const afterAgain = await privacy.countHomeRows(short);+ expect(afterAgain.home_action_log).toBe(1);+ expect(again.homes).toBe(0);+ });++ it('shortening retention applies immediately, and lengthening needs a reason', async () => {+ await setup();+ const owner = await makeUser('control');+ const homeId = await makeHome(owner.id, 'Retention control');+ await sql`insert into home_action_log (home_id, actor, channel, action, outcome, created_at)+ values (${homeId}, 'agent', 'websocket', 'light.turn_on', 'ok', now() - interval '10 days')`;++ const tooLong = await privacy.setActionLogRetention({ homeId, userId: owner.id, days: 365 });+ expect(tooLong.ok).toBe(false);+ expect(tooLong.code).toBe('reason_required');++ const withReason = await privacy.setActionLogRetention({+ homeId,+ userId: owner.id,+ days: 365,+ reason: 'Building operator: incident records are kept for one year.',+ });+ expect(withReason.ok).toBe(true);++ const shortened = await privacy.setActionLogRetention({ homeId, userId: owner.id, days: 1 });+ expect(shortened.ok).toBe(true);+ expect(shortened.purged, 'a 10 day old row must be gone the moment the window becomes 1 day').toBe(1);+ const counts = await privacy.countHomeRows(homeId);+ expect(counts.home_action_log).toBe(0);++ // Out of bounds is refused by the module before it reaches the constraint.+ const absurd = await privacy.setActionLogRetention({ homeId, userId: owner.id, days: 99_999, reason: 'forever please' });+ expect(absurd.ok).toBe(false);+ expect(absurd.code).toBe('bad_retention_days');++ // Somebody else's home is not yours to configure.+ const stranger = await makeUser('stranger2');+ const denied = await privacy.setActionLogRetention({ homeId, userId: stranger.id, days: 30 });+ expect(denied.ok).toBe(false);+ expect(denied.code).toBe('not_found');+ });++ it('the export carries every inventory row and never the credential', async () => {+ await setup();+ const owner = await makeUser('export');+ const homeId = await makeHome(owner.id, 'Exported');+ await sql`insert into home_entity_grants (home_id, entity_id, granted_by) values (${homeId}, ${'lock.front_door'}, ${owner.id})`;+ await sql`insert into home_action_log (home_id, user_id, actor, channel, action, entity_ids, outcome)+ values (${homeId}, ${owner.id}, 'user', 'websocket', 'light.turn_on', ${['light.kitchen']}, 'ok')`;++ const data = await privacy.exportHomeData(owner.id);+ expect(Object.keys(data).sort()).toEqual([+ 'action_log', 'confirmations', 'generated_at', 'grants', 'homes_you_own',+ 'inventory', 'invites', 'members', 'memberships', 'notice',+ ]);+ expect(data.homes_you_own).toHaveLength(1);+ expect(data.grants).toHaveLength(1);+ expect(data.action_log).toHaveLength(1);+ expect(data.inventory).toEqual(INVENTORY);++ const serialized = JSON.stringify(data);+ expect(serialized, 'the export must never carry a credential column').not.toContain('access_token_enc');+ expect(data.homes_you_own[0].token_fingerprint, 'the fingerprint proves which token without being usable').toBeTruthy();+ });+});diff --git a/tests/home-roles.test.js b/tests/home-roles.test.jsnew file mode 100644index 000000000..7308f6047--- /dev/null+++ b/tests/home-roles.test.js@@ -0,0 +1,606 @@+// The household role matrix, asserted cell by cell against a real database.+//+// Order 12's role table is a product decision with a physical actuator on the+// other end of it, so it is not documented in a comment and hoped for: every+// cell in it is executed here, at the enforcement boundary the product calls,+// with real rows in real tables.+//+// What "enforcement boundary" means concretely: nothing in these tests asks a+// role question of a UI, a fixture or a stub. `requireMembership` is the call+// every surface makes (the store's reads, the runtime's acquire, the graph+// projection, the physical-action gate, the confirm endpoint, the grant, layout,+// invite and disconnect writers, and the chat and MCP tools acting for a bearer+// principal), so the matrix is asserted through it once and the surfaces above+// inherit it.+//+// The row that matters most, and the reason this file exists:+//+// a guest is REFUSED a confirmation, with a reason naming their role,+// rather than being shown a confirmation prompt they could say yes to.+//+// Requires DATABASE_URL. Every row it writes is prefixed and deleted afterwards,+// and the same prefix is swept before the run so a crashed previous run cannot+// leave anything behind.++import { afterAll, beforeAll, describe, expect, it } from 'vitest';++import '../tests/setup.env.js';++const HAS_DB = Boolean(process.env.DATABASE_URL);+const d = HAS_DB ? describe : describe.skip;++const PREFIX = 'home-roles-test';+const email = (who) => `${PREFIX}+${who}@example.invalid`;++/** The order 12 table, transcribed. Rows are roles, columns are capabilities. */+const EXPECTED = {+ owner: { read: true, act: true, confirm: true, grant: true, layout: true, invite: true, disconnect: true },+ admin: { read: true, act: true, confirm: true, grant: true, layout: true, invite: true, disconnect: false },+ member: { read: true, act: true, confirm: true, grant: false, layout: true, invite: false, disconnect: false },+ guest: { read: true, act: true, confirm: false, grant: false, layout: false, invite: false, disconnect: false },+ viewer: { read: true, act: false, confirm: false, grant: false, layout: false, invite: false, disconnect: false },+};++/** Roles whose reads and actions are narrowed by entity_scope. */+const SCOPED = new Set(['guest', 'viewer']);++let sql;+let members;+let store;+let users = {};+let homeId;+let otherHomeId;++async function makeUser(who) {+ const [row] = await sql`+ INSERT INTO users (email, display_name)+ VALUES (${email(who)}, ${`${PREFIX} ${who}`})+ RETURNING id+ `;+ return row.id;+}++async function sweep() {+ await sql`DELETE FROM home_connections WHERE label LIKE ${`${PREFIX}%`}`;+ await sql`DELETE FROM users WHERE email LIKE ${`${PREFIX}+%`}`;+}++beforeAll(async () => {+ if (!HAS_DB) return;+ ({ sql } = await import('../api/_lib/db.js'));+ members = await import('../api/_lib/home/members.js');+ store = await import('../api/_lib/home/store.js');++ await sweep();++ for (const who of ['owner', 'admin', 'member', 'guest', 'viewer', 'stranger', 'second']) {+ users[who] = await makeUser(who);+ }++ // Two homes: the one under test, and a second one owned by a stranger, so+ // "this member cannot see that home" is asserted against a real other house+ // rather than a made-up id.+ const [home] = await sql`+ INSERT INTO home_connections (user_id, label, base_url, access_token_enc, token_fingerprint, status)+ VALUES (${users.owner}, ${`${PREFIX} house`}, ${`https://${PREFIX}-1.invalid`}, '', ${`${PREFIX}-1`}, 'connected')+ RETURNING id+ `;+ homeId = home.id;++ const [other] = await sql`+ INSERT INTO home_connections (user_id, label, base_url, access_token_enc, token_fingerprint, status)+ VALUES (${users.stranger}, ${`${PREFIX} other house`}, ${`https://${PREFIX}-2.invalid`}, '', ${`${PREFIX}-2`}, 'connected')+ RETURNING id+ `;+ otherHomeId = other.id;++ // The owner row is not inserted here on purpose: the migration's trigger owns+ // it, and the first assertion below is that the trigger did its job.+ for (const role of ['admin', 'member']) {+ await sql`INSERT INTO home_members (home_id, user_id, role, invited_by) VALUES (${homeId}, ${users[role]}, ${role}, ${users.owner})`;+ }+ for (const role of ['guest', 'viewer']) {+ await sql`+ INSERT INTO home_members (home_id, user_id, role, entity_scope, invited_by)+ VALUES (${homeId}, ${users[role]}, ${role}, ${'{"mode":"allow","areas":["kitchen"],"entities":["light.hall_lamp"]}'}::jsonb, ${users.owner})+ `;+ }+}, 120_000);++afterAll(async () => {+ if (!HAS_DB) return;+ await sweep();+});++d('home_members: the backfill and the ownership invariant', () => {+ it('gives every connection exactly one owner row, created by the database', async () => {+ const [row] = await sql`SELECT user_id, role FROM home_members WHERE home_id = ${homeId} AND role = 'owner'`;+ expect(row).toBeTruthy();+ expect(row.user_id).toBe(users.owner);++ const [{ owners }] = await sql`SELECT count(*)::int AS owners FROM home_members WHERE home_id = ${homeId} AND role = 'owner'`;+ expect(owners).toBe(1);+ });++ it('holds the one-owner-per-home invariant against a second owner insert', async () => {+ await expect(+ sql`INSERT INTO home_members (home_id, user_id, role) VALUES (${homeId}, ${users.second}, 'owner')`,+ ).rejects.toMatchObject({ code: '23505' });+ });++ it('leaves no connection in the database without an owner row', async () => {+ const [{ orphans }] = await sql`+ SELECT count(*)::int AS orphans+ FROM home_connections c+ WHERE NOT EXISTS (SELECT 1 FROM home_members m WHERE m.home_id = c.id AND m.role = 'owner')+ `;+ expect(orphans).toBe(0);+ });+});++d('the role matrix, every cell, at the enforcement boundary', () => {+ for (const [role, expected] of Object.entries(EXPECTED)) {+ for (const [capability, allowed] of Object.entries(expected)) {+ it(`${role} ${allowed ? 'may' : 'may NOT'} ${capability}`, async () => {+ const gate = await members.requireMembership(homeId, users[role], capability);+ expect(gate.ok).toBe(allowed);+ if (!allowed) {+ // A member who lacks a capability is told so, and told which role+ // they hold. 403 and not 404: they are in the household, and+ // pretending the house does not exist would be a worse answer.+ expect(gate.status).toBe(403);+ expect(gate.code).toBe('role_forbidden');+ expect(gate.reason).toContain(role);+ expect(gate.reason).toContain(capability);+ } else {+ expect(gate.role).toBe(role);+ }+ });+ }+ }++ it('marks exactly the scoped roles as scoped', async () => {+ for (const role of Object.keys(EXPECTED)) {+ const gate = await members.requireMembership(homeId, users[role], 'read');+ expect(gate.membership.scoped).toBe(SCOPED.has(role));+ if (!SCOPED.has(role)) expect(gate.membership.scope).toEqual({ mode: 'all' });+ }+ });++ it('refuses every capability to a non-member with 404, never 403', async () => {+ for (const capability of members.HOME_CAPABILITIES) {+ const gate = await members.requireMembership(homeId, users.stranger, capability);+ expect(gate.ok).toBe(false);+ expect(gate.status).toBe(404);+ expect(gate.code).toBe('home_not_found');+ expect(gate.reason).not.toContain('role');+ }+ });++ it('refuses a member of one home every capability on another home, with 404', async () => {+ for (const capability of members.HOME_CAPABILITIES) {+ const gate = await members.requireMembership(otherHomeId, users.member, capability);+ expect(gate.status).toBe(404);+ }+ });++ it('drops every member to 404 the moment the home is revoked', async () => {+ const [tmp] = await sql`+ INSERT INTO home_connections (user_id, label, base_url, access_token_enc, token_fingerprint, status)+ VALUES (${users.owner}, ${`${PREFIX} temp`}, ${`https://${PREFIX}-3.invalid`}, '', ${`${PREFIX}-3`}, 'connected')+ RETURNING id+ `;+ expect((await members.requireMembership(tmp.id, users.owner, 'read')).ok).toBe(true);+ await sql`UPDATE home_connections SET revoked_at = now() WHERE id = ${tmp.id}`;+ const after = await members.requireMembership(tmp.id, users.owner, 'read');+ expect(after.status).toBe(404);+ await sql`DELETE FROM home_connections WHERE id = ${tmp.id}`;+ });+});++d('the guest refusal: a house sitter can turn on a light and cannot open a door', () => {+ it('refuses a guest a confirmation with a role reason, not a prompt', async () => {+ const act = await members.requireMembership(homeId, users.guest, 'act');+ expect(act.ok).toBe(true);++ const confirm = await members.requireMembership(homeId, users.guest, 'confirm');+ expect(confirm.ok).toBe(false);+ expect(confirm.status).toBe(403);+ expect(confirm.code).toBe('role_forbidden');+ expect(confirm.role).toBe('guest');+ expect(confirm.capability).toBe('confirm');+ expect(confirm.reason).toBe('the guest role cannot confirm in this home');+ // The refusal carries no confirmation affordance of any kind: there is no+ // token, no prompt and no pending id a client could echo back.+ expect(Object.keys(confirm)).not.toContain('confirmation');+ expect(Object.keys(confirm)).not.toContain('confirm_token');+ });++ it('refuses a guest a standing allowance, so they cannot grant their way past the gate', async () => {+ const grant = await members.requireMembership(homeId, users.guest, 'grant');+ expect(grant.ok).toBe(false);+ expect(grant.status).toBe(403);+ });++ it('lets a member confirm: a member lives here, a guest is visiting', async () => {+ expect((await members.requireMembership(homeId, users.member, 'confirm')).ok).toBe(true);+ });+});++d('entity scope: enforced in the projection, never in the UI', () => {+ // A house with two rooms and an unassigned entity. The guest above was given+ // the kitchen as an area and one hall lamp as an individual entity.+ const graph = {+ floors: [+ { id: 'ground', name: 'Ground', level: 0 },+ { id: 'upstairs', name: 'Upstairs', level: 1 },+ ],+ rooms: [+ {+ id: 'kitchen',+ name: 'Kitchen',+ floorId: 'ground',+ entities: [+ { entityId: 'light.kitchen_ceiling', domain: 'light', areaId: 'kitchen', name: 'Ceiling', state: 'on', attributes: { brightness: 200 } },+ { entityId: 'lock.back_door', domain: 'lock', areaId: 'kitchen', name: 'Back door', state: 'locked', attributes: {} },+ ],+ lighting: { total: 1, on: 1 },+ climate: null,+ secured: true,+ },+ {+ id: 'hall',+ name: 'Hall',+ floorId: 'ground',+ entities: [+ { entityId: 'light.hall_lamp', domain: 'light', areaId: 'hall', name: 'Hall lamp', state: 'off', attributes: {} },+ { entityId: 'light.hall_spots', domain: 'light', areaId: 'hall', name: 'Hall spots', state: 'on', attributes: { brightness: 255 } },+ { entityId: 'lock.front_door', domain: 'lock', areaId: 'hall', name: 'Front door', state: 'locked', attributes: {} },+ ],+ lighting: { total: 2, on: 1 },+ climate: null,+ secured: true,+ },+ {+ id: 'bedroom',+ name: 'Bedroom',+ floorId: 'upstairs',+ entities: [{ entityId: 'light.bedside', domain: 'light', areaId: 'bedroom', name: 'Bedside', state: 'on', attributes: {} }],+ lighting: { total: 1, on: 1 },+ climate: null,+ secured: null,+ },+ ],+ unassigned: [{ entityId: 'sensor.outside_temp', domain: 'sensor', areaId: null, name: 'Outside', state: '11', attributes: {} }],+ };++ it('gives an unscoped role the whole house, untouched', async () => {+ const gate = await members.requireMembership(homeId, users.member, 'read');+ const filtered = members.filterGraphForScope(graph, gate.scope);+ expect(filtered).toBe(graph);+ });++ it('removes an out-of-scope room from a guest entirely, name included', async () => {+ const gate = await members.requireMembership(homeId, users.guest, 'read');+ const filtered = members.filterGraphForScope(graph, gate.scope);++ const roomIds = filtered.rooms.map((r) => r.id);+ expect(roomIds).toContain('kitchen');+ expect(roomIds).toContain('hall');+ expect(roomIds).not.toContain('bedroom');++ // The whole serialized payload must not carry the room's name or any of+ // its entity ids. This is the assertion that would fail if the filtering+ // were a `visible: false` flag rather than a removal.+ const wire = JSON.stringify(filtered);+ expect(wire).not.toContain('Bedroom');+ expect(wire).not.toContain('light.bedside');+ });++ it('narrows a partially granted room to the granted entity and recomputes its rollups', async () => {+ const gate = await members.requireMembership(homeId, users.guest, 'read');+ const filtered = members.filterGraphForScope(graph, gate.scope);++ const hall = filtered.rooms.find((r) => r.id === 'hall');+ expect(hall.entities.map((e) => e.entityId)).toEqual(['light.hall_lamp']);+ // The unfiltered hall has two lights, one of them on, and a front door.+ // Reporting that rollup to somebody who can see one lamp would disclose+ // the state of the entities the filtering just removed.+ expect(hall.lighting.total).toBe(1);+ expect(hall.lighting.on).toBe(0);+ expect(JSON.stringify(hall)).not.toContain('lock.front_door');+ });++ it('keeps a wholly granted room intact, rollups and all', async () => {+ const gate = await members.requireMembership(homeId, users.guest, 'read');+ const kitchen = members.filterGraphForScope(graph, gate.scope).rooms.find((r) => r.id === 'kitchen');+ expect(kitchen.entities.map((e) => e.entityId)).toEqual(['light.kitchen_ceiling', 'lock.back_door']);+ });++ it('removes a floor that has no visible room, because the floor list is the shape of the building', async () => {+ const gate = await members.requireMembership(homeId, users.guest, 'read');+ const filtered = members.filterGraphForScope(graph, gate.scope);+ expect(filtered.floors.map((f) => f.id)).toEqual(['ground']);+ });++ it('drops unassigned entities that were never granted', async () => {+ const gate = await members.requireMembership(homeId, users.viewer, 'read');+ const filtered = members.filterGraphForScope(graph, gate.scope);+ expect(filtered.unassigned).toEqual([]);+ });++ it('names every out-of-scope target of a resolved action', async () => {+ const gate = await members.requireMembership(homeId, users.guest, 'act');+ const refused = members.outOfScopeEntities(gate.scope, [+ { entityId: 'light.hall_lamp', areaId: 'hall' },+ { entityId: 'light.kitchen_ceiling', areaId: 'kitchen' },+ { entityId: 'light.bedside', areaId: 'bedroom' },+ ]);+ expect(refused).toEqual(['light.bedside']);+ });++ it('normalizes a scoped role back to the whole house when it is promoted', () => {+ const stale = { mode: 'allow', areas: ['kitchen'], entities: [] };+ expect(members.normalizeScope(stale, 'guest')).toEqual({ mode: 'allow', areas: ['kitchen'], entities: [] });+ expect(members.normalizeScope(stale, 'member')).toEqual({ mode: 'all' });+ });+});++d('roster administration', () => {+ it('lets the owner manage everyone below, and never the owner row', () => {+ expect(members.canManageMember('owner', 'admin')).toBe(true);+ expect(members.canManageMember('owner', 'viewer')).toBe(true);+ expect(members.canManageMember('owner', 'owner')).toBe(false);+ expect(members.canManageMember('admin', 'owner')).toBe(false);+ });++ it('lets an admin add a peer admin and never remove one', () => {+ expect(members.canAssignRole('admin', 'admin')).toBe(true);+ expect(members.canManageMember('admin', 'admin')).toBe(false);+ expect(members.canManageMember('admin', 'member')).toBe(true);+ });++ it('never assigns ownership', () => {+ for (const role of members.HOME_ROLES) expect(members.canAssignRole(role, 'owner')).toBe(false);+ expect(members.ASSIGNABLE_ROLES).not.toContain('owner');+ });++ it('gives a member and a guest no roster authority at all', () => {+ for (const actor of ['member', 'guest', 'viewer']) {+ expect(members.canManageMember(actor, 'viewer')).toBe(false);+ expect(members.canAssignRole(actor, 'viewer')).toBe(false);+ }+ });++ it('widens a promoted guest to the whole house in the same statement', async () => {+ const before = await members.resolveMembership(homeId, users.guest);+ expect(before.scope.mode).toBe('allow');++ const promoted = await members.setMemberRole({ homeId, userId: users.guest, role: 'member', scope: before.scope });+ expect(promoted.role).toBe('member');+ expect(promoted.scope).toEqual({ mode: 'all' });++ const restored = await members.setMemberRole({ homeId, userId: users.guest, role: 'guest', scope: before.scope });+ expect(restored.scope).toEqual(before.scope);+ });++ it('refuses to change the owner row', async () => {+ expect(await members.setMemberRole({ homeId, userId: users.owner, role: 'member' })).toBeNull();+ const still = await members.resolveMembership(homeId, users.owner);+ expect(still.role).toBe('owner');+ });+});++d('removing a member revokes their standing allowances in the same transaction', () => {+ it('deletes the grants they authorised and leaves everyone else alone', async () => {+ await sql`INSERT INTO home_members (home_id, user_id, role, invited_by) VALUES (${homeId}, ${users.second}, 'admin', ${users.owner})`;+ await sql`+ INSERT INTO home_entity_grants (home_id, entity_id, granted_by)+ VALUES (${homeId}, 'lock.office_door', ${users.second}), (${homeId}, 'cover.garage', ${users.second}), (${homeId}, 'lock.front_door', ${users.owner})+ `;++ const before = await sql`SELECT entity_id, granted_by FROM home_entity_grants WHERE home_id = ${homeId} ORDER BY entity_id`;+ expect(before.map((r) => r.entity_id)).toEqual(['cover.garage', 'lock.front_door', 'lock.office_door']);++ const result = await members.removeMember({ homeId, userId: users.second });+ expect(result.removed).toBe(true);+ expect(result.grantsRevoked).toEqual(['cover.garage', 'lock.office_door']);++ const after = await sql`SELECT entity_id, granted_by FROM home_entity_grants WHERE home_id = ${homeId} ORDER BY entity_id`;+ expect(after.map((r) => r.entity_id)).toEqual(['lock.front_door']);+ expect(after[0].granted_by).toBe(users.owner);++ expect(await members.resolveMembership(homeId, users.second)).toBeNull();+ await sql`DELETE FROM home_entity_grants WHERE home_id = ${homeId}`;+ });++ it('refuses to remove the owner, so a home is never left ownerless', async () => {+ const result = await members.removeMember({ homeId, userId: users.owner });+ expect(result.removed).toBe(false);+ expect((await members.resolveMembership(homeId, users.owner)).role).toBe('owner');+ });++ it('reaches every household when an identity is deprovisioned', async () => {+ await sql`INSERT INTO home_members (home_id, user_id, role, invited_by) VALUES (${homeId}, ${users.second}, 'member', ${users.owner})`;+ await sql`INSERT INTO home_members (home_id, user_id, role, invited_by) VALUES (${otherHomeId}, ${users.second}, 'guest', ${users.stranger})`;+ await sql`INSERT INTO home_entity_grants (home_id, entity_id, granted_by) VALUES (${homeId}, 'lock.side_gate', ${users.second})`;++ const result = await members.revokeAllMemberships(users.second);+ expect(result.removedFrom.sort()).toEqual([homeId, otherHomeId].sort());+ expect(await members.resolveMembership(homeId, users.second)).toBeNull();+ expect(await members.resolveMembership(otherHomeId, users.second)).toBeNull();++ const [{ left }] = await sql`SELECT count(*)::int AS left FROM home_entity_grants WHERE granted_by = ${users.second}`;+ expect(left).toBe(0);+ });+});++d('invitations are single use and they expire', () => {+ it('admits exactly one holder and refuses the second attempt', async () => {+ const invite = await members.createInvite({+ homeId,+ email: email('invitee'),+ role: 'guest',+ scope: { mode: 'allow', areas: ['kitchen'], entities: [] },+ invitedBy: users.owner,+ });+ expect(invite.token).toBeTruthy();++ const first = await members.acceptInvite({ token: invite.token, userId: users.second });+ expect(first.ok).toBe(true);+ expect(first.membership.role).toBe('guest');+ expect(first.membership.scope).toEqual({ mode: 'allow', areas: ['kitchen'], entities: [] });++ const second = await members.acceptInvite({ token: invite.token, userId: users.stranger });+ expect(second.ok).toBe(false);+ expect(second.code).toBe('invite_spent');+ expect(await members.resolveMembership(homeId, users.stranger)).toBeNull();++ await members.removeMember({ homeId, userId: users.second });+ });++ it('refuses an expired invitation', async () => {+ const invite = await members.createInvite({+ homeId,+ email: email('expired'),+ role: 'viewer',+ invitedBy: users.owner,+ ttlMs: -1000,+ });+ const attempt = await members.acceptInvite({ token: invite.token, userId: users.second });+ expect(attempt.ok).toBe(false);+ expect(attempt.code).toBe('invite_expired');+ expect(await members.resolveMembership(homeId, users.second)).toBeNull();+ });++ it('refuses a withdrawn invitation', async () => {+ const invite = await members.createInvite({ homeId, email: email('withdrawn'), role: 'viewer', invitedBy: users.owner });+ expect(await members.revokeInvite({ homeId, inviteId: invite.id })).toBe(true);+ const attempt = await members.acceptInvite({ token: invite.token, userId: users.second });+ expect(attempt.code).toBe('invite_revoked');+ });++ it('stores the token as a hash and never in plaintext', async () => {+ const invite = await members.createInvite({ homeId, email: email('hashed'), role: 'viewer', invitedBy: users.owner });+ const [row] = await sql`SELECT token_hash FROM home_invites WHERE id = ${invite.id}`;+ expect(row.token_hash).not.toBe(invite.token);+ expect(row.token_hash).toMatch(/^[0-9a-f]{64}$/);+ const [{ hits }] = await sql`SELECT count(*)::int AS hits FROM home_invites WHERE token_hash = ${invite.token}`;+ expect(hits).toBe(0);+ await members.revokeInvite({ homeId, inviteId: invite.id });+ });++ it('replaces an outstanding invitation to the same address rather than stacking a second key', async () => {+ const first = await members.createInvite({ homeId, email: email('replaced'), role: 'viewer', invitedBy: users.owner });+ const second = await members.createInvite({ homeId, email: email('replaced'), role: 'member', invitedBy: users.owner });++ expect((await members.acceptInvite({ token: first.token, userId: users.second })).code).toBe('invite_revoked');+ const accepted = await members.acceptInvite({ token: second.token, userId: users.second });+ expect(accepted.ok).toBe(true);+ expect(accepted.membership.role).toBe('member');++ await members.removeMember({ homeId, userId: users.second });+ });++ it('never lets an invitation hand out ownership', async () => {+ await expect(members.createInvite({ homeId, email: email('usurper'), role: 'owner', invitedBy: users.owner })).rejects.toThrow(/invalid invite role/);+ });++ it('keeps the role an existing member already holds', async () => {+ const invite = await members.createInvite({ homeId, email: email('admin'), role: 'viewer', invitedBy: users.owner });+ const result = await members.acceptInvite({ token: invite.token, userId: users.admin });+ expect(result.ok).toBe(true);+ expect(result.alreadyMember).toBe(true);+ expect((await members.resolveMembership(homeId, users.admin)).role).toBe('admin');+ });++ it('lists outstanding invitations without ever returning a token', async () => {+ const invite = await members.createInvite({ homeId, email: email('listed'), role: 'guest', invitedBy: users.owner });+ const list = await members.listInvites(homeId);+ const found = list.find((i) => i.id === invite.id);+ expect(found).toBeTruthy();+ expect(found.token).toBeUndefined();+ expect(JSON.stringify(list)).not.toContain(invite.token);+ await members.revokeInvite({ homeId, inviteId: invite.id });+ });+});++d('the action log attributes every action to the member who acted', () => {+ it('records two members acting on one home under their own ids', async () => {+ for (const who of ['admin', 'member']) {+ const gate = await members.requireMembership(homeId, users[who], 'act');+ expect(gate.ok).toBe(true);+ // The acting member id is the one the gate resolved, never the+ // connection's owner. This is the value every call site above (the+ // runtime, the gate, the chat and MCP tools) must pass through.+ const landed = await store.logHomeActionNow({+ homeId,+ userId: gate.membership.userId,+ actor: 'user',+ channel: 'websocket',+ action: 'light.turn_on',+ entityIds: ['light.kitchen_ceiling'],+ outcome: 'ok',+ });+ expect(landed).toBe(true);+ }++ const rows = await sql`+ SELECT user_id, action FROM home_action_log+ WHERE home_id = ${homeId} AND action = 'light.turn_on'+ ORDER BY created_at ASC+ `;+ expect(rows.map((r) => r.user_id).sort()).toEqual([users.admin, users.member].sort());+ expect(rows.map((r) => r.user_id)).not.toContain(users.owner);+ });++ it('records a guest refusal against the guest, with the gate verdict', async () => {+ const gate = await members.requireMembership(homeId, users.guest, 'confirm');+ expect(gate.ok).toBe(false);+ await store.logHomeActionNow({+ homeId,+ userId: gate.membership.userId,+ actor: 'user',+ channel: 'websocket',+ action: 'lock.unlock',+ entityIds: ['lock.front_door'],+ guarded: true,+ risk: 'security',+ outcome: 'refused',+ detail: { reason: gate.code, role: gate.role },+ });++ const [row] = await sql`+ SELECT user_id, guarded, risk, outcome, confirmed_by, detail+ FROM home_action_log WHERE home_id = ${homeId} AND action = 'lock.unlock'+ `;+ expect(row.user_id).toBe(users.guest);+ expect(row.guarded).toBe(true);+ expect(row.outcome).toBe('refused');+ // Nobody confirmed it, and the row says so. A refused guarded action with+ // a confirmed_by would be the audit trail lying about who opened a door.+ expect(row.confirmed_by).toBeNull();+ expect(row.detail.role).toBe('guest');+ });+});++d('listing homes resolves through membership, not through ownership', () => {+ it('shows a member the home they were invited to, with the role they hold', async () => {+ const listed = await members.listMembershipHomes(users.viewer);+ const found = listed.find((h) => h.home_id === homeId);+ expect(found).toBeTruthy();+ expect(found.role).toBe('viewer');+ expect(found.label).toBe(`${PREFIX} house`);+ });++ it('shows a stranger nothing of a home they are not in', async () => {+ const listed = await members.listMembershipHomes(users.stranger);+ expect(listed.map((h) => h.home_id)).not.toContain(homeId);+ expect(listed.map((h) => h.home_id)).toContain(otherHomeId);+ });++ it('never returns a credential column on a membership listing', async () => {+ const listed = await members.listMembershipHomes(users.owner);+ for (const row of listed) expect(Object.keys(row)).not.toContain('access_token_enc');+ });+});diff --git a/tests/home-runtime.test.js b/tests/home-runtime.test.jsnew file mode 100644index 000000000..0deda65d1--- /dev/null+++ b/tests/home-runtime.test.js@@ -0,0 +1,580 @@+// The bridge runtime's pool, proved without a network.+//+// Every test here builds its OWN runtime through `createHomeRuntime` with a+// counting bridge factory and a controllable clock. Nothing touches the module's+// process-wide singleton, so these tests cannot leak pool state into each other+// and a failure names one behaviour rather than one ordering.+//+// What is deliberately NOT faked: Home Assistant itself. The live proof that a+// real socket is reused across two `withHome` calls lives in+// tests/home-runtime-live.test.js against a real instance. What is faked here is+// the bridge, because refcounting, idle eviction, the connection cap and the+// circuit breaker are exactly the paths a real house cannot be made to exercise+// on demand: you cannot ask a working Home Assistant to fail its next five+// connects at a chosen millisecond.++import { beforeEach, describe, expect, it, vi } from 'vitest';++import { createHomeRuntime, HOME_RUNTIME_ERR } from '../api/_lib/home/runtime.js';+import { HOME_STATUS } from '../api/_lib/home/store.js';++const HOME_ID = '11111111-1111-4111-8111-111111111111';+const OTHER_HOME_ID = '22222222-2222-4222-8222-222222222222';+const USER_ID = '33333333-3333-4333-8333-333333333333';++/** A room graph with something in it, so "the graph was emptied" is visible. */+const LIVE_GRAPH = Object.freeze({+ floors: [{ id: 'ground', name: 'Ground floor' }],+ rooms: [{ id: 'kitchen', name: 'Kitchen', entities: ['light.kitchen'] }],+ unassigned: [],+});++/**+ * A bridge that behaves like the real one at its seams (connect resolves with a+ * graph, `on` returns an unsubscribe, close is idempotent) and lets a test drive+ * the events a real house would send.+ */+function makeFakeBridge(options, behaviour = {}) {+ const listeners = new Map();+ const bridge = {+ options,+ connected: false,+ closed: false,+ closeCount: 0,+ connectCount: 0,+ graph: LIVE_GRAPH,+ states: { 'light.kitchen': { state: 'on', attributes: {} } },+ haVersion: '2026.9.0',+ on(event, handler) {+ if (!listeners.has(event)) listeners.set(event, new Set());+ listeners.get(event).add(handler);+ return () => listeners.get(event)?.delete(handler);+ },+ emit(event, payload) {+ for (const handler of listeners.get(event) || []) handler(payload);+ },+ async connect() {+ bridge.connectCount += 1;+ if (behaviour.stall) await new Promise(() => {});+ if (behaviour.failWith) throw behaviour.failWith();+ bridge.connected = true;+ return bridge.graph;+ },+ close() {+ bridge.closed = true;+ bridge.closeCount += 1;+ bridge.connected = false;+ },+ };+ return bridge;+}++/** A factory that records every bridge it built, which is how socket reuse is counted. */+function countingFactory(behaviour = {}) {+ const built = [];+ const factory = (options) => {+ const bridge = makeFakeBridge(options, behaviour);+ built.push(bridge);+ return bridge;+ };+ factory.built = built;+ return factory;+}++/** A clock a test moves by hand, so eviction is asserted at its boundary rather than waited out. */+function fakeClock(start = 1_000_000) {+ let t = start;+ return {+ now: () => t,+ advance(ms) {+ t += ms;+ return t;+ },+ };+}++/** The store, reduced to the four reads the runtime actually performs. */+function storeDeps(overrides = {}) {+ const handshakes = [];+ const deps = {+ getConnection: vi.fn(async (id, userId) =>+ userId === USER_ID && (id === HOME_ID || id === OTHER_HOME_ID)+ ? { id, user_id: userId, label: 'Home', base_url: 'https://home.example.com', status: HOME_STATUS.CONNECTED }+ : null,+ ),+ getDecryptedToken: vi.fn(async (id) => ({+ token: 'llat-token',+ baseUrl: 'https://home.example.com',+ transport: 'direct',+ relayId: null,+ fingerprint: `fp-${id}`,+ })),+ listAllowedEntities: vi.fn(async () => ['lock.office_door']),+ recordHandshake: vi.fn(async (id, update) => {+ handshakes.push({ id, ...update });+ return null;+ }),+ ...overrides,+ };+ deps.handshakes = handshakes;+ return deps;+}++describe('home runtime: the pool reuses one socket', () => {+ it('opens exactly one connection for two sequential withHome calls', async () => {+ const createBridge = countingFactory();+ const runtime = createHomeRuntime({ createBridge, ...storeDeps() });++ const first = await runtime.withHome(HOME_ID, USER_ID, (bridge) => bridge.graph.rooms.length);+ const second = await runtime.withHome(HOME_ID, USER_ID, (bridge) => bridge.graph.rooms.length);++ expect(first).toBe(1);+ expect(second).toBe(1);+ // The whole point of the pool: the second call rode the first socket.+ expect(createBridge.built).toHaveLength(1);+ expect(createBridge.built[0].connectCount).toBe(1);+ expect(runtime.stats().open).toBe(1);+ runtime.closeAll();+ });++ it('passes the home standing grants to the bridge, so the gate knows what is pre-approved', async () => {+ const createBridge = countingFactory();+ const deps = storeDeps();+ const runtime = createHomeRuntime({ createBridge, ...deps });++ await runtime.withHome(HOME_ID, USER_ID, () => null);++ expect(deps.listAllowedEntities).toHaveBeenCalledWith(HOME_ID);+ expect(createBridge.built[0].options.allowedEntities).toEqual(['lock.office_door']);+ runtime.closeAll();+ });++ it('opens a separate connection per home', async () => {+ const createBridge = countingFactory();+ const runtime = createHomeRuntime({ createBridge, ...storeDeps() });++ await runtime.withHome(HOME_ID, USER_ID, () => null);+ await runtime.withHome(OTHER_HOME_ID, USER_ID, () => null);++ expect(createBridge.built).toHaveLength(2);+ expect(runtime.stats().open).toBe(2);+ runtime.closeAll();+ });++ it('shares one in-flight open between two concurrent acquires', async () => {+ const createBridge = countingFactory();+ const runtime = createHomeRuntime({ createBridge, ...storeDeps() });++ const [a, b] = await Promise.all([runtime.acquire(HOME_ID, USER_ID), runtime.acquire(HOME_ID, USER_ID)]);++ // A second caller arriving mid-open must not race a second socket to the+ // same house: that is two connections against one user's instance.+ expect(createBridge.built).toHaveLength(1);+ expect(a.bridge).toBe(b.bridge);+ a.release();+ b.release();+ runtime.closeAll();+ });+});++describe('home runtime: references are never leaked', () => {+ it('releases when the callback throws, so the socket becomes evictable', async () => {+ const createBridge = countingFactory();+ const clock = fakeClock();+ const runtime = createHomeRuntime({ createBridge, ...storeDeps(), now: clock.now, idleMs: 90_000 });++ await expect(+ runtime.withHome(HOME_ID, USER_ID, () => {+ throw new Error('the tool call blew up');+ }),+ ).rejects.toThrow('the tool call blew up');++ expect(runtime.stats().subscribers).toBe(0);+ // A held reference would survive this sweep. Being evicted IS the proof+ // that the refcount went back to zero.+ clock.advance(90_001);+ expect(runtime.evictIdle(clock.now())).toBe(1);+ expect(runtime.stats().open).toBe(0);+ expect(createBridge.built[0].closed).toBe(true);+ });++ it('is idempotent on release, so a double release cannot evict a live socket', async () => {+ const createBridge = countingFactory();+ const clock = fakeClock();+ const runtime = createHomeRuntime({ createBridge, ...storeDeps(), now: clock.now, idleMs: 1_000 });++ const first = await runtime.acquire(HOME_ID, USER_ID);+ const second = await runtime.acquire(HOME_ID, USER_ID);+ first.release();+ first.release();+ first.release();++ // `second` is still holding it. A double release that decremented twice+ // would drop the count to zero and evict a connection somebody is using.+ clock.advance(5_000);+ expect(runtime.evictIdle(clock.now())).toBe(0);+ expect(runtime.stats().open).toBe(1);++ second.release();+ clock.advance(5_000);+ expect(runtime.evictIdle(clock.now())).toBe(1);+ });++ it('drops the reference when a subscriber unsubscribes', async () => {+ const createBridge = countingFactory();+ const clock = fakeClock();+ const runtime = createHomeRuntime({ createBridge, ...storeDeps(), now: clock.now, idleMs: 1_000 });++ const events = [];+ const unsubscribe = await runtime.subscribe(HOME_ID, USER_ID, (event) => events.push(event));+ expect(runtime.stats().subscribers).toBe(1);++ clock.advance(5_000);+ expect(runtime.evictIdle(clock.now())).toBe(0);++ unsubscribe();+ unsubscribe();+ expect(runtime.stats().subscribers).toBe(0);+ clock.advance(5_000);+ expect(runtime.evictIdle(clock.now())).toBe(1);+ });+});++describe('home runtime: idle eviction at its boundary', () => {+ let createBridge;+ let clock;+ let runtime;++ beforeEach(async () => {+ createBridge = countingFactory();+ clock = fakeClock();+ runtime = createHomeRuntime({ createBridge, ...storeDeps(), now: clock.now, idleMs: 90_000 });+ const held = await runtime.acquire(HOME_ID, USER_ID);+ held.release();+ });++ it('keeps a connection one millisecond before the window closes', () => {+ clock.advance(89_999);+ expect(runtime.evictIdle(clock.now())).toBe(0);+ expect(runtime.stats().open).toBe(1);+ expect(createBridge.built[0].closed).toBe(false);+ });++ it('closes it at the window', () => {+ clock.advance(90_000);+ expect(runtime.evictIdle(clock.now())).toBe(1);+ expect(runtime.stats().open).toBe(0);+ expect(createBridge.built[0].closed).toBe(true);+ });++ it('reopens on the next acquire, which is the normal cold path and not an error', async () => {+ clock.advance(90_001);+ runtime.evictIdle(clock.now());++ await runtime.withHome(HOME_ID, USER_ID, (bridge) => bridge.graph);++ expect(createBridge.built).toHaveLength(2);+ expect(runtime.stats().open).toBe(1);+ runtime.closeAll();+ });++ it('never evicts a connection that still has a holder', async () => {+ const held = await runtime.acquire(HOME_ID, USER_ID);+ clock.advance(10 * 90_000);+ expect(runtime.evictIdle(clock.now())).toBe(0);+ held.release();+ clock.advance(90_001);+ expect(runtime.evictIdle(clock.now())).toBe(1);+ });+});++describe('home runtime: the connection cap degrades latency, never correctness', () => {+ it('serves a request past the cap without admitting it to the pool', async () => {+ const createBridge = countingFactory();+ const runtime = createHomeRuntime({ createBridge, ...storeDeps(), maxConnections: 1 });++ const pooled = await runtime.acquire(HOME_ID, USER_ID);+ const overflow = await runtime.acquire(OTHER_HOME_ID, USER_ID);++ // The request is served: that is the correctness half.+ expect(overflow.bridge.connected).toBe(true);+ expect(runtime.stats().open).toBe(1);+ expect(runtime.stats().pooledCap).toBe(1);++ // And it closes the moment it is done, because nothing would ever evict it.+ overflow.release();+ expect(createBridge.built[1].closed).toBe(true);+ expect(createBridge.built[0].closed).toBe(false);++ pooled.release();+ runtime.closeAll();+ });+});++describe('home runtime: the circuit breaker', () => {+ function unreachableDeps() {+ return { ...storeDeps() };+ }++ it('opens after five consecutive failures and then fails fast', async () => {+ // A stalled connect is the expensive failure: without a breaker every page+ // load would wait out the full connect timeout.+ const createBridge = countingFactory({ stall: true });+ const deps = unreachableDeps();+ const runtime = createHomeRuntime({ createBridge, ...deps, connectTimeoutMs: 200 });++ for (let attempt = 1; attempt <= 5; attempt += 1) {+ await expect(runtime.acquire(HOME_ID, USER_ID)).rejects.toMatchObject({ code: 'unreachable' });+ }++ const startedAt = Date.now();+ await expect(runtime.acquire(HOME_ID, USER_ID)).rejects.toMatchObject({+ code: HOME_RUNTIME_ERR.BREAKER_OPEN,+ });+ const elapsed = Date.now() - startedAt;++ // The sixth attempt must not pay the 200 ms timeout, let alone the 15 s+ // production one. This assertion is the whole reason the breaker exists.+ expect(elapsed).toBeLessThan(50);+ expect(runtime.stats().breakersOpen).toBe(1);+ expect(createBridge.built).toHaveLength(5);+ }, 10_000);++ it('tells the store why, so the connect screen can explain it without a socket', async () => {+ const createBridge = countingFactory({ stall: true });+ const deps = unreachableDeps();+ const runtime = createHomeRuntime({ createBridge, ...deps, connectTimeoutMs: 100 });++ for (let attempt = 1; attempt <= 5; attempt += 1) {+ await runtime.acquire(HOME_ID, USER_ID).catch(() => null);+ }+ await new Promise((resolve) => setTimeout(resolve, 10));++ const last = deps.handshakes.at(-1);+ expect(last.status).toBe(HOME_STATUS.UNREACHABLE);+ expect(last.statusDetail).toContain('paused retries for five minutes');+ }, 10_000);++ it('closes again once the cooldown expires and the house answers', async () => {+ const clock = fakeClock();+ let stalled = true;+ const built = [];+ const createBridge = (options) => {+ const bridge = makeFakeBridge(options, { get stall() { return stalled; } });+ built.push(bridge);+ return bridge;+ };+ const runtime = createHomeRuntime({ createBridge, ...storeDeps(), now: clock.now, connectTimeoutMs: 100 });++ for (let attempt = 1; attempt <= 5; attempt += 1) {+ await runtime.acquire(HOME_ID, USER_ID).catch(() => null);+ }+ await expect(runtime.acquire(HOME_ID, USER_ID)).rejects.toMatchObject({ code: HOME_RUNTIME_ERR.BREAKER_OPEN });++ clock.advance(5 * 60_000 + 1);+ stalled = false;+ const held = await runtime.acquire(HOME_ID, USER_ID);++ expect(held.bridge.connected).toBe(true);+ // A success clears the counter outright: the next outage starts from zero+ // rather than tripping on its first failure.+ expect(runtime.stats().breakersOpen).toBe(0);+ held.release();+ runtime.closeAll();+ }, 10_000);+});++describe('home runtime: the graph goes stale, never empty', () => {+ it('keeps the last good graph when the socket drops, and marks it stale', async () => {+ const createBridge = countingFactory();+ const runtime = createHomeRuntime({ createBridge, ...storeDeps() });++ const events = [];+ await runtime.subscribe(HOME_ID, USER_ID, (event) => events.push(event));+ const bridge = createBridge.built[0];++ expect(events).toHaveLength(1);+ expect(events[0].graph.rooms).toHaveLength(1);+ expect(events[0].stale).toBe(false);++ bridge.connected = false;+ bridge.emit('disconnected');++ const afterDrop = events.at(-1);+ expect(afterDrop.stale).toBe(true);+ expect(afterDrop.connected).toBe(false);+ // The house must not vanish from the 3D scene because a socket blinked.+ expect(afterDrop.graph.rooms).toHaveLength(1);+ expect(afterDrop.graph).toEqual(LIVE_GRAPH);+ runtime.closeAll();+ });++ it('comes back live on reconnect with no action from the client', async () => {+ const createBridge = countingFactory();+ const runtime = createHomeRuntime({ createBridge, ...storeDeps() });++ const events = [];+ await runtime.subscribe(HOME_ID, USER_ID, (event) => events.push(event));+ const bridge = createBridge.built[0];++ bridge.emit('disconnected');+ bridge.connected = true;+ bridge.emit('reconnected');++ expect(events.at(-1).stale).toBe(false);+ expect(events.at(-1).connected).toBe(true);+ runtime.closeAll();+ });++ it('refuses to replace a real graph with nothing', async () => {+ const createBridge = countingFactory();+ const runtime = createHomeRuntime({ createBridge, ...storeDeps() });++ const events = [];+ await runtime.subscribe(HOME_ID, USER_ID, (event) => events.push(event));+ const bridge = createBridge.built[0];++ bridge.emit('graph', null);++ expect(events.at(-1).graph).toEqual(LIVE_GRAPH);+ runtime.closeAll();+ });++ it('survives a subscriber that throws, and keeps serving the others', async () => {+ const createBridge = countingFactory();+ const runtime = createHomeRuntime({ createBridge, ...storeDeps() });+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});++ const good = [];+ await runtime.subscribe(HOME_ID, USER_ID, () => {+ throw new Error('a dead SSE stream');+ });+ await runtime.subscribe(HOME_ID, USER_ID, (event) => good.push(event));+ createBridge.built[0].emit('disconnected');++ expect(good.at(-1).stale).toBe(true);+ warn.mockRestore();+ runtime.closeAll();+ });+});++describe('home runtime: snapshot', () => {+ it('returns the graph without holding the connection open past the call', async () => {+ const createBridge = countingFactory();+ const clock = fakeClock();+ const runtime = createHomeRuntime({ createBridge, ...storeDeps(), now: clock.now, idleMs: 1_000 });++ const result = await runtime.snapshot(HOME_ID, USER_ID);++ expect(result.graph.rooms).toHaveLength(1);+ expect(result.connected).toBe(true);+ expect(result.stale).toBe(false);+ expect(result.status).toBe(HOME_STATUS.CONNECTED);++ clock.advance(1_001);+ expect(runtime.evictIdle(clock.now())).toBe(1);+ });+});++describe('home runtime: failures a user can act on', () => {+ it('reports a home that is not this account’s as not found, never as forbidden', async () => {+ const createBridge = countingFactory();+ const runtime = createHomeRuntime({+ createBridge,+ ...storeDeps({ getConnection: vi.fn(async () => null) }),+ });++ await expect(runtime.acquire(HOME_ID, 'someone-else')).rejects.toMatchObject({+ code: HOME_RUNTIME_ERR.NOT_FOUND,+ });+ // Nothing was opened for a home the caller does not own.+ expect(createBridge.built).toHaveLength(0);+ });++ it('reports a disconnected home as revoked rather than as a broken socket', async () => {+ const createBridge = countingFactory();+ const runtime = createHomeRuntime({+ createBridge,+ ...storeDeps({ getDecryptedToken: vi.fn(async () => null) }),+ });++ await expect(runtime.acquire(HOME_ID, USER_ID)).rejects.toMatchObject({+ code: HOME_RUNTIME_ERR.REVOKED,+ });+ expect(createBridge.built).toHaveLength(0);+ });++ it('turns an unreadable credential into "reconnect your home", and marks the row', async () => {+ const createBridge = countingFactory();+ const deps = storeDeps({+ getDecryptedToken: vi.fn(async () => {+ throw new Error('unsupported state or unable to authenticate data');+ }),+ });+ const runtime = createHomeRuntime({ createBridge, ...deps });++ await expect(runtime.acquire(HOME_ID, USER_ID)).rejects.toMatchObject({ code: 'auth' });+ expect(deps.handshakes.at(-1)).toMatchObject({ status: HOME_STATUS.AUTH_FAILED });+ expect(createBridge.built).toHaveLength(0);+ });+});++describe('home runtime: what the health probe reads', () => {+ it('reports open connections, subscribers, the cap and a status breakdown', async () => {+ const createBridge = countingFactory();+ const runtime = createHomeRuntime({ createBridge, ...storeDeps(), maxConnections: 42 });++ await runtime.subscribe(HOME_ID, USER_ID, () => {});+ await runtime.subscribe(HOME_ID, USER_ID, () => {});+ const held = await runtime.acquire(OTHER_HOME_ID, USER_ID);++ const snapshot = runtime.stats();+ expect(snapshot).toEqual({+ open: 2,+ subscribers: 2,+ pooledCap: 42,+ breakersOpen: 0,+ byStatus: { [HOME_STATUS.CONNECTED]: 2 },+ });++ held.release();+ runtime.closeAll();+ });++ it('counts a dropped home under its real status, not under connected', async () => {+ const createBridge = countingFactory();+ const runtime = createHomeRuntime({ createBridge, ...storeDeps() });++ const held = await runtime.acquire(HOME_ID, USER_ID);+ createBridge.built[0].emit('disconnected');++ expect(runtime.stats().byStatus).toEqual({ [HOME_STATUS.UNREACHABLE]: 1 });+ held.release();+ runtime.closeAll();+ });+});++describe('home runtime: shutdown', () => {+ it('closes every socket the process holds, so the house is not left with dead connections', async () => {+ const createBridge = countingFactory();+ const runtime = createHomeRuntime({ createBridge, ...storeDeps() });++ const a = await runtime.acquire(HOME_ID, USER_ID);+ const b = await runtime.acquire(OTHER_HOME_ID, USER_ID);++ expect(runtime.closeAll()).toBe(2);+ expect(a.bridge.closed).toBe(true);+ expect(b.bridge.closed).toBe(true);+ expect(runtime.stats().open).toBe(0);+ });++ it('is safe to call twice', async () => {+ const createBridge = countingFactory();+ const runtime = createHomeRuntime({ createBridge, ...storeDeps() });++ await runtime.acquire(HOME_ID, USER_ID);+ expect(runtime.closeAll()).toBe(1);+ expect(runtime.closeAll()).toBe(0);+ expect(createBridge.built[0].closeCount).toBe(1);+ });+});diff --git a/tests/home-store.test.js b/tests/home-store.test.jsnew file mode 100644index 000000000..5da2afdc8--- /dev/null+++ b/tests/home-store.test.js@@ -0,0 +1,356 @@+// The connection store, at the layer where a mistake costs somebody their front+// door.+//+// Three tiers, so the default `npm test` needs no database and no house:+//+// 1. Pure guards. The store's refusals happen before any query runs, so they+// are testable with nothing plugged in.+// 2. Grant scoping over the recorded instance+// (packages/home-bridge/tests/fixtures/home.json). A grant is per entity,+// and the proof that it stays per entity belongs next to the real entity+// ids it has to discriminate between.+// 3. The live round trip. Skips itself unless pointed at a real database, and+// the last block also wants a real Home Assistant:+//+// DATABASE_URL=... npx vitest run tests/home-store.test.js+// HOME_ASSISTANT_URL=http://localhost:8123 HOME_ASSISTANT_TOKEN=... \+// DATABASE_URL=... WALLET_ENCRYPTION_KEY=... npx vitest run tests/home-store.test.js+//+// The live tier writes throwaway users into whatever database it is given+// and deletes them again, the same posture as the package's live-home suite+// changing real state in a real house.++import { readFileSync } from 'node:fs';+import path from 'node:path';+import { fileURLToPath } from 'node:url';++import { afterAll, beforeAll, describe, expect, it } from 'vitest';++import { classifyCall, createAllowList, HomeBridge } from '@three-ws/home-bridge';++import {+ createConnection,+ fingerprintToken,+ getConnection,+ getDecryptedToken,+ grantEntity,+ HOME_STATUS,+ listAllowedEntities,+ listConnections,+ listGrants,+ listHomeActions,+ logHomeActionNow,+ recordHandshake,+ revokeConnection,+ revokeGrant,+} from '../api/_lib/home/store.js';++const HERE = path.dirname(fileURLToPath(import.meta.url));+const fixture = JSON.parse(+ readFileSync(path.join(HERE, '..', 'packages/home-bridge/tests/fixtures/home.json'), 'utf8'),+);++const A_UUID = '00000000-0000-4000-8000-0000000000aa';+const NOT_A_UUID = 'lock.front_door';++describe('the guards that run before any query does', () => {+ it('refuses a domain-wide grant outright', async () => {+ // The whole reason home_entity_grants has no granted_domain column: letting+ // the agent open the office door is not letting it open the front door.+ await expect(grantEntity({ homeId: A_UUID, entityId: 'lock', grantedBy: A_UUID })).rejects.toThrow(/never per domain/);+ await expect(grantEntity({ homeId: A_UUID, entityId: 'lock.*', grantedBy: A_UUID })).rejects.toThrow(/never per domain/);+ await expect(grantEntity({ homeId: A_UUID, entityId: '', grantedBy: A_UUID })).rejects.toThrow();+ });++ it('treats a malformed id as a miss rather than a query', async () => {+ expect(await getConnection(NOT_A_UUID, A_UUID)).toBeNull();+ expect(await getDecryptedToken(NOT_A_UUID, A_UUID)).toBeNull();+ expect(await listGrants(NOT_A_UUID)).toEqual([]);+ expect(await listHomeActions(NOT_A_UUID)).toEqual([]);+ expect(await listConnections('')).toEqual([]);+ });++ it('never answers a read without an owner', async () => {+ expect(await getConnection(A_UUID, '')).toBeNull();+ expect(await getDecryptedToken(A_UUID, null)).toBeNull();+ expect(await revokeConnection(A_UUID, undefined)).toEqual({ revoked: false, alreadyRevoked: false, home: null });+ });++ it('fingerprints a token without being able to give it back', () => {+ const fp = fingerprintToken('a-home-assistant-long-lived-token');+ expect(fp).toMatch(/^[0-9a-f]{64}$/);+ expect(fp).toBe(fingerprintToken('a-home-assistant-long-lived-token'));+ expect(fp).not.toBe(fingerprintToken('a-home-assistant-long-lived-tokem'));+ });+});++describe('grant scoping, over the recorded instance', () => {+ // The fixture is a recording of a real house, so these are the real ids the+ // gate has to tell apart, not names invented to make a test pass.+ const locks = Object.keys(fixture.states).filter((id) => id.startsWith('lock.'));++ it('the recording really does have more than one lock to confuse', () => {+ expect(locks).toContain('lock.front_door');+ expect(locks).toContain('lock.kitchen_door');+ });++ it('a grant for one lock leaves every other lock guarded', () => {+ const allow = createAllowList(['lock.kitchen_door']);+ expect(allow.has('lock.kitchen_door')).toBe(true);+ for (const other of locks.filter((id) => id !== 'lock.kitchen_door')) {+ expect(allow.has(other)).toBe(false);+ }+ expect(classifyCall({ domain: 'lock', service: 'unlock', entityId: 'lock.front_door' }).guarded).toBe(true);+ });++ it('locking up is never guarded, so it never needs a grant', () => {+ expect(classifyCall({ domain: 'lock', service: 'lock', entityId: 'lock.front_door' }).guarded).toBe(false);+ });+});++// ---------------------------------------------------------------------------+// The live tier.+// ---------------------------------------------------------------------------++const hasDb = Boolean(process.env.DATABASE_URL);+const hasKey = Boolean(process.env.WALLET_ENCRYPTION_KEY || process.env.JWT_SECRET);+const haUrl = process.env.HOME_ASSISTANT_URL;+const haToken = process.env.HOME_ASSISTANT_TOKEN;++const liveDb = describe.skipIf(!hasDb || !hasKey);+const liveHome = describe.skipIf(!hasDb || !hasKey || !haUrl || !haToken);++// A token shaped like the real thing but belonging to nothing: the DB-only tier+// proves the credential path without needing a house to point it at.+const SYNTHETIC_TOKEN = `synthetic.home.assistant.token.${'a'.repeat(64)}`;+const BASE_URL = haUrl || 'https://home.invalid.three.ws';++liveDb('against a real database', () => {+ /** @type {import('@neondatabase/serverless').NeonQueryFunction} */+ let sql;+ let owner;+ let stranger;+ let home;++ beforeAll(async () => {+ ({ sql } = await import('../api/_lib/db.js'));+ const stamp = Date.now();+ [owner] = await sql`insert into users (email) values (${`home-store-owner-${stamp}@qa.three.ws`}) returning id`;+ [stranger] = await sql`insert into users (email) values (${`home-store-stranger-${stamp}@qa.three.ws`}) returning id`;+ home = await createConnection({+ userId: owner.id,+ label: ' The office ',+ baseUrl: `${BASE_URL}/`,+ token: haToken || SYNTHETIC_TOKEN,+ });+ }, 60_000);++ afterAll(async () => {+ if (sql && owner) await sql`delete from users where id in (${owner.id}, ${stranger.id})`;+ });++ it('stores the normalized URL and a trimmed label, never the raw input', () => {+ // The trailing slash the user typed is gone, so the unique index below is+ // over one spelling of the house rather than three.+ expect(home.base_url).toBe(BASE_URL);+ expect(home.label).toBe('The office');+ });++ it('returns a row with no credential on it', () => {+ expect(home).not.toHaveProperty('access_token_enc');+ expect(JSON.stringify(home)).not.toContain(haToken || SYNTHETIC_TOKEN);+ });++ it('encrypts the credential at rest', async () => {+ const [row] = await sql`select access_token_enc from home_connections where id = ${home.id}`;+ expect(row.access_token_enc.startsWith('v2:')).toBe(true);+ expect(row.access_token_enc).not.toContain(haToken || SYNTHETIC_TOKEN);+ });++ it('re-connecting the same house updates the row instead of stacking a second one', async () => {+ const again = await createConnection({+ userId: owner.id, label: 'The office', baseUrl: BASE_URL, token: haToken || SYNTHETIC_TOKEN,+ });+ expect(again.id).toBe(home.id);+ expect(again.token_fingerprint).toBe(home.token_fingerprint);+ expect(await listConnections(owner.id)).toHaveLength(1);+ });++ it('a rotated token lands on the same row with a new fingerprint', async () => {+ const rotated = await createConnection({+ userId: owner.id, label: 'The office', baseUrl: BASE_URL, token: `${SYNTHETIC_TOKEN}-rotated`,+ });+ expect(rotated.id).toBe(home.id);+ expect(rotated.token_fingerprint).not.toBe(home.token_fingerprint);+ // Put the working credential back for the tests that follow.+ await createConnection({ userId: owner.id, label: 'The office', baseUrl: BASE_URL, token: haToken || SYNTHETIC_TOKEN });+ });++ it('never shows one user another user\'s home', async () => {+ expect(await listConnections(stranger.id)).toEqual([]);+ expect(await getConnection(home.id, stranger.id)).toBeNull();+ expect(await getDecryptedToken(home.id, stranger.id)).toBeNull();+ expect((await getConnection(home.id, owner.id))?.id).toBe(home.id);+ });++ it('gives the owner back exactly the token they connected with', async () => {+ const cred = await getDecryptedToken(home.id, owner.id);+ expect(cred.token).toBe(haToken || SYNTHETIC_TOKEN);+ expect(cred.baseUrl).toBe(BASE_URL);+ });++ it('merges measured capabilities rather than replacing them', async () => {+ const first = await recordHandshake(home.id, {+ status: HOME_STATUS.CONNECTED,+ capabilities: { websocket: true, entityCount: 120, haVersion: '2026.9.0' },+ });+ expect(first.last_ok_at).toBeTruthy();+ const second = await recordHandshake(home.id, { status: HOME_STATUS.CONNECTED, capabilities: { mcp: false } });+ expect(second.capabilities.entityCount).toBe(120);+ expect(second.capabilities.mcp).toBe(false);+ });++ it('stamps last_error_at, not last_ok_at, on a failed handshake', async () => {+ const failed = await recordHandshake(home.id, {+ status: HOME_STATUS.AUTH_FAILED, statusDetail: 'Home Assistant rejected that token.',+ });+ expect(failed.last_error_at).toBeTruthy();+ expect(failed.status_detail).toMatch(/rejected/);+ await recordHandshake(home.id, { status: HOME_STATUS.CONNECTED });+ });++ it('grants one entity without clearing any other', async () => {+ await grantEntity({ homeId: home.id, entityId: 'lock.office_door', grantedBy: owner.id });+ const allow = createAllowList(await listAllowedEntities(home.id));+ expect(allow.has('lock.office_door')).toBe(true);+ expect(allow.has('lock.front_door')).toBe(false);+ });++ it('filters an expired grant in SQL, not in the caller', async () => {+ await sql`+ insert into home_entity_grants (home_id, entity_id, granted_by, expires_at)+ values (${home.id}, 'lock.expired_door', ${owner.id}, now() - interval '1 hour')+ `;+ const [{ n }] = await sql`select count(*)::int as n from home_entity_grants where home_id = ${home.id}`;+ const live = await listGrants(home.id);+ expect(n).toBeGreaterThan(live.length);+ expect(live.map((g) => g.entity_id)).not.toContain('lock.expired_door');+ });++ it('revokes a grant idempotently', async () => {+ expect(await revokeGrant({ homeId: home.id, entityId: 'lock.office_door' })).toBe(true);+ expect(await revokeGrant({ homeId: home.id, entityId: 'lock.office_door' })).toBe(false);+ });++ it('records what the platform did in the house, with resolved targets', async () => {+ expect(await logHomeActionNow({+ homeId: home.id, userId: owner.id, actor: 'user', channel: 'websocket',+ action: 'lock.unlock', entityIds: ['lock.kitchen_door'], guarded: true,+ confirmedBy: owner.id, risk: 'security', outcome: 'ok', detail: { via: 'store test' },+ })).toBe(true);+ const [entry] = await listHomeActions(home.id);+ expect(entry.entity_ids).toEqual(['lock.kitchen_door']);+ expect(entry.guarded).toBe(true);+ expect(entry.risk).toBe('security');+ });++ it('refuses an actor the schema does not recognize', async () => {+ await expect(sql`+ insert into home_action_log (home_id, actor, channel, action, outcome)+ values (${home.id}, 'burglar', 'websocket', 'lock.unlock', 'ok')+ `).rejects.toThrow();+ });++ it('refuses a relay row with nothing to route through', async () => {+ await expect(sql`+ insert into home_connections (user_id, label, base_url, access_token_enc, token_fingerprint, transport)+ values (${stranger.id}, 'unroutable', 'https://relay.invalid', 'x', 'y', 'relay')+ `).rejects.toThrow();+ });++ it('revokes twice, destroying the credential and keeping the lineage', async () => {+ const first = await revokeConnection(home.id, owner.id);+ expect(first.revoked).toBe(true);+ const second = await revokeConnection(home.id, owner.id);+ expect(second).toMatchObject({ revoked: false, alreadyRevoked: true });++ const [row] = await sql`select access_token_enc, revoked_at, status from home_connections where id = ${home.id}`;+ expect(row.access_token_enc).toBe('');+ expect(row.revoked_at).toBeTruthy();+ expect(row.status).toBe(HOME_STATUS.REVOKED);++ expect(await getDecryptedToken(home.id, owner.id)).toBeNull();+ expect(await listConnections(owner.id)).toEqual([]);+ expect(await listHomeActions(home.id)).toHaveLength(1);+ });++ it('does not let a stranger revoke a home they cannot see', async () => {+ expect(await revokeConnection(home.id, stranger.id)).toMatchObject({ revoked: false, alreadyRevoked: false });+ });++ it('lets the same house be connected again after a revoke', async () => {+ const fresh = await createConnection({+ userId: owner.id, label: 'Home again', baseUrl: BASE_URL, token: haToken || SYNTHETIC_TOKEN,+ });+ expect(fresh.id).not.toBe(home.id);+ expect(await listConnections(owner.id)).toHaveLength(1);+ });+});++liveHome('the stored credential against a real Home Assistant', () => {+ let sql;+ let owner;+ let home;+ /** @type {HomeBridge} */+ let bridge;++ beforeAll(async () => {+ ({ sql } = await import('../api/_lib/db.js'));+ [owner] = await sql`insert into users (email) values (${`home-store-live-${Date.now()}@qa.three.ws`}) returning id`;+ home = await createConnection({ userId: owner.id, label: 'Live', baseUrl: haUrl, token: haToken });+ }, 60_000);++ afterAll(async () => {+ bridge?.close();+ if (sql && owner) await sql`delete from users where id = ${owner.id}`;+ });++ it('opens a real socket with the credential it read back out of the database', async () => {+ const cred = await getDecryptedToken(home.id, owner.id);+ bridge = new HomeBridge({ baseUrl: cred.baseUrl, token: cred.token });+ const graph = await bridge.connect();+ expect(bridge.connected).toBe(true);+ expect(Object.keys(bridge.states).length).toBeGreaterThan(0);+ expect(graph.rooms.length + graph.unassigned.length).toBeGreaterThan(0);+ }, 60_000);++ it('measures the house rather than assuming it, and stores what it measured', async () => {+ const { verifyConnection } = await import('../api/_lib/home/verify.js');+ const { capabilities } = await verifyConnection({ baseUrl: haUrl, token: haToken });+ const config = await (await fetch(`${haUrl}/api/config`, { headers: { authorization: `Bearer ${haToken}` } })).json();+ expect(capabilities.websocket).toBe(true);+ expect(capabilities.haVersion).toBe(config.version);+ expect(capabilities.entityCount).toBe(Object.keys(bridge.states).length);++ const stored = await recordHandshake(home.id, { status: HOME_STATUS.CONNECTED, capabilities });+ expect(stored.capabilities.haVersion).toBe(config.version);+ expect(stored.status).toBe(HOME_STATUS.CONNECTED);+ }, 60_000);++ it('a granted lock passes the gate and an ungranted one still does not', async () => {+ await grantEntity({ homeId: home.id, entityId: 'lock.kitchen_door', grantedBy: owner.id });+ const gated = new HomeBridge({+ baseUrl: haUrl, token: haToken, allowedEntities: await listAllowedEntities(home.id),+ });+ try {+ await gated.connect();+ await gated.call('lock', 'unlock', { entity_id: 'lock.kitchen_door' });+ await expect(gated.call('lock', 'unlock', { entity_id: 'lock.front_door' })).rejects.toMatchObject({+ code: 'needs_confirmation',+ });+ expect(bridge.states['lock.front_door'].state).toBe('locked');+ } finally {+ gated.close();+ }+ }, 60_000);+});