@knowttl/ha-axi 0.0.0-stage → 0.1.0-alpha.1

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.
Files changed (37) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +105 -2
  3. package/artium-inventory.json +142 -0
  4. package/axi-credential.schema.json +91 -0
  5. package/dist/cli.js +73 -0
  6. package/dist/core/credentials/config.js +218 -0
  7. package/dist/core/credentials/errors.js +38 -0
  8. package/dist/core/credentials/paths.js +32 -0
  9. package/dist/core/credentials/private-file.js +278 -0
  10. package/dist/core/credentials/redact.js +127 -0
  11. package/dist/core/output/command.js +141 -0
  12. package/dist/core/registry/credential.js +21 -0
  13. package/dist/core/registry/types.js +31 -0
  14. package/dist/core/transport/mutate-ws.js +165 -0
  15. package/dist/core/transport/mutate.js +109 -0
  16. package/dist/core/transport/rest.js +68 -0
  17. package/dist/core/transport/ws.js +50 -0
  18. package/dist/core/writes/coordinator.js +236 -0
  19. package/dist/core/writes/digest.js +29 -0
  20. package/dist/core/writes/journal.js +123 -0
  21. package/dist/core/writes/passthrough.js +17 -0
  22. package/dist/features/actions/commands.js +254 -0
  23. package/dist/features/actions/feature.js +13 -0
  24. package/dist/features/core/commands.js +164 -0
  25. package/dist/features/core/feature.js +16 -0
  26. package/dist/features/core/home.js +56 -0
  27. package/dist/features/core/writes-status.js +51 -0
  28. package/dist/features/diagnostics/commands.js +168 -0
  29. package/dist/features/diagnostics/feature.js +11 -0
  30. package/dist/features/raw/classify.js +76 -0
  31. package/dist/features/raw/commands.js +135 -0
  32. package/dist/features/raw/feature.js +15 -0
  33. package/dist/features/states/commands.js +100 -0
  34. package/dist/features/states/feature.js +8 -0
  35. package/dist/generated/registry.js +159 -0
  36. package/package.json +62 -4
  37. package/skills/ha-axi/SKILL.md +130 -0
