@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,109 @@
|
|
|
1
|
+
import { Agent as HttpAgent, request as requestHttp } from "node:http";
|
|
2
|
+
import { Agent as HttpsAgent, request as requestHttps } from "node:https";
|
|
3
|
+
import { AxiError, errnoCode } from "../credentials/errors.js";
|
|
4
|
+
export const DEFAULT_TIMEOUT_MS = 30_000;
|
|
5
|
+
export const MAX_REST_RESPONSE_BYTES = 64 * 1024 * 1024;
|
|
6
|
+
const CERTIFICATE_ERROR = /CERT|SELF_SIGNED|UNABLE_TO_(?:GET|VERIFY)/;
|
|
7
|
+
const REDIRECT_STATUSES = new Set([301, 302, 303, 307, 308]);
|
|
8
|
+
const HTTP_AGENT = new HttpAgent();
|
|
9
|
+
const HTTPS_AGENT = new HttpsAgent();
|
|
10
|
+
export const UNKNOWN_OUTCOME = "The write outcome is unknown. Check Home Assistant state before sending it again.";
|
|
11
|
+
export const outcomeUnknown = (error) => error.help.includes(UNKNOWN_OUTCOME);
|
|
12
|
+
export function rejectedStatus(response, label) {
|
|
13
|
+
const status = response.statusCode ?? 0;
|
|
14
|
+
if (REDIRECT_STATUSES.has(status) || (status === 300 && response.headers.location !== undefined)) {
|
|
15
|
+
return new AxiError("UPSTREAM_ERROR", `${label} was redirected (HTTP ${String(status)}); redirects are never followed`, [
|
|
16
|
+
"Set the profile origin to the address Home Assistant serves directly",
|
|
17
|
+
]);
|
|
18
|
+
}
|
|
19
|
+
return status === 401 ? authFailed(label, "HTTP 401") : undefined;
|
|
20
|
+
}
|
|
21
|
+
export const authFailed = (label, reason) => new AxiError("AUTH_FAILED", `Home Assistant rejected the token for ${label} (${reason})`, [
|
|
22
|
+
"Create a new long-lived access token and point the profile's SecretRef at it",
|
|
23
|
+
]);
|
|
24
|
+
export function transportError(error, origin, timedOut, dispatched, effect) {
|
|
25
|
+
const unknownOutcome = dispatched && effect === "write";
|
|
26
|
+
const connectionHelp = ["Check the profile origin and that Home Assistant is running"];
|
|
27
|
+
if (timedOut) {
|
|
28
|
+
const help = unknownOutcome ? [UNKNOWN_OUTCOME] : dispatched ? [] : connectionHelp;
|
|
29
|
+
return new AxiError("UPSTREAM_TIMEOUT", `${origin} did not respond in time`, help);
|
|
30
|
+
}
|
|
31
|
+
const code = errnoCode(error) ?? "network error";
|
|
32
|
+
if (unknownOutcome)
|
|
33
|
+
return new AxiError("UPSTREAM_UNREACHABLE", `Lost the connection to ${origin} (${code})`, [UNKNOWN_OUTCOME]);
|
|
34
|
+
return new AxiError("UPSTREAM_UNREACHABLE", `Cannot reach ${origin} (${code})`, CERTIFICATE_ERROR.test(code)
|
|
35
|
+
? ["Trust a private CA with NODE_EXTRA_CA_CERTS; certificate verification is never disabled"]
|
|
36
|
+
: connectionHelp);
|
|
37
|
+
}
|
|
38
|
+
export async function mutateRest(session, request, effect) {
|
|
39
|
+
const url = new URL(request.path, session.origin);
|
|
40
|
+
for (const [key, value] of request.query ?? [])
|
|
41
|
+
url.searchParams.append(key, value);
|
|
42
|
+
const headers = new Headers(request.headers?.map(([key, value]) => [key, value]));
|
|
43
|
+
headers.delete("transfer-encoding");
|
|
44
|
+
headers.delete("content-length");
|
|
45
|
+
if (request.body !== undefined) {
|
|
46
|
+
if (!headers.has("content-type"))
|
|
47
|
+
headers.set("content-type", "application/json");
|
|
48
|
+
headers.set("content-length", String(request.body.byteLength));
|
|
49
|
+
}
|
|
50
|
+
headers.set("accept-encoding", "identity");
|
|
51
|
+
headers.set("user-agent", session.userAgent);
|
|
52
|
+
const maxBytes = request.maxBytes ?? MAX_REST_RESPONSE_BYTES;
|
|
53
|
+
const label = `${request.method} ${request.path}`;
|
|
54
|
+
const signal = AbortSignal.timeout(request.timeoutMs ?? DEFAULT_TIMEOUT_MS);
|
|
55
|
+
let dispatched = false;
|
|
56
|
+
try {
|
|
57
|
+
const https = url.protocol === "https:";
|
|
58
|
+
const send = https ? requestHttps : requestHttp;
|
|
59
|
+
const agent = https ? HTTPS_AGENT : HTTP_AGENT;
|
|
60
|
+
const response = await new Promise((resolve, reject) => {
|
|
61
|
+
const outgoing = send(url, { method: request.method, agent, signal, rejectUnauthorized: true }, resolve);
|
|
62
|
+
outgoing.once("error", reject);
|
|
63
|
+
outgoing.once("socket", (socket) => {
|
|
64
|
+
if (outgoing.reusedSocket)
|
|
65
|
+
dispatched = true;
|
|
66
|
+
else
|
|
67
|
+
socket.once(https ? "secureConnect" : "connect", () => {
|
|
68
|
+
dispatched = true;
|
|
69
|
+
});
|
|
70
|
+
});
|
|
71
|
+
outgoing.once("upgrade", (_response, socket) => {
|
|
72
|
+
socket.destroy();
|
|
73
|
+
reject(new AxiError("UPSTREAM_ERROR", `${label} attempted to switch protocols (HTTP 101)`));
|
|
74
|
+
});
|
|
75
|
+
headers.forEach((value, name) => outgoing.setHeader(name, value));
|
|
76
|
+
outgoing.setHeader("authorization", `Bearer ${session.token}`);
|
|
77
|
+
outgoing.end(request.body);
|
|
78
|
+
});
|
|
79
|
+
const status = response.statusCode ?? 0;
|
|
80
|
+
const rejected = rejectedStatus(response, label);
|
|
81
|
+
if (rejected !== undefined) {
|
|
82
|
+
response.destroy();
|
|
83
|
+
throw rejected;
|
|
84
|
+
}
|
|
85
|
+
const chunks = [];
|
|
86
|
+
let size = 0;
|
|
87
|
+
const body = response;
|
|
88
|
+
for await (const chunk of body) {
|
|
89
|
+
if (size + chunk.byteLength > MAX_REST_RESPONSE_BYTES) {
|
|
90
|
+
throw new AxiError("UPSTREAM_ERROR", `${label} exceeded the ${String(MAX_REST_RESPONSE_BYTES)}-byte response limit`, effect === "write" ? [UNKNOWN_OUTCOME] : []);
|
|
91
|
+
}
|
|
92
|
+
chunks.push(chunk.subarray(0, maxBytes - size));
|
|
93
|
+
size += chunk.byteLength;
|
|
94
|
+
if (size > maxBytes)
|
|
95
|
+
break;
|
|
96
|
+
}
|
|
97
|
+
return {
|
|
98
|
+
status,
|
|
99
|
+
contentType: response.headers["content-type"] ?? "",
|
|
100
|
+
text: Buffer.concat(chunks).toString("utf8"),
|
|
101
|
+
truncated: size > maxBytes,
|
|
102
|
+
};
|
|
103
|
+
}
|
|
104
|
+
catch (error) {
|
|
105
|
+
if (error instanceof AxiError)
|
|
106
|
+
throw error;
|
|
107
|
+
throw transportError(error, session.origin, signal.aborted, dispatched, effect);
|
|
108
|
+
}
|
|
109
|
+
}
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import { resolveToken } from "../credentials/config.js";
|
|
2
|
+
import { AxiError } from "../credentials/errors.js";
|
|
3
|
+
import { mutateRest } from "./mutate.js";
|
|
4
|
+
export { MAX_REST_RESPONSE_BYTES } from "./mutate.js";
|
|
5
|
+
export const READ_POSTS = ["/api/config/core/check_config", "/api/template"];
|
|
6
|
+
const MAX_JSON_RESPONSE_BYTES = 16 * 1024 * 1024;
|
|
7
|
+
export const isReadPost = (path) => READ_POSTS.some((read) => read === path);
|
|
8
|
+
export function connect(selection, host, files, redactor, userAgent) {
|
|
9
|
+
return { origin: selection.origin, token: resolveToken(selection.token, host, files, redactor, true), userAgent };
|
|
10
|
+
}
|
|
11
|
+
export const readRest = (session, request) => mutateRest(session, request, "read");
|
|
12
|
+
export function statusError(status, text, label, forbiddenHelp = "Use a token from a Home Assistant administrator account") {
|
|
13
|
+
const message = `${label} returned HTTP ${String(status)}`;
|
|
14
|
+
if (status === 403) {
|
|
15
|
+
return new AxiError("FORBIDDEN", message, [
|
|
16
|
+
/\b1010\b/.test(text)
|
|
17
|
+
? "Cloudflare refused the request signature (Error 1010); allow the ha-axi User-Agent in front of Home Assistant"
|
|
18
|
+
: forbiddenHelp,
|
|
19
|
+
]);
|
|
20
|
+
}
|
|
21
|
+
return new AxiError(status === 404 ? "NOT_FOUND" : "UPSTREAM_ERROR", message);
|
|
22
|
+
}
|
|
23
|
+
export async function readJson(session, request, schema) {
|
|
24
|
+
const response = await readRest(session, { ...request, maxBytes: request.maxBytes ?? MAX_JSON_RESPONSE_BYTES });
|
|
25
|
+
const label = `${request.method} ${request.path}`;
|
|
26
|
+
if (response.status < 200 || response.status > 299)
|
|
27
|
+
throw statusError(response.status, response.text, label);
|
|
28
|
+
if (response.truncated)
|
|
29
|
+
throw new AxiError("INVALID_RESPONSE", `${label} exceeded the response size bound`);
|
|
30
|
+
let json;
|
|
31
|
+
try {
|
|
32
|
+
json = JSON.parse(response.text);
|
|
33
|
+
}
|
|
34
|
+
catch {
|
|
35
|
+
throw new AxiError("INVALID_RESPONSE", `${label} did not return JSON`);
|
|
36
|
+
}
|
|
37
|
+
return validate(json, schema, label);
|
|
38
|
+
}
|
|
39
|
+
export function validate(value, schema, label) {
|
|
40
|
+
const parsed = schema.safeParse(value);
|
|
41
|
+
if (parsed.success)
|
|
42
|
+
return parsed.data;
|
|
43
|
+
const [issue] = parsed.error.issues;
|
|
44
|
+
const field = issue?.path.map(String).join(".") ?? "";
|
|
45
|
+
throw new AxiError("INVALID_RESPONSE", `${label} returned an unexpected shape at ${field === "" ? "(root)" : field}: ${issue?.message ?? "invalid"}`);
|
|
46
|
+
}
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import { AxiError } from "../credentials/errors.js";
|
|
2
|
+
import { mutateWs } from "./mutate-ws.js";
|
|
3
|
+
import { validate } from "./rest.js";
|
|
4
|
+
export const WS_READS = [
|
|
5
|
+
"get_config",
|
|
6
|
+
"get_states",
|
|
7
|
+
"get_services",
|
|
8
|
+
"system_log/list",
|
|
9
|
+
"repairs/list_issues",
|
|
10
|
+
"config_entries/get",
|
|
11
|
+
"trace/list",
|
|
12
|
+
"trace/get",
|
|
13
|
+
"automation/config",
|
|
14
|
+
"lovelace/dashboards/list",
|
|
15
|
+
"lovelace/config",
|
|
16
|
+
"lovelace/resources",
|
|
17
|
+
"config/entity_registry/list",
|
|
18
|
+
"config/device_registry/list",
|
|
19
|
+
"config/area_registry/list",
|
|
20
|
+
"config/floor_registry/list",
|
|
21
|
+
"config/label_registry/list",
|
|
22
|
+
"input_boolean/list",
|
|
23
|
+
"input_number/list",
|
|
24
|
+
"input_text/list",
|
|
25
|
+
"input_select/list",
|
|
26
|
+
"input_datetime/list",
|
|
27
|
+
"input_button/list",
|
|
28
|
+
"counter/list",
|
|
29
|
+
"timer/list",
|
|
30
|
+
"schedule/list",
|
|
31
|
+
"search/related",
|
|
32
|
+
];
|
|
33
|
+
export const isWsRead = (type) => WS_READS.some((read) => read === type);
|
|
34
|
+
export const readWs = (session, request) => mutateWs(session, request, "read");
|
|
35
|
+
export async function readWsJson(session, request, schema, redactor) {
|
|
36
|
+
const label = `WebSocket command ${request.type}`;
|
|
37
|
+
const reply = await readWs(session, request);
|
|
38
|
+
if (reply.success)
|
|
39
|
+
return validate(reply.result, schema, label);
|
|
40
|
+
const message = `${label} failed (${redactor.text(reply.error.code)}): ${redactor.text(reply.error.message)}`;
|
|
41
|
+
throw reply.error.code === "unauthorized"
|
|
42
|
+
? new AxiError("FORBIDDEN", message, ["Use a token from a Home Assistant administrator account"])
|
|
43
|
+
: new AxiError("UPSTREAM_ERROR", message);
|
|
44
|
+
}
|
|
@@ -0,0 +1,233 @@
|
|
|
1
|
+
import { randomUUID } from "node:crypto";
|
|
2
|
+
import { AxiError, isErrorCode } from "../credentials/errors.js";
|
|
3
|
+
import { redactPayload } from "../credentials/redact.js";
|
|
4
|
+
import { mutateRest, outcomeUnknown, UNKNOWN_OUTCOME } from "../transport/mutate.js";
|
|
5
|
+
import { mutateWs } from "../transport/mutate-ws.js";
|
|
6
|
+
import { statusError } from "../transport/rest.js";
|
|
7
|
+
import { canonicalJson, CONFIRMATION_TTL_SECONDS, confirmationToken, parseToken, sha256, stateHash, STATELESS, } from "./digest.js";
|
|
8
|
+
import { Journal } from "./journal.js";
|
|
9
|
+
export const WRITE_OPTIONS = {
|
|
10
|
+
execute: { type: "boolean" },
|
|
11
|
+
confirm: { type: "string" },
|
|
12
|
+
"request-id": { type: "string" },
|
|
13
|
+
};
|
|
14
|
+
const REQUEST_ID = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/;
|
|
15
|
+
const statusHelp = (entryId) => `Run \`ha-axi writes status ${entryId}\` to see the journal entry`;
|
|
16
|
+
const nowEpoch = () => Math.floor(Date.now() / 1000);
|
|
17
|
+
function normalized(plan) {
|
|
18
|
+
if ("ws" in plan)
|
|
19
|
+
return { transport: "ws", type: plan.ws.type, payload: plan.ws.payload };
|
|
20
|
+
const { method, path, query = [], headers = [], body } = plan.rest;
|
|
21
|
+
return { transport: "rest", method, path, query, headers, body: body?.toString("base64") ?? null };
|
|
22
|
+
}
|
|
23
|
+
function validate(options, redactor) {
|
|
24
|
+
const requestId = options["request-id"];
|
|
25
|
+
if (options.execute !== true && (options.confirm !== undefined || requestId !== undefined)) {
|
|
26
|
+
throw new AxiError("INVALID_ARGUMENT", "--confirm and --request-id need --execute", ["Run without them to preview the write"]);
|
|
27
|
+
}
|
|
28
|
+
if (options.confirm !== undefined && parseToken(options.confirm) === undefined) {
|
|
29
|
+
throw new AxiError("INVALID_ARGUMENT", "--confirm must be the <issuedAtEpoch>.<sha256> token printed by the preview");
|
|
30
|
+
}
|
|
31
|
+
if (requestId !== undefined && (!REQUEST_ID.test(requestId) || redactor.text(requestId) !== requestId)) {
|
|
32
|
+
throw new AxiError("INVALID_ARGUMENT", "--request-id must match ^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$ and must not look like a credential");
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
function gate(plan, selection) {
|
|
36
|
+
const refuse = (reason, help) => new AxiError("WRITE_DISABLED", `${plan.grantId} is refused: ${reason}; nothing was sent`, [help, "Run without --execute to preview the write"]);
|
|
37
|
+
if (selection.readOnly)
|
|
38
|
+
throw refuse("HA_AXI_READ_ONLY is true", "Previews still work while HA_AXI_READ_ONLY is true");
|
|
39
|
+
if (!selection.writes.allowWrites)
|
|
40
|
+
throw refuse(`profile ${selection.name} does not allow writes`, `Set writes.allowWrites to true for profile ${selection.name}`);
|
|
41
|
+
if (!selection.writes.operations.includes(plan.grantId)) {
|
|
42
|
+
throw refuse(`profile ${selection.name} does not grant it`, `Add ${plan.grantId} to writes.operations for profile ${selection.name}`);
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
function replay(entry) {
|
|
46
|
+
const { intent, outcome } = entry;
|
|
47
|
+
if (outcome === undefined || outcome.outcome === "unknown_outcome") {
|
|
48
|
+
throw new AxiError("UNKNOWN_OUTCOME", `Write ${intent.entryId} for request ${intent.requestId ?? ""} has no known outcome; it was not sent again`, [
|
|
49
|
+
statusHelp(intent.entryId),
|
|
50
|
+
UNKNOWN_OUTCOME,
|
|
51
|
+
]);
|
|
52
|
+
}
|
|
53
|
+
if (outcome.code !== undefined && isErrorCode(outcome.code)) {
|
|
54
|
+
throw new AxiError(outcome.code, `Write ${intent.entryId} already ended with ${outcome.outcome}: ${outcome.message ?? ""}`, [statusHelp(intent.entryId)]);
|
|
55
|
+
}
|
|
56
|
+
return { outcome: outcome.outcome, entryId: intent.entryId, grantId: intent.grantId, target: intent.target, replayed: true, help: [statusHelp(intent.entryId)] };
|
|
57
|
+
}
|
|
58
|
+
async function baseStateHash(plan) {
|
|
59
|
+
return plan.before === undefined ? STATELESS : stateHash(await plan.before());
|
|
60
|
+
}
|
|
61
|
+
const confirmationMismatch = () => new AxiError("CONFIRMATION_MISMATCH", "The confirmation does not match this write or the current Home Assistant state", [
|
|
62
|
+
"Run the preview again and review the changes before executing",
|
|
63
|
+
]);
|
|
64
|
+
function checkConfirmationAge(issuedAtEpoch) {
|
|
65
|
+
const age = nowEpoch() - issuedAtEpoch;
|
|
66
|
+
if (age > CONFIRMATION_TTL_SECONDS) {
|
|
67
|
+
throw new AxiError("CONFIRMATION_EXPIRED", `The confirmation was issued ${String(age)} seconds ago; it is valid for ${String(CONFIRMATION_TTL_SECONDS)}`, [
|
|
68
|
+
"Run the preview again for a fresh digest",
|
|
69
|
+
]);
|
|
70
|
+
}
|
|
71
|
+
if (age < 0)
|
|
72
|
+
throw confirmationMismatch();
|
|
73
|
+
}
|
|
74
|
+
async function confirm(plan, input, token) {
|
|
75
|
+
const parsed = token === undefined ? undefined : parseToken(token);
|
|
76
|
+
if (token === undefined || parsed === undefined) {
|
|
77
|
+
throw new AxiError("CONFIRMATION_REQUIRED", `${plan.grantId} needs --confirm <digest> from a preview`, ["Run without --execute to preview the write and get a digest"]);
|
|
78
|
+
}
|
|
79
|
+
checkConfirmationAge(parsed.issuedAtEpoch);
|
|
80
|
+
const beforeHash = await baseStateHash(plan);
|
|
81
|
+
checkConfirmationAge(parsed.issuedAtEpoch);
|
|
82
|
+
if (confirmationToken({ ...input, baseStateHash: beforeHash }, parsed.issuedAtEpoch) !== token)
|
|
83
|
+
throw confirmationMismatch();
|
|
84
|
+
return token;
|
|
85
|
+
}
|
|
86
|
+
async function dispatch(plan, session) {
|
|
87
|
+
if ("ws" in plan) {
|
|
88
|
+
const result = await mutateWs(session, plan.ws, "write");
|
|
89
|
+
if (!result.success)
|
|
90
|
+
throw new AxiError("UPSTREAM_ERROR", `WebSocket command ${plan.ws.type} failed: ${result.error.code}: ${result.error.message}`);
|
|
91
|
+
return await readback(() => plan.verify(result));
|
|
92
|
+
}
|
|
93
|
+
const response = await mutateRest(session, plan.rest, "write");
|
|
94
|
+
if (response.status < 200 || response.status > 299)
|
|
95
|
+
throw statusError(response.status, response.text, `${plan.rest.method} ${plan.rest.path}`);
|
|
96
|
+
return await readback(() => plan.verify(response));
|
|
97
|
+
}
|
|
98
|
+
async function readback(verify) {
|
|
99
|
+
try {
|
|
100
|
+
return await verify();
|
|
101
|
+
}
|
|
102
|
+
catch (error) {
|
|
103
|
+
const reason = error instanceof AxiError ? `${error.code}: ${error.message}` : "unexpected error";
|
|
104
|
+
return { outcome: "executed_unverified", details: { readback: `failed (${reason})` } };
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
function unknown(intent, cause) {
|
|
108
|
+
return new AxiError("UNKNOWN_OUTCOME", `Write ${intent.entryId} was sent but its outcome is unknown (${cause})`, [statusHelp(intent.entryId), UNKNOWN_OUTCOME]);
|
|
109
|
+
}
|
|
110
|
+
async function execute(plan, journal, intent, { session, redactor }) {
|
|
111
|
+
const record = (outcome, error) => {
|
|
112
|
+
journal.append({
|
|
113
|
+
kind: "outcome",
|
|
114
|
+
entryId: intent.entryId,
|
|
115
|
+
outcome,
|
|
116
|
+
...(error === undefined ? {} : { code: error.code, message: error.message }),
|
|
117
|
+
timestamp: new Date().toISOString(),
|
|
118
|
+
});
|
|
119
|
+
};
|
|
120
|
+
let result;
|
|
121
|
+
try {
|
|
122
|
+
result = await dispatch(plan, session);
|
|
123
|
+
}
|
|
124
|
+
catch (error) {
|
|
125
|
+
if (!(error instanceof AxiError) || outcomeUnknown(error)) {
|
|
126
|
+
const failure = unknown(intent, error instanceof AxiError ? `${error.code}: ${error.message}` : "unexpected error");
|
|
127
|
+
try {
|
|
128
|
+
record("unknown_outcome");
|
|
129
|
+
}
|
|
130
|
+
catch {
|
|
131
|
+
throw failure;
|
|
132
|
+
}
|
|
133
|
+
throw failure;
|
|
134
|
+
}
|
|
135
|
+
try {
|
|
136
|
+
record("failed", error);
|
|
137
|
+
}
|
|
138
|
+
catch {
|
|
139
|
+
throw unknown(intent, "the outcome could not be journaled");
|
|
140
|
+
}
|
|
141
|
+
throw new AxiError(error.code, error.message, [...error.help, statusHelp(intent.entryId)]);
|
|
142
|
+
}
|
|
143
|
+
const mismatch = result.outcome === "executed_mismatch"
|
|
144
|
+
? new AxiError("READBACK_MISMATCH", `Write ${intent.entryId} was acknowledged but the readback of ${intent.target} does not match`, [statusHelp(intent.entryId)])
|
|
145
|
+
: undefined;
|
|
146
|
+
try {
|
|
147
|
+
record(result.outcome, mismatch);
|
|
148
|
+
}
|
|
149
|
+
catch {
|
|
150
|
+
throw unknown(intent, "the outcome could not be journaled");
|
|
151
|
+
}
|
|
152
|
+
if (mismatch !== undefined)
|
|
153
|
+
throw mismatch;
|
|
154
|
+
return {
|
|
155
|
+
outcome: result.outcome,
|
|
156
|
+
entryId: intent.entryId,
|
|
157
|
+
grantId: intent.grantId,
|
|
158
|
+
target: intent.target,
|
|
159
|
+
...(intent.requestId === undefined ? {} : { requestId: intent.requestId }),
|
|
160
|
+
...(result.details === undefined ? {} : { details: redactPayload(result.details, redactor) }),
|
|
161
|
+
help: [
|
|
162
|
+
...(result.outcome === "executed_unverified" ? [`Home Assistant acknowledged the write; check ${intent.target} to confirm its effect`] : []),
|
|
163
|
+
statusHelp(intent.entryId),
|
|
164
|
+
],
|
|
165
|
+
};
|
|
166
|
+
}
|
|
167
|
+
export async function runWrite(request, options, context) {
|
|
168
|
+
try {
|
|
169
|
+
return await coordinate(request, options, context);
|
|
170
|
+
}
|
|
171
|
+
catch (error) {
|
|
172
|
+
if (!(error instanceof AxiError))
|
|
173
|
+
throw error;
|
|
174
|
+
const { redactor } = context;
|
|
175
|
+
throw new AxiError(error.code, redactor.text(error.message), error.help.map((line) => redactor.text(line)));
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
async function coordinate(request, options, context) {
|
|
179
|
+
const { selection, session, redactor } = context;
|
|
180
|
+
validate(options, redactor);
|
|
181
|
+
const plan = { ...request, target: redactor.text(request.target) };
|
|
182
|
+
const input = { grantId: plan.grantId, origin: session.origin, normalizedRequest: normalized(plan) };
|
|
183
|
+
if (options.execute !== true) {
|
|
184
|
+
const issuedAtEpoch = nowEpoch();
|
|
185
|
+
const token = confirmationToken({ ...input, baseStateHash: await baseStateHash(plan) }, issuedAtEpoch);
|
|
186
|
+
return {
|
|
187
|
+
outcome: "preview",
|
|
188
|
+
grantId: plan.grantId,
|
|
189
|
+
target: plan.target,
|
|
190
|
+
confirm: token,
|
|
191
|
+
expiresAt: new Date((issuedAtEpoch + CONFIRMATION_TTL_SECONDS) * 1000).toISOString(),
|
|
192
|
+
help: [`Run the same command with --execute --confirm ${token} within ${String(CONFIRMATION_TTL_SECONDS / 60)} minutes to apply it`],
|
|
193
|
+
};
|
|
194
|
+
}
|
|
195
|
+
gate(plan, selection);
|
|
196
|
+
const journal = new Journal(context.host, context.files, redactor);
|
|
197
|
+
const requestId = options["request-id"];
|
|
198
|
+
const requestHash = sha256(canonicalJson(input));
|
|
199
|
+
const claimed = await journal.locked(async () => {
|
|
200
|
+
if (requestId !== undefined) {
|
|
201
|
+
const previous = journal.entries().findLast((entry) => entry.intent.requestId === requestId);
|
|
202
|
+
if (previous !== undefined && previous.intent.requestHash !== requestHash) {
|
|
203
|
+
throw new AxiError("INVALID_ARGUMENT", `--request-id ${requestId} was already used for a different write (${previous.intent.entryId})`, [
|
|
204
|
+
"Use a new request ID for a new write",
|
|
205
|
+
]);
|
|
206
|
+
}
|
|
207
|
+
if (previous !== undefined)
|
|
208
|
+
return { previous };
|
|
209
|
+
}
|
|
210
|
+
const digest = await confirm(plan, input, options.confirm);
|
|
211
|
+
const intent = {
|
|
212
|
+
kind: "intent",
|
|
213
|
+
entryId: randomUUID(),
|
|
214
|
+
...(requestId === undefined ? {} : { requestId }),
|
|
215
|
+
grantId: plan.grantId,
|
|
216
|
+
target: plan.target,
|
|
217
|
+
origin: session.origin,
|
|
218
|
+
requestHash,
|
|
219
|
+
digest,
|
|
220
|
+
timestamp: new Date().toISOString(),
|
|
221
|
+
};
|
|
222
|
+
try {
|
|
223
|
+
journal.append(intent);
|
|
224
|
+
}
|
|
225
|
+
catch (error) {
|
|
226
|
+
if (!(error instanceof AxiError))
|
|
227
|
+
throw error;
|
|
228
|
+
throw new AxiError(error.code, error.message, [...error.help, "The intent could not be journaled, so nothing was sent"]);
|
|
229
|
+
}
|
|
230
|
+
return { intent };
|
|
231
|
+
});
|
|
232
|
+
return "previous" in claimed ? replay(claimed.previous) : await execute(plan, journal, claimed.intent, context);
|
|
233
|
+
}
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
export const CONFIRMATION_TTL_SECONDS = 300;
|
|
3
|
+
export const STATELESS = "none";
|
|
4
|
+
export function canonicalJson(value) {
|
|
5
|
+
if (value === null || typeof value === "boolean" || typeof value === "string")
|
|
6
|
+
return JSON.stringify(value);
|
|
7
|
+
if (typeof value === "number") {
|
|
8
|
+
if (!Number.isFinite(value))
|
|
9
|
+
throw new TypeError("Canonical JSON numbers must be finite");
|
|
10
|
+
return JSON.stringify(value);
|
|
11
|
+
}
|
|
12
|
+
if (Array.isArray(value))
|
|
13
|
+
return `[${value.map((item) => (item === undefined ? "null" : canonicalJson(item))).join(",")}]`;
|
|
14
|
+
if (typeof value === "object") {
|
|
15
|
+
const members = Object.entries(value)
|
|
16
|
+
.filter(([, item]) => item !== undefined)
|
|
17
|
+
.sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))
|
|
18
|
+
.map(([key, item]) => `${JSON.stringify(key)}:${canonicalJson(item)}`);
|
|
19
|
+
return `{${members.join(",")}}`;
|
|
20
|
+
}
|
|
21
|
+
throw new TypeError(`Canonical JSON cannot encode ${typeof value}`);
|
|
22
|
+
}
|
|
23
|
+
export const sha256 = (text) => createHash("sha256").update(text).digest("hex");
|
|
24
|
+
export const stateHash = (state) => sha256(canonicalJson(state));
|
|
25
|
+
export const confirmationToken = (input, issuedAtEpoch) => `${String(issuedAtEpoch)}.${sha256(canonicalJson({ ...input, issuedAtEpoch }))}`;
|
|
26
|
+
export function parseToken(token) {
|
|
27
|
+
const match = /^(\d{1,12})\.[0-9a-f]{64}$/.exec(token);
|
|
28
|
+
return match === null ? undefined : { issuedAtEpoch: Number(match[1]) };
|
|
29
|
+
}
|
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
import { closeSync, openSync, readFileSync, rmSync, writeSync } from "node:fs";
|
|
2
|
+
import { dirname } from "node:path";
|
|
3
|
+
import { setTimeout as delay } from "node:timers/promises";
|
|
4
|
+
import { z } from "zod";
|
|
5
|
+
import { AxiError, errnoCode } from "../credentials/errors.js";
|
|
6
|
+
import { defaultWriteLog, writeLogPath } from "../credentials/paths.js";
|
|
7
|
+
import { redactPayload } from "../credentials/redact.js";
|
|
8
|
+
const LOCK_WAIT_MS = 10_000;
|
|
9
|
+
const LOCK_RETRY_MS = 25;
|
|
10
|
+
export const OUTCOMES = ["executed_verified", "executed_unverified", "executed_mismatch", "unknown_outcome", "failed"];
|
|
11
|
+
const intentSchema = z.object({
|
|
12
|
+
kind: z.literal("intent"),
|
|
13
|
+
entryId: z.string(),
|
|
14
|
+
requestId: z.string().optional(),
|
|
15
|
+
grantId: z.string(),
|
|
16
|
+
target: z.string(),
|
|
17
|
+
origin: z.string(),
|
|
18
|
+
requestHash: z.string(),
|
|
19
|
+
digest: z.string(),
|
|
20
|
+
timestamp: z.string(),
|
|
21
|
+
});
|
|
22
|
+
const outcomeSchema = z.object({
|
|
23
|
+
kind: z.literal("outcome"),
|
|
24
|
+
entryId: z.string(),
|
|
25
|
+
outcome: z.enum(OUTCOMES),
|
|
26
|
+
code: z.string().optional(),
|
|
27
|
+
message: z.string().optional(),
|
|
28
|
+
timestamp: z.string(),
|
|
29
|
+
});
|
|
30
|
+
const entrySchema = z.discriminatedUnion("kind", [intentSchema, outcomeSchema]);
|
|
31
|
+
export class Journal {
|
|
32
|
+
path;
|
|
33
|
+
#defaultDirectory;
|
|
34
|
+
#files;
|
|
35
|
+
#redactor;
|
|
36
|
+
constructor(host, files, redactor) {
|
|
37
|
+
this.path = writeLogPath(host);
|
|
38
|
+
this.#defaultDirectory = defaultWriteLog(host);
|
|
39
|
+
this.#files = files;
|
|
40
|
+
this.#redactor = redactor;
|
|
41
|
+
}
|
|
42
|
+
entries() {
|
|
43
|
+
const records = (this.#files.read(this.path, "secret", true) ?? "").split("\n").flatMap((line) => {
|
|
44
|
+
try {
|
|
45
|
+
const parsed = entrySchema.safeParse(JSON.parse(line));
|
|
46
|
+
return parsed.success ? [parsed.data] : [];
|
|
47
|
+
}
|
|
48
|
+
catch {
|
|
49
|
+
return [];
|
|
50
|
+
}
|
|
51
|
+
});
|
|
52
|
+
const outcomes = new Map(records.flatMap((record) => (record.kind === "outcome" ? [[record.entryId, record]] : [])));
|
|
53
|
+
return records.flatMap((record) => {
|
|
54
|
+
if (record.kind !== "intent")
|
|
55
|
+
return [];
|
|
56
|
+
const outcome = outcomes.get(record.entryId);
|
|
57
|
+
return [outcome === undefined ? { intent: record } : { intent: record, outcome }];
|
|
58
|
+
});
|
|
59
|
+
}
|
|
60
|
+
append(record) {
|
|
61
|
+
this.#files.append(this.path, this.#defaultDirectory, JSON.stringify(redactPayload(record, this.#redactor)));
|
|
62
|
+
}
|
|
63
|
+
async locked(action) {
|
|
64
|
+
const lock = `${this.path}.lock`;
|
|
65
|
+
this.#files.ensureDirectory(dirname(this.path), this.#defaultDirectory);
|
|
66
|
+
const deadline = Date.now() + LOCK_WAIT_MS;
|
|
67
|
+
for (;;) {
|
|
68
|
+
const holder = acquire(lock);
|
|
69
|
+
if (holder === undefined)
|
|
70
|
+
break;
|
|
71
|
+
if (holder !== "unknown" && !alive(holder)) {
|
|
72
|
+
rmSync(lock, { force: true });
|
|
73
|
+
continue;
|
|
74
|
+
}
|
|
75
|
+
if (Date.now() >= deadline) {
|
|
76
|
+
throw new AxiError("WRITE_DISABLED", `${lock} is held by another ha-axi write${holder === "unknown" ? "" : ` (process ${String(holder)})`}; nothing was sent`, [
|
|
77
|
+
"Wait for that write to finish, or remove the lock file once no ha-axi process is running",
|
|
78
|
+
]);
|
|
79
|
+
}
|
|
80
|
+
await delay(LOCK_RETRY_MS);
|
|
81
|
+
}
|
|
82
|
+
try {
|
|
83
|
+
return await action();
|
|
84
|
+
}
|
|
85
|
+
finally {
|
|
86
|
+
rmSync(lock, { force: true });
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
function acquire(lock) {
|
|
91
|
+
let fd;
|
|
92
|
+
try {
|
|
93
|
+
fd = openSync(lock, "wx", 0o600);
|
|
94
|
+
}
|
|
95
|
+
catch (error) {
|
|
96
|
+
if (errnoCode(error) !== "EEXIST") {
|
|
97
|
+
throw new AxiError("CONFIG_INSECURE", `${lock} could not be created (${errnoCode(error) ?? "unknown error"}); nothing was sent`);
|
|
98
|
+
}
|
|
99
|
+
try {
|
|
100
|
+
const pid = Number(readFileSync(lock, "utf8"));
|
|
101
|
+
return Number.isSafeInteger(pid) && pid > 0 ? pid : "unknown";
|
|
102
|
+
}
|
|
103
|
+
catch {
|
|
104
|
+
return "unknown";
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
try {
|
|
108
|
+
writeSync(fd, String(process.pid));
|
|
109
|
+
}
|
|
110
|
+
finally {
|
|
111
|
+
closeSync(fd);
|
|
112
|
+
}
|
|
113
|
+
return undefined;
|
|
114
|
+
}
|
|
115
|
+
function alive(pid) {
|
|
116
|
+
try {
|
|
117
|
+
process.kill(pid, 0);
|
|
118
|
+
return true;
|
|
119
|
+
}
|
|
120
|
+
catch (error) {
|
|
121
|
+
return errnoCode(error) === "EPERM";
|
|
122
|
+
}
|
|
123
|
+
}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import { AxiError } from "../credentials/errors.js";
|
|
2
|
+
import { mutateRest } from "../transport/mutate.js";
|
|
3
|
+
import { mutateWs } from "../transport/mutate-ws.js";
|
|
4
|
+
function requireWriteEnabled(readOnly, label) {
|
|
5
|
+
if (readOnly)
|
|
6
|
+
throw new AxiError("WRITE_DISABLED", `${label} is a raw write and HA_AXI_READ_ONLY is true; nothing was sent`, [
|
|
7
|
+
"Raw reads on the read-safe allowlist still work while HA_AXI_READ_ONLY is true",
|
|
8
|
+
]);
|
|
9
|
+
}
|
|
10
|
+
export async function passthroughRest(session, readOnly, request) {
|
|
11
|
+
requireWriteEnabled(readOnly, `${request.method} ${request.path}`);
|
|
12
|
+
return await mutateRest(session, request, "write");
|
|
13
|
+
}
|
|
14
|
+
export async function passthroughWs(session, readOnly, request) {
|
|
15
|
+
requireWriteEnabled(readOnly, `WebSocket command ${request.type}`);
|
|
16
|
+
return await mutateWs(session, request, "write");
|
|
17
|
+
}
|