@astrofoundry/pi-astro 0.40.31 → 0.40.33

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.
@@ -78,8 +78,9 @@ describe("morning status lines", () => {
78
78
  });
79
79
 
80
80
  it("checks both resolvers, Nexus, and SABnzbd", () => {
81
- expect(dnsStatus({ status: "ok" }, { status: "ok" })).toEqual({ area: "DNS", line: "both resolvers answer" });
82
- expect(dnsStatus({ status: "ok" }, null)).toMatchObject({ problem: "DNS: the secondary resolver does not answer" });
81
+ expect(dnsStatus({ technitium1: { status: "ok" }, technitium2: { status: "ok" }, technitium3: { status: "ok" } })).toEqual({ area: "DNS", line: "technitium1, technitium2, technitium3 answer" });
82
+ expect(dnsStatus({ technitium1: { status: "ok" }, technitium2: null, technitium3: { status: "ok" } })).toEqual({ area: "DNS", line: "no answer from technitium2", problem: "DNS: technitium2 does not answer", route: "admin" });
83
+ expect(dnsStatus({ technitium1: null, technitium2: { status: "error" }, technitium3: { status: "ok" } })).toMatchObject({ problem: "DNS: technitium1 and technitium2 do not answer" });
83
84
  expect(inferenceStatus("embed \tstate = running \tpid = 80042 health=200\nrerank \tstate = running \tpid = 81670 health=200")).toEqual({ area: "Inference", line: "Nexus embed, rerank running and healthy" });
84
85
  expect(inferenceStatus("embed \tstate = running \tpid = 80042 health=503")).toMatchObject({ problem: "Inference: embed not healthy on Nexus" });
85
86
  expect(mediaStatus({ sabnzbd_paused: true, warnings: [] })).toEqual({ area: "Media", line: "downloads paused" });
@@ -86,11 +86,14 @@ export function identityStatus(status: string | null): AreaStatus {
86
86
  return { area: "Identity", line, ...(bad.length > 0 || units.length === 0 ? { problem: `Identity: ${bad.length > 0 ? bad.join(", ") : "no unit status read"} on the DMZ VM`, route: "admin" as const } : {}) };
87
87
  }
88
88
 
89
- /** `dns technitium <node> resolve <name>`: both resolvers answer an internal name. */
90
- export function dnsStatus(primary: unknown, secondary: unknown): AreaStatus {
89
+ /** `dns technitium primary|node <fqdn> resolve <name>`: every cluster node answers an internal name, keyed by node name. */
90
+ export function dnsStatus(answers: Readonly<Record<string, unknown>>): AreaStatus {
91
91
  const ok = (r: unknown) => (r as { status?: unknown } | null)?.status === "ok";
92
- const down = [ok(primary) ? null : "primary", ok(secondary) ? null : "secondary"].filter(Boolean);
93
- return { area: "DNS", line: down.length === 0 ? "both resolvers answer" : `no answer from the ${down.join(" and ")} resolver`, ...(down.length > 0 ? { problem: `DNS: the ${down.join(" and ")} resolver does not answer`, route: "admin" as const } : {}) };
92
+ const nodes = Object.keys(answers);
93
+ const down = nodes.filter((node) => !ok(answers[node]));
94
+ const names = down.join(" and ");
95
+ if (down.length === 0) return { area: "DNS", line: `${nodes.join(", ")} answer` };
96
+ return { area: "DNS", line: `no answer from ${names}`, problem: `DNS: ${names} ${down.length === 1 ? "does" : "do"} not answer`, route: "admin" };
94
97
  }
95
98
 
96
99
  /** `inference nexus-status`: each Nexus service running with HTTP health 200. */
@@ -169,6 +169,8 @@ const REVIEWER = "astro.release-reviewer";
169
169
  const ARCANE_RUN = "arcane-update";
170
170
  /** An internal name both resolvers must answer for the morning run's DNS line. */
171
171
  const DNS_PROBE = "arcane.37pla.net";
172
+ /** The cluster nodes besides the primary, reached through the primary's `node` parameter. */
173
+ const DNS_NODES = { technitium2: "technitium2.dns.home.arpa", technitium3: "technitium3.dns.home.arpa" } as const;
172
174
 
173
175
  /** The audit caller of updates the morning run applies on its own. */
174
176
  const AUTO_CALLER = "daily-run";
@@ -622,7 +624,18 @@ class Bridge {
622
624
  if (present.has("proxmox")) areas.push((async () => proxmoxStatus(await text("proxmox", ["host-status"]), await text("proxmox", ["updates"])))());
623
625
  if (present.has("network")) areas.push((async () => networkStatus(await text("network", ["pulsar", "radius-status"]), await text("network", ["pulsar", "tailscale-status"])))());
624
626
  if (present.has("identity")) areas.push((async () => identityStatus(await text("identity", ["dmz", "status"])))());
625
- if (present.has("dns")) areas.push((async () => dnsStatus(await json("dns", ["technitium", "primary", "resolve", DNS_PROBE]), await json("dns", ["technitium", "secondary", "resolve", DNS_PROBE])))());
627
+ if (present.has("dns")) {
628
+ areas.push(
629
+ (async () => {
630
+ const [technitium1, technitium2, technitium3] = await Promise.all([
631
+ json("dns", ["technitium", "primary", "resolve", DNS_PROBE]),
632
+ json("dns", ["technitium", "node", DNS_NODES.technitium2, "resolve", DNS_PROBE]),
633
+ json("dns", ["technitium", "node", DNS_NODES.technitium3, "resolve", DNS_PROBE]),
634
+ ]);
635
+ return dnsStatus({ technitium1, technitium2, technitium3 });
636
+ })(),
637
+ );
638
+ }
626
639
  if (present.has("inference")) areas.push((async () => inferenceStatus(await text("inference", ["nexus-status"])))());
627
640
  if (present.has(MEDIA)) areas.push((async () => mediaStatus(await json(MEDIA, ["sabnzbd", "status"])))());
628
641
  return Promise.all(areas);
@@ -42,7 +42,10 @@ describe("approvals", () => {
42
42
  expect(isRisky("arcane", ["host", "radarr-movie", "tt0120737"])).toBe(true);
43
43
  expect(isRisky("arcane", ["host", "db-dump", "mealie"])).toBe(false);
44
44
  expect(isRisky("arcane", ["host", "container-logs", "sonarr", "2026-09-06T12:00:00Z", "2026-09-06T12:15:00Z"])).toBe(false);
45
- expect(isRisky("edge", ["vps", "reboot", "--confirm", "--help"])).toBe(false);
45
+ expect(isRisky("edge", ["vps", "reboot", "--confirm", "--help"])).toBe(true);
46
+ expect(isRisky("dns", ["technitium", "primary", "zone-delete", "example.com", "--help"])).toBe(true);
47
+ expect(isRisky("proxmox", ["snapshot-create", "107", "before", "-h"])).toBe(true);
48
+ expect(isRisky("dns", ["--help"])).toBe(false);
46
49
  expect(isRisky("proxmox", ["guests"])).toBe(false);
47
50
  expect(isRisky("dns", ["technitium", "host", "technitium1", "upgrade"])).toBe(true);
48
51
  expect(isRisky("dns", ["technitium", "host", "technitium3", "restart"])).toBe(true);
@@ -49,8 +49,7 @@ export const RISKY: Readonly<Record<string, readonly RegExp[]>> = {
49
49
  };
50
50
 
51
51
  export function isRisky(service: string, args: readonly string[]): boolean {
52
- // A help lookup prints usage and changes nothing, whatever command it names.
53
- if (args.includes("--help") || args.includes("-h")) return false;
52
+ // `--help` gets no exemption: a wrapper reads it only as the first argument, so anywhere else it would pass a write unasked.
54
53
  if (args.includes("--confirm")) return true;
55
54
  // Flags placed before the command (`--json projects delete x`) must not hide it from the patterns.
56
55
  const joined = args.filter((a) => !a.startsWith("-")).join(" ");
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@astrofoundry/pi-astro",
3
- "version": "0.40.31",
3
+ "version": "0.40.33",
4
4
  "description": "Personal pi customizations (extensions, subagents, skills, prompts, themes) for the pi coding agent.",
5
5
  "keywords": [
6
6
  "pi-package"
@@ -29,7 +29,7 @@ The internal resolvers form one Technitium cluster, `dns.home.arpa`: the Primary
29
29
  | `cluster-remove <secondaryNodeId>` (primary) | ask a Secondary node (id from `cluster-state`) to leave |
30
30
  | `server-domain <name>` (primary or node) | set that node's DNS Server Domain |
31
31
  | `zone-resync <zone>` (primary or node) | re-fetch a Secondary or catalog zone; on a node's cluster catalog it recreates missing member zones |
32
- | `stale-zone-delete <zone>` (node only) | delete a Secondary zone no catalog manages (checked first), so the cluster catalog recreates it |
32
+ | `stale-zone-delete <zone>` (node only) | delete a Secondary zone no catalog manages (checked first), so the cluster catalog recreates it; the cluster catalog itself is refused |
33
33
 
34
34
  Record parameters by type (the API's names): `A`/`AAAA` `ipAddress` (update: `newIpAddress`); `CNAME` `cname`; `TXT` `text`; `MX` `exchange`, `preference`; `SRV` `priority`, `weight`, `port`, `target`; `NS` `nameServer`; `PTR` `ptrName`. `ttl=<seconds>` and `comments=<text>` apply to all; `overwrite=true` replaces the record set on add.
35
35
 
@@ -48,7 +48,7 @@ Change users, passwords, settings, blocklists, and apps only on the primary. Joi
48
48
 
49
49
  API reference: grimoire products `technitium-api` (HTTP API) and `technitium-dns`. The live cluster state lists nodes under `clusterNodes`; the docs call the field `nodes`.
50
50
 
51
- `technitium join <nodeUrl> <nodeIp>` adds a fresh node as a Secondary node: it refuses a node whose default `admin`/`admin` login was already changed, creates a one-time admin with a random password on the primary for the join, and deletes it afterwards. The join replaces the node's settings, blocklists, apps, and users with the primary's. Check `cluster-state` afterwards.
51
+ `technitium join <nodeUrl> <nodeIp>` adds a fresh node as a Secondary node. The URL must name `nodeIp`, a private IPv4 address. It refuses a node whose default `admin`/`admin` login was already changed, creates a one-time admin with a random password on the primary for the join, and deletes it afterwards. The join replaces the node's settings, blocklists, apps, and users with the primary's. Check `cluster-state` afterwards.
52
52
 
53
53
  ```json
54
54
  { "args": ["technitium", "join", "http://10.1.40.53:5380", "10.1.40.53"] }
@@ -66,7 +66,7 @@ Fixed operations on each node's host through one forced-command SSH key (`spc-dn
66
66
  | `restart` | restart Technitium and print its state |
67
67
  | `upgrade` | run the official installer (`download.technitium.com/dns/install.sh`), which upgrades Technitium and its ASP.NET runtime in place; up to 10 minutes |
68
68
 
69
- Upgrade or restart one node at a time and check `cluster-state` and `resolve` on it before the next; the other two nodes keep answering. Upgrade the secondaries first and technitium1 last, and keep all three on the same version.
69
+ Upgrade or restart one node at a time and check `cluster-state` and `resolve` on it before the next; the other two nodes keep answering. The wrapper holds one lock for `restart` and `upgrade` across all nodes and refuses a second one while it runs. Upgrade the secondaries first and technitium1 last, and keep all three on the same version.
70
70
 
71
71
  ```json
72
72
  { "args": ["technitium", "host", "technitium3", "status"] }
@@ -14,7 +14,7 @@ The consoles are joined by Site Magic (SD-WAN). Never call either site "home". T
14
14
 
15
15
  ## Paths to a console
16
16
 
17
- Every `unifi <37|mira>` call goes through the UniFi cloud connector (`api.ui.com`) with the account key. When the cloud cannot serve a read (timeout, rate limit, 5xx, no connection), the wrapper reads from the console directly with that console's local key, TLS pinned, and says so on stderr. A write never retries: the cloud may have applied it before failing, so read the object back first, then retry with `--local` only if it is missing. `--local` skips the cloud. Cortex reaches `37`'s console directly; `mira`'s only once Site Magic carries the route.
17
+ Every `unifi <37|mira>` call goes through the UniFi cloud connector (`api.ui.com`) with the account key. When the cloud cannot serve a read (timeout, rate limit, 5xx, no connection), the wrapper reads from the console directly with that console's local key, TLS pinned, and says so on stderr. A write never retries: the cloud may have applied it before failing, so read the object back first, then retry with `--local` only if it is missing. A cloud timeout or 5xx on a write fails with "the write may have been applied" for the same reason. Secret fields (UniFi's `x_` fields such as `x_passphrase`, and secret-named strings) come back as `[redacted]`; a write body that carries `[redacted]` is refused, so send only the fields to change. `--local` skips the cloud. Cortex reaches `37`'s console directly; `mira`'s only once Site Magic carries the route.
18
18
 
19
19
  ## `unifi <37|mira> <read> [--local] [--limit n] [--offset n] [--filter expr]`
20
20
 
@@ -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
 
@@ -116,7 +116,7 @@ The gateway's NAT rules (Policy Table, type NAT), which the official API lacks.
116
116
  | `nat` | list the rules |
117
117
  | `nat-write POST <json>` | create a rule |
118
118
  | `nat-write PUT <ruleId> <json>` | replace a rule (send the full object) |
119
- | `nat-write DELETE <ruleId>` | delete a rule |
119
+ | `nat-write DELETE <ruleId> <description>` | delete a rule; the wrapper deletes nothing unless the live rule carries that exact `description` |
120
120
 
121
121
  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
122
 
@@ -40,13 +40,13 @@ Wrappers ship as TypeScript and run under Node 24 type stripping: erasable synta
40
40
  - Output filters: Arcane responses pass `stripKeys(ARCANE_DENIED_KEYS)`; Zitadel responses pass `redactSecrets`. Add keys there rather than in a wrapper.
41
41
  - Fixed remote commands: `DMZ_COMMANDS`, `PULSAR_COMMANDS`, `VPS_COMMANDS`, `OBS_COMMANDS`, `BACKUP_COMMANDS`, `HOST_COMMANDS`, and `INFERENCE_COMMANDS` must match the entry scripts in `entry/remote/` and their tracked copies in the homelab repository (`02-pulsar-proxmox/dmz/system/`, `02-pulsar-proxmox/pulsar/system/`, `00-frontdoor-vps/system/`, `02-pulsar-proxmox/observability/system/`, `04-nexus-macstudio/system/`, and `host/` of the `astronaute77/arcane` repository). Pulsar's root `authorized_keys` carries one forced key per specialist (network, backup, proxmox), each pinned to its own entry script. Change both sides in the same commit and redeploy the remote script. A new privileged step on the VPS also needs its exact line in `spc-edge-frontdoor-sudoers`.
42
42
  - Repository access is `lib/repo.ts` (`repoCommand`, `RepoSpec`, `trackedFile`): one clone per specialist under `~/.specialists/work/<checkoutName>` (`homelab-edge`, `homelab-identity`; never share a checkout between specialists), a write deploy key, and an optional `writeRoot` that limits `git write`. `edge` (`deploy-nginx`) and `identity` (`dmz deploy-config`) deploy only what origin has: `trackedFile` refuses a dirty, ahead, or behind checkout. The DMZ entry keeps the previous template and restores it when render or restart fails.
43
- - `network` reaches two consoles, `37` and `mira` (`SITES`), each with `unifi<Site>HostId`, `unifi<Site>LocalUrl`, and `unifi<Site>CertSha256` in `network.json`. `siteRequest` goes through the Site Manager cloud connector (`api.ui.com/v1/connector/consoles/<hostId>/network/integration/...`, account key `UNIFI_API_KEY`); a read the cloud cannot serve (no connection, 408, 429, 5xx) retries on the console itself with its local key (`UNIFI_LOCAL_37_API_KEY`, `UNIFI_LOCAL_MIRA_API_KEY`) through the pinned request, a write never retries because the cloud may have applied it before failing; `--local` skips the cloud. Writes are `unifiWrite`: any `POST`, `PUT`, `PATCH`, or `DELETE` under `/v1/sites/<siteId>/` with a JSON body (none for `DELETE`); UniFi validates the rest, and the gate asks the owner for every one. `unifi cloud <path>` reads the Site Manager API (`/v1/`, `/ea/`, never the connector). Each command reads only the config keys it needs, so `pulsar` works without the UniFi keys.
43
+ - `network` reaches two consoles, `37` and `mira` (`SITES`), each with `unifi<Site>HostId`, `unifi<Site>LocalUrl`, and `unifi<Site>CertSha256` in `network.json`. `siteRequest` goes through the Site Manager cloud connector (`api.ui.com/v1/connector/consoles/<hostId>/network/integration/...`, account key `UNIFI_API_KEY`); a read the cloud cannot serve (no connection, 408, 429, 5xx) retries on the console itself with its local key (`UNIFI_LOCAL_37_API_KEY`, `UNIFI_LOCAL_MIRA_API_KEY`) through the pinned request, a write never retries because the cloud may have applied it before failing, and a cloud 408 or 5xx to a write fails with that hint; `--local` skips the cloud. Every answer passes `redactUnifi`: `x_` fields (UniFi's secret fields: `x_passphrase`, `x_ssh_password`, `x_private_key`, `x_api_token`) and secret-named strings become `[redacted]`, and a write body carrying `[redacted]` is refused, so a read-modify-write cannot store it. `leavesPrefix` refuses `%`, `\`, empty, and dot segments in `get`, `write`, `app-get`, and `cloud` paths, because the URL parser resolves `%2e%2e` like `..`. Writes are `unifiWrite`: any `POST`, `PUT`, `PATCH`, or `DELETE` under `/v1/sites/<siteId>/` with a JSON body (none for `DELETE`); UniFi validates the rest, and the gate asks the owner for every one. `unifi cloud <path>` reads the Site Manager API (`/v1/`, `/ea/`, never the connector). Each command reads only the config keys it needs, so `pulsar` works without the UniFi keys.
44
44
  - Pi executes sibling tool calls in parallel, so two wrapper processes of the same specialist can run at once. `lib/lock.ts` (`withLock`, a directory lock under `~/.specialists/work/locks`, stale after 10 minutes) serialises shared resources; `edge` holds `edge-tunnel` around the fixed IAP port and the gcloud configuration directory. `arcane` holds `arcane-gitops` (stale after 3 hours) around `git`, `manager-upgrade`, and `stack-update`, because an update keeps the checkout for up to about two hours; the other `repo.ts` checkouts are not locked yet.
45
45
  - `edge` retries one SSH call through the IAP tunnel when the first connection is closed during setup (`isTransientSshFailure`: exit 255 with "closed by remote host" or a reset), except `reboot`. The IAP tunnel is `lib/tunnel.ts`: `gcloud compute start-iap-tunnel <instance> 22 --local-host-port=localhost:<port>` (a documented flag; the hidden `--listen-on-stdin` is not used), ready when the port accepts a connection, closed after the ssh call. `gcloud auth activate-service-account` runs before every tunnel with `CLOUDSDK_CONFIG` under `~/.specialists/work/gcloud` and `CLOUDSDK_PYTHON` from the config, because the Homebrew cask ships no interpreter.
46
46
  - `dns` builds every Technitium call from `TECHNITIUM_READS` and `TECHNITIUM_WRITES`; `key=value` record parameters pass through by name (`token` and `node` refused) because the API documents dozens of type-specific parameters. Every call goes to the cluster primary with one token; `node <fqdn>` adds Technitium's `node` parameter so the primary runs a read or `server-domain` on that node. Zone, record, and cluster writes are refused with `node` in code: the catalog zone and the cluster are the only replication paths. `technitium join` joins a fresh node: it logs in with Technitium's default login (refused once changed), creates a one-time admin with a random password on the primary for `initJoin`, and deletes it in `finally`; no password is stored or printed.
47
47
  - `security` parses Wazuh alert lines locally (`summariseWazuh`, `summariseVulns`) so the guest never needs `jq`; `wazuh-vulns`, `wazuh-events` (every non-vulnerability alert of the last N minutes at or above a level, with the alert id and the FIM path, change, and `sha256_after`; at most the newest 1000), and `wazuh-vuln-events` (every vulnerability finding, compact) are local views over the same `wazuh-alerts` dump, not guest commands. `alerts` adds each ban's whole length (time left plus the alert's age, to the hour), the escalated bans (longer than CrowdSec's default 4 hours), and the top countries and networks. The Discord bridge's security checks use these through the entry point (`extensions/astro-discord/security-monitor.ts`).
48
48
  - `arcane change-origin <path> <sha256|-> <utc>` (`lib/change-origin.ts`) fetches origin, hashes the file in the newest 30 commits touching `<project>/<file>` up to 15 minutes after the change, and reads the last 16 MiB of the audit log for our `stack-update`, `manager-upgrade`, `manager-rollback`, or `host db-restore` on that stack (from a minute before its start to ten minutes after its end). It takes no checkout lock: like `update-report`'s holds read, it only fetches and reads objects, never the working tree. On 2026-10-21 the "Old md5sum" values of the live 100020 alerts matched the repository's previous Grimoire commits, which confirms that Arcane syncs these files verbatim.
49
- - TLS pinning for self-signed consoles is `lib/pinned.ts` (`pinnedRequest`); `network` and `proxmox` use it with a `*CertSha256` config value obtained once through the wrapper's `fingerprint` command.
49
+ - TLS pinning for self-signed consoles is `lib/pinned.ts` (`pinnedRequest`): it opens the TLS socket, checks the fingerprint on `secureConnect`, and only then sends the request on that socket (`createConnection`), so a wrong peer never receives the API key; `network` and `proxmox` use it with a `*CertSha256` config value obtained once through the wrapper's `fingerprint` command.
50
50
  - `proxmox` writes are typed commands, never a generic POST: power actions and snapshot changes go through `runTask`, which polls `/nodes/<node>/tasks/<upid>/status` until `stopped` and fails on any `exitstatus` but `OK`. `--confirm` is stripped by `needsConfirm` for every interrupting action. `SET_KEYS` mirrors the privileges of the `SpecialistGuest` role; the API refuses anything the role lacks, the wrapper refuses earlier.
51
51
  - `backup` and `inference` are pure forced-command wrappers with per-command timeouts (`timeoutMs` in the tables) because runs such as `vzdump-run` take many minutes; the gate's `timeoutMs` in `specialists.json` must exceed the longest of them.
52
52
  - `inference` reaches Nexus through one forced-command key. The Europa check is HTTP only until Windows OpenSSH forced commands are verified.
@@ -79,7 +79,7 @@ Wrappers ship as TypeScript and run under Node 24 type stripping: erasable synta
79
79
 
80
80
  ## Chat bridges
81
81
 
82
- `extensions/astro-discord/` runs specialists for Discord messages through `runAgent` and passes `ASTRO_APPROVAL_URL`/`ASTRO_APPROVAL_TOKEN` to the child. The gate consults `RISKY` in `extensions/specialist-gate/index.ts` and blocks on a ticket until an owner decides (`--help`/`-h` never counts; flags are ignored when matching, so they cannot hide a command; Arcane lists only destructive actions since 2026-09-26, because a routine upgrade the caller asked for made them approve the same thing twice); keep `RISKY` in step with the wrappers when a new interrupting or destructive command appears (every `--confirm` command is covered by construction).
82
+ `extensions/astro-discord/` runs specialists for Discord messages through `runAgent` and passes `ASTRO_APPROVAL_URL`/`ASTRO_APPROVAL_TOKEN` to the child. The gate consults `RISKY` in `extensions/specialist-gate/index.ts` and blocks on a ticket until an owner decides (no exemption for `--help` or `-h`, because a wrapper reads help only as the first argument and would run the command otherwise; flags are ignored when matching, so they cannot hide a command, which is why `dns` names refuse a leading hyphen; Arcane lists only destructive actions since 2026-09-26, because a routine upgrade the caller asked for made them approve the same thing twice); keep `RISKY` in step with the wrappers when a new interrupting or destructive command appears (every `--confirm` command is covered by construction).
83
83
 
84
84
  ## Next
85
85
 
@@ -72,7 +72,7 @@ Host: Cortex (macOS on Apple silicon; Homebrew git; the specialists' Node, trend
72
72
  { "zitadelDomain": "auth.37pla.net", "dmzHost": "10.0.20.10", "dmzUser": "dmz",
73
73
  "homelabRemote": "git@github.com:astronaute77/homelab.git", "homelabBranch": "main", "repoArea": "02-pulsar-proxmox/dmz", "pomeriumConfig": "02-pulsar-proxmox/dmz/config.yaml" }
74
74
  { "unifi37HostId": "<from: specialist-cli network -- unifi cloud /v1/hosts>", "unifi37LocalUrl": "https://10.0.10.1/proxy/network/integration", "unifi37CertSha256": "<from: specialist-cli network -- unifi 37 fingerprint>",
75
- "unifiMiraHostId": "<the same>", "unifiMiraLocalUrl": "https://192.168.1.1/proxy/network/integration", "unifiMiraCertSha256": "<the same>", "pulsarHost": "10.0.10.37", "pulsarUser": "root" }
75
+ "unifiMiraHostId": "<the same>", "unifiMiraLocalUrl": "https://10.1.60.1/proxy/network/integration", "unifiMiraCertSha256": "<the same>", "pulsarHost": "10.0.10.37", "pulsarUser": "root" }
76
76
  { "technitiumPrimaryUrl": "http://10.0.40.53:5380" }
77
77
  { "gcloud": "/usr/local/libexec/specialist-gcloud/current/bin/gcloud", "gcloudPython": "/usr/local/libexec/specialist-python/current/bin/python3",
78
78
  "project": "frontdoor-1337", "zone": "us-east1-c", "instance": "frontdoor-1337", "serviceAccount": "spc-edge@frontdoor-1337.iam.gserviceaccount.com",
@@ -145,7 +145,7 @@ The `astro-discord` extension gives Discord users access to the specialists from
145
145
  - Media: where the `media` specialist is present (`config channel <#channel> always media`), `/trending [type] [min_rating] [count]`, `/search <title> [type]`, and `/downloads <status|pause|resume|unpause>` run the wrapper without a model. `/downloads` answers "⏸️ Downloads are paused" with an Unpause button, or "▶️ Downloads are running"; no answer names the tool behind it. Lists arrive as two messages, Movies and Series, each title with a button beside it: **Add** adds it at once and turns into Added, In library, or Not found (Retry after a failure); a greyed-out In library or No IMDb ID button needs nothing. Notes go only to the user who clicked; when downloads are paused, the note has an **Unpause** button. When the media specialist adds a title by name and downloads stay paused, the bridge posts "⏸️ Downloads are paused" with Unpause under its answer; a click resumes the queue and the message names who resumed it. Owners and `access.media` users may use them; anyone else gets a refusal only they see, and in a channel without `media` the bot names the channels that have it. Plain messages in the channel still go to the agent, for requests by name ("add the new Dune"). A `media-weekly` report entry posts the weekly picks there every Friday at its time: three movies and three series from `recommend`, each with the library titles that led to it, an Add button, and a Not interested button; the owners are tagged when there is something new. A pick nobody acts on stays out for six months; Not interested keeps it out for good (`media-picks.json`). At startup the bridge sets the three commands as the application's global commands (servers only).
146
146
  - Arcane manager: when the morning Arcane Daily Report shows a newer manager release, the `arcane` section carries an **Upgrade Arcane to vX** button. Only an owner's click on the newest report runs `arcane manager-upgrade <version>` through the entry point (one at a time, counted as open work so no bridge restart interrupts it); the button turns into the outcome, a reply gives the result, and a successful upgrade installs the matching `arcane-cli` with `specialist-install`.
147
147
  - Access: `owners` may use every specialist and decide approvals; `access.<specialist>` lists extra users for that specialist; everyone else gets no reply. Owners change the configuration from the admin channel (`adminChannelId`) without a shell: `config show`, `config channel <#channel> <always|mention> <*|dns,edge>`, `config channel <#channel> remove`, `config access <specialist> add|remove <@user>`; the bot writes `~/.config/astro-discord/config.json` on Cortex, which is also editable by hand and re-read on every message. Deny the bot's role View Channel on channels it must never read; that is the boundary the map cannot provide.
148
- - Approvals: a risky call (anything with `--confirm`, plus writes such as record or zone deletes, Zitadel changes, every UniFi write, Pomerium deploys, service restarts, and on Arcane destructive actions: `down`, deletes, prunes, image, volume, or network removal, `system upgrade`, `gitops delete`, plus `manager-upgrade`, `manager-rollback`, `host db-restore`, and the Radarr host-config reads; `stack-update` asks only across a major version, through its `--confirm`; an owner's Update click on the report needs no approval; help lookups never ask) pauses the specialist and posts Approve/Deny buttons; only owners' clicks count; no decision within `approvalTimeoutMinutes` denies it. The specialist then reports the denial. Ambiguous tasks get a question back instead of an action.
148
+ - Approvals: a risky call (anything with `--confirm`, plus writes such as record or zone deletes, Zitadel changes, every UniFi write, Pomerium deploys, service restarts, and on Arcane destructive actions: `down`, deletes, prunes, image, volume, or network removal, `system upgrade`, `gitops delete`, plus `manager-upgrade`, `manager-rollback`, `host db-restore`, and the Radarr host-config reads; `stack-update` asks only across a major version, through its `--confirm`; an owner's Update click on the report needs no approval; `--help` as the first argument never asks, anywhere else it does not exempt the call) pauses the specialist and posts Approve/Deny buttons; only owners' clicks count; no decision within `approvalTimeoutMinutes` denies it. The specialist then reports the denial. Ambiguous tasks get a question back instead of an action.
149
149
  - Setup, as `cortex`: `d=$(mktemp -d) && cp ~/.pi/agent/npm/node_modules/@astrofoundry/pi-astro/extensions/astro-discord/*.ts "$d" && node --disable-warning=ExperimentalWarning "$d/setup.ts"` (Node does not strip types inside `node_modules`, so the files are copied first) prompts for the bot token and the ids, checks each against Discord, and writes `~/.config/astro-discord/{token,config.json,run.sh}` and the LaunchAgent; it prints the `launchctl bootstrap` line. After a pi-astro update restart the bridge with `launchctl kickstart -k gui/$(id -u)/com.astrofoundry.astro-discord`. Log: `~/Library/Logs/astro-discord.log`.
150
150
  - Discord side: application `Cortex` with a bot, Message Content Intent enabled, invited with scopes `bot` and `applications.commands` and permissions View Channel, Send Messages, Attach Files, Read Message History, Add Reactions.
151
151
 
@@ -2,6 +2,7 @@ import { randomBytes } from "node:crypto";
2
2
  import { join as joinPath } from "node:path";
3
3
  import { readConfig } from "../lib/config.ts";
4
4
  import { ServiceError, UsageError } from "../lib/errors.ts";
5
+ import { withLock } from "../lib/lock.ts";
5
6
  import { main } from "../lib/main.ts";
6
7
  import { printJson, printRaw } from "../lib/output.ts";
7
8
  import { redactSecrets } from "../lib/sanitize.ts";
@@ -43,19 +44,25 @@ const SINCE = /^[A-Za-z0-9 :+-]{1,40}$/;
43
44
  /** The installer downloads Technitium and the ASP.NET runtime; the gate allows the dns tool 11 minutes. */
44
45
  const UPGRADE_TIMEOUT_MS = 600_000;
45
46
 
47
+ /** One restart or upgrade at a time across the nodes, so the other two keep answering. */
48
+ const NODE_CHANGE_LOCK = "dns-node-change";
49
+
46
50
  /** Commands that need the cluster catalog, which the primary's cluster state names. */
47
- const CATALOG_COMMANDS = new Set(["zone-create", "zone-catalog"]);
51
+ const CATALOG_COMMANDS = new Set(["zone-create", "zone-catalog", "stale-zone-delete"]);
48
52
 
49
53
  const CLOUDFLARE_API = "https://api.cloudflare.com/client/v4";
50
54
  const TIMEOUT_MS = 30_000;
51
- /** Below the gate's 60 s limit for the dns tool; a join transfers the primary's whole configuration. */
52
- const JOIN_TIMEOUT_MS = 55_000;
55
+ /** Within the gate's 11-minute limit for the dns tool; a join transfers the primary's whole configuration, over the WAN for Mira. */
56
+ const JOIN_TIMEOUT_MS = 180_000;
53
57
  /** Technitium's documented default login on a fresh install; a join replaces it with the primary's users. */
54
58
  const DEFAULT_LOGIN = { user: "admin", pass: "admin" } as const;
55
59
  const NODE_URL = /^https?:\/\/[0-9.]+:[0-9]{1,5}\/?$/;
56
- const IPV4 = /^[0-9]{1,3}(\.[0-9]{1,3}){3}$/;
60
+ const OCTET = "(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])";
61
+ const IPV4 = new RegExp(`^${OCTET}(\\.${OCTET}){3}$`);
62
+ const PRIVATE_IPV4 = /^(10\.|192\.168\.|172\.(1[6-9]|2[0-9]|3[01])\.)/;
57
63
 
58
- const NAME = /^[A-Za-z0-9_.-]{1,253}$/;
64
+ /** A leading hyphen is refused: the gate drops arguments that start with one before it matches a command. */
65
+ const NAME = /^[A-Za-z0-9_][A-Za-z0-9_.-]{0,252}$/;
59
66
  const RECORD_TYPE = /^[A-Z0-9]{1,10}$/;
60
67
  const PARAM_KEY = /^[a-zA-Z]{1,40}$/;
61
68
  const STATS_TYPES = ["LastHour", "LastDay", "LastWeek", "LastMonth", "LastYear"];
@@ -77,11 +84,14 @@ async function nodeHost(args: string[]): Promise<number> {
77
84
  const { node, remote } = buildNodeRemote(args);
78
85
  const hosts = readConfig<NodeHostConfig>(SERVICE, NODE_HOST_SHAPE);
79
86
  const host = { technitium1: hosts.technitium1Host, technitium2: hosts.technitium2Host, technitium3: hosts.technitium3Host }[node];
80
- const result = await sshFixed(
81
- { host, user: hosts.nodeSshUser, keyFile: secretPath(SERVICE, "SSH_KEY_DNS_NODES"), knownHostsFile: joinPath(specialistsHome(), "config", "known_hosts") },
82
- remote,
83
- remote === "upgrade" ? UPGRADE_TIMEOUT_MS : 120_000,
84
- );
87
+ const call = () =>
88
+ sshFixed(
89
+ { host, user: hosts.nodeSshUser, keyFile: secretPath(SERVICE, "SSH_KEY_DNS_NODES"), knownHostsFile: joinPath(specialistsHome(), "config", "known_hosts") },
90
+ remote,
91
+ remote === "upgrade" ? UPGRADE_TIMEOUT_MS : 120_000,
92
+ );
93
+ const changes = remote === "restart" || remote === "upgrade";
94
+ const result = changes ? await withLock(NODE_CHANGE_LOCK, call, { timeoutMs: 1_000, staleMs: UPGRADE_TIMEOUT_MS + 60_000 }) : await call();
85
95
  if (result.stdout.length > 0) printRaw(result.stdout);
86
96
  if (result.code !== 0) throw new ServiceError(result.stderr.trim() || `${remote} exited ${result.code}`);
87
97
  return 0;
@@ -270,11 +280,13 @@ async function technitiumCall(base: string, path: string, params: Record<string,
270
280
  return parsed;
271
281
  }
272
282
 
283
+ /** The node URL must name the node's own private address, so the default login and the join reach that node only. */
273
284
  export function parseJoinArgs(args: string[]): { nodeUrl: string; nodeIp: string } {
274
- if (args.length !== 2 || !NODE_URL.test(args[0]) || !IPV4.test(args[1])) {
275
- throw new UsageError("technitium join <nodeUrl> <nodeIp>, e.g. http://10.1.40.53:5380 10.1.40.53");
285
+ const [nodeUrl, nodeIp] = args;
286
+ if (args.length !== 2 || !NODE_URL.test(nodeUrl) || !IPV4.test(nodeIp) || !PRIVATE_IPV4.test(nodeIp) || new URL(nodeUrl).hostname !== nodeIp) {
287
+ throw new UsageError("technitium join <nodeUrl> <nodeIp>: the URL names the node's private IPv4 address, e.g. http://10.1.40.53:5380 10.1.40.53");
276
288
  }
277
- return { nodeUrl: args[0], nodeIp: args[1] };
289
+ return { nodeUrl, nodeIp };
278
290
  }
279
291
 
280
292
  /**
@@ -355,6 +367,8 @@ async function technitium(config: DnsConfig, args: string[]): Promise<number> {
355
367
  if (node === undefined) throw new UsageError("stale-zone-delete needs node <fqdn>; delete a primary zone with zone-delete");
356
368
  const options = await technitiumCall(config.technitiumPrimaryUrl, "/api/zones/options/get", { zone: params.zone, node }, token, target);
357
369
  const zone = options.response as { type?: string; catalog?: string | null } | undefined;
370
+ // On a Secondary node the cluster catalog itself is a SecondaryCatalog zone outside any catalog; deleting it drops every member zone there.
371
+ if (params.zone.replace(/\.$/, "").toLowerCase() === catalog.toLowerCase()) throw new UsageError(`${catalog} is the cluster catalog; it is never stale`);
358
372
  if (!["Secondary", "SecondaryCatalog"].includes(zone?.type ?? "") || (zone?.catalog ?? null) !== null) {
359
373
  throw new UsageError(`${params.zone} on ${node} is ${zone?.type ?? "unknown"} in catalog ${zone?.catalog ?? "none"}; only a Secondary zone outside any catalog is stale`);
360
374
  }
@@ -4,6 +4,8 @@
4
4
  # command="/usr/local/sbin/spc-backup-arcane-entry",no-port-forwarding,no-agent-forwarding,no-pty,no-X11-forwarding ssh-ed25519 AAAA... spc-backup-arcane@cortex
5
5
  set -eu
6
6
  cmd="${SSH_ORIGINAL_COMMAND:-}"
7
+ # One line only: the checks below test each line, so a newline would carry a second line past them.
8
+ case "$cmd" in *[[:cntrl:]]*) echo "refused: control characters" >&2; exit 2 ;; esac
7
9
  name="${cmd%% *}"
8
10
  rest=""
9
11
  [ "$cmd" != "$name" ] && rest="${cmd#* }"
@@ -8,6 +8,8 @@ export HOME=/root
8
8
  export RESTIC_REPOSITORY=/mnt/pve/unas-backup/restic
9
9
  export RESTIC_PASSWORD_FILE=/root/.restic-pw
10
10
  cmd="${SSH_ORIGINAL_COMMAND:-}"
11
+ # One line only: the checks below test each line, so a newline would carry a second line past them.
12
+ case "$cmd" in *[[:cntrl:]]*) echo "refused: control characters" >&2; exit 2 ;; esac
11
13
  name="${cmd%% *}"
12
14
  rest=""
13
15
  [ "$cmd" != "$name" ] && rest="${cmd#* }"
@@ -0,0 +1,34 @@
1
+ #!/bin/sh
2
+ # Forced command for the dns specialist's node key (root): Technitium node operations.
3
+ # authorized_keys line, with the node as the only argument:
4
+ # Synapse: command="/usr/local/sbin/spc-dns-node-entry local",no-port-forwarding,no-agent-forwarding,no-pty,no-X11-forwarding ssh-ed25519 AAAA... spc-dns-nodes@cortex
5
+ # Pulsar: command="/usr/local/sbin/spc-dns-node-entry pct:107",... (technitium2)
6
+ # SPACE-X: command="/usr/local/sbin/spc-dns-node-entry pct:100",... (technitium3)
7
+ set -eu
8
+ export PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
9
+ target="${1:-}"
10
+ cmd="${SSH_ORIGINAL_COMMAND:-}"
11
+ # One line only: the checks below test each line, so a newline would carry a second line past them.
12
+ case "$cmd" in *[[:cntrl:]]*) echo "refused: control characters" >&2; exit 2 ;; esac
13
+ name="${cmd%% *}"
14
+ rest=""
15
+ [ "$cmd" != "$name" ] && rest="${cmd#* }"
16
+
17
+ # run takes an argument list; only fixed scripts go through sh -c, never a caller's value.
18
+ case "$target" in
19
+ local) run() { "$@"; } ;;
20
+ pct:1[0-9][0-9]) vmid="${target#pct:}"; run() { pct exec "$vmid" -- "$@"; } ;;
21
+ *) echo "bad target" >&2; exit 2 ;;
22
+ esac
23
+
24
+ case "$name" in
25
+ status) run sh -c 'systemctl is-active dns; systemctl show dns -p ActiveEnterTimestamp -p NRestarts; uptime; free -h; df -h /' ;;
26
+ journal)
27
+ printf '%s' "$rest" | grep -Eq '^[A-Za-z0-9 :+-]{1,40}$' || { echo "bad since" >&2; exit 2; }
28
+ run journalctl -u dns --since "$rest" --no-pager -n 200 ;;
29
+ updates) run sh -c 'apt list --upgradable 2>/dev/null' ;;
30
+ restart) run sh -c 'systemctl restart dns && sleep 3 && systemctl is-active dns' ;;
31
+ # The installer's exit code decides the result; its last 20 lines are shown either way.
32
+ upgrade) run sh -c 'f=$(mktemp) && curl -fsSL https://download.technitium.com/dns/install.sh -o "$f" || exit 1; rc=0; bash "$f" >"$f.log" 2>&1 || rc=$?; tail -20 "$f.log"; rm -f "$f" "$f.log"; [ "$rc" -eq 0 ] || { echo "installer exited $rc" >&2; exit "$rc"; }; sleep 5; systemctl is-active dns' ;;
33
+ *) echo "refused: $cmd" >&2; exit 2 ;;
34
+ esac
@@ -5,6 +5,8 @@
5
5
  # Privileged steps go through the exact sudoers entries in sudoers-spc-edge.
6
6
  set -eu
7
7
  cmd="${SSH_ORIGINAL_COMMAND:-}"
8
+ # One line only: the checks below test each line, so a newline would carry a second line past them.
9
+ case "$cmd" in *[[:cntrl:]]*) echo "refused: control characters" >&2; exit 2 ;; esac
8
10
  name="${cmd%% *}"
9
11
  rest=""
10
12
  [ "$cmd" != "$name" ] && rest="${cmd#* }"
@@ -4,6 +4,8 @@
4
4
  # command="/usr/local/sbin/spc-identity-dmz-entry",no-port-forwarding,no-agent-forwarding,no-pty,no-X11-forwarding ssh-ed25519 AAAA... spc-identity-dmz@cortex
5
5
  set -eu
6
6
  cmd="${SSH_ORIGINAL_COMMAND:-}"
7
+ # One line only: the checks below test each line, so a newline would carry a second line past them.
8
+ case "$cmd" in *[[:cntrl:]]*) echo "refused: control characters" >&2; exit 2 ;; esac
7
9
  name="${cmd%% *}"
8
10
  rest=""
9
11
  [ "$cmd" != "$name" ] && rest="${cmd#* }"
@@ -5,6 +5,8 @@
5
5
  set -eu
6
6
  export PATH=/usr/bin:/bin:/usr/sbin:/sbin
7
7
  cmd="${SSH_ORIGINAL_COMMAND:-}"
8
+ # One line only: the checks below test each line, so a newline would carry a second line past them.
9
+ case "$cmd" in *[[:cntrl:]]*) echo "refused: control characters" >&2; exit 2 ;; esac
8
10
  name="${cmd%% *}"
9
11
  rest=""
10
12
  [ "$cmd" != "$name" ] && rest="${cmd#* }"
@@ -4,6 +4,8 @@
4
4
  # command="/usr/local/sbin/spc-network-pulsar-entry",no-port-forwarding,no-agent-forwarding,no-pty,no-X11-forwarding ssh-ed25519 AAAA... spc-network-pulsar@cortex
5
5
  set -eu
6
6
  cmd="${SSH_ORIGINAL_COMMAND:-}"
7
+ # One line only: the checks below test each line, so a newline would carry a second line past them.
8
+ case "$cmd" in *[[:cntrl:]]*) echo "refused: control characters" >&2; exit 2 ;; esac
7
9
  name="${cmd%% *}"
8
10
  rest=""
9
11
  [ "$cmd" != "$name" ] && rest="${cmd#* }"
@@ -5,6 +5,8 @@
5
5
  set -eu
6
6
  export PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
7
7
  cmd="${SSH_ORIGINAL_COMMAND:-}"
8
+ # One line only: the checks below test each line, so a newline would carry a second line past them.
9
+ case "$cmd" in *[[:cntrl:]]*) echo "refused: control characters" >&2; exit 2 ;; esac
8
10
  name="${cmd%% *}"
9
11
  rest=""
10
12
  [ "$cmd" != "$name" ] && rest="${cmd#* }"
@@ -0,0 +1,46 @@
1
+ #!/bin/sh
2
+ # Forced command for the spc-proxmox key on SPACE-X (root): host facts and fixed reads inside guests.
3
+ # authorized_keys line:
4
+ # command="/usr/local/sbin/spc-proxmox-spacex-entry",no-port-forwarding,no-agent-forwarding,no-pty,no-X11-forwarding ssh-ed25519 AAAA... spc-proxmox-pulsar@cortex (the same key as on Pulsar)
5
+ set -eu
6
+ export PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
7
+ cmd="${SSH_ORIGINAL_COMMAND:-}"
8
+ # One line only: the checks below test each line, so a newline would carry a second line past them.
9
+ case "$cmd" in *[[:cntrl:]]*) echo "refused: control characters" >&2; exit 2 ;; esac
10
+ name="${cmd%% *}"
11
+ rest=""
12
+ [ "$cmd" != "$name" ] && rest="${cmd#* }"
13
+ since_ok() { printf '%s' "$1" | grep -Eq '^[A-Za-z0-9 :+-]{1,40}$'; }
14
+
15
+ guest_cmd() {
16
+ case "$1" in
17
+ status) echo 'systemctl --failed --no-pager; uptime' ;;
18
+ journal) echo 'journalctl -p warning --since "24 hours ago" --no-pager -n 100' ;;
19
+ df) echo 'df -h -x tmpfs -x devtmpfs' ;;
20
+ updates) echo 'apt list --upgradable 2>/dev/null' ;;
21
+ *) return 1 ;;
22
+ esac
23
+ }
24
+
25
+ case "$name" in
26
+ host-status)
27
+ pveversion
28
+ uptime
29
+ free -h
30
+ df -h / /var/lib/vz
31
+ sensors 2>/dev/null | grep -E 'Tctl|Composite|edge' || true ;;
32
+ host-journal) since_ok "$rest" || { echo "bad since" >&2; exit 2; }; journalctl -p warning --since "$rest" --no-pager -n 200 ;;
33
+ updates) apt list --upgradable 2>/dev/null ;;
34
+ guest-exec)
35
+ vmid="${rest%% *}"; action="${rest#* }"
36
+ case "$vmid" in 1[0-9][0-9]) ;; *) echo "bad vmid" >&2; exit 2 ;; esac
37
+ inner="$(guest_cmd "$action")" || { echo "bad action" >&2; exit 2; }
38
+ if pct status "$vmid" >/dev/null 2>&1; then
39
+ pct exec "$vmid" -- sh -c "$inner"
40
+ elif qm status "$vmid" >/dev/null 2>&1; then
41
+ qm guest exec "$vmid" --timeout 60 -- sh -c "$inner"
42
+ else
43
+ echo "no such guest" >&2; exit 2
44
+ fi ;;
45
+ *) echo "refused: $cmd" >&2; exit 2 ;;
46
+ esac
@@ -4,6 +4,8 @@
4
4
  # command="/usr/local/sbin/spc-security-obs-entry",no-port-forwarding,no-agent-forwarding,no-pty,no-X11-forwarding ssh-ed25519 AAAA... spc-security-obs@cortex
5
5
  set -eu
6
6
  cmd="${SSH_ORIGINAL_COMMAND:-}"
7
+ # One line only: the checks below test each line, so a newline would carry a second line past them.
8
+ case "$cmd" in *[[:cntrl:]]*) echo "refused: control characters" >&2; exit 2 ;; esac
7
9
  name="${cmd%% *}"
8
10
  rest=""
9
11
  [ "$cmd" != "$name" ] && rest="${cmd#* }"
@@ -0,0 +1,55 @@
1
+ import { execFileSync } from "node:child_process";
2
+ import { X509Certificate } from "node:crypto";
3
+ import { mkdtempSync, readFileSync, rmSync } from "node:fs";
4
+ import { createServer, type Server } from "node:https";
5
+ import { tmpdir } from "node:os";
6
+ import { join } from "node:path";
7
+ import { afterAll, beforeAll, describe, expect, it } from "vitest";
8
+ import { pinnedRequest } from "./pinned.ts";
9
+
10
+ describe("pinnedRequest", () => {
11
+ let dir: string;
12
+ let server: Server;
13
+ let url: URL;
14
+ let pin: string;
15
+ const seen: string[] = [];
16
+
17
+ beforeAll(async () => {
18
+ dir = mkdtempSync(join(tmpdir(), "astro-pin-"));
19
+ const key = join(dir, "key.pem");
20
+ const cert = join(dir, "cert.pem");
21
+ execFileSync("openssl", ["req", "-x509", "-newkey", "rsa:2048", "-nodes", "-subj", "/CN=console", "-days", "1", "-keyout", key, "-out", cert], { stdio: "ignore" });
22
+ pin = new X509Certificate(readFileSync(cert)).fingerprint256;
23
+ server = createServer({ key: readFileSync(key), cert: readFileSync(cert) }, (req, res) => {
24
+ let body = "";
25
+ req.on("data", (chunk: Buffer) => (body += chunk.toString()));
26
+ req.on("end", () => {
27
+ seen.push(`${req.method} ${req.headers["x-api-key"]} ${body}`);
28
+ res.end('{"ok":true}');
29
+ });
30
+ });
31
+ await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));
32
+ url = new URL(`https://127.0.0.1:${(server.address() as { port: number }).port}/x`);
33
+ });
34
+ afterAll(() => {
35
+ server.close();
36
+ rmSync(dir, { recursive: true, force: true });
37
+ });
38
+
39
+ const call = (expectedFingerprint: string | null) =>
40
+ pinnedRequest(url, { method: "POST", headers: { "X-API-KEY": "key" }, body: "{}", expectedFingerprint, timeoutMs: 5000 });
41
+
42
+ it("sends nothing to a certificate that does not match the pin", async () => {
43
+ await expect(call("00:11")).rejects.toThrow("does not match the pinned value");
44
+ expect(seen).toEqual([]);
45
+ });
46
+
47
+ it("sends the request after the pin matched, in any letter case", async () => {
48
+ await expect(call(pin.toLowerCase())).resolves.toEqual({ status: 200, body: '{"ok":true}', fingerprint: pin });
49
+ expect(seen).toEqual(["POST key {}"]);
50
+ });
51
+
52
+ it("reports a refused connection", async () => {
53
+ await expect(pinnedRequest(new URL("https://127.0.0.1:1/"), { method: "GET", headers: {}, expectedFingerprint: null, timeoutMs: 2000 })).rejects.toThrow("connection failed");
54
+ });
55
+ });
@@ -1,4 +1,6 @@
1
1
  import { request as httpsRequest } from "node:https";
2
+ import { isIP } from "node:net";
3
+ import { connect as tlsConnect, type TLSSocket } from "node:tls";
2
4
  import { ServiceError } from "./errors.ts";
3
5
 
4
6
  export interface PinnedResponse {
@@ -16,33 +18,48 @@ export interface PinnedOptions {
16
18
  timeoutMs: number;
17
19
  }
18
20
 
21
+ /** Opens the TLS connection and checks the pin before any byte of the request, so a wrong peer never sees the API key. */
22
+ function pinnedSocket(url: URL, options: PinnedOptions): Promise<{ socket: TLSSocket; fingerprint: string }> {
23
+ return new Promise((resolve, reject) => {
24
+ const socket = tlsConnect({
25
+ host: url.hostname,
26
+ port: Number(url.port || 443),
27
+ servername: isIP(url.hostname) === 0 ? url.hostname : undefined,
28
+ rejectUnauthorized: false,
29
+ timeout: options.timeoutMs,
30
+ });
31
+ socket.once("secureConnect", () => {
32
+ const fingerprint = socket.getPeerCertificate().fingerprint256 ?? "";
33
+ if (options.expectedFingerprint !== null && fingerprint.toUpperCase() !== options.expectedFingerprint.toUpperCase()) {
34
+ socket.destroy();
35
+ reject(new ServiceError(`${url.host}: certificate fingerprint ${fingerprint} does not match the pinned value`));
36
+ return;
37
+ }
38
+ socket.setTimeout(0);
39
+ resolve({ socket, fingerprint });
40
+ });
41
+ socket.once("timeout", () => socket.destroy(new ServiceError(`${url.host}: connection timed out`)));
42
+ socket.once("error", (err) => reject(err instanceof ServiceError ? err : new ServiceError(`${url.host}: connection failed: ${err.message}`)));
43
+ });
44
+ }
45
+
19
46
  /**
20
- * HTTPS request to a self-signed service, accepted only when the peer
21
- * certificate matches the pinned fingerprint. Used for consoles that
47
+ * HTTPS request to a self-signed service, sent only after the peer
48
+ * certificate matched the pinned fingerprint. Used for consoles that
22
49
  * cannot present a CA-signed certificate (UniFi, Proxmox VE).
23
50
  */
24
- export function pinnedRequest(url: URL, options: PinnedOptions): Promise<PinnedResponse> {
51
+ export async function pinnedRequest(url: URL, options: PinnedOptions): Promise<PinnedResponse> {
52
+ const { socket, fingerprint } = await pinnedSocket(url, options);
25
53
  return new Promise((resolve, reject) => {
26
- const req = httpsRequest(
27
- url,
28
- // agent:false forces a new connection per call: a pooled TLS socket returns an empty peer certificate on reuse, which would fail the pin.
29
- { method: options.method, rejectUnauthorized: false, headers: options.headers, timeout: options.timeoutMs, agent: false },
30
- (res) => {
31
- const socket = res.socket as { getPeerCertificate?: () => { fingerprint256?: string } };
32
- const fingerprint = socket.getPeerCertificate?.().fingerprint256 ?? "";
33
- if (options.expectedFingerprint !== null && fingerprint.toUpperCase() !== options.expectedFingerprint.toUpperCase()) {
34
- res.destroy();
35
- reject(new ServiceError(`${url.host}: certificate fingerprint ${fingerprint} does not match the pinned value`));
36
- return;
37
- }
38
- let body = "";
39
- res.setEncoding("utf-8");
40
- res.on("data", (chunk: string) => {
41
- body += chunk;
42
- });
43
- res.on("end", () => resolve({ status: res.statusCode ?? 0, body, fingerprint }));
44
- },
45
- );
54
+ // No agent: the request runs on the socket whose certificate was checked, and that socket closes with it.
55
+ const req = httpsRequest(url, { method: options.method, headers: options.headers, timeout: options.timeoutMs, createConnection: () => socket }, (res) => {
56
+ let body = "";
57
+ res.setEncoding("utf-8");
58
+ res.on("data", (chunk: string) => {
59
+ body += chunk;
60
+ });
61
+ res.on("end", () => resolve({ status: res.statusCode ?? 0, body, fingerprint }));
62
+ });
46
63
  req.on("timeout", () => req.destroy(new ServiceError(`${url.host}: request timed out`)));
47
64
  req.on("error", (err) => reject(err instanceof ServiceError ? err : new ServiceError(`${url.host}: request failed: ${err.message}`)));
48
65
  req.end(options.body);
@@ -5,6 +5,7 @@ import { main } from "../lib/main.ts";
5
5
  import { printJson, printRaw } from "../lib/output.ts";
6
6
  import { specialistsHome } from "../lib/paths.ts";
7
7
  import { pinnedRequest, type PinnedResponse } from "../lib/pinned.ts";
8
+ import { SECRET_KEY_PATTERN } from "../lib/sanitize.ts";
8
9
  import { readSecret, secretPath } from "../lib/secrets.ts";
9
10
  import { sshFixed } from "../lib/ssh.ts";
10
11
 
@@ -38,6 +39,8 @@ const CLOUD = "https://api.ui.com";
38
39
  const HOST_ID = /^[A-Za-z0-9]+(:[0-9]+)?$/;
39
40
  /** Cloud answers after which a read retries on the local console: timeout, rate limit, or a gateway or upstream failure. */
40
41
  const CLOUD_UNAVAILABLE = new Set([408, 429, 500, 502, 503, 504]);
42
+ /** Replaces secret values in every answer; a write body carrying it is refused, so a read-modify-write cannot store it. */
43
+ const REDACTED = "[redacted]";
41
44
 
42
45
  const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
43
46
 
@@ -82,10 +85,10 @@ ${Object.values(UNIFI_READS)
82
85
  set a device's management network and IP (keys mgmt_network_id, config_network)
83
86
  unifi <37|mira> client-fixed-ip <clientId> <json> [--local]
84
87
  set or clear a client's DHCP reservation (keys use_fixedip, fixed_ip, network_id)
85
- unifi <37|mira> app-policy-delete <policyId> [--local]
88
+ unifi <37|mira> app-policy-delete <policyId> <name> [--local]
86
89
  delete a firewall policy the official API lists without an id
87
90
  unifi <37|mira> nat [--local] the console's NAT rules (Policy Table; not in the official API)
88
- unifi <37|mira> nat-write POST <json> | PUT <ruleId> <json> | DELETE <ruleId> [--local]
91
+ unifi <37|mira> nat-write POST <json> | PUT <ruleId> <json> | DELETE <ruleId> <description> [--local]
89
92
  unifi <37|mira> fingerprint the local console's certificate fingerprint (for the pin)
90
93
  unifi cloud <path> any GET of the Site Manager API (/v1/ or /ea/, not /v1/connector/)
91
94
  pulsar <command> [args] fixed operations through a forced-command SSH key
@@ -94,7 +97,8 @@ ${Object.entries(PULSAR_COMMANDS)
94
97
  .join("\n")}
95
98
 
96
99
  Calls go through the cloud connector; a read the cloud cannot serve retries on
97
- the local console, a write never does. --local skips the cloud.`;
100
+ the local console, a write never does. --local skips the cloud. A delete names
101
+ its target and runs only when the live object carries that name.`;
98
102
 
99
103
  export interface Query {
100
104
  limit?: number;
@@ -125,12 +129,18 @@ export function parseQuery(args: string[]): { positional: string[]; query: Query
125
129
  return { positional, query };
126
130
  }
127
131
 
132
+ /** A percent sign, a backslash, an empty segment, or a dot segment would let the URL parser or the server leave the allowed prefix. */
133
+ export function leavesPrefix(path: string): boolean {
134
+ const pathname = path.split("?")[0];
135
+ return /[%\\]/.test(pathname) || pathname.includes("//") || pathname.split("/").some((segment) => segment === "." || segment === "..");
136
+ }
137
+
128
138
  export function unifiPath(args: string[]): string {
129
139
  const { positional, query } = parseQuery(args);
130
140
  const [read, ...params] = positional;
131
141
  let path: string;
132
142
  if (read === "get") {
133
- if (params.length !== 1 || !params[0].startsWith("/v1/") || params[0].includes("..") || /\s/.test(params[0])) {
143
+ if (params.length !== 1 || !params[0].startsWith("/v1/") || leavesPrefix(params[0]) || /\s/.test(params[0])) {
134
144
  throw new UsageError("unifi get <path>: path must start with /v1/");
135
145
  }
136
146
  path = params[0];
@@ -173,6 +183,8 @@ export interface UnifiWrite {
173
183
  method: WriteMethod;
174
184
  path: string;
175
185
  body?: string;
186
+ /** A delete names its target, so the approval shows what goes; the live object must carry that name. */
187
+ target?: { id: string; name: string };
176
188
  }
177
189
 
178
190
  function jsonBody(json: string): string {
@@ -183,14 +195,16 @@ function jsonBody(json: string): string {
183
195
  throw new UsageError("body must be JSON");
184
196
  }
185
197
  if (typeof parsed !== "object" || parsed === null) throw new UsageError("body must be a JSON object or array");
186
- return JSON.stringify(parsed);
198
+ const body = JSON.stringify(parsed);
199
+ if (body.includes(REDACTED)) throw new UsageError(`body carries ${REDACTED} from a read; send only the fields to change`);
200
+ return body;
187
201
  }
188
202
 
189
203
  /** `write <method> <path> [json]`: any write under one site of the Network API; the console validates the body. */
190
204
  export function unifiWrite(args: string[]): UnifiWrite {
191
205
  const [method, path, json, ...extra] = args;
192
206
  if (!(WRITE_METHODS as readonly string[]).includes(method)) throw new UsageError(`write <${WRITE_METHODS.join("|")}> <path> [json]`);
193
- if (path === undefined || !SITE_PATH.test(path) || path.split("/").includes("..")) throw new UsageError("write path: /v1/sites/<siteId>/... without query or traversal");
207
+ if (path === undefined || !SITE_PATH.test(path) || leavesPrefix(path)) throw new UsageError("write path: /v1/sites/<siteId>/... without query or traversal");
194
208
  if (extra.length > 0) throw new UsageError("write takes one JSON body; quote it as one argument");
195
209
  if (method === "DELETE") {
196
210
  if (json !== undefined) throw new UsageError("DELETE takes no body");
@@ -209,7 +223,7 @@ const APP_READ = /^\/(api\/s\/default|v2\/api\/site\/default)\/[A-Za-z0-9/_.-]+$
209
223
  /** `app-get <path>`: a read of the Network application's own API, to find the fields a wrapper command needs. */
210
224
  export function appGetPath(args: string[]): string {
211
225
  const [path, ...extra] = args;
212
- if (path === undefined || extra.length > 0 || !APP_READ.test(path) || path.split("/").includes("..")) {
226
+ if (path === undefined || extra.length > 0 || !APP_READ.test(path) || leavesPrefix(path)) {
213
227
  throw new UsageError("app-get <path>: one path under /api/s/default/ or /v2/api/site/default/");
214
228
  }
215
229
  return path;
@@ -239,29 +253,33 @@ export function clientFixedIpWrite(args: string[]): UnifiWrite {
239
253
  return { method: "PUT", path: `/api/s/default/rest/user/${id}`, body };
240
254
  }
241
255
 
242
- /** `app-policy-delete <policyId>`: a firewall policy that the official API returns with `id: null` (rules converted from the old firewall). */
256
+ export const POLICIES_PATH = "/v2/api/site/default/firewall-policies";
257
+
258
+ /** `app-policy-delete <policyId> <name>`: a firewall policy that the official API returns with `id: null` (rules converted from the old firewall). */
243
259
  export function appPolicyDelete(args: string[]): UnifiWrite {
244
- const [id, ...extra] = args;
245
- 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>");
246
- return { method: "DELETE", path: `/v2/api/site/default/firewall-policies/${id}` };
260
+ const [id, name, ...extra] = args;
261
+ if (id === undefined || !NAT_ID.test(id) || name === undefined || name.trim() === "" || extra.length > 0) {
262
+ throw new UsageError(`app-policy-delete <24-hex policyId> <name>, both from app-get ${POLICIES_PATH}`);
263
+ }
264
+ return { method: "DELETE", path: `${POLICIES_PATH}/${id}`, target: { id, name } };
247
265
  }
248
266
 
249
- /** `nat-write POST <json>`, `nat-write PUT <ruleId> <json>`, or `nat-write DELETE <ruleId>`. */
267
+ /** `nat-write POST <json>`, `nat-write PUT <ruleId> <json>`, or `nat-write DELETE <ruleId> <description>`. */
250
268
  export function natWrite(args: string[]): UnifiWrite {
251
269
  const [method, first, second, ...extra] = args;
252
270
  if (method === "POST" && first !== undefined && second === undefined) return { method, path: NAT_PATH, body: jsonBody(first) };
253
- if ((method === "PUT" || method === "DELETE") && first !== undefined && NAT_ID.test(first) && extra.length === 0) {
271
+ if ((method === "PUT" || method === "DELETE") && first !== undefined && NAT_ID.test(first) && second !== undefined && extra.length === 0) {
254
272
  const path = `${NAT_PATH}/${first}`;
255
- if (method === "DELETE" && second === undefined) return { method, path };
256
- if (method === "PUT" && second !== undefined) return { method, path, body: jsonBody(second) };
273
+ if (method === "DELETE" && second.trim() !== "") return { method, path, target: { id: first, name: second } };
274
+ if (method === "PUT") return { method, path, body: jsonBody(second) };
257
275
  }
258
- throw new UsageError("nat-write POST <json> | PUT <ruleId> <json> | DELETE <ruleId>");
276
+ throw new UsageError("nat-write POST <json> | PUT <ruleId> <json> | DELETE <ruleId> <description>");
259
277
  }
260
278
 
261
279
  /** `cloud <path>`: a Site Manager read; the connector is reached through the site commands. */
262
280
  export function cloudPath(args: string[]): string {
263
281
  const [path, ...extra] = args;
264
- if (path === undefined || extra.length > 0 || !/^\/(v1|ea)\/[A-Za-z0-9/_.:?=&%-]*$/.test(path) || path.includes("..") || path.startsWith("/v1/connector/")) {
282
+ if (path === undefined || extra.length > 0 || !/^\/(v1|ea)\/[A-Za-z0-9/_.:?=&%-]*$/.test(path) || leavesPrefix(path) || /^\/v1\/connector\//i.test(path)) {
265
283
  throw new UsageError("unifi cloud <path>: one path under /v1/ or /ea/, not /v1/connector/");
266
284
  }
267
285
  return path;
@@ -320,7 +338,13 @@ async function siteRequest(site: Site, config: SiteConfig, local: boolean, path:
320
338
  let reason: string;
321
339
  try {
322
340
  const answer = await cloudRequest(connector, method, body);
323
- if (method !== "GET" || !CLOUD_UNAVAILABLE.has(answer.status)) return answer;
341
+ if (method !== "GET") {
342
+ if (answer.status === 408 || answer.status >= 500) {
343
+ throw new ServiceError(`cloud answered ${answer.status}: ${answer.body.slice(0, 500)}; the write may have been applied: read the object back before retrying with --local`);
344
+ }
345
+ return answer;
346
+ }
347
+ if (!CLOUD_UNAVAILABLE.has(answer.status)) return answer;
324
348
  reason = `cloud answered ${answer.status}`;
325
349
  } catch (err) {
326
350
  if (method !== "GET") throw new ServiceError(`${err instanceof Error ? err.message : String(err)}; the write may have been applied: read the object back before retrying with --local`);
@@ -330,15 +354,53 @@ async function siteRequest(site: Site, config: SiteConfig, local: boolean, path:
330
354
  return localRequest(site, config, path, method, body, api);
331
355
  }
332
356
 
357
+ /**
358
+ * UniFi names secret fields with an `x_` prefix (`x_passphrase`, `x_ssh_password`, `x_private_key`, `x_api_token`);
359
+ * they and any other secret-named string never leave the wrapper.
360
+ */
361
+ export function redactUnifi(value: unknown): unknown {
362
+ if (Array.isArray(value)) return value.map(redactUnifi);
363
+ if (typeof value === "object" && value !== null) {
364
+ const out: Record<string, unknown> = {};
365
+ for (const [k, v] of Object.entries(value as Record<string, unknown>)) {
366
+ out[k] = k.startsWith("x_") || (SECRET_KEY_PATTERN.test(k) && typeof v === "string") ? REDACTED : redactUnifi(v);
367
+ }
368
+ return out;
369
+ }
370
+ return value;
371
+ }
372
+
373
+ /** Reads the list a delete's target lives in and refuses unless the target is there under the name the caller gave. */
374
+ async function requireLiveName(site: Site, config: SiteConfig, local: boolean, listPath: string, field: "name" | "description", target: { id: string; name: string }): Promise<void> {
375
+ const answer = await siteRequest(site, config, local, listPath, "GET", undefined, "app");
376
+ if (answer.status < 200 || answer.status >= 300) throw new ServiceError(`reading ${listPath} answered ${answer.status}; nothing deleted`);
377
+ let list: unknown;
378
+ try {
379
+ list = JSON.parse(answer.body);
380
+ } catch {
381
+ throw new ServiceError(`${listPath} did not answer JSON; nothing deleted`);
382
+ }
383
+ const live = Array.isArray(list) ? (list as Record<string, unknown>[]).find((o) => o._id === target.id) : undefined;
384
+ if (live === undefined) throw new ServiceError(`${target.id} is not in ${listPath} on ${site}; nothing deleted`);
385
+ if (live[field] !== target.name) throw new ServiceError(`${target.id} has ${field} ${JSON.stringify(live[field])}, not ${JSON.stringify(target.name)}; nothing deleted`);
386
+ }
387
+
388
+ /** The application's classic `/api/s/` paths can report a failure as `meta.rc: "error"`. */
389
+ function failedMeta(parsed: unknown): boolean {
390
+ return (parsed as { meta?: { rc?: unknown } } | null)?.meta?.rc === "error";
391
+ }
392
+
333
393
  function printAnswer(answer: Answer, source: string): number {
334
394
  let parsed: unknown = answer.body;
335
395
  try {
336
- parsed = JSON.parse(answer.body);
396
+ parsed = redactUnifi(JSON.parse(answer.body));
337
397
  } catch {
338
398
  /* non-JSON body stays text */
339
399
  }
340
400
  // The gate shows only stderr for a failed call, so the error carries UniFi's own message.
341
- if (answer.status < 200 || answer.status >= 300) throw new ServiceError(`${source} answered ${answer.status}: ${answer.body.slice(0, 2000)}`);
401
+ if (answer.status < 200 || answer.status >= 300 || failedMeta(parsed)) {
402
+ throw new ServiceError(`${source} answered ${answer.status}: ${(typeof parsed === "string" ? parsed : JSON.stringify(parsed)).slice(0, 2000)}`);
403
+ }
342
404
  printJson(parsed);
343
405
  return 0;
344
406
  }
@@ -359,16 +421,23 @@ async function unifi(args: string[]): Promise<number> {
359
421
  }
360
422
  if (rest[0] === "app-policy-delete") {
361
423
  const call = appPolicyDelete(rest.slice(1));
362
- return printAnswer(await siteRequest(site, readSite(site), local, call.path, call.method, undefined, "app"), `UniFi ${site} policy`);
424
+ const config = readSite(site);
425
+ if (call.target) await requireLiveName(site, config, local, POLICIES_PATH, "name", call.target);
426
+ return printAnswer(await siteRequest(site, config, local, call.path, call.method, undefined, "app"), `UniFi ${site} policy`);
363
427
  }
364
428
  if (rest[0] === "device-network") {
365
429
  const call = deviceNetworkWrite(rest.slice(1));
366
430
  return printAnswer(await siteRequest(site, readSite(site), local, call.path, call.method, call.body, "app"), `UniFi ${site} device`);
367
431
  }
368
- if (rest[0] === "nat" || rest[0] === "nat-write") {
369
- if (rest[0] === "nat" && rest.length > 1) throw new UsageError("unifi <37|mira> nat takes no arguments");
370
- const call = rest[0] === "nat" ? { method: "GET", path: NAT_PATH, body: undefined } : natWrite(rest.slice(1));
371
- return printAnswer(await siteRequest(site, readSite(site), local, call.path, call.method, call.body, "app"), `UniFi ${site} NAT`);
432
+ if (rest[0] === "nat") {
433
+ if (rest.length > 1) throw new UsageError("unifi <37|mira> nat takes no arguments");
434
+ return printAnswer(await siteRequest(site, readSite(site), local, NAT_PATH, "GET", undefined, "app"), `UniFi ${site} NAT`);
435
+ }
436
+ if (rest[0] === "nat-write") {
437
+ const call = natWrite(rest.slice(1));
438
+ const config = readSite(site);
439
+ if (call.target) await requireLiveName(site, config, local, NAT_PATH, "description", call.target);
440
+ return printAnswer(await siteRequest(site, config, local, call.path, call.method, call.body, "app"), `UniFi ${site} NAT`);
372
441
  }
373
442
  const write = rest[0] === "write" ? unifiWrite(rest.slice(1)) : null;
374
443
  const path = write ? write.path : unifiPath(rest);
@@ -358,6 +358,10 @@ export async function command(args: string[]): Promise<number> {
358
358
  return 0;
359
359
  }
360
360
  const { host: hostName, rest } = splitHost(args);
361
+ if (rest.length === 0 || rest[0] === "--help" || rest[0] === "help") {
362
+ printRaw(HELP);
363
+ return 0;
364
+ }
361
365
  const config = readTarget(hostName);
362
366
  if (rest[0] === "fingerprint") {
363
367
  const probe = await pinnedRequest(new URL("/", config.apiUrl), { method: "GET", headers: {}, expectedFingerprint: null, timeoutMs: TIMEOUT_MS });
@@ -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, unifiPath, unifiWrite, command as networkCommand } from "./network/run.ts";
14
+ import { appGetPath, appPolicyDelete, clientFixedIpWrite, 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
 
@@ -112,14 +112,20 @@ describe("network wrapper", () => {
112
112
  expect(unifiPath(["get", "/v1/countries"])).toBe("/v1/countries");
113
113
  expect(() => unifiPath(["devices", "not-a-uuid"])).toThrow(/UUID/);
114
114
  expect(() => unifiPath(["get", "/proxy/network/api/s/default"])).toThrow(/\/v1\//);
115
+ // An encoded dot segment would leave the integration API for the application's unfiltered paths.
116
+ expect(() => unifiPath(["get", "/v1/%2e%2e/%2E%2E/api/s/default/rest/wlanconf"])).toThrow(UsageError);
117
+ expect(() => unifiPath(["get", "/v1/.%2e/x"])).toThrow(UsageError);
118
+ expect(() => unifiPath(["get", "/v1/sites\\..\\x"])).toThrow(UsageError);
115
119
  expect(() => unifiPath(["reboot"])).toThrow(/unknown unifi read/);
116
120
  });
117
121
 
118
122
  it("limits application reads and device network writes", () => {
119
123
  const id = "0123456789abcdef01234567";
120
124
  expect(appGetPath(["/api/s/default/stat/device"])).toBe("/api/s/default/stat/device");
121
- expect(appPolicyDelete(["0123456789abcdef01234567"])).toEqual({ method: "DELETE", path: "/v2/api/site/default/firewall-policies/0123456789abcdef01234567" });
122
- 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);
123
129
  const fixed = JSON.stringify({ use_fixedip: true, fixed_ip: "10.1.50.50", network_id: "0123456789abcdef01234567" });
124
130
  expect(clientFixedIpWrite(["0123456789abcdef01234567", fixed])).toEqual({ method: "PUT", path: "/api/s/default/rest/user/0123456789abcdef01234567", body: fixed });
125
131
  expect(() => clientFixedIpWrite(["0123456789abcdef01234567", JSON.stringify({ name: "x" })])).toThrow(/body keys/);
@@ -138,8 +144,10 @@ describe("network wrapper", () => {
138
144
  const id = "0123456789abcdef01234567";
139
145
  expect(natWrite(["POST", '{"type":"DNAT"}'])).toEqual({ method: "POST", path: NAT_PATH, body: '{"type":"DNAT"}' });
140
146
  expect(natWrite(["PUT", id, "{}"])).toEqual({ method: "PUT", path: `${NAT_PATH}/${id}`, body: "{}" });
141
- expect(natWrite(["DELETE", id])).toEqual({ method: "DELETE", path: `${NAT_PATH}/${id}` });
142
- 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);
143
151
  expect(() => natWrite(["PUT", "not-an-id", "{}"])).toThrow(UsageError);
144
152
  expect(() => natWrite(["POST"])).toThrow(UsageError);
145
153
  expect(() => natWrite(["POST", "{"])).toThrow(/JSON/);
@@ -160,10 +168,20 @@ describe("network wrapper", () => {
160
168
  expect(() => unifiWrite(["POST", `/v1/sites/${site}/../x`, body])).toThrow(/traversal/);
161
169
  expect(() => unifiWrite(["POST", `/v1/sites/${site}/networks?x=1`, body])).toThrow(UsageError);
162
170
  expect(() => unifiWrite(["POST", `/v1/sites/${site}/networks`, body, "extra"])).toThrow(/one JSON body/);
171
+ expect(() => unifiWrite(["PUT", `/v1/sites/${site}/wifi/broadcasts/${site}`, '{"passphrase":"[redacted]"}'])).toThrow(/redacted/);
163
172
  expect(unifiPath(["firewall-zones", site])).toBe(`/v1/sites/${site}/firewall/zones`);
164
173
  expect(unifiPath(["firewall-policy", site, site])).toBe(`/v1/sites/${site}/firewall/policies/${site}`);
165
174
  });
166
175
 
176
+ it("redacts UniFi secret fields in every answer", () => {
177
+ const wlan = { data: [{ name: "Astro", x_passphrase: "p", x_iapp_key: "k", nested: { x_ssh_password: "s", utm_token: "t", public_key: "pub" }, group_rekey: 3600 }], meta: { rc: "ok" } };
178
+ expect(redactUnifi(wlan)).toEqual({
179
+ data: [{ name: "Astro", x_passphrase: "[redacted]", x_iapp_key: "[redacted]", nested: { x_ssh_password: "[redacted]", utm_token: "[redacted]", public_key: "pub" }, group_rekey: 3600 }],
180
+ meta: { rc: "ok" },
181
+ });
182
+ expect(redactUnifi({ x_ssh_keys: [{ key: "k" }] })).toEqual({ x_ssh_keys: "[redacted]" });
183
+ });
184
+
167
185
  it("picks the console and the cloud reads", () => {
168
186
  expect(parseSiteArgs(["37", "sites"])).toEqual({ site: "37", local: false, rest: ["sites"] });
169
187
  expect(parseSiteArgs(["mira", "devices", site, "--local"])).toEqual({ site: "mira", local: true, rest: ["devices", site] });
@@ -173,6 +191,9 @@ describe("network wrapper", () => {
173
191
  expect(cloudPath(["/ea/sites"])).toBe("/ea/sites");
174
192
  expect(() => cloudPath(["/v1/connector/consoles/x/network/integration/v1/sites"])).toThrow(/connector/);
175
193
  expect(() => cloudPath(["/v1/../x"])).toThrow(UsageError);
194
+ expect(() => cloudPath(["/v1/%2e%2e/connector/consoles/x"])).toThrow(UsageError);
195
+ expect(() => cloudPath(["/v1//connector/consoles/x"])).toThrow(UsageError);
196
+ expect(() => cloudPath(["/v1/Connector/consoles/x"])).toThrow(UsageError);
176
197
  expect(() => cloudPath(["/proxy/network"])).toThrow(UsageError);
177
198
  });
178
199
 
@@ -259,6 +280,17 @@ describe("dns wrapper", () => {
259
280
  expect(() => parseJoinArgs(["http://evil.example:5380", "10.1.40.53"])).toThrow(UsageError);
260
281
  expect(() => parseJoinArgs(["http://10.1.40.53:5380", "10.1.40.53,10.0.40.1"])).toThrow(UsageError);
261
282
  expect(() => parseJoinArgs(["http://10.1.40.53:5380"])).toThrow(UsageError);
283
+ // The URL must name the node's own canonical private address: no octal form, no other host, no public address.
284
+ expect(() => parseJoinArgs(["http://010.1.40.53:5380", "010.1.40.53"])).toThrow(UsageError);
285
+ expect(() => parseJoinArgs(["http://10.0.40.53:5380", "10.1.40.53"])).toThrow(UsageError);
286
+ expect(() => parseJoinArgs(["http://8.8.8.8:5380", "8.8.8.8"])).toThrow(UsageError);
287
+ expect(() => parseJoinArgs(["http://10.1.40.256:5380", "10.1.40.256"])).toThrow(UsageError);
288
+ });
289
+
290
+ it("refuses names with a leading hyphen, which the gate would not see", () => {
291
+ expect(() => technitiumTarget(["node", "-x.dns.home.arpa", "stale-zone-delete", "a.b"])).toThrow(UsageError);
292
+ expect(() => technitiumRequest("c", ["zone-delete", "-h"])).toThrow(/DNS name/);
293
+ expect(technitiumRequest("c", ["zone-delete", "_acme.example.com"]).params.zone).toBe("_acme.example.com");
262
294
  });
263
295
 
264
296
  it("rejects malformed names, types, and parameters", () => {
@@ -627,7 +659,9 @@ describe("proxmox wrapper", () => {
627
659
  it("prints help without touching config", async () => {
628
660
  const write = vi.spyOn(process.stdout, "write").mockImplementation(() => true);
629
661
  expect(await proxmoxCommand([])).toBe(0);
662
+ expect(await proxmoxCommand(["space-x", "--help"])).toBe(0);
630
663
  expect(String(write.mock.calls[0][0])).toContain("snapshot-rollback");
664
+ expect(String(write.mock.calls[1][0])).toContain("snapshot-rollback");
631
665
  write.mockRestore();
632
666
  });
633
667
  });
@@ -804,3 +838,78 @@ describe("media wrapper", () => {
804
838
  });
805
839
  });
806
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("refuses a NAT delete of a rule that is not there", async () => {
911
+ const calls = stubConsole([{ _id: "fedcba9876543210fedcba98", description: "IoT DNS redirect" }]);
912
+ await expect(networkCommand(["unifi", "mira", "nat-write", "DELETE", id, "IoT DNS redirect"])).rejects.toThrow(/is not in .*nothing deleted/);
913
+ expect(calls.some((c) => c.startsWith("DELETE"))).toBe(false);
914
+ });
915
+ });