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.

fix(home): guard every entity in a call and refuse area or device targets outside a member scope

nirholasab04cc64e521
diff --git a/api/home/[id]/call.js b/api/home/[id]/call.js
index 6ef90c17f..44e661985 100644
--- a/api/home/[id]/call.js
+++ b/api/home/[id]/call.js
@@ -24,7 +24,7 @@
// refused unlock is the single most important row in that table: it is the
// evidence that the gate held.
-import { classifyCall, flattenEntities } from '@three-ws/home-bridge';
+import { classifyCall, entityIdsOfData, flattenEntities, hasSelectorTargets } from '@three-ws/home-bridge';
import { requireCsrf } from '../../_lib/csrf.js';
import { canAssertConfirmation, CONFIRMATION_REQUIRES_SESSION, outOfScopeEntities, resolveHomeAccess } from '../../_lib/home/access.js';
@@ -77,7 +77,7 @@ export default wrap(async (req, res) => {
const confirmed = body.confirmed === true;
const action = `${domain}.${service}`;
- const targets = entityIdsOf(data);
+ const targets = entityIdsOfData(data);
// WHO may say yes, asked before WHICH ROLE may say yes.
//
@@ -187,6 +187,10 @@ export default wrap(async (req, res) => {
access.scope,
targets.map((id) => ({ entityId: id, areaId: areaOf.get(id) ?? null })),
);
+ // area_id, device_id, label_id and floor_id are expanded by Home Assistant
+ // into entities this check never sees, so a scoped member may only name
+ // entities, which are what the scope is written in.
+ if (hasSelectorTargets(data)) refused.push(...['area_id', 'device_id', 'label_id', 'floor_id'].filter((k) => data[k]));
if (refused.length) {
logHomeAction({
homeId: home.id, userId: caller.userId, actor: actorFor(caller), channel: 'websocket',
@@ -283,13 +287,6 @@ async function syncAllowList(bridge, homeId) {
for (const id of live) allowList.add(id);
}
-/** entity_id is a string or an array of them; the log wants the array either way. */
-function entityIdsOf(data) {
- const id = data?.entity_id;
- if (Array.isArray(id)) return id.filter((v) => typeof v === 'string');
- return typeof id === 'string' ? [id] : [];
-}
-
/** A bearer caller is an agent principal; a cookie session is a person at a screen. */
function actorFor(caller) {
return caller.via === 'bearer' ? 'agent' : 'user';
diff --git a/packages/home-bridge/src/bridge.js b/packages/home-bridge/src/bridge.js
index 0862eeb9c..075ea438b 100644
--- a/packages/home-bridge/src/bridge.js
+++ b/packages/home-bridge/src/bridge.js
@@ -12,7 +12,7 @@ import {
import { ERR, HomeBridgeError } from './errors.js';
import { resolveIntent } from './intents.js';
import { buildHomeGraph, domainOf } from './rooms.js';
-import { classifyCall, createAllowList } from './safety.js';
+import { classifyCallTargets, createAllowList } from './safety.js';
import { normalizeBaseUrl } from './url.js';
/**
@@ -379,15 +379,11 @@ export class HomeBridge {
*/
async call(domain, service, data = {}, options = {}) {
this.#assertConnected();
- const entityId = firstEntityId(data);
- const verdict = classifyCall({
- domain,
- service,
- entityId,
- attributes: entityId ? this.#states[entityId]?.attributes : undefined,
- });
+ const verdict = classifyCallTargets({ domain, service, data, states: this.#states });
+ const entityId = verdict.entityIds[0] ?? firstEntityId(data);
- if (verdict.guarded && !options.confirmed && !(entityId && this.allowList.has(entityId))) {
+ const allowed = !verdict.unresolved && verdict.entityIds.every((id) => this.allowList.has(id));
+ if (verdict.guarded && !options.confirmed && !allowed) {
const err = new HomeBridgeError(ERR.NEEDS_CONFIRMATION, verdict.reason);
err.pending = { domain, service, data, risk: verdict.risk, entityId };
throw err;
diff --git a/packages/home-bridge/src/index.js b/packages/home-bridge/src/index.js
index ac495e6cc..a98e8be4d 100644
--- a/packages/home-bridge/src/index.js
+++ b/packages/home-bridge/src/index.js
@@ -8,6 +8,6 @@ export { ERR_CANNOT_CONNECT, ERR_INVALID_AUTH } from 'home-assistant-js-websocke
export { MACROS, matchMacro, resolveIntent } from './intents.js';
export { connectHomeMcp } from './mcp.js';
export { buildHomeGraph, domainOf, flattenEntities, summarizeClimate, summarizeLighting, summarizeSecurity } from './rooms.js';
-export { classifyCall, classifyMcpCall, createAllowList, isSafetyAction, isSafetyMcpCall, resolveMcpTargets, GUARDED_COVER_CLASSES, GUARDED_DOMAINS } from './safety.js';
+export { classifyCall, classifyCallTargets, entityIdsOfData, hasSelectorTargets, classifyMcpCall, createAllowList, isSafetyAction, isSafetyMcpCall, resolveMcpTargets, GUARDED_COVER_CLASSES, GUARDED_DOMAINS } from './safety.js';
export { createRelayTransport, relayCloseError, RELAY_PROTOCOL_VERSION } from './transport-relay.js';
export { isPrivateHost, normalizeBaseUrl } from './url.js';
diff --git a/packages/home-bridge/src/safety.js b/packages/home-bridge/src/safety.js
index 0543e08e7..9e197c0d0 100644
--- a/packages/home-bridge/src/safety.js
+++ b/packages/home-bridge/src/safety.js
@@ -89,6 +89,59 @@ export function classifyCall({ domain, service, entityId, attributes = {} } = {}
return { guarded: false, risk: null, reason: '' };
}
+/** Home Assistant target selectors other than entity_id. Each expands to a set we cannot see. */
+const SELECTOR_KEYS = ['area_id', 'device_id', 'label_id', 'floor_id'];
+
+function hasValue(v) {
+ return Array.isArray(v) ? v.length > 0 : v !== undefined && v !== null && v !== '';
+}
+
+/** True when service data targets by area, device, label or floor instead of entity id. */
+export function hasSelectorTargets(data) {
+ return SELECTOR_KEYS.some((k) => hasValue(data?.[k]));
+}
+
+/** Every entity id named in service data: a string, a comma list, or an array. */
+export function entityIdsOfData(data) {
+ const raw = data?.entity_id;
+ const list = Array.isArray(raw) ? raw : typeof raw === 'string' ? raw.split(',') : [];
+ return list.filter((v) => typeof v === 'string').map((v) => v.trim()).filter(Boolean);
+}
+
+/**
+ * Classify a whole service call, not just its first entity.
+ *
+ * Home Assistant expands entity lists, "all", and area/device/label/floor
+ * selectors itself, so the gate must look at every target it can see and treat
+ * a selector it cannot resolve as the riskiest thing it could expand to.
+ *
+ * @returns {{ guarded: boolean, risk: ('security'|'physical'|null), reason: string, entityIds: string[], unresolved: boolean }}
+ * entityIds are the guarded entities that need a standing allowance;
+ * unresolved means a selector hides targets, so no allowance can cover it.
+ */
+export function classifyCallTargets({ domain, service, data = {}, states = {} } = {}) {
+ const ids = entityIdsOfData(data);
+ let first = null;
+ const guardedIds = [];
+ for (const entityId of ids) {
+ const v = classifyCall({ domain, service, entityId, attributes: states[entityId]?.attributes });
+ if (v.guarded) {
+ guardedIds.push(entityId);
+ first ??= v;
+ }
+ }
+ if (first) return { ...first, entityIds: guardedIds, unresolved: false };
+
+ const selectors = hasSelectorTargets(data) || ids.includes('all');
+ if (selectors) {
+ const worst = ['lock', 'valve', 'alarm_control_panel', 'cover'].includes(String(domain).toLowerCase())
+ ? classifyCall({ domain, service, entityId: undefined, attributes: { device_class: 'garage' } })
+ : { guarded: false, risk: null, reason: '' };
+ if (worst.guarded) return { ...worst, entityIds: [], unresolved: true };
+ }
+ return { guarded: false, risk: null, reason: '', entityIds: [], unresolved: false };
+}
+
/**
* A standing allowance is per entity and per direction, never per domain: a user
* who lets the agent open the office door has not let it open the front door.
diff --git a/tests/home-call-targets.test.js b/tests/home-call-targets.test.js
new file mode 100644
index 000000000..83e9d1066
--- /dev/null
+++ b/tests/home-call-targets.test.js
@@ -0,0 +1,61 @@
+import { describe, expect, it } from 'vitest';
+
+import {
+ classifyCallTargets,
+ entityIdsOfData,
+ hasSelectorTargets,
+} from '../packages/home-bridge/src/safety.js';
+
+const states = {
+ 'cover.garage': { attributes: { device_class: 'garage' } },
+ 'cover.blind': { attributes: { device_class: 'blind' } },
+ 'lock.front': { attributes: {} },
+};
+
+describe('physical-action gate sees every target', () => {
+ it('guards when the garage is not the first entity', () => {
+ const v = classifyCallTargets({
+ domain: 'cover', service: 'open_cover',
+ data: { entity_id: ['cover.blind', 'cover.garage'] }, states,
+ });
+ expect(v.guarded).toBe(true);
+ expect(v.entityIds).toEqual(['cover.garage']);
+ });
+
+ it('guards a comma-separated entity_id', () => {
+ const v = classifyCallTargets({
+ domain: 'cover', service: 'open_cover',
+ data: { entity_id: 'cover.blind, cover.garage' }, states,
+ });
+ expect(v.guarded).toBe(true);
+ });
+
+ it('guards an unresolvable area target on a cover and refuses any allowance', () => {
+ const v = classifyCallTargets({ domain: 'cover', service: 'open_cover', data: { area_id: 'garage' }, states });
+ expect(v.guarded).toBe(true);
+ expect(v.unresolved).toBe(true);
+ });
+
+ it('guards cover entity_id "all"', () => {
+ const v = classifyCallTargets({ domain: 'cover', service: 'open_cover', data: { entity_id: 'all' }, states });
+ expect(v.guarded).toBe(true);
+ });
+
+ it('leaves safe directions and unrelated domains alone', () => {
+ expect(classifyCallTargets({ domain: 'cover', service: 'close_cover', data: { area_id: 'garage' }, states }).guarded).toBe(false);
+ expect(classifyCallTargets({ domain: 'light', service: 'turn_on', data: { area_id: 'hall' }, states }).guarded).toBe(false);
+ expect(classifyCallTargets({ domain: 'cover', service: 'open_cover', data: { entity_id: 'cover.blind' }, states }).guarded).toBe(false);
+ });
+});
+
+describe('target extraction for the scope check', () => {
+ it('splits comma lists and arrays', () => {
+ expect(entityIdsOfData({ entity_id: 'light.a, light.b' })).toEqual(['light.a', 'light.b']);
+ expect(entityIdsOfData({ entity_id: ['light.a'] })).toEqual(['light.a']);
+ });
+ it('detects selector targets', () => {
+ expect(hasSelectorTargets({ area_id: 'bedroom' })).toBe(true);
+ expect(hasSelectorTargets({ device_id: ['d1'] })).toBe(true);
+ expect(hasSelectorTargets({ entity_id: 'light.a' })).toBe(false);
+ });
+});