@astrofoundry/pi-astro 0.40.72 → 0.40.73

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -80,7 +80,7 @@ pi # launch; confirm [Extensions] lists astro-subagents, grimoire
80
80
 
81
81
  **Bundled subagents** (call them as `astro.<name>`):
82
82
  - General-purpose: `code-reviewer`, `google-tech-lead`, `spec-writer`, `tester-api`, `tester-ui`, `ui-architect`, `ui-design-system`, `ui-frontend-developer`
83
- - Specialists (one homelab area each, need the host setup in [specialists/README.md](specialists/README.md)): `arcane` (Arcane container platform, GitOps first; sanitized host checks, Mealie and Paperless dumps, stack image updates with rollback, and the documented manager upgrade, both with buttons on the daily report), `identity` (Zitadel, Pomerium routes through the homelab repository, certificates), `network` (UniFi consoles of sites 37 and Mira: reads and every Network API write, through the cloud with local fallback; FreeRADIUS, Tailscale), `dns` (Technitium resolvers, Cloudflare zones), `edge` (Frontdoor VPS over IAP, nginx SNI allowlist through the homelab repository, public route checks), `security` (Wazuh, CrowdSec, log archive, read-only), `backup` (vzdump, Restic layers, GCS offsite, restore tests), `proxmox` (guest lifecycle, snapshots, resources; no create or destroy), `inference` (llama.cpp on Nexus, Europa health), `media` (trendarr: trending titles, recommendations from the library, Radarr and Sonarr adds, SABnzbd pause), `research` (internet research in a thread per request in #research: numbered questions first, then facts checked in a sandbox Chrome at Mira with a UAE address, per-category defaults, captchas solved by an owner in a live view), `home` (Home Assistant: health, problems, logs, updates, and actions)
83
+ - Specialists (one homelab area each, need the host setup in [specialists/README.md](specialists/README.md)): `arcane` (Arcane container platform, GitOps first; sanitized host checks, Mealie and Paperless dumps, stack image updates with rollback, and the documented manager upgrade, both with buttons on the daily report), `identity` (Zitadel, Pomerium routes through the homelab repository, certificates), `network` (UniFi consoles of sites 37 and Mira: reads and every Network API write, through the cloud with local fallback; FreeRADIUS, Tailscale), `dns` (Technitium resolvers, Cloudflare zones), `edge` (Frontdoor VPS over IAP, nginx SNI allowlist through the homelab repository, public route checks), `security` (Wazuh, CrowdSec, log archive, read-only), `backup` (vzdump, Restic layers, GCS offsite, restore tests), `proxmox` (guest lifecycle, snapshots, resources; no create or destroy), `inference` (llama.cpp on Nexus, Europa health), `media` (trendarr: trending titles, recommendations from the library, Radarr and Sonarr adds, SABnzbd pause), `research` (internet research in a thread per request in #research: numbered questions first, then facts checked in a sandbox Chrome at Mira with a UAE address, per-category defaults, captchas solved by an owner in a live view), `home` (Home Assistant: health, problems, logs, updates, actions, every API its interface uses, and its YAML files)
84
84
  - Release notes: `release-reviewer` (no tools; judges whether an update could break how we use a tool or image, for the Cortex Tools Report and the Arcane Daily Report)
85
85
  - Supervision: `foreman` (read only; diagnoses an unattended update that failed its check, through the specialists)
86
86
  - Flourish pipeline: `flourish-input-vision` (image to spec), `flourish-input-narrative` (text to spec), `flourish-input-codebase` (HTML to spec), `flourish-architect` (spec to plan), `flourish-template-developer` (plan to SDK template, needs `@flourish/sdk`), `flourish-example-builder` (template to realistic example), `flourish-preview-runner` (multi-breakpoint preview + screenshots, needs `@flourish/sdk`), `flourish-reviewer` (audit)
package/agents/home.md CHANGED
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: home
3
- description: Watches and operates Home Assistant through the home tool, covering versions and Supervisor health, integrations that did not load, repairs, waiting updates, backups, disk space, unavailable entities, logs, updates, restarts, any Home Assistant action, and through its WebSocket, REST, and Supervisor APIs everything its own interface can read or change (entities, devices, areas, integrations, automations, scripts, helpers, dashboards, add-ons). Use for what is wrong with the smart home, why a device or integration fails, installing an update, switching or checking a device, and creating or changing automations, dashboards, and settings.
3
+ description: Watches and operates Home Assistant through the home tool, covering versions and Supervisor health, integrations that did not load, repairs, waiting updates, backups, disk space, unavailable entities, logs, updates, restarts, any Home Assistant action, and through its WebSocket, REST, and Supervisor APIs everything its own interface can read or change (entities, devices, areas, integrations, automations, scripts, helpers, dashboards, add-ons), and reads and changes its YAML configuration files. Use for what is wrong with the smart home, why a device or integration fails, installing an update, switching or checking a device, and creating or changing automations, dashboards, and settings.
4
4
  tools: home, subagent
5
5
  skills: home
6
6
  systemPromptMode: replace
@@ -10,14 +10,15 @@ maxSubagentDepth: 1
10
10
  model: openai-codex/gpt-6-astra
11
11
  thinking: xhigh
12
12
  ---
13
- You are the home specialist. The `home` tool is your only way to reach Home Assistant, which runs as a virtual machine at Mira. You have no shell, no web, and no file access; if a task needs anything else, say so and stop.
13
+ You are the home specialist. The `home` tool is your only way to reach Home Assistant, which runs as a virtual machine at Mira. You have no shell and no web, and the only files you reach are Home Assistant's YAML files through the tool's `file-` commands; if a task needs anything else, say so and stop.
14
14
 
15
15
  Rules:
16
16
 
17
17
  - Read first: `status` or `problems` before you explain or change anything. Name what you read, not what you assume.
18
18
  - A part that could not be read is a finding, never a pass. Say which part.
19
- - Change only what the task asks for. `update`, `restart`, `action`, `integration-remove`, `ws`, and every `rest` or `supervisor` call that is not a `get` ask an owner for approval in chat; say what you are about to send and why before you call them.
19
+ - Change only what the task asks for. `update`, `restart`, `action`, `integration-remove`, `ws`, `file-write`, `file-replace`, `file-restore`, `file-remove`, and every `rest` or `supervisor` call that is not a `get` ask an owner for approval in chat; say what you are about to send and why before you call them.
20
20
  - Read before you write: fetch the current automation, dashboard, or options, change only what the task names, and send the whole object back. Read it again afterwards and report what changed.
21
+ - For a YAML file, read it, change the smallest text with `file-replace`, and report the `check` result and the `backup` stamp. Never write a line that reads `[redacted]`, and never ask for `secrets.yaml`.
21
22
  - Find the cause before you restart. Read `logs core` or the add-on's log for a failing integration; a restart is the last step, not the first.
22
23
  - Never print a token, a password, or a URL that carries one; summarise such a log line.
23
24
  - Keep replies short: the finding, the cause when you know it, and the one next step. When the owner must act, start with `**Needs you:**`.
@@ -27,6 +27,8 @@ describe("approvals", () => {
27
27
  expect(isRisky("home", ["rest", "get", "/api/config"])).toBe(false);
28
28
  expect(isRisky("home", ["supervisor", "post", "/host/reboot"])).toBe(true);
29
29
  expect(isRisky("home", ["supervisor", "get", "/addons"])).toBe(false);
30
+ for (const name of ["file-write", "file-replace", "file-restore", "file-remove", "files-setup"]) expect(isRisky("home", [name, "configuration.yaml"]), name).toBe(true);
31
+ for (const name of ["file-list", "file-read", "file-backups"]) expect(isRisky("home", [name, "configuration.yaml"]), name).toBe(false);
30
32
  expect(isRisky("home", ["problems"])).toBe(false);
31
33
  expect(isRisky("home", ["logs", "core", "50"])).toBe(false);
32
34
  expect(isRisky("identity", ["zitadel", "DELETE", "/v2/users/1"])).toBe(true);
@@ -52,7 +52,7 @@ export const RISKY: Readonly<Record<string, readonly RegExp[]>> = {
52
52
  media: [/^queue-remove\b/, /^jellyfin\s+date-repair\b/],
53
53
  // Everything that changes Home Assistant: an update, a restart, any action (lights, locks, scenes), any
54
54
  // WebSocket command outside the wrapper's read list, and every REST or Supervisor call that is not a GET.
55
- home: [/^(update|restart|action|integration-remove)\b/, /^ws(\s|$)/, /^(rest|supervisor)\s+(post|put|delete)\b/],
55
+ home: [/^(update|restart|action|integration-remove|files-setup|file-(write|replace|restore|remove))\b/, /^ws(\s|$)/, /^(rest|supervisor)\s+(post|put|delete)\b/],
56
56
  };
57
57
 
58
58
  export function isRisky(service: string, args: readonly string[]): boolean {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@astrofoundry/pi-astro",
3
- "version": "0.40.72",
3
+ "version": "0.40.73",
4
4
  "description": "Personal pi customizations (extensions, subagents, skills, prompts, themes) for the pi coding agent.",
5
5
  "keywords": [
6
6
  "pi-package"
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: home
3
- description: How the home specialist reads Home Assistant's health, finds what is wrong, reads logs, installs updates, restarts Core, runs actions, and reads or changes anything else through Home Assistant's WebSocket, REST, and Supervisor APIs with the home tool.
3
+ description: How the home specialist reads Home Assistant's health, finds what is wrong, reads logs, installs updates, restarts Core, runs actions, reads or changes anything else through Home Assistant's WebSocket, REST, and Supervisor APIs, and reads or changes its YAML configuration files with the home tool.
4
4
  ---
5
5
 
6
6
  # Home specialist
@@ -28,6 +28,13 @@ Home Assistant OS runs as VM 112 `homeassistant` on SPACE-X at Mira, in the IoT
28
28
  | `["rest", "post", "/api/config/automation/config/1699999999999", "{...}"]` | any other REST call (`post`, `put`, `delete`); asks an owner |
29
29
  | `["supervisor", "get", "/addons/core_matter_server/info"]` | GET a Supervisor endpoint |
30
30
  | `["supervisor", "post", "/addons/core_matter_server/restart"]` | any other Supervisor call; asks an owner |
31
+ | `["file-list"]` | the YAML files of the configuration folder |
32
+ | `["file-read", "configuration.yaml"]` | one YAML file; a second argument is the first line to show |
33
+ | `["file-backups", "configuration.yaml"]` | the stamps of the copies kept of one file |
34
+ | `["file-replace", "configuration.yaml", "{\"old\":\"...\",\"new\":\"...\"}", "--confirm"]` | replace one exact text in a file; asks an owner |
35
+ | `["file-write", "packages/lights.yaml", "<content>", "--confirm"]` | write a whole file; asks an owner |
36
+ | `["file-restore", "configuration.yaml", "<stamp>", "--confirm"]` | put back one kept copy; asks an owner |
37
+ | `["file-remove", "packages/old.yaml", "--confirm"]` | delete a file; asks an owner |
31
38
 
32
39
  ## Output
33
40
 
@@ -41,6 +48,8 @@ Home Assistant OS runs as VM 112 `homeassistant` on SPACE-X at Mira, in the IoT
41
48
  - `update`: `{ "status": "update started", "entity" }`. The install runs in Home Assistant; read `status` again after a few minutes.
42
49
  - `restart`: `{ "status": "restart requested" }`. The tool cannot reach Home Assistant while it restarts.
43
50
  - `action`: `{ "status": "done", "action" }`.
51
+ - `file-read`: `{ "path", "lines", "from", "content", "next" }`; `next` is the line to continue from when the file is longer than one answer.
52
+ - `file-write`, `file-replace`, `file-restore`, `file-remove`: `{ "status": "written" | "replaced" | "restored" | "removed", "path", "backup", "check": "valid" }`, or `{ "status": "rolled back", "check": "invalid", "errors" }` when the change broke a valid configuration and the tool put the previous file back.
44
53
 
45
54
  ## Everything else: the three generic doors
46
55
 
@@ -64,7 +73,17 @@ Home Assistant's own web interface works through these same APIs, so what the in
64
73
  | Supervisor, system, host | `supervisor get /supervisor/info`, `/core/info`, `/os/info`, `/host/info`, `/network/info`, `/resolution/info`, `/jobs/info`, `/mounts` | `supervisor post /core/update`, `/os/update`, `/supervisor/update`, `/core/restart`, `/host/reboot`, `/host/shutdown`, `/supervisor/repair`, `/resolution/healthcheck` |
65
74
  | Templates | | `rest post /api/template {"template": "{{ states('sun.sun') }}"}` renders one; it is a POST, so it asks |
66
75
 
67
- Limits: no API reads or writes files, so `configuration.yaml` and other YAML stay with the owner (File editor add-on); run `check-config` after he changes one, then `restart`. `ws-read` knows registries, lists, history, traces, and dashboards; a read it does not know goes through `ws` and asks. Never read `backup/config/info`, `application_credentials`, or Thread credentials on your own: they hold secrets.
76
+ ## YAML files
77
+
78
+ The file commands reach the YAML files below Home Assistant's configuration folder (`configuration.yaml`, `automations.yaml`, `scripts.yaml`, `scenes.yaml`, packages, blueprints, ESPHome files) through the Advanced SSH & Web Terminal add-on. They never reach `secrets.yaml`, hidden folders such as `.storage`, or any file that is not YAML.
79
+
80
+ - Prefer the API when it covers the task: automations, scripts, and scenes made in the interface change through `rest post /api/config/<automation|script|scene>/config/<id>`, which also reloads them. Use the files for `configuration.yaml`, packages, and what only YAML can express.
81
+ - `file-read` shows the value of a secret-named key (`password`, `token`, `api_key`, ...) as `[redacted]`; a `!secret name` reference stays readable. The tool refuses to write a text that carries `[redacted]`, so never retype a masked line: change the lines around it with `file-replace`, whose `old` text must occur exactly once in the file.
82
+ - Every change keeps a copy of the previous file (`backup` is its stamp, `none` for a new file) and runs the configuration check before and after. A change that turns a valid configuration invalid is undone at once; read `errors`, fix the text, and try again. A configuration that was invalid before stays changed, and `check` reads `invalid before and after`.
83
+ - A changed file takes effect after a reload or a restart: `action homeassistant.reload_all`, the domain's own reload such as `action automation.reload`, or `restart --confirm` for what no reload covers (for example a new integration in `configuration.yaml`).
84
+ - `file-backups` lists the stamps of one file; `file-restore` puts one back and keeps a copy of the file it replaces.
85
+
86
+ Limits: `ws-read` knows registries, lists, history, traces, and dashboards; a read it does not know goes through `ws` and asks. Never read `backup/config/info`, `application_credentials`, or Thread credentials on your own: they hold secrets.
68
87
 
69
88
  ## Finding a cause
70
89
 
@@ -63,7 +63,7 @@ Wrappers ship as TypeScript and run under Node 24 type stripping: erasable synta
63
63
  - `arcane manager-upgrade <version>` (`lib/arcane-manager.ts`) follows arcane/AGENTS.md "Manager upgrades": the official image's revision label must equal the release tag's commit (GitHub API), `manager-prepare` records `compose.before.yaml` and every container before the pin commit, the pin goes through the `arcane-gitops` checkout (`git` is exported from `lib/repo.ts` for this), the wait polls `gitops list` and the deployed Compose hash every 30 s for up to 30 minutes, then pull, cold backup, `up -d --no-deps --pull never`, and checks. Any failure before the restart reverts the pin (`stopped`); a failed check after it reverts the pin and runs `manager-rollback` (`rolled back`). The answer always exits 0 with `status`, so the bridge and the agent both see it.
64
64
  - `research` is a pure forced-command wrapper: every call is one JSON request on stdin to `request` on VM 110 (`10.1.100.10`, user `spc-research`, key `SSH_KEY_SANDBOX`), whose entry hands it to `spc-research-op` as `researcher` (tracked in the homelab repository's `06-space-x-proxmox/research/system/`). The op attaches one playwright-cli session per Discord thread (`t<id>`) to the shared Chrome over CDP on `127.0.0.1:9222` and opens its own tab; cookie, storage, `run-code`, and browser lifecycle commands are refused. `script` runs the agent's code in the thread folder as `researcher` (5 minutes), on a VM that reaches only the internet (Mira's Sandbox zone plus the VM's own nftables). Defaults stay on Cortex in `work/research/defaults.json`, out of the sandbox's reach. `captcha-help` is in `RISKY`, so its owner approval is the moment the owner solved the challenge in the live view (`research-browser.37pla.net`); the bridge renders that ticket with the channel's `liveView` link.
65
65
  - `media` runs trendarr unchanged: `trendarrCli` in `media.json` is its `dist/cli.js`, started with `process.execPath` because sudo's PATH has no node. Each call gets `HOME` set to a fresh `0700` directory under `~/.specialists/work/media/` that holds only `.trendarr/config.json` (`0600`, trendarr's own schema, built from the note fields and `media.json`) and is removed in `finally`; trendarr reads no environment variables and has no config flag, and Node's `os.homedir()` follows `$HOME` on POSIX. Every call passes `--json`; `init` is refused. An add prints trendarr's per-ID `results` and exits 0 even when trendarr exits 1 for a failed ID, because the gate shows only stderr on failure; other failures carry trendarr's stderr without its `warning:` lines, which go into the JSON as `warnings`. The bridge's slash commands and Add buttons call the same wrapper through the entry point (`extensions/astro-discord/media.ts`). `queue` and `queue-remove` (since 0.40.66) skip trendarr, which has no queue records: the wrapper calls `/api/v3/queue` of Radarr and Sonarr itself with the note's keys in the `X-Api-Key` header and prints only `stuckRecords` fields (no paths or download ids); `queue-remove` sends `DELETE /api/v3/queue/<id>?removeFromClient=true&blocklist=false`, needs `--confirm`, and is in `RISKY`. The `jellyfin` commands (since 0.40.68, pure parts in `lib/media-dates.ts`) exist because Jellyfin adds a renamed or moved file as a new item: the library rename of 2026-11-10 turned 873 of 875 episodes into "added today". `date-check` reads every movie, episode, season, and series from `/Items` (one request per type without a limit, because pages of an unsorted list can overlap), Radarr's and Sonarr's files, and each app's whole history from `/api/v3/history/since`; files match by their last path segments (`pathKey`: two for a movie, three for an episode), so the mount points may differ. `planDates` follows the arcane repository's `media/AGENTS.md`: a movie or episode gets its earliest successful import (`firstArrival`; without an import record the earliest of the file's own import date and its rename and deletion records, since a file a disk scan found has none), a season and a series their earliest episode, an empty season its series; only a date more than a day late changes, so a date only ever moves back, and an item Radarr or Sonarr has no file for is reported as unmatched and left alone. `date-repair --confirm` applies the plan through Jellyfin's own `POST /Items/<id>`, the call behind its metadata editor: the item as `GET /Items/<id>?userId=<an administrator>` returns it (without a user id an API key gets 400) with only `DateCreated` changed and `People` left out, because Jellyfin rewrites people only when the request carries them; a test on one episode showed only `DateCreated` and `Etag` differing afterwards. Jellyfin keeps running, and five failed updates stop the run. The API key travels as `Authorization: MediaBrowser Token="<key>"`, the scheme of the server's own `/api-docs/openapi.json` (12.4.0). `bazarr status` reads `/api/system/status` and `/api/system/health` with `X-API-KEY` and prints versions and issues only; the Sonarr and Radarr versions Bazarr reports show that it reaches them. Both read their own config shape (`jellyfinUrl`, `bazarrUrl`), so the trendarr commands run without those keys.
66
- - `home` (since 0.40.70) reaches Home Assistant, VM 112 on SPACE-X at Mira (`homeAssistantUrl` in `home.json`, token `HOMEASSISTANT_TOKEN`), which replaced a Raspberry Pi with a failing SD card on 2026-11-12. `lib/home-assistant.ts` opens the WebSocket API (`/api/websocket`: `auth_required`, `auth` with the token, `auth_ok`), sends commands with ids, and closes; the wrapper runs on the installer's Node, which has a global `WebSocket`. The Supervisor's state (`/supervisor/info`, `/core/info`, `/os/info`, `/host/info`, `/resolution/info`, `/addons`) is reachable only through the `supervisor/api` command, because Core's REST proxy (`/api/hassio/...`) forwards logs and backups and nothing else (`PATHS_ADMIN` in Core's `hassio/http.py`, read at tag 2026.11.1); `logs` uses that proxy with `?lines=`. `status` prints named fields only (`pick`), so add-on options and addresses stay inside. `homeProblems` turns a snapshot into one line per finding: Core not running, safe or recovery mode, an unhealthy or unsupported Supervisor, its resolution issues, integrations that did not load (`setup_error`, `setup_retry`, ...), open repairs, waiting `update.*` entities, a newest backup older than 48 hours or failed for a location, a disk above 85 %; a part that could not be read is a line too (`unread`), never a pass. `update`, `restart`, `action` (any Home Assistant action with `target` and `data`), and `integration-remove` (since 0.40.71: `DELETE /api/config/config_entries/entry/<id>`, for leftovers such as the Pi's Bluetooth adapter after the move to a VM) change things and are in `RISKY`; all but `action` also need `--confirm`. Since 0.40.72 three generic doors reach everything Home Assistant's own interface can do, the model of the community's ha-mcp server without a second server that holds an administrator token: `ws <type> [json]` (any WebSocket command), `rest <get|post|put|delete> <path> [json]` (any route under `/api/`; dot segments, escapes, and `/api/websocket` refused), and `supervisor <get|post|put|delete> <endpoint> [json]` (through `supervisor/api`; logs and downloads refused because they are not JSON). Reads need no approval: `rest get`, `supervisor get`, and `ws-read`, which sends only the types in `READ_COMMANDS` of `lib/home-assistant.ts` (registries, lists, history, traces, dashboards, the helpers' `<domain>/list`; never `backup/config/info`, `application_credentials`, or `auth`, which return credentials). Everything else is in `RISKY` (`/^ws(\s|$)/` so that `ws-read` stays free). Generic answers pass `redactSecrets` and `bounded` (60,000 characters; a list keeps its first items). `restart` treats a connection Core closes as started, because Core often closes the socket before it sends the result. No Home Assistant API reads or writes files: YAML edits stay with the owner (ha-mcp needs its own component inside Home Assistant for that). The skill's table of commands was checked against Core 2026.11.1 and the Supervisor's route table. Arguments are checked before config and secret are read. The agent has no `read` tool. The morning run reads `home problems` (`homeStatus` in `daily-run.ts`): each line is an item under Home, and the tagged message posts once per set of problems. Cortex reaches `10.1.70.32:8123` through the policies `Home Assistant - from Cortex` on both consoles.
66
+ - `home` (since 0.40.70) reaches Home Assistant, VM 112 on SPACE-X at Mira (`homeAssistantUrl` in `home.json`, token `HOMEASSISTANT_TOKEN`), which replaced a Raspberry Pi with a failing SD card on 2026-11-12. `lib/home-assistant.ts` opens the WebSocket API (`/api/websocket`: `auth_required`, `auth` with the token, `auth_ok`), sends commands with ids, and closes; the wrapper runs on the installer's Node, which has a global `WebSocket`. The Supervisor's state (`/supervisor/info`, `/core/info`, `/os/info`, `/host/info`, `/resolution/info`, `/addons`) is reachable only through the `supervisor/api` command, because Core's REST proxy (`/api/hassio/...`) forwards logs and backups and nothing else (`PATHS_ADMIN` in Core's `hassio/http.py`, read at tag 2026.11.1); `logs` uses that proxy with `?lines=`. `status` prints named fields only (`pick`), so add-on options and addresses stay inside. `homeProblems` turns a snapshot into one line per finding: Core not running, safe or recovery mode, an unhealthy or unsupported Supervisor, its resolution issues, integrations that did not load (`setup_error`, `setup_retry`, ...), open repairs, waiting `update.*` entities, a newest backup older than 48 hours or failed for a location, a disk above 85 %; a part that could not be read is a line too (`unread`), never a pass. `update`, `restart`, `action` (any Home Assistant action with `target` and `data`), and `integration-remove` (since 0.40.71: `DELETE /api/config/config_entries/entry/<id>`, for leftovers such as the Pi's Bluetooth adapter after the move to a VM) change things and are in `RISKY`; all but `action` also need `--confirm`. Since 0.40.72 three generic doors reach everything Home Assistant's own interface can do, the model of the community's ha-mcp server without a second server that holds an administrator token: `ws <type> [json]` (any WebSocket command), `rest <get|post|put|delete> <path> [json]` (any route under `/api/`; dot segments, escapes, and `/api/websocket` refused), and `supervisor <get|post|put|delete> <endpoint> [json]` (through `supervisor/api`; logs and downloads refused because they are not JSON). Reads need no approval: `rest get`, `supervisor get`, and `ws-read`, which sends only the types in `READ_COMMANDS` of `lib/home-assistant.ts` (registries, lists, history, traces, dashboards, the helpers' `<domain>/list`; never `backup/config/info`, `application_credentials`, or `auth`, which return credentials). Everything else is in `RISKY` (`/^ws(\s|$)/` so that `ws-read` stays free). Generic answers pass `redactSecrets` and `bounded` (60,000 characters; a list keeps its first items). `restart` treats a connection Core closes as started, because Core often closes the socket before it sends the result. No Home Assistant API reads or writes files (ha-mcp needs its own component inside Home Assistant for that), so the `file-` commands (since 0.40.73, pure parts in `lib/home-files.ts`) go through the Advanced SSH & Web Terminal add-on (`a0d7b954_ssh`, port 22 on the host network): `files-setup` adds one `authorized_keys` line, `restrict,command="sudo -n /usr/local/bin/spc-home-entry \"$SSH_ORIGINAL_COMMAND\""`, and one `init_commands` line that writes the entry script, because the add-on copies `authorized_keys` lines verbatim and evaluates `init_commands` at every start (`init-ssh/run`, `init-user/run` of hassio-addons/app-ssh, read 2026-11-12); the owner's other options go back unchanged and are never printed, and `--no-password` empties the SSH password, which turns password login off. The script (`entry/remote/spc-home-entry.sh`, embedded as `ENTRY_SCRIPT`; a test compares them and runs it) serves YAML paths below `/homeassistant` without hidden folders, dot segments, or `secrets.yaml`, and copies the current file to `.spc-home-backups/<path>.<UTC stamp>` before every write, restore, and removal, under a stamp no copy has yet. The wrapper reads the add-on's port and user name from `/addons/a0d7b954_ssh/info`, masks secret-named values in `file-read` (`redactYaml`; a mask, not a boundary), refuses to write a text that carries `[redacted]`, and wraps every change in two configuration checks (`changeChecked`): a change that turns a valid configuration invalid is restored from the kept copy, one made while it was already invalid stays. The four changing commands and `files-setup` are in `RISKY`. The skill's table of commands was checked against Core 2026.11.1 and the Supervisor's route table. Arguments are checked before config and secret are read. The agent has no `read` tool. The morning run reads `home problems` (`homeStatus` in `daily-run.ts`): each line is an item under Home, and the tagged message posts once per set of problems. Cortex reaches `10.1.70.32` on TCP 8123, 4357, and 22 through the policies `Home Assistant at Mira - from Cortex` on both consoles.
67
67
  - `arcane release-notes <stack>[/<service>]` is `lib/releases.ts`: a single-image check and `resolveRef` give the running and latest versions, `HttpRegistry.labels` reads `org.opencontainers.image.source` from the latest image (index to linux/amd64 manifest to config blob), and the anonymous GitHub releases API (60 requests an hour, up to 3 pages of 100) gives the releases in between, oldest first. `condenseNotes` keeps each release under 12,000 characters by section priority; `capTotal` drops the oldest releases past 40,000 characters in total.
68
68
 
69
69
  ## Gate
@@ -15,7 +15,7 @@ A specialist is a Pi subagent that is the only way to operate one area of the ho
15
15
  | `astro.inference` | MLX embedding and reranking servers on Nexus, Europa health | `nexus-status|start|stop|restart|log|disk`, `macos-updates`; `europa-health` |
16
16
  | `astro.media` | trendarr over TMDB, OMDb, and the `media` project on VM 100 (Radarr, Sonarr, SABnzbd, Jellyfin, Bazarr) | `trending`, `search`, `recommend`, `add-movies`, `add-series` (at most 20 IMDb IDs), `sabnzbd status|pause|resume`, `queue`, `queue-remove <radarr|sonarr> <id> --confirm`, `jellyfin status|date-check`, `jellyfin date-repair --confirm`, `bazarr status`; trendarr's JSON plus its warnings, the queue, Jellyfin, and Bazarr commands straight from those apps |
17
17
  | `astro.research` | the research sandbox, VM 110 at Mira (Chrome on a virtual screen, scripts, thread folders), through the forced-command key of user `spc-research`; defaults in `~/.specialists/work/research/defaults.json` | `browser <session> <playwright-cli args>`, `captcha`, `captcha-help` (owner approval: solved in the live view), `script`, `read`, `files`, `toolbox`, `defaults list|set|unset`; the sandbox's JSON |
18
- | `astro.home` | Home Assistant at Mira (VM 112 on SPACE-X, `10.1.70.32:8123`), through its WebSocket API and log routes with a long-lived access token | `status`, `problems`, `entities`, `logs <core\|supervisor\|host\|addon <slug>>`, `integrations`, `check-config`, `ws-read <type> [json]`, `rest get <path>`, `supervisor get <endpoint>`; with approval `integration-remove <entry_id> --confirm`, `update <update.entity> --confirm`, `restart --confirm`, `action <domain.action> [json]`, `ws <type> [json]`, `rest <post\|put\|delete> <path> [json]`, `supervisor <post\|put\|delete> <endpoint> [json]`; generic answers are redacted and cut to 60,000 characters |
18
+ | `astro.home` | Home Assistant at Mira (VM 112 on SPACE-X, `10.1.70.32:8123`), through its WebSocket API and log routes with a long-lived access token | `status`, `problems`, `entities`, `logs <core\|supervisor\|host\|addon <slug>>`, `integrations`, `check-config`, `ws-read <type> [json]`, `rest get <path>`, `supervisor get <endpoint>`; with approval `integration-remove <entry_id> --confirm`, `update <update.entity> --confirm`, `restart --confirm`, `action <domain.action> [json]`, `ws <type> [json]`, `rest <post\|put\|delete> <path> [json]`, `supervisor <post\|put\|delete> <endpoint> [json]`; generic answers are redacted and cut to 60,000 characters. YAML files through a forced-command key in the Advanced SSH & Web Terminal add-on: `file-list`, `file-read`, `file-backups`; with approval `file-write`, `file-replace`, `file-restore`, `file-remove`, each with a kept copy and a configuration check; never `secrets.yaml` or hidden folders |
19
19
 
20
20
  Call one with `/run astro.<name> -- <task>` or through the `subagent` tool (both from the bundled `astro-subagents` extension). `/run` saves the specialist's session under `~/.pi/agent/subagent-sessions/<agent>/`; `/run astro.<name> --continue -- <task>` resumes the last one started from the same directory, so the specialist keeps what it saw. Sessions older than 7 days are deleted. Specialists may call each other once (`maxSubagentDepth: 1`). They run on `openai-codex/gpt-6-astra` with `xhigh` thinking, set by `model` and `thinking` in each `agents/<name>.md`; an agent without these fields inherits the caller's model and thinking. Each tool takes `args`, an array of strings; `["--help"]` lists the subcommands.
21
21
 
@@ -45,7 +45,7 @@ Host: Cortex (macOS on Apple silicon; Homebrew git; the specialists' Node, trend
45
45
  - `proxmox`: `PVE_TOKEN_ID` (plain, `spc-proxmox@pve!cortex`), `PVE_TOKEN_SECRET`, `PVE_SPACEX_TOKEN_ID` and `PVE_SPACEX_TOKEN_SECRET` (the same user on SPACE-X), `SSH_KEY_PULSAR_B64` (trusted by Pulsar and SPACE-X). `proxmox.json` also needs `spacexApiUrl`, `spacexCertSha256`, `spacexNode`, `spacexHost`, `spacexUser`, and `known_hosts` the SPACE-X host key.
46
46
  - `inference`: `SSH_KEY_NEXUS_B64`.
47
47
  - `media`: `TMDB_ACCESS_TOKEN` (TMDB API Read Access Token), `OMDB_API_KEY`, `RADARR_API_KEY`, `SONARR_API_KEY` (Settings, General, Security; each app has one), `SABNZBD_API_KEY` (the API key, not the NZB key, which can only add NZBs and cannot read or pause the queue), `JELLYFIN_API_KEY` (Jellyfin's Dashboard, API Keys, New API Key; only the `jellyfin` commands read it), `BAZARR_API_KEY` (Bazarr's Settings, General, Security, API Key; only `bazarr status` reads it).
48
- - `home`: `HOMEASSISTANT_TOKEN` (a long-lived access token of an administrator: Home Assistant, User profile, Security, Long-lived access tokens).
48
+ - `home`: `HOMEASSISTANT_TOKEN` (a long-lived access token of an administrator: Home Assistant, User profile, Security, Long-lived access tokens), `SSH_KEY_HOME_B64` (the key of the file commands).
49
49
  2. **Identities.** Zitadel (`https://auth.37pla.net/ui/console`): service user `spc-arcane` with Access Token Type JWT and a JSON key; service user `spc-identity` with a Personal Access Token and the Instance Owner role. Technitium (cluster primary): user `spc-dns` in the Administrators group with an API token; the cluster syncs the user to every node. Cloudflare: an account-owned API token with `Zone:Read` and `DNS:Edit` on both zones. GCP project `frontdoor-1337`: service account `spc-edge` with `roles/iap.tunnelResourceAccessor` and `roles/compute.viewer`, JSON key. Proxmox (`ssh pulsar`): user `spc-proxmox@pve`, role `SpecialistGuest` = `VM.Audit VM.PowerMgmt VM.Snapshot VM.Snapshot.Rollback VM.Config.CPU VM.Config.Memory VM.Config.Options VM.Config.Network VM.Config.CDROM VM.GuestAgent.Audit`, ACLs `PVEAuditor` on `/` and `SpecialistGuest` on `/vms` for both the user and the token `spc-proxmox@pve!cortex` (`-privsep 1`).
50
50
  3. **Services.** Arcane (Settings, Authentication, Federated Credentials): Issuer `https://auth.37pla.net`, Audience `387825541182390275`, Subject exact = `spc-arcane` user ID, Role Admin, Global, lifetime 300. UniFi: the account key and a local key per console (fields above) and policies on 37 allowing Cortex `10.0.40.37` to TCP 22 on `10.0.20.10`, `10.0.10.37`, `10.0.90.10`, TCP 5380 on `10.0.40.53`, TCP 8006 on `10.0.10.37`, TCP 8081 on `10.0.60.5`, TCP 443 on the Mira console `10.1.60.1`, and TCP 22 and 8006 on SPACE-X `10.1.10.37` (that one also on Mira); the homelab `03-cortex-macmini/README.md` lists them with their ids. GitHub: `spc-arcane-gitops` as a write deploy key on `astronaute77/arcane`, `spc-edge-homelab` and `spc-identity-homelab` as write deploy keys on `astronaute77/homelab`.
51
51
  4. **Sudo and user**, as an administrator:
@@ -124,6 +124,7 @@ Host: Cortex (macOS on Apple silicon; Homebrew git; the specialists' Node, trend
124
124
  - Pulsar, root, two more keys: `spc-backup-pulsar-entry.sh`, `spc-proxmox-pulsar-entry.sh` (tracked in `02-pulsar-proxmox/pulsar/system/`).
125
125
  - SPACE-X, root: `spc-proxmox-spacex-entry.sh` for the same proxmox key (tracked in `06-space-x-proxmox/system/`).
126
126
  - Synapse, Pulsar, and SPACE-X, root: the dns node key, forced to `spc-dns-node-entry.sh` with the node as its argument: `local` on Synapse (technitium1), `pct:107` on Pulsar (technitium2), `pct:100` on SPACE-X (technitium3) (tracked in `01-synapse-dns/system/`).
127
+ - Home Assistant (VM 112 on SPACE-X): no manual install. `specialist-cli home -- files-setup "<public key>" [--no-password] --confirm` writes the key, bound to `spc-home-entry.sh`, and the script itself into the options of the Advanced SSH & Web Terminal add-on, sets the add-on to start at boot, and starts it. The add-on rewrites both at every start. The policies `Home Assistant at Mira - from Cortex` must allow TCP 22.
127
128
  - VM 100, user `arcane`: `spc-backup-arcane-entry.sh` (tracked as `host/spc-backup-arcane-entry` in the `astronaute77/arcane` repository, next to the host backup scripts).
128
129
  - VM 100, user `spc-arcane` (no docker group): `spc-arcane-host-entry.sh` hands each command to the root-owned `spc-arcane-op.py` (installed as `/usr/local/sbin/spc-arcane-op`), the only command `spc-arcane-sudoers` allows; it runs the reviewed probes from `/usr/local/lib/spc-arcane` and the fixed manager and database steps. `spc-arcane-install.sh` creates the user and installs all of it from `/tmp/spc-arcane`; the files are tracked under `host/` in the arcane repository, the probes under `host/spc-arcane-probes/` (moved from the arcane-ops CLI, retired on 2026-10-19). Add `"hostAddress": "10.0.40.30", "hostUser": "spc-arcane"` to `arcane.json`; other arcane commands do not read them.
129
130
  - Nexus, user `nexus`: `spc-inference-nexus-entry.sh` as `/usr/local/sbin/spc-inference-nexus-entry` (tracked in `04-nexus-macstudio/system/`).
@@ -161,6 +162,6 @@ The `astro-discord` extension gives Discord users access to the specialists from
161
162
 
162
163
  ## Rotation and operations
163
164
 
164
- Rotation steps for every field live in the homelab repository, `03-cortex-macmini/ROTATION.md`. After any change in Vaultwarden run `specialist-cli provision`. Host state and the sudo rules are documented in `03-cortex-macmini/README.md`; the forced-command scripts are tracked under `02-pulsar-proxmox/dmz/system/`, `02-pulsar-proxmox/pulsar/system/`, `06-space-x-proxmox/system/`, `01-synapse-dns/system/`, `02-pulsar-proxmox/observability/system/`, `host/` of the `astronaute77/arcane` repository, `04-nexus-macstudio/system/`, and `00-frontdoor-vps/system/`.
165
+ Rotation steps for every field live in the homelab repository, `03-cortex-macmini/ROTATION.md`. After any change in Vaultwarden run `specialist-cli provision`. Host state and the sudo rules are documented in `03-cortex-macmini/README.md`; the forced-command scripts are tracked under `02-pulsar-proxmox/dmz/system/`, `02-pulsar-proxmox/pulsar/system/`, `06-space-x-proxmox/system/`, `01-synapse-dns/system/`, `02-pulsar-proxmox/observability/system/`, `host/` of the `astronaute77/arcane` repository, `04-nexus-macstudio/system/`, `06-space-x-proxmox/homeassistant/system/`, and `00-frontdoor-vps/system/`.
165
166
 
166
167
  All twelve specialists exist. See `AGENTS.md` for how to add one.
@@ -0,0 +1,93 @@
1
+ #!/bin/sh
2
+ # spc-home-entry: forced command of the home specialist's key inside the
3
+ # "Advanced SSH & Web Terminal" add-on of Home Assistant. The add-on's
4
+ # init_commands write this file at every start; the key's authorized_keys line
5
+ # runs it through sudo with the requested command as one argument.
6
+ # It serves YAML files below /homeassistant: no hidden folders (so never
7
+ # .storage), no dot segments, never secrets.yaml. Every change first copies the
8
+ # current file to .spc-home-backups/<path>.<UTC stamp>.
9
+ set -eu
10
+ set -f
11
+ root=/homeassistant
12
+ backups=$root/.spc-home-backups
13
+ # shellcheck disable=SC2086
14
+ set -- ${1:-}
15
+ op=${1:-}
16
+ path=${2:-}
17
+ stamp=${3:-}
18
+ valid() {
19
+ case "$1" in "" | /* | .* | */.* | *..* | *//* | *[!A-Za-z0-9_./-]*) return 1 ;; esac
20
+ case "$1" in *.yaml | *.yml) ;; *) return 1 ;; esac
21
+ case "$1" in secrets.yaml | */secrets.yaml) return 1 ;; esac
22
+ return 0
23
+ }
24
+ refuse() {
25
+ echo "spc-home-entry: $1" >&2
26
+ exit 2
27
+ }
28
+ args() {
29
+ [ "$1" -eq "$2" ] || refuse "usage: list | read <path> | backups <path> | write <path> | restore <path> <stamp> | remove <path>"
30
+ }
31
+ # Copies the current file aside under a stamp that no backup of it has yet.
32
+ keep() {
33
+ if [ ! -f "$root/$path" ]; then
34
+ echo "backup none"
35
+ return 0
36
+ fi
37
+ mkdir -p "$(dirname "$backups/$path")"
38
+ now=$(date -u +%Y%m%dT%H%M%SZ)
39
+ while [ -e "$backups/$path.$now" ]; do
40
+ sleep 1
41
+ now=$(date -u +%Y%m%dT%H%M%SZ)
42
+ done
43
+ cp -p -- "$root/$path" "$backups/$path.$now"
44
+ echo "backup $now"
45
+ }
46
+ case "$op" in
47
+ list)
48
+ args $# 1
49
+ cd "$root"
50
+ find . -maxdepth 6 -type f \( -name '*.yaml' -o -name '*.yml' \) ! -path '*/.*' ! -name secrets.yaml | sed 's|^\./||' | sort
51
+ ;;
52
+ read)
53
+ args $# 2
54
+ valid "$path" || refuse "refused path"
55
+ [ -f "$root/$path" ] || refuse "no such file: $path"
56
+ cat -- "$root/$path"
57
+ ;;
58
+ backups)
59
+ args $# 2
60
+ valid "$path" || refuse "refused path"
61
+ dir=$(dirname "$backups/$path")
62
+ [ -d "$dir" ] || exit 0
63
+ find "$dir" -maxdepth 1 -type f | sed -n "s|^.*/$(basename "$path")\.\([0-9]\{8\}T[0-9]\{6\}Z\)$|\1|p" | sort
64
+ ;;
65
+ write)
66
+ args $# 2
67
+ valid "$path" || refuse "refused path"
68
+ mkdir -p "$(dirname "$root/$path")"
69
+ keep
70
+ cat > "$root/$path.spc-tmp"
71
+ mv -- "$root/$path.spc-tmp" "$root/$path"
72
+ ;;
73
+ restore)
74
+ args $# 3
75
+ valid "$path" || refuse "refused path"
76
+ case "$stamp" in [0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]T[0-9][0-9][0-9][0-9][0-9][0-9]Z) ;; *) refuse "refused stamp" ;; esac
77
+ [ -f "$backups/$path.$stamp" ] || refuse "no such backup: $path $stamp"
78
+ mkdir -p "$(dirname "$root/$path")"
79
+ keep
80
+ cp -p -- "$backups/$path.$stamp" "$root/$path.spc-tmp"
81
+ mv -- "$root/$path.spc-tmp" "$root/$path"
82
+ ;;
83
+ remove)
84
+ args $# 2
85
+ valid "$path" || refuse "refused path"
86
+ [ -f "$root/$path" ] || refuse "no such file: $path"
87
+ keep
88
+ rm -- "$root/$path"
89
+ ;;
90
+ *)
91
+ args 0 1
92
+ ;;
93
+ esac
@@ -1,11 +1,16 @@
1
+ import { join } from "node:path";
1
2
  import { readConfig } from "../lib/config.ts";
