@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.
- package/LICENSE +21 -0
- package/README.md +105 -2
- package/artium-inventory.json +142 -0
- package/axi-credential.schema.json +91 -0
- package/dist/cli.js +73 -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 +141 -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 +68 -0
- package/dist/core/transport/ws.js +50 -0
- package/dist/core/writes/coordinator.js +236 -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/actions/commands.js +254 -0
- package/dist/features/actions/feature.js +13 -0
- package/dist/features/core/commands.js +164 -0
- package/dist/features/core/feature.js +16 -0
- package/dist/features/core/home.js +56 -0
- package/dist/features/core/writes-status.js +51 -0
- package/dist/features/diagnostics/commands.js +168 -0
- package/dist/features/diagnostics/feature.js +11 -0
- package/dist/features/raw/classify.js +76 -0
- package/dist/features/raw/commands.js +135 -0
- package/dist/features/raw/feature.js +15 -0
- package/dist/features/states/commands.js +100 -0
- package/dist/features/states/feature.js +8 -0
- package/dist/generated/registry.js +159 -0
- package/package.json +62 -4
- package/skills/ha-axi/SKILL.md +130 -0
|
@@ -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,168 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
import { selectProfile } from "../../core/credentials/config.js";
|
|
3
|
+
import { AxiError } from "../../core/credentials/errors.js";
|
|
4
|
+
import { entityId, listing, 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 MAX_TEMPLATE_BYTES = 16 * 1024 * 1024;
|
|
13
|
+
const systemLogSchema = z.array(z.object({
|
|
14
|
+
message: z.tuple([z.string()], z.string()),
|
|
15
|
+
level: z.string(),
|
|
16
|
+
source: z.tuple([z.string(), z.number()]),
|
|
17
|
+
timestamp: z.number(),
|
|
18
|
+
count: z.number(),
|
|
19
|
+
}));
|
|
20
|
+
const repairsSchema = z.object({
|
|
21
|
+
issues: z.array(z.object({
|
|
22
|
+
domain: z.string(),
|
|
23
|
+
issue_id: z.string(),
|
|
24
|
+
severity: z.string(),
|
|
25
|
+
is_fixable: z.boolean(),
|
|
26
|
+
ignored: z.boolean(),
|
|
27
|
+
})),
|
|
28
|
+
});
|
|
29
|
+
const configEntriesSchema = z.array(z.object({ entry_id: z.string(), domain: z.string(), title: z.string(), state: z.string() }));
|
|
30
|
+
const templateErrorSchema = z.object({ message: z.string() });
|
|
31
|
+
const historySchema = z.array(z.array(z.object({ state: z.string(), last_changed: z.string() })));
|
|
32
|
+
const logbookSchema = z.array(z.object({
|
|
33
|
+
when: z.string(),
|
|
34
|
+
name: z.string().nullish(),
|
|
35
|
+
entity_id: z.string().nullish(),
|
|
36
|
+
state: z.string().nullish(),
|
|
37
|
+
message: z.string().nullish(),
|
|
38
|
+
}));
|
|
39
|
+
function open(values, { host, files, redactor, userAgent }) {
|
|
40
|
+
return connect(selectProfile(selector(values), host, files), host, files, redactor, userAgent);
|
|
41
|
+
}
|
|
42
|
+
function window(since) {
|
|
43
|
+
const match = DURATION.exec(since ?? "");
|
|
44
|
+
const ms = match === null ? 0 : Number(match[1]) * (UNIT_MS[match[2] ?? ""] ?? 0);
|
|
45
|
+
if (!Number.isSafeInteger(ms) || ms < 1_000 || ms > MAX_WINDOW_MS) {
|
|
46
|
+
throw new AxiError("INVALID_ARGUMENT", "--since must be a duration from 1s to 365d, such as 30m, 1h or 7d");
|
|
47
|
+
}
|
|
48
|
+
const now = Date.now();
|
|
49
|
+
return { start: new Date(now - ms).toISOString(), end: new Date(now).toISOString() };
|
|
50
|
+
}
|
|
51
|
+
const logsList = async (args, context) => {
|
|
52
|
+
const { values } = parse(args, { ...SELECT, level: { type: "string" } }, 0);
|
|
53
|
+
const level = values.level?.toLowerCase();
|
|
54
|
+
const minimum = LEVELS.findIndex((name) => name === level);
|
|
55
|
+
if (level !== undefined && minimum < 0)
|
|
56
|
+
throw new AxiError("INVALID_ARGUMENT", `--level must be one of ${LEVELS.join(", ")}`);
|
|
57
|
+
const entries = await readWsJson(open(values, context), { type: "system_log/list", payload: {} }, systemLogSchema, context.redactor);
|
|
58
|
+
const rows = entries
|
|
59
|
+
.filter((entry) => level === undefined || LEVELS.findIndex((name) => name === entry.level.toLowerCase()) >= minimum)
|
|
60
|
+
.map((entry) => ({
|
|
61
|
+
level: entry.level,
|
|
62
|
+
source: `${context.redactor.text(entry.source[0])}:${String(entry.source[1])}`,
|
|
63
|
+
occurrences: entry.count,
|
|
64
|
+
lastOccurred: new Date(Math.round(entry.timestamp * 1_000)).toISOString(),
|
|
65
|
+
message: context.redactor.text(entry.message.reduce((_, message) => message)),
|
|
66
|
+
}));
|
|
67
|
+
const scope = level === undefined ? "in the system log" : `at level ${level} or above`;
|
|
68
|
+
return { ...listing("entries", rows, `no log entries ${scope}`), total: entries.length };
|
|
69
|
+
};
|
|
70
|
+
const repairsList = async (args, context) => {
|
|
71
|
+
const { values } = parse(args, SELECT, 0);
|
|
72
|
+
const { issues } = await readWsJson(open(values, context), { type: "repairs/list_issues", payload: {} }, repairsSchema, context.redactor);
|
|
73
|
+
const rows = issues.map((issue) => ({
|
|
74
|
+
domain: issue.domain,
|
|
75
|
+
issueId: issue.issue_id,
|
|
76
|
+
severity: issue.severity,
|
|
77
|
+
fixable: issue.is_fixable,
|
|
78
|
+
ignored: issue.ignored,
|
|
79
|
+
}));
|
|
80
|
+
return { ...listing("issues", rows, "no repair issues"), active: issues.filter((issue) => !issue.ignored).length };
|
|
81
|
+
};
|
|
82
|
+
const integrationsList = async (args, context) => {
|
|
83
|
+
const { values } = parse(args, SELECT, 0);
|
|
84
|
+
const entries = await readWsJson(open(values, context), { type: "config_entries/get", payload: {} }, configEntriesSchema, context.redactor);
|
|
85
|
+
const rows = entries.map((entry) => ({ domain: entry.domain, title: context.redactor.text(entry.title), state: entry.state, entryId: entry.entry_id }));
|
|
86
|
+
return { ...listing("integrations", rows, "no integration config entries"), loaded: entries.filter((entry) => entry.state === "loaded").length };
|
|
87
|
+
};
|
|
88
|
+
function templateErrorMessage(text) {
|
|
89
|
+
try {
|
|
90
|
+
const parsed = templateErrorSchema.safeParse(JSON.parse(text));
|
|
91
|
+
return parsed.success ? parsed.data.message : text;
|
|
92
|
+
}
|
|
93
|
+
catch {
|
|
94
|
+
return text;
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
const templateRender = async (args, context) => {
|
|
98
|
+
const { values, positionals } = parse(args, SELECT, 1);
|
|
99
|
+
const [template = ""] = positionals;
|
|
100
|
+
const body = Buffer.from(JSON.stringify({ template }));
|
|
101
|
+
const response = await readRest(open(values, context), { method: "POST", path: "/api/template", body, maxBytes: MAX_TEMPLATE_BYTES })
|
|
102
|
+
.catch((error) => {
|
|
103
|
+
if (!(error instanceof AxiError) || error.code !== "AUTH_FAILED")
|
|
104
|
+
throw error;
|
|
105
|
+
throw new AxiError("AUTH_FAILED", "Home Assistant refused authentication for POST /api/template (HTTP 401)", [
|
|
106
|
+
"Check that the profile's SecretRef points to a valid long-lived access token from a Home Assistant administrator account",
|
|
107
|
+
]);
|
|
108
|
+
});
|
|
109
|
+
if (response.status === 400) {
|
|
110
|
+
const message = response.truncated
|
|
111
|
+
? "the response exceeded the size bound"
|
|
112
|
+
: context.redactor.text(templateErrorMessage(response.text));
|
|
113
|
+
throw new AxiError("INVALID_ARGUMENT", `Home Assistant could not render the template: ${message}`);
|
|
114
|
+
}
|
|
115
|
+
if (response.status < 200 || response.status > 299)
|
|
116
|
+
throw statusError(response.status, response.text, "POST /api/template");
|
|
117
|
+
if (response.truncated)
|
|
118
|
+
throw new AxiError("INVALID_RESPONSE", "POST /api/template exceeded the response size bound");
|
|
119
|
+
if (response.contentType.split(";")[0]?.trim().toLowerCase() !== "text/plain") {
|
|
120
|
+
throw new AxiError("INVALID_RESPONSE", "POST /api/template did not return text/plain");
|
|
121
|
+
}
|
|
122
|
+
return { result: context.redactor.text(response.text) };
|
|
123
|
+
};
|
|
124
|
+
const historyGet = async (args, context) => {
|
|
125
|
+
const { values, positionals } = parse(args, { ...SELECT, since: { type: "string" } }, 1);
|
|
126
|
+
const entity = entityId(positionals[0] ?? "", "<entity_id>");
|
|
127
|
+
const { start, end } = window(values.since);
|
|
128
|
+
const query = [["filter_entity_id", entity], ["end_time", end], ["minimal_response", ""], ["no_attributes", ""]];
|
|
129
|
+
const series = await readJson(open(values, context), { method: "GET", path: `/api/history/period/${start}`, query }, historySchema);
|
|
130
|
+
const rows = series.flat().map((row) => ({ time: row.last_changed, state: context.redactor.text(row.state) }));
|
|
131
|
+
return {
|
|
132
|
+
entity,
|
|
133
|
+
since: start,
|
|
134
|
+
...listing("history", rows, `no state history for ${entity} since ${start}`),
|
|
135
|
+
...(rows.length === 0 ? { help: ["Widen the window with a longer --since, or check the entity ID"] } : {}),
|
|
136
|
+
};
|
|
137
|
+
};
|
|
138
|
+
const logbookList = async (args, context) => {
|
|
139
|
+
const { values } = parse(args, { ...SELECT, entity: { type: "string" }, since: { type: "string" } }, 0);
|
|
140
|
+
const entity = values.entity === undefined ? undefined : entityId(values.entity, "--entity");
|
|
141
|
+
const { start, end } = window(values.since);
|
|
142
|
+
const query = [...(entity === undefined ? [] : [["entity", entity]]), ["end_time", end]];
|
|
143
|
+
const entries = await readJson(open(values, context), { method: "GET", path: `/api/logbook/${start}`, query }, logbookSchema);
|
|
144
|
+
const rows = entries.map((entry) => {
|
|
145
|
+
const event = entry.state ?? entry.message;
|
|
146
|
+
return {
|
|
147
|
+
when: entry.when,
|
|
148
|
+
name: entry.name == null ? null : context.redactor.text(entry.name),
|
|
149
|
+
entityId: entry.entity_id ?? null,
|
|
150
|
+
event: event == null ? null : context.redactor.text(event),
|
|
151
|
+
};
|
|
152
|
+
});
|
|
153
|
+
const scope = entity === undefined ? "" : ` for ${entity}`;
|
|
154
|
+
return {
|
|
155
|
+
...(entity === undefined ? {} : { entity }),
|
|
156
|
+
since: start,
|
|
157
|
+
...listing("entries", rows, `no logbook entries${scope} since ${start}`),
|
|
158
|
+
...(rows.length === 0 ? { help: ["Widen the window with a longer --since"] } : {}),
|
|
159
|
+
};
|
|
160
|
+
};
|
|
161
|
+
export const handlers = {
|
|
162
|
+
"logs list": logsList,
|
|
163
|
+
"repairs list": repairsList,
|
|
164
|
+
"integrations list": integrationsList,
|
|
165
|
+
"template render": templateRender,
|
|
166
|
+
"history get": historyGet,
|
|
167
|
+
"logbook list": logbookList,
|
|
168
|
+
};
|
|
@@ -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
|
+
}
|
|
@@ -0,0 +1,135 @@
|
|
|
1
|
+
import { StringDecoder } from "node:string_decoder";
|
|
2
|
+
import { selectProfile } from "../../core/credentials/config.js";
|
|
3
|
+
import { AxiError } from "../../core/credentials/errors.js";
|
|
4
|
+
import { redactPayload } from "../../core/credentials/redact.js";
|
|
5
|
+
import { parse, PAYLOAD, payload as readPayload, readInput, SELECT, secretName, selector } from "../../core/output/command.js";
|
|
6
|
+
import { connect, MAX_REST_RESPONSE_BYTES, readRest } from "../../core/transport/rest.js";
|
|
7
|
+
import { readWs } from "../../core/transport/ws.js";
|
|
8
|
+
import { passthroughRest, passthroughWs } from "../../core/writes/passthrough.js";
|
|
9
|
+
import { classifyRest, classifyWs } from "./classify.js";
|
|
10
|
+
const FORBIDDEN_HEADERS = new Set([
|
|
11
|
+
"authorization", "proxy-authorization", "cookie", "host", "accept-encoding", "content-length", "transfer-encoding", "connection", "upgrade", "user-agent",
|
|
12
|
+
]);
|
|
13
|
+
const HTTP_TOKEN = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;
|
|
14
|
+
const DEFAULT_MAX_BYTES = 512 * 1024;
|
|
15
|
+
const MAX_TIMEOUT_MS = 600_000;
|
|
16
|
+
const WS_OPTIONS = { ...SELECT, ...PAYLOAD, timeout: { type: "string" } };
|
|
17
|
+
const OPTIONS = {
|
|
18
|
+
...SELECT,
|
|
19
|
+
query: { type: "string", multiple: true },
|
|
20
|
+
header: { type: "string", multiple: true },
|
|
21
|
+
"body-file": { type: "string" },
|
|
22
|
+
stdin: { type: "boolean" },
|
|
23
|
+
"max-bytes": { type: "string" },
|
|
24
|
+
timeout: { type: "string" },
|
|
25
|
+
};
|
|
26
|
+
function pairs(items, separator, flag) {
|
|
27
|
+
return (items ?? []).map((item) => {
|
|
28
|
+
const index = item.indexOf(separator);
|
|
29
|
+
const key = item.slice(0, index).trim();
|
|
30
|
+
if (index < 1 || key === "")
|
|
31
|
+
throw new AxiError("INVALID_ARGUMENT", `${flag} expects <name>${separator}<value>`);
|
|
32
|
+
const value = item.slice(index + 1);
|
|
33
|
+
if (flag === "--query") {
|
|
34
|
+
if (secretName(key) || /signature|^sig$/i.test(key)) {
|
|
35
|
+
throw new AxiError("INVALID_ARGUMENT", `--query ${key} is refused: credentials are never accepted in the query string`);
|
|
36
|
+
}
|
|
37
|
+
return [key, value];
|
|
38
|
+
}
|
|
39
|
+
if (!HTTP_TOKEN.test(key))
|
|
40
|
+
throw new AxiError("INVALID_ARGUMENT", "--header expects a valid HTTP field name");
|
|
41
|
+
if (FORBIDDEN_HEADERS.has(key.toLowerCase())) {
|
|
42
|
+
throw new AxiError("INVALID_ARGUMENT", `--header ${key} is refused: ha-axi controls this header`);
|
|
43
|
+
}
|
|
44
|
+
if (/[^\t -~]/.test(value)) {
|
|
45
|
+
throw new AxiError("INVALID_ARGUMENT", "--header values may only contain printable ASCII and tabs");
|
|
46
|
+
}
|
|
47
|
+
return [key, value.trim()];
|
|
48
|
+
});
|
|
49
|
+
}
|
|
50
|
+
function integer(value, flag, max) {
|
|
51
|
+
if (value === undefined)
|
|
52
|
+
return undefined;
|
|
53
|
+
const parsed = /^\d+$/.test(value) ? Number(value) : 0;
|
|
54
|
+
if (parsed < 1 || parsed > max)
|
|
55
|
+
throw new AxiError("INVALID_ARGUMENT", `${flag} must be an integer from 1 to ${String(max)}`);
|
|
56
|
+
return parsed;
|
|
57
|
+
}
|
|
58
|
+
function vendorBody(response, redactor) {
|
|
59
|
+
const mediaType = response.contentType.split(";", 1)[0]?.trim().toLowerCase();
|
|
60
|
+
if (mediaType === "application/json" || mediaType?.endsWith("+json")) {
|
|
61
|
+
let json;
|
|
62
|
+
try {
|
|
63
|
+
json = JSON.parse(response.text);
|
|
64
|
+
}
|
|
65
|
+
catch {
|
|
66
|
+
json = undefined;
|
|
67
|
+
}
|
|
68
|
+
if (json !== undefined) {
|
|
69
|
+
const body = redactPayload(json, redactor);
|
|
70
|
+
return { body, text: JSON.stringify(body) };
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
const text = redactor.text(response.text);
|
|
74
|
+
return { body: text, text };
|
|
75
|
+
}
|
|
76
|
+
const api = async (args, { host, files, redactor, userAgent, stdin }) => {
|
|
77
|
+
const { values, positionals } = parse(args, OPTIONS, 2);
|
|
78
|
+
const [verb = "", raw = ""] = positionals;
|
|
79
|
+
if (!HTTP_TOKEN.test(verb))
|
|
80
|
+
throw new AxiError("INVALID_ARGUMENT", "Method must be a valid HTTP token");
|
|
81
|
+
const method = verb.toUpperCase();
|
|
82
|
+
if (method === "CONNECT")
|
|
83
|
+
throw new AxiError("INVALID_ARGUMENT", "CONNECT is unavailable for raw REST requests");
|
|
84
|
+
const file = values["body-file"];
|
|
85
|
+
const target = classifyRest(method, raw, file !== undefined || values.stdin === true);
|
|
86
|
+
const query = pairs(values.query, "=", "--query");
|
|
87
|
+
const headers = pairs(values.header, ":", "--header");
|
|
88
|
+
if (file !== undefined && values.stdin === true)
|
|
89
|
+
throw new AxiError("INVALID_ARGUMENT", "Use at most one of --body-file and --stdin");
|
|
90
|
+
const body = file !== undefined ? readInput(file, "--body-file") : values.stdin === true ? await stdin() : undefined;
|
|
91
|
+
const maxBytes = integer(values["max-bytes"], "--max-bytes", MAX_REST_RESPONSE_BYTES) ?? DEFAULT_MAX_BYTES;
|
|
92
|
+
const timeoutMs = integer(values.timeout, "--timeout", MAX_TIMEOUT_MS);
|
|
93
|
+
const selection = selectProfile(selector(values), host, files);
|
|
94
|
+
const session = connect(selection, host, files, redactor, userAgent);
|
|
95
|
+
const base = { query, headers, ...(timeoutMs === undefined ? {} : { timeoutMs }), ...(body === undefined ? {} : { body }) };
|
|
96
|
+
const response = target.kind === "read-get"
|
|
97
|
+
? await readRest(session, { ...base, method: "GET", path: target.path })
|
|
98
|
+
: target.kind === "read-post"
|
|
99
|
+
? await readRest(session, { ...base, method: "POST", path: target.path })
|
|
100
|
+
: await passthroughRest(session, selection.readOnly, { ...base, method, path: target.path });
|
|
101
|
+
const { body: redactedBody, text } = vendorBody(response, redactor);
|
|
102
|
+
const truncated = Buffer.byteLength(text) > maxBytes;
|
|
103
|
+
return {
|
|
104
|
+
request: `${method} ${target.path}`,
|
|
105
|
+
status: response.status,
|
|
106
|
+
body: truncated ? new StringDecoder("utf8").write(Buffer.from(text).subarray(0, maxBytes)) : redactedBody,
|
|
107
|
+
...(truncated
|
|
108
|
+
? { truncated: true, help: [`The body was cut at ${String(maxBytes)} bytes (set by --max-bytes)`] }
|
|
109
|
+
: {}),
|
|
110
|
+
};
|
|
111
|
+
};
|
|
112
|
+
const ws = async (args, { host, files, redactor, userAgent, stdin }) => {
|
|
113
|
+
const { values, positionals } = parse(args, WS_OPTIONS, 1);
|
|
114
|
+
const [type = ""] = positionals;
|
|
115
|
+
const payload = (await readPayload(values, stdin, "raw")) ?? {};
|
|
116
|
+
const target = classifyWs(type, payload);
|
|
117
|
+
const timeoutMs = integer(values.timeout, "--timeout", MAX_TIMEOUT_MS);
|
|
118
|
+
const selection = selectProfile(selector(values), host, files);
|
|
119
|
+
const session = connect(selection, host, files, redactor, userAgent);
|
|
120
|
+
const request = { type, payload, ...(timeoutMs === undefined ? {} : { timeoutMs }) };
|
|
121
|
+
const reply = target.kind === "read"
|
|
122
|
+
? await readWs(session, { ...request, type: target.type })
|
|
123
|
+
: await passthroughWs(session, selection.readOnly, request);
|
|
124
|
+
if (reply.success)
|
|
125
|
+
return { command: type, success: true, result: redactPayload(reply.result, redactor) };
|
|
126
|
+
return {
|
|
127
|
+
command: type,
|
|
128
|
+
success: false,
|
|
129
|
+
error: redactPayload(reply.error, redactor),
|
|
130
|
+
...(reply.error.code === "unknown_command"
|
|
131
|
+
? { help: ["Home Assistant does not recognise this command type; check the spelling and that its integration is loaded"] }
|
|
132
|
+
: {}),
|
|
133
|
+
};
|
|
134
|
+
};
|
|
135
|
+
export const handlers = { api, ws };
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
export const feature = {
|
|
2
|
+
name: "raw",
|
|
3
|
+
commands: [
|
|
4
|
+
{
|
|
5
|
+
name: "api",
|
|
6
|
+
effect: "passthrough",
|
|
7
|
+
summary: "Send a REST request under /api/; writes pass through unless HA_AXI_READ_ONLY=true, deferred v2 families are refused",
|
|
8
|
+
},
|
|
9
|
+
{
|
|
10
|
+
name: "ws",
|
|
11
|
+
effect: "passthrough",
|
|
12
|
+
summary: "Send a WebSocket command; writes pass through unless HA_AXI_READ_ONLY=true, deferred v2 families are refused",
|
|
13
|
+
},
|
|
14
|
+
],
|
|
15
|
+
};
|
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
import { isDeepStrictEqual } from "node:util";
|
|
2
|
+
import { z } from "zod";
|
|
3
|
+
import { selectProfile } from "../../core/credentials/config.js";
|
|
4
|
+
import { AxiError } from "../../core/credentials/errors.js";
|
|
5
|
+
import { redactPayload } from "../../core/credentials/redact.js";
|
|
6
|
+
import { entityId, isDomain, listing, parse, PAYLOAD, payload, SELECT, selector, selectorFlags, stateFor, stateSchema } from "../../core/output/command.js";
|
|
7
|
+
import { connect, readEntityState, readJson } from "../../core/transport/rest.js";
|
|
8
|
+
import { runWrite, WRITE_OPTIONS } from "../../core/writes/coordinator.js";
|
|
9
|
+
const STATE_VALUE = /^[\s\S]{0,255}$/u;
|
|
10
|
+
const row = (state, redactor) => {
|
|
11
|
+
const name = state.attributes["friendly_name"];
|
|
12
|
+
return {
|
|
13
|
+
entity_id: redactor.text(state.entity_id),
|
|
14
|
+
state: redactor.text(state.state),
|
|
15
|
+
friendly_name: typeof name === "string" ? redactor.text(name) : null,
|
|
16
|
+
last_changed: redactor.text(state.last_changed),
|
|
17
|
+
};
|
|
18
|
+
};
|
|
19
|
+
async function readState(session, entity) {
|
|
20
|
+
try {
|
|
21
|
+
return await readEntityState(session, entity, stateFor(entity));
|
|
22
|
+
}
|
|
23
|
+
catch (error) {
|
|
24
|
+
if (error instanceof AxiError && error.code === "NOT_FOUND")
|
|
25
|
+
return null;
|
|
26
|
+
throw error;
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
const statesList = async (args, { host, files, redactor, userAgent }) => {
|
|
30
|
+
const { values } = parse(args, { ...SELECT, domain: { type: "string" } }, 0);
|
|
31
|
+
const domain = values.domain;
|
|
32
|
+
if (domain !== undefined && !isDomain(domain))
|
|
33
|
+
throw new AxiError("INVALID_ARGUMENT", "--domain must be a domain such as light or sensor");
|
|
34
|
+
const session = connect(selectProfile(selector(values), host, files), host, files, redactor, userAgent);
|
|
35
|
+
const states = await readJson(session, { method: "GET", path: "/api/states" }, z.array(stateSchema));
|
|
36
|
+
const rows = states
|
|
37
|
+
.filter((state) => domain === undefined || state.entity_id.startsWith(`${domain}.`))
|
|
38
|
+
.sort((a, b) => (a.entity_id < b.entity_id ? -1 : a.entity_id > b.entity_id ? 1 : 0))
|
|
39
|
+
.map((state) => row(state, redactor));
|
|
40
|
+
const scope = domain === undefined ? "" : ` in domain ${domain}`;
|
|
41
|
+
return {
|
|
42
|
+
...listing("states", rows, `no entities${scope}`),
|
|
43
|
+
...(rows.length > 0
|
|
44
|
+
? { help: [`Run \`ha-axi states get <entity_id>${selectorFlags(values)}\` for one entity's attributes`] }
|
|
45
|
+
: domain === undefined ? {} : { help: [`Run \`ha-axi states list${selectorFlags(values)}\` without --domain to see every domain`] }),
|
|
46
|
+
};
|
|
47
|
+
};
|
|
48
|
+
const statesGet = async (args, { host, files, redactor, userAgent }) => {
|
|
49
|
+
const { values, positionals } = parse(args, SELECT, 1);
|
|
50
|
+
const entity = entityId(positionals[0] ?? "", "<entity_id>");
|
|
51
|
+
const session = connect(selectProfile(selector(values), host, files), host, files, redactor, userAgent);
|
|
52
|
+
const state = await readState(session, entity);
|
|
53
|
+
if (state === null) {
|
|
54
|
+
throw new AxiError("NOT_FOUND", `Entity ${entity} was not found`, [`Run \`ha-axi states list${selectorFlags(values)}\` to see the entity IDs Home Assistant knows`]);
|
|
55
|
+
}
|
|
56
|
+
return {
|
|
57
|
+
...row(state, redactor),
|
|
58
|
+
attributes: redactPayload(state.attributes, redactor),
|
|
59
|
+
};
|
|
60
|
+
};
|
|
61
|
+
const statesSet = async (args, { host, files, redactor, userAgent, stdin }) => {
|
|
62
|
+
const { values, positionals } = parse(args, { ...SELECT, ...PAYLOAD, ...WRITE_OPTIONS }, 2);
|
|
63
|
+
const entity = entityId(positionals[0] ?? "", "<entity_id>");
|
|
64
|
+
const value = positionals[1] ?? "";
|
|
65
|
+
if (!STATE_VALUE.test(value))
|
|
66
|
+
throw new AxiError("INVALID_ARGUMENT", "<state> must be at most 255 characters");
|
|
67
|
+
const attributes = await payload(values, stdin);
|
|
68
|
+
const selection = selectProfile(selector(values), host, files);
|
|
69
|
+
const session = connect(selection, host, files, redactor, userAgent);
|
|
70
|
+
const path = `/api/states/${entity}`;
|
|
71
|
+
const before = async () => {
|
|
72
|
+
const observed = await readState(session, entity);
|
|
73
|
+
const current = observed === null ? null : { state: observed.state, attributes: observed.attributes };
|
|
74
|
+
const clearsAttributes = current !== null && Object.keys(current.attributes).length > 0 && Object.keys(attributes ?? {}).length === 0;
|
|
75
|
+
return {
|
|
76
|
+
snapshot: current === null ? null : { entity_id: entity, ...current },
|
|
77
|
+
changes: {
|
|
78
|
+
before: current,
|
|
79
|
+
after: { state: value, attributes: attributes ?? {} },
|
|
80
|
+
...(clearsAttributes ? { warning: "Home Assistant will clear the entity's existing attributes" } : {}),
|
|
81
|
+
},
|
|
82
|
+
};
|
|
83
|
+
};
|
|
84
|
+
const verify = async () => {
|
|
85
|
+
const observed = await readState(session, entity);
|
|
86
|
+
if (observed === null)
|
|
87
|
+
return { outcome: "executed_mismatch" };
|
|
88
|
+
const matches = observed.state === value && isDeepStrictEqual(observed.attributes, attributes ?? {});
|
|
89
|
+
return { outcome: matches ? "executed_verified" : "executed_mismatch", details: { state: observed.state } };
|
|
90
|
+
};
|
|
91
|
+
const body = Buffer.from(JSON.stringify({ state: value, ...(attributes === undefined ? {} : { attributes }) }));
|
|
92
|
+
return await runWrite({ grantId: "states.set", target: entity, rest: { method: "POST", path, body }, before, verify }, values, {
|
|
93
|
+
host, files, redactor, selection, session,
|
|
94
|
+
});
|
|
95
|
+
};
|
|
96
|
+
export const handlers = {
|
|
97
|
+
"states list": statesList,
|
|
98
|
+
"states get": statesGet,
|
|
99
|
+
"states set": statesSet,
|
|
100
|
+
};
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
export const feature = {
|
|
2
|
+
name: "states",
|
|
3
|
+
commands: [
|
|
4
|
+
{ name: "states list", effect: "read", summary: "List entity states with entity ID, state, friendly name and last change, optionally for one --domain" },
|
|
5
|
+
{ name: "states get", effect: "read", summary: "Show one entity's state, attributes and last change" },
|
|
6
|
+
{ name: "states set", effect: "write", grantId: "states.set", summary: "Set an entity's state and attributes in Home Assistant's state machine, with readback" },
|
|
7
|
+
],
|
|
8
|
+
};
|