@astrofoundry/pi-astro 0.40.32 → 0.40.34

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.
@@ -1,7 +1,7 @@
1
1
  import { describe, expect, it } from "vitest";
2
2
  import type { ArcaneReport } from "./daily-report.ts";
3
3
  import type { ToolsReport } from "./tools-report.ts";
4
- import { agoSeconds, arcaneSummary, backupStatus, dnsStatus, edgeStatus, identityStatus, inferenceStatus, mediaStatus, networkStatus, problemText, proxmoxStatus, summaryText, toolsSummary } from "./daily-run.ts";
4
+ import { agoSeconds, arcaneSummary, backupStatus, dnsStatus, edgeStatus, identityStatus, inferenceStatus, mediaStatus, networkStatus, pendingPackageLines, problemText, proxmoxStatus, summaryText, toolsSummary, updatesStatus } from "./daily-run.ts";
5
5
 
6
6
  const EDGE = `nginx active
7
7
  wg-quick@wg0 active
@@ -62,13 +62,36 @@ describe("morning status lines", () => {
62
62
  expect(edgeStatus(null, null)).toMatchObject({ line: "the check failed (vps status)", problem: "Edge: the status check failed" });
63
63
  });
64
64
 
65
- it("reports Pulsar and its waiting host packages without flagging them", () => {
66
- expect(proxmoxStatus(PULSAR, PULSAR_UPDATES)).toEqual({ area: "Proxmox", line: "Pulsar up 59 days, RAM 47Gi of 60Gi used, root disk 13%, 2 host package updates waiting (1 security), applied by hand" });
65
+ it("reports both Proxmox hosts and their waiting host packages without flagging them", () => {
66
+ const held = `${PULSAR_UPDATES}\nwazuh-agent/stable 4.14.9-1 amd64 [upgradable from: 4.14.7-1]`;
67
+ expect(proxmoxStatus([{ name: "Pulsar", status: PULSAR, updates: held }])).toEqual({ area: "Proxmox", line: "Pulsar up 59 days, RAM 47Gi of 60Gi used, root disk 13%, 2 host package updates waiting (1 security), applied by hand" });
68
+ const both = proxmoxStatus([
69
+ { name: "Pulsar", status: PULSAR, updates: PULSAR_UPDATES },
70
+ { name: "SPACE-X", status: null, updates: null },
71
+ ]);
72
+ expect(both.line).toBe("Pulsar up 59 days, RAM 47Gi of 60Gi used, root disk 13%, 2 host package updates waiting (1 security), applied by hand; SPACE-X status unknown");
73
+ expect(both).toMatchObject({ problem: "Proxmox: the status check failed for SPACE-X", route: "admin" });
74
+ });
75
+
76
+ it("flags updates the nightly run left behind, reading guest-agent JSON too, and ignores the held Wazuh agent", () => {
77
+ const vm = JSON.stringify({ exitcode: 0, exited: 1, "out-data": "Listing...\ndocker-ce/trixie 5:29.9.2-1 amd64 [upgradable from: 5:29.7.2-1]\nwazuh-agent/stable 4.14.9-1 amd64 [upgradable from: 4.14.7-1]\n" });
78
+ expect(pendingPackageLines(vm)).toEqual(["docker-ce/trixie 5:29.9.2-1 amd64 [upgradable from: 5:29.7.2-1]"]);
79
+ const held = "Listing...\nwazuh-agent/stable 4.14.9-1 amd64 [upgradable from: 4.14.7-1]";
80
+ expect(updatesStatus({ technitium2: held, synapse: "Listing..." })).toEqual({ area: "Updates", line: "2 hosts up to date after the nightly run" });
81
+ expect(updatesStatus({ arcane: vm, "technitium3 (Mira)": held, radius: null })).toEqual({
82
+ area: "Updates",
83
+ line: "still waiting after the nightly run: arcane 1; no update list from radius",
84
+ problem: "Updates: arcane (docker-ce) did not install overnight; no update list from radius",
85
+ route: "admin",
86
+ });
67
87
  });
68
88
 
69
89
  it("checks RADIUS and the Tailscale router", () => {
70
90
  expect(networkStatus(RADIUS, TAILSCALE)).toEqual({ area: "Network", line: "RADIUS running, Tailscale router tailscale-37 online" });
71
- expect(networkStatus(RADIUS.replace("active (running)", "failed (Result: exit-code)"), "100.121.19.2 tailscale-37 astronaute@ linux offline, last seen 1h ago")).toMatchObject({ problem: "Network: FreeRADIUS is not running; the Tailscale subnet router is offline" });
91
+ const both = `${TAILSCALE}\n100.95.12.39 astro-mb-m5-2 astronaute@ macOS offline, last seen 15h ago\n100.106.244.101 tailscale-mira astronaute@ linux -`;
92
+ expect(networkStatus(RADIUS, both)).toEqual({ area: "Network", line: "RADIUS running, Tailscale routers tailscale-37 and tailscale-mira online" });
93
+ expect(networkStatus(RADIUS, both.replace("tailscale-mira astronaute@ linux -", "tailscale-mira astronaute@ linux offline, last seen 2h ago"))).toMatchObject({ line: "RADIUS running, Tailscale offline: tailscale-mira", problem: "Network: the Tailscale subnet router tailscale-mira is offline" });
94
+ expect(networkStatus(RADIUS.replace("active (running)", "failed (Result: exit-code)"), "100.121.19.2 tailscale-37 astronaute@ linux offline, last seen 1h ago")).toMatchObject({ problem: "Network: FreeRADIUS is not running; the Tailscale subnet router tailscale-37 is offline" });
72
95
  expect(networkStatus(null, TAILSCALE).problem).toBe("Network: a network status check failed");
73
96
  });
74
97
 
@@ -50,30 +50,94 @@ export function edgeStatus(status: string | null, updates: string | null): AreaS
50
50
  return { area: "Edge", line: `front door: ${parts.join(", ")}`, ...(problem ? { problem, route: "admin" as const } : {}) };
51
51
  }
52
52
 
53
- /** `proxmox host-status` and `proxmox updates`: Pulsar's uptime, memory, root disk, and pending packages (report only). */
54
- export function proxmoxStatus(status: string | null, updates: string | null): AreaStatus {
55
- if (status === null) return failed("Proxmox", "admin", "host-status");
56
- const up = /up\s+([^,]+(?:,\s*\d+:\d+)?)/.exec(status)?.[1]?.split(",")[0]?.trim();
57
- const mem = /^Mem:\s+(\S+)\s+(\S+)/m.exec(status);
58
- const root = /\s(\d+)%\s+\/\s*$/m.exec(status)?.[1];
59
- const lines = updates === null ? null : updates.split("\n").filter((l) => l.includes("[upgradable from"));
53
+ /** One Proxmox host's `host-status` and `updates` output. */
54
+ export interface ProxmoxHost {
55
+ name: string;
56
+ status: string | null;
57
+ updates: string | null;
58
+ }
59
+
60
+ function proxmoxHostLine(h: ProxmoxHost): string {
61
+ if (h.status === null) return `${h.name} status unknown`;
62
+ const up = /up\s+([^,]+(?:,\s*\d+:\d+)?)/.exec(h.status)?.[1]?.split(",")[0]?.trim();
63
+ const mem = /^Mem:\s+(\S+)\s+(\S+)/m.exec(h.status);
64
+ const root = /\s(\d+)%\s+\/\s*$/m.exec(h.status)?.[1];
65
+ const lines = h.updates === null ? null : pendingPackageLines(h.updates);
60
66
  const security = lines?.filter((l) => /-security\s/.test(l)).length ?? 0;
61
- const parts = [
62
- up ? `Pulsar up ${up}` : "Pulsar up",
67
+ return [
68
+ up ? `${h.name} up ${up}` : `${h.name} up`,
63
69
  mem ? `RAM ${mem[2]} of ${mem[1]} used` : null,
64
70
  root ? `root disk ${root}%` : null,
65
71
  lines === null ? "updates unknown" : `${lines.length} host package update${lines.length === 1 ? "" : "s"} waiting${security > 0 ? ` (${security} security)` : ""}, applied by hand`,
72
+ ]
73
+ .filter(Boolean)
74
+ .join(", ");
75
+ }
76
+
77
+ /** `proxmox [space-x] host-status` and `updates`: each host's uptime, memory, root disk, and pending packages (report only). */
78
+ export function proxmoxStatus(hosts: readonly ProxmoxHost[]): AreaStatus {
79
+ const unknown = hosts.filter((h) => h.status === null).map((h) => h.name);
80
+ const line = hosts.map(proxmoxHostLine).join("; ");
81
+ return { area: "Proxmox", line, ...(unknown.length > 0 ? { problem: `Proxmox: the status check failed for ${unknown.join(" and ")}`, route: "admin" as const } : {}) };
82
+ }
83
+
84
+ /** Packages the nightly run leaves alone on purpose: a Wazuh agent must never be newer than the manager. */
85
+ const HELD_PACKAGES = new Set(["wazuh-agent"]);
86
+
87
+ /** The `[upgradable from` lines of `apt list --upgradable`, also when a VM's guest agent wraps them in JSON (`out-data`); held packages left out. */
88
+ export function pendingPackageLines(output: string): string[] {
89
+ let text = output;
90
+ try {
91
+ const wrapped = (JSON.parse(output) as { "out-data"?: unknown } | null)?.["out-data"];
92
+ if (typeof wrapped === "string") text = wrapped;
93
+ } catch {
94
+ /* plain apt output */
95
+ }
96
+ return text
97
+ .split("\n")
98
+ .filter((l) => l.includes("[upgradable from"))
99
+ .filter((l) => !HELD_PACKAGES.has(l.split("/")[0]));
100
+ }
101
+
102
+ /** Each guest's and Synapse's `updates` after the 04:30 run: anything still waiting did not install and needs a look. */
103
+ export function updatesStatus(hosts: Readonly<Record<string, string | null>>): AreaStatus {
104
+ const names = Object.keys(hosts);
105
+ const unknown = names.filter((n) => hosts[n] === null);
106
+ const left = names.flatMap((n) => {
107
+ const out = hosts[n];
108
+ const packages = out === null ? [] : pendingPackageLines(out).map((l) => l.split("/")[0]);
109
+ return packages.length > 0 ? [{ name: n, packages }] : [];
110
+ });
111
+ const checked = names.length - unknown.length;
112
+ const parts = [
113
+ left.length === 0 ? `${checked} host${checked === 1 ? "" : "s"} up to date after the nightly run` : `still waiting after the nightly run: ${left.map((h) => `${escapeDiscord(h.name)} ${h.packages.length}`).join(", ")}`,
114
+ unknown.length > 0 ? `no update list from ${unknown.join(", ")}` : null,
66
115
  ].filter(Boolean);
67
- return { area: "Proxmox", line: parts.join(", ") };
116
+ const problems = [
117
+ left.length > 0 ? `${left.map((h) => `${h.name} (${h.packages.slice(0, 4).join(", ")}${h.packages.length > 4 ? ", ..." : ""})`).join("; ")} did not install overnight` : null,
118
+ unknown.length > 0 ? `no update list from ${unknown.join(", ")}` : null,
119
+ ].filter(Boolean);
120
+ return { area: "Updates", line: parts.join("; "), ...(problems.length > 0 ? { problem: `Updates: ${problems.join("; ")}`, route: "admin" as const } : {}) };
68
121
  }
69
122
 
70
- /** `network pulsar radius-status` and `tailscale-status`: FreeRADIUS running, and the subnet router online. */
123
+ /** `network pulsar radius-status` and `tailscale-status`: FreeRADIUS running, and every `tailscale*` subnet router (37 and Mira) online. */
71
124
  export function networkStatus(radius: string | null, tailscale: string | null): AreaStatus {
72
125
  const radiusUp = radius === null ? null : /Active:\s+active \(running\)/.test(radius);
73
- const first = tailscale?.split("\n").find((l) => l.trim().length > 0)?.trim().split(/\s{2,}/) ?? null;
74
- const routerUp = first === null ? null : !/offline/.test(first[first.length - 1] ?? "") && first.length >= 4;
75
- const parts = [radiusUp === null ? "RADIUS unknown" : radiusUp ? "RADIUS running" : "RADIUS down", routerUp === null ? "Tailscale unknown" : routerUp ? `Tailscale router ${first?.[1] ?? ""} online` : "Tailscale router offline"];
76
- const problems = [radiusUp === false ? "FreeRADIUS is not running" : null, routerUp === false ? "the Tailscale subnet router is offline" : null, radiusUp === null || routerUp === null ? "a network status check failed" : null].filter(Boolean);
126
+ const rows = tailscale
127
+ ?.split("\n")
128
+ .map((l) => l.trim().split(/\s{2,}/))
129
+ .filter((c) => c.length >= 4 && /^tailscale/.test(c[1] ?? ""));
130
+ const routers = rows === undefined || rows.length === 0 ? null : rows.map((c) => ({ name: c[1], up: !/offline/.test(c[c.length - 1] ?? "") }));
131
+ const down = routers?.filter((r) => !r.up).map((r) => r.name) ?? [];
132
+ const parts = [
133
+ radiusUp === null ? "RADIUS unknown" : radiusUp ? "RADIUS running" : "RADIUS down",
134
+ routers === null ? "Tailscale unknown" : down.length === 0 ? `Tailscale router${routers.length === 1 ? "" : "s"} ${routers.map((r) => r.name).join(" and ")} online` : `Tailscale offline: ${down.join(", ")}`,
135
+ ];
136
+ const problems = [
137
+ radiusUp === false ? "FreeRADIUS is not running" : null,
138
+ down.length > 0 ? `the Tailscale subnet router ${down.join(" and ")} ${down.length === 1 ? "is" : "are"} offline` : null,
139
+ radiusUp === null || routers === null ? "a network status check failed" : null,
140
+ ].filter(Boolean);
77
141
  return { area: "Network", line: parts.join(", "), ...(problems.length > 0 ? { problem: `Network: ${problems.join("; ")}`, route: "admin" as const } : {}) };
78
142
  }
79
143
 
@@ -78,7 +78,7 @@ import { ArcaneWatch } from "./arcane-watch-monitor.ts";
78
78
  import { parseSnapshot } from "./arcane-watch.ts";
79
79
  import { type Applied, autoFailureText, foremanTask, stackProblems, stackUpdateAnswer, SUPERVISE_DELAY_MS, SUPERVISE_LIMIT_MS } from "./supervise.ts";
80
80
  import { stackPlan, toolPlan } from "./update-policy.ts";
81
- import { type AreaStatus, arcaneSummary, backupStatus, dnsStatus, edgeStatus, identityStatus, inferenceStatus, mediaStatus, networkStatus, problemText, proxmoxStatus, type ReportLine, type Route, summaryText, toolsSummary } from "./daily-run.ts";
81
+ import { type AreaStatus, arcaneSummary, backupStatus, dnsStatus, edgeStatus, identityStatus, inferenceStatus, mediaStatus, networkStatus, problemText, proxmoxStatus, type ReportLine, type Route, summaryText, toolsSummary, updatesStatus } from "./daily-run.ts";
82
82
  import { type InvestigationRequest, SecurityMonitor } from "./security-monitor.ts";
83
83
  import { nasOutage, readSecurityState } from "./security.ts";
84
84
 
@@ -621,7 +621,35 @@ class Bridge {
621
621
  const areas: Promise<AreaStatus>[] = [];
622
622
  if (present.has("backup")) areas.push((async () => backupStatus(await json("backup", ["vzdump-archives"]), await text("backup", ["restic-check-status"]), Date.now()))());
623
623
  if (present.has("edge")) areas.push((async () => edgeStatus(await text("edge", ["vps", "status"]), await text("edge", ["vps", "updates"])))());
624
- if (present.has("proxmox")) areas.push((async () => proxmoxStatus(await text("proxmox", ["host-status"]), await text("proxmox", ["updates"])))());
624
+ if (present.has("proxmox")) {
625
+ areas.push(
626
+ (async () =>
627
+ proxmoxStatus([
628
+ { name: "Pulsar", status: await text("proxmox", ["host-status"]), updates: await text("proxmox", ["updates"]) },
629
+ { name: "SPACE-X", status: await text("proxmox", ["space-x", "host-status"]), updates: await text("proxmox", ["space-x", "updates"]) },
630
+ ]))(),
631
+ );
632
+ areas.push(
633
+ (async () => {
634
+ const hosts: Record<string, string | null> = {};
635
+ // Guests one at a time: each call is an SSH session on the host.
636
+ for (const prefix of [[], ["space-x"]]) {
637
+ const guests = await json("proxmox", [...prefix, "guests"]);
638
+ if (!Array.isArray(guests)) {
639
+ hosts[prefix.length === 0 ? "Pulsar guests" : "SPACE-X guests (Mira)"] = null;
640
+ continue;
641
+ }
642
+ for (const g of guests as { vmid?: unknown; name?: unknown; status?: unknown }[]) {
643
+ if (g.status !== "running" || typeof g.vmid !== "number") continue;
644
+ const name = typeof g.name === "string" ? g.name : String(g.vmid);
645
+ hosts[prefix.length === 0 ? name : `${name} (Mira)`] = await text("proxmox", [...prefix, "guest-exec", String(g.vmid), "updates"]);
646
+ }
647
+ }
648
+ if (present.has("dns")) hosts.synapse = await text("dns", ["technitium", "host", "technitium1", "updates"]);
649
+ return updatesStatus(hosts);
650
+ })(),
651
+ );
652
+ }
625
653
  if (present.has("network")) areas.push((async () => networkStatus(await text("network", ["pulsar", "radius-status"]), await text("network", ["pulsar", "tailscale-status"])))());
626
654
  if (present.has("identity")) areas.push((async () => identityStatus(await text("identity", ["dmz", "status"])))());
627
655
  if (present.has("dns")) {
@@ -23,6 +23,7 @@ describe("approvals", () => {
23
23
  expect(isRisky("network", ["unifi", "37", "nat"])).toBe(false);
24
24
  expect(isRisky("network", ["unifi", "mira", "app-policy-delete", "0123456789abcdef01234567"])).toBe(true);
25
25
  expect(isRisky("network", ["unifi", "mira", "client-fixed-ip", "0123456789abcdef01234567", "{}"])).toBe(true);
26
+ expect(isRisky("network", ["unifi", "mira", "syslog", '{"ip":"10.0.90.10"}'])).toBe(true);
26
27
  expect(isRisky("network", ["unifi", "mira", "device-network", "0123456789abcdef01234567", "{}"])).toBe(true);
27
28
  expect(isRisky("network", ["unifi", "mira", "app-get", "/api/s/default/stat/device"])).toBe(false);
28
29
  expect(isRisky("arcane", ["projects", "list"])).toBe(false);
@@ -33,7 +33,7 @@ export const RISKY: Readonly<Record<string, readonly RegExp[]>> = {
33
33
  ],
34
34
  identity: [/^zitadel\s+(DELETE|POST|PUT|PATCH)\b/, /^dmz\s+(deploy-config|pomerium-restart|render|lego-renew)\b/],
35
35
  // Every UniFi write, on either console.
36
- network: [/^unifi\s+\S+\s+(write|nat-write|device-network|app-policy-delete|client-fixed-ip)\b/],
36
+ network: [/^unifi\s+\S+\s+(write|nat-write|device-network|app-policy-delete|client-fixed-ip|syslog)\b/],
37
37
  dns: [
38
38
  /^technitium\s+primary\s+(zone-create|zone-catalog|zone-delete|record-add|record-update|record-delete|cluster-init|cluster-delete|cluster-remove|server-domain)\b/,
39
39
  /^technitium\s+node\s+\S+\s+(server-domain|stale-zone-delete)\b/,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@astrofoundry/pi-astro",
3
- "version": "0.40.32",
3
+ "version": "0.40.34",
4
4
  "description": "Personal pi customizations (extensions, subagents, skills, prompts, themes) for the pi coding agent.",
5
5
  "keywords": [
6
6
  "pi-package"
@@ -97,7 +97,7 @@ Behavior learned on the live consoles:
97
97
 
98
98
  `client-fixed-ip <clientId> <json>` sets a DHCP reservation: a PUT of `/api/s/default/rest/user/<clientId>` whose body may hold only `use_fixedip`, `fixed_ip`, and `network_id` (the 24-hex network id from `rest/networkconf`). Find the client id with `app-get /api/s/default/rest/user`; a device keeps its old lease until it renews or reconnects.
99
99
 
100
- `app-policy-delete <policyId>` deletes a firewall policy that the official API lists with `id: null`, such as rules converted from the old firewall (Mira's `BLOCK INTERNET` rows on 2026-10-31). Find its 24-hex `_id` with `app-get /v2/api/site/default/firewall-policies`; every other policy change goes through `write`.
100
+ `app-policy-delete <policyId> <name>` deletes a firewall policy that the official API lists with `id: null`, such as rules converted from the old firewall (Mira's `BLOCK INTERNET` rows on 2026-10-31). Find its 24-hex `_id` and exact `name` with `app-get /v2/api/site/default/firewall-policies`; the name shows in the approval, and the wrapper deletes nothing unless the live policy carries that name. Every other policy change goes through `write`.
101
101
 
102
102
  `device-network` changes only a device's management network and address: a PUT of `/api/s/default/rest/device/<deviceId>` whose body may hold just `mgmt_network_id` and `config_network`. Both sites use the same layout: the uplink port stays native Default with all VLANs tagged, and each device sits on Management with a static address and the local DNS nodes.
103
103
 
@@ -107,6 +107,10 @@ Behavior learned on the live consoles:
107
107
 
108
108
  Change one device at a time, downstream devices and the AP serving the operator last, and wait until `devices` shows it `ONLINE` at the new address before the next. An AP takes the Management network and the static address in one step. A switch does not: on 2026-10-31 the Flex XG lost the controller after getting both at once, and reverted to its previous settings by itself about 10 minutes later. For a switch, first send `mgmt_network_id` with `config_network: {"type":"dhcp"}` and wait for `ONLINE`; then send the static address. If it stays in provisioning (`state` 5, `last_config_applied_successfully: false`), restart it. The official `RESTART` device action works only on an `ONLINE` device. A switch powered by PoE can be restarted from its upstream port: `write POST /v1/sites/<siteId>/devices/<upstreamId>/interfaces/ports/<n>/actions '{"action":"POWER_CYCLE"}'`. A restart interrupts everything behind the switch; at Mira that is SPACE-X and technitium3 on Flex XG port 2.
109
109
 
110
+ ## `unifi <37|mira> syslog <json>`
111
+
112
+ Sets the console's activity log export, the classic setting `rsyslogd` (`app-get /api/s/default/rest/setting`, key `rsyslogd`). Network 10.6 shows a separate Integrations > System Logging / SIEM panel that does not change this setting; this setting decides whether the Network application's CEF events reach the SIEM server. Allowed keys: `this_controller`, `ip`, `port`, `contents`, `log_all_contents`, `enabled`; the wrapper keeps every other field of the live setting. 37 sends to `10.0.90.10:514` with `this_controller: false`.
113
+
110
114
  ## `unifi <37|mira> nat` and `unifi <37|mira> nat-write ...`
111
115
 
112
116
  The gateway's NAT rules (Policy Table, type NAT), which the official API lacks. The wrapper calls the Network application's own path `/proxy/network/v2/api/site/default/nat` through the cloud connector with the account key `UNIFI_API_KEY`; `--local` uses the console's local key instead.
@@ -116,7 +120,7 @@ The gateway's NAT rules (Policy Table, type NAT), which the official API lacks.
116
120
  | `nat` | list the rules |
117
121
  | `nat-write POST <json>` | create a rule |
118
122
  | `nat-write PUT <ruleId> <json>` | replace a rule (send the full object) |
119
- | `nat-write DELETE <ruleId>` | delete a rule |
123
+ | `nat-write DELETE <ruleId> <description>` | delete a rule; the wrapper deletes nothing unless the live rule carries that exact `description` |
120
124
 
121
125
  Rule ids and network ids here are the application's 24-hex ids, not the official API's UUIDs. Take a network's id from an existing rule's `in_interface`, or from `unifi cloud /v1/sd-wan-configs/<id>` (`networkId`). Every rule needs a unique `rule_index`: set it explicitly, lowest first; a second rule without one fails with `duplicate rule_index`. An `exclude: true` rule at a lower index exempts its match from the rules after it.
122
126
 
@@ -85,10 +85,11 @@ ${Object.values(UNIFI_READS)
85
85
  set a device's management network and IP (keys mgmt_network_id, config_network)
86
86
  unifi <37|mira> client-fixed-ip <clientId> <json> [--local]
87
87
  set or clear a client's DHCP reservation (keys use_fixedip, fixed_ip, network_id)
88
- unifi <37|mira> app-policy-delete <policyId> [--local]
88
+ unifi <37|mira> syslog <json> [--local] set the console's activity log export (keys this_controller, ip, port, contents, log_all_contents, enabled)
89
+ unifi <37|mira> app-policy-delete <policyId> <name> [--local]
89
90
  delete a firewall policy the official API lists without an id
90
91
  unifi <37|mira> nat [--local] the console's NAT rules (Policy Table; not in the official API)
91
- unifi <37|mira> nat-write POST <json> | PUT <ruleId> <json> | DELETE <ruleId> [--local]
92
+ unifi <37|mira> nat-write POST <json> | PUT <ruleId> <json> | DELETE <ruleId> <description> [--local]
92
93
  unifi <37|mira> fingerprint the local console's certificate fingerprint (for the pin)
93
94
  unifi cloud <path> any GET of the Site Manager API (/v1/ or /ea/, not /v1/connector/)
94
95
  pulsar <command> [args] fixed operations through a forced-command SSH key
@@ -97,7 +98,8 @@ ${Object.entries(PULSAR_COMMANDS)
97
98
  .join("\n")}
98
99
 
99
100
  Calls go through the cloud connector; a read the cloud cannot serve retries on
100
- the local console, a write never does. --local skips the cloud.`;
101
+ the local console, a write never does. --local skips the cloud. A delete names
102
+ its target and runs only when the live object carries that name.`;
101
103
 
102
104
  export interface Query {
103
105
  limit?: number;
@@ -182,6 +184,8 @@ export interface UnifiWrite {
182
184
  method: WriteMethod;
183
185
  path: string;
184
186
  body?: string;
187
+ /** A delete names its target, so the approval shows what goes; the live object must carry that name. */
188
+ target?: { id: string; name: string };
185
189
  }
186
190
 
187
191
  function jsonBody(json: string): string {
@@ -250,23 +254,44 @@ export function clientFixedIpWrite(args: string[]): UnifiWrite {
250
254
  return { method: "PUT", path: `/api/s/default/rest/user/${id}`, body };
251
255
  }
252
256
 
253
- /** `app-policy-delete <policyId>`: a firewall policy that the official API returns with `id: null` (rules converted from the old firewall). */
257
+ export const SETTINGS_PATH = "/api/s/default/rest/setting";
258
+ const SYSLOG_KEYS = new Set(["this_controller", "ip", "port", "contents", "log_all_contents", "enabled"]);
259
+
260
+ /**
261
+ * `syslog <json>`: the console's activity log export (setting `rsyslogd`). Network 10.6 shows a separate
262
+ * System Logging integration that leaves this setting alone, yet this setting decides whether the
263
+ * Network application's CEF events reach a SIEM server.
264
+ */
265
+ export function syslogChanges(args: string[]): Record<string, unknown> {
266
+ const [json, ...extra] = args;
267
+ if (json === undefined || extra.length > 0) throw new UsageError("syslog <json>");
268
+ const changes = JSON.parse(jsonBody(json)) as Record<string, unknown>;
269
+ const keys = Object.keys(changes);
270
+ if (Array.isArray(changes) || keys.length === 0 || keys.some((k) => !SYSLOG_KEYS.has(k))) throw new UsageError(`syslog body keys: ${[...SYSLOG_KEYS].join(", ")}`);
271
+ return changes;
272
+ }
273
+
274
+ export const POLICIES_PATH = "/v2/api/site/default/firewall-policies";
275
+
276
+ /** `app-policy-delete <policyId> <name>`: a firewall policy that the official API returns with `id: null` (rules converted from the old firewall). */
254
277
  export function appPolicyDelete(args: string[]): UnifiWrite {
255
- const [id, ...extra] = args;
256
- if (id === undefined || !NAT_ID.test(id) || extra.length > 0) throw new UsageError("app-policy-delete <24-hex policyId from app-get /v2/api/site/default/firewall-policies>");
257
- return { method: "DELETE", path: `/v2/api/site/default/firewall-policies/${id}` };
278
+ const [id, name, ...extra] = args;
279
+ if (id === undefined || !NAT_ID.test(id) || name === undefined || name.trim() === "" || extra.length > 0) {
280
+ throw new UsageError(`app-policy-delete <24-hex policyId> <name>, both from app-get ${POLICIES_PATH}`);
281
+ }
282
+ return { method: "DELETE", path: `${POLICIES_PATH}/${id}`, target: { id, name } };
258
283
  }
259
284
 
260
- /** `nat-write POST <json>`, `nat-write PUT <ruleId> <json>`, or `nat-write DELETE <ruleId>`. */
285
+ /** `nat-write POST <json>`, `nat-write PUT <ruleId> <json>`, or `nat-write DELETE <ruleId> <description>`. */
261
286
  export function natWrite(args: string[]): UnifiWrite {
262
287
  const [method, first, second, ...extra] = args;
263
288
  if (method === "POST" && first !== undefined && second === undefined) return { method, path: NAT_PATH, body: jsonBody(first) };
264
- if ((method === "PUT" || method === "DELETE") && first !== undefined && NAT_ID.test(first) && extra.length === 0) {
289
+ if ((method === "PUT" || method === "DELETE") && first !== undefined && NAT_ID.test(first) && second !== undefined && extra.length === 0) {
265
290
  const path = `${NAT_PATH}/${first}`;
266
- if (method === "DELETE" && second === undefined) return { method, path };
267
- if (method === "PUT" && second !== undefined) return { method, path, body: jsonBody(second) };
291
+ if (method === "DELETE" && second.trim() !== "") return { method, path, target: { id: first, name: second } };
292
+ if (method === "PUT") return { method, path, body: jsonBody(second) };
268
293
  }
269
- throw new UsageError("nat-write POST <json> | PUT <ruleId> <json> | DELETE <ruleId>");
294
+ throw new UsageError("nat-write POST <json> | PUT <ruleId> <json> | DELETE <ruleId> <description>");
270
295
  }
271
296
 
272
297
  /** `cloud <path>`: a Site Manager read; the connector is reached through the site commands. */
@@ -363,6 +388,21 @@ export function redactUnifi(value: unknown): unknown {
363
388
  return value;
364
389
  }
365
390
 
391
+ /** Reads the list a delete's target lives in and refuses unless the target is there under the name the caller gave. */
392
+ async function requireLiveName(site: Site, config: SiteConfig, local: boolean, listPath: string, field: "name" | "description", target: { id: string; name: string }): Promise<void> {
393
+ const answer = await siteRequest(site, config, local, listPath, "GET", undefined, "app");
394
+ if (answer.status < 200 || answer.status >= 300) throw new ServiceError(`reading ${listPath} answered ${answer.status}; nothing deleted`);
395
+ let list: unknown;
396
+ try {
397
+ list = JSON.parse(answer.body);
398
+ } catch {
399
+ throw new ServiceError(`${listPath} did not answer JSON; nothing deleted`);
400
+ }
401
+ const live = Array.isArray(list) ? (list as Record<string, unknown>[]).find((o) => o._id === target.id) : undefined;
402
+ if (live === undefined) throw new ServiceError(`${target.id} is not in ${listPath} on ${site}; nothing deleted`);
403
+ if (live[field] !== target.name) throw new ServiceError(`${target.id} has ${field} ${JSON.stringify(live[field])}, not ${JSON.stringify(target.name)}; nothing deleted`);
404
+ }
405
+
366
406
  /** The application's classic `/api/s/` paths can report a failure as `meta.rc: "error"`. */
367
407
  function failedMeta(parsed: unknown): boolean {
368
408
  return (parsed as { meta?: { rc?: unknown } } | null)?.meta?.rc === "error";
@@ -397,18 +437,36 @@ async function unifi(args: string[]): Promise<number> {
397
437
  const call = clientFixedIpWrite(rest.slice(1));
398
438
  return printAnswer(await siteRequest(site, readSite(site), local, call.path, call.method, call.body, "app"), `UniFi ${site} client`);
399
439
  }
440
+ if (rest[0] === "syslog") {
441
+ const changes = syslogChanges(rest.slice(1));
442
+ const config = readSite(site);
443
+ const read = await siteRequest(site, config, local, SETTINGS_PATH, "GET", undefined, "app");
444
+ if (read.status < 200 || read.status >= 300) throw new ServiceError(`reading ${SETTINGS_PATH} answered ${read.status}; nothing changed`);
445
+ const current = ((JSON.parse(read.body) as { data?: Record<string, unknown>[] }).data ?? []).find((d) => d.key === "rsyslogd");
446
+ if (current === undefined || typeof current._id !== "string" || !NAT_ID.test(current._id)) throw new ServiceError(`no rsyslogd setting on ${site}; nothing changed`);
447
+ const kept = Object.fromEntries(Object.entries(current).filter(([k]) => k !== "_id" && k !== "site_id"));
448
+ const body = JSON.stringify({ ...kept, ...changes });
449
+ return printAnswer(await siteRequest(site, config, local, `${SETTINGS_PATH}/rsyslogd/${current._id}`, "PUT", body, "app"), `UniFi ${site} syslog`);
450
+ }
400
451
  if (rest[0] === "app-policy-delete") {
401
452
  const call = appPolicyDelete(rest.slice(1));
402
- return printAnswer(await siteRequest(site, readSite(site), local, call.path, call.method, undefined, "app"), `UniFi ${site} policy`);
453
+ const config = readSite(site);
454
+ if (call.target) await requireLiveName(site, config, local, POLICIES_PATH, "name", call.target);
455
+ return printAnswer(await siteRequest(site, config, local, call.path, call.method, undefined, "app"), `UniFi ${site} policy`);
403
456
  }
404
457
  if (rest[0] === "device-network") {
405
458
  const call = deviceNetworkWrite(rest.slice(1));
406
459
  return printAnswer(await siteRequest(site, readSite(site), local, call.path, call.method, call.body, "app"), `UniFi ${site} device`);
407
460
  }
408
- if (rest[0] === "nat" || rest[0] === "nat-write") {
409
- if (rest[0] === "nat" && rest.length > 1) throw new UsageError("unifi <37|mira> nat takes no arguments");
410
- const call = rest[0] === "nat" ? { method: "GET", path: NAT_PATH, body: undefined } : natWrite(rest.slice(1));
411
- return printAnswer(await siteRequest(site, readSite(site), local, call.path, call.method, call.body, "app"), `UniFi ${site} NAT`);
461
+ if (rest[0] === "nat") {
462
+ if (rest.length > 1) throw new UsageError("unifi <37|mira> nat takes no arguments");
463
+ return printAnswer(await siteRequest(site, readSite(site), local, NAT_PATH, "GET", undefined, "app"), `UniFi ${site} NAT`);
464
+ }
465
+ if (rest[0] === "nat-write") {
466
+ const call = natWrite(rest.slice(1));
467
+ const config = readSite(site);
468
+ if (call.target) await requireLiveName(site, config, local, NAT_PATH, "description", call.target);
469
+ return printAnswer(await siteRequest(site, config, local, call.path, call.method, call.body, "app"), `UniFi ${site} NAT`);
412
470
  }
413
471
  const write = rest[0] === "write" ? unifiWrite(rest.slice(1)) : null;
414
472
  const path = write ? write.path : unifiPath(rest);
@@ -11,7 +11,7 @@ import { buildInferenceRemote, command as inferenceCommand } from "./inference/r
11
11
  import { MAX_ADD_IDS, MAX_EXCLUDE_IDS, buildTrendarrCall, interpretRun, parseImdbIds, trendarrConfig, trendarrError, trendarrWarnings, command as mediaCommand } from "./media/run.ts";
12
12
  import { ServiceError, UsageError } from "./lib/errors.ts";
13
13
  import { safeRepoPath, safeWritePath } from "./lib/repo.ts";
14
- import { appGetPath, appPolicyDelete, clientFixedIpWrite, buildPulsarRemote, cloudPath, deviceNetworkWrite, NAT_PATH, natWrite, parseQuery, parseSiteArgs, redactUnifi, unifiPath, unifiWrite, command as networkCommand } from "./network/run.ts";
14
+ import { appGetPath, appPolicyDelete, clientFixedIpWrite, syslogChanges, buildPulsarRemote, cloudPath, deviceNetworkWrite, NAT_PATH, natWrite, parseQuery, parseSiteArgs, redactUnifi, unifiPath, unifiWrite, command as networkCommand } from "./network/run.ts";
15
15
  import { buildHostRemote, splitHost, needsConfirm, parseSetPairs, parseVmid, validateApiPath as validatePvePath, command as proxmoxCommand } from "./proxmox/run.ts";
16
16
  import { banLength, buildObsRemote, compactDecisions, parseGoDuration, summariseAlerts, summariseVulns, summariseWazuh, vulnEvents, wazuhEvents, command as securityCommand } from "./security/run.ts";
17
17
 
@@ -122,8 +122,10 @@ describe("network wrapper", () => {
122
122
  it("limits application reads and device network writes", () => {
123
123
  const id = "0123456789abcdef01234567";
124
124
  expect(appGetPath(["/api/s/default/stat/device"])).toBe("/api/s/default/stat/device");
125
- expect(appPolicyDelete(["0123456789abcdef01234567"])).toEqual({ method: "DELETE", path: "/v2/api/site/default/firewall-policies/0123456789abcdef01234567" });
126
- expect(() => appPolicyDelete(["611cef69-df2e-4498-9845-8685daee84f3"])).toThrow(UsageError);
125
+ expect(appPolicyDelete([id, "BLOCK INTERNET"])).toEqual({ method: "DELETE", path: `/v2/api/site/default/firewall-policies/${id}`, target: { id, name: "BLOCK INTERNET" } });
126
+ expect(() => appPolicyDelete([id])).toThrow(UsageError);
127
+ expect(() => appPolicyDelete([id, " "])).toThrow(UsageError);
128
+ expect(() => appPolicyDelete(["611cef69-df2e-4498-9845-8685daee84f3", "BLOCK INTERNET"])).toThrow(UsageError);
127
129
  const fixed = JSON.stringify({ use_fixedip: true, fixed_ip: "10.1.50.50", network_id: "0123456789abcdef01234567" });
128
130
  expect(clientFixedIpWrite(["0123456789abcdef01234567", fixed])).toEqual({ method: "PUT", path: "/api/s/default/rest/user/0123456789abcdef01234567", body: fixed });
129
131
  expect(() => clientFixedIpWrite(["0123456789abcdef01234567", JSON.stringify({ name: "x" })])).toThrow(/body keys/);
@@ -142,8 +144,10 @@ describe("network wrapper", () => {
142
144
  const id = "0123456789abcdef01234567";
143
145
  expect(natWrite(["POST", '{"type":"DNAT"}'])).toEqual({ method: "POST", path: NAT_PATH, body: '{"type":"DNAT"}' });
144
146
  expect(natWrite(["PUT", id, "{}"])).toEqual({ method: "PUT", path: `${NAT_PATH}/${id}`, body: "{}" });
145
- expect(natWrite(["DELETE", id])).toEqual({ method: "DELETE", path: `${NAT_PATH}/${id}` });
146
- expect(() => natWrite(["DELETE", id, "{}"])).toThrow(UsageError);
147
+ expect(natWrite(["DELETE", id, "IoT DNS redirect"])).toEqual({ method: "DELETE", path: `${NAT_PATH}/${id}`, target: { id, name: "IoT DNS redirect" } });
148
+ expect(() => natWrite(["DELETE", id])).toThrow(UsageError);
149
+ expect(() => natWrite(["DELETE", id, ""])).toThrow(UsageError);
150
+ expect(() => natWrite(["DELETE", id, "IoT DNS redirect", "extra"])).toThrow(UsageError);
147
151
  expect(() => natWrite(["PUT", "not-an-id", "{}"])).toThrow(UsageError);
148
152
  expect(() => natWrite(["POST"])).toThrow(UsageError);
149
153
  expect(() => natWrite(["POST", "{"])).toThrow(/JSON/);
@@ -834,3 +838,94 @@ describe("media wrapper", () => {
834
838
  });
835
839
  });
836
840
  });
841
+
842
+ describe("dns stale-zone-delete", () => {
843
+ let home: string;
844
+ const originalHome = process.env.HOME;
845
+
846
+ beforeEach(() => {
847
+ home = mkdtempSync(join(tmpdir(), "spec-home-"));
848
+ process.env.HOME = home;
849
+ mkdirSync(join(home, ".specialists", "config"), { recursive: true });
850
+ writeFileSync(join(home, ".specialists", "config", "dns.json"), JSON.stringify({ technitiumPrimaryUrl: "http://10.0.40.53:5380" }));
851
+ mkdirSync(join(home, ".specialists", "secrets", "dns"), { recursive: true });
852
+ writeFileSync(join(home, ".specialists", "secrets", "dns", "TECHNITIUM_TOKEN"), "token", { mode: 0o600 });
853
+ });
854
+
855
+ afterEach(() => {
856
+ vi.unstubAllGlobals();
857
+ process.env.HOME = originalHome;
858
+ rmSync(home, { recursive: true, force: true });
859
+ });
860
+
861
+ it("never deletes the cluster catalog, which a Secondary node holds outside any catalog", async () => {
862
+ const paths: string[] = [];
863
+ vi.stubGlobal("fetch", async (url: URL) => {
864
+ paths.push(url.pathname);
865
+ const response = url.pathname === "/api/admin/cluster/state" ? { clusterDomain: "dns.home.arpa" } : { type: "SecondaryCatalog", catalog: null };
866
+ return new Response(JSON.stringify({ status: "ok", response }));
867
+ });
868
+ await expect(dnsCommand(["technitium", "node", "technitium2.dns.home.arpa", "stale-zone-delete", "Cluster-Catalog.dns.home.arpa."])).rejects.toThrow(/cluster catalog/);
869
+ expect(paths).not.toContain("/api/zones/delete");
870
+ });
871
+ });
872
+
873
+ describe("network deletes check the live name", () => {
874
+ let home: string;
875
+ const originalHome = process.env.HOME;
876
+ const id = "0123456789abcdef01234567";
877
+
878
+ beforeEach(() => {
879
+ home = mkdtempSync(join(tmpdir(), "spec-home-"));
880
+ process.env.HOME = home;
881
+ mkdirSync(join(home, ".specialists", "config"), { recursive: true });
882
+ writeFileSync(join(home, ".specialists", "config", "network.json"), JSON.stringify({ unifiMiraHostId: "ABC123:456", unifiMiraLocalUrl: "https://10.1.60.1/proxy/network/integration", unifiMiraCertSha256: "AA" }));
883
+ mkdirSync(join(home, ".specialists", "secrets", "network"), { recursive: true });
884
+ writeFileSync(join(home, ".specialists", "secrets", "network", "UNIFI_API_KEY"), "key", { mode: 0o600 });
885
+ });
886
+
887
+ afterEach(() => {
888
+ vi.unstubAllGlobals();
889
+ process.env.HOME = originalHome;
890
+ rmSync(home, { recursive: true, force: true });
891
+ });
892
+
893
+ function stubConsole(list: unknown[]): string[] {
894
+ const calls: string[] = [];
895
+ vi.stubGlobal("fetch", async (url: string, init?: RequestInit) => {
896
+ calls.push(`${init?.method ?? "GET"} ${new URL(url).pathname}`);
897
+ return new Response(init?.method === "DELETE" ? "{}" : JSON.stringify(list));
898
+ });
899
+ return calls;
900
+ }
901
+
902
+ it("deletes a policy only under its live name", async () => {
903
+ const calls = stubConsole([{ _id: id, name: "BLOCK INTERNET" }]);
904
+ await expect(networkCommand(["unifi", "mira", "app-policy-delete", id, "Allow All"])).rejects.toThrow(/"BLOCK INTERNET", not "Allow All"; nothing deleted/);
905
+ expect(calls.some((c) => c.startsWith("DELETE"))).toBe(false);
906
+ await networkCommand(["unifi", "mira", "app-policy-delete", id, "BLOCK INTERNET"]);
907
+ expect(calls.filter((c) => c.startsWith("DELETE"))).toHaveLength(1);
908
+ });
909
+
910
+ it("changes only the syslog keys and keeps the rest of the live setting", async () => {
911
+ expect(syslogChanges(['{"ip":"10.0.90.10","port":"514"}'])).toEqual({ ip: "10.0.90.10", port: "514" });
912
+ expect(() => syslogChanges(['{"x_secret":"a"}'])).toThrow(UsageError);
913
+ expect(() => syslogChanges(["{}"])).toThrow(UsageError);
914
+ const sent: { method: string; path: string; body?: string }[] = [];
915
+ vi.stubGlobal("fetch", async (url: string, init?: RequestInit) => {
916
+ sent.push({ method: init?.method ?? "GET", path: new URL(url).pathname, body: typeof init?.body === "string" ? init.body : undefined });
917
+ const data = init?.method === "PUT" ? [] : [{ _id: id, site_id: "s1", key: "rsyslogd", this_controller: true, enabled: true }];
918
+ return new Response(JSON.stringify({ meta: { rc: "ok" }, data }));
919
+ });
920
+ await networkCommand(["unifi", "mira", "syslog", '{"this_controller":false,"ip":"10.0.90.10","port":"514"}']);
921
+ const put = sent.find((r) => r.method === "PUT");
922
+ expect(put?.path).toMatch(new RegExp(`/rest/setting/rsyslogd/${id}$`));
923
+ expect(JSON.parse(put?.body ?? "{}")).toEqual({ key: "rsyslogd", this_controller: false, enabled: true, ip: "10.0.90.10", port: "514" });
924
+ });
925
+
926
+ it("refuses a NAT delete of a rule that is not there", async () => {
927
+ const calls = stubConsole([{ _id: "fedcba9876543210fedcba98", description: "IoT DNS redirect" }]);
928
+ await expect(networkCommand(["unifi", "mira", "nat-write", "DELETE", id, "IoT DNS redirect"])).rejects.toThrow(/is not in .*nothing deleted/);
929
+ expect(calls.some((c) => c.startsWith("DELETE"))).toBe(false);
930
+ });
931
+ });