@@ -0,0 +1,38 @@
1
+ const EXIT_CODES = {
2
+ INVALID_ARGUMENT: 2,
3
+ CONFIG_INVALID: 2,
4
+ CONFIG_INSECURE: 2,
5
+ PROFILE_REQUIRED: 2,
6
+ PROFILE_AMBIGUOUS: 2,
7
+ PROFILE_NOT_FOUND: 2,
8
+ AUTH_REQUIRED: 3,
9
+ AUTH_FAILED: 3,
10
+ FORBIDDEN: 3,
11
+ WRITE_DISABLED: 4,
12
+ CONFIRMATION_REQUIRED: 4,
13
+ CONFIRMATION_MISMATCH: 4,
14
+ CONFIRMATION_EXPIRED: 4,
15
+ NOT_FOUND: 5,
16
+ INVALID_RESPONSE: 6,
17
+ READBACK_MISMATCH: 6,
18
+ UPSTREAM_ERROR: 6,
19
+ UPSTREAM_UNREACHABLE: 6,
20
+ UPSTREAM_TIMEOUT: 6,
21
+ UNKNOWN_OUTCOME: 7,
22
+ };
23
+ export const isErrorCode = (value) => Object.hasOwn(EXIT_CODES, value);
24
+ export class AxiError extends Error {
25
+ code;
26
+ help;
27
+ constructor(code, message, help = []) {
28
+ super(message);
29
+ this.code = code;
30
+ this.help = help;
31
+ }
32
+ get exitCode() {
33
+ return EXIT_CODES[this.code];
34
+ }
35
+ }
36
+ export function errnoCode(error) {
37
+ return error instanceof Error && "code" in error && typeof error.code === "string" ? error.code : undefined;
38
+ }
@@ -0,0 +1,32 @@
1
+ import { homedir } from "node:os";
2
+ import { posix, win32 } from "node:path";
3
+ const TOOL = "ha-axi";
4
+ export const currentHost = () => ({ platform: process.platform, env: process.env, home: homedir() });
5
+ export const pathApi = (platform) => (platform === "win32" ? win32 : posix);
6
+ function setting(host, name) {
7
+ const value = host.env[name];
8
+ return value === undefined || value === "" ? undefined : value;
9
+ }
10
+ function baseDir(host, xdg, windows, windowsDefault, posixDefault) {
11
+ if (host.platform === "win32")
12
+ return setting(host, windows) ?? win32.join(host.home, "AppData", windowsDefault);
13
+ const value = setting(host, xdg);
14
+ return value !== undefined && posix.isAbsolute(value) ? value : posix.join(host.home, ...posixDefault.split("/"));
15
+ }
16
+ export const configDir = (host) => pathApi(host.platform).join(baseDir(host, "XDG_CONFIG_HOME", "APPDATA", "Roaming", ".config"), TOOL);
17
+ export const stateDir = (host) => pathApi(host.platform).join(baseDir(host, "XDG_STATE_HOME", "LOCALAPPDATA", "Local", ".local/state"), TOOL);
18
+ export function configPath(host, flag) {
19
+ const path = pathApi(host.platform);
20
+ if (flag !== undefined)
21
+ return { path: path.resolve(flag), source: "flag" };
22
+ const env = setting(host, "HA_AXI_CONFIG");
23
+ if (env !== undefined)
24
+ return { path: path.resolve(env), source: "HA_AXI_CONFIG" };
25
+ return { path: path.join(configDir(host), "config.json"), source: "default" };
26
+ }
27
+ export const defaultWriteLog = (host) => setting(host, "HA_AXI_WRITE_LOG") === undefined;
28
+ export function writeLogPath(host) {
29
+ const path = pathApi(host.platform);
30
+ const env = setting(host, "HA_AXI_WRITE_LOG");
31
+ return env === undefined ? path.join(stateDir(host), "writes.log") : path.resolve(env);
32
+ }
@@ -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,141 @@
1
+ import { isUtf8 } from "node:buffer";
2
+ import { readFileSync } from "node:fs";
3
+ import { parseArgs } from "node:util";
4
+ import { encode } from "@toon-format/toon";
5
+ import { z } from "zod";
6
+ import { AxiError, errnoCode } from "../credentials/errors.js";
7
+ const SECRET_NAME = /token|secret|passw|key|credential|bearer|auth/i;
8
+ const ENTITY_ID = /^[\p{Nd}a-z]+(?:_[\p{Nd}a-z]+)*\.[\p{Nd}a-z]+(?:_[\p{Nd}a-z]+)*$/u;
9
+ const DOMAIN = /^[\p{Nd}a-z]+(?:_[\p{Nd}a-z]+)*$/u;
10
+ const jsonObjectSchema = z.custom((value) => typeof value === "object" && value !== null && !Array.isArray(value));
11
+ export const CONFIG = { config: { type: "string" } };
12
+ export const SELECT = { ...CONFIG, profile: { type: "string" } };
13
+ export const PAYLOAD = { "payload-file": { type: "string" }, stdin: { type: "boolean" } };
14
+ export const secretName = (name) => SECRET_NAME.test(name);
15
+ export function refusedFlag(arg) {
16
+ const flag = arg.split("=")[0] ?? arg;
17
+ return secretName(flag)
18
+ ? new AxiError("INVALID_ARGUMENT", `${flag} is refused: secrets are never accepted as command-line arguments`, [
19
+ "Reference the token with `ha-axi profile set <name> --token-env <VAR>` or `--token-file <path>`",
20
+ ])
21
+ : new AxiError("INVALID_ARGUMENT", `Unknown flag ${flag}`, ["Run `ha-axi --help` to list commands"]);
22
+ }
23
+ export function parse(args, options, positionals) {
24
+ for (let index = 0; index < args.length; index++) {
25
+ const arg = args[index] ?? "";
26
+ if (arg === "--")
27
+ break;
28
+ if (!arg.startsWith("-"))
29
+ continue;
30
+ const name = arg.startsWith("--") ? (arg.slice(2).split("=")[0] ?? "") : "";
31
+ const option = Object.hasOwn(options, name) ? options[name] : undefined;
32
+ if (option === undefined)
33
+ throw refusedFlag(arg);
34
+ const next = args[index + 1];
35
+ if (option.type === "string" && !arg.includes("=") && (next === "-" || !next?.startsWith("-")))
36
+ index++;
37
+ }
38
+ let parsed;
39
+ try {
40
+ parsed = parseArgs({ args: [...args], options, allowPositionals: true, strict: true });
41
+ }
42
+ catch (error) {
43
+ throw new AxiError("INVALID_ARGUMENT", error instanceof Error ? error.message : "Invalid arguments");
44
+ }
45
+ if (parsed.positionals.length !== positionals) {
46
+ throw new AxiError("INVALID_ARGUMENT", `Expected ${String(positionals)} positional argument(s), got ${String(parsed.positionals.length)}`);
47
+ }
48
+ return parsed;
49
+ }
50
+ export const selector = (values) => ({
51
+ ...(values.config === undefined ? {} : { config: values.config }),
52
+ ...(values.profile === undefined ? {} : { profile: values.profile }),
53
+ });
54
+ const SHELL_SAFE = /^[\w@%+=:,./-]+$/;
55
+ const shellQuote = (value) => (SHELL_SAFE.test(value) ? value : `'${value.replaceAll("'", "'\\''")}'`);
56
+ export const selectorFlags = (values) => `${values.profile === undefined ? "" : ` --profile=${shellQuote(values.profile)}`}${values.config === undefined ? "" : ` --config=${shellQuote(values.config)}`}`;
57
+ export const isEntityId = (value) => ENTITY_ID.test(value);
58
+ export const isDomain = (value) => DOMAIN.test(value);
59
+ function normalizeZero(value) {
60
+ if (value === 0)
61
+ return 0;
62
+ if (Array.isArray(value))
63
+ return value.map(normalizeZero);
64
+ if (typeof value === "object" && value !== null) {
65
+ return Object.fromEntries(Object.entries(value).map(([key, item]) => [key, normalizeZero(item)]));
66
+ }
67
+ return value;
68
+ }
69
+ export const stateSchema = z.object({
70
+ entity_id: z.string().refine(isEntityId, "Expected an entity ID"),
71
+ state: z.string(),
72
+ attributes: z.record(z.string(), z.unknown().transform(normalizeZero)),
73
+ last_changed: z.iso.datetime({ offset: true }),
74
+ });
75
+ export const stateFor = (entity) => stateSchema.refine(({ entity_id }) => entity_id === entity, { path: ["entity_id"], error: "Does not match the requested entity" });
76
+ export function entityId(value, flag) {
77
+ if (!isEntityId(value))
78
+ throw new AxiError("INVALID_ARGUMENT", `${flag} must be an entity ID such as sun.sun`);
79
+ return value;
80
+ }
81
+ export const listing = (name, rows, empty) => rows.length > 0 ? { count: rows.length, [name]: rows } : { count: 0, [name]: `0 results: ${empty}` };
82
+ export function readInput(path, flag) {
83
+ try {
84
+ return readFileSync(path);
85
+ }
86
+ catch (error) {
87
+ throw new AxiError("INVALID_ARGUMENT", `${flag} ${path} cannot be read (${errnoCode(error) ?? "unknown error"})`);
88
+ }
89
+ }
90
+ function decimalValue(source) {
91
+ const [coefficient = "", exponent = "0"] = source.toLowerCase().split("e");
92
+ const [integer = "", fraction = ""] = coefficient.replace(/^-/, "").split(".");
93
+ const digits = (integer + fraction).replace(/^0+/, "");
94
+ if (digits === "")
95
+ return "0";
96
+ const significant = digits.replace(/0+$/, "");
97
+ const scale = BigInt(exponent) + BigInt(digits.length - significant.length - fraction.length);
98
+ return `${coefficient.startsWith("-") ? "-" : ""}${significant}e${String(scale)}`;
99
+ }
100
+ export async function payload(values, stdin, mode = "write") {
101
+ const file = values["payload-file"];
102
+ if (file !== undefined && values.stdin === true)
103
+ throw new AxiError("INVALID_ARGUMENT", "Use at most one of --payload-file and --stdin");
104
+ const source = file !== undefined ? readInput(file, "--payload-file") : values.stdin === true ? await stdin() : undefined;
105
+ if (source === undefined)
106
+ return undefined;
107
+ const flag = file !== undefined ? "--payload-file" : "--stdin";
108
+ if (!isUtf8(source))
109
+ throw new AxiError("INVALID_ARGUMENT", `${flag} is not valid UTF-8`);
110
+ let json;
111
+ try {
112
+ json = JSON.parse(source.toString("utf8"), mode === "raw" ? undefined : (key, value, context) => {
113
+ if (!key.isWellFormed() || (typeof value === "string" && !value.isWellFormed())) {
114
+ throw new AxiError("INVALID_ARGUMENT", `${flag} must contain only well-formed Unicode in JSON keys and strings`);
115
+ }
116
+ if (typeof value !== "number")
117
+ return value;
118
+ if (!Number.isFinite(value)) {
119
+ throw new AxiError("INVALID_ARGUMENT", `${flag} must contain only finite numbers`);
120
+ }
121
+ if (context?.source !== undefined && decimalValue(context.source) !== decimalValue(JSON.stringify(value))) {
122
+ throw new AxiError("INVALID_ARGUMENT", `${flag} contains a number that cannot be sent without rounding`);
123
+ }
124
+ return value === 0 ? 0 : value;
125
+ });
126
+ }
127
+ catch (error) {
128
+ if (error instanceof AxiError)
129
+ throw error;
130
+ throw new AxiError("INVALID_ARGUMENT", `${flag} is not valid JSON`);
131
+ }
132
+ const parsed = jsonObjectSchema.safeParse(json);
133
+ if (!parsed.success)
134
+ throw new AxiError("INVALID_ARGUMENT", `${flag} must contain a JSON object`);
135
+ return parsed.data;
136
+ }
137
+ export const render = (value, redactor) => `${redactor.output(encode(value))}\n`;
138
+ export const errorOutput = (error) => ({
139
+ error: { code: error.code, message: error.message },
140
+ ...(error.help.length > 0 ? { help: error.help } : {}),
141
+ });
@@ -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
+ });