@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,164 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
import { DEFAULT_TOKEN, loadConfig, removeProfile, resolveToken, secretSource, selectProfile, setProfile, } from "../../core/credentials/config.js";
|
|
3
|
+
import { AxiError } from "../../core/credentials/errors.js";
|
|
4
|
+
import { configPath, writeLogPath } from "../../core/credentials/paths.js";
|
|
5
|
+
import { CONFIG, parse, SELECT, selector } from "../../core/output/command.js";
|
|
6
|
+
import { grantIdSchema } from "../../core/registry/types.js";
|
|
7
|
+
import { connect, readJson } from "../../core/transport/rest.js";
|
|
8
|
+
import { handlers as writesHandlers } from "./writes-status.js";
|
|
9
|
+
const INSECURE_HTTP_WARNING = "allowInsecureHttp is on: the token travels unencrypted over the LAN; prefer an https:// origin";
|
|
10
|
+
const NEXT_STEPS = ["Run `ha-axi status` for instance details", "Run `ha-axi config check` to validate the configuration"];
|
|
11
|
+
const coreConfigSchema = z.object({
|
|
12
|
+
version: z.string(),
|
|
13
|
+
state: z.string(),
|
|
14
|
+
location_name: z.string(),
|
|
15
|
+
time_zone: z.string(),
|
|
16
|
+
config_source: z.string(),
|
|
17
|
+
components: z.array(z.string()),
|
|
18
|
+
});
|
|
19
|
+
const checkConfigSchema = z.object({
|
|
20
|
+
result: z.enum(["valid", "invalid"]),
|
|
21
|
+
errors: z.string().nullable(),
|
|
22
|
+
warnings: z.string().nullable(),
|
|
23
|
+
});
|
|
24
|
+
const authStatus = (args, { host, files, redactor }) => {
|
|
25
|
+
const { values } = parse(args, SELECT, 0);
|
|
26
|
+
const selection = selectProfile(selector(values), host, files);
|
|
27
|
+
resolveToken(selection.token, host, files, redactor, true);
|
|
28
|
+
const fileProtection = selection.fromFile || "file" in selection.token
|
|
29
|
+
? host.platform === "win32" ? "windows-dacl-verified" : "posix-owner-and-mode"
|
|
30
|
+
: "none";
|
|
31
|
+
return {
|
|
32
|
+
profile: selection.name,
|
|
33
|
+
selectedBy: selection.selectedBy,
|
|
34
|
+
config: selection.config.path,
|
|
35
|
+
origin: selection.origin,
|
|
36
|
+
token: secretSource(selection.token),
|
|
37
|
+
fileProtection,
|
|
38
|
+
readOnly: selection.readOnly,
|
|
39
|
+
writes: selection.writes,
|
|
40
|
+
...(selection.allowInsecureHttp ? { warnings: [INSECURE_HTTP_WARNING] } : {}),
|
|
41
|
+
};
|
|
42
|
+
};
|
|
43
|
+
const profileList = (args, { host, files }) => {
|
|
44
|
+
const { values } = parse(args, CONFIG, 0);
|
|
45
|
+
const location = configPath(host, values.config);
|
|
46
|
+
const config = loadConfig(location, files, host.platform);
|
|
47
|
+
const profiles = Object.entries(config.profiles).map(([name, profile]) => ({
|
|
48
|
+
name,
|
|
49
|
+
origin: profile.origin,
|
|
50
|
+
token: secretSource(profile.token ?? DEFAULT_TOKEN),
|
|
51
|
+
default: config.defaultProfile === name,
|
|
52
|
+
allowWrites: profile.writes?.allowWrites ?? false,
|
|
53
|
+
}));
|
|
54
|
+
const help = profiles.length === 0 ? ["Run `ha-axi profile set <name> --origin <url> --token-env <VAR>` to add a profile"] : [];
|
|
55
|
+
return { config: location.path, count: profiles.length, profiles, ...(help.length > 0 ? { help } : {}) };
|
|
56
|
+
};
|
|
57
|
+
const profileSet = (args, { host, files }) => {
|
|
58
|
+
const options = {
|
|
59
|
+
...CONFIG,
|
|
60
|
+
origin: { type: "string" },
|
|
61
|
+
"token-env": { type: "string" },
|
|
62
|
+
"token-file": { type: "string" },
|
|
63
|
+
"allow-insecure-http": { type: "boolean" },
|
|
64
|
+
"allow-writes": { type: "boolean" },
|
|
65
|
+
"allow-op": { type: "string", multiple: true },
|
|
66
|
+
};
|
|
67
|
+
const { values, positionals } = parse(args, options, 1);
|
|
68
|
+
const [name = ""] = positionals;
|
|
69
|
+
if (values.origin === undefined)
|
|
70
|
+
throw new AxiError("INVALID_ARGUMENT", "--origin <url> is required");
|
|
71
|
+
const tokenEnv = values["token-env"];
|
|
72
|
+
const tokenFile = values["token-file"];
|
|
73
|
+
const token = tokenEnv !== undefined && tokenFile === undefined ? { env: tokenEnv }
|
|
74
|
+
: tokenFile !== undefined && tokenEnv === undefined ? { file: tokenFile } : undefined;
|
|
75
|
+
if (token === undefined) {
|
|
76
|
+
throw new AxiError("INVALID_ARGUMENT", "Use exactly one of --token-env and --token-file");
|
|
77
|
+
}
|
|
78
|
+
const operations = values["allow-op"] ?? [];
|
|
79
|
+
for (const operation of operations) {
|
|
80
|
+
if (!grantIdSchema.safeParse(operation).success) {
|
|
81
|
+
throw new AxiError("INVALID_ARGUMENT", `--allow-op ${operation} is not a write grant ID`, [`Grant IDs: ${grantIdSchema.options.join(", ")}`]);
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
const allowWrites = values["allow-writes"] ?? false;
|
|
85
|
+
const profile = {
|
|
86
|
+
origin: values.origin,
|
|
87
|
+
token,
|
|
88
|
+
...(values["allow-insecure-http"] === true ? { allowInsecureHttp: true } : {}),
|
|
89
|
+
...(allowWrites || operations.length > 0 ? { writes: { allowWrites, operations } } : {}),
|
|
90
|
+
};
|
|
91
|
+
const location = setProfile(selector(values), name, profile, host, files);
|
|
92
|
+
return {
|
|
93
|
+
profile: name,
|
|
94
|
+
config: location.path,
|
|
95
|
+
origin: profile.origin,
|
|
96
|
+
token: secretSource(token),
|
|
97
|
+
...(profile.allowInsecureHttp === true ? { warnings: [INSECURE_HTTP_WARNING] } : {}),
|
|
98
|
+
help: [`Run \`ha-axi auth status --profile ${name}\` to check it`],
|
|
99
|
+
};
|
|
100
|
+
};
|
|
101
|
+
const profileRemove = (args, { host, files }) => {
|
|
102
|
+
const { values, positionals } = parse(args, CONFIG, 1);
|
|
103
|
+
const [name = ""] = positionals;
|
|
104
|
+
const location = removeProfile(selector(values), name, host, files);
|
|
105
|
+
return { removed: name, config: location.path };
|
|
106
|
+
};
|
|
107
|
+
const configPathCommand = (args, { host }) => {
|
|
108
|
+
const { values } = parse(args, CONFIG, 0);
|
|
109
|
+
const location = configPath(host, values.config);
|
|
110
|
+
return { config: location.path, source: location.source, writeLog: writeLogPath(host) };
|
|
111
|
+
};
|
|
112
|
+
async function instance(args, { host, files, redactor, userAgent }) {
|
|
113
|
+
const { values } = parse(args, SELECT, 0);
|
|
114
|
+
const selection = selectProfile(selector(values), host, files);
|
|
115
|
+
const session = connect(selection, host, files, redactor, userAgent);
|
|
116
|
+
return { selection, config: await readJson(session, { method: "GET", path: "/api/config" }, coreConfigSchema) };
|
|
117
|
+
}
|
|
118
|
+
const doctor = async (args, context) => {
|
|
119
|
+
const { selection, config } = await instance(args, context);
|
|
120
|
+
const warnings = [
|
|
121
|
+
...(selection.allowInsecureHttp ? [INSECURE_HTTP_WARNING] : []),
|
|
122
|
+
...(config.state === "RUNNING" ? [] : [`Home Assistant reports state ${config.state}, not RUNNING`]),
|
|
123
|
+
];
|
|
124
|
+
return {
|
|
125
|
+
profile: selection.name,
|
|
126
|
+
origin: selection.origin,
|
|
127
|
+
token: secretSource(selection.token),
|
|
128
|
+
homeAssistant: { version: config.version, state: config.state, components: config.components.length },
|
|
129
|
+
...(warnings.length > 0 ? { warnings } : {}),
|
|
130
|
+
help: NEXT_STEPS,
|
|
131
|
+
};
|
|
132
|
+
};
|
|
133
|
+
const status = async (args, context) => {
|
|
134
|
+
const { config } = await instance(args, context);
|
|
135
|
+
return {
|
|
136
|
+
version: config.version,
|
|
137
|
+
state: config.state,
|
|
138
|
+
location: config.location_name,
|
|
139
|
+
timeZone: config.time_zone,
|
|
140
|
+
configSource: config.config_source,
|
|
141
|
+
components: config.components.length,
|
|
142
|
+
help: ["Run `ha-axi config check` to validate the configuration"],
|
|
143
|
+
};
|
|
144
|
+
};
|
|
145
|
+
const configCheck = async (args, { host, files, redactor, userAgent }) => {
|
|
146
|
+
const { values } = parse(args, SELECT, 0);
|
|
147
|
+
const session = connect(selectProfile(selector(values), host, files), host, files, redactor, userAgent);
|
|
148
|
+
const check = await readJson(session, { method: "POST", path: "/api/config/core/check_config" }, checkConfigSchema);
|
|
149
|
+
return {
|
|
150
|
+
...check,
|
|
151
|
+
...(check.result === "invalid" ? { help: ["Fix the reported errors, then run `ha-axi config check` again"] } : {}),
|
|
152
|
+
};
|
|
153
|
+
};
|
|
154
|
+
export const handlers = {
|
|
155
|
+
doctor,
|
|
156
|
+
status,
|
|
157
|
+
"config check": configCheck,
|
|
158
|
+
"auth status": authStatus,
|
|
159
|
+
"profile list": profileList,
|
|
160
|
+
"profile set": profileSet,
|
|
161
|
+
"profile remove": profileRemove,
|
|
162
|
+
"config path": configPathCommand,
|
|
163
|
+
...writesHandlers,
|
|
164
|
+
};
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
export const feature = {
|
|
2
|
+
name: "core",
|
|
3
|
+
commands: [
|
|
4
|
+
{ name: "help", effect: "read", summary: "List every ha-axi command with its effect" },
|
|
5
|
+
{ name: "auth status", effect: "read", summary: "Show the selected profile, origin and token source without contacting Home Assistant" },
|
|
6
|
+
{ name: "profile list", effect: "read", summary: "List the profiles in config.json" },
|
|
7
|
+
{ name: "profile set", effect: "read", hosted: "blocked", summary: "Create or replace a local profile in config.json; sends no Home Assistant request" },
|
|
8
|
+
{ name: "profile remove", effect: "read", hosted: "blocked", summary: "Remove a local profile from config.json; sends no Home Assistant request" },
|
|
9
|
+
{ name: "config path", effect: "read", summary: "Print the config.json and writes.log paths" },
|
|
10
|
+
{ name: "doctor", effect: "read", summary: "Check the profile and credentials with one bounded GET /api/config" },
|
|
11
|
+
{ name: "status", effect: "read", summary: "Show the Home Assistant version, state, location and component count" },
|
|
12
|
+
{ name: "config check", effect: "read", summary: "Validate the Home Assistant configuration (read-only POST)" },
|
|
13
|
+
{ name: "writes status", effect: "read", summary: "Show one writes.log entry and its outcome, with reconciliation guidance when the outcome is unknown" },
|
|
14
|
+
{ name: "writes pending", effect: "read", summary: "List journaled writes whose outcome is pending or unknown" },
|
|
15
|
+
],
|
|
16
|
+
};
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
import { AxiError } from "../../core/credentials/errors.js";
|
|
2
|
+
import { parse } from "../../core/output/command.js";
|
|
3
|
+
import { Journal } from "../../core/writes/journal.js";
|
|
4
|
+
const state = (entry) => entry.outcome?.outcome ?? "pending";
|
|
5
|
+
function reconcile(entry) {
|
|
6
|
+
const value = state(entry);
|
|
7
|
+
if (value === "pending") {
|
|
8
|
+
return [`No outcome is journaled; if no ha-axi process is still sending this write, check ${entry.intent.target} in Home Assistant before sending it again`];
|
|
9
|
+
}
|
|
10
|
+
return value === "unknown_outcome" ? [`Check ${entry.intent.target} in Home Assistant before sending this write again`] : [];
|
|
11
|
+
}
|
|
12
|
+
const writesStatus = (args, { host, files, redactor }) => {
|
|
13
|
+
const { positionals } = parse(args, {}, 1);
|
|
14
|
+
const [entryId = ""] = positionals;
|
|
15
|
+
const journal = new Journal(host, files, redactor);
|
|
16
|
+
const entry = journal.entries().find((candidate) => candidate.intent.entryId === entryId);
|
|
17
|
+
if (entry === undefined) {
|
|
18
|
+
throw new AxiError("NOT_FOUND", `No write ${entryId} in ${journal.path}`, ["Run `ha-axi writes pending` to list writes without a known outcome"]);
|
|
19
|
+
}
|
|
20
|
+
const { intent, outcome } = entry;
|
|
21
|
+
const help = reconcile(entry);
|
|
22
|
+
return {
|
|
23
|
+
entryId: intent.entryId,
|
|
24
|
+
state: state(entry),
|
|
25
|
+
grantId: intent.grantId,
|
|
26
|
+
target: intent.target,
|
|
27
|
+
origin: intent.origin,
|
|
28
|
+
...(intent.requestId === undefined ? {} : { requestId: intent.requestId }),
|
|
29
|
+
intentAt: intent.timestamp,
|
|
30
|
+
...(outcome === undefined ? {} : { outcomeAt: outcome.timestamp }),
|
|
31
|
+
...(outcome?.code === undefined ? {} : { error: { code: outcome.code, message: outcome.message ?? "" } }),
|
|
32
|
+
...(help.length > 0 ? { help } : {}),
|
|
33
|
+
};
|
|
34
|
+
};
|
|
35
|
+
const writesPending = (args, { host, files, redactor }) => {
|
|
36
|
+
parse(args, {}, 0);
|
|
37
|
+
const journal = new Journal(host, files, redactor);
|
|
38
|
+
const pending = journal.entries()
|
|
39
|
+
.filter((entry) => ["pending", "unknown_outcome"].includes(state(entry)))
|
|
40
|
+
.map((entry) => ({ entryId: entry.intent.entryId, state: state(entry), grantId: entry.intent.grantId, target: entry.intent.target, intentAt: entry.intent.timestamp }));
|
|
41
|
+
return {
|
|
42
|
+
writeLog: journal.path,
|
|
43
|
+
count: pending.length,
|
|
44
|
+
pending,
|
|
45
|
+
...(pending.length > 0 ? { help: ["Run `ha-axi writes status <entryId>` for one write and how to reconcile it"] } : {}),
|
|
46
|
+
};
|
|
47
|
+
};
|
|
48
|
+
export const handlers = {
|
|
49
|
+
"writes status": writesStatus,
|
|
50
|
+
"writes pending": writesPending,
|
|
51
|
+
};
|
|
@@ -0,0 +1,175 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
import { selectProfile } from "../../core/credentials/config.js";
|
|
3
|
+
import { AxiError } from "../../core/credentials/errors.js";
|
|
4
|
+
import { parse, SELECT, selector } from "../../core/output/command.js";
|
|
5
|
+
import { connect, readJson, readRest, statusError } from "../../core/transport/rest.js";
|
|
6
|
+
import { readWsJson } from "../../core/transport/ws.js";
|
|
7
|
+
const LEVELS = ["debug", "info", "warning", "error", "critical"];
|
|
8
|
+
const DURATION = /^([1-9]\d*)([smhd])$/;
|
|
9
|
+
const DAY_MS = 86_400_000;
|
|
10
|
+
const UNIT_MS = { s: 1_000, m: 60_000, h: 3_600_000, d: DAY_MS };
|
|
11
|
+
const MAX_WINDOW_MS = 365 * DAY_MS;
|
|
12
|
+
const ENTITY_ID = /^[\p{Nd}a-z]+(?:_[\p{Nd}a-z]+)*\.[\p{Nd}a-z]+(?:_[\p{Nd}a-z]+)*$/u;
|
|
13
|
+
const MAX_TEMPLATE_BYTES = 16 * 1024 * 1024;
|
|
14
|
+
const systemLogSchema = z.array(z.object({
|
|
15
|
+
message: z.tuple([z.string()], z.string()),
|
|
16
|
+
level: z.string(),
|
|
17
|
+
source: z.tuple([z.string(), z.number()]),
|
|
18
|
+
timestamp: z.number(),
|
|
19
|
+
count: z.number(),
|
|
20
|
+
}));
|
|
21
|
+
const repairsSchema = z.object({
|
|
22
|
+
issues: z.array(z.object({
|
|
23
|
+
domain: z.string(),
|
|
24
|
+
issue_id: z.string(),
|
|
25
|
+
severity: z.string(),
|
|
26
|
+
is_fixable: z.boolean(),
|
|
27
|
+
ignored: z.boolean(),
|
|
28
|
+
})),
|
|
29
|
+
});
|
|
30
|
+
const configEntriesSchema = z.array(z.object({ entry_id: z.string(), domain: z.string(), title: z.string(), state: z.string() }));
|
|
31
|
+
const templateErrorSchema = z.object({ message: z.string() });
|
|
32
|
+
const historySchema = z.array(z.array(z.object({ state: z.string(), last_changed: z.string() })));
|
|
33
|
+
const logbookSchema = z.array(z.object({
|
|
34
|
+
when: z.string(),
|
|
35
|
+
name: z.string().nullish(),
|
|
36
|
+
entity_id: z.string().nullish(),
|
|
37
|
+
state: z.string().nullish(),
|
|
38
|
+
message: z.string().nullish(),
|
|
39
|
+
}));
|
|
40
|
+
function open(values, { host, files, redactor, userAgent }) {
|
|
41
|
+
return connect(selectProfile(selector(values), host, files), host, files, redactor, userAgent);
|
|
42
|
+
}
|
|
43
|
+
const listing = (name, rows, empty) => rows.length > 0 ? { count: rows.length, [name]: rows } : { count: 0, [name]: `0 results: ${empty}` };
|
|
44
|
+
function entityId(value, flag) {
|
|
45
|
+
if (!ENTITY_ID.test(value))
|
|
46
|
+
throw new AxiError("INVALID_ARGUMENT", `${flag} must be an entity ID such as sun.sun`);
|
|
47
|
+
return value;
|
|
48
|
+
}
|
|
49
|
+
function window(since) {
|
|
50
|
+
const match = DURATION.exec(since ?? "");
|
|
51
|
+
const ms = match === null ? 0 : Number(match[1]) * (UNIT_MS[match[2] ?? ""] ?? 0);
|
|
52
|
+
if (!Number.isSafeInteger(ms) || ms < 1_000 || ms > MAX_WINDOW_MS) {
|
|
53
|
+
throw new AxiError("INVALID_ARGUMENT", "--since must be a duration from 1s to 365d, such as 30m, 1h or 7d");
|
|
54
|
+
}
|
|
55
|
+
const now = Date.now();
|
|
56
|
+
return { start: new Date(now - ms).toISOString(), end: new Date(now).toISOString() };
|
|
57
|
+
}
|
|
58
|
+
const logsList = async (args, context) => {
|
|
59
|
+
const { values } = parse(args, { ...SELECT, level: { type: "string" } }, 0);
|
|
60
|
+
const level = values.level?.toLowerCase();
|
|
61
|
+
const minimum = LEVELS.findIndex((name) => name === level);
|
|
62
|
+
if (level !== undefined && minimum < 0)
|
|
63
|
+
throw new AxiError("INVALID_ARGUMENT", `--level must be one of ${LEVELS.join(", ")}`);
|
|
64
|
+
const entries = await readWsJson(open(values, context), { type: "system_log/list", payload: {} }, systemLogSchema, context.redactor);
|
|
65
|
+
const rows = entries
|
|
66
|
+
.filter((entry) => level === undefined || LEVELS.findIndex((name) => name === entry.level.toLowerCase()) >= minimum)
|
|
67
|
+
.map((entry) => ({
|
|
68
|
+
level: entry.level,
|
|
69
|
+
source: `${context.redactor.text(entry.source[0])}:${String(entry.source[1])}`,
|
|
70
|
+
occurrences: entry.count,
|
|
71
|
+
lastOccurred: new Date(Math.round(entry.timestamp * 1_000)).toISOString(),
|
|
72
|
+
message: context.redactor.text(entry.message.reduce((_, message) => message)),
|
|
73
|
+
}));
|
|
74
|
+
const scope = level === undefined ? "in the system log" : `at level ${level} or above`;
|
|
75
|
+
return { ...listing("entries", rows, `no log entries ${scope}`), total: entries.length };
|
|
76
|
+
};
|
|
77
|
+
const repairsList = async (args, context) => {
|
|
78
|
+
const { values } = parse(args, SELECT, 0);
|
|
79
|
+
const { issues } = await readWsJson(open(values, context), { type: "repairs/list_issues", payload: {} }, repairsSchema, context.redactor);
|
|
80
|
+
const rows = issues.map((issue) => ({
|
|
81
|
+
domain: issue.domain,
|
|
82
|
+
issueId: issue.issue_id,
|
|
83
|
+
severity: issue.severity,
|
|
84
|
+
fixable: issue.is_fixable,
|
|
85
|
+
ignored: issue.ignored,
|
|
86
|
+
}));
|
|
87
|
+
return { ...listing("issues", rows, "no repair issues"), active: issues.filter((issue) => !issue.ignored).length };
|
|
88
|
+
};
|
|
89
|
+
const integrationsList = async (args, context) => {
|
|
90
|
+
const { values } = parse(args, SELECT, 0);
|
|
91
|
+
const entries = await readWsJson(open(values, context), { type: "config_entries/get", payload: {} }, configEntriesSchema, context.redactor);
|
|
92
|
+
const rows = entries.map((entry) => ({ domain: entry.domain, title: context.redactor.text(entry.title), state: entry.state, entryId: entry.entry_id }));
|
|
93
|
+
return { ...listing("integrations", rows, "no integration config entries"), loaded: entries.filter((entry) => entry.state === "loaded").length };
|
|
94
|
+
};
|
|
95
|
+
function templateErrorMessage(text) {
|
|
96
|
+
try {
|
|
97
|
+
const parsed = templateErrorSchema.safeParse(JSON.parse(text));
|
|
98
|
+
return parsed.success ? parsed.data.message : text;
|
|
99
|
+
}
|
|
100
|
+
catch {
|
|
101
|
+
return text;
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
const templateRender = async (args, context) => {
|
|
105
|
+
const { values, positionals } = parse(args, SELECT, 1);
|
|
106
|
+
const [template = ""] = positionals;
|
|
107
|
+
const body = Buffer.from(JSON.stringify({ template }));
|
|
108
|
+
const response = await readRest(open(values, context), { method: "POST", path: "/api/template", body, maxBytes: MAX_TEMPLATE_BYTES })
|
|
109
|
+
.catch((error) => {
|
|
110
|
+
if (!(error instanceof AxiError) || error.code !== "AUTH_FAILED")
|
|
111
|
+
throw error;
|
|
112
|
+
throw new AxiError("AUTH_FAILED", "Home Assistant refused authentication for POST /api/template (HTTP 401)", [
|
|
113
|
+
"Check that the profile's SecretRef points to a valid long-lived access token from a Home Assistant administrator account",
|
|
114
|
+
]);
|
|
115
|
+
});
|
|
116
|
+
if (response.status === 400) {
|
|
117
|
+
const message = response.truncated
|
|
118
|
+
? "the response exceeded the size bound"
|
|
119
|
+
: context.redactor.text(templateErrorMessage(response.text));
|
|
120
|
+
throw new AxiError("INVALID_ARGUMENT", `Home Assistant could not render the template: ${message}`);
|
|
121
|
+
}
|
|
122
|
+
if (response.status < 200 || response.status > 299)
|
|
123
|
+
throw statusError(response.status, response.text, "POST /api/template");
|
|
124
|
+
if (response.truncated)
|
|
125
|
+
throw new AxiError("INVALID_RESPONSE", "POST /api/template exceeded the response size bound");
|
|
126
|
+
if (response.contentType.split(";")[0]?.trim().toLowerCase() !== "text/plain") {
|
|
127
|
+
throw new AxiError("INVALID_RESPONSE", "POST /api/template did not return text/plain");
|
|
128
|
+
}
|
|
129
|
+
return { result: context.redactor.text(response.text) };
|
|
130
|
+
};
|
|
131
|
+
const historyGet = async (args, context) => {
|
|
132
|
+
const { values, positionals } = parse(args, { ...SELECT, since: { type: "string" } }, 1);
|
|
133
|
+
const entity = entityId(positionals[0] ?? "", "<entity_id>");
|
|
134
|
+
const { start, end } = window(values.since);
|
|
135
|
+
const query = [["filter_entity_id", entity], ["end_time", end], ["minimal_response", ""], ["no_attributes", ""]];
|
|
136
|
+
const series = await readJson(open(values, context), { method: "GET", path: `/api/history/period/${start}`, query }, historySchema);
|
|
137
|
+
const rows = series.flat().map((row) => ({ time: row.last_changed, state: context.redactor.text(row.state) }));
|
|
138
|
+
return {
|
|
139
|
+
entity,
|
|
140
|
+
since: start,
|
|
141
|
+
...listing("history", rows, `no state history for ${entity} since ${start}`),
|
|
142
|
+
...(rows.length === 0 ? { help: ["Widen the window with a longer --since, or check the entity ID"] } : {}),
|
|
143
|
+
};
|
|
144
|
+
};
|
|
145
|
+
const logbookList = async (args, context) => {
|
|
146
|
+
const { values } = parse(args, { ...SELECT, entity: { type: "string" }, since: { type: "string" } }, 0);
|
|
147
|
+
const entity = values.entity === undefined ? undefined : entityId(values.entity, "--entity");
|
|
148
|
+
const { start, end } = window(values.since);
|
|
149
|
+
const query = [...(entity === undefined ? [] : [["entity", entity]]), ["end_time", end]];
|
|
150
|
+
const entries = await readJson(open(values, context), { method: "GET", path: `/api/logbook/${start}`, query }, logbookSchema);
|
|
151
|
+
const rows = entries.map((entry) => {
|
|
152
|
+
const event = entry.state ?? entry.message;
|
|
153
|
+
return {
|
|
154
|
+
when: entry.when,
|
|
155
|
+
name: entry.name == null ? null : context.redactor.text(entry.name),
|
|
156
|
+
entityId: entry.entity_id ?? null,
|
|
157
|
+
event: event == null ? null : context.redactor.text(event),
|
|
158
|
+
};
|
|
159
|
+
});
|
|
160
|
+
const scope = entity === undefined ? "" : ` for ${entity}`;
|
|
161
|
+
return {
|
|
162
|
+
...(entity === undefined ? {} : { entity }),
|
|
163
|
+
since: start,
|
|
164
|
+
...listing("entries", rows, `no logbook entries${scope} since ${start}`),
|
|
165
|
+
...(rows.length === 0 ? { help: ["Widen the window with a longer --since"] } : {}),
|
|
166
|
+
};
|
|
167
|
+
};
|
|
168
|
+
export const handlers = {
|
|
169
|
+
"logs list": logsList,
|
|
170
|
+
"repairs list": repairsList,
|
|
171
|
+
"integrations list": integrationsList,
|
|
172
|
+
"template render": templateRender,
|
|
173
|
+
"history get": historyGet,
|
|
174
|
+
"logbook list": logbookList,
|
|
175
|
+
};
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
export const feature = {
|
|
2
|
+
name: "diagnostics",
|
|
3
|
+
commands: [
|
|
4
|
+
{ name: "logs list", effect: "read", summary: "List system log entries at or above an optional --level, with source file and occurrence count" },
|
|
5
|
+
{ name: "repairs list", effect: "read", summary: "List repair issues with domain, severity and whether each is fixable or ignored" },
|
|
6
|
+
{ name: "integrations list", effect: "read", summary: "List integration config entries with domain, title and load state" },
|
|
7
|
+
{ name: "template render", effect: "read", summary: "Render a Jinja2 template and print the text result (read-only POST)" },
|
|
8
|
+
{ name: "history get", effect: "read", summary: "Show an entity's state timeline since a duration ago" },
|
|
9
|
+
{ name: "logbook list", effect: "read", summary: "List logbook entries since a duration ago, optionally for one entity" },
|
|
10
|
+
],
|
|
11
|
+
};
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
import { unescape as decodePercentEscapes } from "node:querystring";
|
|
2
|
+
import { AxiError } from "../../core/credentials/errors.js";
|
|
3
|
+
import { isReadPost } from "../../core/transport/rest.js";
|
|
4
|
+
import { isWsRead } from "../../core/transport/ws.js";
|
|
5
|
+
const WS_DEFERRED_PREFIXES = ["hassio/", "supervisor/", "auth/", "config/auth/", "config/auth_provider/", "backup/", "hacs/", "config_entries/flow/"];
|
|
6
|
+
const RESERVED_FIELDS = ["id", "type"];
|
|
7
|
+
const DEFERRED_PREFIXES = [
|
|
8
|
+
"/api/hassio",
|
|
9
|
+
"/api/backup",
|
|
10
|
+
"/api/hacs",
|
|
11
|
+
"/api/config/config_entries/flow",
|
|
12
|
+
"/api/config/config_entries/options/flow",
|
|
13
|
+
"/api/config/config_entries/subentries/flow",
|
|
14
|
+
"/api/services/hassio/",
|
|
15
|
+
];
|
|
16
|
+
const READ_GETS = /^\/api\/(?:|config|states(?:\/[^/]+)?|services|history\/period\/[^/]+|logbook\/[^/]+|calendars(?:\/[^/]+)?)$/;
|
|
17
|
+
const UNSAFE = /[?#\\]|\p{Cc}/u;
|
|
18
|
+
const invalid = (problem, help = []) => new AxiError("INVALID_ARGUMENT", `Path ${problem}`, help);
|
|
19
|
+
function decodeFully(path) {
|
|
20
|
+
let decoded;
|
|
21
|
+
try {
|
|
22
|
+
decoded = decodeURIComponent(path);
|
|
23
|
+
}
|
|
24
|
+
catch {
|
|
25
|
+
throw invalid("has invalid percent-encoding");
|
|
26
|
+
}
|
|
27
|
+
for (let round = 1; round < 4; round++) {
|
|
28
|
+
const next = decodePercentEscapes(decoded);
|
|
29
|
+
if (next === decoded)
|
|
30
|
+
return next.replace(/\/{2,}/g, "/");
|
|
31
|
+
decoded = next;
|
|
32
|
+
}
|
|
33
|
+
throw invalid("is percent-encoded too many times");
|
|
34
|
+
}
|
|
35
|
+
export function classifyRest(method, raw, hasBody) {
|
|
36
|
+
if (/^[a-z][a-z\d+.-]*:/i.test(raw) || raw.startsWith("//") || raw.includes("://")) {
|
|
37
|
+
throw invalid("is a full URL; pass a path under /api/ and keep the origin in the profile");
|
|
38
|
+
}
|
|
39
|
+
if (UNSAFE.test(raw) || /\s/u.test(raw)) {
|
|
40
|
+
throw invalid("contains ?, #, a backslash, whitespace or a control character", ["Pass query parameters with --query <key>=<value>"]);
|
|
41
|
+
}
|
|
42
|
+
const path = (raw.startsWith("/") ? raw : `/api/${raw}`).replace(/\/{2,}/g, "/");
|
|
43
|
+
const decoded = decodeFully(path);
|
|
44
|
+
if (UNSAFE.test(decoded) || decoded.split("/").some((segment) => segment === "." || segment === "..")) {
|
|
45
|
+
throw invalid("contains a dot segment or an encoded unsafe character");
|
|
46
|
+
}
|
|
47
|
+
if (!path.startsWith("/api/") || !decoded.startsWith("/api/"))
|
|
48
|
+
throw invalid("is not under /api/");
|
|
49
|
+
const lower = decoded.toLowerCase();
|
|
50
|
+
if (DEFERRED_PREFIXES.some((prefix) => lower.startsWith(prefix))) {
|
|
51
|
+
throw invalid("is in a family deferred to v2 (Supervisor, backups, HACS or integration config flows) and is refused for every method");
|
|
52
|
+
}
|
|
53
|
+
if (method === "GET" && !hasBody && READ_GETS.test(path))
|
|
54
|
+
return { kind: "read-get", path };
|
|
55
|
+
if (method === "POST" && isReadPost(path))
|
|
56
|
+
return { kind: "read-post", path };
|
|
57
|
+
return { kind: "write", path };
|
|
58
|
+
}
|
|
59
|
+
export function classifyWs(type, payload) {
|
|
60
|
+
if (type === "") {
|
|
61
|
+
throw new AxiError("INVALID_ARGUMENT", "Command type must not be empty");
|
|
62
|
+
}
|
|
63
|
+
const reserved = RESERVED_FIELDS.filter((field) => Object.hasOwn(payload, field));
|
|
64
|
+
if (reserved.length > 0) {
|
|
65
|
+
throw new AxiError("INVALID_ARGUMENT", `Payload field ${reserved.join(" and ")} is reserved: ha-axi sets the WebSocket envelope id and type`, [
|
|
66
|
+
"Pass the command type as the positional argument and leave id and type out of the payload",
|
|
67
|
+
]);
|
|
68
|
+
}
|
|
69
|
+
const family = `${type.toLowerCase()}/`;
|
|
70
|
+
const domain = payload["domain"];
|
|
71
|
+
const hassioService = family === "call_service/" && typeof domain === "string" && domain.toLowerCase() === "hassio";
|
|
72
|
+
if (hassioService || WS_DEFERRED_PREFIXES.some((prefix) => family.startsWith(prefix))) {
|
|
73
|
+
throw new AxiError("INVALID_ARGUMENT", `Command ${type} is in a family deferred to v2 (Supervisor, backups, HACS, integration config flows, or user and auth management) and is refused for reads and writes`);
|
|
74
|
+
}
|
|
75
|
+
return isWsRead(type) ? { kind: "read", type } : { kind: "write" };
|
|
76
|
+
}
|