@knowttl/ha-axi 0.0.0-stage → 0.1.0-alpha.0
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/LICENSE +21 -0
- package/README.md +76 -2
- package/artium-inventory.json +105 -0
- package/axi-credential.schema.json +91 -0
- package/dist/cli.js +63 -0
- package/dist/core/credentials/config.js +218 -0
- package/dist/core/credentials/errors.js +38 -0
- package/dist/core/credentials/paths.js +32 -0
- package/dist/core/credentials/private-file.js +278 -0
- package/dist/core/credentials/redact.js +127 -0
- package/dist/core/output/command.js +51 -0
- package/dist/core/registry/credential.js +21 -0
- package/dist/core/registry/types.js +31 -0
- package/dist/core/transport/mutate-ws.js +165 -0
- package/dist/core/transport/mutate.js +109 -0
- package/dist/core/transport/rest.js +46 -0
- package/dist/core/transport/ws.js +44 -0
- package/dist/core/writes/coordinator.js +233 -0
- package/dist/core/writes/digest.js +29 -0
- package/dist/core/writes/journal.js +123 -0
- package/dist/core/writes/passthrough.js +17 -0
- package/dist/features/core/commands.js +164 -0
- package/dist/features/core/feature.js +16 -0
- package/dist/features/core/writes-status.js +51 -0
- package/dist/features/diagnostics/commands.js +175 -0
- package/dist/features/diagnostics/feature.js +11 -0
- package/dist/features/raw/classify.js +76 -0
- package/dist/features/raw/commands.js +168 -0
- package/dist/features/raw/feature.js +15 -0
- package/dist/generated/registry.js +116 -0
- package/package.json +62 -4
- package/skills/ha-axi/SKILL.md +76 -0
|
@@ -0,0 +1,278 @@
|
|
|
1
|
+
import { execFileSync } from "node:child_process";
|
|
2
|
+
import { chmodSync, closeSync, constants, fchmodSync, fstatSync, fsyncSync, lstatSync, mkdirSync, openSync, readFileSync, renameSync, rmSync, writeFileSync, writeSync, } from "node:fs";
|
|
3
|
+
import { basename, dirname, join, win32 } from "node:path";
|
|
4
|
+
import { AxiError, errnoCode } from "./errors.js";
|
|
5
|
+
const CHECK_PATH = "$ErrorActionPreference='Stop'; $path=[IO.Path]::GetFullPath($env:HA_AXI_ACL_PATH); " +
|
|
6
|
+
"$paths=[Collections.Generic.Stack[string]]::new(); " +
|
|
7
|
+
"for ($entry=$path; $entry; $entry=[IO.Path]::GetDirectoryName($entry)) { $paths.Push($entry) }; " +
|
|
8
|
+
"foreach ($entry in $paths) { " +
|
|
9
|
+
"try { $attrs=[IO.File]::GetAttributes($entry) } catch [IO.FileNotFoundException],[IO.DirectoryNotFoundException] { break }; " +
|
|
10
|
+
"if ($attrs -band [IO.FileAttributes]::ReparsePoint) { exit 2 } }; ";
|
|
11
|
+
const TRUSTEES = "$allowed=@([System.Security.Principal.WindowsIdentity]::GetCurrent().User.Value,'S-1-5-18','S-1-5-32-544'); ";
|
|
12
|
+
const FILE_ITEM = "$directory=$env:HA_AXI_ACL_KIND -eq 'directory'; $item=if ($directory) { [IO.DirectoryInfo]::new($path) } else { [IO.FileInfo]::new($path) }; ";
|
|
13
|
+
const RESTRICT = FILE_ITEM + TRUSTEES +
|
|
14
|
+
"$acl=if ($directory) { [System.Security.AccessControl.DirectorySecurity]::new() } else { [System.Security.AccessControl.FileSecurity]::new() }; " +
|
|
15
|
+
"$acl.SetAccessRuleProtection($true,$false); " +
|
|
16
|
+
"$inherit=if ($directory) { [System.Security.AccessControl.InheritanceFlags]'ContainerInherit,ObjectInherit' } else { [System.Security.AccessControl.InheritanceFlags]::None }; " +
|
|
17
|
+
"foreach ($id in $allowed) { $sid=[System.Security.Principal.SecurityIdentifier]::new($id); " +
|
|
18
|
+
"$acl.AddAccessRule([System.Security.AccessControl.FileSystemAccessRule]::new($sid,'FullControl',$inherit,'None','Allow')) }; " +
|
|
19
|
+
"$item.SetAccessControl($acl)";
|
|
20
|
+
const VERIFY = FILE_ITEM + TRUSTEES +
|
|
21
|
+
"$acl=$item.GetAccessControl([System.Security.AccessControl.AccessControlSections]::Access); " +
|
|
22
|
+
"$rules=@($acl.GetAccessRules($true,$true,[System.Security.Principal.SecurityIdentifier])); " +
|
|
23
|
+
"if (-not $acl.AreAccessRulesProtected) { 'unprotected'; return }; " +
|
|
24
|
+
"foreach ($rule in $rules) { if ($rule.IsInherited -or $rule.AccessControlType -ne 'Allow' -or " +
|
|
25
|
+
"$rule.FileSystemRights -ne 'FullControl' -or ($rule.PropagationFlags -band [System.Security.AccessControl.PropagationFlags]::InheritOnly) -or " +
|
|
26
|
+
"$allowed -notcontains $rule.IdentityReference.Value) { 'unprotected'; return } }; " +
|
|
27
|
+
"foreach ($id in $allowed) { if ($rules.IdentityReference.Value -notcontains $id) { 'unprotected'; return } }; 'protected'";
|
|
28
|
+
function powershell(script, path, directory = false) {
|
|
29
|
+
const systemRoot = process.env["SystemRoot"];
|
|
30
|
+
if (systemRoot === undefined || !/^[a-z]:[\\/]/i.test(systemRoot))
|
|
31
|
+
throw new Error("Windows SystemRoot is unavailable");
|
|
32
|
+
return execFileSync(win32.join(systemRoot, "System32", "WindowsPowerShell", "v1.0", "powershell.exe"), ["-NoProfile", "-NonInteractive", "-EncodedCommand", Buffer.from(CHECK_PATH + script, "utf16le").toString("base64")], { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"], env: { SystemRoot: systemRoot, HA_AXI_ACL_PATH: path, HA_AXI_ACL_KIND: directory ? "directory" : "file" } });
|
|
33
|
+
}
|
|
34
|
+
export const windowsAcl = {
|
|
35
|
+
checkPath(path) {
|
|
36
|
+
powershell("", path);
|
|
37
|
+
},
|
|
38
|
+
restrict(path, directory) {
|
|
39
|
+
powershell(RESTRICT, path, directory);
|
|
40
|
+
},
|
|
41
|
+
verify(path, directory) {
|
|
42
|
+
return powershell(VERIFY, path, directory).trim() === "protected";
|
|
43
|
+
},
|
|
44
|
+
};
|
|
45
|
+
const pause = (ms) => {
|
|
46
|
+
Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
|
|
47
|
+
};
|
|
48
|
+
export class PrivateFiles {
|
|
49
|
+
#platform;
|
|
50
|
+
#acl;
|
|
51
|
+
constructor(platform = process.platform, acl = windowsAcl) {
|
|
52
|
+
this.#platform = platform;
|
|
53
|
+
this.#acl = acl;
|
|
54
|
+
}
|
|
55
|
+
#insecure(path, kind, reason) {
|
|
56
|
+
const fix = this.#platform !== "win32"
|
|
57
|
+
? `chmod 600 ${path}, owned by you, as a regular file rather than a symlink`
|
|
58
|
+
: kind === "config"
|
|
59
|
+
? "re-run `ha-axi profile set` so ha-axi rewrites it with a protected DACL"
|
|
60
|
+
: "replace it with a regular file readable only by you, not a link, junction or other reparse point";
|
|
61
|
+
return new AxiError("CONFIG_INSECURE", `${path} ${reason}`, [`Fix: ${fix}`]);
|
|
62
|
+
}
|
|
63
|
+
read(path, kind, verify = false) {
|
|
64
|
+
let before;
|
|
65
|
+
try {
|
|
66
|
+
if (this.#platform === "win32")
|
|
67
|
+
this.#acl.checkPath(path);
|
|
68
|
+
try {
|
|
69
|
+
before = lstatSync(path);
|
|
70
|
+
}
|
|
71
|
+
catch (error) {
|
|
72
|
+
if (errnoCode(error) === "ENOENT")
|
|
73
|
+
return undefined;
|
|
74
|
+
throw error;
|
|
75
|
+
}
|
|
76
|
+
if (before.isSymbolicLink())
|
|
77
|
+
throw this.#insecure(path, kind, "is a symlink or reparse point");
|
|
78
|
+
if (!before.isFile())
|
|
79
|
+
throw this.#insecure(path, kind, "is not a regular file");
|
|
80
|
+
if (this.#platform === "win32") {
|
|
81
|
+
if (verify)
|
|
82
|
+
this.#verify(path, kind);
|
|
83
|
+
return readFileSync(path, "utf8");
|
|
84
|
+
}
|
|
85
|
+
const mask = kind === "config" ? 0o022 : 0o077;
|
|
86
|
+
if (before.uid !== process.getuid?.())
|
|
87
|
+
throw this.#insecure(path, kind, "is not owned by the current user");
|
|
88
|
+
if ((before.mode & 0o400) === 0)
|
|
89
|
+
throw this.#insecure(path, kind, "is not readable by its owner");
|
|
90
|
+
if ((before.mode & mask) !== 0)
|
|
91
|
+
throw this.#insecure(path, kind, `is accessible by group or other (mode ${(before.mode & 0o777).toString(8)})`);
|
|
92
|
+
const fd = openSync(path, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
|
|
93
|
+
try {
|
|
94
|
+
const opened = fstatSync(fd);
|
|
95
|
+
if (opened.ino !== before.ino || opened.dev !== before.dev)
|
|
96
|
+
throw this.#insecure(path, kind, "changed while it was being read");
|
|
97
|
+
return readFileSync(fd, "utf8");
|
|
98
|
+
}
|
|
99
|
+
finally {
|
|
100
|
+
closeSync(fd);
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
catch (error) {
|
|
104
|
+
if (error instanceof AxiError)
|
|
105
|
+
throw error;
|
|
106
|
+
throw this.#insecure(path, kind, `cannot be read privately (${errnoCode(error) ?? "path or access check failed"})`);
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
#verify(path, kind, directory = false) {
|
|
110
|
+
try {
|
|
111
|
+
if (this.#acl.verify(path, directory))
|
|
112
|
+
return;
|
|
113
|
+
}
|
|
114
|
+
catch {
|
|
115
|
+
throw this.#insecure(path, kind, "could not be checked for a protected DACL or reparse points");
|
|
116
|
+
}
|
|
117
|
+
throw this.#insecure(path, kind, "does not carry a protected DACL granting FullControl to the current user, SYSTEM and Administrators only");
|
|
118
|
+
}
|
|
119
|
+
#directory(directory, defaultDirectory, create, durable = false) {
|
|
120
|
+
const windows = this.#platform === "win32";
|
|
121
|
+
if (windows)
|
|
122
|
+
this.#acl.checkPath(directory);
|
|
123
|
+
const firstCreated = create ? mkdirSync(directory, { recursive: true, mode: 0o700 }) : undefined;
|
|
124
|
+
const created = firstCreated !== undefined;
|
|
125
|
+
const parent = lstatSync(directory, { throwIfNoEntry: false });
|
|
126
|
+
if (parent === undefined && !create)
|
|
127
|
+
return false;
|
|
128
|
+
if (parent === undefined || !parent.isDirectory())
|
|
129
|
+
throw this.#insecure(directory, "config", "is not a regular directory");
|
|
130
|
+
if (windows) {
|
|
131
|
+
if (defaultDirectory || created)
|
|
132
|
+
this.#acl.restrict(directory, true);
|
|
133
|
+
else
|
|
134
|
+
this.#verify(directory, "config", true);
|
|
135
|
+
}
|
|
136
|
+
else {
|
|
137
|
+
if (parent.uid !== process.getuid?.())
|
|
138
|
+
throw this.#insecure(directory, "config", "is not owned by the current user");
|
|
139
|
+
if (defaultDirectory || created)
|
|
140
|
+
chmodSync(directory, 0o700);
|
|
141
|
+
else if ((parent.mode & 0o022) !== 0)
|
|
142
|
+
throw this.#insecure(directory, "config", "is writable by group or other");
|
|
143
|
+
if (durable && firstCreated !== undefined) {
|
|
144
|
+
const existingParent = dirname(firstCreated);
|
|
145
|
+
for (let path = dirname(directory);; path = dirname(path)) {
|
|
146
|
+
this.#syncDirectory(path);
|
|
147
|
+
if (path === existingParent)
|
|
148
|
+
break;
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
return true;
|
|
153
|
+
}
|
|
154
|
+
ensureDirectory(directory, defaultDirectory) {
|
|
155
|
+
try {
|
|
156
|
+
this.#directory(directory, defaultDirectory, true, true);
|
|
157
|
+
}
|
|
158
|
+
catch (error) {
|
|
159
|
+
if (error instanceof AxiError)
|
|
160
|
+
throw error;
|
|
161
|
+
throw this.#insecure(directory, "config", `could not be created privately (${errnoCode(error) ?? "unknown error"})`);
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
append(path, defaultDirectory, line) {
|
|
165
|
+
const windows = this.#platform === "win32";
|
|
166
|
+
let fd;
|
|
167
|
+
try {
|
|
168
|
+
const directory = dirname(path);
|
|
169
|
+
this.#directory(directory, defaultDirectory, true, true);
|
|
170
|
+
const before = lstatSync(path, { throwIfNoEntry: false });
|
|
171
|
+
if (before?.isSymbolicLink() === true)
|
|
172
|
+
throw this.#insecure(path, "secret", "is a symlink or reparse point");
|
|
173
|
+
if (before !== undefined && !before.isFile())
|
|
174
|
+
throw this.#insecure(path, "secret", "is not a regular file");
|
|
175
|
+
fd = openSync(path, constants.O_RDWR | constants.O_APPEND | constants.O_CREAT | (windows ? 0 : constants.O_NOFOLLOW), 0o600);
|
|
176
|
+
const opened = fstatSync(fd);
|
|
177
|
+
if (windows) {
|
|
178
|
+
if (before === undefined)
|
|
179
|
+
this.#acl.restrict(path, false);
|
|
180
|
+
else
|
|
181
|
+
this.#verify(path, "secret");
|
|
182
|
+
}
|
|
183
|
+
else {
|
|
184
|
+
if (opened.uid !== process.getuid?.())
|
|
185
|
+
throw this.#insecure(path, "secret", "is not owned by the current user");
|
|
186
|
+
if ((opened.mode & 0o077) !== 0)
|
|
187
|
+
throw this.#insecure(path, "secret", `is accessible by group or other (mode ${(opened.mode & 0o777).toString(8)})`);
|
|
188
|
+
}
|
|
189
|
+
const record = Buffer.from(opened.size > 0 ? `\n${line}` : line, "utf8");
|
|
190
|
+
if (writeSync(fd, record) !== record.byteLength)
|
|
191
|
+
throw this.#insecure(path, "secret", "could not be appended privately (short write)");
|
|
192
|
+
fsyncSync(fd);
|
|
193
|
+
if (!windows)
|
|
194
|
+
this.#syncDirectory(directory);
|
|
195
|
+
}
|
|
196
|
+
catch (error) {
|
|
197
|
+
if (error instanceof AxiError)
|
|
198
|
+
throw error;
|
|
199
|
+
throw this.#insecure(path, "secret", `could not be appended privately (${errnoCode(error) ?? "unknown error"})`);
|
|
200
|
+
}
|
|
201
|
+
finally {
|
|
202
|
+
if (fd !== undefined)
|
|
203
|
+
closeSync(fd);
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
update(path, defaultDirectory, content, create = true) {
|
|
207
|
+
const directory = dirname(path);
|
|
208
|
+
const temporary = join(directory, `.${basename(path)}.tmp`);
|
|
209
|
+
let fd;
|
|
210
|
+
let ownsTemporary = false;
|
|
211
|
+
try {
|
|
212
|
+
const windows = this.#platform === "win32";
|
|
213
|
+
if (!this.#directory(directory, defaultDirectory, create))
|
|
214
|
+
return void content();
|
|
215
|
+
fd = openSync(temporary, "wx", 0o600);
|
|
216
|
+
ownsTemporary = true;
|
|
217
|
+
if (windows)
|
|
218
|
+
this.#acl.restrict(temporary, false);
|
|
219
|
+
else
|
|
220
|
+
fchmodSync(fd, 0o600);
|
|
221
|
+
writeFileSync(fd, content());
|
|
222
|
+
fsyncSync(fd);
|
|
223
|
+
closeSync(fd);
|
|
224
|
+
fd = undefined;
|
|
225
|
+
this.#rename(temporary, path);
|
|
226
|
+
ownsTemporary = false;
|
|
227
|
+
if (!windows)
|
|
228
|
+
this.#syncDirectory(directory);
|
|
229
|
+
}
|
|
230
|
+
catch (cause) {
|
|
231
|
+
let error = cause;
|
|
232
|
+
try {
|
|
233
|
+
if (fd !== undefined)
|
|
234
|
+
closeSync(fd);
|
|
235
|
+
}
|
|
236
|
+
catch (cleanupError) {
|
|
237
|
+
error ??= cleanupError;
|
|
238
|
+
}
|
|
239
|
+
try {
|
|
240
|
+
if (ownsTemporary)
|
|
241
|
+
rmSync(temporary, { force: true });
|
|
242
|
+
}
|
|
243
|
+
catch (cleanupError) {
|
|
244
|
+
error ??= cleanupError;
|
|
245
|
+
}
|
|
246
|
+
if (error instanceof AxiError)
|
|
247
|
+
throw error;
|
|
248
|
+
if (errnoCode(error) === "EEXIST" && !ownsTemporary) {
|
|
249
|
+
throw this.#insecure(path, "config", `could not be updated because ${temporary} already exists`);
|
|
250
|
+
}
|
|
251
|
+
throw this.#insecure(path, "config", `could not be written privately (${errnoCode(error) ?? "unknown error"})`);
|
|
252
|
+
}
|
|
253
|
+
}
|
|
254
|
+
#syncDirectory(directory) {
|
|
255
|
+
const dir = openSync(directory, constants.O_RDONLY);
|
|
256
|
+
try {
|
|
257
|
+
fsyncSync(dir);
|
|
258
|
+
}
|
|
259
|
+
finally {
|
|
260
|
+
closeSync(dir);
|
|
261
|
+
}
|
|
262
|
+
}
|
|
263
|
+
#rename(from, to) {
|
|
264
|
+
const deadline = Date.now() + 1000;
|
|
265
|
+
for (;;) {
|
|
266
|
+
try {
|
|
267
|
+
renameSync(from, to);
|
|
268
|
+
return;
|
|
269
|
+
}
|
|
270
|
+
catch (error) {
|
|
271
|
+
const retryable = ["EPERM", "EBUSY", "EACCES"].includes(errnoCode(error) ?? "");
|
|
272
|
+
if (this.#platform !== "win32" || !retryable || Date.now() >= deadline)
|
|
273
|
+
throw error;
|
|
274
|
+
pause(50);
|
|
275
|
+
}
|
|
276
|
+
}
|
|
277
|
+
}
|
|
278
|
+
}
|
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
import { unescape as decodePercentEscapes } from "node:querystring";
|
|
2
|
+
const REDACTED = "[REDACTED]";
|
|
3
|
+
const MAX_URL_NESTING = 8;
|
|
4
|
+
const ENCODED_SEPARATOR = /%((?:25){0,7})(?:3f|26(?:(?:amp|%(?:\1)23(?:0*38|x0*26))%(?:\1)3b)?)/gi;
|
|
5
|
+
const ENCODED_NAME_END = /%(?:25){0,7}(?:3f|26|3d|23)|[&#?=\s"'<>\\]/gi;
|
|
6
|
+
const ENCODED_VALUE_END = /%(?:25){0,7}(?:26|23)|[&#\s"'<>\\]/gi;
|
|
7
|
+
const SECRET_KEY = /token|secret|passw|credential|api_?key|private_?key|authorization|cookie/i;
|
|
8
|
+
const SECRET_QUERY_KEY = /^(?:sig|key)$|signature|token|secret|passw|credential|api_?key|access_?key/i;
|
|
9
|
+
const PATTERNS = [
|
|
10
|
+
[/-----BEGIN [A-Z0-9 ]+-----[\s\S]*?-----END [A-Z0-9 ]+-----/g, REDACTED],
|
|
11
|
+
[/\beyJ[\w-]+\.[\w-]+\.[\w-]+/g, REDACTED],
|
|
12
|
+
[/\b(Bearer\s+)[\w.~+/=-]+/gi, `$1${REDACTED}`],
|
|
13
|
+
[/\b(AccountKey|SharedAccessSignature)=(?:(\\"|["'])(?:(?!\2)[^\r\n])*\2|[^;\s"'&]+)/gi, `$1=$2${REDACTED}$2`],
|
|
14
|
+
];
|
|
15
|
+
function redactQueryValues(text) {
|
|
16
|
+
const parameter = /(?:\?|\\u003f|(?:&|\\u0026)(?:amp;|#0*38;|#x0*26;)?)((?:[^&#?=\s"'<>\\]|\\(?:[\\/]|u(?!(?:000[9a-d]|002[02367]|003[c-f]|00a0|1680|200[\da]|202[89f]|205f|3000|feff))[\da-f]{4}))+)(?:=|\\u003d)/gi;
|
|
17
|
+
const valuePart = /[^&#\s"'<>\\]+|&#(?!0*38;)\d+;|&#x(?!0*26;)[\da-f]+;|\\+(?:\/|u(?!(?:000[9a-d]|002[02367]|003[ce]|00a0|1680|200[\da]|202[89f]|205f|3000|feff))[\da-f]{4})/iy;
|
|
18
|
+
let result = "";
|
|
19
|
+
let end = 0;
|
|
20
|
+
for (let match = parameter.exec(text); match !== null; match = parameter.exec(text)) {
|
|
21
|
+
const name = (match[1] ?? "").replace(/\\u([\da-f]{4})/gi, (_, hex) => String.fromCharCode(Number.parseInt(hex, 16)));
|
|
22
|
+
if (!SECRET_QUERY_KEY.test(decodePercentEscapes(name)))
|
|
23
|
+
continue;
|
|
24
|
+
const start = parameter.lastIndex;
|
|
25
|
+
let valueEnd = start;
|
|
26
|
+
valuePart.lastIndex = start;
|
|
27
|
+
while (valuePart.test(text))
|
|
28
|
+
valueEnd = valuePart.lastIndex;
|
|
29
|
+
if (valueEnd === start)
|
|
30
|
+
continue;
|
|
31
|
+
parameter.lastIndex = valueEnd;
|
|
32
|
+
if (REDACTED.startsWith(text.slice(start, valueEnd)))
|
|
33
|
+
continue;
|
|
34
|
+
result += text.slice(end, start) + REDACTED;
|
|
35
|
+
end = valueEnd;
|
|
36
|
+
}
|
|
37
|
+
return result + text.slice(end);
|
|
38
|
+
}
|
|
39
|
+
function nextMatch(pattern, text, from) {
|
|
40
|
+
pattern.lastIndex = from;
|
|
41
|
+
const found = pattern.exec(text);
|
|
42
|
+
return found === null ? { index: text.length, match: "" } : { index: found.index, match: found[0] };
|
|
43
|
+
}
|
|
44
|
+
function redactEncodedQueryValues(text) {
|
|
45
|
+
const separator = new RegExp(ENCODED_SEPARATOR);
|
|
46
|
+
let result = "";
|
|
47
|
+
let end = 0;
|
|
48
|
+
for (let match = separator.exec(text); match !== null; match = separator.exec(text)) {
|
|
49
|
+
const nameStart = separator.lastIndex;
|
|
50
|
+
const nameEnd = nextMatch(ENCODED_NAME_END, text, nameStart);
|
|
51
|
+
if (nameEnd.index === nameStart || nameEnd.match.toLowerCase() !== `%${match[1] ?? ""}3d`)
|
|
52
|
+
continue;
|
|
53
|
+
let name = text.slice(nameStart, nameEnd.index);
|
|
54
|
+
for (let depth = 0; depth <= MAX_URL_NESTING && name.includes("%"); depth++)
|
|
55
|
+
name = decodePercentEscapes(name);
|
|
56
|
+
if (!SECRET_QUERY_KEY.test(name))
|
|
57
|
+
continue;
|
|
58
|
+
const start = nameEnd.index + nameEnd.match.length;
|
|
59
|
+
const valueEnd = nextMatch(ENCODED_VALUE_END, text, start).index;
|
|
60
|
+
if (valueEnd === start)
|
|
61
|
+
continue;
|
|
62
|
+
separator.lastIndex = valueEnd;
|
|
63
|
+
if (REDACTED.startsWith(text.slice(start, valueEnd)))
|
|
64
|
+
continue;
|
|
65
|
+
result += text.slice(end, start) + REDACTED;
|
|
66
|
+
end = valueEnd;
|
|
67
|
+
}
|
|
68
|
+
return result + text.slice(end);
|
|
69
|
+
}
|
|
70
|
+
function redactTextFields(text) {
|
|
71
|
+
const field = /(?<!\\)(\\?")([^"\r\n]*?)\1[ \t\r\n]*:[ \t\r\n]*(?=\1)/g;
|
|
72
|
+
const plainValue = /(?:[^"\\\r\n]|\\[^\r\n])*("?)/y;
|
|
73
|
+
const escapedValue = /(?:[^\\\r\n]|\\\\(?:\\[^\r\n]|[^\\\r\n])|\\[^"\\\r\n])*(\\")?/y;
|
|
74
|
+
let result = "";
|
|
75
|
+
let end = 0;
|
|
76
|
+
for (let match = field.exec(text); match !== null; match = field.exec(text)) {
|
|
77
|
+
const [, quote = "", spelling = ""] = match;
|
|
78
|
+
const key = spelling.replace(/\\{1,2}u([\da-f]{4})/gi, (_, hex) => String.fromCharCode(Number.parseInt(hex, 16)));
|
|
79
|
+
if (!SECRET_KEY.test(key))
|
|
80
|
+
continue;
|
|
81
|
+
const start = field.lastIndex + quote.length;
|
|
82
|
+
const value = quote === '"' ? plainValue : escapedValue;
|
|
83
|
+
value.lastIndex = start;
|
|
84
|
+
const closing = value.exec(text)?.[1] ?? "";
|
|
85
|
+
result += text.slice(end, start) + REDACTED + closing;
|
|
86
|
+
end = value.lastIndex;
|
|
87
|
+
field.lastIndex = end;
|
|
88
|
+
}
|
|
89
|
+
return result + text.slice(end);
|
|
90
|
+
}
|
|
91
|
+
export class Redactor {
|
|
92
|
+
#secrets = new Set();
|
|
93
|
+
register(secret) {
|
|
94
|
+
if (secret === "")
|
|
95
|
+
return;
|
|
96
|
+
this.#secrets.add(secret);
|
|
97
|
+
this.#secrets.add(JSON.stringify(secret).slice(1, -1));
|
|
98
|
+
if (secret.isWellFormed())
|
|
99
|
+
this.#secrets.add(encodeURIComponent(secret));
|
|
100
|
+
}
|
|
101
|
+
text(value) {
|
|
102
|
+
return this.#replace(redactTextFields(value));
|
|
103
|
+
}
|
|
104
|
+
output(value) {
|
|
105
|
+
return value.replace(/[^\r\n\u2028\u2029]+/g, (line) => this.#replace(line));
|
|
106
|
+
}
|
|
107
|
+
#replace(value) {
|
|
108
|
+
let result = value;
|
|
109
|
+
for (const secret of [...this.#secrets].sort((a, b) => b.length - a.length))
|
|
110
|
+
result = result.split(secret).join(REDACTED);
|
|
111
|
+
for (const [pattern, replacement] of PATTERNS)
|
|
112
|
+
result = result.replace(pattern, replacement);
|
|
113
|
+
return redactEncodedQueryValues(redactQueryValues(result));
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
export function redactPayload(value, redactor) {
|
|
117
|
+
if (typeof value === "string")
|
|
118
|
+
return redactor.text(value);
|
|
119
|
+
if (Array.isArray(value))
|
|
120
|
+
return value.map((item) => redactPayload(item, redactor));
|
|
121
|
+
if (typeof value !== "object" || value === null)
|
|
122
|
+
return value;
|
|
123
|
+
return Object.fromEntries(Object.entries(value).map(([key, item]) => [
|
|
124
|
+
redactor.text(key),
|
|
125
|
+
SECRET_KEY.test(key) && item !== null ? REDACTED : redactPayload(item, redactor),
|
|
126
|
+
]));
|
|
127
|
+
}
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
import { parseArgs } from "node:util";
|
|
2
|
+
import { encode } from "@toon-format/toon";
|
|
3
|
+
import { AxiError } from "../credentials/errors.js";
|
|
4
|
+
const SECRET_NAME = /token|secret|passw|key|credential|bearer|auth/i;
|
|
5
|
+
export const CONFIG = { config: { type: "string" } };
|
|
6
|
+
export const SELECT = { ...CONFIG, profile: { type: "string" } };
|
|
7
|
+
export const secretName = (name) => SECRET_NAME.test(name);
|
|
8
|
+
export function refusedFlag(arg) {
|
|
9
|
+
const flag = arg.split("=")[0] ?? arg;
|
|
10
|
+
return secretName(flag)
|
|
11
|
+
? new AxiError("INVALID_ARGUMENT", `${flag} is refused: secrets are never accepted as command-line arguments`, [
|
|
12
|
+
"Reference the token with `ha-axi profile set <name> --token-env <VAR>` or `--token-file <path>`",
|
|
13
|
+
])
|
|
14
|
+
: new AxiError("INVALID_ARGUMENT", `Unknown flag ${flag}`, ["Run `ha-axi --help` to list commands"]);
|
|
15
|
+
}
|
|
16
|
+
export function parse(args, options, positionals) {
|
|
17
|
+
for (let index = 0; index < args.length; index++) {
|
|
18
|
+
const arg = args[index] ?? "";
|
|
19
|
+
if (arg === "--")
|
|
20
|
+
break;
|
|
21
|
+
if (!arg.startsWith("-"))
|
|
22
|
+
continue;
|
|
23
|
+
const name = arg.startsWith("--") ? (arg.slice(2).split("=")[0] ?? "") : "";
|
|
24
|
+
const option = Object.hasOwn(options, name) ? options[name] : undefined;
|
|
25
|
+
if (option === undefined)
|
|
26
|
+
throw refusedFlag(arg);
|
|
27
|
+
const next = args[index + 1];
|
|
28
|
+
if (option.type === "string" && !arg.includes("=") && (next === "-" || !next?.startsWith("-")))
|
|
29
|
+
index++;
|
|
30
|
+
}
|
|
31
|
+
let parsed;
|
|
32
|
+
try {
|
|
33
|
+
parsed = parseArgs({ args: [...args], options, allowPositionals: true, strict: true });
|
|
34
|
+
}
|
|
35
|
+
catch (error) {
|
|
36
|
+
throw new AxiError("INVALID_ARGUMENT", error instanceof Error ? error.message : "Invalid arguments");
|
|
37
|
+
}
|
|
38
|
+
if (parsed.positionals.length !== positionals) {
|
|
39
|
+
throw new AxiError("INVALID_ARGUMENT", `Expected ${String(positionals)} positional argument(s), got ${String(parsed.positionals.length)}`);
|
|
40
|
+
}
|
|
41
|
+
return parsed;
|
|
42
|
+
}
|
|
43
|
+
export const selector = (values) => ({
|
|
44
|
+
...(values.config === undefined ? {} : { config: values.config }),
|
|
45
|
+
...(values.profile === undefined ? {} : { profile: values.profile }),
|
|
46
|
+
});
|
|
47
|
+
export const render = (value, redactor) => `${redactor.output(encode(value))}\n`;
|
|
48
|
+
export const errorOutput = (error) => ({
|
|
49
|
+
error: { code: error.code, message: error.message },
|
|
50
|
+
...(error.help.length > 0 ? { help: error.help } : {}),
|
|
51
|
+
});
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
import { grantIdSchema } from "./types.js";
|
|
3
|
+
const secretRefSchema = z.union([
|
|
4
|
+
z.strictObject({ env: z.string().regex(/^[A-Za-z_][A-Za-z0-9_]*$/) }),
|
|
5
|
+
z.strictObject({ file: z.string().regex(/^(?:\/|[A-Za-z]:[\\/]).+/) }),
|
|
6
|
+
]);
|
|
7
|
+
const port = "(?=[0-9]{1,5}$)0*(?:[1-9][0-9]{0,3}|[1-5][0-9]{4}|6[0-4][0-9]{3}|65[0-4][0-9]{2}|655[0-2][0-9]|6553[0-5])";
|
|
8
|
+
const originPattern = new RegExp(String.raw `^https://(?:\[[0-9A-Fa-f:]+\]|[A-Za-z0-9.-]+)(?::${port})?$`);
|
|
9
|
+
export const hostedProfileSchema = z
|
|
10
|
+
.strictObject({
|
|
11
|
+
origin: z.string().regex(originPattern),
|
|
12
|
+
token: secretRefSchema.default({ env: "HA_AXI_TOKEN" }).meta({ "x-secret": true }),
|
|
13
|
+
writes: z
|
|
14
|
+
.strictObject({ allowWrites: z.boolean(), operations: z.array(grantIdSchema) })
|
|
15
|
+
.default({ allowWrites: false, operations: [] }),
|
|
16
|
+
})
|
|
17
|
+
.meta({
|
|
18
|
+
title: "Home Assistant credential profile",
|
|
19
|
+
description: "AXI Credential Standard v2 hosted profile. Secret values must be references; hosted profiles are HTTPS-only and never carry allowInsecureHttp.",
|
|
20
|
+
});
|
|
21
|
+
export const credentialSchemaJson = () => z.toJSONSchema(hostedProfileSchema, { target: "draft-7", io: "input" });
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
export const grantIdSchema = z.enum([
|
|
3
|
+
"actions.call",
|
|
4
|
+
"states.set",
|
|
5
|
+
"events.fire",
|
|
6
|
+
"automations.write",
|
|
7
|
+
"automations.delete",
|
|
8
|
+
"scripts.write",
|
|
9
|
+
"scripts.delete",
|
|
10
|
+
"scenes.write",
|
|
11
|
+
"scenes.delete",
|
|
12
|
+
"registries.write",
|
|
13
|
+
"registries.delete",
|
|
14
|
+
"helpers.create",
|
|
15
|
+
"helpers.update",
|
|
16
|
+
"helpers.delete",
|
|
17
|
+
"dashboards.write",
|
|
18
|
+
"dashboards.delete",
|
|
19
|
+
]);
|
|
20
|
+
const commandName = z.string().regex(/^[a-z][a-z-]*( [a-z][a-z-]*)*$/);
|
|
21
|
+
const summary = z.string().min(1);
|
|
22
|
+
const hosted = z.literal("blocked").optional();
|
|
23
|
+
export const commandSchema = z.discriminatedUnion("effect", [
|
|
24
|
+
z.strictObject({ name: commandName, effect: z.literal("read"), hosted, summary }),
|
|
25
|
+
z.strictObject({ name: commandName, effect: z.literal("write"), grantId: grantIdSchema, hosted, summary }),
|
|
26
|
+
z.strictObject({ name: commandName, effect: z.literal("passthrough"), hosted, summary }),
|
|
27
|
+
]);
|
|
28
|
+
export const featureSchema = z.strictObject({
|
|
29
|
+
name: z.string().regex(/^[a-z][a-z0-9-]*$/),
|
|
30
|
+
commands: z.array(commandSchema),
|
|
31
|
+
});
|
|
@@ -0,0 +1,165 @@
|
|
|
1
|
+
import { setTimeout as delay } from "node:timers/promises";
|
|
2
|
+
import WebSocket from "ws";
|
|
3
|
+
import { z } from "zod";
|
|
4
|
+
import { AxiError, errnoCode } from "../credentials/errors.js";
|
|
5
|
+
import { authFailed, DEFAULT_TIMEOUT_MS, rejectedStatus, transportError, UNKNOWN_OUTCOME } from "./mutate.js";
|
|
6
|
+
import { statusError } from "./rest.js";
|
|
7
|
+
const MAX_WS_MESSAGE_BYTES = 16 * 1024 * 1024;
|
|
8
|
+
const COMMAND_ID = 1;
|
|
9
|
+
const MAX_HANDSHAKE_BODY_BYTES = 64 * 1024;
|
|
10
|
+
const UPGRADE_HELP = "Allow WebSocket upgrades on /api/websocket in Home Assistant and any proxy";
|
|
11
|
+
const frameSchema = z.object({ type: z.string(), id: z.unknown().optional() });
|
|
12
|
+
const vendorErrorSchema = z.custom((value) => typeof value === "object" && value !== null &&
|
|
13
|
+
"code" in value && typeof value.code === "string" &&
|
|
14
|
+
"message" in value && typeof value.message === "string");
|
|
15
|
+
const resultSchema = z.discriminatedUnion("success", [
|
|
16
|
+
z.object({ success: z.literal(true), result: z.unknown().nonoptional() }),
|
|
17
|
+
z.object({ success: z.literal(false), error: vendorErrorSchema }),
|
|
18
|
+
]);
|
|
19
|
+
async function handshakeBody(response) {
|
|
20
|
+
const chunks = [];
|
|
21
|
+
let size = 0;
|
|
22
|
+
try {
|
|
23
|
+
const body = response;
|
|
24
|
+
for await (const chunk of body) {
|
|
25
|
+
chunks.push(chunk.subarray(0, MAX_HANDSHAKE_BODY_BYTES - size));
|
|
26
|
+
size += chunk.byteLength;
|
|
27
|
+
if (size >= MAX_HANDSHAKE_BODY_BYTES)
|
|
28
|
+
break;
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
catch {
|
|
32
|
+
return "";
|
|
33
|
+
}
|
|
34
|
+
return Buffer.concat(chunks).toString("utf8");
|
|
35
|
+
}
|
|
36
|
+
async function handshakeError(response, label, remainingMs) {
|
|
37
|
+
const status = response.statusCode ?? 0;
|
|
38
|
+
const rejected = rejectedStatus(response, label);
|
|
39
|
+
if (rejected !== undefined) {
|
|
40
|
+
return rejected.code === "AUTH_FAILED"
|
|
41
|
+
? new AxiError(rejected.code, `${label} upgrade was refused before authentication (HTTP ${String(status)})`, [UPGRADE_HELP])
|
|
42
|
+
: rejected;
|
|
43
|
+
}
|
|
44
|
+
const body = status === 403 && remainingMs > 0
|
|
45
|
+
? await Promise.race([handshakeBody(response), delay(Math.min(1_000, remainingMs), "", { ref: false })])
|
|
46
|
+
: "";
|
|
47
|
+
return statusError(status, body, label, UPGRADE_HELP);
|
|
48
|
+
}
|
|
49
|
+
export function mutateWs(session, request, effect) {
|
|
50
|
+
const url = new URL("/api/websocket", session.origin);
|
|
51
|
+
url.protocol = url.protocol === "https:" ? "wss:" : "ws:";
|
|
52
|
+
const label = `WebSocket command ${request.type}`;
|
|
53
|
+
return new Promise((resolve, reject) => {
|
|
54
|
+
let command;
|
|
55
|
+
try {
|
|
56
|
+
command = JSON.stringify({ ...request.payload, id: COMMAND_ID, type: request.type });
|
|
57
|
+
}
|
|
58
|
+
catch {
|
|
59
|
+
reject(new AxiError("INVALID_ARGUMENT", "Payload cannot be serialized"));
|
|
60
|
+
return;
|
|
61
|
+
}
|
|
62
|
+
let phase = "connecting";
|
|
63
|
+
const socket = new WebSocket(url, {
|
|
64
|
+
headers: { "user-agent": session.userAgent },
|
|
65
|
+
maxPayload: MAX_WS_MESSAGE_BYTES,
|
|
66
|
+
perMessageDeflate: false,
|
|
67
|
+
followRedirects: false,
|
|
68
|
+
rejectUnauthorized: true,
|
|
69
|
+
});
|
|
70
|
+
const unknownOutcome = () => effect === "write" && phase === "sent";
|
|
71
|
+
const settle = (outcome) => {
|
|
72
|
+
if (phase === "settled")
|
|
73
|
+
return;
|
|
74
|
+
const invalidWriteReply = outcome instanceof AxiError && outcome.code === "INVALID_RESPONSE" && unknownOutcome();
|
|
75
|
+
phase = "settled";
|
|
76
|
+
clearTimeout(timer);
|
|
77
|
+
socket.terminate();
|
|
78
|
+
if (outcome instanceof AxiError)
|
|
79
|
+
reject(invalidWriteReply
|
|
80
|
+
? new AxiError(outcome.code, outcome.message, [...outcome.help, UNKNOWN_OUTCOME])
|
|
81
|
+
: outcome);
|
|
82
|
+
else
|
|
83
|
+
resolve(outcome);
|
|
84
|
+
};
|
|
85
|
+
const timeoutMs = request.timeoutMs ?? DEFAULT_TIMEOUT_MS;
|
|
86
|
+
const deadline = performance.now() + timeoutMs;
|
|
87
|
+
const timer = setTimeout(() => {
|
|
88
|
+
settle(transportError(undefined, session.origin, true, phase === "sent", effect));
|
|
89
|
+
}, timeoutMs);
|
|
90
|
+
const handle = (message) => {
|
|
91
|
+
if (phase === "settled")
|
|
92
|
+
return;
|
|
93
|
+
const frame = frameSchema.safeParse(message);
|
|
94
|
+
if (!frame.success) {
|
|
95
|
+
settle(new AxiError("INVALID_RESPONSE", `${label} received a WebSocket message with no type`));
|
|
96
|
+
return;
|
|
97
|
+
}
|
|
98
|
+
const { type, id } = frame.data;
|
|
99
|
+
if (type === "auth_required" && phase === "connecting") {
|
|
100
|
+
phase = "authenticating";
|
|
101
|
+
socket.send(JSON.stringify({ type: "auth", access_token: session.token }));
|
|
102
|
+
}
|
|
103
|
+
else if (type === "auth_ok" && phase === "authenticating") {
|
|
104
|
+
phase = "sent";
|
|
105
|
+
socket.send(command);
|
|
106
|
+
}
|
|
107
|
+
else if (type === "auth_invalid") {
|
|
108
|
+
settle(authFailed(label, "auth_invalid"));
|
|
109
|
+
}
|
|
110
|
+
else if (phase === "sent" && type === "result" && id !== COMMAND_ID) {
|
|
111
|
+
if (!Number.isInteger(id))
|
|
112
|
+
settle(new AxiError("INVALID_RESPONSE", `${label} received a result frame without an integer id`));
|
|
113
|
+
}
|
|
114
|
+
else if (phase === "sent" && type === "result") {
|
|
115
|
+
const reply = resultSchema.safeParse(message);
|
|
116
|
+
if (!reply.success)
|
|
117
|
+
settle(new AxiError("INVALID_RESPONSE", `${label} returned a result frame with an unexpected shape`));
|
|
118
|
+
else
|
|
119
|
+
settle(reply.data.success ? { success: true, result: reply.data.result } : { success: false, error: reply.data.error });
|
|
120
|
+
}
|
|
121
|
+
else if (phase === "sent" && request.type === "ping" && type === "pong" && id === COMMAND_ID) {
|
|
122
|
+
settle({ success: true, result: null });
|
|
123
|
+
}
|
|
124
|
+
};
|
|
125
|
+
socket.addEventListener("message", ({ data }) => {
|
|
126
|
+
if (typeof data !== "string") {
|
|
127
|
+
settle(new AxiError("INVALID_RESPONSE", `${label} received a binary WebSocket message`));
|
|
128
|
+
return;
|
|
129
|
+
}
|
|
130
|
+
let parsed;
|
|
131
|
+
try {
|
|
132
|
+
parsed = JSON.parse(data);
|
|
133
|
+
}
|
|
134
|
+
catch {
|
|
135
|
+
settle(new AxiError("INVALID_RESPONSE", `${label} received a WebSocket message that is not JSON`));
|
|
136
|
+
return;
|
|
137
|
+
}
|
|
138
|
+
const messages = Array.isArray(parsed) ? parsed : [parsed];
|
|
139
|
+
for (const message of messages)
|
|
140
|
+
handle(message);
|
|
141
|
+
});
|
|
142
|
+
socket.on("unexpected-response", (_request, response) => {
|
|
143
|
+
clearTimeout(timer);
|
|
144
|
+
void handshakeError(response, label, deadline - performance.now()).then(settle);
|
|
145
|
+
});
|
|
146
|
+
socket.on("error", (error) => {
|
|
147
|
+
const code = errnoCode(error);
|
|
148
|
+
if (code === "WS_ERR_INVALID_UTF8") {
|
|
149
|
+
settle(new AxiError("INVALID_RESPONSE", `${label} received a WebSocket message with invalid UTF-8`));
|
|
150
|
+
}
|
|
151
|
+
else if (code === "WS_ERR_UNSUPPORTED_MESSAGE_LENGTH") {
|
|
152
|
+
settle(new AxiError("UPSTREAM_ERROR", `${label} exceeded the ${String(MAX_WS_MESSAGE_BYTES)}-byte message limit`, unknownOutcome() ? [UNKNOWN_OUTCOME] : []));
|
|
153
|
+
}
|
|
154
|
+
else {
|
|
155
|
+
settle(transportError(error, session.origin, false, phase === "sent", effect));
|
|
156
|
+
}
|
|
157
|
+
});
|
|
158
|
+
socket.on("close", (code) => {
|
|
159
|
+
const sent = phase === "sent";
|
|
160
|
+
const help = unknownOutcome() ? [UNKNOWN_OUTCOME] : sent ? [] : ["Check the profile origin and that Home Assistant is running"];
|
|
161
|
+
const stage = sent ? "returned a result" : "was sent";
|
|
162
|
+
settle(new AxiError("UPSTREAM_UNREACHABLE", `${session.origin} closed the connection before ${label} ${stage} (close code ${String(code)})`, help));
|
|
163
|
+
});
|
|
164
|
+
});
|
|
165
|
+
}
|