@astrofoundry/pi-astro 0.40.71 → 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 +1 -1
- package/agents/home.md +5 -3
- package/extensions/specialist-gate/approvals.test.ts +8 -0
- package/extensions/specialist-gate/index.ts +3 -2
- package/package.json +1 -1
- package/skills/home/SKILL.md +53 -2
- package/specialists/AGENTS.md +1 -1
- package/specialists/README.md +4 -3
- package/specialists/entry/remote/spc-home-entry.sh +93 -0
- package/specialists/home/run.ts +313 -47
- package/specialists/lib/home-assistant.test.ts +12 -1
- package/specialists/lib/home-assistant.ts +30 -0
- package/specialists/lib/home-files.test.ts +216 -0
- package/specialists/lib/home-files.ts +221 -0
- package/specialists/wrappers.test.ts +69 -1
|
@@ -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 } 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";
|
|
@@ -1098,6 +1098,74 @@ describe("home wrapper", () => {
|
|
|
1098
1098
|
});
|
|
1099
1099
|
});
|
|
1100
1100
|
|
|
1101
|
+
describe("home wrapper, generic calls", () => {
|
|
1102
|
+
it("lets ws-read send only known read commands", () => {
|
|
1103
|
+
expect(parseWs(["config/entity_registry/list"], true)).toEqual({ type: "config/entity_registry/list", fields: {} });
|
|
1104
|
+
expect(parseWs(["input_boolean/list"], true).type).toBe("input_boolean/list");
|
|
1105
|
+
expect(parseWs(["trace/list", JSON.stringify({ domain: "automation" })], true)).toEqual({ type: "trace/list", fields: { domain: "automation" } });
|
|
1106
|
+
expect(() => parseWs(["config/entity_registry/update", "{}"], true)).toThrow(/not a known read command/);
|
|
1107
|
+
expect(() => parseWs(["backup/config/info"], true)).toThrow(/not a known read command/);
|
|
1108
|
+
expect(() => parseWs(["application_credentials/list"], true)).toThrow(/not a known read command/);
|
|
1109
|
+
expect(() => parseWs(["auth/refresh_tokens"], true)).toThrow(/not a known read command/);
|
|
1110
|
+
});
|
|
1111
|
+
|
|
1112
|
+
it("lets ws send any command but never the sign-in or its own id", () => {
|
|
1113
|
+
expect(parseWs(["lovelace/config/save", JSON.stringify({ url_path: null, config: { views: [] } })], false)).toEqual({ type: "lovelace/config/save", fields: { url_path: null, config: { views: [] } } });
|
|
1114
|
+
expect(() => parseWs(["auth", JSON.stringify({ access_token: "x" })], false)).toThrow(UsageError);
|
|
1115
|
+
expect(() => parseWs(["get_states", JSON.stringify({ id: 9 })], false)).toThrow(/must not carry id or type/);
|
|
1116
|
+
expect(() => parseWs(["Config/Core"], false)).toThrow(UsageError);
|
|
1117
|
+
expect(() => parseWs(["get_states", "[1]"], false)).toThrow(/JSON object/);
|
|
1118
|
+
});
|
|
1119
|
+
|
|
1120
|
+
it("keeps rest calls under /api/ and supervisor calls on plain endpoints", () => {
|
|
1121
|
+
expect(parseRest(["get", "/api/config/automation/config/1699999999999"])).toEqual({ method: "get", path: "/api/config/automation/config/1699999999999" });
|
|
1122
|
+
expect(parseRest(["post", "/api/config/config_entries/entry/01JF3GKX39K3WCDRZQADJVMDRH/reload"])).toEqual({ method: "post", path: "/api/config/config_entries/entry/01JF3GKX39K3WCDRZQADJVMDRH/reload" });
|
|
1123
|
+
expect(parseRest(["post", "/api/template", JSON.stringify({ template: "{{ now() }}" })]).body).toEqual({ template: "{{ now() }}" });
|
|
1124
|
+
expect(() => parseRest(["get", "/auth/providers"])).toThrow(/must start with \/api\//);
|
|
1125
|
+
expect(() => parseRest(["get", "/api/../auth/token"])).toThrow(UsageError);
|
|
1126
|
+
expect(() => parseRest(["get", "/api/%2e%2e/x"])).toThrow(UsageError);
|
|
1127
|
+
expect(() => parseRest(["get", "/api/websocket"])).toThrow(UsageError);
|
|
1128
|
+
expect(() => parseRest(["get", "/api/config", "{}"])).toThrow(UsageError);
|
|
1129
|
+
expect(() => parseRest(["patch", "/api/config"])).toThrow(UsageError);
|
|
1130
|
+
expect(() => parseRest(["POST", "/api/config"])).toThrow(UsageError);
|
|
1131
|
+
expect(parseSupervisor(["get", "/addons/core_matter_server/info"])).toEqual({ method: "get", endpoint: "/addons/core_matter_server/info" });
|
|
1132
|
+
expect(parseSupervisor(["post", "/addons/a0d7b954_ssh/options", JSON.stringify({ options: { authorized_keys: ["ssh-ed25519 AAAA"] } })]).body).toEqual({ options: { authorized_keys: ["ssh-ed25519 AAAA"] } });
|
|
1133
|
+
expect(() => parseSupervisor(["get", "/core/logs"])).toThrow(/use the logs command/);
|
|
1134
|
+
expect(() => parseSupervisor(["get", "/backups/c6bfb343/download"])).toThrow(/use the logs command/);
|
|
1135
|
+
expect(() => parseSupervisor(["get", "/addons/../core/info"])).toThrow(UsageError);
|
|
1136
|
+
expect(() => parseSupervisor(["get", "addons"])).toThrow(UsageError);
|
|
1137
|
+
expect(() => parseSupervisor(["post", "/host/reboot", "[]"])).toThrow(/JSON object/);
|
|
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
|
+
});
|
|
1167
|
+
});
|
|
1168
|
+
|
|
1101
1169
|
describe("dns stale-zone-delete", () => {
|
|
1102
1170
|
let home: string;
|
|
1103
1171
|
const originalHome = process.env.HOME;
|