2
3
  import { ServiceError, UsageError } from "../lib/errors.ts";
3
4
  import { backupSummary, bounded, diskUse, entitiesIn, failedIntegrations, haSession, homeProblems, integrationRows, isReadCommand, openRepairs, pendingUpdates, tailLines } from "../lib/home-assistant.ts";
4
5
  import type { HaCall, HomeSnapshot } from "../lib/home-assistant.ts";
6
+ import { REDACTED, SSH_ADDON, isPublicKey, isStamp, isYamlPath, pageLines, redactYaml, replaceOnce, withFileAccess } from "../lib/home-files.ts";
5
7
  import { main } from "../lib/main.ts";
6
8
  import { printJson, printRaw } from "../lib/output.ts";
9
+ import { specialistsHome } from "../lib/paths.ts";
7
10
  import { redactSecrets } from "../lib/sanitize.ts";
8
- import { readSecret } from "../lib/secrets.ts";
11
+ import { readSecret, secretPath } from "../lib/secrets.ts";
12
+ import { sshFixed } from "../lib/ssh.ts";
13
+ import type { SshTarget } from "../lib/ssh.ts";
9
14
 
10
15
  const SERVICE = "home";
11
16
 
@@ -44,6 +49,11 @@ const HELP = `home specialist (Home Assistant at Mira, through its WebSocket API
44
49
  ws-read <type> [json] a WebSocket command that only reads: registries, lists, history, traces, dashboards
45
50
  rest get <path> GET any route under /api/
46
51
  supervisor get <endpoint> GET a Supervisor endpoint, such as /addons/core_matter_server/info
52
+ file-list the YAML files of the configuration folder
53
+ file-read <path> [first line]
54
+ one YAML file, such as configuration.yaml or packages/lights.yaml; values of
55
+ secret-named keys read as ${REDACTED}, and a long file continues from "next"
56
+ file-backups <path> the stamps of the copies kept of one file
47
57
 
48
58
  Changes; each needs an owner's approval in chat:
49
59
  integration-remove <entry_id> --confirm
@@ -58,7 +68,21 @@ Changes; each needs an owner's approval in chat:
58
68
  any other call under /api/, such as /api/config/automation/config/<id>
59
69
  supervisor <post|put|delete> <endpoint> [json]
60
70
  any other Supervisor call, such as /addons/<slug>/restart or /host/reboot
61
-
71
+ file-replace <path> <json> --confirm
72
+ replace one exact text in a YAML file: {"old": "...", "new": "..."}
73
+ file-write <path> <content> --confirm
74
+ write a whole YAML file
75
+ file-restore <path> <stamp> --confirm
76
+ put back one of the copies file-backups lists
77
+ file-remove <path> --confirm
78
+ delete a YAML file
79
+ files-setup <public key> [--no-password] --confirm
80
+ bind the specialist's SSH key to the file commands in the SSH add-on and start
81
+ it at boot; --no-password also turns the add-on's password login off
82
+
83
+ A file change keeps a copy of the previous file and runs check-config before and after; a change that makes
84
+ a valid configuration invalid is undone. It takes effect after a reload or a restart. The file commands never
85
+ reach secrets.yaml or hidden folders such as .storage.
62
86
  Answers longer than ${MAX_ANSWER_CHARS} characters are cut, and values under secret-looking keys are redacted.`;
