Skip to content

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.

feat(home): harden the whole home path and let an owner withdraw a grant

nirholase6a32da61e4b
diff --git a/api/_lib/home-url-guard.js b/api/_lib/home-url-guard.js
index d0d8e2ffe..cfeaa8791 100644
--- a/api/_lib/home-url-guard.js
+++ b/api/_lib/home-url-guard.js
@@ -25,6 +25,8 @@
// the model fetcher use). This module is the home lane's spelling of them, so
// there is one function to call and no room to compose them wrongly.
+import { ERR_CANNOT_CONNECT, ERR_INVALID_AUTH } from 'home-assistant-js-websocket';
+
import { normalizeBaseUrl } from '../../packages/home-bridge/src/url.js';
import { isPrivateAddress, pinnedAgent, resolvePublicHost, SsrfError } from './ssrf.js';
@@ -241,3 +243,113 @@ function toHomeUrlError(err, hostname) {
}
return new HomeUrlError('bad_url', err.message);
}
+
+/**
+ * A `createSocket` for `home-assistant-js-websocket` whose socket is pinned to
+ * the validated addresses.
+ *
+ * The library's own createSocket is one line away from being usable here: it
+ * builds `new WebSocket(url)` against the global, with no way to pass undici a
+ * dispatcher, so the state channel (the connection that stays open for hours)
+ * would be the one dial in the lane that a rebinding host could still redirect.
+ * The auth handshake below therefore mirrors the library's, and only the socket
+ * construction differs. It is verified against a real Home Assistant rather than
+ * assumed: see tests/home-security.test.js.
+ *
+ * Upstream would rather have the option than our copy, and asking for it is the
+ * right end state; until it exists this is the pin.
+ *
+ * @param {{host: string, addresses: Array<{address: string, family: number}>}} pin
+ * @returns {(options: {auth: object, setupRetry?: number}) => Promise<WebSocket>}
+ */
+export function pinnedHomeSocketFactory(pin) {
+ return homeSocketFactory(pin.host, () => homeDispatcher(pin));
+}
+
+/**
+ * The Home Assistant auth handshake over a socket built by `dispatcherFor`.
+ *
+ * Split out from `pinnedHomeSocketFactory` for one reason: the address decision
+ * and the handshake are different jobs, and only the handshake can be verified
+ * against a Home Assistant running on a developer machine (a pin will never
+ * carry a loopback address, correctly). Production never calls this directly;
+ * everything that dials a user's house goes through `pinnedHomeSocketFactory`,
+ * so `homeDispatcher` is always the thing choosing the addresses.
+ *
+ * @param {string} expectedHost the only host this factory will open a socket to
+ * @param {() => import('undici').Agent} dispatcherFor
+ */
+export function homeSocketFactory(expectedHost, dispatcherFor) {
+ return function createHomeSocket(options) {
+ const auth = options?.auth;
+ if (!auth) throw new HomeUrlError('bad_url', 'A Home Assistant auth object is required.');
+ const url = auth.wsUrl;
+ if (new URL(url).hostname !== expectedHost) {
+ throw new HomeUrlError('host_pin_mismatch', 'Refusing to open a socket to a host we did not validate.');
+ }
+
+ const connect = (triesLeft, resolve, reject) => {
+ const socket = new WebSocket(url, { dispatcher: dispatcherFor() });
+ let invalidAuth = false;
+
+ const onClose = () => {
+ socket.removeEventListener('close', onClose);
+ if (invalidAuth) return reject(ERR_INVALID_AUTH);
+ if (triesLeft === 0) return reject(ERR_CANNOT_CONNECT);
+ const next = triesLeft === -1 ? -1 : triesLeft - 1;
+ setTimeout(() => connect(next, resolve, reject), 1_000);
+ };
+
+ const onOpen = () => {
+ socket.send(JSON.stringify({ type: 'auth', access_token: auth.accessToken }));
+ };
+
+ const onMessage = (event) => {
+ const message = JSON.parse(event.data);
+ if (message.type === 'auth_invalid') {
+ invalidAuth = true;
+ socket.close();
+ return;
+ }
+ if (message.type !== 'auth_ok') return;
+ socket.removeEventListener('open', onOpen);
+ socket.removeEventListener('message', onMessage);
+ socket.removeEventListener('close', onClose);
+ socket.removeEventListener('error', onClose);
+ socket.haVersion = message.ha_version;
+ // 2022.9 and newer negotiate compressed state subscriptions; the
+ // library sends this immediately after auth and the graph builder
+ // depends on the reply shape it selects.
+ if (atLeastVersion(socket.haVersion, 2022, 9)) {
+ socket.send(JSON.stringify({ type: 'supported_features', id: 1, features: { coalesce_messages: 1 } }));
+ }
+ resolve(socket);
+ };
+
+ socket.addEventListener('open', onOpen);
+ socket.addEventListener('message', onMessage);
+ socket.addEventListener('close', onClose);
+ socket.addEventListener('error', onClose);
+ };
+
+ return new Promise((resolve, reject) => connect(options.setupRetry ?? 0, resolve, reject));
+ };
+}
+
+/** Home Assistant versions read "2024.6.1", sometimes with a suffix. */
+function atLeastVersion(version, major, minor) {
+ const parts = String(version || '').split('.');
+ const [gotMajor, gotMinor] = [Number(parts[0]), Number(parts[1])];
+ if (!Number.isFinite(gotMajor) || !Number.isFinite(gotMinor)) return false;
+ return gotMajor > major || (gotMajor === major && gotMinor >= minor);
+}
+
+/**
+ * A pinned `fetch` for anything that takes one: the MCP SDK's streamable HTTP
+ * transport, and any other client that dials the home over plain HTTP.
+ *
+ * @param {{host: string, addresses: Array<{address: string, family: number}>, secure?: boolean}} pin
+ */
+export function pinnedHomeFetch(pin) {
+ return (url, init = {}) => homeFetch(pin, typeof url === 'string' ? url : url.toString(), init);
+}
diff --git a/api/_lib/home/access.js b/api/_lib/home/access.js
index a97f7e7eb..73ea47b85 100644
--- a/api/_lib/home/access.js
+++ b/api/_lib/home/access.js
@@ -19,6 +19,7 @@
import { authenticateBearer, extractBearer, getSessionUser } from '../auth.js';
+import { can, filterGraphForScope, normalizeScope, outOfScopeEntities } from './members.js';
import { getConnection } from './store.js';
/**
@@ -41,24 +42,42 @@ export async function resolveCaller(req, res) {
}
/**
- * Authenticate, then resolve one home the caller is entitled to.
+ * Authenticate, then resolve one home this caller is entitled to, for a named
+ * capability.
+ *
+ * Two different refusals, and the difference is deliberate:
+ *
+ * 404 the caller is not in this household (or there is no such home, or it
+ * was disconnected). Indistinguishable on purpose: a 403 here would
+ * confirm the id is real and turn a list of uuids into an oracle for
+ * "is this a house".
+ * 403 the caller IS in the household and their role does not hold this
+ * capability. Naming the role is safe, and it is the only answer that
+ * lets a guest refused an unlock understand it is their role rather than
+ * a broken door.
+ *
+ * `capability` defaults to `read` because every route on this surface needs at
+ * least that, and a route that forgets to name one therefore fails closed at the
+ * weakest useful level rather than open.
*
* @param {import('node:http').IncomingMessage} req
* @param {import('node:http').ServerResponse} res
* @param {string} homeId from `req.query.id`
+ * @param {string} [capability] one of HOME_CAPABILITIES in ./members.js
* @returns {Promise<
- * | { ok: true, caller: { userId: string, via: string, scope: string|null }, home: object }
+ * | { ok: true, caller: object, home: object, role: string, scope: object, scoped: boolean }
* | { ok: false, status: 401, code: 'unauthorized', message: string }
* | { ok: false, status: 404, code: 'not_found', message: string }
+ * | { ok: false, status: 403, code: 'role_forbidden', message: string, role: string }
* >}
*/
-export async function resolveHomeAccess(req, res, homeId) {
+export async function resolveHomeAccess(req, res, homeId, capability = 'read') {
const caller = await resolveCaller(req, res);
if (!caller) {
return { ok: false, status: 401, code: 'unauthorized', message: 'Sign in to reach your home.' };
}
- // A malformed id is answered exactly like a real id that is not yours. A 400
+ // A malformed id is answered exactly like a real id you are not in. A 400
// here would tell an unauthenticated prober which of their guesses were even
// shaped like a home id.
const home = homeId ? await getConnection(homeId, caller.userId) : null;
@@ -66,9 +85,40 @@ export async function resolveHomeAccess(req, res, homeId) {
return { ok: false, status: 404, code: 'not_found', message: 'No such home.', caller };
}
- return { ok: true, caller, home };
+ const role = home.role;
+ const scope = normalizeScope(home.entity_scope, role);
+
+ if (capability && !can(role, capability)) {
+ return {
+ ok: false,
+ status: 403,
+ code: 'role_forbidden',
+ message: `${article(role)} cannot ${capability} in this home.`,
+ role,
+ capability,
+ caller,
+ home,
+ };
+ }
+
+ return { ok: true, caller, home, role, scope, scoped: scope.mode !== 'all' };
}
+/** "an admin" / "a member": role names reach users as copy, not as identifiers. */
+function article(role) {
+ return /^[aeiou]/i.test(String(role)) ? `an ${role}` : `a ${role}`;
+}
+
+/**
+ * The room graph as this member is allowed to see it.
+ *
+ * Re-exported from ./members.js through this module so every route reaches
+ * scope filtering from the same import it already uses for access, and a route
+ * that renders a graph without filtering it reads as an obvious omission rather
+ * than as one missing import among many.
+ */
+export { filterGraphForScope, outOfScopeEntities };
+
/**
* The credential-free projection every route returns for a home.
*
diff --git a/api/_lib/home/errors.js b/api/_lib/home/errors.js
index 4b4c33f30..cbe5b1945 100644
--- a/api/_lib/home/errors.js
+++ b/api/_lib/home/errors.js
@@ -43,6 +43,14 @@ export const HOME_ERR = Object.freeze({
NOT_FOUND: 'not_found',
/** No three.ws session and no valid bearer token. */
UNAUTHORIZED: 'unauthorized',
+ /**
+ * The caller IS in this household and their role does not hold the capability
+ * this route needs. Distinct from NOT_FOUND on purpose: 404 says nothing and
+ * is the answer across a tenancy boundary, while 403 is safe to say inside one
+ * and is the only answer that lets a guest refused an unlock understand it is
+ * their role rather than a broken door. See api/_lib/home/members.js.
+ */
+ FORBIDDEN: 'role_forbidden',
/** The request body or query is malformed. */
VALIDATION: 'validation_error',
});
@@ -56,6 +64,7 @@ const STATUS_BY_CODE = Object.freeze({
[HOME_ERR.AUTH]: 400,
[HOME_ERR.VALIDATION]: 400,
[HOME_ERR.UNAUTHORIZED]: 401,
+ [HOME_ERR.FORBIDDEN]: 403,
[HOME_ERR.NOT_FOUND]: 404,
[HOME_ERR.NEEDS_CONFIRMATION]: 409,
[HOME_ERR.UNREACHABLE]: 502,
diff --git a/api/_lib/home/log-safe.js b/api/_lib/home/log-safe.js
new file mode 100644
index 000000000..dab0900b4
--- /dev/null
+++ b/api/_lib/home/log-safe.js
@@ -0,0 +1,51 @@
+// The one way this lane turns an error into a log line.
+//
+// Application logs are a different system: a different retention window, a
+// different set of readers, and no connection to the account the data belongs
+// to. A home detail that reaches them has the longest tail of any leak here, and
+// the most common error in the whole lane is the one that names the house:
+// `toBridgeError` builds "Could not reach https://home.example.com. If it is
+// only on your home network..." for every unreachable instance. Passing
+// `err.message` through to a log therefore writes somebody's address into a log
+// sink every time their internet wobbles.
+//
+// A driver error is the same problem from the other direction: Postgres echoes
+// bound parameters into constraint-violation messages, and this lane binds a
+// home's status detail, which is itself often a bridge error message.
+//
+// So nothing in the lane logs a raw message. It logs this instead: the code an
+// operator can actually act on, plus a message with every URL removed and a
+// hard length cap. See docs/home-privacy.md.
+
+/** Any absolute URL, however it is embedded in a sentence. */
+const URL_RE = /\b[a-z][a-z0-9+.-]*:\/\/[^\s"'<>)\]]+/gi;
+/** A bare host:port, which is how a LAN instance is usually written. */
+const HOSTPORT_RE = /\b[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)+(:\d{2,5})?\b/gi;
+const MAX = 200;
+
+/**
+ * A log-safe description of an error.
+ *
+ * Returns `{ code, detail }`, never a raw message:
+ *
+ * * `code` is `err.code` where the error has one (the whole `ERR` vocabulary
+ * does), else `err.name`, else `'unknown'`. This is the field worth
+ * alerting on, and it says nothing about whose house it is.
+ * * `detail` is the message with every URL and bare hostname replaced by
+ * `[host]`, truncated. Present so a genuinely unexpected failure is still
+ * diagnosable; absent when there is nothing left after redaction.
+ *
+ * @param {unknown} err
+ * @returns {{ code: string, detail?: string }}
+ */
+export function safeError(err) {
+ const code = String(
+ (err && typeof err === 'object' && ('code' in err ? err.code : null)) ||
+ (err && typeof err === 'object' && 'name' in err ? err.name : null) ||
+ 'unknown',
+ ).slice(0, 64);
+
+ const raw = err && typeof err === 'object' && 'message' in err ? String(err.message ?? '') : String(err ?? '');
+ const detail = raw.replace(URL_RE, '[host]').replace(HOSTPORT_RE, '[host]').trim().slice(0, MAX);
+ return detail ? { code, detail } : { code };
+}
diff --git a/api/_lib/home/members.js b/api/_lib/home/members.js
index 654b4a4c8..8470a6613 100644
--- a/api/_lib/home/members.js
+++ b/api/_lib/home/members.js
@@ -44,9 +44,15 @@ export const HOME_ROLES = Object.freeze(['owner', 'admin', 'member', 'guest', 'v
* 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
+ * manage administer the CONNECTION: rename it, re-pair its relay, retry it
* disconnect revoke the connection and take the house off the platform
+ *
+ * `grant`, `invite` and `manage` are held by the same two roles today, and they
+ * are still three names. They are different powers over different things (a
+ * lock, the roster, the connection), and collapsing them would mean a future
+ * role could not hold one without the others.
*/
-export const HOME_CAPABILITIES = Object.freeze(['read', 'act', 'confirm', 'grant', 'layout', 'invite', 'disconnect']);
+export const HOME_CAPABILITIES = Object.freeze(['read', 'act', 'confirm', 'grant', 'layout', 'invite', 'manage', 'disconnect']);
/**
* The role matrix. `rank` orders the roles for roster administration; `scoped`
@@ -62,8 +68,8 @@ export const HOME_CAPABILITIES = Object.freeze(['read', 'act', 'confirm', 'grant
* 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'])) }),
+ owner: Object.freeze({ rank: 5, scoped: false, can: Object.freeze(new Set(['read', 'act', 'confirm', 'grant', 'layout', 'invite', 'manage', 'disconnect'])) }),
+ admin: Object.freeze({ rank: 4, scoped: false, can: Object.freeze(new Set(['read', 'act', 'confirm', 'grant', 'layout', 'invite', 'manage'])) }),
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'])) }),
@@ -188,7 +194,7 @@ export function filterGraphForScope(graph, scope) {
...room,
entities: kept,
lighting: summarizeLighting(kept),
- climate: summarizeClimate(kept),
+ climate: summarizeClimate(kept, graph.temperatureUnit || null),
secured: summarizeSecurity(kept),
},
);
diff --git a/api/_lib/home/privacy.js b/api/_lib/home/privacy.js
index 22a0e57c5..2b55ee3cb 100644
--- a/api/_lib/home/privacy.js
+++ b/api/_lib/home/privacy.js
@@ -32,6 +32,8 @@
import { sql } from '../db.js';
import { withDbRetry } from '../db-retry.js';
+import { resolveHomeEntitlementsForUser } from './entitlements.js';
+
/** The 90-day default, stated once so the doc, the UI and the DB agree. */
export const DEFAULT_ACTION_LOG_RETENTION_DAYS = 90;
/** The bounds the schema check constraint enforces. Mirrored, never guessed. */
@@ -128,6 +130,41 @@ export const INVENTORY = Object.freeze([
deletedBy: 'The daily retention sweep, deleting this home, or deleting your account.',
sensitive: true,
},
+ {
+ key: 'satellite',
+ data: 'A voice satellite you set up: what you called it, which room you said it is in, which agent appears on it, and the key that lets a browser in that room attach to it',
+ table: 'home_satellites',
+ why: 'So a speaker in a room can carry your agent, and so a screen on the same network can show it even when three.ws is unreachable.',
+ retention: 'Until you remove the satellite. The key is encrypted at rest with the same primitive as a home credential.',
+ deletedBy: 'Remove the satellite, or delete your account.',
+ sensitive: true,
+ },
+ {
+ key: 'satellite_pairing',
+ data: 'A short-lived setup code for a satellite, stored as a one-way digest',
+ table: 'home_satellite_codes',
+ why: 'To claim a satellite you are setting up, once.',
+ retention: 'Until it is claimed or expires; expired unclaimed codes are swept by the daily retention pass.',
+ deletedBy: 'Claiming it, the retention sweep, or deleting your account.',
+ sensitive: true,
+ },
+ {
+ key: 'plan_override',
+ data: 'A per-account limit an administrator agreed with you (how many homes, how many members, how long the log is kept), and the sentence explaining why',
+ table: 'home_plan_overrides',
+ why: 'So an operator whose numbers do not fit a published plan gets the numbers they were promised, on the record.',
+ retention: 'Until the override is removed or your account is deleted.',
+ deletedBy: 'Delete your account, or ask for the override to be removed.',
+ },
+ {
+ key: 'relay_pairing',
+ data: 'A short-lived pairing code, stored as a one-way digest, when you connect a home that only exists on your own network',
+ table: 'home_relay_pairings',
+ why: 'To introduce the add-on running inside your house to your account, once.',
+ retention: 'Ten minutes, and single use. It is a digest, never the code, so a database read cannot pair anything. The row is deleted with the home.',
+ deletedBy: 'Redeeming or expiring it, deleting this home, or deleting your account.',
+ sensitive: true,
+ },
{
key: 'confirmations',
data: 'A pending request to open something, and the sentence you were shown before you said yes: "Unlock the Front Door"',
@@ -212,6 +249,20 @@ export async function setActionLogRetention({ homeId, userId, days, reason = nul
}
const storedReason = n > DEFAULT_ACTION_LOG_RETENTION_DAYS ? trimmed.slice(0, 500) : null;
+ // The plan's ceiling on how LONG a log may be kept. Deliberately one-way: it
+ // can refuse a request to keep more, and it never shortens what is already
+ // kept. Retroactively truncating somebody's audit trail because their plan
+ // changed would destroy their evidence, and the log's integrity is not a paid
+ // feature on any tier. Shortening is always allowed and never checked, because
+ // keeping less of somebody's own data never needs a plan's permission.
+ if (n > DEFAULT_ACTION_LOG_RETENTION_DAYS) {
+ const entitlements = await resolveHomeEntitlementsForUser(userId);
+ const ceiling = entitlements.limits.logRetentionDays;
+ if (Number.isFinite(ceiling) && n > ceiling) {
+ return { ok: false, code: 'retention_over_plan', limit: ceiling, requested: n };
+ }
+ }
+
const rows = await sql`
update home_connections
set action_log_retention_days = ${n},
@@ -301,6 +352,17 @@ export async function purgeExpiredActionLog({ batch = 5000, maxRows = 100_000 }
for (const row of del) homes.add(row.home_id);
if (del.length < batch) break;
}
+ // The satellite pairing codes are the one thing here with no per-home window,
+ // because they hang off an account rather than a house and they are dead in
+ // minutes by design. Their creating migration states they are swept by this
+ // pass, so this is where that promise is kept: an expired, unclaimed code has
+ // no purpose and is a digest of a secret somebody typed into a terminal.
+ const satelliteCodes = await sql`
+ delete from home_satellite_codes
+ where claimed_at is null and expires_at < now()
+ returning id
+ `;
+
// Retired confirmations ride the same window. They are the other half of the
// same audit trail (the action log says a door was opened; the confirmation
// says who was shown what before it was), and the summary sentence frozen on
@@ -320,7 +382,13 @@ export async function purgeExpiredActionLog({ batch = 5000, maxRows = 100_000 }
returning id
`;
- return { deleted, batches, homes: homes.size, confirmations: confirmations.length };
+ return {
+ deleted,
+ batches,
+ homes: homes.size,
+ confirmations: confirmations.length,
+ satelliteCodes: satelliteCodes.length,
+ };
}
// ── Export ───────────────────────────────────────────────────────────────────
@@ -351,7 +419,10 @@ export async function exportHomeData(userId) {
`;
const homeIds = homes.map((h) => h.id);
- const [members, invites, grants, actions, confirmations, invitesToMe] = await Promise.all([
+ const [
+ members, invites, grants, actions, confirmations, pairings, invitesToMe,
+ satellites, satelliteCodes, planOverrides,
+ ] = await Promise.all([
homeIds.length
? sql`select home_id, user_id, role, entity_scope, invited_by, created_at, updated_at
from home_members where home_id = any(${homeIds}) order by home_id, created_at`
@@ -376,11 +447,25 @@ export async function exportHomeData(userId) {
outcome, created_at
from home_confirmations where home_id = any(${homeIds}) order by home_id, created_at`
: [],
+ homeIds.length
+ ? sql`select id, home_id, user_id, relay_id, expires_at, redeemed_at, redeemed_by,
+ attempts, created_at
+ from home_relay_pairings where home_id = any(${homeIds}) order by home_id, created_at`
+ : [],
// Homes somebody else owns that you are a member of, and invitations
// addressed to you: both are data about you that a query scoped to homes
// you own would miss entirely.
sql`select m.home_id, m.role, m.entity_scope, m.created_at
from home_members m where m.user_id = ${userId} order by m.created_at`,
+ // Account-scoped, not home-scoped: a satellite belongs to a person and an
+ // agent, not to one house, so a query over homes you own would miss it.
+ // The viewer secret is excluded for the same reason the home credential is.
+ sql`select id, agent_id, name, area, version, wyoming_version, created_at, last_seen_at
+ from home_satellites where user_id = ${userId} order by created_at`,
+ sql`select id, agent_id, name, created_at, expires_at, claimed_at, satellite_id
+ from home_satellite_codes where user_id = ${userId} order by created_at`,
+ sql`select limits, note, created_at, updated_at
+ from home_plan_overrides where user_id = ${userId}`,
]);
return {
@@ -395,6 +480,14 @@ export async function exportHomeData(userId) {
grants,
action_log: actions,
confirmations,
+ // The pairing digest itself is deliberately absent: it is a one-way hash of
+ // a code that is dead in ten minutes, and exporting it tells the reader
+ // nothing they can use. What a person needs to know is that a pairing
+ // happened and when.
+ relay_pairings: pairings,
+ satellites,
+ satellite_codes: satelliteCodes,
+ plan_override: planOverrides[0] ?? null,
};
}
@@ -469,6 +562,10 @@ export async function deleteAllHomeDataForUser(userId, { email = null } = {}) {
await sql`delete from home_members where user_id = ${userId}`;
await sql`delete from home_entity_grants where granted_by = ${userId}`;
await sql`delete from home_invites where invited_by = ${userId}`;
+ await sql`delete from home_relay_pairings where user_id = ${userId}`;
+ await sql`delete from home_satellite_codes where user_id = ${userId}`;
+ await sql`delete from home_satellites where user_id = ${userId}`;
+ await sql`delete from home_plan_overrides where user_id = ${userId}`;
if (email) {
await sql`delete from home_invites where lower(email) = lower(${email})`;
}
@@ -504,13 +601,14 @@ export async function deleteAllHomeDataForUser(userId, { email = null } = {}) {
* @returns {Promise<Record<string, number>>}
*/
export async function countHomeRows(homeId) {
- const [conn, members, invites, grants, actions, confirmations, audit] = await Promise.all([
+ const [conn, members, invites, grants, actions, confirmations, pairings, audit] = await Promise.all([
sql`select count(*)::int as n from home_connections where id = ${homeId}`,
sql`select count(*)::int as n from home_members where home_id = ${homeId}`,
sql`select count(*)::int as n from home_invites where home_id = ${homeId}`,
sql`select count(*)::int as n from home_entity_grants where home_id = ${homeId}`,
sql`select count(*)::int as n from home_action_log where home_id = ${homeId}`,
sql`select count(*)::int as n from home_confirmations where home_id = ${homeId}`,
+ sql`select count(*)::int as n from home_relay_pairings where home_id = ${homeId}`,
sql`select count(*)::int as n from audit_log where resource_id = ${homeId} and action like '%home%'`,
]);
return {
@@ -520,6 +618,7 @@ export async function countHomeRows(homeId) {
home_entity_grants: grants[0].n,
home_action_log: actions[0].n,
home_confirmations: confirmations[0].n,
+ home_relay_pairings: pairings[0].n,
audit_log: audit[0].n,
};
}
@@ -532,7 +631,10 @@ export async function countHomeRows(homeId) {
* @returns {Promise<Record<string, number>>}
*/
export async function countUserRows(userId, email = null) {
- const [conn, members, invites, invitesToEmail, grants, actorRows, confirmRows, confirmations, audit] =
+ const [
+ conn, members, invites, invitesToEmail, grants, actorRows, confirmRows,
+ confirmations, pairings, satellites, satelliteCodes, planOverride, audit,
+ ] =
await Promise.all([
sql`select count(*)::int as n from home_connections where user_id = ${userId}`,
sql`select count(*)::int as n from home_members where user_id = ${userId}`,
@@ -544,6 +646,10 @@ export async function countUserRows(userId, email = null) {
sql`select count(*)::int as n from home_action_log where user_id = ${userId}`,
sql`select count(*)::int as n from home_action_log where confirmed_by = ${userId}`,
sql`select count(*)::int as n from home_confirmations where user_id = ${userId} or redeemed_by = ${userId}`,
+ sql`select count(*)::int as n from home_relay_pairings where user_id = ${userId}`,
+ sql`select count(*)::int as n from home_satellites where user_id = ${userId}`,
+ sql`select count(*)::int as n from home_satellite_codes where user_id = ${userId}`,
+ sql`select count(*)::int as n from home_plan_overrides where user_id = ${userId}`,
sql`select count(*)::int as n from audit_log where action like '%home%' and user_id = ${userId}`,
]);
return {
@@ -555,6 +661,10 @@ export async function countUserRows(userId, email = null) {
home_action_log_actor: actorRows[0].n,
home_action_log_confirmed_by: confirmRows[0].n,
home_confirmations: confirmations[0].n,
+ home_relay_pairings: pairings[0].n,
+ home_satellites: satellites[0].n,
+ home_satellite_codes: satelliteCodes[0].n,
+ home_plan_overrides: planOverride[0].n,
audit_log: audit[0].n,
};
}
diff --git a/api/_lib/home/runtime.js b/api/_lib/home/runtime.js
index 09f7d56ba..d02143259 100644
--- a/api/_lib/home/runtime.js
+++ b/api/_lib/home/runtime.js
@@ -25,6 +25,8 @@
import { ERR, HomeBridge, HomeBridgeError } from '@three-ws/home-bridge';
+import { assertDialableHomeUrl, HomeUrlError, pinnedHomeSocketFactory } from '../home-url-guard.js';
+
import { createAdmissionController } from './admission.js';
import {
getConnection,
@@ -33,6 +35,8 @@ import {
listAllowedEntities,
recordHandshake,
} from './store.js';
+import { relayTransportFor } from './relay.js';
+import { safeError } from './log-safe.js';
/**
* Codes `acquire` adds to the bridge package's `ERR` vocabulary, so the route
@@ -92,6 +96,12 @@ export function createHomeRuntime(deps = {}) {
const maxConnections = deps.maxConnections ?? readMaxConnections();
const idleMs = deps.idleMs ?? IDLE_MS;
const connectTimeoutMs = deps.connectTimeoutMs ?? CONNECT_TIMEOUT_MS;
+ /**
+ * How a relayed home is reached, injectable so a test can drive the relay
+ * path without a relay. Most houses only exist on a LAN, so this is not the
+ * exotic case: it is the one the majority of installs will take.
+ */
+ const buildRelayTransport = deps.relayTransportFor || relayTransportFor;
/**
* The backpressure ladder (api/_lib/home/admission.js). The pool decides which
@@ -274,7 +284,7 @@ export function createHomeRuntime(deps = {}) {
try {
onGraph(eventFor(entry, bridge));
} catch (err) {
- console.warn('[home-runtime] a subscriber threw on its first event', { homeId, error: err?.message });
+ console.warn('[home-runtime] a subscriber threw on its first event', { homeId, ...safeError(err) });
}
return () => {
@@ -323,6 +333,24 @@ export function createHomeRuntime(deps = {}) {
return { open: entries.size, subscribers, pooledCap: maxConnections, breakersOpen, byStatus, admission: admission.snapshot() };
}
+ /**
+ * How many live stream subscribers this instance is holding for one home.
+ *
+ * Per-instance, and deliberately not reconciled across the fleet. A
+ * cross-instance stream tally would need a shared counter with a lease, and a
+ * process that dies holding sockets leaks that counter until it expires,
+ * which shows up as a user being refused a dashboard they are not watching.
+ * Counting locally under-states a fleet-wide total, so the per-home stream
+ * limit built on it errs toward serving the user, which is the only direction
+ * a quota is allowed to err.
+ *
+ * @param {string} homeId
+ * @returns {number}
+ */
+ function streamCount(homeId) {
+ return entries.get(homeId)?.subscribers.size ?? 0;
+ }
+
/**
* Rung 4 and rung 5, for the action path.
*
@@ -437,6 +465,15 @@ export function createHomeRuntime(deps = {}) {
);
}
+ // A relayed home has no credential to load, and that absence is the design
+ // rather than a gap: the three.ws integration inside the house
+ // authenticates to Home Assistant locally, so there has never been a token
+ // here for us to decrypt. Everything downstream treats the transport it
+ // gets back exactly like a base URL and a token.
+ if (row.transport === 'relay') {
+ return { transport: 'relay', relayId: row.relay_id, baseUrl: row.base_url, transportFactory: buildRelayTransport(row) };
+ }
+
let credential;
try {
credential = await readCredential(homeId, userId);
@@ -460,6 +497,24 @@ export function createHomeRuntime(deps = {}) {
return credential;
}
+ /**
+ * The addresses this home is allowed to be dialled at, resolved fresh.
+ *
+ * A refusal is reported as UNREACHABLE rather than as a fault: from the
+ * owner's side, a house that has moved onto a LAN-only name looks exactly
+ * like a house that is offline, and the connect screen already knows how to
+ * explain that one.
+ */
+ async function resolveDialPin(baseUrl) {
+ try {
+ const dial = await assertDialableHomeUrl(baseUrl);
+ return { host: dial.host, addresses: dial.addresses, secure: dial.secure };
+ } catch (cause) {
+ if (!(cause instanceof HomeUrlError)) throw cause;
+ throw new HomeBridgeError(ERR.UNREACHABLE, cause.message, cause);
+ }
+ }
+
function openEntry({ homeId, userId, pooled }) {
const entry = {
homeId,
@@ -484,7 +539,23 @@ export function createHomeRuntime(deps = {}) {
// three.ws retrying a house that is merely offline.
const credential = await loadCredential(homeId, userId);
const allowedEntities = await readAllowed(homeId).catch(() => []);
- const bridge = createBridge({ baseUrl: credential.baseUrl, token: credential.token, allowedEntities });
+ // A direct home is re-resolved on EVERY dial, not trusted from the
+ // connect that stored it. That is the whole answer to DNS rebinding on
+ // a long-lived connection: a name that was public when the user added
+ // their house and points into our network today is refused here, and
+ // the socket that does open is pinned to what this resolved. A relayed
+ // home has no URL of ours to dial, so there is nothing to pin.
+ const dial = credential.transportFactory ? null : await resolveDialPin(credential.baseUrl);
+ const bridge = createBridge(
+ credential.transportFactory
+ ? { transport: credential.transportFactory, allowedEntities }
+ : {
+ baseUrl: credential.baseUrl,
+ token: credential.token,
+ allowedEntities,
+ createSocket: pinnedHomeSocketFactory(dial),
+ },
+ );
entry.bridge = bridge;
wireEvents(entry, bridge);
@@ -494,7 +565,9 @@ export function createHomeRuntime(deps = {}) {
connectTimeoutMs,
() => new HomeBridgeError(
ERR.UNREACHABLE,
- `${credential.baseUrl} did not answer within ${Math.round(connectTimeoutMs / 1000)} seconds. If it is only on your home network, three.ws cannot route to it: use your remote https URL, or connect the three.ws add-on.`,
+ credential.transport === 'relay'
+ ? `This home did not answer through the three.ws relay within ${Math.round(connectTimeoutMs / 1000)} seconds. Its three.ws integration is offline, which usually means Home Assistant is restarting. It reconnects on its own.`
+ : `${credential.baseUrl} did not answer within ${Math.round(connectTimeoutMs / 1000)} seconds. If it is only on your home network, three.ws cannot route to it: use your remote https URL, or connect the three.ws integration.`,
),
);
entry.lastGraph = graph || entry.lastGraph;
@@ -541,7 +614,12 @@ export function createHomeRuntime(deps = {}) {
// able to fill the log.
if (entry.loggedError) return;
entry.loggedError = true;
- console.warn('[home-runtime] bridge reported an error', { homeId: entry.homeId, error: err?.message || String(err) });
+ // A bridge error message names the house: toBridgeError builds
+ // "Could not reach https://home.example.com...", which is the most
+ // common error there is. The code is what an operator can act on; the
+ // URL is somebody's address in a log with its own retention. Fall back
+ // to the error's name, never its message.
+ console.warn('[home-runtime] bridge reported an error', { homeId: entry.homeId, ...safeError(err) });
});
}
@@ -552,7 +630,7 @@ export function createHomeRuntime(deps = {}) {
try {
listener(event);
} catch (err) {
- console.warn('[home-runtime] a subscriber threw', { homeId: entry.homeId, error: err?.message });
+ console.warn('[home-runtime] a subscriber threw', { homeId: entry.homeId, ...safeError(err) });
}
}
}
@@ -584,7 +662,7 @@ export function createHomeRuntime(deps = {}) {
measuredAt: new Date().toISOString(),
},
}).catch((err) => {
- console.warn('[home-runtime] handshake record dropped', { homeId, error: err?.message });
+ console.warn('[home-runtime] handshake record dropped', { homeId, ...safeError(err) });
});
}
@@ -635,7 +713,7 @@ export function createHomeRuntime(deps = {}) {
try {
entry.bridge?.close();
} catch (err) {
- console.warn('[home-runtime] close threw on an already dead socket', { homeId: entry.homeId, error: err?.message });
+ console.warn('[home-runtime] close threw on an already dead socket', { homeId: entry.homeId, ...safeError(err) });
}
}
@@ -652,7 +730,7 @@ export function createHomeRuntime(deps = {}) {
sweepTimer = null;
}
- return { acquire, withHome, snapshot, subscribe, evictIdle, stats, closeHome, closeAll, admitAction, withAction, readPlan, admission };
+ return { acquire, withHome, snapshot, subscribe, streamCount, evictIdle, stats, closeHome, closeAll, admitAction, withAction, readPlan, admission };
}
function readMaxConnections() {
@@ -675,6 +753,7 @@ export const acquire = runtime.acquire;
export const withHome = runtime.withHome;
export const snapshot = runtime.snapshot;
export const subscribe = runtime.subscribe;
+export const streamCount = runtime.streamCount;
export const evictIdle = runtime.evictIdle;
export const stats = runtime.stats;
export const closeHome = runtime.closeHome;
diff --git a/api/_lib/home/store.js b/api/_lib/home/store.js
index 97b1b7b01..89ac1e4ef 100644
--- a/api/_lib/home/store.js
+++ b/api/_lib/home/store.js
@@ -27,7 +27,8 @@ import { logAudit } from '../audit.js';
import { sql } from '../db.js';
import { withDbRetry } from '../db-retry.js';
import { decryptSecret, encryptSecret } from '../secret-box.js';
-import { redactUrlSecrets, scrubSecrets } from '../scrub-secrets.js';
+import { scrubSecrets } from '../scrub-secrets.js';
+import { safeError } from './log-safe.js';
/** Statuses the schema's check constraint accepts. */
export const HOME_STATUS = Object.freeze({
@@ -51,6 +52,20 @@ const SAFE_COLUMNS = sql`
created_at, updated_at, revoked_at
`;
+// The same projection, qualified, for the reads that join home_members.
+//
+// Those reads answer "may this caller see this home" through membership rather
+// than through `user_id` equality, and a join makes the bare list ambiguous:
+// home_members carries a user_id of its own. `c.user_id` stays on the row and
+// keeps meaning what it always meant, the account that connected the house,
+// which is why order 12 could add membership beside this column instead of
+// rewriting it.
+const SAFE_COLUMNS_C = sql`
+ c.id, c.user_id, c.label, c.base_url, c.token_fingerprint, c.transport, c.relay_id,
+ c.capabilities, c.status, c.status_detail, c.last_ok_at, c.last_error_at,
+ c.created_at, c.updated_at, c.revoked_at
+`;
+
/** sha256 of the token, hex. Never reversible, only comparable. */
export function fingerprintToken(token) {
return createHash('sha256').update(String(token), 'utf8').digest('hex');
@@ -131,30 +146,54 @@ export async function createConnection({
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
+ select ${SAFE_COLUMNS_C}, m.role, m.entity_scope
+ from home_connections c
+ join home_members m on m.home_id = c.id and m.user_id = ${userId}
+ where c.revoked_at is null
+ order by c.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.
+ * Returns null both when the id does not exist and when the caller is not in
+ * its household, 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.
+ *
+ * Entitlement is MEMBERSHIP, not ownership: the join against home_members is
+ * what lets a partner, a house sitter or a colleague reach a home somebody else
+ * connected. There is deliberately no `or c.user_id = ${userId}` beside it. Such
+ * a branch would look like belt and braces and would in fact be the bypass, and
+ * it is unnecessary: the migration's trigger gives every connection an owner row
+ * the moment it is inserted, so the account that connected a house is always in
+ * its household.
+ *
+ * The returned row carries `role` and `entity_scope`, because every caller that
+ * needs the home also needs to know what this member may do with it, and a
+ * second round trip to find out is a second place to forget.
*
* @param {string} id
* @param {string} userId
* @param {{ includeRevoked?: boolean }} [options]
- * @returns {Promise<object|null>}
+ * @returns {Promise<object|null>} the credential-free row plus `role` and `entity_scope`
*/
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`;
+ ? await sql`
+ select ${SAFE_COLUMNS_C}, m.role, m.entity_scope
+ from home_connections c
+ join home_members m on m.home_id = c.id and m.user_id = ${userId}
+ where c.id = ${id}
+ `
+ : await sql`
+ select ${SAFE_COLUMNS_C}, m.role, m.entity_scope
+ from home_connections c
+ join home_members m on m.home_id = c.id and m.user_id = ${userId}
+ where c.id = ${id} and c.revoked_at is null
+ `;
return rows[0] || null;
}
@@ -175,9 +214,10 @@ export async function getConnection(id, userId, { includeRevoked = false } = {})
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
+ select c.access_token_enc, c.base_url, c.transport, c.relay_id, c.token_fingerprint
+ from home_connections c
+ join home_members m on m.home_id = c.id and m.user_id = ${userId}
+ where c.id = ${id} and c.revoked_at is null
`;
const row = rows[0];
if (!row || !row.access_token_enc) return null;
@@ -419,14 +459,10 @@ export async function logHomeActionNow({
// MCP tool name ('light.turn_on'), never a friendly name, and the entity
// ids are deliberately absent: correlating a dropped write needs the home
// and the verb, not the list of things in somebody's bedroom. A driver
- // error can echo a bound parameter, so the message is redacted and
- // truncated rather than passed through.
- console.warn('[home-store] action log insert dropped', {
- homeId,
- action,
- outcome,
- error: redactUrlSecrets(String(err?.message ?? '')).slice(0, 200),
- });
+ // error can echo a bound parameter, so it goes through safeError() like
+ // every other error in the lane: a code, and a message with every host
+ // stripped out of it.
+ console.warn('[home-store] action log insert dropped', { homeId, action, outcome, ...safeError(err) });
return false;
}
}
diff --git a/api/_lib/home/tools.js b/api/_lib/home/tools.js
index 1ed2f352b..5b85a56a7 100644
--- a/api/_lib/home/tools.js
+++ b/api/_lib/home/tools.js
@@ -428,7 +428,7 @@ async function homeActivate(args, run) {
}
return await performCall(
- { domain: match.kind, service: 'turn_on', data: { entity_id: match.entityId } },
+ { domain: match.kind, service: 'turn_on', data: { entity_id: match.entity_id } },
run,
{ toolName: 'home_activate', extra: { matched: true, match, phrase: safeText(phrase, 200) } },
);
@@ -437,7 +437,15 @@ async function homeActivate(args, run) {
async function homeCall(args, run) {
const domain = String(args.domain || '').trim().toLowerCase();
const service = String(args.service || '').trim().toLowerCase();
- const data = args.data && typeof args.data === 'object' && !Array.isArray(args.data) ? args.data : {};
+ const raw = args.data && typeof args.data === 'object' && !Array.isArray(args.data) ? args.data : {};
+
+ // `data` is free-form service data by necessity (brightness, temperature,
+ // colour), which is the one place a model could smuggle in a field named
+ // `confirmed`. It would authorise nothing, because the gate below never reads
+ // service data for its verdict, but it would send a confusing key to Home
+ // Assistant and it would make the invariant "no confirmed anywhere" untrue on
+ // inspection. Drop it, and say why here rather than in a commit message.
+ const data = Object.fromEntries(Object.entries(raw).filter(([key]) => key !== 'confirmed'));
if (!/^[a-z0-9_]+$/.test(domain) || !/^[a-z0-9_]+$/.test(service)) {
return err(
@@ -576,6 +584,11 @@ async function performCall({ domain, service, data }, run, { toolName, extra = {
try {
await withHome(run.homeId, run.ownerId, (bridge) => bridge.call(domain, service, data, { confirmed: false }));
} catch (error) {
+ // Logged and answered HERE rather than rethrown. A rethrow would reach
+ // `bridgeFailure` in the dispatcher, which logs a second row under the tool
+ // name, and one refused service call must not read as two events in a
+ // household's history.
+ const message = safeText(error?.message, 400) || 'The home did not answer.';
logHomeAction({
homeId: run.homeId,
userId: run.userId,
@@ -585,9 +598,13 @@ async function performCall({ domain, service, data }, run, { toolName, extra = {
entityIds: targetIds,
guarded: false,
outcome: 'failed',
- detail: { reason: safeText(error?.message, 200), code: error?.code || null, tool: toolName },
+ detail: { reason: message, code: error?.code || null, tool: toolName },
+ });
+ return err(error?.code || 'call_failed', 502, message, {
+ home: { id: run.homeId },
+ action: `${domain}.${service}`,
+ entity_ids: targetIds,
});
- throw error;
}
logHomeAction({
@@ -766,6 +783,11 @@ function scopedGraph(graph, scope) {
floors: graph.floors || [],
rooms,
unassigned: (graph.unassigned || []).filter((e) => entityInScope(scope, e)),
+ // Narrowing WHICH rooms a guest sees must not change WHAT the numbers in
+ // them mean. Rebuilding this object field by field silently dropped the
+ // house's temperature unit, so a scoped caller read bare degrees off a
+ // Fahrenheit house while the owner read the same rooms in F.
+ temperatureUnit: graph.temperatureUnit ?? null,
};
}
diff --git a/api/_lib/home/verify.js b/api/_lib/home/verify.js
index 6efac1f2e..f1d81c4ec 100644
--- a/api/_lib/home/verify.js
+++ b/api/_lib/home/verify.js
@@ -15,6 +15,14 @@
import { connectHomeMcp, ERR, HomeBridge, HomeBridgeError, normalizeBaseUrl } from '@three-ws/home-bridge';
+import {
+ assertDialableHomeUrl,
+ homeFetch,
+ HomeUrlError,
+ pinnedHomeFetch,
+ pinnedHomeSocketFactory,
+} from '../home-url-guard.js';
+
/** 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. */
@@ -33,12 +41,19 @@ const CONFIG_TIMEOUT_MS = 5_000;
* @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 }) {
+export async function verifyConnection({ baseUrl, token, timeoutMs = CONNECT_TIMEOUT_MS, pin = null }) {
// 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 });
+ // The SSRF guard, resolved HERE rather than trusted from the caller, so no
+ // route can dial a house by forgetting to pass one. The hostname check the
+ // connect route runs first is a courtesy to the user; this is the control.
+ // A caller that already resolved the same URL passes its pin through so the
+ // name is looked up once per connect rather than once per channel.
+ const dial = pin || (await resolveDialPin(http));
+
+ const bridge = new HomeBridge({ baseUrl: http, token, createSocket: pinnedHomeSocketFactory(dial) });
let graph;
try {
graph = await withTimeout(
@@ -54,7 +69,10 @@ export async function verifyConnection({ baseUrl, token, timeoutMs = CONNECT_TIM
try {
const states = bridge.states || {};
const entityCount = Object.keys(states).length;
- const [mcp, config] = await Promise.all([probeMcp({ baseUrl: http, token }), readConfig({ baseUrl: http, token })]);
+ const [mcp, config] = await Promise.all([
+ probeMcp({ baseUrl: http, token, pin: dial }),
+ readConfig({ baseUrl: http, token, pin: dial }),
+ ]);
return {
graph,
@@ -93,11 +111,11 @@ export async function verifyConnection({ baseUrl, token, timeoutMs = CONNECT_TIM
* confident, wrong number to the user. An unreadable version is null, never a
* guess, because the connect screen prints this verbatim.
*/
-async function readConfig({ baseUrl, token }) {
+async function readConfig({ baseUrl, token, pin }) {
try {
- const res = await fetch(`${baseUrl}/api/config`, {
+ const res = await homeFetch(pin, `${baseUrl}/api/config`, {
headers: { authorization: `Bearer ${token}` },
- signal: AbortSignal.timeout(CONFIG_TIMEOUT_MS),
+ timeoutMs: CONFIG_TIMEOUT_MS,
});
if (!res.ok) return { version: null, locationName: null };
const body = await res.json();
@@ -112,10 +130,10 @@ async function readConfig({ baseUrl, token }) {
}
}
-async function probeMcp({ baseUrl, token }) {
+async function probeMcp({ baseUrl, token, pin }) {
try {
const session = await withTimeout(
- connectHomeMcp({ baseUrl, token }),
+ connectHomeMcp({ baseUrl, token, fetchImpl: pinnedHomeFetch(pin) }),
MCP_TIMEOUT_MS,
() => new HomeBridgeError(ERR.NO_MCP, 'The MCP endpoint did not answer in time.'),
);
@@ -140,3 +158,25 @@ function withTimeout(promise, ms, makeError) {
});
return Promise.race([promise, timeout]).finally(() => clearTimeout(timer));
}
+
+/**
+ * Resolve a base URL to the addresses we are willing to dial, in this lane's
+ * error vocabulary.
+ *
+ * A refusal here is nearly always a person typing their LAN address, not an
+ * attack, so it comes back as UNREACHABLE with the sentence that tells them what
+ * to do instead. The security property is the same either way: the name is
+ * resolved on our side and the connection is pinned to what it resolved to, so a
+ * public hostname pointing into RFC1918 (or flipping there after the check) is
+ * refused rather than dialled from inside our network.
+ */
+async function resolveDialPin(http) {
+ try {
+ const dial = await assertDialableHomeUrl(http);
+ return { host: dial.host, addresses: dial.addresses, secure: dial.secure };
+ } catch (err) {
+ if (!(err instanceof HomeUrlError)) throw err;
+ const code = err.code === 'bad_url' ? ERR.BAD_URL : ERR.UNREACHABLE;
+ throw new HomeBridgeError(code, err.message, err);
+ }
+}
diff --git a/api/_lib/rate-limit.js b/api/_lib/rate-limit.js
index 48393d622..94951fc90 100644
--- a/api/_lib/rate-limit.js
+++ b/api/_lib/rate-limit.js
@@ -2043,6 +2043,31 @@ export const limits = {
// what stops an enumeration sweep from costing us a database round trip each.
homeInviteRedeem: (ip) =>
getLimiter('home:invite:redeem:ip', { limit: 30, window: '10 m' }).limit(ip),
+ // Redeeming a relay pairing code (api/home/pair/redeem.js). Unlike the invite
+ // token above, this secret is deliberately weak: 8 characters a person reads
+ // off one screen and types into another, so roughly 40 bits. The per-pairing
+ // attempt counter is what actually makes guessing hopeless (five wrong tries
+ // kills the code); this bounds a distributed sweep across every live pairing
+ // at once, which the per-pairing counter alone cannot see. Ten in ten minutes
+ // is far above what a person retyping a code they mistyped ever needs.
+ homePairRedeem: (ip) =>
+ getLimiter('home:pair:redeem:ip', { limit: 10, window: '10 m' }).limit(ip),
+ // Minting a voice-satellite pairing code (api/home/satellite.js). A code buys
+ // a microphone in a house an attachment to an agent, so the ceiling is the
+ // same shape as homeInvite: keyed on the account, low enough that a
+ // compromised session cannot mint a pile of them, high enough that somebody
+ // setting up four displays in one afternoon never notices it.
+ homeSatellitePair: (userId) =>
+ getLimiter('home:satellite:pair:user', { limit: 20, window: '1 h' }).limit(userId),
+ // Redeeming one (action 'claim') and refreshing a satellite's hub token
+ // (action 'session'). Both are called by a program with no session cookie, so
+ // the IP is the only key available. The code itself is 8 characters from a
+ // 31-character alphabet, roughly 40 bits, single use, and dead in 15 minutes;
+ // this is what makes a distributed sweep across every live code at once cost
+ // more than it can possibly return. A satellite refreshing its own token does
+ // so once a day, so 30 in ten minutes never binds on the honest path.
+ homeSatelliteClaimIp: (ip) =>
+ getLimiter('home:satellite:claim:ip', { limit: 30, window: '10 m' }).limit(ip),
// Redeeming a pending physical-action confirmation (api/home/[id]/confirm.js).
// Every redemption is a human pressing a button in front of a door, so the
// honest ceiling is "faster than a person could ever mean to": 30 in five
@@ -2092,6 +2117,17 @@ export const limits = {
// one cheap read.
homeStream: (userId) =>
getLimiter('home:stream', { limit: 60, window: '5 m', local: true }).limit(userId),
+ // The privacy surface (api/home/privacy.js): the full data export, the
+ // retention change, and the deletion. Its own bucket, and a tight one, for
+ // two different reasons that happen to want the same ceiling. The export
+ // assembles every home, every grant and the whole action log for an account
+ // in one response, so it is the most expensive read on the surface and an
+ // obvious amplification lever. The DELETE destroys data that cannot be
+ // regenerated, so a loop that hits it is not abuse we merely want to slow
+ // down. 20 an hour is far more than anyone exercising their own privacy
+ // rights will ever need. NOT local: this must hold across instances.
+ homePrivacy: (userId) =>
+ getLimiter('home:privacy', { limit: 20, window: '1 h' }).limit(userId),
};
// ── Fail-closed limiter call for privacy-boundary reads (H7) ─────────────────
diff --git a/api/chat.js b/api/chat.js
index 0601f6fec..0860957f1 100644
--- a/api/chat.js
+++ b/api/chat.js
@@ -1014,6 +1014,77 @@ export default wrap(async (req, res) => {
return;
}
+ // ── The home round ───────────────────────────────────────────────────────
+ //
+ // A viewer action is fire-and-forget: the model asks, the browser does it, and
+ // the conversation moves on. A home tool cannot work that way, because the
+ // model has to see what the house actually said before it can say anything
+ // true about it, and because a guarded action comes back as a pending
+ // confirmation that the model has to relay rather than retry.
+ //
+ // So home tools run HERE, on the server, through the same handler module the
+ // MCP surface uses, and their results go back to the model for one more pass.
+ // Exactly one round: enough to read the house and act on it, never a loop, and
+ // the second pass is offered no home tools at all.
+ //
+ // Nothing in this block can approve anything. `runHomeTool` returns a
+ // `pending_confirmation` for a guarded action and the browser renders it as a
+ // card; the approval happens at /api/home/:id/confirm, which this file never
+ // calls and no model can reach.
+ const homeCalls = (result.toolCalls || []).filter((c) => isHomeTool(c.name));
+ let homeResults = [];
+ /**
+ * The home this turn touched, stamped into the usage row below.
+ *
+ * This is what makes a home agent turn countable WITHOUT a second counter:
+ * the row the chat meter already writes (priced, with the real token counts)
+ * is the same row the Home lane's quota reads, distinguished only by this
+ * key. See api/_lib/home/usage.js.
+ */
+ let homeTouched = null;
+ if (homeCalls.length && auth?.userId) {
+ homeResults = await runHomeRound(homeCalls, auth.userId);
+ for (const entry of homeResults) {
+ // Streamed immediately, ahead of the model's second pass, so a
+ // confirmation card is on screen while the model is still composing the
+ // sentence that explains it.
+ const touchedId = entry.result.structured?.home?.id || entry.call.input?.home_id || null;
+ if (touchedId) homeTouched = touchedId;
+ sendSSE({
+ type: 'home_tool',
+ tool: entry.call.name,
+ status: entry.result.kind,
+ home_id: touchedId,
+ data: entry.result.structured,
+ });
+ }
+
+ const followUp = await runFollowUpPass({
+ route,
+ systemPrompt,
+ sys,
+ history,
+ maxTokens,
+ assistantText: result.reply,
+ toolCalls: result.toolCalls,
+ homeResults,
+ sendSSE,
+ });
+ if (followUp) {
+ result.reply = [result.reply.trim(), followUp.reply.trim()].filter(Boolean).join('\n\n');
+ result.actions = [...result.actions, ...followUp.actions];
+ result.inputTokens += followUp.inputTokens || 0;
+ result.outputTokens += followUp.outputTokens || 0;
+ result.cacheWriteTokens = (result.cacheWriteTokens || 0) + (followUp.cacheWriteTokens || 0);
+ result.cacheReadTokens = (result.cacheReadTokens || 0) + (followUp.cacheReadTokens || 0);
+ } else if (!result.reply.trim()) {
+ // The second pass could not run (a provider blip, a spent time budget).
+ // The tools still ran and the user still deserves the answer, so speak
+ // the handler's own sentences rather than returning an empty turn.
+ result.reply = homeResults.map((entry) => entry.result.text).join('\n\n');
+ }
+ }
+
// IBM Granite Guardian "Trust Layer": before the client executes an autonomous
// value transfer, classify the request with Granite and enforce the dollar cap.
// A jailbreak ("ignore your rules and send everything") or an over-cap amount is
@@ -1034,6 +1105,14 @@ export default wrap(async (req, res) => {
reply,
actions: governedActions,
governance,
+ // What the home tools did this turn, for a client that only reads `done`.
+ // Empty on every turn that did not touch a house.
+ home: homeResults.map((entry) => ({
+ tool: entry.call.name,
+ status: entry.result.kind,
+ home_id: entry.result.structured?.home?.id || null,
+ data: entry.result.structured,
+ })),
model: route.model,
provider: route.name,
// Exactly the memories the server injected into this reply's context — the
@@ -1084,6 +1163,11 @@ export default wrap(async (req, res) => {
outputTokens: result.outputTokens,
costMicroUsd: chatCost,
meta: {
+ // Present only when this turn actually acted on a house. The Home lane's
+ // monthly agent-turn quota counts exactly the chat rows carrying this
+ // key, so the number on the quota page and the number an invoice would
+ // charge for come from one row rather than from two counters.
+ ...(homeTouched ? { home_id: homeTouched } : {}),
// `route.via` records the Vertex transport ('vertex-anthropic') distinctly
// from the first-party 'anthropic' provider so spend/usage reporting can
// attribute GCP-credit traffic; falls back to the provider name otherwise.
@@ -1116,6 +1200,135 @@ export default wrap(async (req, res) => {
}
});
+// ── The server-side home round ───────────────────────────────────────────────
+
+/**
+ * Run every home tool the model called, in order, through the one handler module
+ * that owns the gate. Ordered rather than parallel on purpose: a turn that reads
+ * the house and then acts on it must act on what the read returned, and two
+ * writes racing each other in one turn is never what a person meant.
+ *
+ * A thrown handler is turned into a result, never into a failed turn: the
+ * conversation is the product and a house that did not answer is something the
+ * agent should be able to say out loud.
+ */
+async function runHomeRound(calls, userId) {
+ const out = [];
+ for (const call of calls.slice(0, 4)) {
+ let result;
+ try {
+ result = await runHomeTool(call.name, call.input || {}, { userId, source: 'chat' });
+ } catch (err) {
+ captureException(err, { route: 'chat', stage: 'home-tool', tool: call.name });
+ result = {
+ ok: false,
+ kind: 'error',
+ code: 'call_failed',
+ text: `The home did not answer: ${String(err?.message || err).slice(0, 200)}`,
+ structured: { error: 'call_failed' },
+ };
+ }
+ out.push({ call, result });
+ }
+ return out;
+}
+
+/**
+ * A second model pass carrying the tool results, so the agent can speak about
+ * what the house actually said.
+ *
+ * Two rules encoded here:
+ *
+ * 1. EVERY tool call in the assistant turn gets a result, viewer actions
+ * included. Both wire formats reject an assistant turn with an unanswered
+ * tool call, and the honest answer for a viewer action is "the browser is
+ * doing it", which is exactly what the model should believe.
+ * 2. The second pass is offered NO home tools. That is what makes this one
+ * round rather than a loop, and it is why a model that just received a
+ * pending confirmation cannot respond by asking to unlock the door again.
+ *
+ * Returns null on any failure. The caller falls back to the tool text, so a
+ * provider blip costs the turn its prose, never its truth.
+ */
+async function runFollowUpPass({ route, systemPrompt, sys, history, maxTokens, assistantText, toolCalls, homeResults, sendSSE }) {
+ if (route.style === 'orchestrate') return null;
+
+ const resultText = new Map(homeResults.map((entry) => [entry.call.id, entry.result]));
+ const answerFor = (call) => {
+ const result = resultText.get(call.id);
+ if (result) return { text: result.text, isError: result.kind === 'error' };
+ return { text: 'Queued in the viewer; it is running there now.', isError: false };
+ };
+
+ const anthropic = route.style === 'anthropic';
+ const nextHistory = anthropic
+ ? [
+ ...history,
+ {
+ role: 'assistant',
+ content: [
+ ...(assistantText.trim() ? [{ type: 'text', text: assistantText.trim() }] : []),
+ ...toolCalls.map((c) => ({ type: 'tool_use', id: c.id, name: c.name, input: c.input || {} })),
+ ],
+ },
+ {
+ role: 'user',
+ content: toolCalls.map((c) => {
+ const answer = answerFor(c);
+ return { type: 'tool_result', tool_use_id: c.id, content: answer.text, ...(answer.isError ? { is_error: true } : {}) };
+ }),
+ },
+ ]
+ : [
+ ...history,
+ {
+ role: 'assistant',
+ content: assistantText.trim() || null,
+ tool_calls: toolCalls.map((c) => ({
+ id: c.id,
+ type: 'function',
+ function: { name: c.name, arguments: JSON.stringify(c.input || {}) },
+ })),
+ },
+ ...toolCalls.map((c) => ({ role: 'tool', tool_call_id: c.id, content: answerFor(c).text })),
+ ];
+
+ try {
+ const headers = route.headers || (await route.resolveHeaders());
+ const ctrl = new AbortController();
+ const timer = setTimeout(() => ctrl.abort(), PER_CALL_TIMEOUT_MS);
+ let upstream;
+ try {
+ upstream = await fetch(route.url, {
+ method: 'POST',
+ headers,
+ body: JSON.stringify(
+ route.buildPayload({
+ systemPrompt,
+ systemParts: sys,
+ history: nextHistory,
+ maxTokens,
+ includeTools: true,
+ toolSet: DEFAULT_TOOL_SET,
+ }),
+ ),
+ signal: ctrl.signal,
+ });
+ } finally {
+ clearTimeout(timer);
+ }
+ if (!upstream.ok || !upstream.body) {
+ console.warn(`[chat:${route.name}] home follow-up pass returned ${upstream.status}`);
+ return null;
+ }
+ const followUp = anthropic ? await streamAnthropic(upstream, sendSSE) : await streamOpenAI(upstream, sendSSE);
+ return followUp.error ? null : followUp;
+ } catch (err) {
+ captureException(err, { route: 'chat', stage: 'home-follow-up', provider: route.name });
+ return null;
+ }
+}
+
// Govern autonomous value-transfer actions with IBM Granite Guardian before the
// client executes them. Only sendSol is gated — it moves real SOL from the
// avatar's own wallet, so a jailbreak or an over-cap amount must be caught before
@@ -1564,6 +1777,10 @@ async function streamAnthropic(upstream, sendSSE) {
let buf = '';
let reply = '';
const actions = [];
+ // Every tool call the model made, ids intact. `actions` is the subset the
+ // browser executes; the home tools in here run server-side and their results
+ // go back to the model, which is why the id has to survive the stream.
+ const toolCalls = [];
const blocks = {};
let inputTokens = 0;
let outputTokens = 0;
@@ -1597,7 +1814,7 @@ async function streamAnthropic(upstream, sendSSE) {
cacheReadTokens = evt.message?.usage?.cache_read_input_tokens ?? 0;
} else if (evt.type === 'content_block_start') {
const cb = evt.content_block;
- blocks[evt.index] = { type: cb.type, name: cb.name, partialJson: '' };
+ blocks[evt.index] = { type: cb.type, id: cb.id, name: cb.name, partialJson: '' };
} else if (evt.type === 'content_block_delta') {
const block = blocks[evt.index];
if (!block) continue;
@@ -1610,7 +1827,9 @@ async function streamAnthropic(upstream, sendSSE) {
} else if (evt.type === 'content_block_stop') {
const block = blocks[evt.index];
if (block?.type === 'tool_use') {
- const action = parseToolJson(block.name, block.partialJson);
+ const call = parseToolCall(block.id, block.name, block.partialJson);
+ if (call) toolCalls.push(call);
+ const action = toViewerAction(call);
if (action) actions.push(action);
}
} else if (evt.type === 'message_delta') {
@@ -1619,10 +1838,10 @@ async function streamAnthropic(upstream, sendSSE) {
}
}
} catch (err) {
- return { error: err, reply, actions, inputTokens, outputTokens, cacheWriteTokens, cacheReadTokens };
+ return { error: err, reply, actions, toolCalls, inputTokens, outputTokens, cacheWriteTokens, cacheReadTokens };
}
- return { reply, actions, inputTokens, outputTokens, cacheWriteTokens, cacheReadTokens };
+ return { reply, actions, toolCalls, inputTokens, outputTokens, cacheWriteTokens, cacheReadTokens };
}
async function streamOpenAI(upstream, sendSSE) {
@@ -1631,7 +1850,8 @@ async function streamOpenAI(upstream, sendSSE) {
let buf = '';
let reply = '';
const actions = [];
- // OpenAI streams tool calls as deltas keyed by index. Accumulate name + arguments per index.
+ const toolCalls = [];
+ // OpenAI streams tool calls as deltas keyed by index. Accumulate id + name + arguments per index.
const toolBuf = {};
let inputTokens = 0;
let outputTokens = 0;
@@ -1662,7 +1882,8 @@ async function streamOpenAI(upstream, sendSSE) {
if (Array.isArray(delta?.tool_calls)) {
for (const tc of delta.tool_calls) {
const idx = tc.index ?? 0;
- const slot = (toolBuf[idx] ||= { name: '', args: '' });
+ const slot = (toolBuf[idx] ||= { id: '', name: '', args: '' });
+ if (tc.id) slot.id = tc.id;
if (tc.function?.name) slot.name += tc.function.name;
if (tc.function?.arguments) slot.args += tc.function.arguments;
}
@@ -1674,28 +1895,40 @@ async function streamOpenAI(upstream, sendSSE) {
}
}
} catch (err) {
- return { error: err, reply, actions, inputTokens, outputTokens };
+ return { error: err, reply, actions, toolCalls, inputTokens, outputTokens };
}
for (const slot of Object.values(toolBuf)) {
- const action = parseToolJson(slot.name, slot.args);
+ const call = parseToolCall(slot.id, slot.name, slot.args);
+ if (call) toolCalls.push(call);
+ const action = toViewerAction(call);
if (action) actions.push(action);
}
- return { reply, actions, inputTokens, outputTokens };
+ return { reply, actions, toolCalls, inputTokens, outputTokens };
}
-function parseToolJson(name, jsonText) {
- if (!name || !ACTION_NAMES.has(name)) return null;
+/**
+ * One tool call off the wire, in a shape both providers share. Unknown names are
+ * dropped: a model that hallucinates a tool must not be able to put an arbitrary
+ * `type` on the action list the browser executes.
+ */
+function parseToolCall(id, name, jsonText) {
+ if (!name || (!ACTION_NAMES.has(name) && !isHomeTool(name))) return null;
const text = jsonText && jsonText.trim() ? jsonText : '{}';
try {
- const input = JSON.parse(text);
- return { type: name, ...input };
+ return { id: id || `call_${name}`, name, input: JSON.parse(text) };
} catch {
return null;
}
}
+/** The subset the BROWSER executes. Home tools run on the server and are absent here. */
+function toViewerAction(call) {
+ if (!call || !ACTION_NAMES.has(call.name)) return null;
+ return { type: call.name, ...call.input };
+}
+
// ── System prompt + auth + helpers ───────────────────────────────────────────
// Pull the memories that should ground THIS reply: the agent's always-in-context
diff --git a/api/home/[id].js b/api/home/[id].js
index dc8d657d0..29ec6a28e 100644
--- a/api/home/[id].js
+++ b/api/home/[id].js
@@ -16,7 +16,7 @@
// the first one broke something.
import { requireCsrf } from '../_lib/csrf.js';
-import { publicHome, resolveHomeAccess } from '../_lib/home/access.js';
+import { filterGraphForScope, publicHome, resolveHomeAccess } from '../_lib/home/access.js';
import { homeError, toHomeFailure } from '../_lib/home/errors.js';
import { revokeConnection } from '../_lib/home/store.js';
import { closeHome, snapshot } from '../_lib/home/runtime.js';
@@ -28,14 +28,16 @@ export default wrap(async (req, res) => {
if (!method(req, res, ['GET', 'DELETE'])) return;
const homeId = req.query?.id;
- const access = await resolveHomeAccess(req, res, homeId);
+ // GET is a read; DELETE takes the house off the platform, which is the one
+ // thing an admin may not do.
+ const access = await resolveHomeAccess(req, res, homeId, req.method === 'DELETE' ? 'disconnect' : 'read');
if (!access.ok) return error(res, access.status, access.code, access.message);
if (req.method === 'GET') return handleRead(req, res, access);
return handleRevoke(req, res, access);
});
-async function handleRead(req, res, { caller, home }) {
+async function handleRead(req, res, { caller, home, scope }) {
const rl = await limits.homeRead(caller.userId);
if (!rl.success) return rateLimited(res, rl, 'too many home reads, slow down');
@@ -53,7 +55,13 @@ async function handleRead(req, res, { caller, home }) {
return json(res, 200, {
home: publicHome(home),
- graph: live?.graph ?? null,
+ role: home.role,
+ // Filtered before serialization, never in the client. A guest given the
+ // kitchen receives a house with one room in it; the rooms they were not
+ // given do not reach the wire at all, names included, because a room whose
+ // name arrived in a browser has been disclosed no matter what the browser
+ // then chooses to draw.
+ graph: live?.graph ? filterGraphForScope(live.graph, scope) : null,
connected: live?.connected ?? false,
stale: live?.stale ?? true,
live_status: live?.status ?? home.status,
diff --git a/api/home/[id]/activate.js b/api/home/[id]/activate.js
index e8663bc93..a9ac43d85 100644
--- a/api/home/[id]/activate.js
+++ b/api/home/[id]/activate.js
@@ -19,6 +19,7 @@
import { requireCsrf } from '../../_lib/csrf.js';
import { resolveHomeAccess } from '../../_lib/home/access.js';
+import { can } from '../../_lib/home/members.js';
import { homeError, homeFailure, HOME_ERR, toHomeFailure } from '../../_lib/home/errors.js';
import { acquire } from '../../_lib/home/runtime.js';
import { listAllowedEntities, logHomeAction } from '../../_lib/home/store.js';
@@ -32,7 +33,9 @@ export default wrap(async (req, res) => {
if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;
if (!method(req, res, ['POST'])) return;
- const access = await resolveHomeAccess(req, res, req.query?.id);
+ // Running a scene moves things in the world, so it needs `act`. A viewer is
+ // refused here; a guest is admitted and then held to their scope below.
+ const access = await resolveHomeAccess(req, res, req.query?.id, 'act');
if (!access.ok) return error(res, access.status, access.code, access.message);
const { caller, home } = access;
@@ -48,6 +51,23 @@ export default wrap(async (req, res) => {
// able to stand in for a person saying yes.
const confirmed = body.confirmed === true;
+ // The same role check call.js makes, for the same reason. A scene is a bundle
+ // of service calls the user assembled themselves, and "good night" in a house
+ // with a smart lock locks the door. Whether that bundle may be waved through a
+ // guarded step is a question about the person, not about the phrase.
+ if (confirmed && !can(access.role, 'confirm')) {
+ return error(res, 403, 'role_forbidden', `A ${access.role} cannot confirm a guarded action in this home.`);
+ }
+
+ // A scoped member gets scenes, not the house. A scene reaches whatever its
+ // author put in it, which for "good night" is usually every room, so running
+ // one from a role that was given the kitchen is not something to narrow down
+ // to the kitchen: it is something to refuse. Refusing is also the honest
+ // answer, because a half-run scene is worse than no scene.
+ if (access.scoped) {
+ return error(res, 403, 'out_of_scope', 'Scenes run across the whole house, so they are not available on a scoped role.');
+ }
+
// A dry run moves nothing, so it is metered as a read. Charging it to the act
// bucket would make the voice loop's read-back step compete with the actions
// it is reading back, and the honest ceiling for "resolve a phrase" is the
diff --git a/api/home/[id]/call.js b/api/home/[id]/call.js
index f99ce76a5..9ed679d9b 100644
--- a/api/home/[id]/call.js
+++ b/api/home/[id]/call.js
@@ -24,10 +24,12 @@
// refused unlock is the single most important row in that table: it is the
// evidence that the gate held.
-import { classifyCall } from '@three-ws/home-bridge';
+import { classifyCall, flattenEntities } from '@three-ws/home-bridge';
import { requireCsrf } from '../../_lib/csrf.js';
-import { resolveHomeAccess } from '../../_lib/home/access.js';
+import { outOfScopeEntities, resolveHomeAccess } from '../../_lib/home/access.js';
+import { can } from '../../_lib/home/members.js';
+import { assertHomeActionAllowed, HomePausedError } from '../../_lib/home/entitlements.js';
import { homeError, homeFailure, HOME_ERR, toHomeFailure } from '../../_lib/home/errors.js';
import { acquire } from '../../_lib/home/runtime.js';
import { listAllowedEntities, logHomeAction } from '../../_lib/home/store.js';
@@ -41,7 +43,10 @@ export default wrap(async (req, res) => {
if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;
if (!method(req, res, ['POST'])) return;
- const access = await resolveHomeAccess(req, res, req.query?.id);
+ // `act` admits the caller to the endpoint. Whether they may say yes to a
+ // GUARDED action is a second question, asked below, and the two are different
+ // on purpose: a guest may turn a light on and may never authorise an unlock.
+ const access = await resolveHomeAccess(req, res, req.query?.id, 'act');
if (!access.ok) return error(res, access.status, access.code, access.message);
const { caller, home } = access;
@@ -74,6 +79,54 @@ export default wrap(async (req, res) => {
const action = `${domain}.${service}`;
const targets = entityIdsOf(data);
+ // The role check on the confirmation, and the reason order 12 exists.
+ //
+ // `confirmed: true` is a human saying yes to something that opens a building.
+ // A guest is admitted to this endpoint because a house sitter should be able
+ // to turn the lights on, and a guest saying yes to an unlock is exactly what
+ // a house sitter must not be able to do. So the refusal happens HERE, before
+ // the socket is even acquired, and it is a refusal naming their role rather
+ // than a confirmation prompt they could answer: a role that cannot confirm
+ // must never be shown a door it could open.
+ if (confirmed && !can(access.role, 'confirm')) {
+ logHomeAction({
+ homeId: home.id, userId: caller.userId, actor: actorFor(caller), channel: 'websocket',
+ action, entityIds: targets, guarded: true, outcome: 'refused',
+ detail: { reason: 'role_forbidden', role: access.role },
+ });
+ return error(res, 403, 'role_forbidden', `A ${access.role} cannot confirm a guarded action in this home.`);
+ }
+
+ // The plan check, and the ONE line in this file that is about money.
+ //
+ // It sits here, before the socket is acquired, and it checks the safety
+ // exemption FIRST: locking a door, closing a garage or a valve and arming an
+ // alarm are never refused by a commercial limit, on any plan, in any state,
+ // including on a home this account's plan has paused. The classification
+ // needs only the domain and the service, so the exemption does not depend on
+ // the connection being healthy, which matters because the degraded states are
+ // exactly the ones where somebody needs to lock up.
+ //
+ // A refusal is logged like every other refusal. A home_action_log row that
+ // says "we would not do this because of a plan" is evidence the gate held for
+ // a different reason, and the owner is entitled to see it.
+ try {
+ assertHomeActionAllowed({ home, call: { domain, service } });
+ } catch (err) {
+ if (!(err instanceof HomePausedError)) throw err;
+ logHomeAction({
+ homeId: home.id, userId: caller.userId, actor: actorFor(caller), channel: 'websocket',
+ action, entityIds: targets, outcome: 'refused', detail: { reason: err.code },
+ });
+ return json(res, err.status, {
+ error: err.code,
+ error_description: err.message,
+ code: err.code,
+ message: err.message,
+ upgrade: err.upgradePath,
+ });
+ }
+
let checkout;
try {
checkout = await acquire(home.id, caller.userId);
@@ -96,6 +149,31 @@ export default wrap(async (req, res) => {
// the user took the key back.
await syncAllowList(bridge, home.id);
+ // Scope, enforced on the way out as well as on the way in.
+ //
+ // A scoped member's room graph is filtered before it reaches them, so they
+ // cannot SEE an out-of-scope entity. That is not a reason to skip checking
+ // what they ASK for: the filtered graph is what an honest client renders,
+ // and this endpoint takes an entity id straight from a request body. The
+ // area is resolved from the live graph rather than trusted from the body,
+ // because an area a caller names is an argument and an area an entity is
+ // actually in is a fact.
+ if (access.scoped) {
+ const areaOf = new Map(flattenEntities(bridge.graph).map((e) => [e.entityId, e.areaId]));
+ const refused = outOfScopeEntities(
+ access.scope,
+ targets.map((id) => ({ entityId: id, areaId: areaOf.get(id) ?? null })),
+ );
+ if (refused.length) {
+ logHomeAction({
+ homeId: home.id, userId: caller.userId, actor: actorFor(caller), channel: 'websocket',
+ action, entityIds: refused, outcome: 'refused',
+ detail: { reason: 'out_of_scope', role: access.role },
+ });
+ return error(res, 403, 'out_of_scope', 'That is not one of the things you were given access to in this home.');
+ }
+ }
+
// Classified for the LOG, not for the decision. The decision is made once,
// inside bridge.call, so there is exactly one gate and this cannot drift
// away from it.
diff --git a/api/home/[id]/grants.js b/api/home/[id]/grants.js
index 304158d12..b63d13e6a 100644
--- a/api/home/[id]/grants.js
+++ b/api/home/[id]/grants.js
@@ -1,154 +1,146 @@
-// /api/home/:id/grants: the standing allowances behind the physical-action gate.
+// /api/home/:id/grants: the standing allowances the physical-action gate honours.
//
-// GET what this home has pre-approved, expired rows already filtered out
-// POST grant one entity, optionally with an expiry
-// DELETE revoke one entity, addressed as ?entity_id= or in the body
+// GET what the agent may do in this house without asking again
+// POST grant one entity, optionally until a date
+// DELETE withdraw one (also reachable as DELETE .../grants/:entityId)
//
-// A grant is the one thing on this surface that makes the gate stop asking, so
-// it is deliberately narrow: one entity, one home, never a domain and never a
-// wildcard. Home Assistant's own intent__HassTurnOff is documented as performing
-// an UNLOCK on a lock, so "let the agent turn things off" would otherwise be a
-// sentence that opens a front door. Granting is per entity because the blast
-// radius of getting it wrong is a building.
+// Per entity, never per domain. A user who lets their agent open the office door
+// has not let it open the front door, and a `granted_domain` column is exactly
+// the shortcut that turns a convenience into a burglary tool. The store refuses a
+// domain-shaped id outright rather than trusting this route to check.
//
-// Every grant and every revoke lands in home_action_log. Changing what the agent
-// may do without asking is itself an action in the house, and an owner reading
-// that log has to be able to see the moment the rules changed, not just the
-// actions that followed.
+// A grant is a security decision, so it needs a session and a CSRF token even
+// though reads on this surface accept a bearer. An agent must be able to ACT with
+// a token; it must not be able to widen its own permissions with one.
+import { logAudit } from '../../_lib/audit.js';
import { requireCsrf } from '../../_lib/csrf.js';
-import { publicHome, resolveHomeAccess } from '../../_lib/home/access.js';
-import { HOME_ERR, homeError, homeFailure } from '../../_lib/home/errors.js';
+import { resolveHomeAccess } from '../../_lib/home/access.js';
+import { homeError, homeFailure, HOME_ERR } from '../../_lib/home/errors.js';
import { grantEntity, listGrants, logHomeAction, revokeGrant } from '../../_lib/home/store.js';
import { cors, error, json, method, rateLimited, readJson, wrap } from '../../_lib/http.js';
import { limits } from '../../_lib/rate-limit.js';
-/** `domain.object_id`, which is the only shape Home Assistant ever produces. */
-const ENTITY_ID = /^[a-z_][a-z0-9_]*\.[a-z0-9_]+$/;
-
-/**
- * A grant with no end is a legitimate choice ("my office door, always"), but an
- * unbounded one that was meant to be temporary is how a convenience becomes
- * permanent by accident. A year is the ceiling: long enough to mean "standing",
- * short enough that it is not forever.
- */
-const MAX_EXPIRY_MS = 365 * 24 * 60 * 60 * 1000;
+/** Home Assistant entity id: domain.object_id, both lower snake case. */
+const ENTITY_RE = /^[a-z_]+\.[a-z0-9_]+$/;
+/** A standing allowance on a lock should not outlive the reason for it. */
+const MAX_GRANT_MS = 365 * 24 * 60 * 60 * 1000;
+/** Distinguishes "you sent a bad date" from "you sent no date", which is legal. */
+const INVALID_EXPIRY = Symbol('invalid expiry');
export default wrap(async (req, res) => {
if (cors(req, res, { methods: 'GET,POST,DELETE,OPTIONS', credentials: true })) return;
if (!method(req, res, ['GET', 'POST', 'DELETE'])) return;
- const access = await resolveHomeAccess(req, res, req.query?.id);
+ // Reading the allowances is a read; creating or withdrawing one is a standing
+ // yes to opening something, which only the owner and an admin may leave behind.
+ const access = await resolveHomeAccess(req, res, req.query?.id, req.method === 'GET' ? 'read' : 'grant');
if (!access.ok) return error(res, access.status, access.code, access.message);
+ const { caller, home } = access;
- if (req.method === 'GET') return handleList(req, res, access);
- if (req.method === 'POST') return handleGrant(req, res, access);
- return handleRevoke(req, res, access);
-});
-
-async function handleList(req, res, { caller, home }) {
- const rl = await limits.homeRead(caller.userId);
- if (!rl.success) return rateLimited(res, rl, 'too many home reads, slow down');
-
- // listGrants filters expiry in SQL, so an expired allowance can never reach a
- // client (or the gate) because some caller forgot to compare a date.
- const grants = await listGrants(home.id);
- return json(res, 200, { home: publicHome(home), grants: grants.map(publicGrant) });
-}
+ if (req.method === 'GET') {
+ const rl = await limits.homeRead(caller.userId);
+ if (!rl.success) return rateLimited(res, rl, 'too many home reads, slow down');
+ return json(res, 200, { grants: (await listGrants(home.id)).map(shape) });
+ }
-async function handleGrant(req, res, { caller, home }) {
+ // Both writes change what the agent may do unattended, so both need a real
+ // person behind them.
if (!(await requireCsrf(req, res, caller.userId))) return;
-
const rl = await limits.homeAct(caller.userId);
- if (!rl.success) return rateLimited(res, rl, 'too many home actions, slow down');
+ if (!rl.success) return rateLimited(res, rl, 'too many permission changes, slow down');
+
+ if (req.method === 'POST') return handleGrant(req, res, caller, home);
+ return handleRevoke(req, res, caller, home, entityFromQuery(req));
+});
+async function handleGrant(req, res, caller, home) {
const body = await readJson(req, 4_000).catch(() => null);
const entityId = normalizeEntity(body?.entity_id ?? body?.entityId);
if (!entityId) {
- return homeError(res, homeFailure(HOME_ERR.VALIDATION, 'Send the entity_id to allow, for example "lock.office_door".'));
+ return homeError(res, homeFailure(HOME_ERR.VALIDATION, 'entity_id must be one Home Assistant entity, for example "lock.office_door". Grants are per entity, never per domain.'));
}
- let expiresAt = null;
- if (body?.expires_at ?? body?.expiresAt) {
- const parsed = Date.parse(body.expires_at ?? body.expiresAt);
- if (!Number.isFinite(parsed)) {
- return homeError(res, homeFailure(HOME_ERR.VALIDATION, 'expires_at must be an ISO 8601 timestamp.'));
- }
- if (parsed <= Date.now()) {
- return homeError(res, homeFailure(HOME_ERR.VALIDATION, 'expires_at is already in the past.'));
- }
- expiresAt = new Date(Math.min(parsed, Date.now() + MAX_EXPIRY_MS));
+ const expiresAt = readExpiry(body?.expires_at ?? body?.expiresAt);
+ if (expiresAt === INVALID_EXPIRY) {
+ return homeError(res, homeFailure(HOME_ERR.VALIDATION, 'expires_at must be a date in the future and no more than a year away.'));
}
const grant = await grantEntity({ homeId: home.id, entityId, grantedBy: caller.userId, expiresAt });
+ logAudit({ userId: caller.userId, action: 'grant_home_entity', resourceId: home.id, meta: { entity_id: entityId, expires_at: expiresAt }, req });
logHomeAction({
- homeId: home.id,
- userId: caller.userId,
- actor: 'user',
- channel: 'websocket',
- action: 'grant.allow',
- entityIds: [entityId],
- guarded: true,
- // The grant IS the human saying yes, so the person who made it is the
- // confirmer of every action it later waves through.
- confirmedBy: caller.userId,
- risk: null,
- outcome: 'ok',
- detail: { expires_at: expiresAt ? expiresAt.toISOString() : null },
+ homeId: home.id, userId: caller.userId, actor: 'user', channel: 'websocket',
+ action: 'grant.create', entityIds: [entityId], guarded: true, confirmedBy: caller.userId,
+ risk: null, outcome: 'ok', detail: { expires_at: expiresAt ? new Date(expiresAt).toISOString() : null },
});
- return json(res, 201, { grant: publicGrant(grant) });
+ return json(res, 201, { grant: shape(grant) });
}
-async function handleRevoke(req, res, { caller, home }) {
- if (!(await requireCsrf(req, res, caller.userId))) return;
-
- const rl = await limits.homeAct(caller.userId);
- if (!rl.success) return rateLimited(res, rl, 'too many home actions, slow down');
-
- // A DELETE carries its target in the path segment the route table captured,
- // in the query, or in a body, because all three are ordinary for a client and
- // refusing two of them is a papercut with no security value.
- const fromPath = req.query?.entity_id ?? req.query?.entityId;
- const body = fromPath ? null : await readJson(req, 2_000).catch(() => null);
- const entityId = normalizeEntity(fromPath ?? body?.entity_id ?? body?.entityId);
+async function handleRevoke(req, res, caller, home, fromPath) {
+ const body = fromPath ? null : await readJson(req, 4_000).catch(() => null);
+ const entityId = fromPath ?? normalizeEntity(body?.entity_id ?? body?.entityId);
if (!entityId) {
- return homeError(res, homeFailure(HOME_ERR.VALIDATION, 'Send the entity_id to revoke.'));
+ return homeError(res, homeFailure(HOME_ERR.VALIDATION, 'entity_id is required to withdraw a grant.'));
}
- const { revoked } = await revokeGrant({ homeId: home.id, entityId });
-
- // Idempotent: revoking an allowance that is already gone is a person clicking
- // twice, not an error. Both calls end with the agent unable to open it.
- logHomeAction({
- homeId: home.id,
- userId: caller.userId,
- actor: 'user',
- channel: 'websocket',
- action: 'grant.revoke',
- entityIds: [entityId],
- guarded: true,
- confirmedBy: caller.userId,
- risk: null,
- outcome: 'ok',
- detail: { was_present: revoked },
- });
+ const removed = await revokeGrant({ homeId: home.id, entityId });
+ if (removed) {
+ logAudit({ userId: caller.userId, action: 'revoke_home_entity_grant', resourceId: home.id, meta: { entity_id: entityId }, req });
+ logHomeAction({
+ homeId: home.id, userId: caller.userId, actor: 'user', channel: 'websocket',
+ action: 'grant.revoke', entityIds: [entityId], guarded: true, confirmedBy: caller.userId,
+ risk: null, outcome: 'ok', detail: null,
+ });
+ }
+ // Idempotent: withdrawing a grant that is already gone is the state the caller
+ // asked for, so it is a 200. `changed` is how a log tells the two apart.
+ return json(res, 200, { revoked: true, changed: removed, entity_id: entityId });
+}
- return json(res, 200, { revoked, entity_id: entityId });
+/**
+ * The entity id from `DELETE /api/home/:id/grants/:entityId`.
+ *
+ * Also accepted as `?entity_id=`, and that is not belt and braces: a Home
+ * Assistant object id may legitimately be `js` (a script named "js"), and
+ * `script.js` in a path segment is stripped to `script` by the same rule that
+ * lets `/api/foo.js` reach `api/foo.js`. The query form is the escape hatch for
+ * every id the path shape cannot carry.
+ */
+function entityFromQuery(req) {
+ const fromPath = normalizeEntity(req.query?.entityId);
+ if (fromPath) return fromPath;
+ const url = new URL(req.url, 'http://x');
+ return normalizeEntity(url.searchParams.get('entity_id'));
}
function normalizeEntity(value) {
- const id = String(value || '').trim().toLowerCase();
- return ENTITY_ID.test(id) ? id : '';
+ const id = String(value ?? '').trim().toLowerCase();
+ return ENTITY_RE.test(id) ? id : null;
+}
+
+/**
+ * @returns {string|null|symbol} an ISO date, null for "until withdrawn", or the
+ * INVALID_EXPIRY sentinel. A sentinel rather than a throw because the
+ * caller has to answer with a worded 400, and rather than null because null is
+ * already the legitimate "no expiry" answer.
+ */
+function readExpiry(value) {
+ if (value === null || value === undefined || value === '') return null;
+ const at = new Date(value);
+ if (Number.isNaN(at.getTime())) return INVALID_EXPIRY;
+ const ms = at.getTime() - Date.now();
+ if (ms <= 0 || ms > MAX_GRANT_MS) return INVALID_EXPIRY;
+ return at.toISOString();
}
-/** `granted_by` is a user id; it stays internal, and the UI shows the entity. */
-function publicGrant(row) {
- if (!row) return null;
+function shape(grant) {
return {
- entity_id: row.entity_id,
- expires_at: row.expires_at ?? null,
- created_at: row.created_at,
+ id: grant.id,
+ entity_id: grant.entity_id,
+ granted_by: grant.granted_by,
+ expires_at: grant.expires_at,
+ created_at: grant.created_at,
};
}
diff --git a/api/home/[id]/grants/[entityId].js b/api/home/[id]/grants/[entityId].js
new file mode 100644
index 000000000..0c86f38fc
--- /dev/null
+++ b/api/home/[id]/grants/[entityId].js
@@ -0,0 +1,9 @@
+// DELETE /api/home/:id/grants/:entityId: withdraw one standing allowance.
+//
+// The path form of the DELETE on ../grants.js, which is where the whole
+// implementation lives: one handler, two ways in, so a REST client that models
+// a grant as a resource and a form that posts an entity id cannot drift apart.
+// Withdrawal is the half of a permission system that has to be trivially
+// reachable, so it gets both spellings rather than the tidier one.
+
+export { default } from '../grants.js';
diff --git a/api/home/[id]/log.js b/api/home/[id]/log.js
index bd5a399c4..68688d708 100644
--- a/api/home/[id]/log.js
+++ b/api/home/[id]/log.js
@@ -1,16 +1,20 @@
-// /api/home/:id/log: what the platform actually did inside this house.
+// GET /api/home/:id/log: what the platform did inside this house.
//
-// This is the owner's record, not ours. It answers one question, "what did my
-// agent do in my house, and what did it refuse to do", and it is the only place
-// a refused unlock is visible. A refusal row matters more than a success row:
-// it is the evidence that the gate fired when something asked to open a door.
+// This is not the general audit_log. It is higher volume, it carries the
+// physical-action verdict, and an operator has to be able to answer "what did my
+// agent do in my house last Tuesday" without a join across a shared table.
//
-// Read-only, session or bearer, newest first, cursor-paginated on the timestamp
-// rather than an offset, because rows arrive while a person is reading and an
-// offset would silently skip one.
+// Newest first, keyset-paginated on `created_at` rather than an offset: an offset
+// page shifts under you when new rows land at the head, which for a log that is
+// actively being written is every page. `?before=` takes the `created_at` of the
+// last row you saw.
+//
+// Session only, no bearer. Reading the log is reading a record of when a person
+// was home and which doors opened when, which is the most privacy-sensitive data
+// this whole surface holds; an agent token that can act does not thereby get to
+// read the history of everything that ever acted.
-import { publicHome, resolveHomeAccess } from '../../_lib/home/access.js';
-import { HOME_ERR, homeError, homeFailure } from '../../_lib/home/errors.js';
+import { resolveHomeAccess } from '../../_lib/home/access.js';
import { listHomeActions } from '../../_lib/home/store.js';
import { cors, error, json, method, rateLimited, wrap } from '../../_lib/http.js';
import { limits } from '../../_lib/rate-limit.js';
@@ -22,61 +26,58 @@ export default wrap(async (req, res) => {
if (cors(req, res, { methods: 'GET,OPTIONS', credentials: true })) return;
if (!method(req, res, ['GET'])) return;
- const access = await resolveHomeAccess(req, res, req.query?.id);
+ const access = await resolveHomeAccess(req, res, req.query?.id, 'read');
if (!access.ok) return error(res, access.status, access.code, access.message);
+ const { caller, home } = access;
+
+ if (caller.via !== 'session') {
+ return error(res, 403, 'forbidden', 'The action log is readable from a signed-in session only.');
+ }
- const rl = await limits.homeRead(access.caller.userId);
+ const rl = await limits.homeRead(caller.userId);
if (!rl.success) return rateLimited(res, rl, 'too many home reads, slow down');
const url = new URL(req.url, 'http://x');
+ const limit = clamp(Number(url.searchParams.get('limit')) || DEFAULT_LIMIT, 1, MAX_LIMIT);
- const rawLimit = url.searchParams.get('limit');
- if (rawLimit != null && !/^\d{1,3}$/.test(rawLimit)) {
- return homeError(res, homeFailure(HOME_ERR.VALIDATION, 'limit must be a number.'));
- }
- const limit = Math.min(Number(rawLimit) || DEFAULT_LIMIT, MAX_LIMIT);
-
- const before = url.searchParams.get('before');
- if (before && !Number.isFinite(Date.parse(before))) {
- return homeError(res, homeFailure(HOME_ERR.VALIDATION, 'before must be an ISO 8601 timestamp.'));
+ const beforeRaw = url.searchParams.get('before');
+ let before = null;
+ if (beforeRaw) {
+ const at = new Date(beforeRaw);
+ if (Number.isNaN(at.getTime())) {
+ return error(res, 400, 'validation_error', 'before must be an ISO timestamp from a previous page.');
+ }
+ before = at;
}
- const rows = await listHomeActions(access.home.id, { limit: limit + 1, before });
+ // One extra row answers "is there another page" without a second count query
+ // over a table that only grows.
+ const rows = await listHomeActions(home.id, { limit: limit + 1, before });
const hasMore = rows.length > limit;
- const actions = hasMore ? rows.slice(0, limit) : rows;
+ const page = hasMore ? rows.slice(0, limit) : rows;
return json(res, 200, {
- home: publicHome(access.home),
- actions: actions.map(publicAction),
- // The cursor is the oldest row's timestamp, so the next page continues from
- // exactly where this one stopped even as new rows land at the top.
- next_before: hasMore ? isoOf(actions[actions.length - 1]?.created_at) : null,
+ actions: page.map(shape),
+ next_before: hasMore ? new Date(page[page.length - 1].created_at).toISOString() : null,
});
});
-/**
- * `detail` is deliberately dropped from the list view. It is a small free-form
- * object written by the action path, and this endpoint renders straight into a
- * page: keeping it out means one less place for a house-controlled string to
- * reach a client that has no schema for it.
- */
-function publicAction(row) {
+function shape(row) {
return {
id: String(row.id),
actor: row.actor,
channel: row.channel,
action: row.action,
- entity_ids: Array.isArray(row.entity_ids) ? row.entity_ids : [],
- guarded: Boolean(row.guarded),
- confirmed: Boolean(row.confirmed_by),
- risk: row.risk ?? null,
+ entity_ids: row.entity_ids || [],
+ guarded: row.guarded,
+ confirmed_by: row.confirmed_by,
+ risk: row.risk,
outcome: row.outcome,
- created_at: isoOf(row.created_at),
+ detail: row.detail ?? null,
+ created_at: row.created_at,
};
}
-function isoOf(value) {
- if (!value) return null;
- const at = value instanceof Date ? value : new Date(value);
- return Number.isFinite(at.getTime()) ? at.toISOString() : null;
+function clamp(value, min, max) {
+ return Math.min(Math.max(Math.trunc(value) || min, min), max);
}
diff --git a/api/home/[id]/macros.js b/api/home/[id]/macros.js
new file mode 100644
index 000000000..d3a07fe41
--- /dev/null
+++ b/api/home/[id]/macros.js
@@ -0,0 +1,61 @@
+// GET /api/home/:id/macros: the scenes and scripts this house already has.
+//
+// For the UI, which lists them as buttons, and for the agent, which needs to
+// know that "Bedtime" exists before it starts composing twelve individual
+// service calls to approximate it. The user's own scene knows about the plant
+// light and the fish tank; a composed sequence never will.
+//
+// The canonical macros (good night, leaving, arriving, morning, movie, focus)
+// come back alongside, each annotated with whether this house has something that
+// matches it. That is what lets a connect screen say "you have no Leaving scene,
+// here is what one usually does" instead of showing an empty list and no next
+// step.
+
+import { MACROS, resolveIntent } from '@three-ws/home-bridge';
+
+import { resolveHomeAccess } from '../../_lib/home/access.js';
+import { toHomeFailure } from '../../_lib/home/errors.js';
+import { withHome } from '../../_lib/home/runtime.js';
+import { cors, error, json, method, rateLimited, wrap } from '../../_lib/http.js';
+import { limits } from '../../_lib/rate-limit.js';
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'GET,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['GET'])) return;
+
+ const access = await resolveHomeAccess(req, res, req.query?.id, 'read');
+ if (!access.ok) return error(res, access.status, access.code, access.message);
+ const { caller, home } = access;
+
+ const rl = await limits.homeRead(caller.userId);
+ if (!rl.success) return rateLimited(res, rl, 'too many home reads, slow down');
+
+ try {
+ const payload = await withHome(home.id, caller.userId, (bridge) => {
+ const macros = bridge.macros();
+ return {
+ macros: macros.map((m) => ({ entity_id: m.entityId, name: m.name, kind: m.kind })),
+ // Resolved against this house's real scene names, so an empty `match`
+ // is a true statement about the house and not a guess.
+ canonical: Object.entries(MACROS).map(([id, macro]) => {
+ const match = resolveIntent(macro.triggers[0], macros);
+ return {
+ id,
+ label: macro.label,
+ example_phrase: macro.triggers[0],
+ match: match ? { entity_id: match.entityId, name: match.name, kind: match.kind } : null,
+ };
+ }),
+ };
+ });
+ return json(res, 200, payload);
+ } catch (err) {
+ const shaped = toHomeFailure(err);
+ if (shaped.unexpected) throw err;
+ return error(res, shaped.status, shaped.code, shaped.message, {
+ code: shaped.code,
+ message: shaped.message,
+ ...(shaped.detailCode ? { detail_code: shaped.detailCode } : {}),
+ });
+ }
+});
diff --git a/api/home/[id]/members.js b/api/home/[id]/members.js
index 497b8612b..8be5b818e 100644
--- a/api/home/[id]/members.js
+++ b/api/home/[id]/members.js
@@ -15,6 +15,7 @@
import { logAudit } from '../../_lib/audit.js';
import { getSessionUser } from '../../_lib/auth.js';
import { requireCsrf } from '../../_lib/csrf.js';
+import { assertMemberCapacity, HomeQuotaError } from '../../_lib/home/entitlements.js';
import {
ASSIGNABLE_ROLES,
canAssignRole,
@@ -41,6 +42,11 @@ function inviteUrl(req, token) {
return `${proto}://${host}/home/join?invite=${encodeURIComponent(token)}`;
}
+/** "an admin" / "a member": role names are user-facing copy, not identifiers. */
+function a(role) {
+ return /^[aeiou]/i.test(String(role)) ? `an ${role}` : `a ${role}`;
+}
+
function emailish(value) {
const v = String(value || '').trim().toLowerCase();
return /^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(v) && v.length <= 254 ? v : null;
@@ -109,7 +115,21 @@ export default wrap(async (req, res) => {
const role = String(body?.role || '').trim();
if (!canAssignRole(gate.role, role)) {
- return error(res, 403, 'role_forbidden', `a ${gate.role} cannot invite somebody as ${role || 'that role'}`);
+ return error(res, 403, 'role_forbidden', `${a(gate.role)} cannot invite somebody as ${role ? a(role) : 'that role'}`);
+ }
+
+ // Seats are billed to the home's owner, not to whoever sent the invite, and
+ // the ceiling counts outstanding invitations as well as members: an unspent
+ // invite is a seat about to be taken, and discovering the refusal at the
+ // moment somebody accepts is the worst time to discover it.
+ try {
+ await assertMemberCapacity(homeId);
+ } catch (err) {
+ if (!(err instanceof HomeQuotaError)) throw err;
+ return error(res, err.status, err.code, err.message, {
+ code: err.code,
+ quota: { dimension: err.dimension, label: err.dimensionLabel, limit: err.limit, used: err.used, upgrade: err.upgradePath },
+ });
}
const invite = await createInvite({
@@ -137,12 +157,12 @@ export default wrap(async (req, res) => {
const target = await resolveMembership(homeId, targetId);
if (!target) return error(res, 404, 'not_found', 'that person is not in this household');
if (!canManageMember(gate.role, target.role)) {
- return error(res, 403, 'role_forbidden', `a ${gate.role} cannot change a ${target.role}`);
+ return error(res, 403, 'role_forbidden', `${a(gate.role)} cannot change ${a(target.role)}`);
}
const role = body?.role === undefined ? target.role : String(body.role).trim();
if (!canAssignRole(gate.role, role)) {
- return error(res, 403, 'role_forbidden', `a ${gate.role} cannot assign the ${role || 'requested'} role`);
+ return error(res, 403, 'role_forbidden', `${a(gate.role)} cannot assign the ${role || 'requested'} role`);
}
const scope = body?.scope === undefined ? target.scope : body.scope;
@@ -171,7 +191,7 @@ export default wrap(async (req, res) => {
const target = await resolveMembership(homeId, targetId);
if (!target) return error(res, 404, 'not_found', 'that person is not in this household');
if (!canManageMember(gate.role, target.role)) {
- return error(res, 403, 'role_forbidden', `a ${gate.role} cannot remove a ${target.role}`);
+ return error(res, 403, 'role_forbidden', `${a(gate.role)} cannot remove ${a(target.role)}`);
}
const { removed, grantsRevoked } = await removeMember({ homeId, userId: targetId });
diff --git a/api/home/[id]/stream.js b/api/home/[id]/stream.js
index b654b6fa1..4f2af248e 100644
--- a/api/home/[id]/stream.js
+++ b/api/home/[id]/stream.js
@@ -26,9 +26,10 @@
// frames until the response ends, which for a stream is never, and the page
// looks hung while the server believes it is delivering.
-import { resolveHomeAccess } from '../../_lib/home/access.js';
+import { filterGraphForScope, resolveHomeAccess } from '../../_lib/home/access.js';
import { toHomeFailure } from '../../_lib/home/errors.js';
-import { subscribe } from '../../_lib/home/runtime.js';
+import { assertWithinLimit, HomeQuotaError, resolveHomeEntitlementsForUser } from '../../_lib/home/entitlements.js';
+import { streamCount, subscribe } from '../../_lib/home/runtime.js';
import { cors, error, method, rateLimited, wrap } from '../../_lib/http.js';
import { limits } from '../../_lib/rate-limit.js';
@@ -41,15 +42,46 @@ export default wrap(async (req, res) => {
if (cors(req, res, { methods: 'GET,OPTIONS', credentials: true })) return;
if (!method(req, res, ['GET'])) return;
- const access = await resolveHomeAccess(req, res, req.query?.id);
+ const access = await resolveHomeAccess(req, res, req.query?.id, 'read');
if (!access.ok) return error(res, access.status, access.code, access.message);
const { caller, home } = access;
const rl = await limits.homeStream(caller.userId);
if (!rl.success) return rateLimited(res, rl, 'too many stream connections, slow down');
+ // The plan's per-home stream ceiling. This is the wall-display dimension: a
+ // screen left open in a kitchen is a subscriber we serialize the whole house
+ // to on every state change, for the entire month, and it is the second
+ // measured cost in this lane after the held socket itself.
+ //
+ // The count is this instance's, which under-states a fleet-wide total and so
+ // errs toward admitting the stream. That is the only direction a quota may
+ // err, and it is the same bias the platform's other counters take.
+ //
+ // A refusal here is a normal HTTP response with a designed body, deliberately
+ // BEFORE any SSE head is written: a stream that opens and then says nothing is
+ // the failure mode this whole route was shaped to avoid.
+ try {
+ const entitlements = await resolveHomeEntitlementsForUser(caller.userId);
+ assertWithinLimit({ entitlements, dimension: 'streams', used: streamCount(home.id) });
+ } catch (err) {
+ if (!(err instanceof HomeQuotaError)) throw err;
+ return error(res, err.status, err.code, err.message, {
+ code: err.code,
+ message: err.message,
+ quota: { dimension: err.dimension, label: err.dimensionLabel, limit: err.limit, used: err.used, upgrade: err.upgradePath },
+ });
+ }
+
let closed = false;
let flowing = false;
+ // Declared here, not beside `deliver` below, because the first frame is
+ // flushed the moment the head is written and that call runs ABOVE the point
+ // a `let` further down would be initialized. Temporal dead zone: the very
+ // first subscriber threw "Cannot access 'lastStatusKey' before
+ // initialization" and got a 500 instead of a stream.
+ let lastStatusKey = null;
+ let lastGraph = null;
/** The event `subscribe` delivers synchronously, before the head exists. */
let pending = null;
@@ -128,8 +160,6 @@ export default wrap(async (req, res) => {
* heartbeat arrived, so the split happens here and each half is sent only when
* that half changed.
*/
- let lastStatusKey = null;
- let lastGraph = null;
function deliver(event) {
const statusKey = `${event.status}|${event.stale}|${event.connected}`;
if (statusKey !== lastStatusKey) {
@@ -150,7 +180,13 @@ export default wrap(async (req, res) => {
// already said.
if (event.graph && event.graph !== lastGraph) {
lastGraph = event.graph;
- send('graph', { graph: event.graph, stale: Boolean(event.stale), at: Date.now() });
+ // Filtered per member, on every frame, before it is serialized. The
+ // identity comparison above is against the RAW graph on purpose: it
+ // answers "did the house change", and the filtering is what this one
+ // subscriber is allowed to see of that change. A guest given the kitchen
+ // never receives a frame carrying another room, so no client-side rule
+ // stands between them and a room they were not given.
+ send('graph', { graph: filterGraphForScope(event.graph, access.scope), stale: Boolean(event.stale), at: Date.now() });
}
}
diff --git a/api/home/index.js b/api/home/index.js
index 972e15ccc..0978f18d4 100644
--- a/api/home/index.js
+++ b/api/home/index.js
@@ -24,12 +24,14 @@
// would follow to turn it on. Treating a missing optional integration as a
// failure is how a connect screen tells a person their working house is broken.
-import { isPrivateHost, normalizeBaseUrl } from '@three-ws/home-bridge';
+import { normalizeBaseUrl } from '@three-ws/home-bridge';
import { logAudit } from '../_lib/audit.js';
import { requireCsrf } from '../_lib/csrf.js';
import { publicHome, resolveCaller } from '../_lib/home/access.js';
+import { assertWithinLimit, HomeQuotaError, resolveHomeEntitlementsForUser } from '../_lib/home/entitlements.js';
import { homeError, homeFailure, HOME_ERR } from '../_lib/home/errors.js';
+import { assertDialableHomeUrl, HomeUrlError } from '../_lib/home-url-guard.js';
import { createConnection, HOME_STATUS, listConnections } from '../_lib/home/store.js';
import { verifyConnection } from '../_lib/home/verify.js';
import { cors, error, json, method, rateLimited, readJson, wrap } from '../_lib/http.js';
@@ -55,8 +57,12 @@ async function handleList(req, res, caller) {
const rl = await limits.homeRead(caller.userId);
if (!rl.success) return rateLimited(res, rl, 'too many home reads, slow down');
+ // Every home this account is a MEMBER of, which is not the same list as every
+ // home it connected: a partner's house and a colleague's office belong here
+ // too, each carrying the role this account holds in it so the UI can render a
+ // guest's house as a guest's house without a second call per home.
const homes = await listConnections(caller.userId);
- return json(res, 200, { homes: homes.map(publicHome) });
+ return json(res, 200, { homes: homes.map((h) => ({ ...publicHome(h), role: h.role })) });
}
async function handleConnect(req, res, caller) {
@@ -93,20 +99,68 @@ async function handleConnect(req, res, caller) {
return homeError(res, err);
}
+ // The plan check happens BEFORE the socket, for the same reason the URL check
+ // does: an account that cannot add another home should be told so in a
+ // sentence, not after a fifteen second handshake with a house we are about to
+ // refuse. Reconnecting a house this account already has is an UPDATE, not an
+ // acquisition (createConnection upserts on the normalized URL), so it is
+ // excluded from the count and a token rotation is never refused for being one
+ // home too many.
+ const existing = await listConnections(caller.userId);
+ const isReconnect = existing.some((h) => h.base_url === normalized.http);
+ if (!isReconnect) {
+ const entitlements = await resolveHomeEntitlementsForUser(caller.userId);
+ const active = existing.filter((h) => !h.deactivated_at).length;
+ try {
+ assertWithinLimit({ entitlements, dimension: 'homes', used: active });
+ } catch (err) {
+ if (!(err instanceof HomeQuotaError)) throw err;
+ return json(res, err.status, {
+ error: err.code,
+ error_description: err.message,
+ code: err.code,
+ message: err.message,
+ quota: {
+ dimension: err.dimension,
+ label: err.dimensionLabel,
+ limit: err.limit,
+ used: err.used,
+ tier: err.tierId,
+ upgrade: err.upgradePath,
+ },
+ });
+ }
+ }
+
// Our servers cannot route to RFC1918 space at all, so a private address is a
// certain failure we can name up front rather than a fifteen second wait
// followed by a generic timeout.
- const host = new URL(normalized.http).hostname;
- if (isPrivateHost(host) && !normalized.loopback) {
+ //
+ // This is a DNS resolution, not a hostname test, and the difference is the
+ // whole control. A hostname test passes `10-0-0-1.nip.io` and every other
+ // public name that answers with an address inside our network, and our
+ // servers would then dial it on three channels with our network identity. The
+ // addresses this returns are the only ones the connect is allowed to reach,
+ // and they are handed to verifyConnection so the name is resolved once rather
+ // than once per channel (which is also where a rebinding host would slip in).
+ let dial;
+ try {
+ dial = await assertDialableHomeUrl(normalized.http);
+ } catch (err) {
+ if (!(err instanceof HomeUrlError)) throw err;
return homeError(res, homeFailure(
- HOME_ERR.UNREACHABLE,
- `${host} is an address on your own network, and three.ws runs on the public internet, so it cannot reach it. Use the remote https URL from Home Assistant Cloud or your own reverse proxy.`,
+ err.code === 'bad_url' ? HOME_ERR.BAD_URL : HOME_ERR.UNREACHABLE,
+ err.message,
));
}
let measured;
try {
- measured = await verifyConnection({ baseUrl: normalized.http, token });
+ measured = await verifyConnection({
+ baseUrl: normalized.http,
+ token,
+ pin: { host: dial.host, addresses: dial.addresses, secure: dial.secure },
+ });
} catch (err) {
// Nothing is stored on a failed verify: a house we could not reach never
// becomes a row, and the token never becomes ciphertext at rest.
@@ -127,9 +181,13 @@ async function handleConnect(req, res, caller) {
userId: caller.userId,
action: 'connect_home',
resourceId: home.id,
- // The base URL is the one identifying fact worth keeping; the token is not
- // here, is not logged anywhere else, and must never be added.
- meta: { base_url: home.base_url, entity_count: measured.capabilities.entityCount, mcp: measured.capabilities.mcp },
+ // The home id is the identifying fact, and it is already in resourceId. The
+ // base URL is deliberately absent: audit_log has its own 365 day window,
+ // its own readers, and its user_id is SET NULL on account deletion rather
+ // than removed, so an address written here outlives the account that owned
+ // it. The token is not here, is not logged anywhere else, and must never be
+ // added. See docs/home-privacy.md.
+ meta: { transport: home.transport, entity_count: measured.capabilities.entityCount, mcp: measured.capabilities.mcp },
req,
});
diff --git a/api/home/privacy.js b/api/home/privacy.js
index 094212b89..7129a70f4 100644
--- a/api/home/privacy.js
+++ b/api/home/privacy.js
@@ -26,7 +26,8 @@
import { getSessionUser } from '../_lib/auth.js';
import { requireCsrf } from '../_lib/csrf.js';
-import { cors, error, json, method, readJson, wrap } from '../_lib/http.js';
+import { cors, error, json, method, rateLimited, readJson, wrap } from '../_lib/http.js';
+import { limits } from '../_lib/rate-limit.js';
import {
DEFAULT_ACTION_LOG_RETENTION_DAYS,
MAX_ACTION_LOG_RETENTION_DAYS,
@@ -54,6 +55,12 @@ export default wrap(async (req, res) => {
if (req.method === 'GET') {
const wantsExport = req.query?.export === '1' || req.query?.export === 'true';
+ // The summary is a page load; the export assembles every home, grant and
+ // action-log row this account has. They do not belong in the same bucket.
+ const rl = await (wantsExport ? limits.homePrivacy(session.id) : limits.homeRead(session.id));
+ if (!rl.success) {
+ return rateLimited(res, rl, wantsExport ? 'too many exports, try again shortly' : 'too many reads, slow down');
+ }
if (wantsExport) {
const data = await exportHomeData(session.id);
// A download, not a page: the browser saves it under a name the user
@@ -70,6 +77,11 @@ export default wrap(async (req, res) => {
// both carry the same CSRF requirement as the other session-auth writers.
if (!(await requireCsrf(req, res, session.id))) return;
+ // Both write verbs change or destroy data that cannot be regenerated, so both
+ // are held to the tight bucket rather than the read one.
+ const writeLimit = await limits.homePrivacy(session.id);
+ if (!writeLimit.success) return rateLimited(res, writeLimit, 'too many privacy changes, try again shortly');
+
const body = (await readJson(req)) ?? {};
if (req.method === 'PATCH') {
@@ -85,6 +97,16 @@ export default wrap(async (req, res) => {
if (result.ok) return json(res, 200, result);
if (result.code === 'not_found') return error(res, 404, 'not_found', 'no such home');
+ if (result.code === 'retention_over_plan') {
+ return error(
+ res,
+ 402,
+ 'retention_over_plan',
+ `Your plan keeps the action log for up to ${result.limit} days and you asked for ${result.requested}. ` +
+ 'Upgrade at three.ws/pricing to keep it longer. Nothing already recorded is affected: a plan never shortens a log you have already kept.',
+ { code: 'retention_over_plan', quota: { dimension: 'logRetentionDays', limit: result.limit, requested: result.requested, upgrade: '/pricing' } },
+ );
+ }
if (result.code === 'reason_required') {
return error(
res,
diff --git a/home-assistant-integration/custom_components/three_ws/__init__.py b/home-assistant-integration/custom_components/three_ws/__init__.py
index 087abf9ff..3409d9095 100644
--- a/home-assistant-integration/custom_components/three_ws/__init__.py
+++ b/home-assistant-integration/custom_components/three_ws/__init__.py
@@ -15,9 +15,7 @@ the ones that administer this machine refused outright.
from __future__ import annotations
-import json
import logging
-from pathlib import Path
from typing import Any
from homeassistant.auth.const import GROUP_ID_ADMIN
@@ -25,7 +23,9 @@ from homeassistant.config_entries import ConfigEntry
from homeassistant.const import EVENT_HOMEASSISTANT_STOP, Platform
from homeassistant.core import HomeAssistant
from homeassistant.helpers.dispatcher import async_dispatcher_send
+from homeassistant.loader import async_get_integration
+from . import allowlist
from .const import (
CONF_INSTALL_TOKEN,
CONF_REFRESH_TOKEN_ID,
@@ -42,15 +42,18 @@ _LOGGER = logging.getLogger(__name__)
PLATFORMS: list[Platform] = [Platform.BINARY_SENSOR]
-def _version() -> str:
- manifest = json.loads((Path(__file__).parent / "manifest.json").read_text(encoding="utf-8"))
- return str(manifest.get("version", "0.0.0"))
-
-
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
"""Mint this install's local credential and start dialling out."""
hass.data.setdefault(DOMAIN, {})
- hass.data[f"{DOMAIN}_version"] = _version()
+ # The loader already parsed the manifest during startup, so asking it for the
+ # version costs nothing and, unlike reading the file here, does not do disk
+ # IO on the event loop.
+ version = str((await async_get_integration(hass, DOMAIN)).version or "0.0.0")
+ hass.data[f"{DOMAIN}_version"] = version
+
+ # Every relayed frame is checked against the allowlist inside the loop, so
+ # the file it is loaded from is read once, here, in an executor.
+ await allowlist.async_preload(hass)
refresh_token = await _async_get_or_create_token(hass, entry)
@@ -66,7 +69,7 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
install_token=entry.data[CONF_INSTALL_TOKEN],
local_ws_url=_local_ws_url(hass),
mint_access_token=mint_access_token,
- integration_version=_version(),
+ integration_version=version,
on_status=lambda status: async_dispatcher_send(hass, f"{SIGNAL_STATUS}_{entry.entry_id}", status),
)
hass.data[DOMAIN][entry.entry_id] = client
@@ -96,9 +99,9 @@ async def async_remove_entry(hass: HomeAssistant, entry: ConfigEntry) -> None:
token_id = entry.data.get(CONF_REFRESH_TOKEN_ID)
user_id = entry.data.get(CONF_USER_ID)
if token_id:
- token = await hass.auth.async_get_refresh_token(token_id)
+ token = hass.auth.async_get_refresh_token(token_id)
if token is not None:
- await hass.auth.async_remove_refresh_token(token)
+ hass.auth.async_remove_refresh_token(token)
if user_id:
user = await hass.auth.async_get_user(user_id)
if user is not None and user.system_generated:
@@ -116,7 +119,7 @@ async def _async_get_or_create_token(hass: HomeAssistant, entry: ConfigEntry) ->
"""
token_id = entry.data.get(CONF_REFRESH_TOKEN_ID)
if token_id:
- existing = await hass.auth.async_get_refresh_token(token_id)
+ existing = hass.auth.async_get_refresh_token(token_id)
if existing is not None:
return existing
diff --git a/home-assistant-integration/custom_components/three_ws/allowlist.py b/home-assistant-integration/custom_components/three_ws/allowlist.py
index 01dd90ea2..711b2f168 100644
--- a/home-assistant-integration/custom_components/three_ws/allowlist.py
+++ b/home-assistant-integration/custom_components/three_ws/allowlist.py
@@ -26,6 +26,16 @@ def manifest() -> dict[str, Any]:
return json.loads(_ALLOWLIST_PATH.read_text(encoding="utf-8"))
+async def async_preload(hass: Any) -> None:
+ """Warm the cache off the event loop.
+
+ Every allowlist check happens on a hot path inside the loop, and Home
+ Assistant rightly refuses to let an integration read a file there. Reading
+ it once in an executor at setup makes every later check pure CPU.
+ """
+ await hass.async_add_executor_job(manifest)
+
+
class Denied(Exception):
"""A message was refused by the allowlist.
diff --git a/packages/home-bridge/README.md b/packages/home-bridge/README.md
index 8a4572b03..40bf2fc7e 100644
--- a/packages/home-bridge/README.md
+++ b/packages/home-bridge/README.md
@@ -140,6 +140,38 @@ An instance without the integration set up throws `ERR.NO_MCP`, which is an ordi
be in and not an outage. The WebSocket channel works on every instance with nothing but a
token, so the MCP channel is always an upgrade and never a requirement.
+## A house you cannot dial into
+
+Most Home Assistant installs answer only on their own network, and no remote https URL exists for
+them. For those, the house dials out: the three.ws integration inside it opens one outbound
+WebSocket to a relay, and this package reaches the instance back down that socket.
+
+Above this line nothing changes. The room graph, the gate, intent resolution and every error code
+are identical, because `HomeBridge` takes a transport where it would otherwise take a token:
+
+```js
+import { HomeBridge, createRelayTransport } from '@three-ws/home-bridge';
+
+const home = new HomeBridge({
+ transport: createRelayTransport({
+ relayUrl: 'wss://home-relay.three.ws',
+ relayId,
+ serviceToken,
+ }),
+});
+console.log(home.transport); // "relay"
+console.log(home.baseUrl); // "wss://home-relay.three.ws/v1/bridge?relay_id=abc123"
+await home.connect();
+```
+
+No `baseUrl` and no `token`: a transport replaces both. It carries **no Home Assistant
+credential** at all, because the integration authenticates locally, inside the house, and hands
+the session over already authenticated, so no long-lived token ever leaves the building.
+
+The two halves of that socket are [`services/home-relay`](../../services/home-relay) (the
+terminator) and [`home-assistant-integration/`](../../home-assistant-integration) (the piece that
+installs in the house and dials out).
+
## Errors
Every failure carries a `code`, because a connect screen has to tell "your token is wrong"
@@ -166,6 +198,7 @@ apart from "your house is offline".
| `summarizeLighting` / `summarizeClimate` / `summarizeSecurity` | Per-room rollups the 3D scene reads |
| `resolveIntent` / `matchMacro` / `MACROS` | Phrase to an existing scene or script |
| `classifyCall` / `classifyMcpCall` / `createAllowList` | The physical-action gate |
+| `createRelayTransport` / `relayCloseError` / `RELAY_PROTOCOL_VERSION` | Reach a house that dialled out to a relay instead of one you dial into. See below |
| `normalizeBaseUrl` / `isPrivateHost` | URL handling and the LAN reachability check |
## Tests
@@ -177,14 +210,26 @@ npx vitest run packages/home-bridge
The default suite runs against `tests/fixtures/home.json`, a recording of a real Home
Assistant instance rather than hand-written shapes (regenerate it with
`scripts/capture-home-fixture.mjs`). Set `HOME_ASSISTANT_URL` and `HOME_ASSISTANT_TOKEN` to
-also run the live suite, which changes real state on a real instance:
+also run the live suite, which changes real state on a real instance. A throwaway house,
+onboarded and seeded, is one command:
```bash
-docker run -d --name ha -p 8123:8123 ghcr.io/home-assistant/home-assistant:stable
-# add `demo:` to its configuration.yaml for a house full of entities, then restart
-HOME_ASSISTANT_URL=http://localhost:8123 HOME_ASSISTANT_TOKEN=... npx vitest run packages/home-bridge
+node scripts/home-test-instance.mjs --up --onboard --seed --json
+# {"ok":true,"baseUrl":"http://127.0.0.1:42125","token":"eyJhbGciOi...","seeded":true, ...}
+
+HOME_ASSISTANT_URL=http://127.0.0.1:42125 HOME_ASSISTANT_TOKEN=... npx vitest run packages/home-bridge
+node scripts/home-test-instance.mjs --down
```
+## Read next
+
+- [docs/tutorials/connect-your-home.md](../../docs/tutorials/connect-your-home.md): zero to a
+ working agent in a real house, by text and by voice.
+- [`@three-ws/home-mcp`](../home-mcp): this library packaged as an MCP server, so any assistant
+ can run a house without you writing a client.
+- [docs/smart-home.md](../../docs/smart-home.md): why Home Assistant owns the device layer, what
+ else was evaluated, and where this goes next.
+
## License
Apache-2.0. Built on [`home-assistant-js-websocket`](https://github.com/home-assistant/home-assistant-js-websocket)
diff --git a/packages/home-bridge/package.json b/packages/home-bridge/package.json
index 90d382ef6..002a041f9 100644
--- a/packages/home-bridge/package.json
+++ b/packages/home-bridge/package.json
@@ -25,7 +25,9 @@
"main": "./src/index.js",
"module": "./src/index.js",
"exports": {
- ".": "./src/index.js"
+ ".": "./src/index.js",
+ "./url": "./src/url.js",
+ "./errors": "./src/errors.js"
},
"files": [
"src",
@@ -40,11 +42,15 @@
"home-assistant-js-websocket": "^9.6.0"
},
"peerDependencies": {
- "@modelcontextprotocol/sdk": "^1.29.0"
+ "@modelcontextprotocol/sdk": "^1.29.0",
+ "ws": "^8.21.0"
},
"peerDependenciesMeta": {
"@modelcontextprotocol/sdk": {
"optional": true
+ },
+ "ws": {
+ "optional": true
}
},
"engines": {
diff --git a/packages/home-bridge/src/bridge.js b/packages/home-bridge/src/bridge.js
index a8be44b5d..ebea2d42a 100644
--- a/packages/home-bridge/src/bridge.js
+++ b/packages/home-bridge/src/bridge.js
@@ -30,7 +30,8 @@ export class HomeBridge {
#unsubscribers = [];
#states = {};
#registries = { floors: [], areas: [], devices: [], entities: [] };
- #graph = { floors: [], rooms: [], unassigned: [] };
+ #config = null;
+ #graph = { floors: [], rooms: [], unassigned: [], temperatureUnit: null };
#listeners = new Map();
#rebuildTimer = null;
#closed = false;
@@ -47,6 +48,9 @@ export class HomeBridge {
* add-on uses, for the majority of installs that only exist on a LAN. It is
* an EITHER/OR with baseUrl + token: a relayed home authenticates inside the
* house and three.ws never holds a Home Assistant credential for it.
+ * @param {Function} [options.createSocket] a `home-assistant-js-websocket`
+ * socket factory, for a server that must pin the connection to addresses it
+ * already validated (see api/_lib/home-url-guard.js). Browser callers omit it.
* @param {boolean} [options.requireSecure] reject plain http for remote hosts
* @param {string[]} [options.allowedEntities] entities pre-approved for guarded actions
* @param {number} [options.rebuildDelayMs] coalescing window for graph rebuilds
@@ -99,6 +103,17 @@ export class HomeBridge {
return this.#graph;
}
+ /**
+ * The temperature unit this house measures in, as the instance itself
+ * reports it ('\u00b0C' or '\u00b0F'), or null before connect(). Read, never
+ * guessed: a browser locale says where the reader is, not what the
+ * thermostat is set to, and an American house browsed from Berlin is still
+ * in Fahrenheit.
+ */
+ get temperatureUnit() {
+ return this.#config?.unit_system?.temperature || null;
+ }
+
/** Raw entity states, keyed by entity id. */
get states() {
return this.#states;
@@ -135,7 +150,14 @@ export class HomeBridge {
// after this line is identical for both, which is the whole point.
const connectionOptions = this.#options.transport
? { createSocket: this.#options.transport.createSocket }
- : { auth: createLongLivedTokenAuth(this.#options.baseUrl, this.#options.token) };
+ : {
+ auth: createLongLivedTokenAuth(this.#options.baseUrl, this.#options.token),
+ // A server dialling a user-supplied URL supplies its own socket
+ // factory so the connection is pinned to the addresses its SSRF
+ // guard validated. In the browser there is nothing to pin and the
+ // option is simply absent.
+ ...(this.#options.createSocket ? { createSocket: this.#options.createSocket } : {}),
+ };
try {
this.#connection = await createConnection(connectionOptions);
} catch (err) {
@@ -145,7 +167,7 @@ export class HomeBridge {
this.#connection.addEventListener('ready', () => this.#emit('reconnected', undefined));
this.#connection.addEventListener('disconnected', () => this.#emit('disconnected', undefined));
- this.#registries = await this.#loadRegistries();
+ [this.#registries, this.#config] = await Promise.all([this.#loadRegistries(), this.#loadConfig()]);
this.#unsubscribers.push(
subscribeEntities(this.#connection, (entities) => {
this.#states = entities;
@@ -183,6 +205,19 @@ export class HomeBridge {
return { floors, areas, devices, entities };
}
+ // get_config carries the unit system, and it is the only place the house
+ // states its own units. An instance that refuses it (an old core, a relay
+ // that filters the message) leaves the unit null, and the scene falls back
+ // to a bare degree sign rather than inventing a unit it cannot verify.
+ async #loadConfig() {
+ try {
+ const result = await this.#connection.sendMessagePromise({ type: 'get_config' });
+ return result && typeof result === 'object' ? result : null;
+ } catch {
+ return null;
+ }
+ }
+
async #list(type) {
try {
const result = await this.#connection.sendMessagePromise({ type });
@@ -201,7 +236,11 @@ export class HomeBridge {
}
#rebuild() {
- this.#graph = buildHomeGraph({ ...this.#registries, states: this.#states });
+ this.#graph = buildHomeGraph({
+ ...this.#registries,
+ states: this.#states,
+ temperatureUnit: this.temperatureUnit,
+ });
this.#emit('graph', this.#graph);
}
diff --git a/packages/home-bridge/src/mcp.js b/packages/home-bridge/src/mcp.js
index 17fec7be3..868ce1864 100644
--- a/packages/home-bridge/src/mcp.js
+++ b/packages/home-bridge/src/mcp.js
@@ -29,9 +29,11 @@ import { normalizeBaseUrl } from './url.js';
* action gate for tool calls, which is the only way an agent driving these
* tools is safe: see classifyMcpCall for why the tool names do not tell you.
* @param {(entityId: string) => boolean} [options.isAllowed] standing per-entity approvals
+ * @param {Function} [options.fetchImpl] a pinned fetch, for a server dialling a
+ * user-supplied URL. See api/_lib/home-url-guard.js.
* @returns {Promise<{ client: object, tools: Array, callTool: Function, close: () => Promise<void> }>}
*/
-export async function connectHomeMcp({ baseUrl, token, api, clientName = 'three.ws', entities, isAllowed } = {}) {
+export async function connectHomeMcp({ baseUrl, token, api, clientName = 'three.ws', entities, isAllowed, fetchImpl } = {}) {
const { http } = normalizeBaseUrl(baseUrl);
if (!token) throw new HomeBridgeError(ERR.AUTH, 'A Home Assistant long-lived access token is required.');
@@ -47,6 +49,9 @@ export async function connectHomeMcp({ baseUrl, token, api, clientName = 'three.
const url = new URL(`${http}/api/mcp${api ? `/${api}` : ''}`);
const transport = new StreamableHTTPClientTransport(url, {
requestInit: { headers: { authorization: `Bearer ${token}` } },
+ // A server dialling a user-supplied URL passes a fetch pinned to the
+ // addresses its SSRF guard validated; the browser has nothing to pin.
+ ...(fetchImpl ? { fetch: fetchImpl } : {}),
});
const client = new Client({ name: clientName, version: '0.1.0' }, { capabilities: {} });
diff --git a/packages/home-bridge/src/rooms.js b/packages/home-bridge/src/rooms.js
index 6986d58c3..0491d4a65 100644
--- a/packages/home-bridge/src/rooms.js
+++ b/packages/home-bridge/src/rooms.js
@@ -36,7 +36,7 @@ export function domainOf(entityId) {
* @param {Array} input.entities config/entity_registry/list
* @param {Record<string, object>} input.states entity_id to state object
*/
-export function buildHomeGraph({ floors = [], areas = [], devices = [], entities = [], states = {} } = {}) {
+export function buildHomeGraph({ floors = [], areas = [], devices = [], entities = [], states = {}, temperatureUnit = null } = {}) {
const deviceArea = new Map(devices.map((d) => [d.id, d.area_id || null]));
const rooms = new Map(
@@ -85,7 +85,7 @@ export function buildHomeGraph({ floors = [], areas = [], devices = [], entities
...room,
entities: room.entities.sort(byName),
lighting: summarizeLighting(room.entities),
- climate: summarizeClimate(room.entities),
+ climate: summarizeClimate(room.entities, temperatureUnit),
secured: summarizeSecurity(room.entities),
}));
@@ -93,6 +93,10 @@ export function buildHomeGraph({ floors = [], areas = [], devices = [], entities
floors: floors.map((f) => ({ id: f.floor_id, name: f.name, level: f.level ?? 0, icon: f.icon || null })).sort((a, b) => a.level - b.level),
rooms: list.sort(byName),
unassigned: unassigned.sort(byName),
+ // Carried on the graph rather than read at render time: the scene, the 2D
+ // fallback and the agent's answers all have to say the same unit, and this
+ // is the one object all three of them already read.
+ temperatureUnit,
};
}
@@ -144,14 +148,46 @@ export function summarizeLighting(entities) {
};
}
-export function summarizeClimate(entities) {
- const readings = entities
- .filter((e) => e.domain === 'climate' || (e.domain === 'sensor' && e.deviceClass === 'temperature'))
- .map((e) => (e.domain === 'climate' ? Number(e.attributes.current_temperature) : Number(e.state)))
- .filter((n) => Number.isFinite(n));
+const CELSIUS = '\u00b0C';
+const FAHRENHEIT = '\u00b0F';
+
+/**
+ * Convert one reading between the two units Home Assistant measures temperature
+ * in. An unknown pair is returned untouched rather than mangled: a wrong number
+ * is worse than an unconverted one, because it looks right.
+ */
+function convertTemperature(value, from, to) {
+ if (!Number.isFinite(value) || !from || !to || from === to) return value;
+ if (from === CELSIUS && to === FAHRENHEIT) return (value * 9) / 5 + 32;
+ if (from === FAHRENHEIT && to === CELSIUS) return ((value - 32) * 5) / 9;
+ return value;
+}
+
+/**
+ * The room's temperature, in the unit the house displays.
+ *
+ * A house is not all one unit. Switching an instance to US customary does not
+ * rewrite a sensor that declares its own `unit_of_measurement`, so a real house
+ * can hold a Celsius sensor and a Fahrenheit thermostat at once, and averaging
+ * their raw numbers produces a reading that belongs to neither. Every reading
+ * is converted to `unit` first, using the unit that reading itself declares: a
+ * sensor states it outright, and a climate entity is already normalised to the
+ * instance's own unit, which is what `unit` is.
+ */
+export function summarizeClimate(entities, unit = null) {
+ const readings = [];
+ for (const entity of entities) {
+ const isClimate = entity.domain === 'climate';
+ if (!isClimate && !(entity.domain === 'sensor' && entity.deviceClass === 'temperature')) continue;
+ const attributes = entity.attributes || {};
+ const raw = isClimate ? Number(attributes.current_temperature) : Number(entity.state);
+ if (!Number.isFinite(raw)) continue;
+ const own = (isClimate ? attributes.temperature_unit : attributes.unit_of_measurement) || unit;
+ readings.push(convertTemperature(raw, own, unit || own));
+ }
if (!readings.length) return null;
const mean = readings.reduce((a, b) => a + b, 0) / readings.length;
- return { temperature: Number(mean.toFixed(1)), sources: readings.length };
+ return { temperature: Number(mean.toFixed(1)), sources: readings.length, unit: unit || null };
}
/**
diff --git a/packages/home-bridge/src/safety.js b/packages/home-bridge/src/safety.js
index 20c2b6a64..0543e08e7 100644
--- a/packages/home-bridge/src/safety.js
+++ b/packages/home-bridge/src/safety.js
@@ -221,17 +221,25 @@ function toArray(value) {
* @param {object} call
* @param {string} call.domain
* @param {string} call.service
- * @param {object} [call.attributes] the entity's current attributes, for device_class
* @returns {boolean}
*/
-export function isSafetyAction({ domain, service, attributes = {} } = {}) {
+export function isSafetyAction({ domain, service } = {}) {
const d = String(domain || '').toLowerCase();
const s = String(service || '').toLowerCase();
- if (d === 'cover') {
- const deviceClass = String(attributes.device_class || '').toLowerCase();
- return GUARDED_COVER_CLASSES.has(deviceClass) && SAFE_SERVICES.has(s);
- }
+ // Deliberately NOT filtered by device_class, unlike classifyCall. The gate has
+ // to know whether a cover is a garage door before it will refuse opening it,
+ // because opening a blind is nothing and opening a garage is an opening in the
+ // building. Closing has no such asymmetry: there is no cover whose CLOSING is
+ // dangerous, and no valve whose closing is dangerous.
+ //
+ // That is not a shortcut, it is the property that makes the exemption usable.
+ // Reading device_class requires a live socket to the house, and the moment a
+ // safety exemption depends on the connection being healthy it stops being an
+ // exemption: the states where a user most needs to lock up (a paused home, a
+ // degraded instance, an account over quota) are exactly the states where the
+ // attributes are not in hand.
+ if (d === 'cover' || d === 'valve') return SAFE_SERVICES.has(s);
if (d === 'alarm_control_panel') return s.startsWith('alarm_arm') && SAFE_SERVICES.has(s);
if (GUARDED_DOMAINS.has(d)) return SAFE_SERVICES.has(s);
return false;
diff --git a/packages/home-bridge/src/transport-relay.js b/packages/home-bridge/src/transport-relay.js
index ca47168f8..94431fdae 100644
--- a/packages/home-bridge/src/transport-relay.js
+++ b/packages/home-bridge/src/transport-relay.js
@@ -46,15 +46,29 @@ const FRAME = {
};
/**
- * Resolve the WebSocket constructor. Node 22 has a global `WebSocket`, and a
- * caller can inject one (a test double, or `ws`) instead.
+ * Resolve the WebSocket constructor.
+ *
+ * The relay authenticates the platform with an `Authorization` header on the
+ * upgrade, and the WHATWG `WebSocket` a browser and Node both expose has no way
+ * to send one: its second argument is the subprotocol list, so passing headers
+ * there fails silently and the relay answers 401. This transport therefore uses
+ * `ws`, which does support upgrade headers, and is imported lazily so that
+ * merely importing this module costs nothing where the relay is not used.
+ *
+ * @param {Function} [injected] a constructor to use instead, for tests
*/
-function resolveWebSocket(injected) {
- const impl = injected || globalThis.WebSocket;
- if (typeof impl !== 'function') {
- throw new HomeBridgeError(ERR.UNREACHABLE, 'No WebSocket implementation is available for the relay transport. Pass WebSocketImpl.');
+async function resolveWebSocket(injected) {
+ if (typeof injected === 'function') return injected;
+ try {
+ const mod = await import('ws');
+ return mod.WebSocket || mod.default;
+ } catch (cause) {
+ throw new HomeBridgeError(
+ ERR.UNREACHABLE,
+ 'The relay transport needs the `ws` package, because the relay is authenticated with an upgrade header that the built-in WebSocket cannot send. Install ws, or pass WebSocketImpl.',
+ cause,
+ );
}
- return impl;
}
/**
@@ -72,7 +86,6 @@ export function createRelayTransport({ relayUrl, relayId, serviceToken, openTime
if (!relayUrl) throw new HomeBridgeError(ERR.BAD_URL, 'The relay transport needs a relayUrl.');
if (!relayId) throw new HomeBridgeError(ERR.BAD_URL, 'The relay transport needs a relayId.');
if (!serviceToken) throw new HomeBridgeError(ERR.AUTH, 'The relay transport needs the relay service token.');
- const WS = resolveWebSocket(WebSocketImpl);
const endpoint = buildEndpoint(relayUrl, relayId);
/**
@@ -80,8 +93,9 @@ export function createRelayTransport({ relayUrl, relayId, serviceToken, openTime
* every reconnect, so a house that goes offline and comes back recovers with
* no action from the user and no code above this line.
*/
- const createSocket = () =>
- new Promise((resolve, reject) => {
+ const createSocket = async () => {
+ const WS = await resolveWebSocket(WebSocketImpl);
+ return new Promise((resolve, reject) => {
let socket;
try {
socket = new WS(endpoint, { headers: { authorization: `Bearer ${serviceToken}` } });
@@ -113,6 +127,7 @@ export function createRelayTransport({ relayUrl, relayId, serviceToken, openTime
reject(err);
};
});
+ };
return { createSocket, endpoint, relayId };
}
diff --git a/packages/home-bridge/tests/home-bridge.test.js b/packages/home-bridge/tests/home-bridge.test.js
index 4f76ba186..aae362b9d 100644
--- a/packages/home-bridge/tests/home-bridge.test.js
+++ b/packages/home-bridge/tests/home-bridge.test.js
@@ -22,6 +22,7 @@ import {
normalizeBaseUrl,
resolveIntent,
resolveMcpTargets,
+ summarizeClimate,
summarizeLighting,
} from '../src/index.js';
@@ -103,7 +104,35 @@ describe('room graph', () => {
});
it('survives an empty house without throwing', () => {
- expect(buildHomeGraph()).toEqual({ floors: [], rooms: [], unassigned: [] });
+ expect(buildHomeGraph()).toEqual({ floors: [], rooms: [], unassigned: [], temperatureUnit: null });
+ });
+
+ it('converts a reading that declares its own unit into the unit the house shows', () => {
+ // The case this exists for: an instance switched to US customary does not
+ // rewrite a sensor pinned to Celsius, so the raw numbers are mixed. 20C is
+ // 68F, and averaged with a 70F thermostat the room is 69F, not 45 of
+ // nothing.
+ const room = [
+ { domain: 'sensor', deviceClass: 'temperature', state: '20', attributes: { unit_of_measurement: '\u00b0C' } },
+ { domain: 'climate', deviceClass: null, state: 'heat', attributes: { current_temperature: 70 } },
+ ];
+ expect(summarizeClimate(room, '\u00b0F')).toEqual({ temperature: 69, sources: 2, unit: '\u00b0F' });
+ // The same two readings displayed in Celsius: 70F is 21.1C, averaged with 20C.
+ expect(summarizeClimate(room, '\u00b0C').temperature).toBeCloseTo(20.6, 1);
+ });
+
+ it('leaves readings alone when the house never said what unit it uses', () => {
+ // No unit means no safe conversion. The raw number is passed through and
+ // labelled with a bare degree sign rather than converted on a guess.
+ const out = summarizeClimate([{ domain: 'sensor', deviceClass: 'temperature', state: '25', attributes: {} }]);
+ expect(out).toEqual({ temperature: 25, sources: 1, unit: null });
+ });
+
+ it('carries the unit the house reported, and null when it reported none', () => {
+ // Null is the honest answer, not a Celsius default: the scene shows a bare
+ // degree sign rather than labelling a reading with a unit nobody confirmed.
+ expect(buildHomeGraph().temperatureUnit).toBeNull();
+ expect(buildHomeGraph({ temperatureUnit: '\u00b0F' }).temperatureUnit).toBe('\u00b0F');
});
});
diff --git a/packages/home-bridge/tests/live-home.test.js b/packages/home-bridge/tests/live-home.test.js
index e0e5f3c7c..f66c3185f 100644
--- a/packages/home-bridge/tests/live-home.test.js
+++ b/packages/home-bridge/tests/live-home.test.js
@@ -47,6 +47,23 @@ live('against a real Home Assistant', () => {
expect(home.graph.rooms.length + home.graph.unassigned.length).toBeGreaterThan(0);
});
+ it('reports the unit the house measures temperature in, read from the house', async () => {
+ // The point of this one is that it is not a guess. Home Assistant states
+ // its unit system in get_config, and the assertion compares what the
+ // bridge exposes against what the instance's own REST config says, so a
+ // locale-derived or hardcoded default cannot pass it.
+ const res = await fetch(`${instance.baseUrl}/api/config`, {
+ headers: { Authorization: `Bearer ${instance.token}` },
+ });
+ expect(res.ok).toBe(true);
+ const config = await res.json();
+ expect(config.unit_system.temperature).toMatch(/^\u00b0[CF]$/);
+ expect(home.temperatureUnit).toBe(config.unit_system.temperature);
+ // And it reaches the graph the scene renders, which is the only copy the
+ // browser ever sees.
+ expect(home.graph.temperatureUnit).toBe(config.unit_system.temperature);
+ }, 30_000);
+
it('reports the version the house is actually running', () => {
// The connect screen and the capability record both have to state this,
// and a support conversation starts with it.
diff --git a/packages/home-mcp/src/lib/gate.js b/packages/home-mcp/src/lib/gate.js
index 2b32ec5bb..b2c2a4595 100644
--- a/packages/home-mcp/src/lib/gate.js
+++ b/packages/home-mcp/src/lib/gate.js
@@ -24,7 +24,7 @@
import { ERR } from '@three-ws/home-bridge';
/** Where a person actually confirms a guarded action. */
-export const CONFIRM_AT = 'https://three.ws/home';
+export const CONFIRM_AT = 'https://three.ws/smart-home';
/**
* Turn a bridge refusal into the answer the model should read.
@@ -53,8 +53,8 @@ export function refusal(err) {
message: err.message,
why: 'This action opens the house, and this server has no way for a person to say yes: an MCP client carries no session and no browser. It is refused rather than guessed at.',
how_a_person_confirms: [
- `Do it in the three.ws home surface at ${CONFIRM_AT}, where the action is shown to the account holder before it runs.`,
- 'Or, if you want this agent to hold a standing allowance for this exact entity, the person running this server adds it to HOME_ALLOWED_ENTITIES and restarts:' +
+ `Connect the house at ${CONFIRM_AT} and act through the hosted three.ws MCP server instead. That surface mints a pending confirmation and the account holder redeems it in their own browser, which is a person saying yes.`,
+ 'Or, for a standing allowance on this exact entity, the person running THIS server adds it to HOME_ALLOWED_ENTITIES and restarts:' +
(targets.length ? ` HOME_ALLOWED_ENTITIES=${targets.join(',')}` : ' HOME_ALLOWED_ENTITIES=lock.office_door'),
],
retry: 'Do not retry this call. No argument you can pass will change the answer.',
diff --git a/pages/home-scene.html b/pages/home-scene.html
index eea158854..a777b49a0 100644
--- a/pages/home-scene.html
+++ b/pages/home-scene.html
@@ -14,12 +14,11 @@
<link rel="stylesheet" href="/home-scene.css" />
</head>
<body>
- <a class="skip-link" href="#hs-stage">Skip to the house</a>
<div id="nav-root"></div>
<div class="hs-shell" id="hs-shell">
<div class="hs-bar">
- <a class="hs-back" href="/home/connect">
+ <a class="hs-back" href="/home">
<svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M19 12H5M12 19l-7-7 7-7" /></svg>
<span>Homes</span>
</a>
diff --git a/src/avatar-page.js b/src/avatar-page.js
index 55f0665f2..ed94374c2 100644
--- a/src/avatar-page.js
+++ b/src/avatar-page.js
@@ -37,6 +37,7 @@ import { emitRecallFromChat } from './agents/memory-client.js';
import { moodEngine } from './agents/mood-engine.js';
import { skillLabel } from './shared/skill-label.js';
import { mountCoinStatus } from './pump/coin-status-card.js';
+import { renderHomeConfirmation } from './home-confirm-card.js';
const ATTACHED_KEY_PREFIX = 'avatar_attached_v1:';
@@ -2429,6 +2430,14 @@ async function sendChatMessage(text) {
assistantNode.textContent = acc;
logEl.scrollTop = logEl.scrollHeight;
streamThoughtText(acc);
+ } else if (evt.type === 'home_tool') {
+ // The agent touched the connected house. A guarded action arrives
+ // here as a pending confirmation and is rendered as a card the
+ // person approves; the browser NEVER performs it itself, and there
+ // is no path from this branch to the door.
+ if (evt.status === 'pending_confirmation') {
+ renderHomeConfirmation(logEl, evt.data);
+ }
} else if (evt.type === 'done') {
// The server reports exactly which memories it recalled into this
// reply's context — turn that into a `memory:recalled` bus event so
diff --git a/src/home-confirm-card.js b/src/home-confirm-card.js
new file mode 100644
index 000000000..17877c798
--- /dev/null
+++ b/src/home-confirm-card.js
@@ -0,0 +1,251 @@
+/**
+ * The confirmation card: the one place a person says yes to a physical action.
+ *
+ * When the agent asks to unlock a door, open a garage, or disarm an alarm, the
+ * server does not do it. It freezes the action, mints a confirmation, and hands
+ * the browser a `home_tool` event with `status: 'pending_confirmation'`. This
+ * module renders that as a card with the sentence the SERVER composed, a live
+ * countdown, and one button.
+ *
+ * Three product decisions live in here, and each one is deliberate:
+ *
+ * 1. **The card shows the server's sentence, never the model's.** The summary
+ * comes from the confirmation record, which was composed from the resolved
+ * entities before any of this reached a browser. A model that has been
+ * talked into something cannot change what the person is asked.
+ * 2. **The button sends an id and nothing else.** The action is already frozen
+ * server-side. There is no form here, because there is nothing about the
+ * action for a client to decide.
+ * 3. **The countdown is real.** Ninety seconds is the whole lifetime of a
+ * confirmation, and a card that silently goes dead is worse than one that
+ * says so. At zero the card retires itself and tells the person to ask
+ * again.
+ *
+ * Usage from any chat surface:
+ *
+ * import { renderHomeConfirmation } from './home-confirm-card.js';
+ * if (evt.type === 'home_tool' && evt.status === 'pending_confirmation') {
+ * renderHomeConfirmation(logEl, evt.data, { onResolved: (r) => … });
+ * }
+ */
+
+let stylesInjected = false;
+
+/**
+ * Mount a confirmation card.
+ *
+ * @param {HTMLElement} container where to append it
+ * @param {object} payload the `data` of a `home_tool` SSE event
+ * @param {{ onResolved?: (result: object) => void }} [options]
+ * @returns {HTMLElement|null} the card, or null when the payload is not pending
+ */
+export function renderHomeConfirmation(container, payload, options = {}) {
+ const pending = payload?.confirmation;
+ const homeId = payload?.home?.id;
+ if (!container || !pending?.id || !homeId) return null;
+
+ injectStyles();
+
+ const card = document.createElement('div');
+ card.className = 'home-confirm';
+ card.setAttribute('role', 'group');
+ card.setAttribute('aria-label', 'Home action awaiting your approval');
+
+ const risk = pending.risk === 'security' ? 'Security' : 'Physical';
+ card.innerHTML = `
+ <div class="home-confirm-head">
+ <span class="home-confirm-badge" data-risk="${escapeAttr(pending.risk || 'physical')}">${escapeHtml(risk)}</span>
+ <span class="home-confirm-title">Needs your approval</span>
+ <span class="home-confirm-clock" aria-live="off"></span>
+ </div>
+ <p class="home-confirm-summary"></p>
+ <ul class="home-confirm-entities"></ul>
+ <div class="home-confirm-actions">
+ <button type="button" class="home-confirm-yes">Yes, ${escapeHtml(verbOf(pending))}</button>
+ <button type="button" class="home-confirm-no">Not now</button>
+ </div>
+ <p class="home-confirm-status" role="status" aria-live="polite"></p>
+ `;
+
+ // textContent, not innerHTML: the summary is server-composed but it embeds
+ // device names, and a device name is a string a stranger can write.
+ card.querySelector('.home-confirm-summary').textContent = pending.summary || 'This will change something in your home.';
+
+ const list = card.querySelector('.home-confirm-entities');
+ for (const entity of pending.entities || []) {
+ const li = document.createElement('li');
+ li.textContent = entity.name || entity.entity_id;
+ li.title = entity.entity_id;
+ list.appendChild(li);
+ }
+ if (!list.childElementCount) list.remove();
+
+ const clock = card.querySelector('.home-confirm-clock');
+ const status = card.querySelector('.home-confirm-status');
+ const yes = card.querySelector('.home-confirm-yes');
+ const no = card.querySelector('.home-confirm-no');
+
+ const expiresAt = pending.expires_at ? Date.parse(pending.expires_at) : Date.now() + (pending.expires_in_seconds || 90) * 1000;
+ let timer = null;
+
+ function retire(message, tone) {
+ if (timer) clearInterval(timer);
+ timer = null;
+ yes.disabled = true;
+ no.disabled = true;
+ clock.textContent = '';
+ card.dataset.state = tone;
+ status.textContent = message;
+ }
+
+ function tick() {
+ const left = Math.max(0, Math.round((expiresAt - Date.now()) / 1000));
+ clock.textContent = `${left}s`;
+ card.classList.toggle('is-urgent', left <= 15);
+ if (left === 0) retire('This expired. Ask again if you still want it.', 'expired');
+ }
+ tick();
+ timer = setInterval(tick, 1000);
+
+ no.addEventListener('click', () => {
+ retire('Left alone. Nothing changed in your home.', 'declined');
+ options.onResolved?.({ ok: false, declined: true, confirmation_id: pending.id });
+ });
+
+ yes.addEventListener('click', async () => {
+ yes.disabled = true;
+ no.disabled = true;
+ status.textContent = 'Sending…';
+ try {
+ const result = await approveHomeConfirmation(homeId, pending.id);
+ retire(result.message, result.ok ? 'done' : 'failed');
+ options.onResolved?.(result);
+ } catch (err) {
+ retire(err.message || 'Could not reach three.ws.', 'failed');
+ options.onResolved?.({ ok: false, message: err.message });
+ }
+ });
+
+ container.appendChild(card);
+ if (typeof container.scrollTo === 'function') container.scrollTop = container.scrollHeight;
+ return card;
+}
+
+/**
+ * Redeem a confirmation. Session cookie plus a one-time CSRF token, which is the
+ * only credential this endpoint accepts: a bearer token, including one holding
+ * `home:act`, is refused server-side by design.
+ *
+ * @param {string} homeId
+ * @param {string} confirmationId
+ * @returns {Promise<{ ok: boolean, message: string, ran?: string }>}
+ */
+export async function approveHomeConfirmation(homeId, confirmationId) {
+ const csrf = await fetchCsrfToken();
+ const res = await fetch(`/api/home/${encodeURIComponent(homeId)}/confirm`, {
+ method: 'POST',
+ credentials: 'include',
+ headers: { 'content-type': 'application/json', ...(csrf ? { 'x-csrf-token': csrf } : {}) },
+ body: JSON.stringify({ confirmation_id: confirmationId }),
+ });
+ const body = await res.json().catch(() => ({}));
+ if (!res.ok) {
+ return {
+ ok: false,
+ message: body.error_description || body.message || `That did not go through (${res.status}).`,
+ code: body.error || null,
+ };
+ }
+ return { ok: true, message: 'Done.', ran: body.ran, confirmation_id: confirmationId };
+}
+
+async function fetchCsrfToken() {
+ try {
+ const res = await fetch('/api/csrf-token', { credentials: 'include' });
+ if (!res.ok) return null;
+ const body = await res.json();
+ return body.data?.token || body.token || null;
+ } catch {
+ return null;
+ }
+}
+
+function verbOf(pending) {
+ const service = String(pending.service || '');
+ if (service.includes('unlock')) return 'unlock';
+ if (service.includes('disarm')) return 'disarm';
+ if (service.includes('open')) return 'open';
+ if (service.includes('position')) return 'move it';
+ return 'do it';
+}
+
+function escapeHtml(value) {
+ return String(value ?? '').replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' })[c]);
+}
+
+function escapeAttr(value) {
+ return escapeHtml(value).replace(/\s+/g, '-');
+}
+
+function injectStyles() {
+ if (stylesInjected || typeof document === 'undefined') return;
+ stylesInjected = true;
+ const style = document.createElement('style');
+ style.id = 'home-confirm-styles';
+ style.textContent = `
+.home-confirm {
+ border: 1px solid var(--color-border-strong, rgba(255,255,255,.22));
+ border-left: 3px solid var(--color-warning, #f5a524);
+ border-radius: var(--radius-md, 10px);
+ background: var(--color-surface, rgba(255,255,255,.04));
+ padding: var(--space-md, 1rem);
+ margin: var(--space-sm, .618rem) 0;
+ display: grid;
+ gap: var(--space-xs, .382rem);
+ max-width: 100%;
+ animation: home-confirm-in .22s ease-out;
+}
+@media (prefers-reduced-motion: reduce) { .home-confirm { animation: none; } }
+@keyframes home-confirm-in { from { opacity: 0; transform: translateY(6px); } to { opacity: 1; transform: none; } }
+.home-confirm[data-state="done"] { border-left-color: var(--color-success, #2ecc71); }
+.home-confirm[data-state="failed"] { border-left-color: var(--color-danger, #ff5c5c); }
+.home-confirm[data-state="expired"], .home-confirm[data-state="declined"] { border-left-color: var(--color-border, rgba(255,255,255,.18)); opacity: .72; }
+.home-confirm-head { display: flex; align-items: center; gap: var(--space-xs, .382rem); }
+.home-confirm-badge {
+ font-size: var(--text-2xs, .6875rem);
+ text-transform: uppercase;
+ letter-spacing: .06em;
+ padding: 2px 7px;
+ border-radius: var(--radius-pill, 999px);
+ background: color-mix(in srgb, var(--color-warning, #f5a524) 20%, transparent);
+ color: var(--color-warning, #f5a524);
+}
+.home-confirm-badge[data-risk="security"] { background: color-mix(in srgb, var(--color-danger, #ff5c5c) 18%, transparent); color: var(--color-danger, #ff5c5c); }
+.home-confirm-title { font-size: var(--text-md, .8125rem); font-weight: var(--weight-semibold, 600); color: var(--color-text-bright, #fff); }
+.home-confirm-clock { margin-left: auto; font-variant-numeric: tabular-nums; font-size: var(--text-sm, .764rem); color: var(--color-text-dim, rgba(255,255,255,.6)); }
+.home-confirm.is-urgent .home-confirm-clock { color: var(--color-danger, #ff5c5c); }
+.home-confirm-summary { margin: 0; font-size: var(--text-ui, .875rem); line-height: var(--leading-normal, 1.618); color: var(--color-text, rgba(255,255,255,.86)); }
+.home-confirm-entities { margin: 0; padding-left: 1.1em; font-size: var(--text-sm, .764rem); color: var(--color-text-dim, rgba(255,255,255,.6)); }
+.home-confirm-actions { display: flex; flex-wrap: wrap; gap: var(--space-xs, .382rem); margin-top: var(--space-2xs, .236rem); }
+.home-confirm-actions button {
+ font: inherit;
+ font-size: var(--text-md, .8125rem);
+ padding: .45em 1em;
+ border-radius: var(--radius-sm, 6px);
+ border: 1px solid var(--color-border, rgba(255,255,255,.18));
+ background: transparent;
+ color: var(--color-text, rgba(255,255,255,.86));
+ cursor: pointer;
+ transition: background .15s ease, border-color .15s ease, transform .1s ease;
+}
+.home-confirm-yes { background: var(--color-accent, #4f8cff); border-color: transparent; color: #05070d; font-weight: var(--weight-semibold, 600); }
+.home-confirm-actions button:hover:not(:disabled) { transform: translateY(-1px); }
+.home-confirm-no:hover:not(:disabled) { background: var(--color-surface-2, rgba(255,255,255,.08)); border-color: var(--color-border-strong, rgba(255,255,255,.28)); }
+.home-confirm-actions button:active:not(:disabled) { transform: translateY(0); }
+.home-confirm-actions button:focus-visible { outline: 2px solid var(--color-accent, #4f8cff); outline-offset: 2px; }
+.home-confirm-actions button:disabled { opacity: .5; cursor: default; }
+.home-confirm-status:empty { display: none; }
+.home-confirm-status { margin: 0; font-size: var(--text-sm, .764rem); color: var(--color-text-dim, rgba(255,255,255,.6)); }
+`;
+ document.head.appendChild(style);
+}
diff --git a/src/home/api.js b/src/home/api.js
index bbc624af0..53adc8e54 100644
--- a/src/home/api.js
+++ b/src/home/api.js
@@ -153,3 +153,28 @@ function parse(data) {
return null;
}
}
+
+/**
+ * What this account's plan covers, what it is using, and when it resets.
+ *
+ * Every dimension comes back whether or not it is near its ceiling: a quota you
+ * only learn about at the moment it refuses you is a quota that was never shown.
+ */
+export function getPlan(signal) {
+ return request('/api/home/plan', { signal });
+}
+
+/**
+ * Pause a home to make room for another one, or bring a paused one back.
+ *
+ * Pausing is never a disconnect. The row, the stored credential and the action
+ * log are all untouched, and a paused home still answers safety actions:
+ * locking up, closing a garage or valve and arming an alarm are never refused by
+ * a plan.
+ *
+ * @param {'pause'|'resume'|'preview'} action
+ * @param {string} [homeId]
+ */
+export function changePlanState(action, homeId) {
+ return request('/api/home/plan', { method: 'POST', body: { action, home_id: homeId } });
+}
diff --git a/src/home/connect.js b/src/home/connect.js
index 0bb1a2d19..f41d27f31 100644
--- a/src/home/connect.js
+++ b/src/home/connect.js
@@ -22,7 +22,11 @@
* a physical actuator on the other end.
*/
-import { isPrivateHost, normalizeBaseUrl } from '@three-ws/home-bridge';
+// The `/url` subpath, not the package root: url.js is pure string handling, and
+// importing it directly keeps the Home Assistant WebSocket client and the MCP
+// SDK (both behind the root export) out of this page's bundle. The same
+// functions the server validates with, so the two cannot disagree.
+import { isPrivateHost, normalizeBaseUrl } from '@three-ws/home-bridge/url';
import { renderManage } from './manage.js';
@@ -39,6 +43,14 @@ export const STATE = Object.freeze({
DEGRADED: 'degraded',
REVOKED: 'revoked',
MANY: 'many',
+ /**
+ * Not in the original eleven: the plan ceiling. It surfaced the first time a
+ * second house was connected on a free account, and it needs its own
+ * treatment because the recovery is commercial, not technical: sending
+ * someone back to re-check a URL that was never wrong is the worst possible
+ * answer to "you have run out of homes".
+ */
+ QUOTA_REACHED: 'quota_reached',
});
/** Where Home Assistant hides the token minting screen. Never make anyone hunt. */
@@ -88,6 +100,7 @@ function render(state, data = {}) {
case STATE.AUTH_FAILED: return root.append(connectCard(data));
case STATE.UNREACHABLE: return root.append(connectCard(data));
case STATE.REVOKED: return root.append(connectCard(data));
+ case STATE.QUOTA_REACHED: return root.append(quotaCard(data));
case STATE.CONNECTED:
case STATE.DEGRADED:
case STATE.MANY:
@@ -211,6 +224,27 @@ function connectCard({ notice, values = {}, focus } = {}) {
return panel;
}
+/**
+ * The plan ceiling. No form: re-submitting the same house would hit the same
+ * wall, so the card offers only the two actions that actually change the answer.
+ */
+function quotaCard({ notice, upgrade } = {}) {
+ const panel = el('section', 'hm-panel');
+ panel.append(el('h2', 'hm-panel-title', 'This account is at its home limit'));
+ if (notice) panel.append(noticeEl(notice));
+
+ const actions = el('div', 'hm-actions');
+ const up = el('a', 'hm-btn hm-btn-primary', 'See the plans');
+ up.href = typeof upgrade === 'string' && upgrade.startsWith('/') ? upgrade : '/pricing';
+ const back = el('button', 'hm-btn hm-btn-ghost', 'Back to my homes');
+ back.type = 'button';
+ back.addEventListener('click', () => boot());
+ actions.append(up, back);
+ panel.append(actions);
+ queueMicrotask(() => up.focus());
+ return panel;
+}
+
/** Where to get a token, inline, so nobody has to go and search for it. */
function tokenHelp() {
const wrap = el('details', 'hm-panel');
@@ -374,6 +408,25 @@ function renderFailure(err, values) {
});
}
+ // A plan ceiling is not a failure of the address or the token, so it must not
+ // send the user back to re-check either. It is a decision with a price on it,
+ // and the only useful next action is the upgrade or disconnecting a house.
+ if (err?.quota) {
+ return render(STATE.QUOTA_REACHED, {
+ values: carried,
+ notice: {
+ tone: 'warn',
+ title: quotaTitle(err.quota),
+ body: messageOf(err),
+ bullets: [
+ 'Disconnect a home you no longer use and this one will connect.',
+ 'Or move to a plan that carries more homes.',
+ ],
+ },
+ upgrade: err.quota.upgrade || '/pricing',
+ });
+ }
+
return render(STATE.EMPTY, {
values: carried,
focus: 'url',
@@ -381,6 +434,12 @@ function renderFailure(err, values) {
});
}
+function quotaTitle(quota) {
+ const limit = Number(quota?.limit);
+ if (!Number.isFinite(limit)) return 'Your plan is at its limit for homes.';
+ return `Your plan covers ${limit} ${limit === 1 ? 'home' : 'homes'}.`;
+}
+
function showConnectCard(notice) {
render(STATE.EMPTY, notice ? { notice } : {});
}
@@ -516,6 +575,10 @@ function apiError(body, res) {
const err = new Error(body?.message || body?.error_description || body?.error || `Request failed (${res.status}).`);
err.code = body?.code || (res.status === 404 ? 'not_found' : 'call_failed');
err.status = res.status;
+ // A plan limit answers with a `quota` block naming the dimension, the ceiling
+ // and where to lift it. Carrying it here is what lets the card offer the
+ // upgrade instead of a dead end.
+ if (body?.quota) err.quota = body.quota;
return err;
}
diff --git a/src/home/manage.js b/src/home/manage.js
index a0fab995d..97952ab10 100644
--- a/src/home/manage.js
+++ b/src/home/manage.js
@@ -29,10 +29,19 @@ export function renderManage({ homes, notice, onDisconnect, onReconnect }) {
);
head.append(heading);
+ const headActions = el('div', 'hm-card-actions');
+ // The plan surface, reachable from the place a person is when they wonder how
+ // many of these they are allowed. A limit that can only be found after it
+ // refuses you was never shown to you.
+ const plan = el('a', 'hm-btn hm-btn-ghost', 'Plan and usage');
+ plan.href = '/smart-home/plan';
+ headActions.append(plan);
+
const add = el('button', 'hm-btn hm-btn-ghost', 'Connect another');
add.type = 'button';
add.addEventListener('click', () => onReconnect && onReconnect());
- head.append(add);
+ headActions.append(add);
+ head.append(headActions);
panel.append(head);
const list = el('ul', 'hm-list');
@@ -116,7 +125,7 @@ function grantRow(home, grant, rerender) {
revoke.disabled = true;
revoke.textContent = 'Revoking';
try {
- await sendJson(`/api/home/${encodeURIComponent(home.id)}/grants/${encodeURIComponent(grant.entity_id)}`, 'DELETE');
+ await sendJson(`/api/home/${encodeURIComponent(home.id)}/grants?entity_id=${encodeURIComponent(grant.entity_id)}`, 'DELETE');
rerender();
} catch (err) {
revoke.disabled = false;
diff --git a/src/home/scene-model.js b/src/home/scene-model.js
index 901ce3318..163b7f35c 100644
--- a/src/home/scene-model.js
+++ b/src/home/scene-model.js
@@ -181,17 +181,24 @@ export function lightOf(room) {
* Warm or cool, from the room's own measured temperature. Neutral below the
* comfort band's width so an ordinary room is not permanently tinted.
*/
-export function climateOf(room) {
+export function climateOf(room, unit = null) {
const climate = room.climate;
if (!climate || !Number.isFinite(climate.temperature)) return null;
const t = climate.temperature;
- const offset = clamp(-1, 1, (t - 21) / 6);
+ // The comfort band is centred where the house measures it. Home Assistant
+ // reports whatever unit the instance is configured in, so a Fahrenheit house
+ // must not read as permanently freezing because 70 is nowhere near 21.
+ const fahrenheit = String(unit || '').includes('F');
+ const centre = fahrenheit ? 70 : 21;
+ const span = fahrenheit ? 11 : 6;
+ const offset = clamp(-1, 1, (t - centre) / span);
return {
temperature: t,
sources: climate.sources,
+ unit: unit || null,
// -1 fully cool, +1 fully warm. The renderer and the 2D card both read it.
tint: Number(offset.toFixed(3)),
- label: `${t.toFixed(1)}°`,
+ label: `${t.toFixed(1)}${unit || '°'}`,
};
}
@@ -244,7 +251,7 @@ export function buildSceneModel(graph, options = {}) {
// The rollups a real area gets, applied to the bucket nobody filed.
// Same functions the graph builder uses, so one shape flows through.
lighting: summarizeLighting(unassigned),
- climate: summarizeClimate(unassigned),
+ climate: summarizeClimate(unassigned, source.temperatureUnit || null),
secured: summarizeSecurity(unassigned),
});
}
@@ -258,7 +265,7 @@ export function buildSceneModel(graph, options = {}) {
const cell = cells[index];
const x = Number.isFinite(authored?.x) ? authored.x : cell.x * CELL;
const z = Number.isFinite(authored?.z) ? authored.z : cell.z * CELL;
- placed.push(buildRoom(room, floor, { x, z, w: authored?.w, d: authored?.d }));
+ placed.push(buildRoom(room, { ...floor, temperatureUnit: source.temperatureUnit || null }, { x, z, w: authored?.w, d: authored?.d }));
});
}
@@ -329,7 +336,10 @@ function lowestFloor(floors) {
* screen is, and a house read from a 3/4 camera reads better in rows.
*/
export function packCells(n) {
- const cols = Math.max(1, Math.ceil(Math.sqrt(n * 1.35)));
+ // Never wider than there are rooms: the 1.35 bias makes a grid landscape,
+ // but applied to a single-room house it produced a two-column grid with one
+ // room sitting half a cell off centre.
+ const cols = Math.max(1, Math.min(n, Math.ceil(Math.sqrt(n * 1.35))));
const rows = Math.max(1, Math.ceil(n / cols));
const out = [];
for (let i = 0; i < n; i += 1) {
@@ -381,7 +391,7 @@ function buildRoom(room, floor, cell) {
d,
h: WALL_HEIGHT,
light: lightOf(room),
- climate: climateOf(room),
+ climate: climateOf(room, floor.temperatureUnit),
security: secured
? { ...secured, unlocked: secured.unlocked || [], open: secured.open || [] }
: null,
diff --git a/src/home/scene-render.js b/src/home/scene-render.js
index 5661e0d71..02772be88 100644
--- a/src/home/scene-render.js
+++ b/src/home/scene-render.js
@@ -46,6 +46,7 @@ import {
WebGLRenderer,
} from 'three';
import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
+import { mergeGeometries } from 'three/addons/utils/BufferGeometryUtils.js';
import { createFrameGovernor, FPS_ACTIVE, FPS_IDLE, FPS_SAVER, getPowerSaver, onPowerSaverChange, trackWindowFocus } from '../shared/frame-governor.js';
import { diffScene } from './scene-model.js';
@@ -84,6 +85,34 @@ function sharedGeometry() {
};
}
+/** The four waist-high walls of a room, as one geometry. */
+function roomShell(w, d) {
+ const h = 0.92;
+ const parts = [];
+ for (const [sx, sz, px, pz] of [
+ [w, 0.06, 0, -d / 2],
+ [w, 0.06, 0, d / 2],
+ [0.06, d, -w / 2, 0],
+ [0.06, d, w / 2, 0],
+ ]) {
+ const box = new BoxGeometry(sx, h, sz);
+ box.translate(px, h / 2, pz);
+ parts.push(box);
+ }
+ const merged = mergeGeometries(parts, false);
+ for (const part of parts) part.dispose();
+ return merged;
+}
+
+/** The "this device is not answering" marker, built only when one is. */
+function addMissingMarker(node) {
+ const marker = new Sprite(new SpriteMaterial({ color: 0xe05a4a, transparent: true, opacity: 0, depthWrite: false, depthTest: false }));
+ marker.scale.set(0.34, 0.34, 1);
+ marker.position.y = 0.42;
+ node.add(marker);
+ return marker;
+}
+
/**
* @param {HTMLElement} container
* @param {object} [options]
@@ -126,7 +155,7 @@ export function createHomeScene(container, options = {}) {
const objects = new Map();
/** @type {Map<string, object>} roomId to its live room record */
const rooms = new Map();
- const spare = { color: new Color(), target: new Color(), v: new Vector3() };
+ const spare = { color: new Color(), target: new Color(), v: new Vector3(), toward: new Vector3(), forward: new Vector3() };
let model = null;
let stale = false;
@@ -140,6 +169,11 @@ export function createHomeScene(container, options = {}) {
let frames = 0;
let fpsWindowStart = 0;
let fps = 0;
+ // Split on purpose. Under a software rasterizer (headless CI, a locked-down
+ // browser) `render` dominates and says nothing about the scene's own cost, so
+ // the update work is timed separately and both numbers are reported.
+ let updateMs = 0;
+ let renderMs = 0;
const raycaster = new Raycaster();
const pointer = new Vector2();
@@ -233,19 +267,14 @@ export function createHomeScene(container, options = {}) {
// Waist-high walls, translucent. Full-height walls would hide the room's
// contents from every angle an orbiting camera can reach, and a dollhouse
// you cannot see into is a box.
+ //
+ // All four are ONE geometry. As separate meshes they were four draw calls
+ // per room, which is four hundred in a hundred-room house for a shape that
+ // never moves relative to its room.
const wallMat = new MeshStandardMaterial({ color: WALL, roughness: 0.75, metalness: 0.05, transparent: true, opacity: 0.34 });
- const h = 0.92;
- for (const [sx, sz, px, pz] of [
- [room.w, 0.06, 0, -room.d / 2],
- [room.w, 0.06, 0, room.d / 2],
- [0.06, room.d, -room.w / 2, 0],
- [0.06, room.d, room.w / 2, 0],
- ]) {
- const wall = new Mesh(geo.panel, wallMat);
- wall.scale.set(sx, h, sz);
- wall.position.set(px, h / 2, pz);
- group.add(wall);
- }
+ const wallGeo = roomShell(room.w, room.d);
+ const walls = new Mesh(wallGeo, wallMat);
+ group.add(walls);
// The security tell: a line around the room's foot that goes amber the
// moment something in it is unlocked or open. Readable from across the
@@ -274,6 +303,7 @@ export function createHomeScene(container, options = {}) {
edgeMat,
light: usesLight ? light : null,
label,
+ wallGeo,
labelText: '',
color: new Color(room.light.hex),
targetColor: new Color(room.light.hex),
@@ -432,15 +462,6 @@ export function createHomeScene(container, options = {}) {
}
}
- // A device Home Assistant cannot reach is drawn, never omitted: a thing
- // that vanished from a house is information, and hiding it is how a scene
- // tells a comfortable lie.
- const missing = new Sprite(new SpriteMaterial({ color: 0xe05a4a, transparent: true, opacity: 0, depthWrite: false, depthTest: false }));
- missing.scale.set(0.34, 0.34, 1);
- missing.position.y = 0.42;
- node.add(missing);
- record.missing = missing;
-
commitObject(record);
return record;
}
@@ -538,6 +559,11 @@ export function createHomeScene(container, options = {}) {
// is off" and "the lamp is gone" can never look the same.
record.material.opacity = 0.24 + available * 0.76;
for (const part of record.parts) part.opacity = 0.3 + available * 0.7;
+ // A device Home Assistant cannot reach is drawn, never omitted: a thing
+ // that vanished from a house is information, and hiding it is how a scene
+ // tells a comfortable lie. The marker is built the first time a device
+ // actually goes missing, so a healthy house pays nothing for it.
+ if (available < 0.999 && !record.missing) record.missing = addMissingMarker(record.node);
if (record.missing) record.missing.material.opacity = (1 - available) * 0.9;
record.node.scale.setScalar(1 + record.select * 0.18);
}
@@ -564,6 +590,7 @@ export function createHomeScene(container, options = {}) {
const dt = last ? Math.min(0.1, (now - last) / 1000) : 0.016;
last = now;
+ const updateStart = performance.now();
const staleTarget = stale ? 1 : 0;
staleMoving = Math.abs(staleAmount - staleTarget) > 0.002;
staleAmount = damp(staleAmount, staleTarget, dt);
@@ -602,7 +629,10 @@ export function createHomeScene(container, options = {}) {
if (agent) agent.update(dt, now);
controls.update();
+ const renderStart = performance.now();
+ updateMs = renderStart - updateStart;
renderer.render(scene, camera);
+ renderMs = performance.now() - renderStart;
frames += 1;
if (!fpsWindowStart) fpsWindowStart = now;
@@ -744,6 +774,7 @@ export function createHomeScene(container, options = {}) {
for (const record of rooms.values()) {
record.floorMat.dispose();
record.wallMat.dispose();
+ record.wallGeo.dispose();
record.edgeMat.dispose();
record.label.material.map?.dispose();
record.label.material.dispose();
@@ -768,9 +799,32 @@ export function createHomeScene(container, options = {}) {
if (next?.roomId) agent?.moveToRoom(rooms.get(next.roomId)?.source);
agent?.act();
},
+ /**
+ * Where an entity currently sits on screen, so the confirmation can be
+ * pinned to the door it would open rather than to a corner of the page.
+ * @returns {{ x: number, y: number, visible: boolean }|null}
+ */
+ project(entityId) {
+ const record = objects.get(entityId);
+ if (!record) return null;
+ record.node.getWorldPosition(spare.v);
+ spare.v.y += 0.5;
+ spare.toward.copy(spare.v).sub(camera.position);
+ camera.getWorldDirection(spare.forward);
+ const behind = spare.toward.dot(spare.forward) <= 0;
+ spare.v.project(camera);
+ const rect = renderer.domElement.getBoundingClientRect();
+ return {
+ x: ((spare.v.x + 1) / 2) * rect.width,
+ y: ((1 - spare.v.y) / 2) * rect.height,
+ visible: !behind && Math.abs(spare.v.x) <= 1.05 && Math.abs(spare.v.y) <= 1.05,
+ };
+ },
stats() {
return {
fps,
+ updateMs: Math.round(updateMs * 100) / 100,
+ renderMs: Math.round(renderMs * 100) / 100,
objects: objects.size,
rooms: rooms.size,
drawCalls: renderer.info.render.calls,
diff --git a/src/home/scene.js b/src/home/scene.js
new file mode 100644
index 000000000..8f4750095
--- /dev/null
+++ b/src/home/scene.js
@@ -0,0 +1,894 @@
+/**
+ * /home/:id, the live 3D home.
+ *
+ * The page owns state, not geometry. It holds one SSE subscription to the
+ * house, turns every event into a scene model, hands that to whichever renderer
+ * this device can run, and renders the ten states a real house actually reaches
+ * (loading, empty, unfiled, live, stale, disconnected, acting, awaiting a human
+ * yes, no WebGL, broken) as designed screens rather than as a spinner and a
+ * stack trace.
+ *
+ * The one rule that outranks everything else here: the house never empties. A
+ * dropped socket greys the scene and shows its age. It does not clear it.
+ */
+
+import { HomeApiError, callService, getHome, grantEntity, openStream } from './api.js';
+import { buildSceneModel } from './scene-model.js';
+import { createHomeFallback, webglAvailable } from './scene-fallback.js';
+
+const VIEW_KEY = 'three:home:view';
+/** A device that cannot hold this for a few seconds is sent to the 2D house. */
+const MIN_FPS = 18;
+const FPS_GRACE_MS = 6000;
+
+const el = {
+ shell: document.getElementById('hs-shell'),
+ title: document.getElementById('hs-title'),
+ status: document.getElementById('hs-status'),
+ rooms: document.getElementById('hs-rooms'),
+ stage: document.getElementById('hs-stage'),
+ panel: document.getElementById('hs-panel'),
+ panelEmpty: document.getElementById('hs-panel-empty'),
+ inspector: document.getElementById('hs-inspector'),
+ live: document.getElementById('hs-live'),
+ view3d: document.getElementById('hs-view-3d'),
+ view2d: document.getElementById('hs-view-2d'),
+ reconnect: document.getElementById('hs-reconnect'),
+};
+
+const state = {
+ homeId: homeIdFromPath(),
+ home: null,
+ graph: null,
+ model: null,
+ view: preferredView(),
+ renderer: null,
+ stream: null,
+ status: 'connecting',
+ stale: false,
+ lastGraphAt: 0,
+ selected: null,
+ pending: null,
+ busy: new Set(),
+ log: [],
+ // Latency instrumentation: the wall time from an SSE frame landing to the
+ // first painted frame that carries it. Reported on window for the
+ // measurement pass and for the e2e spec.
+ latency: { last: null, samples: [] },
+ overlay: null,
+ fpsSince: 0,
+ // True once a person picked a view, by clicking the toggle or by asking for
+ // one in the URL. An explicit choice is never overridden by the frame-rate
+ // watchdog: measuring a slow device is a reason to offer the flat house, not
+ // a reason to overrule someone who asked for the 3D one.
+ viewChosen: new URLSearchParams(location.search).has('view'),
+};
+
+window.__homeScene = {
+ get model() {
+ return state.model;
+ },
+ get latency() {
+ return state.latency;
+ },
+ get status() {
+ return { status: state.status, stale: state.stale, view: state.view };
+ },
+ stats() {
+ return state.renderer?.stats?.() || null;
+ },
+};
+
+boot();
+
+async function boot() {
+ if (!state.homeId) {
+ showOverlay({
+ title: 'No home in that link',
+ body: 'A home scene needs a home id, as in /home/<id>. Open one from your list of connected homes.',
+ actions: [{ label: 'Your homes', href: '/home', primary: true }],
+ });
+ return;
+ }
+ el.view3d.addEventListener('click', () => {
+ state.viewChosen = true;
+ setView('3d', { remember: true });
+ });
+ el.view2d.addEventListener('click', () => {
+ state.viewChosen = true;
+ setView('2d', { remember: true });
+ });
+ el.reconnect.addEventListener('click', () => reconnect());
+ document.addEventListener('keydown', onKeydown);
+
+ await load();
+}
+
+async function load() {
+ setStatus('connecting', 'Connecting');
+ try {
+ const payload = await getHome(state.homeId);
+ state.home = payload.home || null;
+ el.title.textContent = state.home?.label || 'Your home';
+ document.title = `${state.home?.label || 'Your home'} · three.ws`;
+ mountRenderer();
+ if (payload.graph) {
+ applyGraph(payload.graph, { stale: Boolean(payload.stale) });
+ setStatusFromServer({ status: payload.live_status, stale: payload.stale, detail: payload.error?.message });
+ } else if (payload.error) {
+ // A 200 carrying a coded failure: the connection record exists, the house
+ // did not answer. That is a designed screen, not an exception.
+ renderFailure(new HomeApiError(payload.error.code, payload.error.message));
+ return;
+ }
+ subscribe();
+ } catch (err) {
+ renderFailure(err);
+ }
+}
+
+// ── the stream ───────────────────────────────────────────────────────────────
+
+function subscribe() {
+ state.stream?.close();
+ state.stream = openStream(state.homeId, {
+ onOpen() {
+ setStatus('live', 'Live');
+ },
+ onGraph(payload) {
+ const receivedAt = performance.now();
+ applyGraph(payload.graph, { stale: Boolean(payload.stale), receivedAt });
+ if (payload.stale) setStatusFromServer(payload);
+ },
+ onStatus(payload) {
+ setStatusFromServer(payload);
+ },
+ onSilence() {
+ // A stream that stopped delivering without closing. Treat it as a
+ // disconnect rather than as a very quiet house.
+ setStatusFromServer({ status: 'disconnected', stale: true, detail: 'The live stream went quiet.' });
+ },
+ });
+}
+
+function reconnect() {
+ el.reconnect.disabled = true;
+ setStatus('connecting', 'Connecting');
+ load().finally(() => {
+ el.reconnect.disabled = false;
+ });
+}
+
+function setStatusFromServer(payload) {
+ const status = payload.status || 'live';
+ state.stale = Boolean(payload.stale);
+ if (status === 'disconnected' || status === 'unreachable' || status === 'auth_failed') {
+ setStatus('disconnected', status === 'auth_failed' ? 'Sign in again' : 'Disconnected', payload.detail || payload.statusDetail);
+ } else if (state.stale || status === 'reconnecting' || status === 'connecting') {
+ setStatus('stale', status === 'reconnecting' ? 'Reconnecting' : 'Stale', payload.detail || payload.statusDetail);
+ } else {
+ setStatus('live', 'Live');
+ }
+}
+
+function setStatus(kind, label, detail) {
+ state.status = kind;
+ el.status.dataset.status = kind;
+ el.status.textContent = label;
+ el.status.title = detail || '';
+ el.reconnect.hidden = kind !== 'disconnected';
+ const stale = kind === 'stale' || kind === 'disconnected';
+ state.stale = stale;
+ state.renderer?.setStale?.(stale);
+ el.stage.classList.toggle('is-stale', stale);
+ renderAge();
+ if (kind === 'disconnected') {
+ announce(detail || 'The connection to your home dropped. The house below is the last state we saw.');
+ }
+}
+
+// ── the model ────────────────────────────────────────────────────────────────
+
+function applyGraph(graph, { stale = false, receivedAt = 0 } = {}) {
+ if (!graph) return;
+ state.graph = graph;
+ state.lastGraphAt = Date.now();
+ state.stale = stale;
+ const model = buildSceneModel(graph, { focusRoomId: state.model?.focusRoomId });
+ state.model = model;
+ renderRooms(model);
+ renderInspector();
+ if (receivedAt) measureLatency(receivedAt);
+ if (!state.renderer) return;
+ state.renderer.setModel(model);
+ state.renderer.setStale?.(stale);
+ renderEmptyStates(model);
+ renderAge();
+ repositionConfirm();
+}
+
+/**
+ * How long a real device change takes to reach the screen: the SSE frame lands,
+ * the next painted frame carries it, and the difference is the number this
+ * order has to report. Measured, not estimated.
+ */
+function measureLatency(receivedAt) {
+ requestAnimationFrame(() => {
+ const ms = Math.round(performance.now() - receivedAt);
+ state.latency.last = ms;
+ state.latency.samples.push(ms);
+ // A ten-minute wall display must not grow an array forever.
+ if (state.latency.samples.length > 200) state.latency.samples.splice(0, 100);
+ });
+}
+
+// ── renderers ────────────────────────────────────────────────────────────────
+
+function mountRenderer() {
+ const want = state.view === '2d' || !webglAvailable() ? '2d' : '3d';
+ if (want === '2d' && state.view !== '2d') {
+ // Not a preference: this device genuinely cannot run WebGL, and it is
+ // told so rather than being shown a blank canvas.
+ announce('This browser cannot run WebGL, so your home is shown as a floor list you can still read and control.');
+ state.view = '2d';
+ }
+ setView(state.view, { remember: false, force: true });
+}
+
+function setView(view, { remember = true, force = false } = {}) {
+ if (view === '3d' && !webglAvailable()) {
+ announce('WebGL is unavailable in this browser, so the 2D house stays on.');
+ view = '2d';
+ }
+ if (!force && view === state.view && state.renderer) return;
+ state.view = view;
+ if (remember) {
+ try {
+ localStorage.setItem(VIEW_KEY, view);
+ } catch {
+ // A private window keeps the choice for this visit only.
+ }
+ }
+ el.view3d.setAttribute('aria-pressed', String(view === '3d'));
+ el.view2d.setAttribute('aria-pressed', String(view === '2d'));
+ el.view3d.disabled = !webglAvailable();
+ if (el.view3d.disabled) el.view3d.title = 'This browser cannot run WebGL.';
+
+ state.renderer?.dispose();
+ state.renderer = null;
+ clearStage();
+ el.stage.classList.toggle('is-flat', view === '2d');
+
+ if (view === '2d') {
+ state.renderer = createHomeFallback(el.stage, { onAct: act, onFocusRoom: focusRoom });
+ state.fpsSince = 0;
+ } else {
+ mount3d();
+ }
+ if (state.model) {
+ state.renderer.setModel(state.model);
+ state.renderer.setStale?.(state.stale);
+ renderEmptyStates(state.model);
+ }
+ renderAge();
+}
+
+async function mount3d() {
+ // The renderer pulls Three.js, the avatar loader and the clip library. A
+ // device that will never show it (or a visitor who prefers the flat house)
+ // must not pay for the bytes, so it is imported here and not at module load.
+ try {
+ const { createHomeScene } = await import('./scene-render.js');
+ if (state.view !== '3d') return;
+ state.renderer = createHomeScene(el.stage, {
+ onSelect: (entityId, object) => {
+ state.selected = entityId ? { entityId, object } : null;
+ renderInspector();
+ },
+ onFocusRoom: focusRoom,
+ onFirstFrame: () => {
+ state.fpsSince = performance.now();
+ startFpsWatch();
+ },
+ });
+ if (state.model) {
+ state.renderer.setModel(state.model);
+ state.renderer.setStale?.(state.stale);
+ }
+ } catch (err) {
+ announce('The 3D house could not start, so the 2D house is on instead.');
+ console.warn('[home] 3D renderer failed to start', err);
+ setView('2d', { remember: false, force: true });
+ }
+}
+
+/**
+ * If this device measurably cannot hold a usable frame rate, move it to the 2D
+ * house and say so. Measure, then route: never assume a class of device is too
+ * slow, and never leave someone watching a slideshow of their own kitchen.
+ */
+function startFpsWatch() {
+ const started = performance.now();
+ const timer = setInterval(() => {
+ if (state.view !== '3d' || !state.renderer) return clearInterval(timer);
+ const stats = state.renderer.stats?.();
+ if (!stats || !stats.fps) return;
+ if (performance.now() - started < FPS_GRACE_MS) return;
+ clearInterval(timer);
+ if (stats.fps >= MIN_FPS) return;
+ if (state.viewChosen) {
+ // They asked for this view. Say what the device is doing and leave it on.
+ announce(`This device is holding ${stats.fps} frames a second in the 3D house. The 2D button is faster if it feels heavy.`);
+ return;
+ }
+ announce(`This device held only ${stats.fps} frames a second, so your home switched to the 2D view. The 3D button turns it back on.`);
+ setView('2d', { remember: false, force: true });
+ }, 1000);
+}
+
+function clearStage() {
+ for (const node of [...el.stage.children]) {
+ if (node.classList?.contains('hs-overlay') || node.classList?.contains('hs-confirm') || node.classList?.contains('hs-age')) continue;
+ node.remove();
+ }
+}
+
+// ── the room rail ────────────────────────────────────────────────────────────
+
+function renderRooms(model) {
+ el.rooms.classList.remove('hs-skeleton');
+ el.rooms.removeAttribute('aria-busy');
+ el.rooms.innerHTML = '';
+ if (!model.rooms.length) {
+ const note = document.createElement('p');
+ note.className = 'hs-panel-empty';
+ note.textContent = 'No rooms yet.';
+ el.rooms.appendChild(note);
+ return;
+ }
+ for (const floor of model.floors) {
+ const section = document.createElement('section');
+ section.className = 'hs-floor';
+ if (model.floors.length > 1) {
+ const name = document.createElement('p');
+ name.className = 'hs-floor-name';
+ name.textContent = floor.name;
+ section.appendChild(name);
+ }
+ const list = document.createElement('ul');
+ list.className = 'hs-room-list';
+ for (const roomId of floor.roomIds) {
+ const room = model.rooms.find((r) => r.id === roomId);
+ if (!room) continue;
+ const item = document.createElement('li');
+ const button = document.createElement('button');
+ button.type = 'button';
+ button.className = 'hs-room';
+ button.setAttribute('aria-current', String(room.id === model.focusRoomId));
+ button.dataset.roomId = room.id;
+
+ const dot = document.createElement('span');
+ dot.className = 'hs-room-dot';
+ dot.style.setProperty('--room-dot', room.light.on ? room.light.hex : 'rgba(255,255,255,0.14)');
+ dot.style.setProperty('--room-halo', room.light.on ? `${Math.round(3 + room.light.brightness * 7)}px` : '0px');
+ button.appendChild(dot);
+
+ const name = document.createElement('span');
+ name.className = 'hs-room-name';
+ name.textContent = room.name;
+ button.appendChild(name);
+
+ const meta = document.createElement('span');
+ meta.className = 'hs-room-meta';
+ if (room.security && !room.security.secure) {
+ meta.classList.add('hs-room-alert');
+ meta.textContent = 'open';
+ } else if (room.climate) {
+ meta.textContent = room.climate.label;
+ } else {
+ meta.textContent = `${room.entityCount}`;
+ }
+ button.appendChild(meta);
+
+ button.addEventListener('click', () => focusRoom(room.id));
+ item.appendChild(button);
+ list.appendChild(item);
+ }
+ section.appendChild(list);
+ el.rooms.appendChild(section);
+ }
+}
+
+function focusRoom(roomId) {
+ if (!state.model) return;
+ state.model = { ...state.model, focusRoomId: roomId };
+ state.renderer?.focusRoom?.(roomId);
+ for (const button of el.rooms.querySelectorAll('.hs-room')) {
+ button.setAttribute('aria-current', String(button.dataset.roomId === roomId));
+ }
+}
+
+// ── inspector ────────────────────────────────────────────────────────────────
+
+function renderInspector() {
+ const selection = state.selected;
+ if (!selection) {
+ el.inspector.hidden = true;
+ el.panelEmpty.hidden = false;
+ renderLog();
+ return;
+ }
+ const object = findObject(selection.entityId) || selection.object;
+ if (!object) {
+ el.inspector.hidden = true;
+ el.panelEmpty.hidden = false;
+ return;
+ }
+ el.panelEmpty.hidden = true;
+ el.inspector.hidden = false;
+ el.inspector.innerHTML = '';
+
+ const name = document.createElement('h2');
+ name.className = 'hs-entity-name';
+ name.textContent = object.name;
+ el.inspector.appendChild(name);
+
+ const id = document.createElement('p');
+ id.className = 'hs-entity-id';
+ id.textContent = object.entityId;
+ el.inspector.appendChild(id);
+
+ const stateLine = document.createElement('p');
+ stateLine.className = 'hs-entity-state';
+ stateLine.textContent = object.available ? `Currently ${object.state}.` : 'Home Assistant cannot reach this device right now.';
+ el.inspector.appendChild(stateLine);
+
+ const attrs = describeAttributes(object);
+ if (attrs.length) {
+ const dl = document.createElement('dl');
+ dl.className = 'hs-entity-attrs';
+ for (const [key, value] of attrs) {
+ const dt = document.createElement('dt');
+ dt.textContent = key;
+ const dd = document.createElement('dd');
+ dd.textContent = value;
+ dl.append(dt, dd);
+ }
+ el.inspector.appendChild(dl);
+ }
+
+ const actions = actionsFor(object);
+ if (actions.length && object.available) {
+ const row = document.createElement('div');
+ row.className = 'hs-actions';
+ for (const action of actions) {
+ const button = document.createElement('button');
+ button.type = 'button';
+ button.className = action.risky ? 'hs-btn hs-btn--danger' : 'hs-btn';
+ button.textContent = state.busy.has(object.entityId) ? 'Working' : action.label;
+ button.disabled = state.busy.has(object.entityId);
+ button.addEventListener('click', () =>
+ act({ entityId: object.entityId, domain: action.domain, service: action.service, name: object.name, roomId: roomOf(object.entityId)?.id }),
+ );
+ row.appendChild(button);
+ }
+ el.inspector.appendChild(row);
+ }
+ renderLog();
+}
+
+function describeAttributes(object) {
+ const out = [];
+ const a = object.attributes || {};
+ if (Number.isFinite(Number(a.brightness))) out.push(['Brightness', `${Math.round((Number(a.brightness) / 255) * 100)}%`]);
+ if (Array.isArray(a.rgb_color)) out.push(['Colour', `rgb(${a.rgb_color.join(', ')})`]);
+ if (Number.isFinite(Number(a.current_position))) out.push(['Open', `${Number(a.current_position)}%`]);
+ if (Number.isFinite(Number(a.current_temperature))) out.push(['Now', `${a.current_temperature}°`]);
+ if (Number.isFinite(Number(a.temperature))) out.push(['Set to', `${a.temperature}°`]);
+ if (a.device_class) out.push(['Class', String(a.device_class)]);
+ if (a.media_title) out.push(['Playing', String(a.media_title)]);
+ return out.slice(0, 6);
+}
+
+function actionsFor(object) {
+ const on = object.activity > 0.02;
+ switch (object.domain) {
+ case 'light':
+ case 'switch':
+ case 'fan':
+ return [on
+ ? { domain: object.domain, service: 'turn_off', label: 'Turn off' }
+ : { domain: object.domain, service: 'turn_on', label: 'Turn on' }];
+ case 'lock':
+ return on
+ ? [{ domain: 'lock', service: 'lock', label: 'Lock' }]
+ : [{ domain: 'lock', service: 'unlock', label: 'Unlock', risky: true }];
+ case 'cover':
+ return on
+ ? [{ domain: 'cover', service: 'close_cover', label: 'Close' }]
+ : [{ domain: 'cover', service: 'open_cover', label: 'Open', risky: true }];
+ case 'media_player':
+ return [on ? { domain: 'media_player', service: 'media_pause', label: 'Pause' } : { domain: 'media_player', service: 'media_play', label: 'Play' }];
+ case 'vacuum':
+ return [on ? { domain: 'vacuum', service: 'return_to_base', label: 'Send home' } : { domain: 'vacuum', service: 'start', label: 'Start' }];
+ case 'alarm_control_panel':
+ return on
+ ? [{ domain: 'alarm_control_panel', service: 'alarm_disarm', label: 'Disarm', risky: true }]
+ : [{ domain: 'alarm_control_panel', service: 'alarm_arm_away', label: 'Arm' }];
+ default:
+ return [];
+ }
+}
+
+// ── acting ───────────────────────────────────────────────────────────────────
+
+async function act(request, { confirmed = false, remember = false } = {}) {
+ const room = request.roomId ? state.model?.rooms.find((r) => r.id === request.roomId) : roomOf(request.entityId);
+ state.busy.add(request.entityId);
+ state.renderer?.setBusy?.([...state.busy]);
+ state.renderer?.setActing?.({ roomId: room?.id || null, entityId: request.entityId });
+ renderInspector();
+
+ try {
+ if (confirmed && remember) {
+ await grantEntity(state.homeId, { entityId: request.entityId, expiresAt: null });
+ }
+ await callService(state.homeId, {
+ domain: request.domain,
+ service: request.service,
+ data: { entity_id: request.entityId },
+ confirmed,
+ });
+ dismissConfirm();
+ pushLog({ text: `${request.service.replace(/_/g, ' ')} ${request.name}`, outcome: 'ok' });
+ announce(`${request.name}: ${request.service.replace(/_/g, ' ')}.`);
+ } catch (err) {
+ if (err instanceof HomeApiError && err.code === 'needs_confirmation') {
+ // The gate fired. Ask, next to the thing it would move.
+ state.pending = { request, message: err.message, risk: err.pending?.risk || 'physical', entityId: err.pending?.entityId || request.entityId };
+ pushLog({ text: `${request.service.replace(/_/g, ' ')} ${request.name}`, outcome: 'refused' });
+ renderConfirm();
+ announce(err.message);
+ } else {
+ pushLog({ text: `${request.service.replace(/_/g, ' ')} ${request.name}`, outcome: 'failed' });
+ announce(err.message || 'That did not work.');
+ showToastError(err);
+ }
+ } finally {
+ state.busy.delete(request.entityId);
+ state.renderer?.setBusy?.([...state.busy]);
+ renderInspector();
+ }
+}
+
+/**
+ * The confirmation lives on top of the thing it would move, not in a toast in
+ * the corner. A person being asked "unlock the front door?" has to be able to
+ * see WHICH door without reading an entity id.
+ */
+function renderConfirm() {
+ dismissConfirm();
+ const pending = state.pending;
+ if (!pending) return;
+
+ const card = document.createElement('div');
+ card.className = 'hs-confirm';
+ card.setAttribute('role', 'alertdialog');
+ card.setAttribute('aria-modal', 'false');
+ card.setAttribute('aria-label', 'Confirm this action');
+
+ const risk = document.createElement('p');
+ risk.className = 'hs-confirm-risk';
+ risk.textContent = pending.risk === 'security' ? 'Opens your home' : 'Moves something physical';
+ card.appendChild(risk);
+
+ const text = document.createElement('p');
+ text.className = 'hs-confirm-text';
+ const object = findObject(pending.entityId);
+ text.textContent = `${pending.request.service.replace(/_/g, ' ')} ${object?.name || pending.request.name}?`;
+ card.appendChild(text);
+
+ const why = document.createElement('p');
+ why.className = 'hs-confirm-text';
+ why.style.color = 'var(--ink-dim)';
+ why.textContent = pending.message;
+ card.appendChild(why);
+
+ const row = document.createElement('div');
+ row.className = 'hs-confirm-row';
+ const yes = document.createElement('button');
+ yes.type = 'button';
+ yes.className = 'hs-btn hs-btn--primary';
+ yes.textContent = 'Yes, do it';
+ yes.addEventListener('click', () => {
+ const remember = card.querySelector('input')?.checked;
+ const request = pending.request;
+ state.pending = null;
+ act(request, { confirmed: true, remember });
+ });
+ const no = document.createElement('button');
+ no.type = 'button';
+ no.className = 'hs-btn';
+ no.textContent = 'Cancel';
+ no.addEventListener('click', () => {
+ state.pending = null;
+ dismissConfirm();
+ });
+ row.append(yes, no);
+ card.appendChild(row);
+
+ const rememberLabel = document.createElement('label');
+ rememberLabel.className = 'hs-confirm-remember';
+ const checkbox = document.createElement('input');
+ checkbox.type = 'checkbox';
+ rememberLabel.append(checkbox, document.createTextNode(`Do not ask again for ${object?.name || 'this device'}`));
+ card.appendChild(rememberLabel);
+
+ el.stage.appendChild(card);
+ state.confirmCard = card;
+ repositionConfirm();
+ yes.focus();
+}
+
+function repositionConfirm() {
+ const card = state.confirmCard;
+ if (!card || !state.pending) return;
+ const point = state.renderer?.project?.(state.pending.entityId);
+ const rect = el.stage.getBoundingClientRect();
+ if (point && point.visible) {
+ card.style.left = `${clamp(point.x, 150, rect.width - 150)}px`;
+ card.style.top = `${clamp(point.y - 18, 130, rect.height - 20)}px`;
+ } else {
+ // The 2D house and an off-screen object both anchor to the row instead.
+ const row = el.stage.querySelector(`[data-entity-id="${cssEscape(state.pending.entityId)}"]`);
+ if (row) {
+ const r = row.getBoundingClientRect();
+ card.style.left = `${clamp(r.left - rect.left + r.width / 2, 150, rect.width - 150)}px`;
+ card.style.top = `${clamp(r.top - rect.top + el.stage.scrollTop, 130, rect.height + el.stage.scrollTop)}px`;
+ } else {
+ card.style.left = '50%';
+ card.style.top = '50%';
+ }
+ }
+}
+
+function dismissConfirm() {
+ state.confirmCard?.remove();
+ state.confirmCard = null;
+}
+
+function onKeydown(event) {
+ if (event.key === 'Escape' && state.pending) {
+ state.pending = null;
+ dismissConfirm();
+ }
+}
+
+// ── the designed nothings ────────────────────────────────────────────────────
+
+function renderEmptyStates(model) {
+ if (model.empty) {
+ showOverlay({
+ title: 'Your home is connected, and empty',
+ body: 'Home Assistant answered, but it is not exposing any devices yet. Add an integration in Home Assistant (Settings, Devices and services), and this scene fills in as soon as the first device appears. Nothing else to do here.',
+ actions: [{ label: 'Add a device in Home Assistant', href: integrationsUrl(), external: true, primary: true }],
+ });
+ return;
+ }
+ if (model.needsLayout) {
+ showOverlay({
+ title: 'Nothing is in a room yet',
+ body: 'Every device in this house is unfiled, so they are all in one room below. Assign them to areas in Home Assistant (Settings, Areas and zones) or lay the house out here, and the scene splits into real rooms.',
+ actions: [
+ { label: 'Assign rooms in Home Assistant', href: areasUrl(), external: true, primary: true },
+ ],
+ dismissable: true,
+ });
+ return;
+ }
+ hideOverlay();
+}
+
+function showOverlay({ title, body, actions = [], dismissable = false }) {
+ hideOverlay();
+ const overlay = document.createElement('div');
+ overlay.className = 'hs-overlay';
+ const h = document.createElement('h2');
+ h.textContent = title;
+ const p = document.createElement('p');
+ p.textContent = body;
+ overlay.append(h, p);
+ const row = document.createElement('div');
+ row.className = 'hs-actions';
+ for (const action of actions) {
+ if (!action.href && !action.onClick) continue;
+ const node = action.href ? document.createElement('a') : document.createElement('button');
+ node.className = action.primary ? 'hs-btn hs-btn--primary' : 'hs-btn';
+ node.textContent = action.label;
+ if (action.href) {
+ node.href = action.href;
+ if (action.external) {
+ node.target = '_blank';
+ node.rel = 'noopener noreferrer';
+ }
+ } else {
+ node.type = 'button';
+ node.addEventListener('click', action.onClick);
+ }
+ row.appendChild(node);
+ }
+ if (dismissable) {
+ const close = document.createElement('button');
+ close.type = 'button';
+ close.className = 'hs-btn';
+ close.textContent = 'Show me the house anyway';
+ close.addEventListener('click', hideOverlay);
+ row.appendChild(close);
+ }
+ if (row.children.length) overlay.appendChild(row);
+ el.stage.appendChild(overlay);
+ state.overlay = overlay;
+}
+
+function hideOverlay() {
+ state.overlay?.remove();
+ state.overlay = null;
+}
+
+function renderFailure(err) {
+ const code = err instanceof HomeApiError ? err.code : 'call_failed';
+ const copy = {
+ unauthorized: {
+ title: 'Sign in to see this home',
+ body: 'A home belongs to the account that connected it. Sign in and this page opens straight onto your house.',
+ actions: [{ label: 'Sign in', href: `/login?next=${encodeURIComponent(location.pathname)}`, primary: true }],
+ },
+ not_found: {
+ title: 'That home is not here',
+ body: 'Either this home was removed, or it belongs to another account. Your connected homes are one click away.',
+ actions: [{ label: 'Your homes', href: '/home', primary: true }],
+ },
+ auth: {
+ title: 'Home Assistant rejected the token',
+ body: 'The long-lived access token this home was connected with no longer works. Create a new one in Home Assistant (your profile, Security) and reconnect.',
+ actions: [{ label: 'Reconnect this home', href: '/home', primary: true }],
+ },
+ unreachable: {
+ title: 'Your home did not answer',
+ body: 'three.ws could not reach this Home Assistant. If it only exists on your home network, a public server cannot route to it: use your remote https URL, or run the three.ws add-on inside the network.',
+ actions: [{ label: 'Try again', onClick: () => reconnect(), primary: true }, { label: 'Connection settings', href: '/home' }],
+ },
+ not_connected: {
+ title: 'Still opening the connection',
+ body: 'The link to your house is coming up, or was paused after repeated failures. Give it a moment and try again.',
+ actions: [{ label: 'Try again', onClick: () => reconnect(), primary: true }],
+ },
+ }[code] || {
+ title: 'Something went wrong loading your home',
+ body: err?.message || 'The request failed. Trying again usually works; if it keeps failing, the connection settings will say why.',
+ actions: [{ label: 'Try again', onClick: () => reconnect(), primary: true }, { label: 'Connection settings', href: '/home' }],
+ };
+ setStatus('disconnected', 'Disconnected', err?.message);
+ showOverlay(copy);
+ announce(copy.body);
+}
+
+function showToastError(err) {
+ // A failed action is reported in the log and the live region rather than as
+ // a modal: the house is still on screen and still usable.
+ pushLog({ text: err?.message || 'Action failed', outcome: 'failed' });
+}
+
+function renderAge() {
+ const existing = el.stage.querySelector('.hs-age');
+ if (!state.stale || !state.lastGraphAt) {
+ existing?.remove();
+ if (state.ageTimer) {
+ clearInterval(state.ageTimer);
+ state.ageTimer = 0;
+ }
+ return;
+ }
+ const node = existing || document.createElement('div');
+ node.className = 'hs-age';
+ const write = () => {
+ node.textContent = `Last seen ${relativeAge(Date.now() - state.lastGraphAt)}. Showing the house as it was.`;
+ };
+ write();
+ if (!existing) {
+ el.stage.appendChild(node);
+ state.ageTimer = setInterval(write, 1000);
+ }
+}
+
+function relativeAge(ms) {
+ const s = Math.max(0, Math.round(ms / 1000));
+ if (s < 60) return `${s} second${s === 1 ? '' : 's'} ago`;
+ const m = Math.round(s / 60);
+ if (m < 60) return `${m} minute${m === 1 ? '' : 's'} ago`;
+ const h = Math.round(m / 60);
+ return `${h} hour${h === 1 ? '' : 's'} ago`;
+}
+
+function pushLog(entry) {
+ state.log.unshift({ ...entry, at: new Date() });
+ // Bounded on purpose: a wall display left open overnight must not grow one
+ // DOM node per action forever.
+ state.log = state.log.slice(0, 20);
+ renderLog();
+}
+
+function renderLog() {
+ const existing = el.panel.querySelector('.hs-log');
+ existing?.remove();
+ if (!state.log.length) return;
+ const list = document.createElement('ul');
+ list.className = 'hs-log';
+ for (const entry of state.log) {
+ const li = document.createElement('li');
+ if (entry.outcome !== 'ok') li.className = entry.outcome === 'refused' ? 'is-refused' : 'is-failed';
+ const time = document.createElement('time');
+ time.dateTime = entry.at.toISOString();
+ time.textContent = entry.at.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
+ const text = document.createElement('span');
+ text.textContent = entry.outcome === 'refused' ? `${entry.text} (needs your yes)` : entry.text;
+ li.append(time, text);
+ list.appendChild(li);
+ }
+ el.panel.appendChild(list);
+}
+
+function announce(message) {
+ el.live.textContent = message;
+}
+
+// ── helpers ──────────────────────────────────────────────────────────────────
+
+function homeIdFromPath() {
+ const match = location.pathname.match(/^\/home\/([0-9a-fA-F-]{36})/);
+ if (match) return match[1];
+ const query = new URLSearchParams(location.search).get('home');
+ return query && /^[0-9a-fA-F-]{36}$/.test(query) ? query : null;
+}
+
+function preferredView() {
+ try {
+ const stored = localStorage.getItem(VIEW_KEY);
+ if (stored === '2d' || stored === '3d') return stored;
+ } catch {
+ // Storage disabled: default to 3D and let the WebGL probe decide.
+ }
+ return new URLSearchParams(location.search).get('view') === '2d' ? '2d' : '3d';
+}
+
+function findObject(entityId) {
+ if (!state.model) return null;
+ for (const room of state.model.rooms) {
+ const found = room.objects.find((o) => o.entityId === entityId);
+ if (found) return found;
+ }
+ return null;
+}
+
+function roomOf(entityId) {
+ if (!state.model) return null;
+ return state.model.rooms.find((room) => room.objects.some((o) => o.entityId === entityId)) || null;
+}
+
+/** Home Assistant's own areas screen, on this user's own instance. */
+function areasUrl() {
+ return state.home?.base_url ? `${state.home.base_url}/config/areas/dashboard` : null;
+}
+
+/** ...and the screen where a device gets added in the first place. */
+function integrationsUrl() {
+ return state.home?.base_url ? `${state.home.base_url}/config/integrations` : null;
+}
+
+function clamp(value, min, max) {
+ return Math.min(max, Math.max(min, value));
+}
+
+function cssEscape(value) {
+ return typeof CSS !== 'undefined' && CSS.escape ? CSS.escape(value) : String(value).replace(/["\\]/g, '\\$&');
+}