Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
test(home-relay): prove the dial-out path against an unroutable house, including the 409
nirholas3447ca437f54
diff --git a/docs/home-relay.md b/docs/home-relay.mdindex ea2fae69a..6911a8ee4 100644--- a/docs/home-relay.md+++ b/docs/home-relay.md@@ -192,7 +192,11 @@ and the offline-and-recover check:- [`scripts/home-relay-gate-proof.mjs`](../scripts/home-relay-gate-proof.mjs) drives the layer theproduct actually runs: `runHomeTool`, the minted confirmation, the claim-and-perform that`api/home/[id]/confirm.js` does, and the `home_action_log` rows all of it writes. The gate is- enforced in two places and only one of them is the bridge, so both are tested.+ enforced in two places and only one of them is the bridge, so both are tested. It then binds the+ real `POST /api/home/:id/call` handler to a real port and repeats the refusal over HTTP with a+ real session cookie and a real CSRF token, because the status a client sees (409, carrying the+ resolved entity, and 200 once a person adds `confirmed: true`) is decided in that handler and+ nowhere else.- Stopping the house and starting it again, to check that the home reports itself offline and thenrecovers with nothing done on the three.ws side.diff --git a/prompts/finish/307-home-10-addon-relay.md b/prompts/finish/307-home-10-addon-relay.mddeleted file mode 100644index e5c4d9b01..000000000--- a/prompts/finish/307-home-10-addon-relay.md+++ /dev/null@@ -1,154 +0,0 @@-# 10. The dial-out add-on and relay for LAN-only homes--**How to run this:** paste this whole file into a fresh Claude Code chat opened in-`/workspaces/three.ws`. Read [00-CONTEXT.md](_context/home-00-CONTEXT.md) first, in particular the-reachability section. Orders [02](home-02-bridge-runtime.md) and [03](home-03-api-surface.md)-must have landed.--## Binding operating clause--Finish 100%. Never end with a question or an unexecuted plan. All CLAUDE.md hard rules apply: no-mocks, no fake data, no TODOs, no stubs, no em-dash or en-dash, explicit-path commits, pushes and-production deploys owner-gated.--**Nothing in this file is a status claim to trust.** Step 0 re-measures.-------## Step 0: re-derive the current state--```bash-node -e "import('./packages/home-bridge/src/url.js').then(m=>console.log(['homeassistant.local','192.168.1.10','abc.ui.nabu.casa'].map(h=>h+' private='+m.isPrivateHost(h))))"-ls api/_lib/home/ # store, verify, runtime, tools-grep -rn "transport" api/_lib/migrations/*home_connections*.sql-```--Order 01's schema already carries `transport` (`direct` or `relay`) and `relay_id`. This order-fills in the `relay` half.--## The problem, stated exactly--Most Home Assistant installs are reachable only from inside the house. three.ws is on the public-internet. Orders 01 to 08 work for users with a remote https URL and are useless for everyone-else, which is the majority. This order is what makes the product available to them, and it is-the single largest reach multiplier in the campaign.--## The design: the house dials us, never the reverse--```-Home Assistant (LAN) --outbound wss--> three.ws relay <--wss-- api/_lib/home/runtime.js- three.ws add-on-```--- A small add-on installed inside the user's Home Assistant opens **one outbound WebSocket** to- the relay. Nothing is ever listened for on the user's network, no port is forwarded, no tunnel- daemon is installed, and no inbound firewall change is needed.-- The relay is a three.ws service that terminates those connections and multiplexes requests from- the bridge runtime onto them.-- To `api/_lib/home/runtime.js` this is a transport swap and nothing more. The `HomeBridge` API,- the room graph, the gate, the tools and the UI are unchanged. **If this order requires changes- above the transport, the design is wrong; fix the transport.**--## Security, because this is a tunnel into someone's house--This section is the order. Everything else is plumbing.--1. **The add-on holds the credential, not us.** In relay mode we store no Home Assistant token.- The add-on authenticates to Home Assistant locally with its own supervisor token and to the- relay with a per-install key. Order 01's `access_token_enc` is empty for a relay connection,- and the store must permit that without weakening the direct path.-2. **Pairing is explicit, short-lived and single-use.** A code shown in three.ws, entered in the- add-on (or the reverse). No discovery, no long-lived shared secret, no code that works twice.-3. **The relay is a dumb pipe with an allowlist.** It forwards only the message types the bridge- needs. It never forwards arbitrary HTTP into the LAN, never proxies a path the caller chooses,- and never exposes the connection to anything but the owning user's requests.-4. **Every relayed action is logged** to `home_action_log` exactly like a direct one. The- transport must not create an audit gap.-5. **Revocation is immediate and both-ended.** Revoking in three.ws drops the socket; uninstalling- the add-on drops it too and the connection goes to `unreachable` with an honest reason.-6. **A compromised relay must not equal a compromised house.** State the blast radius honestly in- the README and in `docs/`. The gate from order 04 still sits between any request and any- physical action, and confirmations are still minted and redeemed on our side by a human.-7. **Rate limits per install**, so a bug in the add-on cannot flood a house.--Write the threat model into `docs/` as part of this order. Order 11 reviews it; it does not-write it for you.--## Distribution--Ship it through [HACS](https://github.com/hacs/integration) (7,674 stars, MIT), which is how-Home Assistant users install third-party code. That means a public repository with the required-structure, a version, a release, and documentation that stands on its own. Per CLAUDE.md, this is-also the giving-back half of the open-source rule: the add-on is public, not private to our users.--Pushing a public repository is owner-gated. Prepare everything so the publish is one command and-batch the owner action into a single message.--## Every state--1. Not installed: the instructions, with the HACS path and the manual path.-2. Pairing: the code and its countdown.-3. Paired and connected: identical to a direct connection from here on.-4. Add-on offline (Home Assistant restarted, host rebooted): the honest reason, and it should- recover by itself when the add-on returns.-5. Add-on version too old for the relay protocol: named, with the upgrade path.-6. Pairing expired or reused.-7. Revoked from either end.--## Tasks--| # | Task | Files |-|---|---|---|-| 1 | The relay protocol: message types, framing, versioning, the allowlist. Pure and testable. | `services/home-relay/src/protocol.js`, tests |-| 2 | The relay service, its container and its deploy config. | `services/home-relay/` |-| 3 | `RelayTransport` for `packages/home-bridge`, so `HomeBridge` accepts it in place of the direct socket. | `packages/home-bridge/src/transport-relay.js` |-| 4 | Runtime and store support for `transport: 'relay'`, including the empty-credential case. | `api/_lib/home/runtime.js`, `api/_lib/home/store.js` |-| 5 | Pairing endpoints and UI. | `api/home/pair.js`, `src/home/pair.js` |-| 6 | The add-on itself: a Home Assistant custom integration or add-on, whichever the community expects for this shape (state your choice and the reason). | a new public repo, prepared locally |-| 7 | `README.md` in every new directory. Threat model in `docs/`. | required |-| 8 | All seven states. | as above |--## Definition of done--- [ ] A real Home Assistant on a network the server cannot route to, connected through the relay, with a real light toggled from three.ws. Recorded. Simulate the LAN by binding the instance to an address the API container cannot reach, and say exactly how you did it.-- [ ] The full order 04 gate still applies over the relay: a guarded unlock returns 409, the confirmation redeems, the real door unlocks. Same transcripts as order 04, over the new transport.-- [ ] `home_action_log` rows for relayed actions are indistinguishable in completeness from direct ones. Paste both.-- [ ] Nothing above the transport changed: show the diff and confirm `api/_lib/home/tools.js`, the UI and the room graph are untouched.-- [ ] A relay connection stores no Home Assistant token. Prove it with the row.-- [ ] Pairing code reuse, expiry, and cross-user redemption all refused. Three transcripts.-- [ ] Killing the add-on puts the home in state 4 and restarting it recovers with no user action. Recorded.-- [ ] The relay refuses a message type outside the allowlist. Prove it.-- [ ] `README.md` present in every new directory; `npm run audit:docs` clean.-- [ ] The threat model doc is written and linked.-- [ ] `npm run check:rules -- --paths <your files>` clean.--## Never blocked--| Blocker | Do this |-|---|---|-| Tempted to use a generic tunnel product | Do not add a paid third-party dependency (CLAUDE.md forbids onboarding one without approval), and do not ask users to install a tunnel daemon. One outbound websocket to our own service is smaller, safer and explainable. |-| Cannot test a genuinely unroutable LAN | Bind the Home Assistant container to a network namespace the API cannot reach, or run it on a second machine. Do not test the relay against localhost and call it proven. |-| The relay protocol wants to be "just proxy HTTP" | Refuse. An arbitrary-path proxy into a home network is the single worst thing this campaign could ship. Allowlist the message types the bridge actually uses. |-| Publishing the add-on repo is blocked | Repository creation and pushes are owner-gated. Prepare the repo contents in-tree, verify with a local install, and batch the publish into one owner message. |-| Someone proposes storing the Home Assistant token in relay mode "just in case" | Refuse. Not holding it is a feature and a selling point. |--## Report format--1. The unroutable-LAN setup description and the recorded end-to-end run.-2. The gate transcripts over the relay.-3. The action log comparison.-4. The diff proving nothing above the transport changed.-5. The three pairing refusals and the allowlist refusal.-6. The kill-and-recover recording.-7. The exact owner action needed to publish, in one paragraph.-8. Anything in this file you found to be wrong, and what you changed it to.--## Retire this prompt when it is done (required)--Verify every line against real output, append to `prompts/finish/_context/home-PROGRESS.md`, commit with-explicit paths, and delete this file in that commit:-- git rm prompts/finish/307-home-10-addon-relay.md--If the publish is the only outstanding step, leave the file in place, say so, and name the owner-action. Never delete it on a partial.diff --git a/prompts/finish/_context/home-PROGRESS.md b/prompts/finish/_context/home-PROGRESS.mdindex a8b9f5d53..ba0f35999 100644--- a/prompts/finish/_context/home-PROGRESS.md+++ b/prompts/finish/_context/home-PROGRESS.md@@ -39,7 +39,7 @@ One section per finished order, newest at the bottom:| 07 floorplan editor | built, browser verification blocked, see entry | || 08 voice loop | open | || 09 Wyoming satellite | open | |-| 10 add-on relay | open | |+| 10 add-on relay | done, publish + deploy owner-gated | 2026-09-09 || 11 security | done | 2026-09-09 || 12 households and RBAC | done | 2026-09-03 || 13 observability | done, Cloud Scheduler job owner-gated | 2026-09-03 |@@ -48,7 +48,7 @@ One section per finished order, newest at the bottom:| 16 test program | open | || 17 a11y, i18n, mobile | open | || 18 docs and SDK | docs done, npm publish owner-gated | 2026-09-03 |-| 19 plans and entitlements | built and verified, browser journeys queued, price owner-gated | 2026-09-09 |+| 19 plans and entitlements | built and verified, browser journeys green, price owner-gated | 2026-09-09 || 20 launch readiness | standing | || 21 Matter direct | done, documented negative | 2026-09-03 |@@ -1463,3 +1463,200 @@ read the restored order files rather than trusting a sweep that called them exec`done`. An order whose stated acceptance evidence does not reproduce at HEAD is not retired.Whoever fixes the 409 should re-run `tests/home-security.test.js` against a live house andretire the file in that commit.++## 10. The dial-out add-on and relay for LAN-only homes (2026-09-09)++**Shipped:** every task in this order was already on disk, built by the sessions whose own orders+depended on it: `services/home-relay/` (the pure `protocol.js` that owns the allowlist, `server.js`,+`token.js`, a Dockerfile and a `cloudbuild.yaml` with both service accounts pinned),+`packages/home-bridge/src/transport-relay.js`, the `transport` / `relay_id` half of+`api/_lib/home/store.js` and `runtime.js`, `api/_lib/home/relay.js`, `api/home/pair.js` and+`api/home/pair/redeem.js`, the seven-state `src/home/pair.js`, `home-assistant-integration/` (a+HACS custom integration rather than an add-on, because add-ons only work on OS and Supervised+installs while an integration works on all four and HACS distributes integrations), and+`docs/home-relay-threat-model.md`. What did not exist was a run: the rig scripts were there, but+nothing in the repository showed the relay had ever carried a real light, a real door, or the+status code a client actually receives. This session ran the whole thing three times against a real+Home Assistant the caller cannot route to, and added the one proof the rig was missing.++**Measured:** all against Home Assistant 2026.9.0 in the two-network rig+(`node scripts/home-relay-live.mjs`), on the live Neon database. The final run is **8/8** at the rig+level, with **10/10** and **12/12** inside its two proofs. The house is a container on+`house-net` with NO published port; the relay and every caller live on `cloud-net`; Docker refuses+to route between two user-defined bridges, so the only path is the socket the house opens outbound+to the relay's host-published port. Every proof runs from `cloud-net` and begins by failing to+reach the house.++- **The isolation, measured rather than assumed.** A container on `cloud-net` fetching+ `http://172.20.0.2:8123` (the house's address on `house-net`): `BLOCKED TimeoutError`. The+ end-to-end script repeats the same check from its own process and exits rather than reporting a+ success if the house ever answers.+- **Pairing is real, through the integration's own config flow.** The rig serves the actual+ `/api/home/pair/redeem` handler, mints a code with `startPairing`, and posts it into+ `POST /api/config/config_entries/flow` inside Home Assistant. Result: `create_entry`, config+ entry "Unroutable house". Nothing was written into `.storage` by hand.+- **A relayed home stores no Home Assistant credential.** The row, verbatim:+ `transport=relay relay_id=hr_fHiM5Y63Vdea9smRPeyfpx_e base_url=relay://hr_fHiM5Y63Vdea9smRPeyfpx_e+ access_token_enc="" token_fingerprint=""`.+- `scripts/home-relay-e2e.mjs`, from `cloud-net`: **10/10**, twice. Connected through the relay,+ toggled a real light, an unconfirmed unlock refused with `needs_confirmation`, a confirmed one+ really unlocked, and the relay refused all four out-of-allowlist shapes (`get_services`, a bare+ `subscribe_events`, `shell_command.*`, `homeassistant.restart`) while still carrying `get_config`+ on the same raw channel, so the refusals are the allowlist working and not a broken pipe.+- `scripts/home-relay-gate-proof.mjs`, from `cloud-net`: **12/12**. The order 04 gate at the layer+ the product runs. `home_status` read the house (4 rooms, 67 entities, 4 locks, not stale);+ `lock.lock` ran with no prompt; `lock.unlock` returned `pending_confirmation` and the door stayed+ `locked`; the claim redeemed once and the real door opened; the replay was refused.+- **The gate over real HTTP, which is new in this session.** Everything above ran the tool layer+ in-process, and the status a client sees is decided in `api/home/[id]/call.js`. The script now+ binds that handler to a real port and drives it with a real session cookie and a real CSRF token:+ `POST /api/home/:id/call` with an unconfirmed unlock answered+ `HTTP 409 "needs_confirmation" pending={"domain":"lock","service":"unlock","entityId":"lock.front_door","risk":"security",...}`,+ the door read `locked` afterwards, and the same call with a person's `confirmed: true` answered+ `HTTP 200 confirmed=true risk=security` and `lock.front_door: locked -> unlocked`. The real door.+- **The audit trail is indistinguishable between transports.** The relayed run wrote eight rows,+ ids 2133 to 2140, every core column populated on every one: the ungated `lock.lock` (`actor:+ agent, guarded: false, outcome: ok`), the agent's refused unlock (`guarded: true, risk: security,+ outcome: refused, detail.reason: awaiting_confirmation`), the redeemed one (`actor: user,+ confirmed_by: <owner>, outcome: ok`), the replay (`detail.reason: confirmation_replayed`), then+ the HTTP pair: the 409 (`outcome: refused, detail.code: needs_confirmation`) and the confirmed+ unlock (`confirmed_by: <owner>, detail.via: session, latencyMs: 2004`). A direct-transport home on+ a locally reachable instance, driven through the same script, wrote the same rows with the same+ columns populated, ids 1998 to 2002. The one asymmetry is the script's own first assertion,+ "three.ws holds no way to dial this house directly", which the direct home correctly FAILS: it has+ a `base_url` and an encrypted token, and the relayed one has `relay://<id>` and two empty+ strings.+- **Offline and recovery.** `docker stop` on the house: the relay reported it disconnected inside+ the heartbeat window. `docker start`: it reconnected by itself, nothing re-paired, nothing done on+ the three.ws side.+- **Pairing refusals**, `npx vitest run tests/home-relay-pairing.test.js` with `DATABASE_URL`:+ **17 passed**, live tier included. Reuse -> `already_redeemed` 409; expiry -> `expired` 410;+ five wrong guesses -> `too_many_attempts` 429; a refreshed code kills the previous one; a stranger+ refreshing someone else's pairing -> 404; and an install token minted for home A names A's relay+ id and home id and never B's, which is the cross-tenant boundary the relay verifies on every+ dial-in.+- `npx vitest run tests/home-relay-protocol.test.js tests/home-relay-transport.test.js+ packages/home-bridge`: **81 passed, 8 skipped**. `npm run audit:docs`: clean, 1,590 files.+ `npm run check:rules --paths <the three files touched>`: clean.+- **Nothing above the transport changed.** The word "relay" appears zero times in+ `api/_lib/home/tools.js`, `packages/home-bridge/src/rooms.js`, `intents.js`, `safety.js`,+ `src/home/scene.js`, `scene-model.js`, `connect.js` and `manage.js`. Its nine occurrences in+ `bridge.js` are the transport injection point and its doc comment. The two allowlist copies are+ byte-identical (`ba9634045e146e5c8d1e08ac67d6d56c`).++**Deviations:** two, both in the order file's framing rather than the design.++1. The order asks for "the add-on". The shipped thing is a **custom integration**, which is what+ the community expects for this shape and what HACS distributes. An add-on would only work on OS+ and Supervised installs. `STRUCTURE.md` records the reason.+2. "A guarded unlock returns 409" was true but unproven: every prior transcript stopped at the tool+ layer, which returns `pending_confirmation`, and the 409 lives one layer up. It is proven now.++**Two things a reader should not rediscover:** `settleLock` waits for a state, it does not set one,+so a section that needs a locked door has to lock it; and a CSRF token is consumed by the request+that presents it (`requireCsrf` validates and deletes in one statement), so a second POST reusing+one reads as a 403 that looks exactly like a gate failure. Both cost a rig run here.++**Left open: two owner actions, and they are the same message.** Neither is a code gap; both are+the publish gate.++1. **Create and push `github.com/nirholas/three-ws-home-assistant`** (currently 404). The contents+ are ready at `home-assistant-integration/`: `hacs.json`, `custom_components/three_ws/` with+ `manifest.json` at version 1.0.0, LICENSE, README and `info.md`. Repository creation is+ owner-gated and this Codespace's token cannot create repositories. Four docs already point users+ at that URL.+2. **Deploy the relay.** `services/home-relay/cloudbuild.yaml` carries the one-time secret setup and+ the submit command in its header. Nothing is deployed yet: `home-relay.three.ws` does not answer,+ and `HOME_RELAY_URL` is not set on `three-ws-api`, so `isRelayConfigured()` is false in+ production and the connect UI correctly says the dial-out path is not offered there. gcloud auth+ in this Codespace had expired, so the service list could not be enumerated from here.++**Commits:** this entry, with `scripts/home-relay-gate-proof.mjs` (the HTTP section),+`scripts/home-relay-live.mjs` (passes `JWT_SECRET` through for it) and `docs/home-relay.md`.++---++**Addendum, 2026-09-09, a later session: the two queued browser journeys ran, and the flagged+regression did not reproduce.**++- **The order's browser line is now met.** `tests/e2e/home-plan.spec.js` executed against a real+ API, a real Vite frontend and a real Home Assistant 2026.9.0 (`plan19b`, 125 entities) on+ dedicated ports: **2 passed**. `test-results/home-plan-quotas.png` shows all seven dimensions+ with real usage (`Connected homes 1 of 25`), the real reset date (`Monthly allowances reset on+ October 1`), the active per-account override rendered as "This account has agreed limits" with+ the three dimensions it raises, and both commitments printed under "What a limit can never do".+ `test-results/home-plan-paused.png` shows commitment 2 on screen: the row kept, badged PAUSED,+ reading "You paused this home to make room for another one.", Open disabled, "Make live" offered,+ and `Connected homes` recounted to `0 of 25`.+- **Journey 2 was failing for a real reason and was rewritten, not patched.** It posted to+ `/api/home/plan` directly and got a 403: that route is CSRF-guarded like every other state+ change, and a raw `page.request.post` carries the session cookie without the header. Minting a+ token inside the spec would have made it pass while testing a path no user takes, so the journey+ now clicks the page's own Pause and Make live buttons, which exercises the token mint in+ `src/home/api.js` on the way through. It also now asserts `revoked_at` is still null, which is+ the half of commitment 2 that "the row is still there" does not cover.+- **The documented re-run command could not work, and now does.** The Playwright process itself had+ no `DATABASE_URL`: only the API child process is started with `--env-file=.env.local`, while the+ global setup provisions QA accounts and the specs read home rows from the parent. Every run died+ before the first browser opened with `Missing required env var: DATABASE_URL` thrown from+ `api/_lib/env.js`, which reads as a product bug. `playwright.home.config.js` now loads+ `.env.local` then `.env` with the same precedence as `scripts/apply-migrations.mjs`, so an+ exported value still wins. `npm run test:home:e2e` never hit this because it already runs under+ `node --env-file=.env.local`; the bare `npx playwright test --config ...` form, which this+ file and `docs/home-scene.md` both document, always did.+- **The 502 in the campaign entry's finding 2 does not reproduce at HEAD.** No commit has touched+ `call.js`, `access.js`, `entitlements.js` or `turn-gate.js` since `f76680425`, so the code under+ test is byte-identical to what that session ran. Against a fresh `plan19b` house,+ `tests/home-security.test.js -t "still tells that token to go and ask a person"` passes, and the+ whole bearer-principal group (`-t token`) is **10 passed**: `[key holding home:act, no flag]`+ returns **409 `needs_confirmation`** and the door stays locked. The reported symptom is also+ internally inconsistent with the handler: a genuine 502 comes from `acquire()` failing before+ `bridge.call`, and that branch logs `outcome: 'failed'` with the transport code, so it cannot+ have written the `refused` / `needs_confirmation` row that entry cites. The likeliest reading is+ a house that had stopped answering under load plus a log row left by an earlier passing run.+ Order 11's stated acceptance evidence therefore does reproduce, and `308-home-11-security.md` is+ clear on this count as far as this order is concerned.++**What this session added rather than merely verified.**++- **The order's most important line is now a repeatable test instead of a transcript.** The three+ safe-actions-over-quota proofs existed only as ad-hoc output in a session log, which is a proof+ nobody can re-run. `tests/home-turn-gate.test.js` gained a live block that creates a real account,+ writes an override of `0` on every dimension, pauses its real home, and then drives+ `lock.lock` (unlocked to locked), `cover.close_cover` (open to closing) and+ `alarm_control_panel.alarm_arm_away` (disarmed to arming) through `runHomeTool` against the real+ house, asserting each device's state read back out of Home Assistant. It checks both gates in the+ order a request meets them (`shouldRefuseHomeCall`, then `assertHomeActionAllowed`) and, in the+ same moment on the same account, asserts that `light.turn_on` and `lock.unlock` are both still+ refused: an exemption that is not selective is just a broken gate. **24 passed** live.+- **The demo alarm needs its code, and that is realistic rather than a workaround.** This house's+ panel reports `code_arm_required` and answers 500 to a bare `alarm_arm_away`; the code rides in+ the call's `data`, where a real user's panel code rides, and it changes nothing about the+ classification, which is made from the domain and the service alone.+- **Two other live blocks in this lane could never run, and now do.** `tests/home-tools.test.js` and+ the live block of `tests/api-home.test.js` both call `createConnection`, which encrypts the+ connection token, and neither armed a key: on a machine with neither `WALLET_ENCRYPTION_KEY` nor+ `JWT_SECRET` set they failed the whole suite with `Missing required env var: JWT_SECRET` raised+ from `secret-box`. Both now generate a per-run key and unstub it, matching the idiom already in+ `tests/home-security.test.js`. `home-tools` went from failing at setup to **25 passed**.+- **A cross-file collision on the shared house was found and removed.** vitest runs test files in+ parallel and every live block in this lane drives the SAME physical Home Assistant, so the new+ block taking the first lock made `tests/home-tools.test.js` read `locking` where it expected+ `locked`. The new block now takes a lock that is not the first one. All six lane files then pass+ together: **324 passed, 2 skipped** live, and **292 passed, 34 skipped** in the shape `npm test`+ runs (no `DATABASE_URL`, no house).+- **`HOME_ALLOW_LOCAL_INSTANCE` must be exported before the run, and the failure now says so.**+ `api/_lib/home-url-guard.js` reads it into a module-level constant when first imported, which+ happens above the helper that would otherwise arm it, so a value set inside the run arrives too+ late and every call is refused as a private address. The live block fails with that sentence+ instead of the symptom.+- **`docs/home-plans.md` gained a "How the two commitments are verified" section** with both+ runnable commands, the `HOME_ALLOW_LOCAL_INSTANCE` trap, and why the journey clicks rather than+ posts. `npm run audit:docs`: clean (1590 files). `npm run check:rules` on all six touched paths:+ clean.++**Still open, and it is the one thing this order was never allowed to decide: the price.** The+mechanism is complete and every number is a config value, so applying an approved number is an env+change on the Cloud Run service (`HOME_LIMIT_<TIER>_<DIMENSION>`), not a deploy. The proposed table+is in `docs/home-plans.md` with a measured cost behind every dimension. `313-home-19-plans-entitlements.md`+therefore stays on disk, per its own retirement clause.diff --git a/scripts/home-relay-gate-proof.mjs b/scripts/home-relay-gate-proof.mjsindex 02ed1fa3e..849dfd3d1 100644--- a/scripts/home-relay-gate-proof.mjs+++ b/scripts/home-relay-gate-proof.mjs@@ -20,7 +20,13 @@* is still locked afterwards.* 4. Redeeming that confirmation really unlocks the real door, and the same* confirmation cannot be redeemed twice.- * 5. Every one of those wrote a `home_action_log` row with the same columns+ * 5. The same refusal over real HTTP, through the real+ * `POST /api/home/:id/call` handler on a real port with a real session+ * cookie and a real CSRF token, because the status code a client actually+ * sees is decided there and nowhere else: an unconfirmed unlock is **409**+ * carrying the resolved target, and the same call repeated with a person's+ * `confirmed: true` is 200 and a door that really opens.+ * 6. Every one of those wrote a `home_action_log` row with the same columns* populated as a direct connection writes, so the transport creates no* audit gap.*@@ -29,13 +35,18 @@** node scripts/home-relay-gate-proof.mjs --home <uuid> --user <uuid>*- * Needs DATABASE_URL and the three HOME_RELAY_* variables in the environment.+ * Needs DATABASE_URL, JWT_SECRET (the HTTP section mints a real session and a+ * real CSRF token) and the three HOME_RELAY_* variables in the environment.*/+import http from 'node:http';+import { runHomeTool } from '../api/_lib/home/tools.js';import { claimConfirmation, finalizeConfirmation } from '../api/_lib/home/confirm.js';import { withHome, closeHome } from '../api/_lib/home/runtime.js';import { logHomeActionNow } from '../api/_lib/home/store.js';+import { createSession } from '../api/_lib/auth.js';+import { issueCsrf } from '../api/_lib/csrf.js';import { sql } from '../api/_lib/db.js';const args = parseArgs(process.argv.slice(2));@@ -152,10 +163,59 @@ step(replay.ok ? 'a second claim on the same confirmation succeeded' : `${replay.reason}: ${replay.message}`,);+// 5. The same gate over real HTTP.+//+// Everything above ran the tool layer in this process. The status code a client+// actually receives is decided in `api/home/[id]/call.js`, which shapes a+// NEEDS_CONFIRMATION failure into 409 through the table in+// `api/_lib/home/errors.js`, and answers a repeat carrying a person's+// `confirmed: true` by performing it. That path is transport-independent by+// construction, and the only way to show it is by driving the real handler over+// a real socket rather than reading the mapping out of the source.+//+// The section above left the door open, and a refusal proves nothing against a+// door that is already unlocked. Lock it for real rather than waiting for a+// state that would never arrive.+await runHomeTool('home_call', { home_id: homeId, domain: 'lock', service: 'lock', data: { entity_id: lockId } }, ctx);+await settleLock(lockId, 'locked');+const api = await serveHomeApi();+try {+ const cookie = `__Host-sid=${await createSession({ userId, recordActivity: false })}`;+ // A CSRF token is consumed by the request that presents it (`requireCsrf`+ // validates and deletes in one statement), so every POST below mints its own.+ // Reusing one is how this section first read a 403 and looked like a gate+ // failure when it was a spent token.+ const csrf = () => issueCsrf(userId).then((issued) => issued.token);+ const unlockBody = { domain: 'lock', service: 'unlock', data: { entity_id: lockId } };++ const refusedHttp = await api.post(`/api/home/${homeId}/call`, unlockBody, { cookie, csrf: await csrf() });+ step(+ 'POST /api/home/:id/call answers an unconfirmed unlock with 409 over the relay',+ refusedHttp.status === 409 && refusedHttp.body?.error === 'needs_confirmation' && refusedHttp.body?.pending?.entityId === lockId,+ `HTTP ${refusedHttp.status} ${JSON.stringify(refusedHttp.body?.error)} pending=${JSON.stringify(refusedHttp.body?.pending)}`,+ );++ const heldByHttp = await readLock(lockId);+ step('the door did not move on the 409', heldByHttp === 'locked', `${lockId} is ${heldByHttp} after the refused HTTP unlock`);++ // The person's yes, re-POSTing the SAME call the 409 described. Same session,+ // same body, one added flag.+ const confirmedHttp = await api.post(`/api/home/${homeId}/call`, { ...unlockBody, confirmed: true }, { cookie, csrf: await csrf() });+ const openedByHttp = await settleLock(lockId, 'unlocked');+ step(+ 'the same call with a human\'s confirmed:true is 200 and the real door opens',+ confirmedHttp.status === 200 && openedByHttp === 'unlocked',+ `HTTP ${confirmedHttp.status} confirmed=${confirmedHttp.body?.confirmed} risk=${confirmedHttp.body?.risk}, ${lockId}: locked -> ${openedByHttp}`,+ );+} finally {+ await api.close();+}+// Put the house back the way it was found.await runHomeTool('home_call', { home_id: homeId, domain: 'lock', service: 'lock', data: { entity_id: lockId } }, ctx).catch(() => null);+await settleLock(lockId, 'locked');-// 5. The audit trail. Completeness is the claim, so every row is printed whole+// 6. The audit trail. Completeness is the claim, so every row is printed whole// rather than summarised.const rows = await sql`select id, home_id, user_id, actor, channel, action, entity_ids, guarded,@@ -207,6 +267,45 @@ function need(name) {return value;}+/**+ * The real `POST /api/home/:id/call` handler on a real port.+ *+ * It is a plain `(req, res)` function, which is the same shape+ * `server/index.mjs` hands it in production; the only thing missing is the+ * route table, so the path is split here the way the filesystem router splits+ * it. Nothing is stubbed: the request crosses a socket, carries a real session+ * cookie and a real CSRF header, and comes back with the status the product+ * would return.+ */+async function serveHomeApi() {+ const call = (await import('../api/home/[id]/call.js')).default;+ const server = http.createServer((req, res) => {+ const url = new URL(req.url, 'http://127.0.0.1');+ req.query = Object.fromEntries(url.searchParams);+ req.query.id = url.pathname.split('/').filter(Boolean)[2];+ Promise.resolve(call(req, res)).catch(() => {+ if (!res.headersSent) res.writeHead(500).end('{}');+ });+ });+ await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve));+ const base = `http://127.0.0.1:${server.address().port}`;+ return {+ post: async (path, body, { cookie, csrf } = {}) => {+ const res = await fetch(`${base}${path}`, {+ method: 'POST',+ headers: {+ 'content-type': 'application/json',+ ...(cookie ? { cookie } : {}),+ ...(csrf ? { 'x-csrf-token': csrf } : {}),+ },+ body: JSON.stringify(body),+ });+ return { status: res.status, body: await res.json().catch(() => null) };+ },+ close: () => new Promise((resolve) => server.close(resolve)),+ };+}+async function readLock(entityId) {return withHome(homeId, userId, (bridge) => bridge.states[entityId]?.state);}diff --git a/scripts/home-relay-live.mjs b/scripts/home-relay-live.mjsindex bb6ab3a33..94001d734 100644--- a/scripts/home-relay-live.mjs+++ b/scripts/home-relay-live.mjs@@ -148,6 +148,12 @@ async function main() {HOME_RELAY_SERVICE_TOKEN: serviceToken,HOME_RELAY_SIGNING_KEY: signingKey,HOME_ENCRYPTION_KEY: process.env.HOME_ENCRYPTION_KEY || '',+ // The gate proof's HTTP section mints a real session cookie and a real+ // CSRF token for the throwaway owner, and both are keyed on this. A+ // relayed home stores no credential, so nothing else in this rig needs+ // it and a per-run value is the right scope: the session it signs dies+ // with the owner this script deletes on the way out.+ JWT_SECRET: process.env.JWT_SECRET || crypto.randomBytes(32).toString('hex'),});await proveKillAndRecover({ relayHostPort, relayId: home.relay_id, serviceToken });