63
87
 
64
88
  /** The Supervisor's answer to a call, through Core's `supervisor/api` command. */
@@ -282,7 +306,157 @@ function answer(value: unknown): unknown {
282
306
  return bounded(redactSecrets(value), MAX_ANSWER_CHARS);
283
307
  }
284
308
 
285
- const COMMANDS = ["status", "problems", "entities", "integrations", "integration-remove", "logs", "check-config", "update", "restart", "action", "ws-read", "ws", "rest", "supervisor"];
309
+ const FILE_COMMANDS = ["file-list", "file-read", "file-backups", "file-write", "file-replace", "file-restore", "file-remove", "files-setup"];
310
+ const COMMANDS = ["status", "problems", "entities", "integrations", "integration-remove", "logs", "check-config", "update", "restart", "action", "ws-read", "ws", "rest", "supervisor", ...FILE_COMMANDS];
311
+ const FILE_USAGE: Record<string, string> = {
312
+ "file-write": "file-write <path> <content> --confirm",
313
+ "file-replace": 'file-replace <path> {"old": "...", "new": "..."} --confirm',
314
+ "file-restore": "file-restore <path> <stamp> --confirm",
315
+ "file-remove": "file-remove <path> --confirm",
316
+ "files-setup": "files-setup <public key> [--no-password] --confirm",
317
+ };
318
+
319
+ export type FileCommand =
320
+ | { op: "list" }
321
+ | { op: "read"; path: string; from: number }
322
+ | { op: "backups"; path: string }
323
+ | { op: "write"; path: string; content: string }
324
+ | { op: "replace"; path: string; old: string; replacement: string }
325
+ | { op: "restore"; path: string; stamp: string }
326
+ | { op: "remove"; path: string }
327
+ | { op: "setup"; publicKey: string; keepPassword: boolean };
328
+
329
+ function yamlPath(path: string | undefined, usage: string): string {
330
+ if (path === undefined || !isYamlPath(path)) throw new UsageError(`${usage}: the path must be a YAML file below the configuration folder, not hidden, and not secrets.yaml`);
331
+ return path;
332
+ }
333
+
334
+ function unmasked(text: string, usage: string): string {
335
+ if (text.includes(REDACTED)) throw new UsageError(`${usage}: the text carries ${REDACTED}, a value file-read masked; change the lines around it with file-replace`);
336
+ return text;
337
+ }
338
+
339
+ /** The file commands; every one that changes something needs `--confirm`. */
340
+ export function parseFileCommand(name: string, args: string[]): FileCommand {
341
+ if (name === "file-list") {
342
+ if (args.length > 0) throw new UsageError("file-list takes no arguments");
343
+ return { op: "list" };
344
+ }
345
+ if (name === "file-read") {
346
+ if (args.length < 1 || args.length > 2) throw new UsageError("file-read <path> [first line]");
347
+ return { op: "read", path: yamlPath(args[0], "file-read <path> [first line]"), from: parseCount(args[1], "the first line", 10_000_000, 1) };
348
+ }
349
+ if (name === "file-backups") {
350
+ if (args.length !== 1) throw new UsageError("file-backups <path>");
351
+ return { op: "backups", path: yamlPath(args[0], "file-backups <path>") };
352
+ }
353
+ const usage = FILE_USAGE[name];
354
+ if (usage === undefined) throw new UsageError(`unknown command: ${name}`);
355
+ const rest = confirmed(args, usage);
356
+ if (name === "files-setup") {
357
+ const key = rest.filter((a) => a !== "--no-password");
358
+ if (key.length !== 1 || !isPublicKey(key[0])) throw new UsageError(`${usage}: give one ssh-ed25519 public key line`);
359
+ return { op: "setup", publicKey: key[0], keepPassword: key.length === rest.length };
360
+ }
361
+ const path = yamlPath(rest[0], usage);
362
+ if (name === "file-remove") {
363
+ if (rest.length !== 1) throw new UsageError(usage);
364
+ return { op: "remove", path };
365
+ }
366
+ if (rest.length !== 2) throw new UsageError(usage);
367
+ if (name === "file-restore") {
368
+ if (!isStamp(rest[1])) throw new UsageError(`${usage}: a stamp looks like 20261112T101500Z`);
369
+ return { op: "restore", path, stamp: rest[1] };
370
+ }
371
+ if (name === "file-write") return { op: "write", path, content: unmasked(rest[1], usage) };
372
+ const change = record(parseJson(rest[1]), "the change");
373
+ if (typeof change?.old !== "string" || typeof change.new !== "string" || Object.keys(change).length !== 2) throw new UsageError(usage);
374
+ return { op: "replace", path, old: unmasked(change.old, usage), replacement: unmasked(change.new, usage) };
375
+ }
376
+
377
+ interface AddonInfo {
378
+ state?: unknown;
379
+ network?: Record<string, unknown> | null;
380
+ options?: { ssh?: { username?: unknown } };
381
+ }
382
+
383
+ /** One entry-script command; `input` becomes the remote command's stdin. */
384
+ type Entry = (remote: string, input?: string) => Promise<string>;
385
+
386
+ /** Entry-script calls through the specialist's key. The add-on tells its own port and user, once per process. */
387
+ function fileEntry(config: HomeConfig, call: HaCall): Entry {
388
+ let target: SshTarget | null = null;
389
+ return async (remote, input) => {
390
+ if (target === null) {
391
+ const info = (await supervisorCall(call, "get", `/addons/${SSH_ADDON}/info`)) as AddonInfo | null;
392
+ const port = info?.network?.["22/tcp"];
393
+ const user = info?.options?.ssh?.username;
394
+ if (info?.state !== "started") throw new ServiceError("the SSH add-on is not started; an owner runs files-setup first");
395
+ if (typeof port !== "number" || typeof user !== "string") throw new ServiceError("the SSH add-on reports no port or user name");
396
+ // The add-on lower-cases the user name before it creates the account (`init-ssh/run`).
397
+ target = { host: new URL(config.homeAssistantUrl).hostname, user: user.toLowerCase(), port, keyFile: secretPath(SERVICE, "SSH_KEY_HOME"), knownHostsFile: join(specialistsHome(), "config", "known_hosts") };
398
+ }
399
+ const result = await sshFixed(target, remote, 60_000, input);
400
+ if (result.code !== 0) throw new ServiceError(`the file command failed: ${(result.stderr.trim().split("\n").at(-1) ?? "").slice(0, 300) || `exit ${result.code}`}`);
401
+ return result.stdout;
402
+ };
403
+ }
404
+
405
+ async function configValid(config: HomeConfig, token: string): Promise<{ valid: boolean; errors: string | null }> {
406
+ const check = (await restRequest(config, token, "post", "/api/config/core/check_config")).body as { result?: unknown; errors?: unknown } | null;
407
+ return { valid: check?.result === "valid", errors: typeof check?.errors === "string" ? check.errors.slice(0, 1500) : null };
408
+ }
409
+
410
+ /**
411
+ * Runs one changing entry command between two configuration checks. A change that turns a valid configuration
412
+ * invalid is undone from the copy the entry script kept; one made while the configuration was already invalid
413
+ * stays, because it may be part of the repair.
414
+ */
415
+ async function changeChecked(run: Entry, config: HomeConfig, token: string, status: string, path: string, remote: string, input?: string): Promise<Record<string, unknown>> {
416
+ const before = await configValid(config, token);
417
+ const backup = /^backup (\S+)$/m.exec(await run(remote, input))?.[1];
418
+ if (backup === undefined) throw new ServiceError("the entry script named no backup");
419
+ const after = await configValid(config, token);
420
+ if (after.valid) return { status, path, backup, check: "valid" };
421
+ if (!before.valid) return { status, path, backup, check: "invalid before and after", errors: after.errors };
422
+ await run(backup === "none" ? `remove ${path}` : `restore ${path} ${backup}`);
423
+ return { status: "rolled back", path, check: "invalid", errors: after.errors };
424
+ }
425
+
426
+ function wait(ms: number): Promise<void> {
427
+ return new Promise((resolve) => setTimeout(resolve, ms));
428
+ }
429
+
430
+ async function fileCommand(config: HomeConfig, token: string, call: HaCall, cmd: FileCommand): Promise<Record<string, unknown>> {
431
+ const run = fileEntry(config, call);
432
+ const lines = (text: string): string[] => text.split("\n").filter((l) => l.length > 0);
433
+ if (cmd.op === "list") return { files: lines(await run("list")) };
434
+ if (cmd.op === "read") return { path: cmd.path, ...pageLines(redactYaml(await run(`read ${cmd.path}`)), cmd.from, MAX_ANSWER_CHARS) };
435
+ if (cmd.op === "backups") return { path: cmd.path, backups: lines(await run(`backups ${cmd.path}`)) };
436
+ if (cmd.op === "write") return changeChecked(run, config, token, "written", cmd.path, `write ${cmd.path}`, cmd.content);
437
+ if (cmd.op === "replace") {
438
+ const changed = replaceOnce(await run(`read ${cmd.path}`), cmd.old, cmd.replacement);
439
+ if (typeof changed !== "string") throw new ServiceError(`${cmd.path}: ${changed.error}`);
440
+ return changeChecked(run, config, token, "replaced", cmd.path, `write ${cmd.path}`, changed);
441
+ }
442
+ if (cmd.op === "restore") return changeChecked(run, config, token, "restored", cmd.path, `restore ${cmd.path} ${cmd.stamp}`);
443
+ if (cmd.op === "remove") return changeChecked(run, config, token, "removed", cmd.path, `remove ${cmd.path}`);
444
+ // The add-on's options hold the owner's keys and password: they go back to the Supervisor and are never printed.
445
+ const info = (await supervisorCall(call, "get", `/addons/${SSH_ADDON}/info`)) as (AddonInfo & { options?: unknown }) | null;
446
+ const started = info?.state === "started";
447
+ await supervisorCall(call, "post", `/addons/${SSH_ADDON}/options`, { options: withFileAccess(info?.options, cmd.publicKey, cmd.keepPassword), boot: "auto" });
448
+ await supervisorCall(call, "post", `/addons/${SSH_ADDON}/${started ? "restart" : "start"}`);
449
+ let failure = "";
450
+ for (let attempt = 0; attempt < 8; attempt++) {
451
+ try {
452
+ return { status: "file access set up", addon: SSH_ADDON, was: started ? "started" : "stopped", boot: "auto", passwordLogin: cmd.keepPassword ? "unchanged" : "off", files: lines(await run("list")).length };
453
+ } catch (err) {
454
+ failure = err instanceof Error ? err.message : String(err);
455
+ await wait(5000);
456
+ }
457
+ }
458
+ throw new ServiceError(`the add-on took the options, but the file commands do not answer: ${failure}`);
459
+ }
286
460
 
