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
feat(home): persist a connected house, its members and its privacy window
nirholas16cc7a7b16f8
diff --git a/api/_lib/home/members.js b/api/_lib/home/members.jsnew file mode 100644index 000000000..654b4a4c8--- /dev/null+++ b/api/_lib/home/members.js@@ -0,0 +1,559 @@+// Households: who is in this home, what they may do in it, and what they may see.+//+// This module is the single authority on that question. Every surface that acts+// on a home (the connection store's reads, the bridge runtime's acquire, the+// room graph projection, the physical-action gate, the confirm endpoint, the+// grant and layout writers, the chat tools and the MCP tools) resolves the+// caller through `requireMembership` and branches on what it returns. None of+// them keeps its own copy of the rules, and none of them falls back to+// "or the connection's user_id is the caller": a role system with a bypass is+// decoration, and the bypass is always the path an attacker takes.+//+// The rule the whole design exists for:+//+// A guest can never confirm a guarded action.+//+// A house sitter should be able to turn the lights on and should not be able to+// authorise unlocking the front door. Home Assistant's own `intent__HassTurnOff`+// performs an unlock on a lock, so "turn something off" and "open the building"+// are the same call with different targets. `confirm` is the line between them+// and it is drawn here, server side, once.+//+// Scope is enforced here too, for the same reason. A guest given the kitchen can+// read the kitchen. The rooms they were not given are removed from the graph+// before it is serialized, not hidden by the client, because a room whose state+// reached the browser has already been disclosed.++import { createHash, randomBytes, timingSafeEqual } from 'node:crypto';++import { sql } from '../db.js';+import { withDbRetry } from '../db-retry.js';+import { summarizeClimate, summarizeLighting, summarizeSecurity } from '../../../packages/home-bridge/src/rooms.js';++/** Every role the schema's check constraint accepts, strongest first. */+export const HOME_ROLES = Object.freeze(['owner', 'admin', 'member', 'guest', 'viewer']);++/**+ * The capability vocabulary. Every enforcement point names one of these rather+ * than testing a role string, so adding a role is a change to one table below+ * instead of a grep across the codebase.+ *+ * read read the home's state at all+ * act perform an ungated action (turn a light on, set a temperature)+ * confirm authorise a guarded action (unlock, open, disarm)+ * grant create a standing allowance that clears the gate in future+ * layout edit the floorplan and the 3D layout+ * invite administer the roster: invite, change a role, remove a member+ * disconnect revoke the connection and take the house off the platform+ */+export const HOME_CAPABILITIES = Object.freeze(['read', 'act', 'confirm', 'grant', 'layout', 'invite', 'disconnect']);++/**+ * The role matrix. `rank` orders the roles for roster administration; `scoped`+ * says whether this role's reads and actions are narrowed by `entity_scope`.+ *+ * Read this table as the product decision it is:+ *+ * owner the account that connected the house. Exactly one, schema-enforced.+ * admin runs the household but cannot take the house off the platform.+ * member lives here. Acts, confirms, arranges the layout. Cannot hand out+ * access and cannot leave a standing allowance behind.+ * guest is visiting. Scoped, and never a confirmation.+ * viewer a wall display or a monitoring seat. Scoped, and reads only.+ */+const ROLE_MATRIX = Object.freeze({+ owner: Object.freeze({ rank: 5, scoped: false, can: Object.freeze(new Set(['read', 'act', 'confirm', 'grant', 'layout', 'invite', 'disconnect'])) }),+ admin: Object.freeze({ rank: 4, scoped: false, can: Object.freeze(new Set(['read', 'act', 'confirm', 'grant', 'layout', 'invite'])) }),+ member: Object.freeze({ rank: 3, scoped: false, can: Object.freeze(new Set(['read', 'act', 'confirm', 'layout'])) }),+ guest: Object.freeze({ rank: 2, scoped: true, can: Object.freeze(new Set(['read', 'act'])) }),+ viewer: Object.freeze({ rank: 1, scoped: true, can: Object.freeze(new Set(['read'])) }),+});++/** Roles an invite or a role change may assign. Ownership is never handed out. */+export const ASSIGNABLE_ROLES = Object.freeze(HOME_ROLES.filter((r) => r !== 'owner'));++const WHOLE_HOUSE_SCOPE = Object.freeze({ mode: 'all' });+const INVITE_TTL_MS = 7 * 24 * 60 * 60 * 1000;+const SCOPE_LIST_MAX = 500;+const EMAIL_MAX = 254;++/** Does this role hold this capability? Unknown roles hold nothing. */+export function can(role, capability) {+ return ROLE_MATRIX[role]?.can.has(capability) === true;+}++/** Is this role's view of the house narrowed by its entity scope? */+export function isScopedRole(role) {+ return ROLE_MATRIX[role]?.scoped === true;+}++/** Ordering for roster administration. An unknown role sorts below every real one. */+export function roleRank(role) {+ return ROLE_MATRIX[role]?.rank ?? 0;+}++/**+ * The whole matrix as plain data, for the member UI and for the docs to render+ * without restating it and drifting from it.+ */+export function roleMatrix() {+ return HOME_ROLES.map((role) => ({+ role,+ rank: ROLE_MATRIX[role].rank,+ scoped: ROLE_MATRIX[role].scoped,+ capabilities: Object.fromEntries(HOME_CAPABILITIES.map((c) => [c, ROLE_MATRIX[role].can.has(c)])),+ }));+}++// ── Entity scope ────────────────────────────────────────────────────────────++/**+ * Normalize a caller-supplied scope into the two shapes the schema accepts.+ *+ * A non-scoped role is always whole-house: a stale allowlist left on someone who+ * was promoted from guest to member must not silently keep narrowing them, and a+ * scope on a role that does not read it is a lie in the database.+ *+ * @param {unknown} scope+ * @param {string} [role] when given, a non-scoped role forces {mode:'all'}+ */+export function normalizeScope(scope, role) {+ if (role && !isScopedRole(role)) return { ...WHOLE_HOUSE_SCOPE };+ if (!scope || typeof scope !== 'object' || Array.isArray(scope)) return { ...WHOLE_HOUSE_SCOPE };+ if (scope.mode !== 'allow') return { ...WHOLE_HOUSE_SCOPE };+ const clean = (list) =>+ Array.from(new Set((Array.isArray(list) ? list : []).map((v) => String(v || '').trim()).filter(Boolean))).slice(0, SCOPE_LIST_MAX);+ return { mode: 'allow', areas: clean(scope.areas), entities: clean(scope.entities) };+}++/**+ * Is this entity inside this scope?+ *+ * An entity is in scope when it was named directly, or when the area holding it+ * was named. Nothing is inferred from the domain: "all the lights" is not a+ * scope anyone can reason about while granting it, which is the same reason+ * home_entity_grants refused a domain column.+ */+export function entityInScope(scope, { entityId, areaId = null } = {}) {+ const s = normalizeScope(scope);+ if (s.mode === 'all') return true;+ if (entityId && s.entities.includes(entityId)) return true;+ return Boolean(areaId && s.areas.includes(areaId));+}++/** Every entity id in a resolved action that falls outside the scope. */+export function outOfScopeEntities(scope, targets = []) {+ return targets+ .filter((t) => {+ const spec = typeof t === 'string' ? { entityId: t } : t;+ return !entityInScope(scope, spec);+ })+ .map((t) => (typeof t === 'string' ? t : t.entityId));+}++/**+ * The room graph as this member is allowed to see it.+ *+ * Three things happen, and all three matter:+ *+ * 1. Rooms the member was not given are removed, not marked. A room the client+ * knows the name of is a room that was disclosed.+ * 2. In a room reached through an individual entity grant, the entities that+ * were not granted are removed AND the room's lighting, climate and+ * security rollups are recomputed over what remains. Leaving the original+ * rollups would report "three lights on" for a room the member can see one+ * light in, which is the leak the filtering exists to prevent.+ * 3. Floors with no visible room are removed, because the floor list is the+ * shape of the building.+ *+ * @param {object} graph buildHomeGraph() output+ * @param {object} scope+ */+export function filterGraphForScope(graph, scope) {+ const s = normalizeScope(scope);+ if (!graph || s.mode === 'all') return graph;++ const areas = new Set(s.areas);+ const entities = new Set(s.entities);++ const rooms = [];+ for (const room of graph.rooms || []) {+ const wholeRoom = areas.has(room.id);+ const kept = wholeRoom ? room.entities || [] : (room.entities || []).filter((e) => entities.has(e.entityId));+ if (!wholeRoom && kept.length === 0) continue;+ rooms.push(+ wholeRoom+ ? room+ : {+ ...room,+ entities: kept,+ lighting: summarizeLighting(kept),+ climate: summarizeClimate(kept),+ secured: summarizeSecurity(kept),+ },+ );+ }++ const visibleFloors = new Set(rooms.map((r) => r.floorId).filter(Boolean));+ return {+ ...graph,+ floors: (graph.floors || []).filter((f) => visibleFloors.has(f.id)),+ rooms,+ unassigned: (graph.unassigned || []).filter((e) => entities.has(e.entityId)),+ };+}++// ── Membership resolution ───────────────────────────────────────────────────++function shapeMembership(row) {+ if (!row) return null;+ return {+ homeId: row.home_id,+ userId: row.user_id,+ role: row.role,+ scope: normalizeScope(row.entity_scope, row.role),+ scoped: isScopedRole(row.role),+ invitedBy: row.invited_by || null,+ createdAt: row.created_at,+ updatedAt: row.updated_at,+ };+}++/**+ * This caller's membership in this home, or null.+ *+ * Null covers three cases on purpose and does not distinguish between them: the+ * home does not exist, the home was revoked, and the caller is not a member.+ * A caller who is not in the household must not be able to learn that a home id+ * is real, which is why every endpoint above this answers 404 and never 403.+ */+export async function resolveMembership(homeId, userId) {+ if (!homeId || !userId) return null;+ const [row] = await withDbRetry(+ () => sql`+ SELECT m.home_id, m.user_id, m.role, m.entity_scope, m.invited_by, m.created_at, m.updated_at+ FROM home_members m+ JOIN home_connections c ON c.id = m.home_id AND c.revoked_at IS NULL+ WHERE m.home_id = ${homeId} AND m.user_id = ${userId}+ `,+ );+ return shapeMembership(row);+}++/**+ * The authorisation call every enforcement point makes.+ *+ * Returns a discriminated result rather than throwing, because the two failure+ * modes need different HTTP answers and the caller is the only one that knows+ * which surface it is:+ *+ * { ok: false, status: 404 } not a member (or no such home). Says nothing.+ * { ok: false, status: 403 } a member, but this role may not do this. Says+ * which role and which capability, because a+ * guest who is refused an unlock deserves to be+ * told it is their role and not a broken door.+ *+ * @param {string} homeId+ * @param {string} userId+ * @param {string} capability one of HOME_CAPABILITIES+ */+export async function requireMembership(homeId, userId, capability) {+ const membership = await resolveMembership(homeId, userId);+ if (!membership) {+ return { ok: false, status: 404, code: 'home_not_found', reason: 'home not found', membership: null };+ }+ if (capability && !can(membership.role, capability)) {+ return {+ ok: false,+ status: 403,+ code: 'role_forbidden',+ reason: `the ${membership.role} role cannot ${capability} in this home`,+ role: membership.role,+ capability,+ membership,+ };+ }+ return { ok: true, membership, role: membership.role, scope: membership.scope };+}++/** Every live home this user is a member of, with the role they hold in each. */+export async function listMembershipHomes(userId) {+ if (!userId) return [];+ return withDbRetry(+ () => sql`+ SELECT m.home_id, m.role, m.entity_scope, c.label, c.base_url, c.status, c.status_detail,+ c.capabilities, c.transport, c.last_ok_at, c.created_at+ FROM home_members m+ JOIN home_connections c ON c.id = m.home_id AND c.revoked_at IS NULL+ WHERE m.user_id = ${userId}+ ORDER BY c.created_at DESC+ `,+ );+}++// ── The roster ──────────────────────────────────────────────────────────────++/** Who is in this household, strongest role first, with their account identity. */+export async function listMembers(homeId) {+ const rows = await withDbRetry(+ () => sql`+ SELECT m.home_id, m.user_id, m.role, m.entity_scope, m.invited_by, m.created_at, m.updated_at,+ u.email, u.username, u.display_name+ FROM home_members m+ JOIN users u ON u.id = m.user_id+ WHERE m.home_id = ${homeId}+ ORDER BY m.created_at ASC+ `,+ );+ return rows+ .map((row) => ({+ ...shapeMembership(row),+ email: row.email || null,+ username: row.username || null,+ displayName: row.display_name || null,+ }))+ .sort((a, b) => roleRank(b.role) - roleRank(a.role) || String(a.createdAt) - String(b.createdAt));+}++/**+ * May this actor administer this target's membership?+ *+ * Strictly-lower rank, always. An admin may create a peer admin and may not+ * remove one; only the owner can. The owner row is never a target: there is+ * exactly one, the schema enforces it, and the way out of a household is to+ * disconnect the house, not to leave it ownerless.+ */+export function canManageMember(actorRole, targetRole) {+ if (!can(actorRole, 'invite')) return false;+ if (targetRole === 'owner') return false;+ return roleRank(actorRole) > roleRank(targetRole);+}++/** May this actor hand out this role? Peers yes, ownership never. */+export function canAssignRole(actorRole, role) {+ if (!can(actorRole, 'invite')) return false;+ if (!ASSIGNABLE_ROLES.includes(role)) return false;+ return roleRank(actorRole) >= roleRank(role);+}++/**+ * Change a member's role, normalizing their scope to the new role.+ *+ * Promoting a guest to a member widens them to the whole house in the same+ * statement, so no stale allowlist survives the promotion.+ */+export async function setMemberRole({ homeId, userId, role, scope }) {+ const next = normalizeScope(scope, role);+ const [row] = await withDbRetry(+ () => sql`+ UPDATE home_members+ SET role = ${role}, entity_scope = ${JSON.stringify(next)}::jsonb, updated_at = now()+ WHERE home_id = ${homeId} AND user_id = ${userId} AND role <> 'owner'+ RETURNING home_id, user_id, role, entity_scope, invited_by, created_at, updated_at+ `,+ );+ return shapeMembership(row);+}++/**+ * Remove a member and revoke every standing allowance they left behind, in one+ * transaction.+ *+ * The two halves are inseparable. A standing allowance is a permanent yes to+ * unlocking one specific thing, recorded with the account that said it. Leaving+ * a removed member's allowances in place means the front door still opens on+ * the authority of someone who no longer lives there, and nothing in the UI+ * would ever show it. That is the bug that gets somebody burgled, so it is a+ * transaction and not two calls with a hopeful comment between them.+ *+ * @returns {Promise<{removed: boolean, grantsRevoked: string[]}>}+ */+export async function removeMember({ homeId, userId }) {+ const doomed = await withDbRetry(+ () => sql`SELECT entity_id FROM home_entity_grants WHERE home_id = ${homeId} AND granted_by = ${userId} ORDER BY entity_id`,+ );+ const [[removed]] = await sql.transaction([+ sql`DELETE FROM home_members WHERE home_id = ${homeId} AND user_id = ${userId} AND role <> 'owner' RETURNING user_id`,+ sql`DELETE FROM home_entity_grants WHERE home_id = ${homeId} AND granted_by = ${userId}`,+ sql`UPDATE home_invites SET revoked_at = now() WHERE home_id = ${homeId} AND accepted_by = ${userId} AND revoked_at IS NULL`,+ ]);+ return { removed: Boolean(removed), grantsRevoked: doomed.map((r) => r.entity_id) };+}++// ── Invitations ─────────────────────────────────────────────────────────────++function hashInviteToken(token) {+ return createHash('sha256').update(String(token), 'utf8').digest('hex');+}++/** Constant-time comparison of two invite token hashes. */+function hashesMatch(a, b) {+ const left = Buffer.from(String(a), 'utf8');+ const right = Buffer.from(String(b), 'utf8');+ if (left.length !== right.length) return false;+ return timingSafeEqual(left, right);+}++function shapeInvite(row, { token } = {}) {+ if (!row) return null;+ return {+ id: row.id,+ homeId: row.home_id,+ email: row.email,+ role: row.role,+ scope: normalizeScope(row.entity_scope, row.role),+ invitedBy: row.invited_by,+ expiresAt: row.expires_at,+ acceptedAt: row.accepted_at || null,+ acceptedBy: row.accepted_by || null,+ revokedAt: row.revoked_at || null,+ createdAt: row.created_at,+ ...(token ? { token } : {}),+ };+}++/**+ * Create a single-use, expiring, role-bound invitation.+ *+ * The plaintext token is returned exactly once, on this call, and is never+ * readable again: the row holds sha256 of it. A re-invite to the same address+ * replaces the outstanding one rather than stacking a second working key.+ *+ * @param {object} input+ * @param {string} input.homeId+ * @param {string} input.email+ * @param {string} input.role one of ASSIGNABLE_ROLES+ * @param {object} [input.scope]+ * @param {string} input.invitedBy+ * @param {number} [input.ttlMs]+ */+export async function createInvite({ homeId, email, role, scope, invitedBy, ttlMs = INVITE_TTL_MS }) {+ const address = String(email || '').trim().toLowerCase().slice(0, EMAIL_MAX);+ if (!address) throw new Error('an invite needs an email address');+ if (!ASSIGNABLE_ROLES.includes(role)) throw new Error(`invalid invite role: ${role}`);++ const token = randomBytes(32).toString('base64url');+ const expiresAt = new Date(Date.now() + ttlMs);+ const normalized = JSON.stringify(normalizeScope(scope, role));++ const [row] = await sql.transaction([+ sql`UPDATE home_invites SET revoked_at = now() WHERE home_id = ${homeId} AND lower(email) = ${address} AND accepted_at IS NULL AND revoked_at IS NULL`,+ sql`+ INSERT INTO home_invites (home_id, email, role, entity_scope, token_hash, invited_by, expires_at)+ VALUES (${homeId}, ${address}, ${role}, ${normalized}::jsonb, ${hashInviteToken(token)}, ${invitedBy}, ${expiresAt})+ RETURNING id, home_id, email, role, entity_scope, invited_by, expires_at, accepted_at, accepted_by, revoked_at, created_at+ `,+ ]).then((results) => results[1]);++ return shapeInvite(row, { token });+}++/** Outstanding invitations for this home, newest first. Never the token. */+export async function listInvites(homeId, { includeSpent = false } = {}) {+ const rows = await withDbRetry(+ () =>+ includeSpent+ ? sql`SELECT id, home_id, email, role, entity_scope, invited_by, expires_at, accepted_at, accepted_by, revoked_at, created_at+ FROM home_invites WHERE home_id = ${homeId} ORDER BY created_at DESC LIMIT 200`+ : sql`SELECT id, home_id, email, role, entity_scope, invited_by, expires_at, accepted_at, accepted_by, revoked_at, created_at+ FROM home_invites WHERE home_id = ${homeId} AND accepted_at IS NULL AND revoked_at IS NULL AND expires_at > now()+ ORDER BY created_at DESC LIMIT 200`,+ );+ return rows.map((r) => shapeInvite(r));+}++/** Withdraw an invitation before anyone has used it. Idempotent. */+export async function revokeInvite({ homeId, inviteId }) {+ const [row] = await withDbRetry(+ () => sql`UPDATE home_invites SET revoked_at = now() WHERE home_id = ${homeId} AND id = ${inviteId} AND accepted_at IS NULL AND revoked_at IS NULL RETURNING id`,+ );+ return Boolean(row);+}++/**+ * The invitation behind a token, without spending it, for the acceptance screen+ * to say "you were invited to Home as a guest" before asking anyone to sign in.+ * Returns the reason it cannot be used rather than null, because "expired" and+ * "never existed" are different screens.+ */+export async function inspectInvite(token) {+ const hash = hashInviteToken(token);+ const [row] = await withDbRetry(+ () => sql`+ SELECT i.id, i.home_id, i.email, i.role, i.entity_scope, i.invited_by, i.expires_at,+ i.accepted_at, i.accepted_by, i.revoked_at, i.created_at, i.token_hash,+ c.label, c.revoked_at AS home_revoked_at+ FROM home_invites i+ JOIN home_connections c ON c.id = i.home_id+ WHERE i.token_hash = ${hash}+ `,+ );+ if (!row || !hashesMatch(row.token_hash, hash)) return { ok: false, code: 'invite_not_found', reason: 'this invitation link is not valid' };+ if (row.home_revoked_at) return { ok: false, code: 'home_revoked', reason: 'this home has been disconnected' };+ if (row.revoked_at) return { ok: false, code: 'invite_revoked', reason: 'this invitation was withdrawn' };+ if (row.accepted_at) return { ok: false, code: 'invite_spent', reason: 'this invitation has already been used' };+ if (new Date(row.expires_at).getTime() <= Date.now()) return { ok: false, code: 'invite_expired', reason: 'this invitation has expired' };+ return { ok: true, invite: shapeInvite(row), homeLabel: row.label };+}++/**+ * Redeem an invitation for an account that already exists.+ *+ * Single use is enforced in the UPDATE's own WHERE clause rather than by a read+ * followed by a write, so two people opening the same link at the same moment+ * cannot both become members: exactly one UPDATE matches a row, and the other+ * sees zero and is told the invite is spent.+ *+ * An account that is already in this household keeps the role it has. An invite+ * is a way in, not a way to be quietly demoted by a stale link.+ */+export async function acceptInvite({ token, userId }) {+ const inspected = await inspectInvite(token);+ if (!inspected.ok) return inspected;++ const { invite } = inspected;+ const existing = await resolveMembership(invite.homeId, userId);+ if (existing) {+ await withDbRetry(+ () => sql`UPDATE home_invites SET accepted_at = now(), accepted_by = ${userId} WHERE id = ${invite.id} AND accepted_at IS NULL`,+ );+ return { ok: true, alreadyMember: true, membership: existing, homeLabel: inspected.homeLabel };+ }++ const [claimed, member] = await sql.transaction([+ sql`UPDATE home_invites SET accepted_at = now(), accepted_by = ${userId} WHERE id = ${invite.id} AND accepted_at IS NULL AND revoked_at IS NULL AND expires_at > now() RETURNING id`,+ sql`+ INSERT INTO home_members (home_id, user_id, role, entity_scope, invited_by)+ VALUES (${invite.homeId}, ${userId}, ${invite.role}, ${JSON.stringify(invite.scope)}::jsonb, ${invite.invitedBy})+ ON CONFLICT (home_id, user_id) DO NOTHING+ RETURNING home_id, user_id, role, entity_scope, invited_by, created_at, updated_at+ `,+ ]);++ if (!claimed?.[0]) return { ok: false, code: 'invite_spent', reason: 'this invitation has already been used' };+ return { ok: true, alreadyMember: false, membership: shapeMembership(member?.[0]), homeLabel: inspected.homeLabel };+}++/**+ * Remove an identity from every household it is in.+ *+ * The deprovisioning path. When an SSO identity is deactivated upstream, losing+ * the session is not enough: the account has standing membership in buildings,+ * and membership outlives a session. Sessions are revoked by the existing auth+ * paths; this is the half that reaches the houses.+ *+ * Owner rows are left alone. An owner's home is their own record, and cascading+ * a deprovision into deleting somebody's house is not a decision an SSO webhook+ * gets to make. Their allowances are still revoked.+ */+export async function revokeAllMemberships(userId) {+ const homes = await withDbRetry(+ () => sql`SELECT home_id, role FROM home_members WHERE user_id = ${userId}`,+ );+ const [removed] = await sql.transaction([+ sql`DELETE FROM home_members WHERE user_id = ${userId} AND role <> 'owner' RETURNING home_id`,+ sql`DELETE FROM home_entity_grants WHERE granted_by = ${userId}`,+ sql`UPDATE home_invites SET revoked_at = now() WHERE accepted_by = ${userId} AND revoked_at IS NULL`,+ ]);+ return { removedFrom: removed.map((r) => r.home_id), ownedHomes: homes.filter((h) => h.role === 'owner').map((h) => h.home_id) };+}diff --git a/api/_lib/home/store.js b/api/_lib/home/store.jsnew file mode 100644index 000000000..0fa0eb240--- /dev/null+++ b/api/_lib/home/store.js@@ -0,0 +1,469 @@+// The connection store: where a user's homes live, and the only module that+// ever touches a home's credential.+//+// Everything here takes and returns plain objects. No HTTP, no `res`, no Home+// Assistant. The runtime (api/_lib/home/runtime.js) and the endpoints+// (api/home/*) sit above it, and neither of them is allowed to write SQL+// against these tables or to read a credential column.+//+// Two invariants this module enforces so its callers cannot get them wrong:+//+// 1. A connection row is NEVER returned with `access_token_enc` on it. The+// safe projection is built in SQL (SAFE_COLUMNS below), so a new caller+// cannot accidentally spread a credential into a response body.+// 2. Ownership is a `where user_id = $1` inside every query, never a check in+// JavaScript after the row is already in hand. A miss and a+// wrong-owner both return null, so the store never leaks the existence of+// another user's home.+//+// `getDecryptedToken` is the single exception to (1), which is exactly why it is+// its own export with its own name: every call site that can hold a plaintext+// key to someone's front door is one grep away.++import { createHash } from 'node:crypto';++import { normalizeBaseUrl } from '../../../packages/home-bridge/src/url.js';+import { logAudit } from '../audit.js';+import { sql } from '../db.js';+import { withDbRetry } from '../db-retry.js';+import { decryptSecret, encryptSecret } from '../secret-box.js';++/** Statuses the schema's check constraint accepts. */+export const HOME_STATUS = Object.freeze({+ PENDING: 'pending',+ CONNECTED: 'connected',+ UNREACHABLE: 'unreachable',+ AUTH_FAILED: 'auth_failed',+ REVOKED: 'revoked',+});++const VALID_STATUSES = new Set(Object.values(HOME_STATUS));+const VALID_TRANSPORTS = new Set(['direct', 'relay']);+const LABEL_MAX = 120;+const DETAIL_MAX = 500;++// Every column a caller may see. `access_token_enc` is absent on purpose and+// must stay absent: this list is the mechanical guarantee behind invariant (1).+const SAFE_COLUMNS = sql`+ id, user_id, label, base_url, token_fingerprint, transport, relay_id,+ capabilities, status, status_detail, last_ok_at, last_error_at,+ created_at, updated_at, revoked_at+`;++/** sha256 of the token, hex. Never reversible, only comparable. */+export function fingerprintToken(token) {+ return createHash('sha256').update(String(token), 'utf8').digest('hex');+}++/**+ * Record that a user connected a house, or refresh the record they already had.+ *+ * The URL is normalized before it is written, because the unique index is over+ * the normalized form: "https://home.example.com/" and "home.example.com" are+ * the same house and must collide, not stack up as two live rows.+ *+ * Re-connecting the same house is an update, not a duplicate: a token rotation+ * lands as new ciphertext and a new fingerprint on the SAME row, so the grants+ * and the action log that reference it survive the rotation.+ *+ * @param {object} input+ * @param {string} input.userId+ * @param {string} input.label what the user calls this home+ * @param {string} input.baseUrl as typed; normalized before write+ * @param {string} input.token a Home Assistant long-lived access token+ * @param {'direct'|'relay'} [input.transport]+ * @param {string|null} [input.relayId]+ * @param {object} [input.capabilities] measured at connect, never assumed+ * @param {string} [input.status]+ * @param {string|null} [input.statusDetail]+ * @returns {Promise<object>} the credential-free row+ */+export async function createConnection({+ userId,+ label,+ baseUrl,+ token,+ transport = 'direct',+ relayId = null,+ capabilities = {},+ status = HOME_STATUS.PENDING,+ statusDetail = null,+}) {+ if (!userId) throw new Error('createConnection: userId is required');+ if (!token) throw new Error('createConnection: a Home Assistant access token is required');+ if (!VALID_TRANSPORTS.has(transport)) throw new Error(`createConnection: unknown transport "${transport}"`);+ if (!VALID_STATUSES.has(status)) throw new Error(`createConnection: unknown status "${status}"`);++ const { http } = normalizeBaseUrl(baseUrl);+ const cleanLabel = normalizeLabel(label) || hostOf(http);+ const enc = await encryptSecret(String(token));+ const fingerprint = fingerprintToken(token);++ const rows = await sql`+ insert into home_connections+ (user_id, label, base_url, access_token_enc, token_fingerprint,+ transport, relay_id, capabilities, status, status_detail)+ values+ (${userId}, ${cleanLabel}, ${http}, ${enc}, ${fingerprint},+ ${transport}, ${relayId}, ${JSON.stringify(capabilities)}::jsonb, ${status}, ${truncate(statusDetail, DETAIL_MAX)})+ on conflict (user_id, base_url) where revoked_at is null+ do update set+ label = excluded.label,+ access_token_enc = excluded.access_token_enc,+ token_fingerprint = excluded.token_fingerprint,+ transport = excluded.transport,+ relay_id = excluded.relay_id,+ capabilities = excluded.capabilities,+ status = excluded.status,+ status_detail = excluded.status_detail,+ updated_at = now()+ returning ${SAFE_COLUMNS}+ `;+ return rows[0];+}++/**+ * One user's live homes, newest first, with no credential on any of them.+ * @param {string} userId+ * @returns {Promise<object[]>}+ */+export async function listConnections(userId) {+ if (!userId) return [];+ return sql`+ select ${SAFE_COLUMNS}+ from home_connections+ where user_id = ${userId} and revoked_at is null+ order by created_at desc+ `;+}++/**+ * One home, ownership-checked in SQL.+ *+ * Returns null both when the id does not exist and when it belongs to somebody+ * else, so a caller cannot distinguish the two and turn this into an oracle for+ * "does this home id exist". The endpoint layer maps null to 404, never 403.+ *+ * @param {string} id+ * @param {string} userId+ * @param {{ includeRevoked?: boolean }} [options]+ * @returns {Promise<object|null>}+ */+export async function getConnection(id, userId, { includeRevoked = false } = {}) {+ if (!id || !userId || !isUuid(id)) return null;+ const rows = includeRevoked+ ? await sql`select ${SAFE_COLUMNS} from home_connections where id = ${id} and user_id = ${userId}`+ : await sql`select ${SAFE_COLUMNS} from home_connections where id = ${id} and user_id = ${userId} and revoked_at is null`;+ return rows[0] || null;+}++/**+ * The ONLY function that returns a plaintext home credential.+ *+ * Its own export, its own name, so `grep -rn getDecryptedToken api/` is a+ * complete list of the places a key to someone's house can be held in memory.+ * It writes nothing and logs nothing: not the token, not a prefix of it, not its+ * length. A revoked home has an empty ciphertext and returns null rather than+ * throwing, because "this home was disconnected" is an ordinary state the caller+ * has to render, not an exception.+ *+ * @param {string} id+ * @param {string} userId+ * @returns {Promise<{ token: string, baseUrl: string, transport: string, relayId: string|null, fingerprint: string }|null>}+ */+export async function getDecryptedToken(id, userId) {+ if (!id || !userId || !isUuid(id)) return null;+ const rows = await sql`+ select access_token_enc, base_url, transport, relay_id, token_fingerprint+ from home_connections+ where id = ${id} and user_id = ${userId} and revoked_at is null+ `;+ const row = rows[0];+ if (!row || !row.access_token_enc) return null;+ return {+ token: await decryptSecret(row.access_token_enc),+ baseUrl: row.base_url,+ transport: row.transport,+ relayId: row.relay_id,+ fingerprint: row.token_fingerprint,+ };+}++/**+ * Record the outcome of a handshake against the house.+ *+ * Called by the runtime on every connect attempt, so the connect UI can explain+ * a broken home without opening a socket of its own. `capabilities` is merged+ * rather than replaced: a failed MCP probe must not erase the WebSocket+ * capabilities a successful one measured a minute earlier.+ *+ * Ownership is not checked here on purpose: the caller has already proved it by+ * holding the id, and the runtime reaches this from a background reconnect where+ * no user is present. It is not reachable from an endpoint without a prior+ * ownership-checked read.+ *+ * @param {string} id+ * @param {{ status: string, statusDetail?: string|null, capabilities?: object|null }} update+ * @returns {Promise<object|null>} the credential-free row+ */+export async function recordHandshake(id, { status, statusDetail = null, capabilities = null } = {}) {+ if (!id || !isUuid(id)) return null;+ if (!VALID_STATUSES.has(status)) throw new Error(`recordHandshake: unknown status "${status}"`);+ const ok = status === HOME_STATUS.CONNECTED;+ const rows = await sql`+ update home_connections set+ status = ${status},+ status_detail = ${truncate(statusDetail, DETAIL_MAX)},+ capabilities = case when ${capabilities === null}::boolean then capabilities+ else capabilities || ${JSON.stringify(capabilities || {})}::jsonb end,+ last_ok_at = case when ${ok}::boolean then now() else last_ok_at end,+ last_error_at = case when ${ok}::boolean then last_error_at else now() end,+ updated_at = now()+ where id = ${id} and revoked_at is null+ returning ${SAFE_COLUMNS}+ `;+ return rows[0] || null;+}++/**+ * Disconnect a home: soft delete the row, destroy the credential.+ *+ * The row survives so the action log keeps its lineage (an operator must still+ * be able to answer "what did my agent do in my house last Tuesday" about a+ * house they have since removed). The ciphertext does not survive: it is+ * overwritten with '' in the same statement, so a database dump taken after a+ * revoke cannot be replayed against the user's front door.+ *+ * Idempotent: revoking twice succeeds twice, and the second call reports+ * `alreadyRevoked` rather than pretending it did the work again.+ *+ * @param {string} id+ * @param {string} userId+ * @returns {Promise<{ revoked: boolean, alreadyRevoked: boolean, home: object|null }>}+ */+export async function revokeConnection(id, userId) {+ if (!id || !userId || !isUuid(id)) return { revoked: false, alreadyRevoked: false, home: null };++ const rows = await sql`+ update home_connections set+ revoked_at = now(),+ access_token_enc = '',+ status = ${HOME_STATUS.REVOKED},+ status_detail = 'Disconnected by the owner.',+ updated_at = now()+ where id = ${id} and user_id = ${userId} and revoked_at is null+ returning ${SAFE_COLUMNS}+ `;++ if (rows[0]) {+ logAudit({+ userId,+ action: 'revoke_home_connection',+ resourceId: id,+ meta: { baseUrl: rows[0].base_url, label: rows[0].label },+ });+ return { revoked: true, alreadyRevoked: false, home: rows[0] };+ }++ // Either it was already revoked, or it is not this user's. Distinguish those+ // for the caller (one is a 200, the other a 404) without a second read that+ // could leak existence: the ownership filter is still in the query.+ const existing = await getConnection(id, userId, { includeRevoked: true });+ return { revoked: false, alreadyRevoked: Boolean(existing), home: existing };+}++/**+ * Grant the agent a standing allowance for ONE entity in one home.+ *+ * Per entity and per home, never per domain: letting the agent open the office+ * door is not letting it open the front door. Re-granting refreshes the expiry+ * on the existing row so a user extending "just for tonight" does not+ * accumulate rows.+ *+ * @param {{ homeId: string, entityId: string, grantedBy: string, expiresAt?: Date|string|null }} input+ * @returns {Promise<object>}+ */+export async function grantEntity({ homeId, entityId, grantedBy, expiresAt = null }) {+ if (!homeId || !isUuid(homeId)) throw new Error('grantEntity: homeId is required');+ if (!grantedBy) throw new Error('grantEntity: grantedBy is required');+ const entity = normalizeEntityId(entityId);+ const rows = await sql`+ insert into home_entity_grants (home_id, entity_id, granted_by, expires_at)+ values (${homeId}, ${entity}, ${grantedBy}, ${expiresAt ? new Date(expiresAt) : null})+ on conflict (home_id, entity_id) do update set+ granted_by = excluded.granted_by,+ expires_at = excluded.expires_at,+ created_at = now()+ returning id, home_id, entity_id, granted_by, expires_at, created_at+ `;+ return rows[0];+}++/**+ * Withdraw a standing allowance. Idempotent.+ * @param {{ homeId: string, entityId: string }} input+ * @returns {Promise<boolean>} true when a grant was actually removed+ */+export async function revokeGrant({ homeId, entityId }) {+ if (!homeId || !isUuid(homeId)) return false;+ const rows = await sql`+ delete from home_entity_grants+ where home_id = ${homeId} and entity_id = ${normalizeEntityId(entityId)}+ returning id+ `;+ return rows.length > 0;+}++/**+ * The live allowances for a home.+ *+ * Expiry is filtered in SQL, not in JavaScript: an expired grant that reaches a+ * caller is an entity the gate would wave through, and "the caller remembered to+ * check the date" is not a security boundary.+ *+ * @param {string} homeId+ * @returns {Promise<object[]>}+ */+export async function listGrants(homeId) {+ if (!homeId || !isUuid(homeId)) return [];+ return sql`+ select id, home_id, entity_id, granted_by, expires_at, created_at+ from home_entity_grants+ where home_id = ${homeId}+ and (expires_at is null or expires_at > now())+ order by entity_id asc+ `;+}++/**+ * The set of entity ids the gate may wave through for this home, ready to hand+ * to `createAllowList` in the bridge.+ * @param {string} homeId+ * @returns {Promise<string[]>}+ */+export async function listAllowedEntities(homeId) {+ const grants = await listGrants(homeId);+ return grants.map((g) => g.entity_id);+}++/**+ * Record a write the platform performed against a house.+ *+ * Fire and forget, mirroring api/_lib/audit.js: it never throws and never blocks+ * a response, because a logging failure must not be able to stop a light from+ * turning on. Use `logHomeActionNow` where the row IS the deliverable.+ *+ * @param {object} entry see logHomeActionNow+ */+export function logHomeAction(entry) {+ queueMicrotask(() => {+ logHomeActionNow(entry);+ });+}++/**+ * The same write, awaitable, resolving true when the row landed.+ *+ * @param {object} entry+ * @param {string} entry.homeId+ * @param {string|null} [entry.userId] null when an agent principal acted with no account+ * @param {'user'|'agent'|'voice'|'mcp'|'automation'} entry.actor+ * @param {'websocket'|'mcp'} entry.channel+ * @param {string} entry.action `light.turn_on`, or the MCP tool name+ * @param {string[]} [entry.entityIds] resolved targets, not the raw argument+ * @param {boolean} [entry.guarded] did the physical-action gate fire+ * @param {string|null} [entry.confirmedBy] who said yes, when it did+ * @param {'security'|'physical'|null} [entry.risk]+ * @param {'ok'|'refused'|'failed'} entry.outcome+ * @param {object|null} [entry.detail] small; no secrets, no state dumps+ * @returns {Promise<boolean>}+ */+export async function logHomeActionNow({+ homeId,+ userId = null,+ actor,+ channel,+ action,+ entityIds = [],+ guarded = false,+ confirmedBy = null,+ risk = null,+ outcome,+ detail = null,+}) {+ try {+ await withDbRetry(+ () => sql`+ insert into home_action_log+ (home_id, user_id, actor, channel, action, entity_ids, guarded, confirmed_by, risk, outcome, detail)+ values+ (${homeId}, ${userId}, ${actor}, ${channel}, ${action},+ ${entityIds.map(String)}, ${Boolean(guarded)}, ${confirmedBy}, ${risk}, ${outcome},+ ${detail === null ? null : JSON.stringify(detail)}::jsonb)+ `,+ { timeoutMs: 5_000 },+ );+ return true;+ } catch (err) {+ console.warn('[home-store] action log insert dropped', { homeId, action, outcome, error: err?.message });+ return false;+ }+}++/**+ * What the agent did in this house, most recent first.+ * @param {string} homeId+ * @param {{ limit?: number, before?: Date|string|null }} [options]+ * @returns {Promise<object[]>}+ */+export async function listHomeActions(homeId, { limit = 50, before = null } = {}) {+ if (!homeId || !isUuid(homeId)) return [];+ const cap = Math.min(Math.max(Number(limit) || 50, 1), 200);+ return before+ ? sql`+ select id, home_id, user_id, actor, channel, action, entity_ids, guarded,+ confirmed_by, risk, outcome, detail, created_at+ from home_action_log+ where home_id = ${homeId} and created_at < ${new Date(before)}+ order by created_at desc+ limit ${cap}+ `+ : sql`+ select id, home_id, user_id, actor, channel, action, entity_ids, guarded,+ confirmed_by, risk, outcome, detail, created_at+ from home_action_log+ where home_id = ${homeId}+ order by created_at desc+ limit ${cap}+ `;+}++function normalizeLabel(label) {+ return typeof label === 'string' ? label.trim().slice(0, LABEL_MAX) : '';+}++function normalizeEntityId(entityId) {+ const id = String(entityId || '').trim().toLowerCase();+ if (!/^[a-z_]+\.[a-z0-9_]+$/.test(id)) {+ throw new Error(`grantEntity: "${entityId}" is not an entity id. Grants are per entity, never per domain.`);+ }+ return id;+}++function truncate(value, max) {+ if (value === null || value === undefined) return null;+ return String(value).slice(0, max);+}++function hostOf(url) {+ try {+ return new URL(url).hostname;+ } catch {+ return 'Home';+ }+}++const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;+function isUuid(value) {+ return UUID_RE.test(String(value));+}diff --git a/api/_lib/home/verify.js b/api/_lib/home/verify.jsnew file mode 100644index 000000000..2116f472b--- /dev/null+++ b/api/_lib/home/verify.js@@ -0,0 +1,119 @@+/**+ * The handshake we run before we agree to store a home.+ *+ * Connecting is the one moment where we can tell the user something true and+ * specific about their instance, so we measure rather than assume: the Home+ * Assistant version, how many entities and areas it actually has, and whether+ * the optional `mcp_server` integration answers (and with how many tools). None+ * of that is inferred from the URL, the token, or a version string we hope is+ * there. If a capability is unknown we say unknown; we never claim one.+ *+ * The MCP probe is deliberately allowed to fail. `mcp_server` is an upgrade, not+ * a requirement: an instance without it is a perfectly good home, and the connect+ * screen offers the setting path rather than an error.+ */++import { connectHomeMcp, ERR, HomeBridge, HomeBridgeError, normalizeBaseUrl } from '@three-ws/home-bridge';++/** A house behind a slow tunnel is common; a hang is not. */+const CONNECT_TIMEOUT_MS = 15_000;+/** The optional channel gets a shorter leash: it must never dominate connect latency. */+const MCP_TIMEOUT_MS = 8_000;++/**+ * Open a real connection, measure it, close it.+ *+ * @param {object} input+ * @param {string} input.baseUrl+ * @param {string} input.token+ * @param {number} [input.timeoutMs]+ * @returns {Promise<{ capabilities: object, graph: object }>}+ * @throws {HomeBridgeError} with the `ERR` vocabulary, so the route layer can+ * map one table of codes instead of two.+ */+export async function verifyConnection({ baseUrl, token, timeoutMs = CONNECT_TIMEOUT_MS }) {+ // Throws BAD_URL before anything opens a socket, which is what lets the UI+ // refuse a LAN address without a network call.+ const { http } = normalizeBaseUrl(baseUrl);++ const bridge = new HomeBridge({ baseUrl: http, token });+ let graph;+ try {+ graph = await withTimeout(+ bridge.connect(),+ timeoutMs,+ () => new HomeBridgeError(ERR.UNREACHABLE, `${http} did not answer within ${Math.round(timeoutMs / 1000)} seconds. If it is only on your home network, three.ws cannot route to it.`),+ );+ } catch (err) {+ bridge.close();+ throw err;+ }++ try {+ const states = bridge.states || {};+ const entityCount = Object.keys(states).length;+ const mcp = await probeMcp({ baseUrl: http, token });++ return {+ graph,+ capabilities: {+ websocket: true,+ entityCount,+ areaCount: graph?.rooms?.length ?? 0,+ floorCount: graph?.floors?.length ?? 0,+ macroCount: bridge.macros().length,+ haVersion: readVersion(states),+ mcp: mcp.available,+ mcpToolCount: mcp.toolCount,+ mcpDetail: mcp.detail,+ measuredAt: new Date().toISOString(),+ },+ };+ } finally {+ bridge.close();+ }+}++/**+ * Home Assistant publishes its own version on the `zone.home`/`sun.sun`-style+ * state attributes only sporadically, but `persistent_notification` and the+ * config entry do not travel over subscribeEntities at all. The reliable place+ * on the state channel is any entity carrying the supervisor/core version+ * attribute; when nothing does, we return null rather than inventing a number.+ */+function readVersion(states) {+ for (const state of Object.values(states)) {+ const v = state?.attributes?.installed_version || state?.attributes?.version;+ if (typeof v === 'string' && /^\d+\.\d+/.test(v)) return v;+ }+ return null;+}++async function probeMcp({ baseUrl, token }) {+ try {+ const session = await withTimeout(+ connectHomeMcp({ baseUrl, token }),+ MCP_TIMEOUT_MS,+ () => new HomeBridgeError(ERR.NO_MCP, 'The MCP endpoint did not answer in time.'),+ );+ const toolCount = Array.isArray(session.tools) ? session.tools.length : 0;+ await session.close().catch(() => {});+ return { available: true, toolCount, detail: null };+ } catch (err) {+ // Not an error: the integration is simply not enabled, or this instance+ // does not expose it to this token. The connect screen offers the setting.+ return {+ available: false,+ toolCount: 0,+ detail: err instanceof HomeBridgeError && err.code === ERR.NO_MCP ? err.message : 'The Model Context Protocol Server integration did not answer.',+ };+ }+}++function withTimeout(promise, ms, makeError) {+ let timer;+ const timeout = new Promise((_resolve, reject) => {+ timer = setTimeout(() => reject(makeError()), ms);+ });+ return Promise.race([promise, timeout]).finally(() => clearTimeout(timer));+}diff --git a/api/_lib/migrations/20260903030000_home_connections.sql b/api/_lib/migrations/20260903030000_home_connections.sqlnew file mode 100644index 000000000..803b84a57--- /dev/null+++ b/api/_lib/migrations/20260903030000_home_connections.sql@@ -0,0 +1,154 @@+begin;++-- three.ws Home: the record that a person connected a real house, the credential+-- that makes it work, what they have standing permission for, and everything the+-- platform did inside their building.+--+-- Home Assistant owns the device layer. We store no devices, no entity states and+-- no room graph: those are a live projection of a live WebSocket and go stale the+-- moment a light changes. What is durable is exactly four things, and they are+-- the four tables below.+--+-- The credential is a Home Assistant long-lived access token. It is a key to a+-- physical building: with it an agent can unlock a front door. It therefore gets+-- the same primitive as a custodial wallet key (AES-256-GCM through+-- api/_lib/secret-box.js) from the first write, never a hash and never plaintext.+-- A hash would be cheaper and is wrong: we have to replay the token on every+-- reconnect, so we need it back, not just a way to compare it.++create table if not exists home_connections (+ id uuid primary key default gen_random_uuid(),+ -- The owner. Households, roles and per-member scopes arrive later and hang+ -- off this row rather than replacing this column: the owner of a house stays+ -- the owner once members exist.+ user_id uuid not null references users(id) on delete cascade,+ -- What the user calls it ("Home", "The office"). User-supplied, so every+ -- render treats it as untrusted text.+ label text not null,+ -- Always the normalized form from normalizeBaseUrl(): scheme present, no+ -- trailing slash, a reverse-proxy path prefix preserved. Storing the raw+ -- input would make the uniqueness constraint below meaningless, because+ -- "ha.example.com" and "https://ha.example.com/" are the same house.+ base_url text not null,+ -- encryptSecret() output. Scrubbed to '' on revoke so a revoked row keeps+ -- its audit lineage without keeping a key to someone's front door.+ access_token_enc text not null,+ -- sha256(token), hex. Lets a re-connect with the same token be idempotent+ -- and a rotation be detectable without decrypting anything, which keeps the+ -- decrypt path down to exactly one function (getDecryptedToken).+ token_fingerprint text not null,+ -- How we reach the house. 'direct' is the user's own https URL; 'relay' is+ -- an add-on inside their LAN dialing out to us.+ transport text not null default 'direct',+ relay_id text,+ -- What this instance can actually do, MEASURED at connect: HA version,+ -- entity count, whether the WebSocket channel opened, whether mcp_server+ -- answered and with how many tools. Never assumed from a version number.+ capabilities jsonb not null default '{}'::jsonb,+ status text not null default 'pending',+ -- The last human-readable reason, so a list view can explain an unreachable+ -- home without a second round trip to the house.+ status_detail text,+ last_ok_at timestamptz,+ last_error_at timestamptz,+ created_at timestamptz not null default now(),+ updated_at timestamptz not null default now(),+ -- Soft delete. The action log below references this row, and an operator has+ -- to be able to answer "what did it do in my house" about a home they have+ -- since disconnected.+ revoked_at timestamptz,+ constraint home_connections_status_chk+ check (status in ('pending', 'connected', 'unreachable', 'auth_failed', 'revoked')),+ constraint home_connections_transport_chk+ check (transport in ('direct', 'relay')),+ -- A relay connection without a relay id is unroutable, and a direct one with+ -- one is a contradiction. Both are bugs, so the database refuses them.+ constraint home_connections_relay_chk+ check ((transport = 'relay') = (relay_id is not null))+);++create index if not exists home_connections_user_idx+ on home_connections (user_id, created_at desc)+ where revoked_at is null;++-- One live record per house per user. Two rows for the same instance means two+-- pooled sockets, two divergent capability snapshots, and a UI that cannot say+-- which one an action ran through. If a genuine need for two appears (two HA+-- accounts on one instance) the second dimension is token_fingerprint, not+-- dropping this.+create unique index if not exists home_connections_user_base_url_uniq+ on home_connections (user_id, base_url)+ where revoked_at is null;++-- The standing per-entity allowances behind the physical-action gate.+--+-- REJECTED, deliberately: a granted_domain column. A user who lets the agent+-- open the office door has not let it open the front door, and Home Assistant's+-- own tool descriptions make this concrete rather than theoretical: its+-- intent__HassTurnOff is documented as performing an UNLOCK on a lock, so an+-- agent told to "turn everything off" reaches locks through a tool whose name+-- says nothing about doors. A domain-wide grant would turn one convenience into+-- a burglary tool. Grants are per entity, and the direction is implicit: only+-- the opening direction is ever guarded, so only the opening direction is ever+-- granted. Locking up, closing and arming never prompt and never need a row here.+create table if not exists home_entity_grants (+ id uuid primary key default gen_random_uuid(),+ home_id uuid not null references home_connections(id) on delete cascade,+ entity_id text not null,+ granted_by uuid not null references users(id),+ -- null means until revoked. The UI must always offer a bounded option, so+ -- "let it in for the next two hours" does not become forever by default.+ expires_at timestamptz,+ created_at timestamptz not null default now()+);++create unique index if not exists home_entity_grants_entity_uniq+ on home_entity_grants (home_id, entity_id);++-- Every write the platform performed against a house.+--+-- Deliberately NOT audit_log. That table is the platform-wide "who deleted what"+-- trail: low volume, one shape, read by us. This one is higher volume by an order+-- of magnitude (every light, every call, from five kinds of actor), carries the+-- physical-action verdict that only exists here, and is read by the HOUSE OWNER,+-- who has to be able to answer "what did my agent do in my house last Tuesday"+-- without a scan across every other tenant's rows.+create table if not exists home_action_log (+ id bigserial primary key,+ home_id uuid not null references home_connections(id) on delete cascade,+ -- null when the actor is an agent principal with no account behind it.+ user_id uuid,+ actor text not null,+ channel text not null,+ -- A Home Assistant service ('light.turn_on') or an MCP tool name.+ action text not null,+ -- The RESOLVED targets, not the raw argument. "turn off the lights" has to+ -- land in this column as the entities it actually touched, or the log cannot+ -- answer the only question anyone asks it.+ entity_ids text[] not null default '{}',+ -- Did the gate fire on this call.+ guarded boolean not null default false,+ -- Who said yes, when it did. Never a model, never an inference: this column+ -- holds a human.+ confirmed_by uuid,+ risk text,+ outcome text not null,+ -- Small. No credentials, no full state dumps: scrubbed through+ -- api/_lib/scrub-secrets.js before it lands.+ detail jsonb,+ created_at timestamptz not null default now(),+ constraint home_action_log_actor_chk+ check (actor in ('user', 'agent', 'voice', 'mcp', 'automation')),+ constraint home_action_log_channel_chk+ check (channel in ('websocket', 'mcp')),+ constraint home_action_log_outcome_chk+ check (outcome in ('ok', 'refused', 'failed')),+ constraint home_action_log_risk_chk+ check (risk is null or risk in ('security', 'physical'))+);++-- The owner's own history, newest first: the only read shape this table has.+create index if not exists home_action_log_home_idx+ on home_action_log (home_id, created_at desc);++commit;diff --git a/api/_lib/migrations/20260903130000_home_members.sql b/api/_lib/migrations/20260903130000_home_members.sqlnew file mode 100644index 000000000..8a988f7be--- /dev/null+++ b/api/_lib/migrations/20260903130000_home_members.sql@@ -0,0 +1,188 @@+begin;++-- Households: who else lives here, what they are allowed to do, and how they+-- got in.+--+-- home_connections is keyed on a single user_id and stays that way. That column+-- is the creating owner and it is never rewritten: membership lands BESIDE it,+-- so nothing that already reads home_connections has to change its shape to+-- keep working. What changes is the question the code above asks. Instead of+-- "is this row's user_id the caller", it becomes "what is this caller's role in+-- this home", and the answer for a house with one person in it is still+-- "owner", derived from the backfill below.+--+-- Why this table has to exist at all: a house has more than one person in it.+-- Without membership the only way to give a partner, a house sitter or a+-- colleague access is to hand over the account password, which for a system+-- that opens doors is the worst outcome available. For the enterprise cases (a+-- hotel, an office, a serviced building) the roles and the attribution ARE the+-- purchase decision.+--+-- Two tables:+--+-- home_members who is in this household, with what role and what scope+-- home_invites a single-use, expiring, role-bound way to become a member+--+-- The one row in the role matrix that justifies the whole design: a `guest`+-- can never confirm a guarded action. A house sitter should be able to turn the+-- lights on and should NOT be able to authorise unlocking the front door. Every+-- other distinction here is convenience; that one is the product.+--+-- Considered and rejected:+--+-- * Custom roles. Five roles cover households, house sitters, offices and+-- hotels. Anything past that needs a policy engine with its own evaluation+-- order, its own conflict rules and its own audit surface, and that is a+-- different product decision than "let my partner turn the lights on".+--+-- * A granted_domain style scope ("all locks"). Same reason home_entity_grants+-- refused one: a scope that names a domain is a scope nobody can reason+-- about at the moment they grant it. entity_scope names areas and entities,+-- both of which the user can see in their own house.+--+-- * Enforcing scope in the UI. The filtered room graph is built server side,+-- before serialization, because a guest who can read the state of a room+-- they were not given has already been given that room. A hidden card in a+-- browser is not a permission boundary.+--+-- * Multiple owners per home. The partial unique index below allows exactly+-- one, which is what makes "you cannot remove the last owner" a schema fact+-- rather than an application check somebody forgets. Ownership transfer,+-- when it is needed, is an UPDATE of that one row, not a second owner.++create table if not exists home_members (+ home_id uuid not null references home_connections(id) on delete cascade,+ user_id uuid not null references users(id) on delete cascade,++ -- owner : the creating account. One per home. Can disconnect the house.+ -- admin : full control including invites, cannot disconnect the house.+ -- member : lives here. Acts, confirms guarded actions, edits the layout.+ -- Cannot invite and cannot grant a standing allowance.+ -- guest : visiting. Scoped reads and scoped ungated actions, and NEVER a+ -- confirmation of a guarded action.+ -- viewer : scoped reads only. A wall display, a monitoring seat.+ role text not null,++ -- {"mode":"all"} or {"mode":"allow","areas":[...],"entities":[...]}.+ -- Meaningful for guest and viewer; owner, admin and member are always+ -- whole-house and the store normalizes their scope to {"mode":"all"} so a+ -- stale allowlist on a promoted member cannot silently narrow them.+ entity_scope jsonb not null default '{"mode":"all"}'::jsonb,++ invited_by uuid references users(id) on delete set null,+ created_at timestamptz not null default now(),+ updated_at timestamptz not null default now(),++ primary key (home_id, user_id),++ constraint home_members_role_chk check (role in ('owner', 'admin', 'member', 'guest', 'viewer')),++ -- The scope is read by the graph projection on every state push. A malformed+ -- one there is a silent unfiltered read, so it is rejected at write time.+ constraint home_members_scope_chk check (+ jsonb_typeof(entity_scope) = 'object'+ and entity_scope->>'mode' in ('all', 'allow')+ )+);++-- "Who is in this household" (the member list) and "which homes can this person+-- see" (every list view, every resolution) are the only two access patterns.+create index if not exists home_members_user_idx on home_members (user_id);++-- Exactly one owner per home. This is what makes removing the last owner+-- impossible rather than merely discouraged.+create unique index if not exists home_members_one_owner_uniq+ on home_members (home_id)+ where role = 'owner';++-- Every home that already existed belongs to the account that created it.+-- Idempotent, so re-running the migration on a database that has already been+-- backfilled is a no-op rather than a conflict.+insert into home_members (home_id, user_id, role, invited_by)+select id, user_id, 'owner', user_id from home_connections+on conflict (home_id, user_id) do nothing;++-- The owner row is created by the database, not by the application.+--+-- api/_lib/home/store.js (the connection store) does not know this table exists,+-- and it should not have to: "a connection has an owner" is an integrity fact+-- about the data, not a step in one code path. A trigger makes it true for every+-- writer, including a future admin tool, a support script and a manual insert,+-- and it means a home can never exist in a state where nobody can administer it.+--+-- Only on INSERT: createConnection upserts, so re-connecting a house with a+-- rotated token updates the existing row and must not disturb a membership list+-- that has since grown.+create or replace function home_connections_seed_owner() returns trigger+language plpgsql as $$+begin+ insert into home_members (home_id, user_id, role, invited_by)+ values (new.id, new.user_id, 'owner', new.user_id)+ on conflict (home_id, user_id) do nothing;+ return new;+end;+$$;++drop trigger if exists home_connections_seed_owner_trg on home_connections;+create trigger home_connections_seed_owner_trg+ after insert on home_connections+ for each row execute function home_connections_seed_owner();+++-- An invitation to join a household.+--+-- Addressed to an email rather than a user id because the person being invited+-- usually does not have an account yet, and requiring them to register before+-- they can be invited is the kind of ordering that kills an onboarding flow.+-- Accepting still requires an account: the existing registration and sign-in+-- paths do that job and this table does not invent a second one.+--+-- The plaintext token leaves the server exactly once, in the invite link. What+-- is stored is sha256 of it, for the same reason a password is not stored: an+-- invite is a bearer credential for a role in a building, and a leaked database+-- must not be a set of working keys.+--+-- Single use is `accepted_at is null`, checked in the same UPDATE that sets it,+-- so two simultaneous redemptions cannot both win.+create table if not exists home_invites (+ id uuid primary key default gen_random_uuid(),+ home_id uuid not null references home_connections(id) on delete cascade,++ -- Lowercased before write. The acceptance path does not require the+ -- accepting account's email to match: the token is the credential, and an+ -- invite forwarded to the right person's other address is a support ticket+ -- we do not want. The email is who it was addressed to, and it is shown in+ -- the pending list so the inviter can see what they sent and to whom.+ email text not null,++ -- No 'owner': ownership is not something an invite can hand out.+ role text not null,+ entity_scope jsonb not null default '{"mode":"all"}'::jsonb,++ token_hash text not null unique,++ invited_by uuid not null references users(id) on delete cascade,+ expires_at timestamptz not null,+ accepted_at timestamptz,+ accepted_by uuid references users(id) on delete set null,+ revoked_at timestamptz,+ created_at timestamptz not null default now(),++ constraint home_invites_role_chk check (role in ('admin', 'member', 'guest', 'viewer')),+ constraint home_invites_scope_chk check (+ jsonb_typeof(entity_scope) = 'object'+ and entity_scope->>'mode' in ('all', 'allow')+ )+);++-- One live invite per person per home, so a re-invite replaces rather than+-- stacks. A spent or revoked invite does not participate, which is what allows+-- re-inviting someone who was removed.+create unique index if not exists home_invites_home_email_live_uniq+ on home_invites (home_id, lower(email))+ where accepted_at is null and revoked_at is null;++-- The pending list for one home, and the redemption lookup by token.+create index if not exists home_invites_home_idx on home_invites (home_id, created_at desc);++commit;diff --git a/api/_lib/migrations/20260903180000_home_privacy_retention.sql b/api/_lib/migrations/20260903180000_home_privacy_retention.sqlnew file mode 100644index 000000000..8cb9d07ba--- /dev/null+++ b/api/_lib/migrations/20260903180000_home_privacy_retention.sql@@ -0,0 +1,103 @@+begin;++-- three.ws Home: retention, and the two schema facts that made "delete my+-- account" and "delete my house" incomplete.+--+-- This migration is the schema half of the privacy lane (docs/home-privacy.md).+-- It changes three things, and every one of them was measured against the live+-- database rather than assumed.+--+-- 1. THE ACTION LOG NEEDS A RETENTION WINDOW, AND IT HAS TO BE THE OWNER'S.+--+-- home_action_log is the answer to "what did my agent do in my house last+-- Tuesday". It is also, read the other way round, a behavioural record of a+-- household: when someone came home, which rooms they lit, what time the+-- bedroom light went off. Those are the same rows. Keeping them forever+-- turns an audit trail into a surveillance archive, and keeping them for a+-- day makes the audit trail useless.+--+-- The default is 90 days. Long enough to answer "what happened last month",+-- short enough that the archive never becomes a history of someone's life.+-- It is per home and it is the owner's to change, down to a single day for+-- a household that wants no trail, and up for an operator (a hotel, an+-- office) whose compliance obligation is longer than ours. An extension past+-- the default has to carry a written reason, because "why does this building+-- keep two years of occupancy data" is a question somebody will be asked.+--+-- 2. A GRANT COULD BLOCK ACCOUNT DELETION.+--+-- home_entity_grants.granted_by referenced users(id) with NO action. The+-- owner's own deletion happens to work (their homes cascade, which cascades+-- their grants, in the same statement), but a grant made by a household+-- MEMBER on someone else's home has no such cascade: that member's account+-- deletion fails outright on a foreign-key violation. Deleting the grant is+-- also the privacy-correct behaviour on its own terms. The person who+-- granted the standing allowance is gone; the allowance goes with them,+-- rather than outliving the human who authorised it.+--+-- 3. THE PURGE NEEDS AN INDEX IT CAN ACTUALLY USE.+--+-- The sweep asks one question per home, "which rows here are older than this+-- home's own window", and the existing (home_id, created_at desc) index+-- answers it directly. No new index: the ascending scan the purge wants is+-- the same index read backwards, which Postgres does natively.+--+-- Deliberately NOT here: any table that would persist entity STATE. The room+-- graph and every entity's state live in the bridge runtime's memory and die+-- with the instance, on purpose. A persisted history of "the bedroom light went+-- on at 23:14" is an occupancy record for a building, and this campaign does not+-- create one. See docs/home-privacy.md.++alter table home_connections+ add column if not exists action_log_retention_days integer not null default 90;++alter table home_connections+ add column if not exists action_log_retention_reason text;++alter table home_connections+ add column if not exists action_log_retention_set_by uuid;++alter table home_connections+ add column if not exists action_log_retention_set_at timestamptz;++-- 1 day is "keep essentially nothing"; 3650 is ten years, past any retention+-- obligation an operator has actually cited to us. Both ends are guard rails+-- against a typo in an API call, not product opinions.+do $$+begin+ if not exists (+ select 1 from pg_constraint where conname = 'home_connections_retention_days_chk'+ ) then+ alter table home_connections+ add constraint home_connections_retention_days_chk+ check (action_log_retention_days between 1 and 3650);+ end if;+end $$;++-- An extension past the 90-day default must say why. Shortening never needs a+-- reason: keeping less of someone's data is never the decision that has to be+-- justified.+do $$+begin+ if not exists (+ select 1 from pg_constraint where conname = 'home_connections_retention_reason_chk'+ ) then+ alter table home_connections+ add constraint home_connections_retention_reason_chk+ check (+ action_log_retention_days <= 90+ or (action_log_retention_reason is not null+ and length(btrim(action_log_retention_reason)) >= 8)+ );+ end if;+end $$;++-- (2) above: a grant must not be able to pin a user row in place.+alter table home_entity_grants+ drop constraint if exists home_entity_grants_granted_by_fkey;++alter table home_entity_grants+ add constraint home_entity_grants_granted_by_fkey+ foreign key (granted_by) references users(id) on delete cascade;++commit;diff --git a/packages/home-bridge/src/bridge.js b/packages/home-bridge/src/bridge.jsindex f736b9293..eb81794a3 100644--- a/packages/home-bridge/src/bridge.js+++ b/packages/home-bridge/src/bridge.js@@ -58,6 +58,21 @@ export class HomeBridge {return Boolean(this.#connection?.connected);}+ /**+ * The Home Assistant version this instance reported during the handshake, or+ * null before connect(). Measured from the socket, never guessed: the connect+ * screen and the capability record both have to state what the house actually+ * is, and a version is how a support conversation starts.+ */+ get haVersion() {+ return this.#connection?.haVersion || null;+ }++ /** The registries as loaded at connect: floors, areas, devices, entities. */+ get registries() {+ return this.#registries;+ }+/** The room graph the 3D scene renders. Rebuilt on every state burst. */get graph() {return this.#graph;diff --git a/scripts/home-fleet.mjs b/scripts/home-fleet.mjsnew file mode 100644index 000000000..391695214--- /dev/null+++ b/scripts/home-fleet.mjs@@ -0,0 +1,469 @@+#!/usr/bin/env node+/**+ * A fleet of real Home Assistant instances, for the Home lane's load and chaos work.+ *+ * Every measurement in docs/home-operations.md is taken against containers this+ * script starts: real Home Assistant, real onboarding, real long-lived access+ * tokens, real WebSocket handshakes. Nothing here simulates Home Assistant, and+ * nothing here ever points at somebody's house. The only hosts it touches are+ * containers on this machine.+ *+ * node scripts/home-fleet.mjs up --homes 10 # a small-house fleet+ * node scripts/home-fleet.mjs up --homes 4 --big 1 --slow 1+ * node scripts/home-fleet.mjs status+ * node scripts/home-fleet.mjs down+ *+ * `up` writes a manifest to tasks/home/fleet.local.json (gitignored: it holds+ * live tokens to running containers). scripts/home-load.mjs reads it.+ */++import { spawn } from 'node:child_process';+import { mkdir, readFile, rm, writeFile } from 'node:fs/promises';+import { createServer, connect as netConnect } from 'node:net';+import path from 'node:path';+import process from 'node:process';+import { fileURLToPath } from 'node:url';++import WebSocket from 'ws';++const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');+const MANIFEST = path.join(ROOT, 'tasks', 'home', 'fleet.local.json');+const CONFIG_ROOT = path.join(ROOT, '.home-fleet');+const IMAGE = 'ghcr.io/home-assistant/home-assistant:stable';+const NAME_PREFIX = 'threews-ha-';+const BASE_PORT = 18200;+const PASSWORD = 'threews-load-harness';++/** A "large house": the entity count order 14 measures the expensive end against. */+const BIG_HOUSE_ENTITIES = 500;++// ---------------------------------------------------------------- shell helpers++function run(cmd, args, { capture = true } = {}) {+ return new Promise((resolve, reject) => {+ const child = spawn(cmd, args, { stdio: capture ? ['ignore', 'pipe', 'pipe'] : 'inherit' });+ let out = '';+ let err = '';+ child.stdout?.on('data', (d) => (out += d));+ child.stderr?.on('data', (d) => (err += d));+ child.on('error', reject);+ child.on('close', (code) => {+ if (code === 0) resolve(out.trim());+ else reject(new Error(`${cmd} ${args.join(' ')} exited ${code}: ${err.trim() || out.trim()}`));+ });+ });+}++const docker = (...args) => run('docker', args);+const sleep = (ms) => new Promise((r) => setTimeout(r, ms));++// ---------------------------------------------------------------- configuration++/**+ * Home Assistant's configuration for one fixture house.+ *+ * `demo:` is the integration the home-bridge tests already use: it produces a+ * realistic mix of lights, covers, locks, climate and sensors that changes on+ * its own, which is what makes the state-burst measurements honest. The extra+ * helper entities exist only on the big house, and they are the ones the load+ * harness drives when it needs a controlled update rate.+ */+function configurationYaml({ big }) {+ const lines = [+ '# Written by scripts/home-fleet.mjs. This is a load fixture, not a home.',+ 'default_config:',+ 'demo:',+ 'logger:',+ ' default: warning',+ 'http:',+ ' server_port: 8123',+ ];+ if (!big) return `${lines.join('\n')}\n`;++ const booleans = [];+ const numbers = [];+ const texts = [];+ const per = Math.ceil(BIG_HOUSE_ENTITIES / 3);+ for (let i = 0; i < per; i++) {+ booleans.push(` load_switch_${i}:\n name: Load Switch ${i}`);+ numbers.push(` load_level_${i}:\n name: Load Level ${i}\n min: 0\n max: 100\n step: 1\n mode: box`);+ texts.push(` load_note_${i}:\n name: Load Note ${i}\n max: 60`);+ }+ lines.push('input_boolean:', ...booleans, 'input_number:', ...numbers, 'input_text:', ...texts);+ return `${lines.join('\n')}\n`;+}++// ---------------------------------------------------------------- onboarding++async function waitForHttp(url, timeoutMs) {+ const deadline = Date.now() + timeoutMs;+ let lastError = 'no response';+ while (Date.now() < deadline) {+ try {+ const res = await fetch(url, { redirect: 'manual' });+ if (res.status < 500) return true;+ lastError = `status ${res.status}`;+ } catch (err) {+ lastError = err.message;+ }+ await sleep(1000);+ }+ throw new Error(`${url} never came up within ${timeoutMs}ms (${lastError})`);+}++async function postJson(url, body, token) {+ const res = await fetch(url, {+ method: 'POST',+ headers: {+ 'content-type': 'application/json',+ ...(token ? { authorization: `Bearer ${token}` } : {}),+ },+ body: JSON.stringify(body),+ });+ const text = await res.text();+ if (!res.ok) throw new Error(`POST ${url} -> ${res.status} ${text.slice(0, 200)}`);+ return text ? JSON.parse(text) : null;+}++/**+ * Walk Home Assistant's real onboarding API, exactly as the browser does, and+ * come back with an access token. There is no shortcut here and there should+ * not be: an instance that has not been onboarded rejects every other call.+ */+async function onboard(baseUrl, username) {+ const clientId = `${baseUrl}/`;+ const { auth_code: code } = await postJson(`${baseUrl}/api/onboarding/users`, {+ client_id: clientId,+ name: 'Load Harness Owner',+ username,+ password: PASSWORD,+ language: 'en',+ });++ const form = new URLSearchParams({ grant_type: 'authorization_code', code, client_id: clientId });+ const res = await fetch(`${baseUrl}/auth/token`, {+ method: 'POST',+ headers: { 'content-type': 'application/x-www-form-urlencoded' },+ body: form,+ });+ if (!res.ok) throw new Error(`token exchange -> ${res.status} ${await res.text()}`);+ const { access_token: accessToken } = await res.json();++ await postJson(+ `${baseUrl}/api/onboarding/core_config`,+ { client_id: clientId },+ accessToken,+ ).catch(() => null);+ await postJson(`${baseUrl}/api/onboarding/analytics`, {}, accessToken).catch(() => null);+ await postJson(`${baseUrl}/api/onboarding/integration`, { client_id: clientId, redirect_uri: clientId }, accessToken).catch(() => null);++ return accessToken;+}++// ---------------------------------------------------------------- websocket work++/**+ * A minimal authenticated WebSocket session against one instance.+ *+ * home-assistant-js-websocket is the client the product uses, but it is built to+ * hold a connection open and reconnect forever, which is the wrong shape for a+ * three-message provisioning errand. This is the errand-sized version and it is+ * used for exactly two things: minting the long-lived token and seeding the area+ * registry.+ */+async function wsSession(baseUrl, token, work) {+ const wsUrl = `${baseUrl.replace(/^http/, 'ws')}/api/websocket`;+ const socket = new WebSocket(wsUrl);+ const pending = new Map();+ let id = 1;++ const ready = new Promise((resolve, reject) => {+ socket.on('error', reject);+ socket.on('close', () => reject(new Error('socket closed before auth completed')));+ socket.on('message', (raw) => {+ const msg = JSON.parse(raw.toString());+ if (msg.type === 'auth_required') {+ socket.send(JSON.stringify({ type: 'auth', access_token: token }));+ return;+ }+ if (msg.type === 'auth_ok') {+ resolve();+ return;+ }+ if (msg.type === 'auth_invalid') {+ reject(new Error(`auth rejected: ${msg.message}`));+ return;+ }+ const waiter = pending.get(msg.id);+ if (!waiter) return;+ pending.delete(msg.id);+ if (msg.success === false) waiter.reject(new Error(msg.error?.message || 'command failed'));+ else waiter.resolve(msg.result);+ });+ });++ await ready;+ const send = (payload) =>+ new Promise((resolve, reject) => {+ const messageId = id++;+ pending.set(messageId, { resolve, reject });+ socket.send(JSON.stringify({ ...payload, id: messageId }));+ });++ try {+ return await work(send);+ } finally {+ socket.close();+ }+}++/**+ * Home Assistant's demo integration ships entities but no areas, and the room+ * graph the 3D scene renders is built from the area registry. A fixture house+ * with zero areas would understate the graph rebuild cost, so every house in the+ * fleet gets a real floor and real areas through the real registry API.+ */+const FLOORS = [+ { name: 'Ground floor', areas: ['Kitchen', 'Living Room', 'Hallway', 'Garage'] },+ { name: 'Upstairs', areas: ['Bedroom', 'Bathroom', 'Study'] },+];++async function seedRegistry(send) {+ const areas = [];+ for (const floor of FLOORS) {+ let floorId = null;+ try {+ const created = await send({ type: 'config/floor_registry/create', name: floor.name });+ floorId = created?.floor_id ?? null;+ } catch {+ // Instances older than the floor registry are still valid fixtures; the+ // areas below simply land unassigned, which the graph already handles.+ }+ for (const name of floor.areas) {+ try {+ const area = await send({ type: 'config/area_registry/create', name, ...(floorId ? { floor_id: floorId } : {}) });+ areas.push(area);+ } catch {+ // A duplicate name on a re-run is not a failure.+ }+ }+ }++ // Spread the house's entities across those areas, so the graph has real rooms+ // with real rollups rather than one giant unassigned bucket.+ const entities = await send({ type: 'config/entity_registry/list' });+ const assignable = entities.filter((e) => !e.area_id);+ let assigned = 0;+ for (let i = 0; i < assignable.length && areas.length; i++) {+ const area = areas[i % areas.length];+ try {+ await send({ type: 'config/entity_registry/update', entity_id: assignable[i].entity_id, area_id: area.area_id });+ assigned++;+ } catch {+ // Some entities are not registry entries and cannot carry an area.+ }+ }+ return { floors: FLOORS.length, areas: areas.length, entitiesAssigned: assigned };+}++async function mintLongLivedToken(send, clientName) {+ return send({ type: 'auth/long_lived_access_token', client_name: clientName, client_icon: null, lifespan: 3650 });+}++// ---------------------------------------------------------------- latency shim++/**+ * A TCP proxy that delays every byte in both directions by a fixed amount.+ *+ * Chaos scenario 6 needs a genuinely slow house, and slowing one is the only+ * honest way to prove the fast one beside it is unaffected. Delaying at the+ * socket rather than inside Home Assistant means the slowness looks exactly like+ * a distant house on a bad link, which is the real-world failure being modelled.+ */+export function startLatencyShim({ listenPort, targetPort, delayMs, targetHost = '127.0.0.1' }) {+ const server = createServer((client) => {+ const upstream = netConnect(targetPort, targetHost);+ const pipeDelayed = (from, to) => {+ from.on('data', (chunk) => {+ setTimeout(() => {+ if (!to.destroyed) to.write(chunk);+ }, delayMs);+ });+ from.on('close', () => setTimeout(() => to.destroy(), delayMs + 50));+ from.on('error', () => to.destroy());+ };+ pipeDelayed(client, upstream);+ pipeDelayed(upstream, client);+ });+ return new Promise((resolve, reject) => {+ server.once('error', reject);+ server.listen(listenPort, '127.0.0.1', () => resolve(server));+ });+}++// ---------------------------------------------------------------- fleet lifecycle++async function listContainers() {+ const out = await docker('ps', '-a', '--filter', `name=${NAME_PREFIX}`, '--format', '{{.Names}}\t{{.Status}}');+ return out+ .split('\n')+ .filter(Boolean)+ .map((line) => {+ const [name, status] = line.split('\t');+ return { name, status };+ });+}++async function startHouse({ index, big }) {+ const name = `${NAME_PREFIX}${index}`;+ const port = BASE_PORT + index;+ const configDir = path.join(CONFIG_ROOT, String(index));++ await docker('rm', '-f', name).catch(() => null);+ await rm(configDir, { recursive: true, force: true });+ await mkdir(configDir, { recursive: true });+ await writeFile(path.join(configDir, 'configuration.yaml'), configurationYaml({ big }));+ await writeFile(path.join(configDir, 'automations.yaml'), '[]\n');++ await docker(+ 'run', '-d',+ '--name', name,+ '-p', `127.0.0.1:${port}:8123`,+ '-e', 'TZ=UTC',+ '-v', `${configDir}:/config`,+ IMAGE,+ );++ const baseUrl = `http://127.0.0.1:${port}`;+ const startedAt = Date.now();+ await waitForHttp(`${baseUrl}/`, big ? 300_000 : 180_000);+ const bootMs = Date.now() - startedAt;++ const accessToken = await onboard(baseUrl, `owner${index}`);+ const registry = await wsSession(baseUrl, accessToken, seedRegistry);+ const token = await wsSession(baseUrl, accessToken, (send) => mintLongLivedToken(send, `three.ws load harness ${index}`));++ const states = await fetch(`${baseUrl}/api/states`, { headers: { authorization: `Bearer ${token}` } }).then((r) => r.json());++ return {+ index,+ name,+ baseUrl,+ port,+ token,+ big: Boolean(big),+ bootMs,+ entityCount: states.length,+ registry,+ };+}++async function up({ homes, big, slow }) {+ await mkdir(path.dirname(MANIFEST), { recursive: true });+ console.log(`starting ${homes} Home Assistant container(s) (${big} large), image ${IMAGE}`);++ // Home Assistant's first boot is CPU heavy and largely serial inside the+ // container, so starting them in one wave is faster than in sequence but a+ // full parallel storm on a 16 core box starves each one. Four at a time is+ // the measured sweet spot on this machine.+ const specs = Array.from({ length: homes }, (_, i) => ({ index: i, big: i < big }));+ const houses = [];+ const WAVE = 4;+ for (let i = 0; i < specs.length; i += WAVE) {+ const wave = specs.slice(i, i + WAVE);+ const settled = await Promise.all(+ wave.map((spec) =>+ startHouse(spec).then(+ (house) => ({ ok: true, house }),+ (error) => ({ ok: false, index: spec.index, error: error.message }),+ ),+ ),+ );+ for (const result of settled) {+ if (result.ok) {+ houses.push(result.house);+ console.log(` up ${result.house.name} ${result.house.baseUrl} ${result.house.entityCount} entities boot ${result.house.bootMs}ms`);+ } else {+ console.error(` FAIL house ${result.index}: ${result.error}`);+ }+ }+ }++ if (!houses.length) throw new Error('no house came up; nothing to measure');++ const manifest = {+ createdAt: new Date().toISOString(),+ image: IMAGE,+ slowShim: slow ? { listenPort: BASE_PORT + 900, delayMs: 2000, targetIndex: houses[houses.length - 1].index } : null,+ houses,+ };+ await writeFile(MANIFEST, `${JSON.stringify(manifest, null, 2)}\n`);+ console.log(`\nmanifest: ${path.relative(ROOT, MANIFEST)} (${houses.length} houses)`);+ return manifest;+}++async function down() {+ const containers = await listContainers();+ for (const { name } of containers) {+ await docker('rm', '-f', name).catch(() => null);+ console.log(` removed ${name}`);+ }+ await rm(CONFIG_ROOT, { recursive: true, force: true });+ await rm(MANIFEST, { force: true });+ console.log(containers.length ? `\n${containers.length} container(s) removed` : 'nothing running');+}++async function status() {+ const containers = await listContainers();+ if (!containers.length) {+ console.log('no fleet containers');+ return;+ }+ for (const { name, status: state } of containers) console.log(` ${name}\t${state}`);+ const manifest = await readFile(MANIFEST, 'utf8').then(JSON.parse).catch(() => null);+ if (manifest) {+ console.log(`\nmanifest from ${manifest.createdAt}: ${manifest.houses.length} houses, ${manifest.houses.reduce((n, h) => n + h.entityCount, 0)} entities total`);+ }+}++export async function readFleet() {+ const raw = await readFile(MANIFEST, 'utf8').catch(() => null);+ if (!raw) throw new Error(`no fleet manifest at ${path.relative(ROOT, MANIFEST)}. Run: node scripts/home-fleet.mjs up --homes 10`);+ return JSON.parse(raw);+}++export { MANIFEST, NAME_PREFIX, BASE_PORT };++// ---------------------------------------------------------------- cli++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;+}++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] || 'status';+ const run = {+ up: () => up({ homes: Number(args.homes || 10), big: Number(args.big || 0), slow: Boolean(args.slow) }),+ down,+ status,+ }[command];+ if (!run) {+ console.error(`unknown command "${command}". Use: up | down | status`);+ process.exit(2);+ }+ run().then(+ () => process.exit(0),+ (err) => {+ console.error(err.stack || err.message);+ process.exit(1);+ },+ );+}diff --git a/scripts/provision-home-assistant.mjs b/scripts/provision-home-assistant.mjsnew file mode 100644index 000000000..caecc4af5--- /dev/null+++ b/scripts/provision-home-assistant.mjs@@ -0,0 +1,170 @@+#!/usr/bin/env node+// Drives a fresh Home Assistant container through onboarding and prints a+// long-lived access token, so every order in the home campaign can verify+// against a REAL instance instead of a mock.+//+// A throwaway instance plus a usable token, in two commands:+//+// docker run -d --name threews-ha -p 8123:8123 -v "$PWD/.ha-config:/config" \+// ghcr.io/home-assistant/home-assistant:stable+// node scripts/provision-home-assistant.mjs --url http://localhost:8123 --demo+//+// It prints shell-ready exports:+//+// export HOME_ASSISTANT_URL=http://localhost:8123+// export HOME_ASSISTANT_TOKEN=eyJhbGciOi...+//+// --demo appends the `demo:` integration to the instance's configuration.yaml+// through Home Assistant's own file API is not a thing, so it is written by the+// caller; this script instead creates areas, a floor and a scene over the+// WebSocket API, which is what the room graph actually reads.+//+// The credentials it creates are throwaway QA credentials for a local container.+// Never point this at an instance that controls a real building.++const args = process.argv.slice(2);+const arg = (name, fallback) => {+ const i = args.indexOf(`--${name}`);+ return i === -1 ? fallback : args[i + 1];+};++const HA = String(arg('url', process.env.HOME_ASSISTANT_URL || 'http://localhost:8123')).replace(/\/+$/, '');+const USERNAME = arg('username', 'threews');+const PASSWORD = arg('password', 'threews-home-qa');+const CLIENT_ID = `${HA}/`;+const wantRooms = args.includes('--rooms');++const log = (...a) => console.error('[provision]', ...a);++async function post(path, body, { form = false, token = null } = {}) {+ const headers = { 'content-type': form ? 'application/x-www-form-urlencoded' : 'application/json' };+ if (token) headers.authorization = `Bearer ${token}`;+ const res = await fetch(`${HA}${path}`, {+ method: 'POST',+ headers,+ body: body === undefined ? undefined : form ? new URLSearchParams(body) : JSON.stringify(body),+ });+ const text = await res.text();+ let json = null;+ try {+ json = JSON.parse(text);+ } catch {+ // Home Assistant answers a few onboarding errors with an HTML page.+ }+ if (!res.ok) throw new Error(`POST ${path} -> ${res.status} ${text.slice(0, 300)}`);+ return json;+}++async function onboardingSteps() {+ const res = await fetch(`${HA}/api/onboarding`);+ if (!res.ok) throw new Error(`GET /api/onboarding -> ${res.status}`);+ return res.json();+}++/** One authenticated WebSocket session, with a promise per command id. */+async function openSocket(token) {+ const ws = new WebSocket(`${HA.replace(/^http/, 'ws')}/api/websocket`);+ const pending = new Map();+ let nextId = 1;++ await new Promise((resolve, reject) => {+ ws.addEventListener('error', () => reject(new Error(`Could not open a WebSocket to ${HA}.`)), { once: true });+ ws.addEventListener('message', (event) => {+ const msg = JSON.parse(event.data);+ if (msg.type === 'auth_required') {+ ws.send(JSON.stringify({ type: 'auth', access_token: token }));+ return;+ }+ if (msg.type === 'auth_ok') return resolve();+ if (msg.type === 'auth_invalid') return reject(new Error('Home Assistant rejected the access token.'));+ const entry = pending.get(msg.id);+ if (!entry) return;+ pending.delete(msg.id);+ msg.success ? entry.resolve(msg.result) : entry.reject(new Error(JSON.stringify(msg.error)));+ });+ });++ return {+ send(payload) {+ const id = nextId++;+ return new Promise((resolve, reject) => {+ pending.set(id, { resolve, reject });+ ws.send(JSON.stringify({ id, ...payload }));+ });+ },+ close() {+ ws.close();+ },+ };+}++const steps = await onboardingSteps();+const userDone = steps.find((s) => s.step === 'user')?.done;++let bearer;+if (userDone) {+ log('already onboarded, signing in as', USERNAME);+ bearer = await signIn();+} else {+ const created = await post('/api/onboarding/users', {+ client_id: CLIENT_ID,+ name: 'three.ws QA',+ username: USERNAME,+ password: PASSWORD,+ language: 'en',+ });+ const token = await post('/auth/token', { grant_type: 'authorization_code', code: created.auth_code, client_id: CLIENT_ID }, { form: true });+ bearer = token.access_token;+ log('created the owner account');++ for (const step of ['core_config', 'analytics']) {+ try {+ await post(`/api/onboarding/${step}`, undefined, { token: bearer });+ } catch (err) {+ // analytics is optional on some builds and answers 403 once done.+ log(`onboarding ${step}:`, String(err.message).slice(0, 120));+ }+ }+ await post('/api/onboarding/integration', { client_id: CLIENT_ID, redirect_uri: `${HA}/?auth_callback=1` }, { token: bearer });+ log('onboarding complete');+}++/** The login flow, for an instance that is already onboarded. */+async function signIn() {+ const flow = await post('/auth/login_flow', {+ client_id: CLIENT_ID,+ handler: ['homeassistant', null],+ redirect_uri: `${HA}/?auth_callback=1`,+ });+ const step = await post(`/auth/login_flow/${flow.flow_id}`, { client_id: CLIENT_ID, username: USERNAME, password: PASSWORD });+ if (!step.result) throw new Error(`login failed: ${JSON.stringify(step).slice(0, 200)}`);+ const token = await post('/auth/token', { grant_type: 'authorization_code', code: step.result, client_id: CLIENT_ID }, { form: true });+ return token.access_token;+}++const socket = await openSocket(bearer);+const longLived = await socket.send({ type: 'auth/long_lived_access_token', client_name: `three.ws ${Date.now()}`, lifespan: 3650 });++if (wantRooms) {+ const floors = await socket.send({ type: 'config/floor_registry/list' });+ let floorId = floors[0]?.floor_id;+ if (!floorId) {+ const floor = await socket.send({ type: 'config/floor_registry/create', name: 'Ground floor', level: 0 });+ floorId = floor.floor_id;+ log('created floor', floor.name);+ }+ const areas = await socket.send({ type: 'config/area_registry/list' });+ // Home Assistant slugs an area name into its id, so "Living room" and+ // "living_room" collide. Compare on the slug, not on the display name.+ const slug = (name) => name.toLowerCase().replace(/[^a-z0-9]+/g, '');+ const have = new Set(areas.flatMap((a) => [slug(a.name), slug(a.area_id)]));+ for (const name of ['Kitchen', 'Living room', 'Bedroom']) {+ if (have.has(slug(name))) continue;+ await socket.send({ type: 'config/area_registry/create', name, floor_id: floorId });+ log('created area', name);+ }+}++socket.close();++process.stdout.write(`export HOME_ASSISTANT_URL=${HA}\nexport HOME_ASSISTANT_TOKEN=${longLived}\n`);diff --git a/services/home-relay/src/protocol.js b/services/home-relay/src/protocol.jsnew file mode 100644index 000000000..6aa3eb96d--- /dev/null+++ b/services/home-relay/src/protocol.js@@ -0,0 +1,412 @@+/**+ * The three.ws home relay wire protocol, version 1.+ *+ * This module is pure. It owns the framing, the version negotiation and, most+ * importantly, the allowlist. It has no sockets, no timers and no I/O, so the+ * one part of this system that must never be wrong can be tested exhaustively+ * without a network.+ *+ * ## Why a relay exists at all+ *+ * Home Assistant lives on a LAN. three.ws is served over https from Cloud Run+ * and cannot route to RFC1918 space. The house therefore dials out to us: one+ * outbound WebSocket from a three.ws integration running inside Home Assistant,+ * to this relay. No port is forwarded, nothing listens on the user's network,+ * and no inbound firewall rule is needed.+ *+ * ## Why this is not an HTTP proxy+ *+ * The obvious implementation is "forward any HTTP request into the LAN". That+ * would be the single worst thing this platform could ship: a caller-chosen+ * path into someone's home network. This protocol instead carries a fixed,+ * enumerated set of Home Assistant WebSocket message types, and refuses+ * everything else at both ends.+ *+ * The allowlist below is derived from what `packages/home-bridge` actually+ * sends, which in turn is what `home-assistant-js-websocket` emits for the+ * three channels the product uses: the entity subscription, the four registry+ * reads, and service calls. Nothing else has ever been needed, so nothing else+ * is permitted.+ *+ * ## Where the allowlist is enforced+ *+ * Twice, independently:+ *+ * 1. In the relay (`server.js`), so a compromised or buggy platform-side+ * caller cannot reach past it.+ * 2. In the integration inside the house (`relay_client.py`), so a compromised+ * relay cannot either. This is the property that matters: the relay is+ * operated by us and is therefore exactly the component a user has to+ * trust least. See `docs/home-relay-threat-model.md`.+ *+ * Both enforcement points import their rules from the same enumeration: this+ * file is the source of truth, and `services/home-relay/allowlist.json` is the+ * generated copy the Python side reads, kept honest by a test.+ */++/** The only protocol version this build speaks. */+export const PROTOCOL_VERSION = 1;++/**+ * The oldest integration build the relay will still talk to. Bumping this is+ * how an old add-on is told to upgrade, which is state 5 in the connect UI:+ * a named version and an upgrade path, never a silent failure.+ */+export const MIN_AGENT_PROTOCOL = 1;++/** Frame types on the control and session planes. */+export const FRAME = {+ /** agent to relay: I am here, this is my build. */+ HELLO: 'hello',+ /** relay to agent: accepted, here is the heartbeat interval. */+ HELLO_OK: 'hello.ok',+ /** relay to agent: refused, with a reason a human can act on. */+ HELLO_ERR: 'hello.err',+ /** either direction: liveness. */+ PING: 'ping',+ PONG: 'pong',+ /** bridge to agent: open a Home Assistant session for this sid. */+ SESSION_OPEN: 'session.open',+ /** agent to bridge: the session is live, and this is the house's HA version. */+ SESSION_READY: 'session.ready',+ /** either direction: this session is over, with a coded reason. */+ SESSION_CLOSE: 'session.close',+ /** either direction: one Home Assistant WebSocket message, allowlisted. */+ HA: 'ha',+};++const FRAME_TYPES = new Set(Object.values(FRAME));++/** Coded close and refusal reasons. The UI maps these to real sentences. */+export const CODE = {+ OK: 'ok',+ /** The integration is older than MIN_AGENT_PROTOCOL. */+ PROTOCOL_TOO_OLD: 'protocol_too_old',+ /** The relay is older than the integration expects. */+ PROTOCOL_TOO_NEW: 'protocol_too_new',+ /** The bearer token did not verify. */+ UNAUTHORIZED: 'unauthorized',+ /** This relay id has been revoked in three.ws. */+ REVOKED: 'revoked',+ /** No integration is currently dialled in for this relay id. */+ AGENT_OFFLINE: 'agent_offline',+ /** A frame carried a message type outside the allowlist. */+ NOT_ALLOWED: 'not_allowed',+ /** The frame was not valid protocol. */+ MALFORMED: 'malformed',+ /** Per-install rate limit tripped. */+ RATE_LIMITED: 'rate_limited',+ /** Home Assistant itself refused or dropped the local connection. */+ HA_UNREACHABLE: 'ha_unreachable',+ /** The relay or the integration is shutting down. */+ GOING_AWAY: 'going_away',+ /** Too many concurrent sessions for one install. */+ TOO_MANY_SESSIONS: 'too_many_sessions',+};++/**+ * Home Assistant WebSocket message types the platform may send INTO a house.+ *+ * Every entry is justified by a real call site in `packages/home-bridge`:+ *+ * supported_features sent once after auth by home-assistant-js-websocket+ * get_states the initial entity snapshot+ * get_config the instance's own name, unit system and location+ * subscribe_entities the live state channel (HA 2022.4 and newer)+ * subscribe_events the legacy live state channel, state_changed only+ * unsubscribe_events tearing either of those down+ * ping liveness+ * config/floor_registry/list+ * config/area_registry/list the room graph the 3D scene renders+ * config/device_registry/list+ * config/entity_registry/list+ * call_service the only type that actuates anything+ *+ * Notably absent, and deliberately: `auth`, because authentication never+ * crosses the relay (the integration authenticates locally, inside the house);+ * `get_services`, `auth/current_user`, and every `config/*` write.+ */+export const OUTBOUND_TYPES = Object.freeze([+ 'supported_features',+ 'get_states',+ 'get_config',+ 'subscribe_entities',+ 'subscribe_events',+ 'unsubscribe_events',+ 'ping',+ 'config/floor_registry/list',+ 'config/area_registry/list',+ 'config/device_registry/list',+ 'config/entity_registry/list',+ 'call_service',+]);++/**+ * Message types the house may send OUT. Home Assistant's WebSocket API answers+ * in exactly three shapes plus the pong, so nothing else needs to leave.+ */+export const INBOUND_TYPES = Object.freeze(['result', 'event', 'pong']);++/**+ * `subscribe_events` without an event type subscribes to EVERY event in the+ * house, which is a far larger read surface than the room graph needs (it would+ * carry, for example, every `call_service` another integration makes). Only the+ * one event the legacy state channel uses is permitted.+ */+export const ALLOWED_EVENT_TYPES = Object.freeze(['state_changed']);++/**+ * Service domains that administer the Home Assistant install or execute+ * arbitrary code on the host, rather than controlling a device.+ *+ * The physical-action gate in `packages/home-bridge/src/safety.js` is about+ * doors, locks and alarms. This list is about the box itself: a relayed+ * `shell_command.*` is remote code execution on the user's server, and no+ * amount of user confirmation in a chat window makes that a smart-home feature.+ * Neither three.ws nor the relay has any reason to reach these, so the protocol+ * refuses them outright and the refusal is not overridable by a confirmation.+ */+export const DENIED_SERVICE_DOMAINS = Object.freeze([+ 'shell_command',+ 'python_script',+ 'hassio',+ 'supervisor',+ 'backup',+ 'update',+ 'cloud',+ 'config',+ 'auth',+ 'command_line',+]);++/**+ * Individual services on otherwise legitimate domains that restart, stop or+ * reconfigure the instance. `homeassistant.turn_on` is a normal device call;+ * `homeassistant.restart` is not.+ */+export const DENIED_SERVICES = Object.freeze([+ 'homeassistant.restart',+ 'homeassistant.stop',+ 'homeassistant.check_config',+ 'homeassistant.reload_all',+ 'homeassistant.reload_core_config',+ 'persistent_notification.create',+]);++const OUTBOUND_SET = new Set(OUTBOUND_TYPES);+const INBOUND_SET = new Set(INBOUND_TYPES);+const EVENT_SET = new Set(ALLOWED_EVENT_TYPES);+const DENIED_DOMAIN_SET = new Set(DENIED_SERVICE_DOMAINS);+const DENIED_SERVICE_SET = new Set(DENIED_SERVICES);++/** Hard ceilings, so a bug on either side cannot exhaust the other's memory. */+export const LIMITS = Object.freeze({+ /** One frame. A large house's `get_states` result is the biggest legitimate+ * payload and measures a few hundred kilobytes; 4 MB is generous headroom+ * without being an amplification target. */+ maxFrameBytes: 4 * 1024 * 1024,+ /** Concurrent Home Assistant sessions per install. One three.ws instance+ * holds one; the cap exists so a reconnect storm cannot open hundreds. */+ maxSessionsPerInstall: 8,+ /** Frames per second into one house, averaged over the window below. A+ * relayed house is a physical building: nothing legitimate needs more. */+ outboundFramesPerSecond: 40,+ /** Actuating calls per minute into one house. */+ serviceCallsPerMinute: 60,+ /** How long the relay waits for a pong before dropping a socket. */+ heartbeatMs: 25_000,+ heartbeatTimeoutMs: 60_000,+});++/**+ * Encode one frame. Always returns a string: the protocol is JSON text frames,+ * because every payload it carries is already JSON and a binary framing would+ * buy nothing but a second parser to get wrong.+ */+export function encodeFrame(frame) {+ return JSON.stringify(frame);+}++/**+ * Parse and structurally validate one inbound frame.+ *+ * @param {string|Buffer} raw+ * @returns {{ ok: true, frame: object } | { ok: false, code: string, message: string }}+ */+export function decodeFrame(raw) {+ const text = typeof raw === 'string' ? raw : String(raw);+ if (text.length > LIMITS.maxFrameBytes) {+ return refuse(CODE.MALFORMED, `Frame of ${text.length} bytes exceeds the ${LIMITS.maxFrameBytes} byte limit.`);+ }+ let frame;+ try {+ frame = JSON.parse(text);+ } catch {+ return refuse(CODE.MALFORMED, 'Frame was not valid JSON.');+ }+ if (!frame || typeof frame !== 'object' || Array.isArray(frame)) {+ return refuse(CODE.MALFORMED, 'Frame must be a JSON object.');+ }+ if (frame.v !== PROTOCOL_VERSION) {+ return refuse(CODE.MALFORMED, `Frame version ${JSON.stringify(frame.v)} is not ${PROTOCOL_VERSION}.`);+ }+ if (!FRAME_TYPES.has(frame.t)) {+ return refuse(CODE.MALFORMED, `Unknown frame type ${JSON.stringify(frame.t)}.`);+ }+ if (needsSid(frame.t) && !isSid(frame.sid)) {+ return refuse(CODE.MALFORMED, `Frame type ${frame.t} requires a session id.`);+ }+ if (frame.t === FRAME.HA && (!frame.msg || typeof frame.msg !== 'object' || Array.isArray(frame.msg))) {+ return refuse(CODE.MALFORMED, 'A ha frame must carry a msg object.');+ }+ return { ok: true, frame };+}++function needsSid(type) {+ return type === FRAME.SESSION_OPEN || type === FRAME.SESSION_READY || type === FRAME.SESSION_CLOSE || type === FRAME.HA;+}++function isSid(sid) {+ return typeof sid === 'string' && sid.length > 0 && sid.length <= 64 && /^[A-Za-z0-9_-]+$/.test(sid);+}++function refuse(code, message) {+ return { ok: false, code, message };+}++/**+ * The allowlist decision for one Home Assistant message travelling INTO a house.+ *+ * @param {object} msg a Home Assistant WebSocket message+ * @returns {{ allowed: true } | { allowed: false, code: string, reason: string }}+ */+export function checkOutbound(msg) {+ if (!msg || typeof msg !== 'object' || Array.isArray(msg)) {+ return deny(CODE.MALFORMED, 'A Home Assistant message must be an object.');+ }+ const type = msg.type;+ if (typeof type !== 'string' || !OUTBOUND_SET.has(type)) {+ return deny(CODE.NOT_ALLOWED, `"${describe(type)}" is not a message type this relay carries into a home.`);+ }+ if (type === 'subscribe_events') {+ const eventType = msg.event_type;+ if (typeof eventType !== 'string' || !EVENT_SET.has(eventType)) {+ return deny(+ CODE.NOT_ALLOWED,+ `subscribe_events is limited to ${ALLOWED_EVENT_TYPES.join(', ')}; "${describe(eventType)}" would subscribe to more of the house than the room graph needs.`,+ );+ }+ }+ if (type === 'call_service') {+ return checkServiceCall(msg);+ }+ return { allowed: true };+}++function checkServiceCall(msg) {+ const domain = typeof msg.domain === 'string' ? msg.domain : '';+ const service = typeof msg.service === 'string' ? msg.service : '';+ if (!domain || !service) {+ return deny(CODE.MALFORMED, 'call_service needs a domain and a service.');+ }+ if (DENIED_DOMAIN_SET.has(domain)) {+ return deny(+ CODE.NOT_ALLOWED,+ `The "${domain}" domain administers the Home Assistant install rather than a device, so the relay never carries it. Run it from Home Assistant itself.`,+ );+ }+ if (DENIED_SERVICE_SET.has(`${domain}.${service}`)) {+ return deny(+ CODE.NOT_ALLOWED,+ `"${domain}.${service}" changes the Home Assistant install itself, so the relay never carries it. Run it from Home Assistant itself.`,+ );+ }+ if (msg.return_response !== undefined && typeof msg.return_response !== 'boolean') {+ return deny(CODE.MALFORMED, 'call_service return_response must be a boolean when present.');+ }+ return { allowed: true };+}++/**+ * The allowlist decision for one Home Assistant message travelling OUT of a+ * house. Narrower than it looks: this is the direction that carries the user's+ * own data, so it is capped at the three reply shapes the client understands.+ */+export function checkInbound(msg) {+ if (!msg || typeof msg !== 'object' || Array.isArray(msg)) {+ return deny(CODE.MALFORMED, 'A Home Assistant message must be an object.');+ }+ if (typeof msg.type !== 'string' || !INBOUND_SET.has(msg.type)) {+ return deny(CODE.NOT_ALLOWED, `"${describe(msg.type)}" is not a message type this relay carries out of a home.`);+ }+ return { allowed: true };+}++function deny(code, reason) {+ return { allowed: false, code, reason };+}++/** Renders an arbitrary caller-supplied value for an error string, bounded. */+function describe(value) {+ if (typeof value !== 'string') return typeof value === 'undefined' ? 'undefined' : JSON.stringify(value);+ return value.length > 64 ? `${value.slice(0, 64)}...` : value;+}++/**+ * Version negotiation, run once per agent connection.+ *+ * @param {number} agentProtocol the version the integration claims+ */+export function negotiate(agentProtocol) {+ if (!Number.isInteger(agentProtocol)) {+ return { ok: false, code: CODE.MALFORMED, message: 'hello.protocol must be an integer.' };+ }+ if (agentProtocol < MIN_AGENT_PROTOCOL) {+ return {+ ok: false,+ code: CODE.PROTOCOL_TOO_OLD,+ message: `This three.ws integration speaks relay protocol ${agentProtocol}; the relay needs ${MIN_AGENT_PROTOCOL} or newer. Update the integration in HACS.`,+ };+ }+ if (agentProtocol > PROTOCOL_VERSION) {+ return {+ ok: false,+ code: CODE.PROTOCOL_TOO_NEW,+ message: `This three.ws integration speaks relay protocol ${agentProtocol}; this relay speaks ${PROTOCOL_VERSION}. The relay is being upgraded, so retrying shortly will succeed.`,+ };+ }+ return { ok: true, protocol: agentProtocol };+}++/** Frame builders, so no call site hand-writes a frame shape. */+export const frames = {+ hello: (relayId, agent) => ({ v: PROTOCOL_VERSION, t: FRAME.HELLO, relayId, protocol: PROTOCOL_VERSION, agent }),+ helloOk: (relayId, relay) => ({ v: PROTOCOL_VERSION, t: FRAME.HELLO_OK, relayId, relay, heartbeatMs: LIMITS.heartbeatMs }),+ helloErr: (code, message) => ({ v: PROTOCOL_VERSION, t: FRAME.HELLO_ERR, code, message }),+ ping: (ts) => ({ v: PROTOCOL_VERSION, t: FRAME.PING, ts }),+ pong: (ts) => ({ v: PROTOCOL_VERSION, t: FRAME.PONG, ts }),+ sessionOpen: (sid) => ({ v: PROTOCOL_VERSION, t: FRAME.SESSION_OPEN, sid }),+ sessionReady: (sid, haVersion) => ({ v: PROTOCOL_VERSION, t: FRAME.SESSION_READY, sid, haVersion }),+ sessionClose: (sid, code, reason) => ({ v: PROTOCOL_VERSION, t: FRAME.SESSION_CLOSE, sid, code, reason }),+ ha: (sid, msg) => ({ v: PROTOCOL_VERSION, t: FRAME.HA, sid, msg }),+};++/**+ * The machine-readable form of everything above, for the Python side and for+ * the threat-model doc. `tests/home-relay-protocol.test.js` asserts the+ * generated `allowlist.json` still matches this, so the two enforcement points+ * can never silently diverge.+ */+export function allowlistManifest() {+ return {+ protocolVersion: PROTOCOL_VERSION,+ minAgentProtocol: MIN_AGENT_PROTOCOL,+ frameTypes: Object.values(FRAME),+ outboundTypes: [...OUTBOUND_TYPES],+ inboundTypes: [...INBOUND_TYPES],+ allowedEventTypes: [...ALLOWED_EVENT_TYPES],+ deniedServiceDomains: [...DENIED_SERVICE_DOMAINS],+ deniedServices: [...DENIED_SERVICES],+ limits: { ...LIMITS },+ };+}diff --git a/services/home-relay/src/token.js b/services/home-relay/src/token.jsnew file mode 100644index 000000000..864eb3486--- /dev/null+++ b/services/home-relay/src/token.js@@ -0,0 +1,107 @@+/**+ * Install tokens: how the relay knows which house is dialling in, without+ * holding a database and without ever seeing a Home Assistant credential.+ *+ * three.ws mints one of these at pairing time and hands it to the integration+ * running inside the user's house. The integration stores it and presents it on+ * every dial-in. The relay verifies the HMAC with the shared signing key and+ * reads the relay id out of the payload, so the relay stays stateless about+ * ownership: it never queries a database on the connect path, and it cannot be+ * tricked into binding a socket to a relay id its holder was not granted.+ *+ * What this token is NOT: a Home Assistant credential. In relay mode three.ws+ * stores no Home Assistant token at all (`home_connections.access_token_enc` is+ * empty), because the integration authenticates to Home Assistant locally with+ * a refresh token it mints for itself and never sends off the machine. Stealing+ * an install token gets an attacker a socket to the relay, which the relay will+ * only ever join to the owning user's own sessions, and which the physical+ * action gate still sits above.+ *+ * Revocation is push based and immediate: three.ws calls the relay's admin+ * endpoint when a home is revoked, the relay drops the socket and denies the+ * relay id. The token itself is not the last line of defence, which is why it+ * does not carry an expiry the user would have to re-pair around: the platform+ * re-reads the connection row on every bridge connect, so a revoked home never+ * gets a session opened even if the relay were to forget the denial.+ */++import { createHmac, timingSafeEqual, randomBytes } from 'node:crypto';++const PREFIX = 'hr1';++/** URL-safe base64 without padding, so the token is copy-pasteable. */+function b64url(buf) {+ return Buffer.from(buf).toString('base64').replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');+}++function unb64url(text) {+ const padded = text.replace(/-/g, '+').replace(/_/g, '/');+ return Buffer.from(padded, 'base64');+}++function sign(payloadB64, key) {+ return b64url(createHmac('sha256', key).update(`${PREFIX}.${payloadB64}`).digest());+}++/**+ * A relay id: the public, non-secret handle for one paired house. Stored in+ * `home_connections.relay_id`, carried in the token, and used as the routing+ * key inside the relay. It is deliberately not a database primary key, so the+ * relay never learns anything about three.ws's own identifiers.+ */+export function newRelayId() {+ return `hr_${b64url(randomBytes(18))}`;+}++/**+ * @param {object} claims+ * @param {string} claims.relayId+ * @param {string} claims.userId the owning three.ws user+ * @param {string} claims.homeId the home_connections row+ * @param {string} key HOME_RELAY_SIGNING_KEY+ */+export function mintInstallToken({ relayId, userId, homeId }, key) {+ assertKey(key);+ if (!relayId || !userId || !homeId) throw new Error('mintInstallToken needs relayId, userId and homeId.');+ const payload = { rid: relayId, uid: userId, hid: homeId, iat: Math.floor(Date.now() / 1000) };+ const payloadB64 = b64url(JSON.stringify(payload));+ return `${PREFIX}.${payloadB64}.${sign(payloadB64, key)}`;+}++/**+ * @returns {{ ok: true, claims: { relayId: string, userId: string, homeId: string, issuedAt: number } }+ * | { ok: false, reason: string }}+ */+export function verifyInstallToken(token, key) {+ assertKey(key);+ if (typeof token !== 'string') return { ok: false, reason: 'No token presented.' };+ const parts = token.split('.');+ if (parts.length !== 3 || parts[0] !== PREFIX) return { ok: false, reason: 'Token is not a three.ws install token.' };+ const [, payloadB64, mac] = parts;+ const expected = sign(payloadB64, key);+ if (!constantTimeEquals(mac, expected)) return { ok: false, reason: 'Token signature did not verify.' };+ let payload;+ try {+ payload = JSON.parse(unb64url(payloadB64).toString('utf8'));+ } catch {+ return { ok: false, reason: 'Token payload was not readable.' };+ }+ if (!payload?.rid || !payload?.uid || !payload?.hid) return { ok: false, reason: 'Token payload was incomplete.' };+ return { ok: true, claims: { relayId: payload.rid, userId: payload.uid, homeId: payload.hid, issuedAt: payload.iat || 0 } };+}++/**+ * Compares two secrets without leaking their contents through timing. Length+ * differences are hashed away first so a mismatched length is not a fast path.+ */+export function constantTimeEquals(a, b) {+ const ha = createHmac('sha256', 'three.ws/home-relay/compare').update(String(a ?? '')).digest();+ const hb = createHmac('sha256', 'three.ws/home-relay/compare').update(String(b ?? '')).digest();+ return timingSafeEqual(ha, hb);+}++function assertKey(key) {+ if (typeof key !== 'string' || key.length < 32) {+ throw new Error('HOME_RELAY_SIGNING_KEY must be set to at least 32 characters.');+ }+}