@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 ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 knowttl
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,77 @@
1
- # Temporary Holding Version
1
+ # ha-axi
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Home Assistant OS core admin AXI CLI for agents (strict TypeScript, standalone and via artium-axi).
4
+
5
+ `ha-axi` gives an AI agent UI-free command-line access to Home Assistant OS core commands, diagnostics and raw REST and WebSocket fallbacks.
6
+ It follows the AXI Credential Standard v2 (with one approved standalone deviation for local LAN HTTP) and sends no telemetry.
7
+
8
+ ## Status
9
+
10
+ Unit `S1a` is in place: the repository scaffold, the `pnpm run check` gate with rule-proofs for `TYPE-001` to `TYPE-009`, the feature registry generator, the packaged skill and `--help` contract, and the offline network guard.
11
+ Unit `S1b` adds local credential and profile management.
12
+ Unit `S1c` adds the REST transport, `doctor`, `status`, `config check` and the raw `api` fallback.
13
+ Unit `S1d` adds the WebSocket transport and the raw `ws` fallback.
14
+ Unit `S1e` adds the [dedicated write coordinator](docs/design/design.md#write-lifecycle-preview-confirmation-pre-dispatch-intent-and-crash-recovery) and local write journal inspection.
15
+ Unit `S1f` (`ha-axi` side) names the npm package `@knowttl/ha-axi` and ships the [hosted integration artifacts](docs/design/design.md#artium-hosted-contract-s1f).
16
+ Unit `S2` adds [diagnostics commands](skills/ha-axi/SKILL.md#commands) for logs, repairs, integrations, templates, history and logbook.
17
+ The package is awaiting its first npm release.
18
+ More Home Assistant commands arrive in later units; see the [implementation plan](docs/design/implementation-plan.md).
19
+
20
+ ## Setup
21
+
22
+ Requires Node `>=24.11.0` and pnpm `10.34.6` (Corepack reads `packageManager` from `package.json`).
23
+ Development runs on Linux, including WSL 2.
24
+ The test suite also needs `openssl` on `PATH` to create the fake Home Assistant server's test CA.
25
+
26
+ ```sh
27
+ pnpm install --frozen-lockfile --config.confirm-modules-purge=false
28
+ ```
29
+
30
+ ## Check
31
+
32
+ ```sh
33
+ pnpm run check
34
+ ```
35
+
36
+ This one command runs the no-comments, file-length, layout, boundary and registry checks, `tsc`, ESLint, the package build and the offline Vitest suite.
37
+ After those checks pass, it runs the rule-proofs when the current [rule inputs](docs/testing.md#rule-proofs) have no cached success.
38
+ Last, it runs the [opt-in Artium check](docs/testing.md#opt-in-artium-check).
39
+ The aggregate check must pass before a change is complete.
40
+ See the [testing policy](docs/testing.md) for each step and the testing rules.
41
+
42
+ ## Usage
43
+
44
+ ```sh
45
+ pnpm run build
46
+ node dist/cli.js --help
47
+ ```
48
+
49
+ Set `HA_AXI_TOKEN` in your environment to a Home Assistant long-lived access token, then save a profile that references it and check credential resolution locally.
50
+ Replace `https://ha.example.com:8123` with your Home Assistant origin.
51
+
52
+ ```sh
53
+ node dist/cli.js profile set home --origin https://ha.example.com:8123 --token-env HA_AXI_TOKEN
54
+ node dist/cli.js auth status --profile home
55
+ node dist/cli.js doctor --profile home
56
+ node dist/cli.js api GET /api/calendars --profile home
57
+ node dist/cli.js ws get_config --profile home
58
+ node dist/cli.js logs list --level warning --profile home
59
+ node dist/cli.js history get sun.sun --since 1h --profile home
60
+ ```
61
+
62
+ The [packaged agent skill](skills/ha-axi/SKILL.md#credentials) explains profile selection, credential paths and the standalone LAN HTTP option.
63
+ The [raw fallback contract](docs/design/design.md#raw-api-fallbacks-passthrough-policy-single-classifier) explains which `api` and `ws` calls can write and how to enable read-only mode.
64
+
65
+ Use `node dist/cli.js writes pending` to find writes that need reconciliation, then run `node dist/cli.js writes status <entryId>` for the entry and its guidance.
66
+ See the [write journal inspection contract](docs/design/design.md#write-journal-inspection).
67
+
68
+ ## Documentation
69
+
70
+ - [Design](docs/design/design.md), including the 2026-11-30 amendments (public MIT repository, raw passthrough policy, WSL development).
71
+ - [Implementation plan](docs/design/implementation-plan.md).
72
+ - [Testing policy](docs/testing.md).
73
+ - [Packaged agent skill](skills/ha-axi/SKILL.md).
74
+
75
+ ## Licence
76
+
77
+ [MIT](LICENSE).
@@ -0,0 +1,105 @@
1
+ {
2
+ "tool": "ha-axi",
3
+ "commands": [
4
+ {
5
+ "name": "help",
6
+ "effect": "read",
7
+ "summary": "List every ha-axi command with its effect"
8
+ },
9
+ {
10
+ "name": "auth status",
11
+ "effect": "read",
12
+ "summary": "Show the selected profile, origin and token source without contacting Home Assistant"
13
+ },
14
+ {
15
+ "name": "profile list",
16
+ "effect": "read",
17
+ "summary": "List the profiles in config.json"
18
+ },
19
+ {
20
+ "name": "profile set",
21
+ "effect": "read",
22
+ "summary": "Create or replace a local profile in config.json; sends no Home Assistant request"
23
+ },
24
+ {
25
+ "name": "profile remove",
26
+ "effect": "read",
27
+ "summary": "Remove a local profile from config.json; sends no Home Assistant request"
28
+ },
29
+ {
30
+ "name": "config path",
31
+ "effect": "read",
32
+ "summary": "Print the config.json and writes.log paths"
33
+ },
34
+ {
35
+ "name": "doctor",
36
+ "effect": "read",
37
+ "summary": "Check the profile and credentials with one bounded GET /api/config"
38
+ },
39
+ {
40
+ "name": "status",
41
+ "effect": "read",
42
+ "summary": "Show the Home Assistant version, state, location and component count"
43
+ },
44
+ {
45
+ "name": "config check",
46
+ "effect": "read",
47
+ "summary": "Validate the Home Assistant configuration (read-only POST)"
48
+ },
49
+ {
50
+ "name": "writes status",
51
+ "effect": "read",
52
+ "summary": "Show one writes.log entry and its outcome, with reconciliation guidance when the outcome is unknown"
53
+ },
54
+ {
55
+ "name": "writes pending",
56
+ "effect": "read",
57
+ "summary": "List journaled writes whose outcome is pending or unknown"
58
+ },
59
+ {
60
+ "name": "logs list",
61
+ "effect": "read",
62
+ "summary": "List system log entries at or above an optional --level, with source file and occurrence count"
63
+ },
64
+ {
65
+ "name": "repairs list",
66
+ "effect": "read",
67
+ "summary": "List repair issues with domain, severity and whether each is fixable or ignored"
68
+ },
69
+ {
70
+ "name": "integrations list",
71
+ "effect": "read",
72
+ "summary": "List integration config entries with domain, title and load state"
73
+ },
74
+ {
75
+ "name": "template render",
76
+ "effect": "read",
77
+ "summary": "Render a Jinja2 template and print the text result (read-only POST)"
78
+ },
79
+ {
80
+ "name": "history get",
81
+ "effect": "read",
82
+ "summary": "Show an entity's state timeline since a duration ago"
83
+ },
84
+ {
85
+ "name": "logbook list",
86
+ "effect": "read",
87
+ "summary": "List logbook entries since a duration ago, optionally for one entity"
88
+ },
89
+ {
90
+ "name": "api",
91
+ "effect": "passthrough",
92
+ "summary": "Send a REST request under /api/; writes pass through unless HA_AXI_READ_ONLY=true, deferred v2 families are refused"
93
+ },
94
+ {
95
+ "name": "ws",
96
+ "effect": "passthrough",
97
+ "summary": "Send a WebSocket command; writes pass through unless HA_AXI_READ_ONLY=true, deferred v2 families are refused"
98
+ }
99
+ ],
100
+ "confirmedWrites": [],
101
+ "blockedCommands": [
102
+ "profile set",
103
+ "profile remove"
104
+ ]
105
+ }
@@ -0,0 +1,91 @@
1
+ {
2
+ "$schema": "http://json-schema.org/draft-07/schema#",
3
+ "type": "object",
4
+ "properties": {
5
+ "origin": {
6
+ "type": "string",
7
+ "pattern": "^https:\\/\\/(?:\\[[0-9A-Fa-f:]+\\]|[A-Za-z0-9.-]+)(?::(?=[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
+ },
9
+ "token": {
10
+ "default": {
11
+ "env": "HA_AXI_TOKEN"
12
+ },
13
+ "x-secret": true,
14
+ "anyOf": [
15
+ {
16
+ "type": "object",
17
+ "properties": {
18
+ "env": {
19
+ "type": "string",
20
+ "pattern": "^[A-Za-z_][A-Za-z0-9_]*$"
21
+ }
22
+ },
23
+ "required": [
24
+ "env"
25
+ ],
26
+ "additionalProperties": false
27
+ },
28
+ {
29
+ "type": "object",
30
+ "properties": {
31
+ "file": {
32
+ "type": "string",
33
+ "pattern": "^(?:\\/|[A-Za-z]:[\\\\/]).+"
34
+ }
35
+ },
36
+ "required": [
37
+ "file"
38
+ ],
39
+ "additionalProperties": false
40
+ }
41
+ ]
42
+ },
43
+ "writes": {
44
+ "default": {
45
+ "allowWrites": false,
46
+ "operations": []
47
+ },
48
+ "type": "object",
49
+ "properties": {
50
+ "allowWrites": {
51
+ "type": "boolean"
52
+ },
53
+ "operations": {
54
+ "type": "array",
55
+ "items": {
56
+ "type": "string",
57
+ "enum": [
58
+ "actions.call",
59
+ "states.set",
60
+ "events.fire",
61
+ "automations.write",
62
+ "automations.delete",
63
+ "scripts.write",
64
+ "scripts.delete",
65
+ "scenes.write",
66
+ "scenes.delete",
67
+ "registries.write",
68
+ "registries.delete",
69
+ "helpers.create",
70
+ "helpers.update",
71
+ "helpers.delete",
72
+ "dashboards.write",
73
+ "dashboards.delete"
74
+ ]
75
+ }
76
+ }
77
+ },
78
+ "required": [
79
+ "allowWrites",
80
+ "operations"
81
+ ],
82
+ "additionalProperties": false
83
+ }
84
+ },
85
+ "required": [
86
+ "origin"
87
+ ],
88
+ "additionalProperties": false,
89
+ "title": "Home Assistant credential profile",
90
+ "description": "AXI Credential Standard v2 hosted profile. Secret values must be references; hosted profiles are HTTPS-only and never carry allowInsecureHttp."
91
+ }
package/dist/cli.js ADDED
@@ -0,0 +1,63 @@
1
+ #!/usr/bin/env node
2
+ import { readFileSync } from "node:fs";
3
+ import { buffer } from "node:stream/consumers";
4
+ import { encode } from "@toon-format/toon";
5
+ import { z } from "zod";
6
+ import { AxiError } from "./core/credentials/errors.js";
7
+ import { currentHost } from "./core/credentials/paths.js";
8
+ import { PrivateFiles } from "./core/credentials/private-file.js";
9
+ import { Redactor } from "./core/credentials/redact.js";
10
+ import { errorOutput, refusedFlag, render } from "./core/output/command.js";
11
+ import { handlers as coreHandlers } from "./features/core/commands.js";
12
+ import { handlers as diagnosticsHandlers } from "./features/diagnostics/commands.js";
13
+ import { handlers as rawHandlers } from "./features/raw/commands.js";
14
+ import { registry } from "./generated/registry.js";
15
+ const packageSchema = z.object({ version: z.string() });
16
+ const handlers = { ...coreHandlers, ...diagnosticsHandlers, ...rawHandlers };
17
+ function version() {
18
+ const raw = JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8"));
19
+ return packageSchema.parse(raw).version;
20
+ }
21
+ function help() {
22
+ const commands = registry.features.flatMap((feature) => feature.commands.map((command) => ({ name: command.name, effect: command.effect, summary: command.summary })));
23
+ return encode({
24
+ tool: "ha-axi",
25
+ description: "Home Assistant OS core admin AXI CLI",
26
+ commands,
27
+ help: ["Run `ha-axi --version` to print the installed version"],
28
+ });
29
+ }
30
+ async function main(args) {
31
+ const [first, ...rest] = args;
32
+ if (rest.length === 0 && (first === undefined || first === "help" || first === "--help" || first === "-h")) {
33
+ process.stdout.write(`${help()}\n`);
34
+ return 0;
35
+ }
36
+ if (rest.length === 0 && first === "--version") {
37
+ process.stdout.write(`ha-axi ${version()}\n`);
38
+ return 0;
39
+ }
40
+ const redactor = new Redactor();
41
+ const name = Object.keys(handlers).find((key) => key.split(" ").every((word, index) => args[index] === word));
42
+ try {
43
+ const handler = name === undefined ? undefined : handlers[name];
44
+ if (name === undefined || handler === undefined) {
45
+ const flag = args.slice(0, 2).find((arg) => arg.startsWith("-"));
46
+ if (flag !== undefined)
47
+ throw refusedFlag(flag);
48
+ throw new AxiError("INVALID_ARGUMENT", "Unknown command", ["Run `ha-axi --help` to list commands"]);
49
+ }
50
+ const context = { host: currentHost(), files: new PrivateFiles(), redactor, userAgent: `ha-axi/${version()}`, stdin: () => buffer(process.stdin) };
51
+ process.stdout.write(render(await handler(args.slice(name.split(" ").length), context), redactor));
52
+ return 0;
53
+ }
54
+ catch (error) {
55
+ if (!(error instanceof AxiError)) {
56
+ process.stderr.write("Unexpected error\n");
57
+ return 1;
58
+ }
59
+ process.stdout.write(render(errorOutput(error), redactor));
60
+ return error.exitCode;
61
+ }
62
+ }
63
+ process.exitCode = await main(process.argv.slice(2));
@@ -0,0 +1,218 @@
1
+ import { z } from "zod";
2
+ import { AxiError } from "./errors.js";
3
+ import { configPath, pathApi } from "./paths.js";
4
+ const PROFILE_NAME = /^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/;
5
+ const SECRET_REF_HINT = 'must be a SecretRef {"env": "NAME"} or {"file": "/absolute/path"}; inline secret values and {"stored": true} are not accepted';
6
+ const secretRefSchema = z.union([
7
+ z.strictObject({ env: z.string().regex(/^[A-Za-z_][A-Za-z0-9_]*$/) }),
8
+ z.strictObject({ file: z.string().min(1) }),
9
+ ]);
10
+ const writesSchema = z.strictObject({ allowWrites: z.boolean(), operations: z.array(z.string()) });
11
+ const profileSchema = z.strictObject({
12
+ origin: z.string(),
13
+ token: secretRefSchema.optional(),
14
+ allowInsecureHttp: z.boolean().optional(),
15
+ writes: writesSchema.optional(),
16
+ });
17
+ const configSchema = z.strictObject({
18
+ version: z.literal(1),
19
+ defaultProfile: z.string().regex(PROFILE_NAME).optional(),
20
+ profiles: z.record(z.string().regex(PROFILE_NAME), profileSchema),
21
+ });
22
+ export const DEFAULT_TOKEN = { env: "HA_AXI_TOKEN" };
23
+ const READ_ONLY_WRITES = { allowWrites: false, operations: [] };
24
+ const invalid = (message, help = []) => new AxiError("CONFIG_INVALID", message, help);
25
+ export function envBoolean(env, name) {
26
+ const value = env[name]?.toLowerCase();
27
+ if (value === undefined || value === "0" || value === "false")
28
+ return false;
29
+ if (value === "1" || value === "true")
30
+ return true;
31
+ throw invalid(`${name} must be 1, true, 0 or false`);
32
+ }
33
+ function privateHost(hostname) {
34
+ const host = hostname.toLowerCase();
35
+ if (host.startsWith("[")) {
36
+ const ip = host.slice(1, -1);
37
+ return ip === "::1" || /^f[cd][0-9a-f]{2}:/.test(ip) || /^fe[89ab][0-9a-f]:/.test(ip);
38
+ }
39
+ const octets = /^(\d+)\.(\d+)\.\d+\.\d+$/.exec(host);
40
+ if (octets !== null) {
41
+ const a = Number(octets[1]);
42
+ const b = Number(octets[2]);
43
+ return a === 127 || a === 10 || (a === 172 && b >= 16 && b <= 31) || (a === 192 && b === 168) || (a === 169 && b === 254);
44
+ }
45
+ return host === "localhost" || host.endsWith(".local") || !host.includes(".");
46
+ }
47
+ export function originProblem(origin, allowInsecureHttp) {
48
+ let url;
49
+ try {
50
+ url = new URL(origin);
51
+ }
52
+ catch {
53
+ return "is not a valid URL";
54
+ }
55
+ if (!/^[a-z][a-z\d+.-]*:\/\/[^/\\?#@\s]+$/i.test(origin) || /\p{Cc}/u.test(origin))
56
+ return "must be a bare origin such as https://ha.example.com:8123, with no path, query, userinfo, fragment or trailing slash";
57
+ if (url.protocol === "https:")
58
+ return undefined;
59
+ if (url.protocol !== "http:")
60
+ return "must use https://";
61
+ if (!allowInsecureHttp)
62
+ return "uses http://, which needs allowInsecureHttp: true and a local or private host";
63
+ if (!privateHost(url.hostname)) {
64
+ return "uses http:// with a host that is not loopback, RFC 1918, link-local, IPv6 ULA, .local or a single-label LAN name";
65
+ }
66
+ return undefined;
67
+ }
68
+ function filePathProblem(path, platform) {
69
+ if (platform === "win32") {
70
+ return /^[A-Za-z]:[\\/]/.test(path) ? undefined : "must be an absolute drive path such as C:\\secrets\\ha-token; relative, UNC and device paths are refused";
71
+ }
72
+ return pathApi(platform).isAbsolute(path) ? undefined : "must be an absolute path";
73
+ }
74
+ export function profileProblems(profile, platform) {
75
+ const problems = [];
76
+ const origin = originProblem(profile.origin, profile.allowInsecureHttp ?? false);
77
+ if (origin !== undefined)
78
+ problems.push(`origin ${origin}`);
79
+ if (profile.token !== undefined && "file" in profile.token) {
80
+ const file = filePathProblem(profile.token.file, platform);
81
+ if (file !== undefined)
82
+ problems.push(`token.file ${file}`);
83
+ }
84
+ return problems;
85
+ }
86
+ function issueText(error) {
87
+ const [issue] = error.issues;
88
+ const path = issue?.path.map(String).join(".") ?? "";
89
+ const tokenField = issue?.path.at(-1) === "token" && (issue.path.length === 1 || issue.path.length === 3);
90
+ const message = tokenField ? SECRET_REF_HINT : (issue?.message ?? "is invalid");
91
+ return `field ${path === "" ? "(root)" : path}: ${message}`;
92
+ }
93
+ export function parseConfig(raw, location, platform) {
94
+ let json;
95
+ try {
96
+ json = JSON.parse(raw);
97
+ }
98
+ catch {
99
+ throw invalid(`${location} is not valid JSON`);
100
+ }
101
+ const parsed = configSchema.safeParse(json);
102
+ if (!parsed.success)
103
+ throw invalid(`${location} ${issueText(parsed.error)}`);
104
+ const config = parsed.data;
105
+ for (const [name, profile] of Object.entries(config.profiles)) {
106
+ const [problem] = profileProblems(profile, platform);
107
+ if (problem !== undefined)
108
+ throw invalid(`${location} field profiles.${name}.${problem}`);
109
+ }
110
+ if (config.defaultProfile !== undefined && !Object.hasOwn(config.profiles, config.defaultProfile)) {
111
+ throw invalid(`${location} field defaultProfile names a profile that does not exist`);
112
+ }
113
+ return config;
114
+ }
115
+ export function loadConfig(location, files, platform, verify = false) {
116
+ const raw = files.read(location.path, "config", verify);
117
+ if (raw !== undefined)
118
+ return parseConfig(raw, location.path, platform);
119
+ if (location.source !== "default")
120
+ throw invalid(`${location.path} (selected by ${location.source === "flag" ? "--config" : "HA_AXI_CONFIG"}) does not exist`);
121
+ return { version: 1, profiles: {} };
122
+ }
123
+ function fromFile(config, location, name, selectedBy, readOnly) {
124
+ const profile = Object.hasOwn(config.profiles, name) ? config.profiles[name] : undefined;
125
+ if (profile === undefined) {
126
+ throw new AxiError("PROFILE_NOT_FOUND", `Profile ${name} is not defined in ${location.path}`, ["Run `ha-axi profile list` to see the defined profiles"]);
127
+ }
128
+ return {
129
+ name,
130
+ selectedBy,
131
+ config: location,
132
+ fromFile: true,
133
+ origin: profile.origin,
134
+ allowInsecureHttp: profile.allowInsecureHttp ?? false,
135
+ token: profile.token ?? DEFAULT_TOKEN,
136
+ writes: profile.writes ?? READ_ONLY_WRITES,
137
+ readOnly,
138
+ };
139
+ }
140
+ export function selectProfile(options, host, files) {
141
+ const readOnly = envBoolean(host.env, "HA_AXI_READ_ONLY");
142
+ const location = configPath(host, options.config);
143
+ const envName = host.env["HA_AXI_PROFILE"];
144
+ const requested = options.profile ?? (envName === "" ? undefined : envName);
145
+ if (requested !== undefined) {
146
+ const selectedBy = options.profile === undefined ? "HA_AXI_PROFILE" : "flag";
147
+ if (!PROFILE_NAME.test(requested)) {
148
+ const code = selectedBy === "flag" ? "INVALID_ARGUMENT" : "CONFIG_INVALID";
149
+ throw new AxiError(code, `${selectedBy === "flag" ? "--profile" : "HA_AXI_PROFILE"} must match ^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$`);
150
+ }
151
+ return fromFile(loadConfig(location, files, host.platform, true), location, requested, selectedBy, readOnly);
152
+ }
153
+ const origin = host.env["HA_AXI_ORIGIN"];
154
+ const allowInsecureHttp = envBoolean(host.env, "HA_AXI_ALLOW_INSECURE_HTTP");
155
+ if (origin !== undefined && origin !== "") {
156
+ if ((host.env["HA_AXI_TOKEN"] ?? "") === "") {
157
+ throw invalid("The environment profile is incomplete: set both HA_AXI_ORIGIN and HA_AXI_TOKEN, or unset HA_AXI_ORIGIN");
158
+ }
159
+ const problem = originProblem(origin, allowInsecureHttp);
160
+ if (problem !== undefined)
161
+ throw invalid(`HA_AXI_ORIGIN ${problem}`);
162
+ return { name: "env", selectedBy: "env-profile", config: location, fromFile: false, origin, allowInsecureHttp, token: DEFAULT_TOKEN, writes: READ_ONLY_WRITES, readOnly };
163
+ }
164
+ const config = loadConfig(location, files, host.platform, true);
165
+ if (config.defaultProfile !== undefined)
166
+ return fromFile(config, location, config.defaultProfile, "defaultProfile", readOnly);
167
+ const names = Object.keys(config.profiles);
168
+ const [sole] = names;
169
+ if (names.length === 1 && sole !== undefined)
170
+ return fromFile(config, location, sole, "sole", readOnly);
171
+ const help = ["Run `ha-axi profile set <name> --origin <url> --token-env <VAR>`, or pass --profile <name>"];
172
+ if (names.length === 0)
173
+ throw new AxiError("PROFILE_REQUIRED", `No profile is configured in ${location.path} or the environment`, help);
174
+ throw new AxiError("PROFILE_AMBIGUOUS", `${location.path} defines ${String(names.length)} profiles and no defaultProfile`, help);
175
+ }
176
+ export const secretSource = (ref) => ("env" in ref ? `env:${ref.env}` : `file:${ref.file}`);
177
+ export function resolveToken(ref, host, files, redactor, verify = false) {
178
+ const source = secretSource(ref);
179
+ const raw = "env" in ref ? host.env[ref.env] : files.read(ref.file, "secret", verify)?.replace(/^\uFEFF/, "").trimEnd();
180
+ if (raw === undefined || raw === "") {
181
+ throw new AxiError("AUTH_REQUIRED", `No token found at ${source}`, ["Provide the Home Assistant long-lived access token through the profile's SecretRef"]);
182
+ }
183
+ redactor.register(raw);
184
+ if (!/^[\x21-\x7e]+$/.test(raw))
185
+ throw invalid(`The token from ${source} contains whitespace, control or non-ASCII characters`);
186
+ return raw;
187
+ }
188
+ const serialize = (config) => `${JSON.stringify(config, null, 2)}\n`;
189
+ export function setProfile(options, name, profile, host, files) {
190
+ if (!PROFILE_NAME.test(name))
191
+ throw new AxiError("INVALID_ARGUMENT", "Profile names must match ^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$");
192
+ const checked = profileSchema.safeParse(profile);
193
+ if (!checked.success)
194
+ throw invalid(`Profile ${name} ${issueText(checked.error)}`);
195
+ const [problem] = profileProblems(profile, host.platform);
196
+ if (problem !== undefined)
197
+ throw invalid(`Profile ${name} field ${problem}`);
198
+ const location = configPath(host, options.config);
199
+ files.update(location.path, location.source === "default", () => {
200
+ const raw = files.read(location.path, "config");
201
+ const config = raw === undefined ? { version: 1, profiles: {} } : parseConfig(raw, location.path, host.platform);
202
+ return serialize({ ...config, profiles: { ...config.profiles, [name]: profile } });
203
+ });
204
+ return location;
205
+ }
206
+ export function removeProfile(options, name, host, files) {
207
+ const location = configPath(host, options.config);
208
+ files.update(location.path, location.source === "default", () => {
209
+ const config = loadConfig(location, files, host.platform);
210
+ if (!Object.hasOwn(config.profiles, name)) {
211
+ throw new AxiError("PROFILE_NOT_FOUND", `Profile ${name} is not defined in ${location.path}`, ["Run `ha-axi profile list` to see the defined profiles"]);
212
+ }
213
+ const profiles = Object.fromEntries(Object.entries(config.profiles).filter(([key]) => key !== name));
214
+ const { defaultProfile, ...rest } = config;
215
+ return serialize(defaultProfile === name ? { ...rest, profiles } : { ...config, profiles });
216
+ }, false);
217
+ return location;
218
+ }
@@ -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
+ }