287
461
  export async function command(args: string[]): Promise<number> {
288
462
  const [name, ...rest] = args;
@@ -298,6 +472,7 @@ export async function command(args: string[]): Promise<number> {
298
472
  const ws = name === "ws-read" || name === "ws" ? parseWs(rest, name === "ws-read") : null;
299
473
  const restCall = name === "rest" ? parseRest(rest) : null;
300
474
  const supervisor = name === "supervisor" ? parseSupervisor(rest) : null;
475
+ const file = FILE_COMMANDS.includes(name) ? parseFileCommand(name, rest) : null;
301
476
  const updateTarget = name === "update" ? confirmed(rest, "update <update.entity_id> --confirm") : null;
302
477
  if (updateTarget !== null && (updateTarget.length !== 1 || !ENTITY_ID.test(updateTarget[0]) || !updateTarget[0].startsWith("update."))) throw new UsageError("update <update.entity_id> --confirm");
303
478
  if (name === "restart" && confirmed(rest, "restart --confirm").length > 0) throw new UsageError("restart --confirm");
@@ -357,6 +532,8 @@ export async function command(args: string[]): Promise<number> {
357
532
  printJson({ result: answer(await call(ws.type, ws.fields)) });
358
533
  } else if (supervisor !== null) {
359
534
  printJson({ result: answer(await supervisorCall(call, supervisor.method, supervisor.endpoint, supervisor.body)) });
535
+ } else if (file !== null) {
536
+ printJson(await fileCommand(config, token, call, file));
360
537
  }
361
538
  });
362
539
  return 0;
@@ -0,0 +1,216 @@
1
+ import { spawnSync } from "node:child_process";
2
+ import { existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, writeFileSync } from "node:fs";
3
+ import { tmpdir } from "node:os";
4
+ import { join } from "node:path";
5
+ import { afterEach, beforeEach, describe, expect, it } from "vitest";
6
+ import { ENTRY_PATH, ENTRY_SCRIPT, REDACTED, authorizedKeyLine, entryInitCommand, isPublicKey, isStamp, isYamlPath, pageLines, redactYaml, replaceOnce, withFileAccess } from "./home-files.ts";
7
+
8
+ const KEY = `ssh-ed25519 ${"A".repeat(68)} spc-home@cortex`;
9
+
10
+ describe("home file access, checks", () => {
11
+ it("accepts YAML files below the configuration folder only", () => {
12
+ for (const path of ["configuration.yaml", "automations.yaml", "packages/lights.yaml", "esphome/living-room.yml", "blueprints/automation/homeassistant/motion_light.yaml", "a.b.yaml"]) expect(isYamlPath(path), path).toBe(true);
13
+ for (const path of [
14
+ "secrets.yaml",
15
+ "esphome/secrets.yaml",
16
+ ".storage/core.config_entries.yaml",
17
+ "packages/.hidden/x.yaml",
18
+ "../x.yaml",
19
+ "a/../b.yaml",
20
+ "/etc/x.yaml",
21
+ "a//b.yaml",
22
+ "configuration.yaml.bak",
23
+ "home-assistant.log",
24
+ "a b.yaml",
25
+ "a;id.yaml",
26
+ "-x.yaml",
27
+ "",
28
+ `${"a".repeat(200)}.yaml`,
29
+ ])
30
+ expect(isYamlPath(path), path).toBe(false);
31
+ });
32
+
33
+ it("accepts a stamp and one ed25519 public key line", () => {
34
+ expect(isStamp("20261112T101500Z")).toBe(true);
35
+ expect(isStamp("2026-11-12T10:15:00Z")).toBe(false);
36
+ expect(isPublicKey(KEY)).toBe(true);
37
+ expect(isPublicKey(`${KEY}\nssh-ed25519 ${"B".repeat(68)}`)).toBe(false);
38
+ expect(isPublicKey(`command="sh" ${KEY}`)).toBe(false);
39
+ expect(isPublicKey(`ssh-rsa ${"A".repeat(68)}`)).toBe(false);
40
+ });
41
+
42
+ it("binds the key to the entry script and nothing else", () => {
43
+ expect(authorizedKeyLine(KEY)).toBe(`restrict,command="sudo -n /usr/local/bin/spc-home-entry \\"$SSH_ORIGINAL_COMMAND\\"" ${KEY}`);
44
+ });
45
+
46
+ it("carries the entry script of entry/remote word for word", () => {
47
+ expect(ENTRY_SCRIPT).toBe(readFileSync(join(import.meta.dirname, "..", "entry", "remote", "spc-home-entry.sh"), "utf-8"));
48
+ const encoded = /^echo (\S+) \| base64 -d > \/usr\/local\/bin\/spc-home-entry && chmod 755 \/usr\/local\/bin\/spc-home-entry$/.exec(entryInitCommand())?.[1];
49
+ expect(Buffer.from(encoded ?? "", "base64").toString("utf-8")).toBe(ENTRY_SCRIPT);
50
+ });
51
+
52
+ it("adds its key and init command and keeps the owner's options", () => {
53
+ const options = { ssh: { username: "hassio", password: "owner-password", authorized_keys: ["ssh-ed25519 OWNER"], sftp: false }, zsh: true, init_commands: ["echo hello"] };
54
+ const first = withFileAccess(options, KEY, true) as { ssh: Record<string, unknown>; init_commands: string[]; zsh: boolean };
55
+ expect(first.ssh).toEqual({ username: "hassio", password: "owner-password", authorized_keys: ["ssh-ed25519 OWNER", authorizedKeyLine(KEY)], sftp: false });
56
+ expect(first.init_commands).toEqual(["echo hello", entryInitCommand()]);
57
+ expect(first.zsh).toBe(true);
58
+ const other = `ssh-ed25519 ${"C".repeat(68)}`;
59
+ const second = withFileAccess(first, other, false) as { ssh: { password: string; authorized_keys: string[] }; init_commands: string[] };
60
+ expect(second.ssh.authorized_keys).toEqual(["ssh-ed25519 OWNER", authorizedKeyLine(other)]);
61
+ expect(second.ssh.password).toBe("");
62
+ expect(second.init_commands).toEqual(["echo hello", entryInitCommand()]);
63
+ expect(withFileAccess(null, KEY, true)).toEqual({ ssh: { authorized_keys: [authorizedKeyLine(KEY)] }, init_commands: [entryInitCommand()] });
64
+ });
65
+
66
+ it("replaces a text only when it occurs exactly once", () => {
67
+ expect(replaceOnce("a: 1\nb: 2\n", "b: 2", "b: 3")).toBe("a: 1\nb: 3\n");
68
+ expect(replaceOnce("a: 1\n", "c: 1", "c: 2")).toEqual({ error: "the text to replace is not in the file" });
69
+ expect(replaceOnce("a: 1\na: 1\n", "a: 1", "a: 2")).toEqual({ error: "the text to replace occurs more than once; give more of its surroundings" });
70
+ expect(replaceOnce("a: 1\n", "", "x")).toEqual({ error: "the text to replace is empty" });
71
+ expect(replaceOnce("a: $1\n", "a: $1", "a: $&")).toBe("a: $&\n");
72
+ });
73
+
74
+ it("masks the values of secret-named keys", () => {
75
+ const yaml = [
76
+ "homeassistant:",
77
+ " name: Mira",
78
+ "mqtt:",
79
+ " username: ha",
80
+ " password: hunter2",
81
+ ' "api_key": abc # note',
82
+ " token: !secret mqtt_token",
83
+ "rest_command:",
84
+ " - url: https://example.org",
85
+ " headers:",
86
+ " Authorization: Bearer abc",
87
+ "tls:",
88
+ " private_key: |",
89
+ " -----BEGIN KEY-----",
90
+ " abc",
91
+ "",
92
+ " port: 8883",
93
+ "api_keys:",
94
+ "- one",
95
+ "- two",
96
+ "after: 1",
97
+ ].join("\n");
98
+ expect(redactYaml(yaml).split("\n")).toEqual([
99
+ "homeassistant:",
100
+ " name: Mira",
101
+ "mqtt:",
102
+ " username: ha",
103
+ ` password: ${REDACTED}`,
104
+ ` "api_key": ${REDACTED}`,
105
+ " token: !secret mqtt_token",
106
+ "rest_command:",
107
+ " - url: https://example.org",
108
+ " headers:",
109
+ ` Authorization: ${REDACTED}`,
110
+ "tls:",
111
+ ` private_key: ${REDACTED}`,
112
+ " port: 8883",
113
+ `api_keys: ${REDACTED}`,
114
+ "after: 1",
115
+ ]);
116
+ expect(redactYaml("- token:\n value: abc\n- name: next\n")).toBe(`- token: ${REDACTED}\n- name: next\n`);
117
+ });
118
+
119
+ it("pages a long file by whole lines", () => {
120
+ const content = "one\ntwo\nthree\nfour\n";
121
+ expect(pageLines(content, 1, 1000)).toEqual({ lines: 4, from: 1, content: "one\ntwo\nthree\nfour" });
122
+ expect(pageLines(content, 1, 8)).toEqual({ lines: 4, from: 1, content: "one\ntwo", next: 3 });
123
+ expect(pageLines(content, 3, 8)).toEqual({ lines: 4, from: 3, content: "three", next: 4 });
124
+ expect(pageLines(content, 4, 1)).toEqual({ lines: 4, from: 4, content: "four" });
125
+ expect(pageLines(content, 9, 100)).toEqual({ lines: 4, from: 9, content: "" });
126
+ });
127
+ });
128
+
129
+ describe("home file access, entry script", () => {
130
+ let dir: string;
131
+ let root: string;
132
+ let script: string;
133
+
134
+ /** Runs the script as sshd does: the requested command is one argument. */
135
+ function entry(command: string, input?: string): { code: number | null; out: string; err: string } {
136
+ const result = spawnSync("/bin/sh", [script, command], { input, encoding: "utf-8" });
137
+ return { code: result.status, out: result.stdout, err: result.stderr };
138
+ }
139
+
140
+ beforeEach(() => {
141
+ dir = mkdtempSync(join(tmpdir(), "spc-home-entry-"));
142
+ root = join(dir, "homeassistant");
143
+ script = join(dir, "spc-home-entry");
144
+ mkdirSync(join(root, ".storage"), { recursive: true });
145
+ mkdirSync(join(root, "packages", ".hidden"), { recursive: true });
146
+ writeFileSync(join(root, "configuration.yaml"), "default_config:\n");
147
+ writeFileSync(join(root, "secrets.yaml"), "mqtt: hunter2\n");
148
+ writeFileSync(join(root, ".storage", "auth.yaml"), "token: abc\n");
149
+ writeFileSync(join(root, "packages", "lights.yaml"), "light: []\n");
150
+ writeFileSync(join(root, "packages", "secrets.yaml"), "x: y\n");
151
+ writeFileSync(join(root, "packages", ".hidden", "x.yaml"), "x: y\n");
152
+ writeFileSync(join(root, "home-assistant.log"), "log\n");
153
+ expect(ENTRY_SCRIPT).toContain("root=/homeassistant\n");
154
+ writeFileSync(script, ENTRY_SCRIPT.replace("root=/homeassistant\n", `root=${root}\n`));
155
+ });
156
+
157
+ afterEach(() => {
158
+ rmSync(dir, { recursive: true, force: true });
159
+ });
160
+
161
+ it("lists YAML files without hidden folders and secrets files", () => {
162
+ expect(entry("list")).toEqual({ code: 0, out: "configuration.yaml\npackages/lights.yaml\n", err: "" });
163
+ });
164
+
165
+ it("reads a YAML file and refuses every other path", () => {
166
+ expect(entry("read packages/lights.yaml")).toEqual({ code: 0, out: "light: []\n", err: "" });
167
+ for (const path of ["secrets.yaml", "packages/secrets.yaml", ".storage/auth.yaml", "packages/.hidden/x.yaml", "packages/../secrets.yaml", `${root}/configuration.yaml`, "home-assistant.log", "packages//lights.yaml", "x.yaml;id", "$(id).yaml"]) {
168
+ const result = entry(`read ${path}`);
169
+ expect(result, path).toEqual({ code: 2, out: "", err: "spc-home-entry: refused path\n" });
170
+ }
171
+ expect(entry("read missing.yaml")).toEqual({ code: 2, out: "", err: "spc-home-entry: no such file: missing.yaml\n" });
172
+ });
173
+
174
+ it("refuses unknown commands and extra words", () => {
175
+ for (const command of ["", "shell", "list extra", "read configuration.yaml extra", "read a b.yaml", "write", "restore configuration.yaml"]) {
176
+ const result = entry(command, "x: 1\n");
177
+ expect(result.code, command).toBe(2);
178
+ expect(result.err, command).toContain("usage: list | read <path>");
179
+ }
180
+ expect(readFileSync(join(root, "configuration.yaml"), "utf-8")).toBe("default_config:\n");
181
+ });
182
+
183
+ it("keeps a copy before every change and restores it", () => {
184
+ expect(entry("write packages/new/fans.yaml", "fan: []\n")).toEqual({ code: 0, out: "backup none\n", err: "" });
185
+ expect(readFileSync(join(root, "packages", "new", "fans.yaml"), "utf-8")).toBe("fan: []\n");
186
+ expect(entry("backups packages/new/fans.yaml")).toEqual({ code: 0, out: "", err: "" });
187
+
188
+ const first = /^backup (\d{8}T\d{6}Z)\n$/.exec(entry("write configuration.yaml", "second: 2\n").out)?.[1] ?? "";
189
+ expect(isStamp(first)).toBe(true);
190
+ expect(readFileSync(join(root, "configuration.yaml"), "utf-8")).toBe("second: 2\n");
191
+ // A second change in the same second must not overwrite the first copy.
192
+ const second = /^backup (\d{8}T\d{6}Z)\n$/.exec(entry("write configuration.yaml", "third: 3\n").out)?.[1] ?? "";
193
+ expect(isStamp(second)).toBe(true);
194
+ expect(second > first).toBe(true);
195
+ expect(entry("backups configuration.yaml").out).toBe(`${first}\n${second}\n`);
196
+
197
+ const restored = /^backup (\d{8}T\d{6}Z)\n$/.exec(entry(`restore configuration.yaml ${first}`).out)?.[1] ?? "";
198
+ expect(readFileSync(join(root, "configuration.yaml"), "utf-8")).toBe("default_config:\n");
199
+ expect(readFileSync(join(root, ".spc-home-backups", `configuration.yaml.${restored}`), "utf-8")).toBe("third: 3\n");
200
+ expect(entry("restore configuration.yaml 20000101T000000Z")).toEqual({ code: 2, out: "", err: "spc-home-entry: no such backup: configuration.yaml 20000101T000000Z\n" });
201
+ expect(entry("restore configuration.yaml ../x").err).toBe("spc-home-entry: refused stamp\n");
202
+ expect(readdirSync(root).filter((name) => name.endsWith(".spc-tmp"))).toEqual([]);
203
+ expect(entry("list").out).toBe("configuration.yaml\npackages/lights.yaml\npackages/new/fans.yaml\n");
204
+ }, 20_000);
205
+
206
+ it("removes a file after keeping a copy", () => {
207
+ const stamp = /^backup (\d{8}T\d{6}Z)\n$/.exec(entry("remove packages/lights.yaml").out)?.[1] ?? "";
208
+ expect(existsSync(join(root, "packages", "lights.yaml"))).toBe(false);
209
+ expect(readFileSync(join(root, ".spc-home-backups", "packages", `lights.yaml.${stamp}`), "utf-8")).toBe("light: []\n");
210
+ expect(entry(`restore packages/lights.yaml ${stamp}`)).toEqual({ code: 0, out: "backup none\n", err: "" });
211
+ expect(readFileSync(join(root, "packages", "lights.yaml"), "utf-8")).toBe("light: []\n");
212
+ expect(entry("remove secrets.yaml").err).toBe("spc-home-entry: refused path\n");
213
+ expect(existsSync(join(root, "secrets.yaml"))).toBe(true);
214
+ expect(ENTRY_PATH).toBe("/usr/local/bin/spc-home-entry");
215
+ });
216
+ });
@@ -0,0 +1,221 @@
1
+ /**
2
+ * YAML file access for the home specialist. Home Assistant has no API for files, so the specialist's SSH key
3
+ * is bound, in the "Advanced SSH & Web Terminal" add-on, to one forced command: the entry script below. The
4
+ * add-on writes its `authorized_keys` option lines verbatim and runs its `init_commands` at every start
5
+ * (`init-ssh/run` and `init-user/run` of hassio-addons/app-ssh), so both the binding and the script live in
6
+ * the add-on's options and survive an update or a restore.
7
+ */
8
+
9
+ /** Slug of the "Advanced SSH & Web Terminal" add-on (repository a0d7b954, hassio-addons). */
10
+ export const SSH_ADDON = "a0d7b954_ssh";
11
+ export const ENTRY_PATH = "/usr/local/bin/spc-home-entry";
12
+ /** What a masked value reads as; a write that carries it is refused, so a read can never be stored back. */
13
+ export const REDACTED = "[redacted]";
14
+
15
+ /** The forced command, word for word `entry/remote/spc-home-entry.sh` (a test compares them). */
16
+ export const ENTRY_SCRIPT = `#!/bin/sh
17
+ # spc-home-entry: forced command of the home specialist's key inside the
18
+ # "Advanced SSH & Web Terminal" add-on of Home Assistant. The add-on's
19
+ # init_commands write this file at every start; the key's authorized_keys line
20
+ # runs it through sudo with the requested command as one argument.
21
+ # It serves YAML files below /homeassistant: no hidden folders (so never
22
+ # .storage), no dot segments, never secrets.yaml. Every change first copies the
23
+ # current file to .spc-home-backups/<path>.<UTC stamp>.
24
+ set -eu
25
+ set -f
26
+ root=/homeassistant
27
+ backups=$root/.spc-home-backups
28
+ # shellcheck disable=SC2086
29
+ set -- \${1:-}
30
+ op=\${1:-}
31
+ path=\${2:-}
32
+ stamp=\${3:-}
33
+ valid() {
34
+ case "$1" in "" | /* | .* | */.* | *..* | *//* | *[!A-Za-z0-9_./-]*) return 1 ;; esac
35
+ case "$1" in *.yaml | *.yml) ;; *) return 1 ;; esac
36
+ case "$1" in secrets.yaml | */secrets.yaml) return 1 ;; esac
37
+ return 0
38
+ }
39
+ refuse() {
40
+ echo "spc-home-entry: $1" >&2
41
+ exit 2
42
+ }
43
+ args() {
44
+ [ "$1" -eq "$2" ] || refuse "usage: list | read <path> | backups <path> | write <path> | restore <path> <stamp> | remove <path>"
45
+ }
46
+ # Copies the current file aside under a stamp that no backup of it has yet.
47
+ keep() {
48
+ if [ ! -f "$root/$path" ]; then
49
+ echo "backup none"
50
+ return 0
51
+ fi
52
+ mkdir -p "$(dirname "$backups/$path")"
53
+ now=$(date -u +%Y%m%dT%H%M%SZ)
54
+ while [ -e "$backups/$path.$now" ]; do
55
+ sleep 1
56
+ now=$(date -u +%Y%m%dT%H%M%SZ)
57
+ done
58
+ cp -p -- "$root/$path" "$backups/$path.$now"
59
+ echo "backup $now"
60
+ }
61
+ case "$op" in
62
+ list)
63
+ args $# 1
64
+ cd "$root"
65
+ find . -maxdepth 6 -type f \\( -name '*.yaml' -o -name '*.yml' \\) ! -path '*/.*' ! -name secrets.yaml | sed 's|^\\./||' | sort
66
+ ;;
67
+ read)
68
+ args $# 2
69
+ valid "$path" || refuse "refused path"
70
+ [ -f "$root/$path" ] || refuse "no such file: $path"
71
+ cat -- "$root/$path"
72
+ ;;
73
+ backups)
74
+ args $# 2
75
+ valid "$path" || refuse "refused path"
76
+ dir=$(dirname "$backups/$path")
77
+ [ -d "$dir" ] || exit 0
78
+ find "$dir" -maxdepth 1 -type f | sed -n "s|^.*/$(basename "$path")\\.\\([0-9]\\{8\\}T[0-9]\\{6\\}Z\\)$|\\1|p" | sort
79
+ ;;
80
+ write)
81
+ args $# 2
82
+ valid "$path" || refuse "refused path"
83
+ mkdir -p "$(dirname "$root/$path")"
84
+ keep
85
+ cat > "$root/$path.spc-tmp"
86
+ mv -- "$root/$path.spc-tmp" "$root/$path"
87
+ ;;
88
+ restore)
89
+ args $# 3
90
+ valid "$path" || refuse "refused path"
91
+ case "$stamp" in [0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]T[0-9][0-9][0-9][0-9][0-9][0-9]Z) ;; *) refuse "refused stamp" ;; esac
92
+ [ -f "$backups/$path.$stamp" ] || refuse "no such backup: $path $stamp"
93
+ mkdir -p "$(dirname "$root/$path")"
94
+ keep
95
+ cp -p -- "$backups/$path.$stamp" "$root/$path.spc-tmp"
96
+ mv -- "$root/$path.spc-tmp" "$root/$path"
97
+ ;;
98
+ remove)
99
+ args $# 2
100
+ valid "$path" || refuse "refused path"
101
+ [ -f "$root/$path" ] || refuse "no such file: $path"
102
+ keep
103
+ rm -- "$root/$path"
104
+ ;;
105
+ *)
106
+ args 0 1
107
+ ;;
108
+ esac
109
+ `;
110
+
111
+ const PUBLIC_KEY = /^ssh-ed25519 [A-Za-z0-9+/]{60,80}={0,2}(?: [A-Za-z0-9@._-]{1,64})?$/;
112
+ const FILE_PATH = /^[A-Za-z0-9_][A-Za-z0-9_-]*(?:\.[A-Za-z0-9_-]+)*(?:\/[A-Za-z0-9_][A-Za-z0-9_-]*(?:\.[A-Za-z0-9_-]+)*)*\.ya?ml$/;
113
+ const STAMP = /^\d{8}T\d{6}Z$/;
114
+ /** A YAML key whose value is a credential by its name. */
115
+ const SECRET_LINE = /^(\s*(?:-\s+)?["']?[\w.-]*(?:password|passwd|secret|token|api_?key|private_?key|credential|network_key|passphrase|psk|authorization)[\w.-]*["']?\s*:)\s*(.*)$/i;
116
+
117
+ /** True for a path the entry script serves: a YAML file below the configuration folder, not hidden, not a secrets file. */
118
+ export function isYamlPath(path: string): boolean {
119
+ return FILE_PATH.test(path) && path.length <= 200 && path !== "secrets.yaml" && !path.endsWith("/secrets.yaml");
120
+ }
121
+
122
+ export function isStamp(stamp: string): boolean {
123
+ return STAMP.test(stamp);
124
+ }
125
+
126
+ export function isPublicKey(line: string): boolean {
127
+ return PUBLIC_KEY.test(line);
128
+ }
129
+
130
+ /** The `authorized_keys` line that binds a key to the entry script; the add-on's user reaches root through sudo. */
131
+ export function authorizedKeyLine(publicKey: string): string {
132
+ return `restrict,command="sudo -n ${ENTRY_PATH} \\"$SSH_ORIGINAL_COMMAND\\"" ${publicKey}`;
133
+ }
134
+
135
+ /** The init command that writes the entry script into the add-on's container at every start. */
136
+ export function entryInitCommand(): string {
137
+ return `echo ${Buffer.from(ENTRY_SCRIPT, "utf-8").toString("base64")} | base64 -d > ${ENTRY_PATH} && chmod 755 ${ENTRY_PATH}`;
138
+ }
139
+
140
+ function list(value: unknown): string[] {
141
+ return Array.isArray(value) ? value.filter((v): v is string => typeof v === "string") : [];
142
+ }
143
+
144
+ /**
145
+ * The add-on's options with the specialist's key and entry script in place. Everything else stays as it was,
146
+ * including the owner's own keys; an earlier specialist key or entry command is replaced. `keepPassword` false
147
+ * empties the SSH password, which turns password login off (the add-on then sets a random one).
148
+ */
149
+ export function withFileAccess(options: unknown, publicKey: string, keepPassword: boolean): Record<string, unknown> {
150
+ const current = typeof options === "object" && options !== null ? (options as Record<string, unknown>) : {};
151
+ const ssh = typeof current.ssh === "object" && current.ssh !== null ? (current.ssh as Record<string, unknown>) : {};
152
+ const keys = list(ssh.authorized_keys).filter((line) => !line.includes(ENTRY_PATH));
153
+ const init = list(current.init_commands).filter((line) => !line.includes(ENTRY_PATH));
154
+ return {
155
+ ...current,
156
+ ssh: { ...ssh, ...(keepPassword ? {} : { password: "" }), authorized_keys: [...keys, authorizedKeyLine(publicKey)] },
157
+ init_commands: [...init, entryInitCommand()],
158
+ };
159
+ }
160
+
161
+ /** Replaces exactly one occurrence of `old` in `content`; anything else is an error the caller reports. */
162
+ export function replaceOnce(content: string, old: string, replacement: string): string | { error: string } {
163
+ if (old.length === 0) return { error: "the text to replace is empty" };
164
+ const first = content.indexOf(old);
165
+ if (first === -1) return { error: "the text to replace is not in the file" };
166
+ if (content.indexOf(old, first + old.length) !== -1) return { error: "the text to replace occurs more than once; give more of its surroundings" };
167
+ return content.slice(0, first) + replacement + content.slice(first + old.length);
168
+ }
169
+
170
+ /**
171
+ * Masks the values of secret-named keys in YAML text, line by line: an inline value becomes `[redacted]`, and a
172
+ * block or nested value loses its lines. `!secret` and `!env_var` references stay, because they name a secret
173
+ * without holding it. A mask for what a person or a model reads, not a boundary: a credential under another
174
+ * key name, or inside a URL, passes.
175
+ */
176
+ export function redactYaml(content: string): string {
177
+ const out: string[] = [];
178
+ /** The indent of a secret key whose value follows on later lines; `items`: list items at that same indent belong to it. */
179
+ let hiddenBelow: { indent: number; items: boolean } | null = null;
180
+ for (const line of content.split("\n")) {
181
+ const indent = line.length - line.trimStart().length;
182
+ if (hiddenBelow !== null) {
183
+ if (line.trim().length === 0 || indent > hiddenBelow.indent || (indent === hiddenBelow.indent && hiddenBelow.items && line.trimStart().startsWith("- "))) continue;
184
+ hiddenBelow = null;
185
+ }
186
+ const match = SECRET_LINE.exec(line);
187
+ const value = match?.[2].trim() ?? "";
188
+ if (match === null || /^!(secret|env_var)\s/.test(value)) {
189
+ out.push(line);
190
+ continue;
191
+ }
192
+ out.push(`${match[1]} ${REDACTED}`);
193
+ if (value.length === 0 || value.startsWith("#") || /^[|>][+-]?\d*$/.test(value)) hiddenBelow = { indent, items: !line.trimStart().startsWith("- ") };
194
+ }
195
+ return out.join("\n");
196
+ }
197
+
198
+ export interface Page {
199
+ /** Lines in the whole file. */
200
+ lines: number;
201
+ /** First line of this page, counted from 1. */
202
+ from: number;
203
+ content: string;
204
+ /** The line to continue from, when the file goes on. */
205
+ next?: number;
206
+ }
207
+
208
+ /** The lines of `content` from line `from` on, as many whole lines as fit in `maxChars` (at least one). */
209
+ export function pageLines(content: string, from: number, maxChars: number): Page {
210
+ const lines = content.split("\n");
211
+ if (lines.at(-1) === "") lines.pop();
212
+ const taken: string[] = [];
213
+ let size = 0;
214
+ for (let i = from - 1; i < lines.length; i++) {
215
+ size += lines[i].length + 1;
216
+ if (taken.length > 0 && size > maxChars) break;
217
+ taken.push(lines[i]);
218
+ }
219
+ const next = from + taken.length;
220
+ return { lines: lines.length, from, content: taken.join("\n"), ...(next <= lines.length ? { next } : {}) };
221
+ }
@@ -10,7 +10,7 @@ import { buildBackupRemote, command as backupCommand } from "./backup/run.ts";
10
10
  import { buildNodeRemote, parseJoinArgs, parseParams, parseRecordFilters, technitiumRequest, technitiumTarget, command as dnsCommand } from "./dns/run.ts";
11
11
  import { buildVpsRemote, command as edgeCommand, isTransientSshFailure, PUBLIC_ROUTES, routeProbe } from "./edge/run.ts";
12
12
  import { API_PREFIXES, buildDmzRemote, installedRelease, publishedSha256, validateApiPath, command as identityCommand } from "./identity/run.ts";
13
- import { command as homeCommand, parseAction, parseEntityQuery, parseLogs, parseRest, parseSupervisor, parseWs } from "./home/run.ts";
13
+ import { command as homeCommand, parseAction, parseEntityQuery, parseFileCommand, parseLogs, parseRest, parseSupervisor, parseWs } from "./home/run.ts";
14
14
  import { buildInferenceRemote, command as inferenceCommand } from "./inference/run.ts";
15
15
  import { MAX_ADD_IDS, MAX_EXCLUDE_IDS, buildTrendarrCall, interpretRun, parseImdbIds, parseQueueRemove, stuckRecords, trendarrConfig, trendarrError, trendarrWarnings, command as mediaCommand } from "./media/run.ts";
16
16
  import { ServiceError, UsageError } from "./lib/errors.ts";
@@ -1136,6 +1136,34 @@ describe("home wrapper, generic calls", () => {
1136
1136
  expect(() => parseSupervisor(["get", "addons"])).toThrow(UsageError);
1137
1137
  expect(() => parseSupervisor(["post", "/host/reboot", "[]"])).toThrow(/JSON object/);
1138
1138
  });
1139
+
1140
+ it("parses the file commands and refuses paths outside the YAML files", async () => {
1141
+ const key = `ssh-ed25519 ${"A".repeat(68)} spc-home@cortex`;
1142
+ expect(parseFileCommand("file-list", [])).toEqual({ op: "list" });
1143
+ expect(parseFileCommand("file-read", ["configuration.yaml"])).toEqual({ op: "read", path: "configuration.yaml", from: 1 });
1144
+ expect(parseFileCommand("file-read", ["automations.yaml", "801"])).toEqual({ op: "read", path: "automations.yaml", from: 801 });
1145
+ expect(parseFileCommand("file-backups", ["packages/lights.yaml"])).toEqual({ op: "backups", path: "packages/lights.yaml" });
1146
+ expect(parseFileCommand("file-write", ["packages/lights.yaml", "light: []\n", "--confirm"])).toEqual({ op: "write", path: "packages/lights.yaml", content: "light: []\n" });
1147
+ expect(parseFileCommand("file-replace", ["configuration.yaml", JSON.stringify({ old: "a: 1", new: "a: 2" }), "--confirm"])).toEqual({ op: "replace", path: "configuration.yaml", old: "a: 1", replacement: "a: 2" });
1148
+ expect(parseFileCommand("file-restore", ["configuration.yaml", "20261112T101500Z", "--confirm"])).toEqual({ op: "restore", path: "configuration.yaml", stamp: "20261112T101500Z" });
1149
+ expect(parseFileCommand("file-remove", ["packages/old.yaml", "--confirm"])).toEqual({ op: "remove", path: "packages/old.yaml" });
1150
+ expect(parseFileCommand("files-setup", [key, "--confirm"])).toEqual({ op: "setup", publicKey: key, keepPassword: true });
1151
+ expect(parseFileCommand("files-setup", ["--no-password", key, "--confirm"])).toEqual({ op: "setup", publicKey: key, keepPassword: false });
1152
+ for (const path of ["secrets.yaml", ".storage/auth.yaml", "../x.yaml", "/etc/x.yaml", "esphome/secrets.yaml", "home-assistant.log"]) {
1153
+ expect(() => parseFileCommand("file-read", [path]), path).toThrow(/must be a YAML file/);
1154
+ expect(() => parseFileCommand("file-write", [path, "x: 1", "--confirm"]), path).toThrow(/must be a YAML file/);
1155
+ }
1156
+ expect(() => parseFileCommand("file-read", ["configuration.yaml", "0"])).toThrow(/first line/);
1157
+ expect(() => parseFileCommand("file-write", ["configuration.yaml", "password: [redacted]\n", "--confirm"])).toThrow(/masked/);
1158
+ expect(() => parseFileCommand("file-replace", ["configuration.yaml", JSON.stringify({ old: "a", new: "token: [redacted]" }), "--confirm"])).toThrow(/masked/);
1159
+ expect(() => parseFileCommand("file-replace", ["configuration.yaml", JSON.stringify({ old: "a" }), "--confirm"])).toThrow(UsageError);
1160
+ expect(() => parseFileCommand("file-restore", ["configuration.yaml", "yesterday", "--confirm"])).toThrow(/stamp/);
1161
+ expect(() => parseFileCommand("files-setup", ["ssh-rsa AAAA", "--confirm"])).toThrow(/ssh-ed25519/);
1162
+ await expect(homeCommand(["file-write", "configuration.yaml", "x: 1"])).rejects.toThrow(/needs --confirm/);
1163
+ await expect(homeCommand(["file-remove", "configuration.yaml"])).rejects.toThrow(/needs --confirm/);
1164
+ await expect(homeCommand(["files-setup", key])).rejects.toThrow(/needs --confirm/);
1165
+ await expect(homeCommand(["file-read", "secrets.yaml"])).rejects.toThrow(/must be a YAML file/);
1166
+ });
1139
1167
  });
1140
1168
 
1141
1169
  describe("dns stale-zone-delete", () => {