Compare commits
6
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
8148678af8 | ||
|
|
f14c763463 | ||
|
|
ab44ff02e1 | ||
|
|
c4c44efb1b | ||
|
|
5cc6258326 | ||
|
|
21f5301268 |
@@ -0,0 +1,22 @@
|
||||
# anthropic-consumer's runtime: the tool runtime, carrying this module's compiled code.
|
||||
#
|
||||
# **Built from this module's own directory and nothing else.** The sdk and the tool runtime are in
|
||||
# the base images, published like any other artifact — which is what makes this buildable by the
|
||||
# mesh from a repository and a path (novox/hq ADR 0069) rather than only on a workstation that
|
||||
# happens to have the siblings.
|
||||
#
|
||||
# Two bases, named rather than pinned (novox/hq issue 044): the image this is COMPILED in and the
|
||||
# image it RUNS in — the second must not carry a compiler. Declared in module.json's `build.on`.
|
||||
ARG BUILD_BASE
|
||||
ARG RUNTIME_BASE
|
||||
|
||||
FROM ${BUILD_BASE} AS build
|
||||
WORKDIR /app/modules/anthropic-consumer
|
||||
COPY . .
|
||||
RUN node /app/node_modules/typescript/bin/tsc apply/index.ts usage/index.ts \
|
||||
--module NodeNext --moduleResolution NodeNext --target ES2022 --outDir dist
|
||||
|
||||
FROM ${RUNTIME_BASE}
|
||||
COPY --from=build /app/modules/anthropic-consumer/dist /app/modules/anthropic-consumer/dist
|
||||
# No serve-time entrypoints: every container of this module names its command (`run` on a
|
||||
# schedule), so nothing here serves — deliberately no MESH_TOOL_MODULES.
|
||||
@@ -9,20 +9,29 @@
|
||||
"model-access"
|
||||
],
|
||||
"binds": {
|
||||
"model-access": "${dir:state}/model.json"
|
||||
"model-access": "/var/lib/anthropic-consumer/model.json"
|
||||
},
|
||||
"secrets": {
|
||||
"model-access": "${dir:state}/access-token"
|
||||
"model-access": "/var/lib/anthropic-consumer/access-token"
|
||||
},
|
||||
"own-secrets": {
|
||||
"broker": "/var/lib/mesh/anthropic-consumer/broker"
|
||||
},
|
||||
"emits": [
|
||||
"usage.session"
|
||||
],
|
||||
"resources": [
|
||||
{
|
||||
"id": "mesh-state",
|
||||
"type": "directory",
|
||||
"path": "/var/lib/mesh/anthropic-consumer",
|
||||
"mode": "0700"
|
||||
},
|
||||
{
|
||||
"id": "state",
|
||||
"type": "directory",
|
||||
"mode": "0700",
|
||||
"place": "."
|
||||
"path": "/var/lib/anthropic-consumer",
|
||||
"mode": "0700"
|
||||
},
|
||||
{
|
||||
"id": "claude-home",
|
||||
@@ -33,43 +42,71 @@
|
||||
{
|
||||
"id": "out",
|
||||
"type": "directory",
|
||||
"path": "/var/lib/anthropic-consumer/out",
|
||||
"mode": "0700"
|
||||
},
|
||||
{
|
||||
"id": "apply",
|
||||
"type": "process",
|
||||
"name": "anthropic-consumer-apply",
|
||||
"artifact": "code",
|
||||
"run": [
|
||||
"node",
|
||||
"apply/index.js"
|
||||
],
|
||||
"type": "container",
|
||||
"name": "mesh-anthropic-consumer-apply",
|
||||
"network": "host",
|
||||
"schedule": "*/5 * * * *",
|
||||
"args": [
|
||||
"run",
|
||||
"/app/modules/anthropic-consumer/dist/apply/index.js"
|
||||
],
|
||||
"volumes": [
|
||||
"/var/lib/anthropic-consumer:/run/state"
|
||||
],
|
||||
"env": {
|
||||
"MESH_MODEL_ACCESS_SECRET_FILE": "${dir:state}/access-token",
|
||||
"MESH_MODEL_ACCESS_BIND_FILE": "${dir:state}/model.json",
|
||||
"MESH_CLAUDE_CREDENTIALS_FILE": "${dir:state}/claude/.credentials.json",
|
||||
"MESH_CLAUDE_IDENTITY_FILE": "${dir:state}/claude/.claude.json"
|
||||
}
|
||||
"MESH_MODEL_ACCESS_SECRET_FILE": "/run/state/access-token",
|
||||
"MESH_MODEL_ACCESS_BIND_FILE": "/run/state/model.json",
|
||||
"MESH_CLAUDE_CREDENTIALS_FILE": "/run/state/claude/.credentials.json",
|
||||
"MESH_CLAUDE_IDENTITY_FILE": "/run/state/claude/.claude.json"
|
||||
},
|
||||
"artifact": "runtime"
|
||||
},
|
||||
{
|
||||
"id": "usage",
|
||||
"type": "container",
|
||||
"name": "mesh-anthropic-consumer-usage",
|
||||
"network": "host",
|
||||
"schedule": "*/5 * * * *",
|
||||
"args": [
|
||||
"run",
|
||||
"/app/modules/anthropic-consumer/dist/usage/index.js"
|
||||
],
|
||||
"volumes": [
|
||||
"/var/lib/mesh/anthropic-consumer/broker:/run/secrets/broker:ro",
|
||||
"/var/lib/anthropic-consumer:/run/state"
|
||||
],
|
||||
"env": {
|
||||
"MESH_BROKER_FILE": "/run/secrets/broker",
|
||||
"MESH_CLAUDE_PROJECTS_DIR": "/run/state/claude/projects",
|
||||
"MESH_ANTHROPIC_USAGE_OUT": "/run/state/out/session-usage.json",
|
||||
"MESH_TOOLS_MAIN": "/app/dist/main.js"
|
||||
},
|
||||
"artifact": "runtime"
|
||||
}
|
||||
],
|
||||
"build": {
|
||||
"on": [
|
||||
{
|
||||
"arg": "BUILD_BASE",
|
||||
"module": "mesh-tools",
|
||||
"artifact": "build"
|
||||
},
|
||||
{
|
||||
"arg": "RUNTIME_BASE",
|
||||
"module": "mesh-tools",
|
||||
"artifact": "runtime"
|
||||
}
|
||||
],
|
||||
"artifacts": [
|
||||
{
|
||||
"name": "code",
|
||||
"kind": "bundle",
|
||||
"language": "typescript",
|
||||
"entrypoints": [
|
||||
"apply/index.js",
|
||||
"usage/index.js"
|
||||
],
|
||||
"loads": [
|
||||
"usage/index.js"
|
||||
],
|
||||
"env": {
|
||||
"MESH_CLAUDE_PROJECTS_DIR": "${dir:state}/claude/projects",
|
||||
"MESH_ANTHROPIC_USAGE_OUT": "${dir:state}/out/session-usage.json"
|
||||
}
|
||||
"name": "runtime",
|
||||
"kind": "image",
|
||||
"from": "Dockerfile"
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
@@ -3,15 +3,12 @@
|
||||
// per session. The consumer IS the (node,module) session's fixed binding, so no per-message account
|
||||
// attribution is done — just the totals (port map "don't-map" #3).
|
||||
//
|
||||
// Runs in the node's runtime (novox/hq ADR 0198), every five minutes, so events are emitted through
|
||||
// the runtime as this module; the totals are also written to a file so the reading is observable
|
||||
// without one.
|
||||
// Runs as `mesh-tools run` (no broker), so events are emitted best-effort via the sibling mesh-tools
|
||||
// `emit` primitive; the totals are also written to a file so the reading is observable without one.
|
||||
|
||||
import { readdirSync, statSync, readFileSync, writeFileSync, renameSync, mkdirSync } from "node:fs";
|
||||
import { join, dirname } from "node:path";
|
||||
|
||||
import { emit } from "@novox/mesh-sdk/events";
|
||||
|
||||
import { readSessionFile, type SessionUsage } from "../transcript.js";
|
||||
|
||||
/** The vendor-neutral usage row ADR 0054 fixes — the shape the model-usage store upserts. Kept local
|
||||
@@ -119,20 +116,22 @@ function atomicWrite(path: string, content: string): void {
|
||||
renameSync(tmp, path);
|
||||
}
|
||||
|
||||
/** Emit best-effort through the runtime: a reading that could not be announced is still in the file. */
|
||||
/** Emit best-effort via the sibling mesh-tools `emit`, which wires a broker a run step has none. */
|
||||
async function emitUsage(body: Record<string, unknown>): Promise<void> {
|
||||
try {
|
||||
await emit("usage.session", body);
|
||||
} catch (err) {
|
||||
console.error(`[anthropic-consumer] could not emit usage: ${err}`);
|
||||
}
|
||||
const main = process.env.MESH_TOOLS_MAIN ?? "/app/dist/main.js";
|
||||
const { spawn } = await import("node:child_process");
|
||||
await new Promise<void>((resolve) => {
|
||||
const child = spawn(
|
||||
process.execPath,
|
||||
[main, "emit", "usage.session", JSON.stringify(body)],
|
||||
{ stdio: "inherit" },
|
||||
);
|
||||
child.on("exit", () => resolve());
|
||||
child.on("error", (err) => {
|
||||
console.error(`[anthropic-consumer] could not emit usage: ${err}`);
|
||||
resolve();
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
// The cadence the scheduled container had: once at start, then every five minutes. Not awaited, so the
|
||||
// runtime's handshake is answered while a long first reading is still under way.
|
||||
const EVERY_MS = 5 * 60 * 1000;
|
||||
const tick = (): void => {
|
||||
void main().catch((err) => console.error(`[anthropic-consumer] usage reading failed: ${err}`));
|
||||
};
|
||||
tick();
|
||||
setInterval(tick, EVERY_MS);
|
||||
await main();
|
||||
|
||||
@@ -9,13 +9,13 @@
|
||||
"model-access"
|
||||
],
|
||||
"binds": {
|
||||
"model-access": "${dir:mesh-state}/model.json"
|
||||
"model-access": "/var/lib/mesh/anthropic-manager/model.json"
|
||||
},
|
||||
"secrets": {
|
||||
"model-access": "${dir:mesh-state}/refresh-token"
|
||||
"model-access": "/var/lib/mesh/anthropic-manager/refresh-token"
|
||||
},
|
||||
"own-secrets": {
|
||||
"broker": "${dir:mesh-state}/broker"
|
||||
"broker": "/var/lib/mesh/anthropic-manager/broker"
|
||||
},
|
||||
"emits": [
|
||||
"usage.read"
|
||||
@@ -24,13 +24,13 @@
|
||||
{
|
||||
"id": "mesh-state",
|
||||
"type": "directory",
|
||||
"mode": "0700",
|
||||
"place": "mesh"
|
||||
"path": "/var/lib/mesh/anthropic-manager",
|
||||
"mode": "0700"
|
||||
},
|
||||
{
|
||||
"id": "out",
|
||||
"type": "directory",
|
||||
"path": "${dir:mesh-state}/out",
|
||||
"path": "/var/lib/mesh/anthropic-manager/out",
|
||||
"mode": "0700"
|
||||
},
|
||||
{
|
||||
@@ -45,8 +45,8 @@
|
||||
"/app/modules/anthropic-manager/dist/refresh/index.js"
|
||||
],
|
||||
"volumes": [
|
||||
"${dir:mesh-state}/broker:/run/secrets/broker:ro",
|
||||
"${dir:mesh-state}:/run/state"
|
||||
"/var/lib/mesh/anthropic-manager/broker:/run/secrets/broker:ro",
|
||||
"/var/lib/mesh/anthropic-manager:/run/state"
|
||||
],
|
||||
"env": {
|
||||
"MESH_BROKER_FILE": "/run/secrets/broker",
|
||||
|
||||
@@ -1,257 +0,0 @@
|
||||
# asus-zephyrus-g14
|
||||
|
||||
The hardware module for the **ASUS ROG Zephyrus G14** laptop: its vendor daemon and platform
|
||||
profiles, the hybrid GPU's mode and driver options, suspend, the lid and power key, low battery,
|
||||
the backlights, the vendor keys and the touchpad (novox/hq research 027/03 *Power management on
|
||||
the laptop*, research 026/05, to-be 42 phase 3).
|
||||
|
||||
## Why this name
|
||||
|
||||
A module is named after the hardware model, never the node (novox/hq ADR 0112; research 026/03:
|
||||
no flavors, no machine names). `asus-zephyrus-g14` is the model family exactly as the firmware
|
||||
reports it (`/sys/class/dmi/id/product_family` = `ROG Zephyrus G14`). The module's code checks that
|
||||
value and its switcher does nothing on any other model, and `zephyrus_check` reports it.
|
||||
|
||||
A wider name such as `asus-rog-laptop` would promise what this module cannot keep. Its contents
|
||||
belong to this family: the vendor-key scan codes, the eDP panel beside an NVIDIA dGPU, and the NVIDIA
|
||||
D3 workaround. A second G14 is assigned the same module. Another ROG model gets its own.
|
||||
|
||||
Written against the GA403 (2024, Ryzen 8945HS, RTX 4070 Laptop, hybrid). Older G14 years have the same
|
||||
daemons and probably the same keys. Their GPU options are unverified.
|
||||
|
||||
## What it owns
|
||||
|
||||
| | what | how |
|
||||
|---|---|---|
|
||||
| package | `asusctl` (asusd + client) | the distribution's package (`extra`). The machine was found with a local build of 6.4.0. The host only asserts *present*, so the switch to 6.5.0 from `extra` happens at the next `pacman -Syu` (or `pacman -S asusctl`). `zephyrus_check` flags a local build |
|
||||
| package | `upower`, `playerctl`, `xorg-xinput` | what the low-battery drop-in, the media keys and the touchpad key use |
|
||||
| service | `asusd` running (static unit: no boot state to declare), `supergfxd` running and enabled | |
|
||||
| archive | `/usr/local/lib/asus-zephyrus-g14/bin/` | the module's scripts, from `files/bin` (below) |
|
||||
| file | `/etc/modprobe.d/g14-nvidia-power.conf` | `NVreg_DynamicPowerManagement=0x00` (runtime D3 off: the ACPI D-Notifier hang) and `NVreg_PreserveVideoMemoryAllocations=1`. The path is adopted (ADR 0182) |
|
||||
| file | `/etc/modprobe.d/video-brightness-switch.conf` | `video.brightness_switch_enabled=0`, so the ACPI video driver does not also move a backlight on the keys. The file was on the machine and owned by nothing |
|
||||
| file ×3 | `systemd-{suspend,hibernate,suspend-then-hibernate}.service.d/asus-zephyrus-g14-nvidia.conf` | `Wants=` the matching `nvidia-*` sleep units and `nvidia-resume` (see *suspend units* below) |
|
||||
| file | `nvidia-powerd.service.d/asus-zephyrus-g14.conf` | `ConditionKernelCommandLine=zephyrus.nvidia-powerd`: Dynamic Boost runs only when the operator opts in at boot |
|
||||
| file | `/etc/systemd/logind.conf.d/power.conf` | the power key and the lid suspend, on battery, on mains and docked. `systemd-logind` is reloaded, never restarted |
|
||||
| file | `/etc/udev/rules.d/90-backlight.rules` | backlights writable by the `video` group. `systemd-udevd` is reloaded |
|
||||
| file | `triggerhappy.service.d/asus-zephyrus-g14.conf` | `thd … --user ${machine:account}`: the triggers run as the operator's account (below) |
|
||||
| file | `/etc/triggerhappy/triggers.d/asus-g14.conf` | the vendor keys: media (`KEY_PROG1/3/4`), panel brightness, touchpad (`KEY_F21`). The path is adopted, because two trigger files would fire every key twice |
|
||||
| file | `/etc/UPower/UPower.conf.d/50-asus-zephyrus-g14.conf` | low battery at 15/10/7 %; at 7 % **suspend**, not power off. A drop-in over the package's own file |
|
||||
| file | `/etc/X11/xorg.conf.d/30-asus-zephyrus-g14-touchpad.conf` | tap to click, natural scrolling, acceleration 0.15, as an X input class |
|
||||
|
||||
**What it does not own, on purpose:**
|
||||
|
||||
- `/etc/asusd/*.ron` belong to asusd, which rewrites them whenever a setting changes. RON is not a
|
||||
format the host writes into (ADR 0102 speaks JSON and marked blocks). Owning the file whole would
|
||||
repeat the predecessor's freeze: the measured file already differs from the one the predecessor
|
||||
shipped. The settings the module needs are set through asusd, by its code (below).
|
||||
- `/etc/supergfxd.conf` and `/etc/modprobe.d/supergfxd.conf` belong to supergfxd, which writes both.
|
||||
- The swap file, its unit and the swap partition are the machine's swap layout (research 027,
|
||||
question 3). They are not this module's, nor `memory-pressure`'s.
|
||||
- The i3 fragments (`~/.config/i3/config.d/10-asus.conf`, `20-g14.conf`) and the keyboard-backlight
|
||||
notifier they start belong to phase 2 (the `i3` module).
|
||||
|
||||
## Software outside the distribution (ADR 0205, research 027 question 1)
|
||||
|
||||
`supergfxctl` (5.2.7, from the asus-linux repository, which is no longer configured) and
|
||||
`triggerhappy` (AUR) are **kept as found, and depended on**. The module declares no package for
|
||||
either, because the host installs from the official repositories only. It declares their services
|
||||
(`supergfxd` running, `triggerhappy` running), so on a machine without them the host refuses the
|
||||
service by name: *does not exist on this machine*. The refusal is loud, never a silent pass.
|
||||
`zephyrus_check` names both as foreign.
|
||||
|
||||
This module does not choose between the options of research 027 question 1. Under the starting
|
||||
position (P2: the build machine builds AUR packages into a repository the mesh serves), both become
|
||||
`package` resources here, and a fresh G14 installs them. **Until P2 exists, a fresh G14 is blocked
|
||||
on installing these two by hand.** ADR 0205's vendored archive (P1) does not fit: supergfxctl is a
|
||||
daemon with a system-bus policy and udev rules, and triggerhappy is C.
|
||||
|
||||
A later option for the keys: the module's own Go code could read the vendor keys from evdev, which
|
||||
the operator's account may do through the `input` group. That would retire triggerhappy entirely.
|
||||
It is not done here, because it would put the keys behind the node's runtime, and the runtime
|
||||
restarts a bundle that dies only on its next call (below).
|
||||
|
||||
## The long-running code: the profile switcher (ADR 0198)
|
||||
|
||||
The module's Go bundle serves the tools and runs the platform-profile switcher in the same process.
|
||||
The node's runtime launches the bundle at the runtime's start. It replaces the predecessor's
|
||||
`auto-profile`, a user unit that woke every five seconds, on battery too.
|
||||
|
||||
- **Policy** (constants until settings exist, issue 168): battery → `Quiet`; mains → `Balanced`;
|
||||
mains with the CPU at or above 50 % for 3 samples of 10 s → `Performance`, back to `Balanced` after
|
||||
3 samples at or below 20 %. Between the lines nothing moves (hysteresis). iowait counts as idle.
|
||||
- **Woken by events, not a poll.** The kernel's power-supply uevents (netlink, group 1) wake the
|
||||
switcher. Any account may listen on that group, and it needs no daemon, bus client or dependency;
|
||||
upower re-announces the same changes but would need a D-Bus client in the bundle. The CPU is
|
||||
sampled only on mains, every 10 s, because only there does the answer depend on it. On battery,
|
||||
a safety re-read every 5 minutes covers an event lost across a suspend. If the uevent socket
|
||||
cannot be opened, the switcher polls every 10 s and says so in `zephyrus_profile_policy`.
|
||||
- **The battery decides the source.** A battery that is *discharging* means battery, whatever any
|
||||
adapter says. The predecessor took any `online` file reading 1 as mains, and on this model the USB-C
|
||||
ports report `online`. Batteries of `scope=Device` (a mouse, a headset) are ignored.
|
||||
- **It acts on a change of its decision, never to restore one.** A profile someone chose by hand (the
|
||||
profile key, asusctl, `zephyrus_profile`) stays until the power source changes or the load crosses
|
||||
a line. The predecessor re-asserted its choice every five seconds, which made the profile key
|
||||
useless. **Starting is not a decision**: the runtime restarts the bundle on every push that changes
|
||||
one, and a push must not reset the operator's profile.
|
||||
- **A hold.** `zephyrus_profile` holds the profile it sets for 60 min (`hold_minutes`). A change of
|
||||
power source ends the hold.
|
||||
- **One assertion at start:** through asusctl, the charge limit (80 %) and asusd's own on-mains and
|
||||
on-battery profiles (`Balanced`, `Quiet`), each read first and set only if it differs. asusd's own
|
||||
switching on a change of power source then agrees with the switcher's. A limit set later with
|
||||
`zephyrus_charge_limit` stands until the bundle next starts. For a one-off full charge, use its
|
||||
`oneshot`.
|
||||
- **Events:** `profile.switched` (`profile`, `from`, `reason`, `source`), published through the
|
||||
runtime.
|
||||
|
||||
No root is involved. asusd's and supergfxd's bus policies admit the `users` and `wheel` groups, and the
|
||||
runtime runs as the operator's account. The one write that may escalate is the panel's backlight,
|
||||
when the udev rule has not run yet. It uses `sudo -n` and never prompts. Every command is bounded at
|
||||
20 s.
|
||||
|
||||
**Known limit.** The runtime restarts a launched bundle that exits *on its next tool call*, not at
|
||||
once (mesh-tools `launch.ts`), so a crashed switcher stays down until a tool is called. ADR 0198 §1
|
||||
says *started again when it exits*. The switcher recovers from a panic and reports it in
|
||||
`zephyrus_profile_policy` and `zephyrus_check`, but a crash of the process is the runtime's to restart.
|
||||
|
||||
## The vendor keys and the scripts
|
||||
|
||||
triggerhappy opens the input devices as root, then **drops to the operator's account with its groups**
|
||||
(`initgroups`: `input`, `video`). The packaged unit already drops to `nobody`, and the module's drop-in
|
||||
names the account instead. The predecessor replaced the packaged unit with one that ran every trigger
|
||||
as root, then `su`-ed to a named person with a hard-coded uid and display, and sourced a file of
|
||||
secrets on the way (research 027 question 2). Now:
|
||||
|
||||
- `zephyrus-session CMD…`: runs a command in the account's graphical session. It sets the account's
|
||||
own bus (`/run/user/<uid>/bus`) and finds the display from logind, or from a process of the account
|
||||
that has one. Nothing is sourced.
|
||||
- `zephyrus-backlight + | - | N`: the panel in 5 % steps, never below 1 %. **The panel is the
|
||||
backlight under the eDP connector**, because this model also registers `nvidia_0`, which moves
|
||||
nothing. The predecessor named `amdgpu_bl1` literally.
|
||||
- `zephyrus-notify ID TEXT`: one replacing notification, through `busctl` (the service manager's
|
||||
client, so no libnotify).
|
||||
- `zephyrus-touchpad reset | toggle`: bound to the touchpad key (`KEY_F21`).
|
||||
|
||||
**Media keys** go to MPRIS through `playerctl`. The predecessor's Plex fallback needed a Plex token
|
||||
from the secrets file and is dropped until a module can be handed a secret (research 027 question 2).
|
||||
|
||||
## The touchpad: an input class instead of a sleep hook
|
||||
|
||||
The predecessor re-ran `xinput` from `/etc/systemd/system-sleep/` after every resume, as a named person
|
||||
on a guessed display, because settings made with `xinput` are lost when the device initialises again.
|
||||
An X input class is applied by X **every time the device appears**: at login, on hotplug and after a
|
||||
resume. So the cause is fixed, and the hook is gone. The class matches any touchpad on the machine,
|
||||
which is the model's, so it holds across G14 years whose touchpads differ. It takes effect at the next
|
||||
X start. `zephyrus-touchpad reset` stays as the manual form.
|
||||
|
||||
## Suspend units without enabling them
|
||||
|
||||
`nvidia-suspend`, `-hibernate`, `-suspend-then-hibernate` and `-resume` are enabled with links in the
|
||||
sleep services' `.wants` directories. The mesh makes no links (ADR 0012). The host's service shape
|
||||
cannot declare them either: it may only say *running* or *stopped*, and *running* on a one-shot that
|
||||
last failed would start `nvidia-sleep.sh suspend` with the machine awake. So the module asks for them
|
||||
from the other side: a drop-in on each sleep service that `Wants=` them. The units' own
|
||||
`Before=`/`After=` order them. The found links stay and are harmless.
|
||||
|
||||
`suspend-then-hibernate` now also gets `nvidia-suspend-then-hibernate`, which the machine lacked.
|
||||
|
||||
The drop-ins take effect at the service manager's next `daemon-reload`. In the same apply, the restart
|
||||
of `triggerhappy` (whose drop-in changes) performs one.
|
||||
|
||||
## Tools
|
||||
|
||||
| tool | r/a | what |
|
||||
|---|---|---|
|
||||
| `zephyrus_brightness` | r/a | panel (percent or ±step, floor 1 %) and keyboard (off/low/med/high, 0-3, ±) through asusd |
|
||||
| `zephyrus_battery` | r | charge, energy in Wh, health (full ÷ design), cycles (the firmware reports 0, and this is said), limit, watts, hours left |
|
||||
| `zephyrus_charge_limit` | r/a | 20-100 through asusd; `oneshot` |
|
||||
| `zephyrus_gpu_mode` | r/a | mode, supported modes, dGPU power, the pending mode and action; says that asusd switches the mode on every change of power source |
|
||||
| `zephyrus_profile` | r/a | active, on-mains and on-battery profile, kernel platform profile; set with a hold |
|
||||
| `zephyrus_thermals` | r | every hwmon temperature and fan, the hottest, the dGPU's temperature **only when it is awake** (nvidia-smi wakes a suspended GPU) |
|
||||
| `zephyrus_power_draw` | r | battery flow, APU package power (PPT), dGPU draw when awake, power source and why |
|
||||
| `zephyrus_profile_policy` | r | what the switcher would choose now and why: source, recent load against the thresholds, decision, hold, last switch, what woke it, what it asserted at start, and whether the predecessor's switcher still runs |
|
||||
| `zephyrus_fan_curves` | r | asusd's curves per profile and fan |
|
||||
| `zephyrus_check` | r | every expectation: model, packages (local or foreign), daemons, nvidia-powerd, sleep units, the NVIDIA options **in force** (`/proc/driver/nvidia/params`), charge limit, one authority each over the profile and the GPU mode, predecessor leftovers. It also lists what it did not check |
|
||||
|
||||
`profile` is a candidate verb for a future `node-power-profile` seat (research 027/03). That seat has
|
||||
no record yet, so this is the module's own tool.
|
||||
|
||||
## Found on the laptop, 2026-10-04 (read-only)
|
||||
|
||||
- **Two authorities over the GPU mode.** `asusd.ron` has `ac_command: "supergfxctl -m Hybrid"` and
|
||||
`bat_command: "supergfxctl -m Integrated"`, so asusd switches the GPU mode on every change of power
|
||||
source. **supergfxd 5.2.7 cannot read logind's sessions** (`manager is an invalid variant`, every
|
||||
boot), so a switch that needs a logout times out. `zephyrus_check` reports both. The fix is the
|
||||
operator's, in asusd's file: clear both commands, or update supergfxctl once it can be packaged.
|
||||
- **`brightness.conf` did nothing.** `HandleBrightnessKey` is not a logind key, and logind logs
|
||||
*Unknown key … ignoring* at every start. The module does not carry it. The brightness keys were
|
||||
always triggerhappy's, with the ACPI video switch off.
|
||||
- **Two profile switchers** would run at once until `auto-profile` is stopped (below).
|
||||
- **asusctl is a local build** (6.4.0, *Unknown Packager*) beside a foreign `asusctl-debug`.
|
||||
|
||||
## When assigned to the laptop: what changes
|
||||
|
||||
1. `/usr/local/lib/asus-zephyrus-g14/` appears (four scripts).
|
||||
2. Written over found files (each original kept once by the host): `g14-nvidia-power.conf` and
|
||||
`video-brightness-switch.conf` (same options, so no change until the next boot either),
|
||||
`logind.conf.d/power.conf` (same keys; logind reloaded), `90-backlight.rules` (same effect;
|
||||
udevd reloaded), `triggers.d/asus-g14.conf` (now the module's scripts).
|
||||
3. New: the three sleep drop-ins (behaviour gained: `nvidia-suspend-then-hibernate`), the
|
||||
nvidia-powerd drop-in (no effect while it is masked), the triggerhappy drop-in, the UPower drop-in
|
||||
(same values as today), and the touchpad input class (at the next X start).
|
||||
4. `daemon-reload` and a `triggerhappy` restart. thd now runs as the account and the keys run the
|
||||
module's scripts. `upower` restarts.
|
||||
5. Packages, asusd and supergfxd: already as declared, so nothing changes. asusctl stays the local
|
||||
6.4.0 until the next upgrade.
|
||||
6. The node runtime restarts with the new bundle. The switcher asserts the limit (80, already) and
|
||||
asusd's profiles (Balanced and Quiet, already), so it sets nothing. It takes the current decision
|
||||
as applied and acts from the first event on.
|
||||
|
||||
## Predecessor files this module makes redundant — the operator removes them once (ADR 0182)
|
||||
|
||||
**On the laptop:**
|
||||
|
||||
1. `systemctl --user disable --now auto-profile.service`, then delete
|
||||
`~/.config/systemd/user/auto-profile.service` and `~/scripts/auto-profile`. **Do this right after
|
||||
the push**, or two switchers run at once.
|
||||
2. `~/scripts/asus-bright`, `~/scripts/asusctl-kbd-bright`, `~/scripts/xrandr-bright`,
|
||||
`~/scripts/as-user`, `~/scripts/media-control`: no trigger and no i3 binding uses them any more.
|
||||
3. `~/scripts/xinput-reset-touchpad`: still started and bound by `~/.config/i3/config.d/20-g14.conf`.
|
||||
Point those two lines at `/usr/local/lib/asus-zephyrus-g14/bin/zephyrus-touchpad reset`, or wait for
|
||||
the i3 module (phase 2) to rewrite the fragment.
|
||||
4. `/etc/systemd/system/triggerhappy.service`: the predecessor's replacement of the packaged unit. The
|
||||
module's drop-in works over either, so delete it and `systemctl daemon-reload` to return to the
|
||||
packaged unit (`Type=notify`, socket).
|
||||
5. `/etc/systemd/logind.conf.d/brightness.conf`: the unknown key, which does nothing.
|
||||
6. `/etc/systemd/system-sleep/xinput-reset-touchpad.sh`: replaced by the input class.
|
||||
7. `/etc/UPower/UPower.conf`: the predecessor's replacement of the package's file. Its values are now
|
||||
the module's drop-in. Restore the package's copy (`rm` it, then `pacman -S upower`).
|
||||
8. Optional: `systemctl disable nvidia-suspend nvidia-resume nvidia-hibernate` (the drop-ins carry them
|
||||
now), `/etc/asusd/*.ron-old` and `fan_curves.ron.bak`, the foreign `asusctl-debug` package, and
|
||||
`pacman -S asusctl` for the distribution's build.
|
||||
|
||||
**Stays the machine's:** `/swapfile` and `/etc/systemd/system/swapfile.swap` (the swap layout),
|
||||
`/etc/udev/rules.d/91-monitor-hotplug.rules` (the display's, phase 2), and the i3 fragments.
|
||||
|
||||
**On the desktop** (the predecessor's G14 flavor reached it; part was removed on 2026-10-04): none of
|
||||
this module applies there. Still present and to be deleted:
|
||||
`/etc/systemd/logind.conf.d/brightness.conf`, `/etc/systemd/system-sleep/xinput-reset-touchpad.sh`,
|
||||
`~/scripts/xinput-reset-touchpad`, `~/scripts/xrandr-bright` and
|
||||
`~/.config/i3/scripts/kbd-brightness-notify.sh`.
|
||||
|
||||
## Tests
|
||||
|
||||
`go test ./...` in this directory. Every tool runs against a tree standing in for `/sys`, `/proc` and
|
||||
`/etc`, and an injected runner answering with what asusctl 6.4 and supergfxctl 5.2 said on the laptop.
|
||||
The tests cover:
|
||||
|
||||
- the power-source rule;
|
||||
- battery arithmetic from `charge_*`;
|
||||
- the eDP panel choice;
|
||||
- brightness bounds;
|
||||
- the policy's sustain, relax and hysteresis, with iowait counted as idle;
|
||||
- the switcher: no act at start, one switch per change of source, a published event, boost from
|
||||
samples, holds, retry after failure, start-up assertions only where they differ, inert on another
|
||||
model;
|
||||
- the uevent filter;
|
||||
- the manifest: tools listed equal tools served, no machine named, triggers exist, every key runs a
|
||||
shipped executable script, every script passes `bash -n`.
|
||||
@@ -1,264 +0,0 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"regexp"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// The vendor daemons are reached through their own command-line clients, which speak to them on the
|
||||
// system bus. Their bus policy admits the `users` and `wheel` groups, so none of this needs root.
|
||||
|
||||
// Profiles are the platform profiles asusd offers on this model, in its spelling.
|
||||
var Profiles = []string{"Quiet", "Balanced", "Performance"}
|
||||
|
||||
// canonicalProfile accepts any case and answers asusd's spelling, or an error naming the choices.
|
||||
func canonicalProfile(s string) (string, error) {
|
||||
for _, p := range Profiles {
|
||||
if strings.EqualFold(strings.TrimSpace(s), p) {
|
||||
return p, nil
|
||||
}
|
||||
}
|
||||
return "", fmt.Errorf("profile %q is not one of %s", s, strings.Join(Profiles, ", "))
|
||||
}
|
||||
|
||||
// ProfileState is what asusd says about the platform profile.
|
||||
type ProfileState struct {
|
||||
Active string `json:"active"`
|
||||
OnAC string `json:"on_ac,omitempty"`
|
||||
Battery string `json:"on_battery,omitempty"`
|
||||
Platform string `json:"platform_profile,omitempty"`
|
||||
Choices string `json:"platform_profile_choices,omitempty"`
|
||||
}
|
||||
|
||||
var (
|
||||
activeProfile = regexp.MustCompile(`(?m)^Active profile:\s*(\S+)`)
|
||||
acProfile = regexp.MustCompile(`(?m)^AC profile\s+(\S+)`)
|
||||
batteryProfile = regexp.MustCompile(`(?m)^Battery profile\s+(\S+)`)
|
||||
)
|
||||
|
||||
// ParseProfileGet reads `asusctl profile get`.
|
||||
func ParseProfileGet(out string) (ProfileState, error) {
|
||||
var p ProfileState
|
||||
if m := activeProfile.FindStringSubmatch(out); m != nil {
|
||||
p.Active = m[1]
|
||||
} else {
|
||||
return p, fmt.Errorf("asusctl profile get said no active profile: %q", strings.TrimSpace(out))
|
||||
}
|
||||
if m := acProfile.FindStringSubmatch(out); m != nil {
|
||||
p.OnAC = m[1]
|
||||
}
|
||||
if m := batteryProfile.FindStringSubmatch(out); m != nil {
|
||||
p.Battery = m[1]
|
||||
}
|
||||
return p, nil
|
||||
}
|
||||
|
||||
// Profile reads the platform profile from asusd and the kernel.
|
||||
func (m *Machine) Profile(ctx context.Context) (ProfileState, error) {
|
||||
out, err := m.Run(ctx, "asusctl", "profile", "get")
|
||||
if err != nil {
|
||||
return ProfileState{}, vendor("asusctl", err)
|
||||
}
|
||||
p, err := ParseProfileGet(out)
|
||||
if err != nil {
|
||||
return p, err
|
||||
}
|
||||
p.Platform = m.read("/sys/firmware/acpi/platform_profile")
|
||||
p.Choices = m.read("/sys/firmware/acpi/platform_profile_choices")
|
||||
return p, nil
|
||||
}
|
||||
|
||||
// SetProfile has asusd switch the active profile.
|
||||
func (m *Machine) SetProfile(ctx context.Context, profile string) error {
|
||||
_, err := m.Run(ctx, "asusctl", "profile", "set", profile)
|
||||
return vendor("asusctl", err)
|
||||
}
|
||||
|
||||
var chargeLimit = regexp.MustCompile(`charge limit:\s*(\d+)\s*%`)
|
||||
|
||||
// ChargeLimit is the battery's charge limit as asusd reports it.
|
||||
func (m *Machine) ChargeLimit(ctx context.Context) (int, error) {
|
||||
out, err := m.Run(ctx, "asusctl", "battery", "info")
|
||||
if err != nil {
|
||||
return 0, vendor("asusctl", err)
|
||||
}
|
||||
g := chargeLimit.FindStringSubmatch(out)
|
||||
if g == nil {
|
||||
return 0, fmt.Errorf("asusctl battery info said no limit: %q", strings.TrimSpace(out))
|
||||
}
|
||||
n, _ := strconv.Atoi(g[1])
|
||||
return n, nil
|
||||
}
|
||||
|
||||
// Keyboard backlight levels in asusd's spelling, index = the kernel's brightness value.
|
||||
var KeyboardLevels = []string{"off", "low", "med", "high"}
|
||||
|
||||
var ledLevel = regexp.MustCompile(`(?i)brightness:\s*(off|low|med|high)`)
|
||||
|
||||
// ParseLeds reads `asusctl leds get`.
|
||||
func ParseLeds(out string) (string, error) {
|
||||
g := ledLevel.FindStringSubmatch(out)
|
||||
if g == nil {
|
||||
return "", fmt.Errorf("asusctl leds get said no level: %q", strings.TrimSpace(out))
|
||||
}
|
||||
return strings.ToLower(g[1]), nil
|
||||
}
|
||||
|
||||
// FanCurve is one fan's curve in one profile: eight points of temperature (°C) and duty (0-255).
|
||||
type FanCurve struct {
|
||||
Fan string `json:"fan"`
|
||||
Enabled bool `json:"enabled"`
|
||||
Temp []int `json:"temp_c"`
|
||||
PWM []int `json:"pwm"`
|
||||
}
|
||||
|
||||
var (
|
||||
fanBlock = regexp.MustCompile(`(?s)fan:\s*(\w+),\s*pwm:\s*\(([^)]*)\),\s*temp:\s*\(([^)]*)\),\s*enabled:\s*(true|false)`)
|
||||
)
|
||||
|
||||
// ParseFanCurves reads `asusctl fan-curve --mod-profile <p>`.
|
||||
func ParseFanCurves(out string) []FanCurve {
|
||||
var curves []FanCurve
|
||||
for _, g := range fanBlock.FindAllStringSubmatch(out, -1) {
|
||||
curves = append(curves, FanCurve{Fan: g[1], PWM: ints(g[2]), Temp: ints(g[3]), Enabled: g[4] == "true"})
|
||||
}
|
||||
return curves
|
||||
}
|
||||
|
||||
func ints(list string) []int {
|
||||
var out []int
|
||||
for _, f := range strings.Split(list, ",") {
|
||||
if n, err := strconv.Atoi(strings.TrimSpace(f)); err == nil {
|
||||
out = append(out, n)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// GPUState is what supergfxd says about the hybrid GPU.
|
||||
type GPUState struct {
|
||||
Mode string `json:"mode"`
|
||||
Supported []string `json:"supported"`
|
||||
Power string `json:"dgpu_power,omitempty"`
|
||||
PendingAction string `json:"pending_action,omitempty"`
|
||||
PendingMode string `json:"pending_mode,omitempty"`
|
||||
Vendor string `json:"dgpu_vendor,omitempty"`
|
||||
}
|
||||
|
||||
// ParseSupported reads `supergfxctl -s`: `[Integrated, Hybrid, AsusMuxDgpu]`.
|
||||
func ParseSupported(out string) []string {
|
||||
out = strings.Trim(strings.TrimSpace(out), "[]")
|
||||
var modes []string
|
||||
for _, f := range strings.Split(out, ",") {
|
||||
if f = strings.TrimSpace(f); f != "" {
|
||||
modes = append(modes, f)
|
||||
}
|
||||
}
|
||||
return modes
|
||||
}
|
||||
|
||||
// GPU reads supergfxd.
|
||||
func (m *Machine) GPU(ctx context.Context) (GPUState, error) {
|
||||
var g GPUState
|
||||
mode, err := m.Run(ctx, "supergfxctl", "-g")
|
||||
if err != nil {
|
||||
return g, vendor("supergfxctl", err)
|
||||
}
|
||||
g.Mode = strings.TrimSpace(mode)
|
||||
if s, err := m.Run(ctx, "supergfxctl", "-s"); err == nil {
|
||||
g.Supported = ParseSupported(s)
|
||||
}
|
||||
if s, err := m.Run(ctx, "supergfxctl", "-S"); err == nil {
|
||||
g.Power = strings.TrimSpace(s)
|
||||
}
|
||||
if s, err := m.Run(ctx, "supergfxctl", "-p"); err == nil {
|
||||
g.PendingAction = strings.TrimSpace(s)
|
||||
}
|
||||
if s, err := m.Run(ctx, "supergfxctl", "-P"); err == nil {
|
||||
g.PendingMode = strings.TrimSpace(s)
|
||||
}
|
||||
if s, err := m.Run(ctx, "supergfxctl", "-V"); err == nil {
|
||||
g.Vendor = strings.TrimSpace(s)
|
||||
}
|
||||
return g, nil
|
||||
}
|
||||
|
||||
// vendor names a vendor client that is not installed, rather than passing on "executable file not
|
||||
// found". asusctl is in the distribution's repositories; supergfxctl is not, and the module keeps it as
|
||||
// it was found until the mesh can build packages from the user repository (research 027, question 1).
|
||||
func vendor(name string, err error) error {
|
||||
if err == nil {
|
||||
return nil
|
||||
}
|
||||
if notInstalled(err) {
|
||||
switch name {
|
||||
case "supergfxctl":
|
||||
return fmt.Errorf("supergfxctl is not installed: it is not in the distribution's repositories, " +
|
||||
"and this module keeps the copy it finds rather than install one (novox/hq research 027, question 1)")
|
||||
default:
|
||||
return fmt.Errorf("%s is not installed; the module's package resource installs it", name)
|
||||
}
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
// AsusdConfig is the few settings of asusd's own file that decide what this module's code does. The
|
||||
// file is asusd's: it rewrites it whenever a setting changes, so the module reads it and never writes
|
||||
// it.
|
||||
type AsusdConfig struct {
|
||||
ChargeLimit *int `json:"charge_control_end_threshold,omitempty"`
|
||||
ProfileOnAC string `json:"platform_profile_on_ac,omitempty"`
|
||||
ProfileOnBattery string `json:"platform_profile_on_battery,omitempty"`
|
||||
ChangesProfileOnAC *bool `json:"change_platform_profile_on_ac,omitempty"`
|
||||
ChangesProfileOnBatt *bool `json:"change_platform_profile_on_battery,omitempty"`
|
||||
ACCommand string `json:"ac_command,omitempty"`
|
||||
BatteryCommand string `json:"bat_command,omitempty"`
|
||||
DisablesPowerdOnBatt *bool `json:"disable_nvidia_powerd_on_battery,omitempty"`
|
||||
}
|
||||
|
||||
var ronField = regexp.MustCompile(`(?m)^\s{4}([a-z_]+):\s*(.*?),?\s*$`)
|
||||
|
||||
// ParseAsusdRon reads the top-level scalar fields of asusd.ron. RON is not a format the mesh
|
||||
// speaks; these are one line each, and nothing nested is read.
|
||||
func ParseAsusdRon(text string) AsusdConfig {
|
||||
var c AsusdConfig
|
||||
for _, g := range ronField.FindAllStringSubmatch(text, -1) {
|
||||
key, value := g[1], strings.TrimSuffix(strings.TrimSpace(g[2]), ",")
|
||||
unquoted := strings.Trim(value, `"`)
|
||||
boolean := func() *bool { b := value == "true"; return &b }
|
||||
switch key {
|
||||
case "charge_control_end_threshold":
|
||||
if n, err := strconv.Atoi(value); err == nil {
|
||||
c.ChargeLimit = &n
|
||||
}
|
||||
case "platform_profile_on_ac":
|
||||
c.ProfileOnAC = unquoted
|
||||
case "platform_profile_on_battery":
|
||||
c.ProfileOnBattery = unquoted
|
||||
case "change_platform_profile_on_ac":
|
||||
c.ChangesProfileOnAC = boolean()
|
||||
case "change_platform_profile_on_battery":
|
||||
c.ChangesProfileOnBatt = boolean()
|
||||
case "ac_command":
|
||||
c.ACCommand = unquoted
|
||||
case "bat_command":
|
||||
c.BatteryCommand = unquoted
|
||||
case "disable_nvidia_powerd_on_battery":
|
||||
c.DisablesPowerdOnBatt = boolean()
|
||||
}
|
||||
}
|
||||
return c
|
||||
}
|
||||
|
||||
// Asusd reads asusd's file; nil when it is not there.
|
||||
func (m *Machine) Asusd() *AsusdConfig {
|
||||
text := m.read("/etc/asusd/asusd.ron")
|
||||
if text == "" {
|
||||
return nil
|
||||
}
|
||||
c := ParseAsusdRon(text)
|
||||
return &c
|
||||
}
|
||||
@@ -1,146 +0,0 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// What asusctl 6.4 and supergfxctl 5.2 said on the laptop on 2026-10-04.
|
||||
const fanCurveQuiet = `
|
||||
Fan curves for Quiet
|
||||
|
||||
[
|
||||
(
|
||||
fan: CPU,
|
||||
pwm: (2, 0, 10, 20, 35, 55, 80, 100),
|
||||
temp: (35, 45, 50, 55, 60, 65, 70, 80),
|
||||
enabled: true,
|
||||
),
|
||||
(
|
||||
fan: GPU,
|
||||
pwm: (0, 0, 10, 20, 35, 65, 90, 115),
|
||||
temp: (35, 45, 50, 55, 60, 65, 70, 80),
|
||||
enabled: false,
|
||||
),
|
||||
]
|
||||
`
|
||||
|
||||
const asusdRon = `(
|
||||
charge_control_end_threshold: 80,
|
||||
base_charge_control_end_threshold: 0,
|
||||
disable_nvidia_powerd_on_battery: true,
|
||||
ac_command: "supergfxctl -m Hybrid",
|
||||
bat_command: "supergfxctl -m Integrated",
|
||||
platform_profile_linked_epp: true,
|
||||
platform_profile_on_battery: Quiet,
|
||||
change_platform_profile_on_battery: true,
|
||||
platform_profile_on_ac: Balanced,
|
||||
change_platform_profile_on_ac: true,
|
||||
ac_profile_tunings: {
|
||||
Quiet: (
|
||||
enabled: false,
|
||||
group: {},
|
||||
),
|
||||
},
|
||||
)`
|
||||
|
||||
func TestAsusctlsAnswersAreRead(t *testing.T) {
|
||||
p, err := ParseProfileGet(profileGetBalanced)
|
||||
if err != nil || p.Active != "Balanced" || p.OnAC != "Balanced" || p.Battery != "Quiet" {
|
||||
t.Fatalf("%+v %v", p, err)
|
||||
}
|
||||
if _, err := ParseProfileGet("something else"); err == nil {
|
||||
t.Fatal("an answer with no profile was read as one")
|
||||
}
|
||||
if l, err := ParseLeds("Current keyboard led brightness: High\n"); err != nil || l != "high" {
|
||||
t.Fatalf("%q %v", l, err)
|
||||
}
|
||||
curves := ParseFanCurves(fanCurveQuiet)
|
||||
if len(curves) != 2 || curves[0].Fan != "CPU" || curves[0].PWM[7] != 100 || curves[0].Temp[0] != 35 || curves[1].Enabled {
|
||||
t.Fatalf("%+v", curves)
|
||||
}
|
||||
if got := ParseSupported("[Integrated, Hybrid, AsusMuxDgpu]\n"); strings.Join(got, ",") != "Integrated,Hybrid,AsusMuxDgpu" {
|
||||
t.Fatalf("%v", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAsusdsFileIsReadForWhatDecidesTheModulesCodeAndNothingNested(t *testing.T) {
|
||||
c := ParseAsusdRon(asusdRon)
|
||||
if *c.ChargeLimit != 80 || c.ProfileOnAC != "Balanced" || c.ProfileOnBattery != "Quiet" ||
|
||||
c.ACCommand != "supergfxctl -m Hybrid" || c.BatteryCommand != "supergfxctl -m Integrated" ||
|
||||
!*c.ChangesProfileOnAC || !*c.DisablesPowerdOnBatt {
|
||||
t.Fatalf("%+v", c)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAMissingVendorClientIsNamedWithWhyItIsMissing(t *testing.T) {
|
||||
f := newFake(t)
|
||||
f.fails["supergfxctl"] = notFound
|
||||
_, err := f.machine().GPU(context.Background())
|
||||
if err == nil || !strings.Contains(err.Error(), "research 027") {
|
||||
t.Fatalf("%v", err)
|
||||
}
|
||||
f.fails["asusctl"] = notFound
|
||||
_, err = f.machine().Profile(context.Background())
|
||||
if err == nil || !strings.Contains(err.Error(), "package resource installs it") {
|
||||
t.Fatalf("%v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAGPUModeIsSetOnlyWhenTheMachineSupportsItAndAsusdsSwitchingIsSaid(t *testing.T) {
|
||||
f := newFake(t)
|
||||
f.answers["supergfxctl -g"] = "Hybrid\n"
|
||||
f.answers["supergfxctl -s"] = "[Integrated, Hybrid, AsusMuxDgpu]\n"
|
||||
f.file("/etc/asusd/asusd.ron", asusdRon)
|
||||
m := f.machine()
|
||||
if _, err := GPUModeTool(context.Background(), m, map[string]any{"mode": "Vfio"}); err == nil {
|
||||
t.Fatal("an unsupported mode was accepted")
|
||||
}
|
||||
out, err := GPUModeTool(context.Background(), m, map[string]any{"mode": "integrated"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !f.called("supergfxctl -m Integrated") {
|
||||
t.Fatalf("calls %v", f.calls)
|
||||
}
|
||||
if _, said := out.(map[string]any)["asusd_switches_it"]; !said {
|
||||
t.Fatalf("asusd's own switching of the mode was not said: %+v", out)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTheChargeLimitIsBoundedAndSetThroughAsusd(t *testing.T) {
|
||||
f := newFake(t)
|
||||
f.answers["asusctl battery info"] = "Current battery charge limit: 60%\n"
|
||||
m := f.machine()
|
||||
for _, bad := range []any{float64(10), float64(101), "x", 55.5} {
|
||||
if _, err := ChargeLimitTool(context.Background(), m, map[string]any{"limit": bad}); err == nil {
|
||||
t.Errorf("limit %v was accepted", bad)
|
||||
}
|
||||
}
|
||||
out, err := ChargeLimitTool(context.Background(), m, map[string]any{"limit": float64(60)})
|
||||
if err != nil || !f.called("asusctl battery limit 60") || out.(map[string]any)["asusd_limit_percent"] != 60 {
|
||||
t.Fatalf("%+v %v %v", out, err, f.calls)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAProfileSetByToolIsHeldAndAnUnknownOneRefused(t *testing.T) {
|
||||
f := newFake(t)
|
||||
f.onMains()
|
||||
f.answers["asusctl profile get"] = profileGetBalanced
|
||||
m := f.machine()
|
||||
sw := NewSwitcher(m, nil)
|
||||
if _, err := ProfileTool(context.Background(), m, sw, map[string]any{"profile": "Turbo"}); err == nil {
|
||||
t.Fatal("an unknown profile was accepted")
|
||||
}
|
||||
out, err := ProfileTool(context.Background(), m, sw, map[string]any{"profile": "performance", "hold_minutes": float64(30)})
|
||||
if err != nil || !f.called("asusctl profile set Performance") {
|
||||
t.Fatalf("%v %v", err, f.calls)
|
||||
}
|
||||
if _, held := out.(map[string]any)["held_until"]; !held {
|
||||
t.Fatalf("not held: %+v", out)
|
||||
}
|
||||
if r := sw.Report(); r.Held != "Performance" {
|
||||
t.Fatalf("%+v", r)
|
||||
}
|
||||
}
|
||||
@@ -1,184 +0,0 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// Check is one thing the module expects of the machine, and whether it holds.
|
||||
type Check struct {
|
||||
Name string `json:"name"`
|
||||
OK bool `json:"ok"`
|
||||
Detail string `json:"detail"`
|
||||
}
|
||||
|
||||
// CheckReport is what zephyrus_check answers. NotChecked says what it did not look at, because a
|
||||
// check that reads as clean while skipping something is the predecessor's verifier again.
|
||||
type CheckReport struct {
|
||||
Model string `json:"model"`
|
||||
Checks []Check `json:"checks"`
|
||||
Failing int `json:"failing"`
|
||||
NotChecked []string `json:"not_checked"`
|
||||
}
|
||||
|
||||
var (
|
||||
pacmanVersion = regexp.MustCompile(`(?m)^Version\s*:\s*(\S+)`)
|
||||
pacmanPackager = regexp.MustCompile(`(?m)^Packager\s*:\s*(.+)$`)
|
||||
nvidiaParam = regexp.MustCompile(`(?m)^(\w+):\s*(\S+)`)
|
||||
)
|
||||
|
||||
// ParseNvidiaParams reads /proc/driver/nvidia/params.
|
||||
func ParseNvidiaParams(text string) map[string]string {
|
||||
out := map[string]string{}
|
||||
for _, g := range nvidiaParam.FindAllStringSubmatch(text, -1) {
|
||||
out[g[1]] = g[2]
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// predecessorProcess finds a running process whose command line names the predecessor's script.
|
||||
func (m *Machine) predecessorProcess(name string) (int, bool) {
|
||||
for _, dir := range m.glob("/proc/[0-9]*") {
|
||||
cmd := strings.ReplaceAll(m.read(dir+"/cmdline"), "\x00", " ")
|
||||
if strings.Contains(cmd, "/"+name) && !strings.Contains(cmd, "zephyrus") {
|
||||
var pid int
|
||||
fmt.Sscanf(filepath.Base(dir), "%d", &pid)
|
||||
return pid, true
|
||||
}
|
||||
}
|
||||
return 0, false
|
||||
}
|
||||
|
||||
func (m *Machine) unitIs(ctx context.Context, verb, unit string) string {
|
||||
out, _ := m.Run(ctx, "systemctl", verb, unit)
|
||||
return strings.TrimSpace(out)
|
||||
}
|
||||
|
||||
// Check reads every expectation and reports each.
|
||||
func (m *Machine) Check(ctx context.Context, sw *Switcher) CheckReport {
|
||||
r := CheckReport{Model: m.Model(), NotChecked: []string{
|
||||
"the fan curves (asusd's own, read them with zephyrus_fan_curves)",
|
||||
"whether the initramfs carries the NVIDIA options (they are read from the running driver instead)",
|
||||
"the vendor keys themselves (press them)",
|
||||
}}
|
||||
add := func(name string, ok bool, format string, a ...any) {
|
||||
r.Checks = append(r.Checks, Check{Name: name, OK: ok, Detail: fmt.Sprintf(format, a...)})
|
||||
if !ok {
|
||||
r.Failing++
|
||||
}
|
||||
}
|
||||
add("model", m.ThisModel(), "the firmware reports %q; this module is for %q", r.Model, ModelFamily)
|
||||
|
||||
// asusctl: present, and from the distribution rather than a local build.
|
||||
if info, err := m.Run(ctx, "pacman", "-Qi", "asusctl"); err != nil {
|
||||
add("asusctl package", false, "not installed: %v", err)
|
||||
} else {
|
||||
v, p := "", ""
|
||||
if g := pacmanVersion.FindStringSubmatch(info); g != nil {
|
||||
v = g[1]
|
||||
}
|
||||
if g := pacmanPackager.FindStringSubmatch(info); g != nil {
|
||||
p = strings.TrimSpace(g[1])
|
||||
}
|
||||
local := p == "Unknown Packager"
|
||||
add("asusctl package", !local, "version %s, packager %s%s", v, p,
|
||||
map[bool]string{true: "; a local build — the distribution's package replaces it at the next upgrade (pacman -S asusctl)", false: ""}[local])
|
||||
}
|
||||
for _, foreign := range []string{"supergfxctl", "triggerhappy"} {
|
||||
_, err := m.Run(ctx, "pacman", "-Q", foreign)
|
||||
add(foreign+" package", err == nil, "%s; not in the distribution's repositories, kept as found (novox/hq research 027, question 1)",
|
||||
map[bool]string{true: "installed", false: "NOT installed"}[err == nil])
|
||||
}
|
||||
for _, unit := range []string{"asusd.service", "supergfxd.service", "triggerhappy.service"} {
|
||||
state := m.unitIs(ctx, "is-active", unit)
|
||||
add(unit, state == "active", "%s", state)
|
||||
}
|
||||
powerd := m.unitIs(ctx, "is-enabled", "nvidia-powerd.service")
|
||||
add("nvidia-powerd.service", powerd == "masked" || powerd == "disabled" || powerd == "" || strings.Contains(powerd, "not-found"),
|
||||
"%s; the module's drop-in keeps it from starting unless the kernel command line says zephyrus.nvidia-powerd", orNone(powerd))
|
||||
wants, _ := m.Run(ctx, "systemctl", "show", "-p", "Wants", "systemd-suspend.service")
|
||||
add("nvidia suspend and resume", strings.Contains(wants, "nvidia-suspend.service") && strings.Contains(wants, "nvidia-resume.service"),
|
||||
"systemd-suspend.service %s", strings.TrimSpace(wants))
|
||||
|
||||
params := ParseNvidiaParams(m.read("/proc/driver/nvidia/params"))
|
||||
if len(params) == 0 {
|
||||
add("nvidia options", false, "the NVIDIA driver is not loaded (no /proc/driver/nvidia/params)")
|
||||
} else {
|
||||
add("nvidia options", params["PreserveVideoMemoryAllocations"] == "1" && params["DynamicPowerManagement"] == "0",
|
||||
"PreserveVideoMemoryAllocations=%s DynamicPowerManagement=%s (want 1 and 0; a change applies when the driver loads again)",
|
||||
params["PreserveVideoMemoryAllocations"], params["DynamicPowerManagement"])
|
||||
}
|
||||
|
||||
for _, b := range m.Batteries() {
|
||||
ok := b.LimitPercent != nil && *b.LimitPercent == ChargeLimitPercent
|
||||
have := "unknown"
|
||||
if b.LimitPercent != nil {
|
||||
have = fmt.Sprintf("%d%%", *b.LimitPercent)
|
||||
}
|
||||
add("charge limit", ok, "%s is %s, the module's is %d%%", b.Name, have, ChargeLimitPercent)
|
||||
}
|
||||
|
||||
if c := m.Asusd(); c != nil && (c.ACCommand != "" || c.BatteryCommand != "") {
|
||||
add("one authority over the GPU mode", false,
|
||||
"asusd runs %q on mains and %q on battery: it switches the GPU mode on every change of power source, "+
|
||||
"so a mode set with zephyrus_gpu_mode lasts until the next one. Clear ac_command and bat_command in /etc/asusd/asusd.ron (asusd's file) to make it the operator's alone",
|
||||
c.ACCommand, c.BatteryCommand)
|
||||
}
|
||||
if out, err := m.Run(ctx, "journalctl", "-b", "-u", "supergfxd.service", "-g", "invalid variant", "-n", "1", "-q", "-o", "cat"); err == nil && strings.TrimSpace(out) != "" {
|
||||
add("supergfxd and logind", false, "supergfxd cannot read logind's sessions this boot (%s): a mode change that needs a logout times out", strings.TrimSpace(out))
|
||||
}
|
||||
|
||||
if pid, ok := m.predecessorProcess("auto-profile"); ok {
|
||||
add("one profile switcher", false, "the predecessor's auto-profile still runs (pid %d) and switches the profile every five seconds; "+
|
||||
"stop it: systemctl --user disable --now auto-profile.service", pid)
|
||||
} else {
|
||||
add("one profile switcher", true, "no predecessor auto-profile is running")
|
||||
}
|
||||
if sw != nil {
|
||||
rep := sw.Report()
|
||||
add("profile switcher", rep.Running, "%s", orNone(firstNonEmpty(rep.Disabled, rep.LastError, "woken by "+rep.Watching)))
|
||||
}
|
||||
if home := os.Getenv("MESH_OPERATOR_HOME"); home != "" {
|
||||
var left []string
|
||||
for _, p := range PredecessorHomeFiles {
|
||||
if _, err := os.Stat(filepath.Join(m.Root, home, p)); err == nil {
|
||||
left = append(left, "~/"+p)
|
||||
}
|
||||
}
|
||||
add("predecessor files in the home", len(left) == 0, "%s", orNone(strings.Join(left, ", ")))
|
||||
} else {
|
||||
r.NotChecked = append(r.NotChecked, "the predecessor's files in the operator's home (MESH_OPERATOR_HOME is not set)")
|
||||
}
|
||||
return r
|
||||
}
|
||||
|
||||
// PredecessorHomeFiles are what the predecessor placed in the operator's home for this model and this
|
||||
// module replaces. The mesh removes nothing it did not make (novox/hq ADR 0182): the operator does,
|
||||
// once, and this list is how the check knows.
|
||||
var PredecessorHomeFiles = []string{
|
||||
"scripts/auto-profile",
|
||||
".config/systemd/user/auto-profile.service",
|
||||
"scripts/asus-bright",
|
||||
"scripts/asusctl-kbd-bright",
|
||||
"scripts/xrandr-bright",
|
||||
}
|
||||
|
||||
func orNone(s string) string {
|
||||
if strings.TrimSpace(s) == "" {
|
||||
return "none"
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
func firstNonEmpty(ss ...string) string {
|
||||
for _, s := range ss {
|
||||
if s != "" {
|
||||
return s
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
@@ -1,202 +0,0 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"math"
|
||||
"os"
|
||||
"path"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// MinPanelPercent is the floor a brightness change never goes below: a panel at zero is a black
|
||||
// screen that looks like a dead machine, and the keys cannot be seen to bring it back.
|
||||
const MinPanelPercent = 1
|
||||
|
||||
// Panel is the internal display's backlight.
|
||||
type Panel struct {
|
||||
Device string `json:"device"`
|
||||
Percent float64 `json:"percent"`
|
||||
Raw int64 `json:"raw"`
|
||||
Max int64 `json:"max"`
|
||||
Others []string `json:"other_backlights,omitempty"`
|
||||
}
|
||||
|
||||
// panelDevice chooses the backlight that drives the internal panel.
|
||||
//
|
||||
// **This model registers two.** In hybrid mode the integrated GPU drives the panel (amdgpu_bl1,
|
||||
// beneath the eDP connector) and the discrete GPU's driver registers one of its own (nvidia_0) that
|
||||
// moves nothing. The predecessor's scripts named amdgpu_bl1 literally, which is right until the GPU
|
||||
// mode puts the panel on the other GPU. The one that sits under an eDP connector is the panel's; failing
|
||||
// that, the kernel's own preference: firmware, then platform, then raw.
|
||||
func (m *Machine) panelDevice() (string, []string, error) {
|
||||
all := m.glob("/sys/class/backlight/*")
|
||||
if len(all) == 0 {
|
||||
return "", nil, fmt.Errorf("this machine has no backlight in /sys/class/backlight")
|
||||
}
|
||||
names := make([]string, 0, len(all))
|
||||
for _, d := range all {
|
||||
names = append(names, path.Base(d))
|
||||
}
|
||||
sort.Strings(names)
|
||||
rank := func(name string) int {
|
||||
dir := "/sys/class/backlight/" + name
|
||||
if target, err := os.Readlink(m.path(dir)); err == nil && strings.Contains(target, "-eDP-") {
|
||||
return 0
|
||||
}
|
||||
switch m.read(dir + "/type") {
|
||||
case "firmware":
|
||||
return 1
|
||||
case "platform":
|
||||
return 2
|
||||
}
|
||||
return 3
|
||||
}
|
||||
best := names[0]
|
||||
for _, n := range names[1:] {
|
||||
if rank(n) < rank(best) {
|
||||
best = n
|
||||
}
|
||||
}
|
||||
var others []string
|
||||
for _, n := range names {
|
||||
if n != best {
|
||||
others = append(others, n)
|
||||
}
|
||||
}
|
||||
return best, others, nil
|
||||
}
|
||||
|
||||
// PanelBrightness reads the panel.
|
||||
func (m *Machine) PanelBrightness() (Panel, error) {
|
||||
dev, others, err := m.panelDevice()
|
||||
if err != nil {
|
||||
return Panel{}, err
|
||||
}
|
||||
dir := "/sys/class/backlight/" + dev
|
||||
raw, ok1 := m.readInt(dir + "/brightness")
|
||||
max, ok2 := m.readInt(dir + "/max_brightness")
|
||||
if !ok1 || !ok2 || max <= 0 {
|
||||
return Panel{}, fmt.Errorf("%s does not say its brightness", dir)
|
||||
}
|
||||
return Panel{Device: dev, Raw: raw, Max: max, Percent: round1(float64(raw) / float64(max) * 100), Others: others}, nil
|
||||
}
|
||||
|
||||
// PanelTarget turns a request — "40", "40%", "+5", "-10" — into the percentage to set, clamped to
|
||||
// [MinPanelPercent, 100].
|
||||
func PanelTarget(current float64, request string) (float64, error) {
|
||||
r := strings.TrimSuffix(strings.TrimSpace(request), "%")
|
||||
if r == "" {
|
||||
return 0, fmt.Errorf("panel needs a percentage (40) or a step (+5, -5)")
|
||||
}
|
||||
n, err := strconv.ParseFloat(r, 64)
|
||||
if err != nil || math.IsNaN(n) || math.IsInf(n, 0) {
|
||||
return 0, fmt.Errorf("panel %q is not a percentage or a step", request)
|
||||
}
|
||||
target := n
|
||||
if strings.HasPrefix(r, "+") || strings.HasPrefix(r, "-") {
|
||||
target = current + n
|
||||
}
|
||||
return math.Max(MinPanelPercent, math.Min(100, target)), nil
|
||||
}
|
||||
|
||||
// SetPanel sets the panel to a percentage.
|
||||
func (m *Machine) SetPanel(ctx context.Context, request string) (Panel, error) {
|
||||
p, err := m.PanelBrightness()
|
||||
if err != nil {
|
||||
return p, err
|
||||
}
|
||||
target, err := PanelTarget(p.Percent, request)
|
||||
if err != nil {
|
||||
return p, err
|
||||
}
|
||||
raw := int64(math.Round(target / 100 * float64(p.Max)))
|
||||
if raw < 1 {
|
||||
raw = 1
|
||||
}
|
||||
if err := m.write(ctx, "/sys/class/backlight/"+p.Device+"/brightness", strconv.FormatInt(raw, 10)); err != nil {
|
||||
return p, err
|
||||
}
|
||||
return m.PanelBrightness()
|
||||
}
|
||||
|
||||
// Keyboard is the keyboard's backlight.
|
||||
type Keyboard struct {
|
||||
Device string `json:"device"`
|
||||
Level string `json:"level"`
|
||||
Value int64 `json:"value"`
|
||||
Max int64 `json:"max"`
|
||||
}
|
||||
|
||||
// KeyboardBrightness reads the keyboard backlight from the kernel.
|
||||
func (m *Machine) KeyboardBrightness() (Keyboard, error) {
|
||||
found := m.glob("/sys/class/leds/*kbd_backlight*")
|
||||
if len(found) == 0 {
|
||||
return Keyboard{}, fmt.Errorf("this machine has no keyboard backlight in /sys/class/leds")
|
||||
}
|
||||
dir := found[0]
|
||||
v, ok1 := m.readInt(dir + "/brightness")
|
||||
max, ok2 := m.readInt(dir + "/max_brightness")
|
||||
if !ok1 || !ok2 {
|
||||
return Keyboard{}, fmt.Errorf("%s does not say its brightness", dir)
|
||||
}
|
||||
k := Keyboard{Device: path.Base(dir), Value: v, Max: max}
|
||||
if max == int64(len(KeyboardLevels)-1) && v >= 0 && v <= max {
|
||||
k.Level = KeyboardLevels[v]
|
||||
}
|
||||
return k, nil
|
||||
}
|
||||
|
||||
// KeyboardTarget turns a request — off/low/med/high, 0-3, "+", "-" — into asusd's level name.
|
||||
func KeyboardTarget(current int64, request string) (string, error) {
|
||||
r := strings.ToLower(strings.TrimSpace(request))
|
||||
switch r {
|
||||
case "medium":
|
||||
r = "med"
|
||||
case "+", "up":
|
||||
r = strconv.FormatInt(min64(current+1, int64(len(KeyboardLevels)-1)), 10)
|
||||
case "-", "down":
|
||||
r = strconv.FormatInt(max64(current-1, 0), 10)
|
||||
}
|
||||
for _, l := range KeyboardLevels {
|
||||
if r == l {
|
||||
return l, nil
|
||||
}
|
||||
}
|
||||
if n, err := strconv.Atoi(r); err == nil && n >= 0 && n < len(KeyboardLevels) {
|
||||
return KeyboardLevels[n], nil
|
||||
}
|
||||
return "", fmt.Errorf("keyboard %q is not one of off, low, med, high, 0-3, + or -", request)
|
||||
}
|
||||
|
||||
// SetKeyboard has asusd set the keyboard backlight, so its own record of the level stays true.
|
||||
func (m *Machine) SetKeyboard(ctx context.Context, request string) (Keyboard, error) {
|
||||
k, err := m.KeyboardBrightness()
|
||||
if err != nil {
|
||||
return k, err
|
||||
}
|
||||
level, err := KeyboardTarget(k.Value, request)
|
||||
if err != nil {
|
||||
return k, err
|
||||
}
|
||||
if _, err := m.Run(ctx, "asusctl", "leds", "set", level); err != nil {
|
||||
return k, vendor("asusctl", err)
|
||||
}
|
||||
return m.KeyboardBrightness()
|
||||
}
|
||||
|
||||
func min64(a, b int64) int64 {
|
||||
if a < b {
|
||||
return a
|
||||
}
|
||||
return b
|
||||
}
|
||||
|
||||
func max64(a, b int64) int64 {
|
||||
if a > b {
|
||||
return a
|
||||
}
|
||||
return b
|
||||
}
|
||||
@@ -1,91 +0,0 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// backlight makes a backlight the way sysfs does: a link from /sys/class/backlight into the device
|
||||
// tree, which is where the eDP connector shows.
|
||||
func (f *fake) backlight(name, device string, raw, max string) {
|
||||
dev := "/sys/devices/" + device + "/" + name
|
||||
f.file(dev+"/brightness", raw)
|
||||
f.file(dev+"/max_brightness", max)
|
||||
f.file(dev+"/type", "raw")
|
||||
link := filepath.Join(f.root, "/sys/class/backlight", name)
|
||||
os.MkdirAll(filepath.Dir(link), 0o755)
|
||||
if err := os.Symlink(filepath.Join(f.root, dev), link); err != nil {
|
||||
f.t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestThePanelIsTheBacklightUnderTheEDPConnectorNotTheDiscreteGPUs(t *testing.T) {
|
||||
f := newFake(t)
|
||||
f.backlight("amdgpu_bl1", "pci0000:00/0000:65:00.0/drm/card1/card1-eDP-1", "199500", "399000")
|
||||
f.backlight("nvidia_0", "pci0000:00/0000:01:00.0/backlight", "100", "100")
|
||||
p, err := f.machine().PanelBrightness()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if p.Device != "amdgpu_bl1" || p.Percent != 50 || len(p.Others) != 1 || p.Others[0] != "nvidia_0" {
|
||||
t.Fatalf("%+v", p)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAPanelRequestIsAPercentageOrAStepAndNeverGoesDark(t *testing.T) {
|
||||
for _, c := range []struct {
|
||||
cur float64
|
||||
req string
|
||||
want float64
|
||||
}{{50, "40", 40}, {50, "40%", 40}, {50, "+5", 55}, {50, "-10", 40}, {3, "-10", 1}, {98, "+5", 100}, {50, "0", 1}} {
|
||||
got, err := PanelTarget(c.cur, c.req)
|
||||
if err != nil || got != c.want {
|
||||
t.Errorf("%v %q: %v %v, want %v", c.cur, c.req, got, err, c.want)
|
||||
}
|
||||
}
|
||||
for _, bad := range []string{"", "bright", "NaN"} {
|
||||
if _, err := PanelTarget(50, bad); err == nil {
|
||||
t.Errorf("%q was accepted", bad)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestSettingThePanelWritesTheRawValue(t *testing.T) {
|
||||
f := newFake(t)
|
||||
f.backlight("amdgpu_bl1", "card1-eDP-1", "399000", "399000")
|
||||
p, err := f.machine().SetPanel(context.Background(), "25")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
raw, _ := os.ReadFile(filepath.Join(f.root, "/sys/devices/card1-eDP-1/amdgpu_bl1/brightness"))
|
||||
if strings.TrimSpace(string(raw)) != "99750" || p.Percent != 25 {
|
||||
t.Fatalf("wrote %q, read back %+v", raw, p)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTheKeyboardIsSetThroughAsusdByLevel(t *testing.T) {
|
||||
f := newFake(t)
|
||||
f.file("/sys/class/leds/asus::kbd_backlight/brightness", "1")
|
||||
f.file("/sys/class/leds/asus::kbd_backlight/max_brightness", "3")
|
||||
k, err := f.machine().KeyboardBrightness()
|
||||
if err != nil || k.Level != "low" {
|
||||
t.Fatalf("%+v %v", k, err)
|
||||
}
|
||||
if _, err := f.machine().SetKeyboard(context.Background(), "+"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !f.called("asusctl leds set med") {
|
||||
t.Fatalf("calls: %v", f.calls)
|
||||
}
|
||||
for req, want := range map[string]string{"high": "high", "0": "off", "medium": "med", "-": "off"} {
|
||||
if got, err := KeyboardTarget(1, req); err != nil || got != want {
|
||||
t.Errorf("%q: %q %v", req, got, err)
|
||||
}
|
||||
}
|
||||
if _, err := KeyboardTarget(1, "7"); err == nil {
|
||||
t.Error("level 7 was accepted")
|
||||
}
|
||||
}
|
||||
@@ -1,103 +0,0 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// fake is a machine for a test: a tree standing in for /, and a runner answering from a table and
|
||||
// recording every command it was asked to run.
|
||||
type fake struct {
|
||||
t *testing.T
|
||||
root string
|
||||
mu sync.Mutex
|
||||
answers map[string]string
|
||||
fails map[string]error
|
||||
calls []string
|
||||
}
|
||||
|
||||
func newFake(t *testing.T) *fake {
|
||||
t.Helper()
|
||||
return &fake{t: t, root: t.TempDir(), answers: map[string]string{}, fails: map[string]error{}}
|
||||
}
|
||||
|
||||
func (f *fake) machine() *Machine { return &Machine{Root: f.root, Run: f.run} }
|
||||
|
||||
func (f *fake) run(_ context.Context, name string, args ...string) (string, error) {
|
||||
line := strings.TrimSpace(name + " " + strings.Join(args, " "))
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
f.calls = append(f.calls, line)
|
||||
if err, ok := f.fails[line]; ok {
|
||||
return "", err
|
||||
}
|
||||
if out, ok := f.answers[line]; ok {
|
||||
return out, nil
|
||||
}
|
||||
if err, ok := f.fails[name]; ok {
|
||||
return "", err
|
||||
}
|
||||
return "", nil
|
||||
}
|
||||
|
||||
func (f *fake) called(line string) bool {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
for _, c := range f.calls {
|
||||
if c == line {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func (f *fake) callsLike(prefix string) []string {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
var out []string
|
||||
for _, c := range f.calls {
|
||||
if strings.HasPrefix(c, prefix) {
|
||||
out = append(out, c)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// file writes a file under the fake root.
|
||||
func (f *fake) file(path, content string) {
|
||||
f.t.Helper()
|
||||
full := filepath.Join(f.root, path)
|
||||
if err := os.MkdirAll(filepath.Dir(full), 0o755); err != nil {
|
||||
f.t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(full, []byte(content), 0o644); err != nil {
|
||||
f.t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
// supply writes one power supply's attributes.
|
||||
func (f *fake) supply(name string, attrs map[string]string) {
|
||||
for k, v := range attrs {
|
||||
f.file("/sys/class/power_supply/"+name+"/"+k, v+"\n")
|
||||
}
|
||||
}
|
||||
|
||||
// onMains and onBattery are this model's two states as measured on 2026-10-04.
|
||||
func (f *fake) onMains() {
|
||||
f.supply("ACAD", map[string]string{"type": "Mains", "online": "1"})
|
||||
f.supply("BAT1", map[string]string{"type": "Battery", "status": "Not charging", "capacity": "80"})
|
||||
}
|
||||
|
||||
func (f *fake) onBattery() {
|
||||
f.supply("ACAD", map[string]string{"type": "Mains", "online": "0"})
|
||||
f.supply("BAT1", map[string]string{"type": "Battery", "status": "Discharging", "capacity": "79"})
|
||||
}
|
||||
|
||||
var notFound = &exec.Error{Name: "x", Err: exec.ErrNotFound}
|
||||
|
||||
const profileGetBalanced = "Active profile: Balanced\n\nAC profile Balanced\nBattery profile Quiet\n"
|
||||
@@ -1,124 +0,0 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// CommandTimeout bounds every command a tool or the switcher runs: a vendor daemon that hangs on its
|
||||
// bus must cost a tool call twenty seconds, never the runtime's thirty.
|
||||
const CommandTimeout = 20 * time.Second
|
||||
|
||||
// Runner runs one command and answers its standard output. It is injected so that every tool is
|
||||
// tested against recorded answers rather than this machine's daemons.
|
||||
type Runner func(ctx context.Context, name string, args ...string) (string, error)
|
||||
|
||||
// ExecRunner runs a command on the machine, bounded by CommandTimeout. A failure carries what the
|
||||
// command said on stderr, because "exit status 1" names nothing.
|
||||
func ExecRunner(ctx context.Context, name string, args ...string) (string, error) {
|
||||
ctx, cancel := context.WithTimeout(ctx, CommandTimeout)
|
||||
defer cancel()
|
||||
cmd := exec.CommandContext(ctx, name, args...)
|
||||
var stdout, stderr bytes.Buffer
|
||||
cmd.Stdout, cmd.Stderr = &stdout, &stderr
|
||||
err := cmd.Run()
|
||||
if ctx.Err() == context.DeadlineExceeded {
|
||||
return stdout.String(), fmt.Errorf("%s did not answer within %s", name, CommandTimeout)
|
||||
}
|
||||
if err != nil {
|
||||
said := strings.TrimSpace(stderr.String())
|
||||
if said == "" {
|
||||
said = strings.TrimSpace(stdout.String())
|
||||
}
|
||||
if said != "" {
|
||||
return stdout.String(), fmt.Errorf("%s %s: %w: %s", name, strings.Join(args, " "), err, said)
|
||||
}
|
||||
return stdout.String(), fmt.Errorf("%s %s: %w", name, strings.Join(args, " "), err)
|
||||
}
|
||||
return stdout.String(), nil
|
||||
}
|
||||
|
||||
// Machine is what the module reads and acts on: a filesystem root (the real one, or a test's tree of
|
||||
// /sys and /proc and /etc) and a way to run commands.
|
||||
type Machine struct {
|
||||
Root string
|
||||
Run Runner
|
||||
}
|
||||
|
||||
// Here is the machine this process runs on.
|
||||
func Here() *Machine { return &Machine{Root: "/", Run: ExecRunner} }
|
||||
|
||||
func (m *Machine) path(p string) string { return filepath.Join(m.Root, p) }
|
||||
|
||||
// read is a file's content, trimmed; "" when it cannot be read.
|
||||
func (m *Machine) read(p string) string {
|
||||
b, err := os.ReadFile(m.path(p))
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
return strings.TrimSpace(string(b))
|
||||
}
|
||||
|
||||
// readInt is a file holding one integer; ok false when it is absent or not a number.
|
||||
func (m *Machine) readInt(p string) (int64, bool) {
|
||||
s := m.read(p)
|
||||
if s == "" {
|
||||
return 0, false
|
||||
}
|
||||
n, err := strconv.ParseInt(s, 10, 64)
|
||||
return n, err == nil
|
||||
}
|
||||
|
||||
func (m *Machine) glob(pattern string) []string {
|
||||
found, _ := filepath.Glob(m.path(pattern))
|
||||
out := make([]string, 0, len(found))
|
||||
for _, f := range found {
|
||||
rel, err := filepath.Rel(m.Root, f)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
out = append(out, "/"+filepath.ToSlash(rel))
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// write puts a value into a file of the kernel's (a backlight). Where the account may not write it
|
||||
// — the udev rule that gives the video group the panel has not run yet — it escalates with `sudo -n`,
|
||||
// which never prompts: the operator's account may escalate without one, and when it may not, the
|
||||
// tool says so in sudo's words.
|
||||
func (m *Machine) write(ctx context.Context, p, value string) error {
|
||||
err := os.WriteFile(m.path(p), []byte(value), 0)
|
||||
if err == nil {
|
||||
return nil
|
||||
}
|
||||
if !errors.Is(err, os.ErrPermission) {
|
||||
return err
|
||||
}
|
||||
if _, serr := m.Run(ctx, "sudo", "-n", "sh", "-c", `printf '%s' "$1" > "$2"`, "sh", value, m.path(p)); serr != nil {
|
||||
return fmt.Errorf("%s is not writable by this account and sudo -n refused: %v", p, serr)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// notInstalled says a command failed because it is not on this machine at all.
|
||||
func notInstalled(err error) bool { return errors.Is(err, exec.ErrNotFound) }
|
||||
|
||||
// round to one decimal, for watts and percentages a person reads.
|
||||
func round1(f float64) float64 {
|
||||
return float64(int64(f*10+sign(f)*0.5)) / 10
|
||||
}
|
||||
|
||||
func sign(f float64) float64 {
|
||||
if f < 0 {
|
||||
return -1
|
||||
}
|
||||
return 1
|
||||
}
|
||||
@@ -1,25 +0,0 @@
|
||||
// The asus-zephyrus-g14 module's Go bundle (novox/hq ADR 0188, ADR 0193, ADR 0198): one process the
|
||||
// node's runtime launches, serving the module's tools over MCP on stdio and running its long-running
|
||||
// code — the platform-profile switcher — beside them.
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"os"
|
||||
|
||||
stdio "git.novox.be/novox/mesh-sdk/go"
|
||||
)
|
||||
|
||||
func main() {
|
||||
m := Here()
|
||||
sw := NewSwitcher(m, func(eventType string, body any) error { return stdio.Emit(eventType, body) })
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
go sw.Run(ctx)
|
||||
// An empty name serves as the module the runtime names (MESH_SERVED_MODULE).
|
||||
if err := stdio.Serve("", Tools(m, sw)); err != nil {
|
||||
fmt.Fprintln(os.Stderr, err)
|
||||
os.Exit(1)
|
||||
}
|
||||
}
|
||||
@@ -1,110 +0,0 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"sort"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
type manifest struct {
|
||||
Module string `json:"module"`
|
||||
Tools []string `json:"tools"`
|
||||
Emits []string `json:"emits"`
|
||||
Resources []map[string]any `json:"resources"`
|
||||
}
|
||||
|
||||
func readManifest(t *testing.T) manifest {
|
||||
t.Helper()
|
||||
raw, err := os.ReadFile("../../module.json")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var m manifest
|
||||
if err := json.Unmarshal(raw, &m); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return m
|
||||
}
|
||||
|
||||
func TestTheManifestNamesExactlyTheToolsTheBundleServes(t *testing.T) {
|
||||
m := readManifest(t)
|
||||
var served []string
|
||||
for _, tool := range Tools(&Machine{Root: t.TempDir(), Run: newFake(t).run}, nil) {
|
||||
served = append(served, tool.Name)
|
||||
}
|
||||
sort.Strings(served)
|
||||
listed := append([]string(nil), m.Tools...)
|
||||
sort.Strings(listed)
|
||||
if strings.Join(served, ",") != strings.Join(listed, ",") {
|
||||
t.Fatalf("served %v, listed %v", served, listed)
|
||||
}
|
||||
if len(m.Emits) != 1 || m.Emits[0] != "profile.switched" {
|
||||
t.Fatalf("emits %v", m.Emits)
|
||||
}
|
||||
}
|
||||
|
||||
// The module names the model, never a node, a person or a user id (novox/hq ADR 0112), and every
|
||||
// trigger it names a service restart or reload on is one of its own resources.
|
||||
func TestTheManifestNamesNoMachineAndItsTriggersExist(t *testing.T) {
|
||||
m := readManifest(t)
|
||||
ids := map[string]bool{}
|
||||
for _, r := range m.Resources {
|
||||
ids[r["id"].(string)] = true
|
||||
}
|
||||
raw, _ := os.ReadFile("../../module.json")
|
||||
for _, banned := range []string{"jochen", "/home/", "/run/user/1000", "\"g14\"", "shanks"} {
|
||||
if strings.Contains(string(raw), banned) {
|
||||
t.Errorf("the manifest says %q", banned)
|
||||
}
|
||||
}
|
||||
for _, r := range m.Resources {
|
||||
for _, key := range []string{"restart-on", "reload-on"} {
|
||||
list, _ := r[key].([]any)
|
||||
for _, id := range list {
|
||||
if !ids[id.(string)] {
|
||||
t.Errorf("%s %s names %v, which is not a resource", r["id"], key, id)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Every trigger runs a script the module ships, and every script parses.
|
||||
func TestTheVendorKeysRunTheModulesOwnScriptsAndTheyParse(t *testing.T) {
|
||||
m := readManifest(t)
|
||||
var triggers string
|
||||
for _, r := range m.Resources {
|
||||
if r["id"] == "vendor-keys" {
|
||||
triggers = r["content"].(string)
|
||||
}
|
||||
}
|
||||
if triggers == "" {
|
||||
t.Fatal("no vendor-keys resource")
|
||||
}
|
||||
for _, line := range strings.Split(triggers, "\n") {
|
||||
f := strings.Split(line, "\t")
|
||||
if strings.HasPrefix(line, "#") || len(f) < 3 {
|
||||
continue
|
||||
}
|
||||
script := strings.Fields(f[2])[0]
|
||||
local := filepath.Join("../../files/bin", filepath.Base(script))
|
||||
if !strings.HasPrefix(script, "/usr/local/lib/asus-zephyrus-g14/bin/") {
|
||||
t.Errorf("%s runs %s, which the module does not ship", f[0], script)
|
||||
} else if st, err := os.Stat(local); err != nil || st.Mode()&0o111 == 0 {
|
||||
t.Errorf("%s: %s is missing or not executable", f[0], local)
|
||||
}
|
||||
}
|
||||
scripts, _ := filepath.Glob("../../files/bin/*")
|
||||
if len(scripts) == 0 {
|
||||
t.Fatal("no scripts")
|
||||
}
|
||||
for _, s := range scripts {
|
||||
if out, err := exec.Command("bash", "-n", s).CombinedOutput(); err != nil {
|
||||
t.Errorf("%s: %v %s", s, err, out)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,137 +0,0 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// The policy, as constants until the mesh has settings a module can read (novox/hq issue 168). The
|
||||
// values are the predecessor's, made explicit, and two of its behaviours are changed on purpose:
|
||||
//
|
||||
// - **Sustained, not momentary.** The predecessor boosted on one five-second sample above 50 %: a
|
||||
// compile's first second, a browser's tab restore. Here the load must stay above the line for
|
||||
// SustainSamples samples in a row, and below the lower line as long, before the profile moves.
|
||||
// - **Waiting on a disk is not load.** iowait is counted as idle: a machine stalled on its SSD does
|
||||
// not get faster with a higher power limit, only hotter.
|
||||
const (
|
||||
ProfileOnBattery = "Quiet"
|
||||
ProfileOnAC = "Balanced"
|
||||
ProfileUnderLoad = "Performance"
|
||||
|
||||
CPUHighPercent = 50.0 // on mains, sustained at or above this boosts to ProfileUnderLoad
|
||||
CPULowPercent = 20.0 // and sustained at or below this goes back to ProfileOnAC
|
||||
|
||||
SampleEvery = 10 * time.Second // CPU is sampled only on mains; on battery nothing is sampled
|
||||
SustainSamples = 3 // 30 s above CPUHighPercent to boost
|
||||
RelaxSamples = 3 // 30 s below CPULowPercent to relax
|
||||
|
||||
// SafetyRecheck is how often the power source is read when no event has said it changed: the
|
||||
// kernel's event is the trigger, and this only covers one lost across a suspend.
|
||||
SafetyRecheck = 5 * time.Minute
|
||||
|
||||
// DefaultHold is how long a profile chosen through the profile tool is kept before the switcher
|
||||
// may move it again. A change of power source ends a hold at once.
|
||||
DefaultHold = 60 * time.Minute
|
||||
|
||||
// ChargeLimitPercent is the battery charge limit the module asserts through asusd at start.
|
||||
ChargeLimitPercent = 80
|
||||
)
|
||||
|
||||
// Policy is the switcher's memory of recent load: how many samples in a row were above the upper line
|
||||
// or below the lower one, and whether it is boosted.
|
||||
type Policy struct {
|
||||
Boosted bool `json:"boosted"`
|
||||
Above int `json:"samples_above"`
|
||||
Below int `json:"samples_below"`
|
||||
Recent []float64 `json:"recent_cpu_percent"`
|
||||
BoostedSince time.Time `json:"boosted_since,omitempty"`
|
||||
}
|
||||
|
||||
// Observe takes one CPU sample (busy percent since the previous one) taken on mains.
|
||||
func (p *Policy) Observe(cpu float64, at time.Time) {
|
||||
p.Recent = append(p.Recent, round1(cpu))
|
||||
if len(p.Recent) > 6 {
|
||||
p.Recent = p.Recent[len(p.Recent)-6:]
|
||||
}
|
||||
switch {
|
||||
case cpu >= CPUHighPercent:
|
||||
p.Above++
|
||||
p.Below = 0
|
||||
if !p.Boosted && p.Above >= SustainSamples {
|
||||
p.Boosted = true
|
||||
p.BoostedSince = at
|
||||
}
|
||||
case cpu <= CPULowPercent:
|
||||
p.Below++
|
||||
p.Above = 0
|
||||
if p.Boosted && p.Below >= RelaxSamples {
|
||||
p.Boosted = false
|
||||
p.BoostedSince = time.Time{}
|
||||
}
|
||||
default:
|
||||
// Between the lines: no direction is sustained, and the profile stays where it is.
|
||||
p.Above, p.Below = 0, 0
|
||||
}
|
||||
}
|
||||
|
||||
// Reset forgets the load, for a change of power source.
|
||||
func (p *Policy) Reset() { *p = Policy{} }
|
||||
|
||||
// Decision is what the switcher would choose, and why.
|
||||
type Decision struct {
|
||||
Profile string `json:"profile"`
|
||||
Reason string `json:"reason"`
|
||||
}
|
||||
|
||||
// Decide is the policy: battery → ProfileOnBattery; mains → ProfileOnAC, or ProfileUnderLoad while
|
||||
// boosted.
|
||||
func (p *Policy) Decide(src Source) Decision {
|
||||
if !src.OnAC {
|
||||
return Decision{ProfileOnBattery, "on battery (" + src.Reason + ")"}
|
||||
}
|
||||
if p.Boosted {
|
||||
return Decision{ProfileUnderLoad, fmt.Sprintf("on mains (%s) and CPU load sustained at or above %s%% for %d samples of %s",
|
||||
src.Reason, strconv.FormatFloat(CPUHighPercent, 'f', -1, 64), SustainSamples, SampleEvery)}
|
||||
}
|
||||
return Decision{ProfileOnAC, fmt.Sprintf("on mains (%s), and CPU load not sustained at or above %s%%",
|
||||
src.Reason, strconv.FormatFloat(CPUHighPercent, 'f', -1, 64))}
|
||||
}
|
||||
|
||||
// CPUTimes is the first line of /proc/stat: total and idle jiffies (iowait counted as idle).
|
||||
type CPUTimes struct{ Total, Idle uint64 }
|
||||
|
||||
// ParseProcStat reads the aggregate cpu line of /proc/stat.
|
||||
func ParseProcStat(text string) (CPUTimes, error) {
|
||||
line := strings.SplitN(text, "\n", 2)[0]
|
||||
f := strings.Fields(line)
|
||||
if len(f) < 6 || f[0] != "cpu" {
|
||||
return CPUTimes{}, fmt.Errorf("/proc/stat does not start with the cpu line")
|
||||
}
|
||||
var t CPUTimes
|
||||
for i, s := range f[1:] {
|
||||
if i >= 8 { // user nice system idle iowait irq softirq steal; guest is already in user
|
||||
break
|
||||
}
|
||||
n, err := strconv.ParseUint(s, 10, 64)
|
||||
if err != nil {
|
||||
return CPUTimes{}, fmt.Errorf("/proc/stat: %v", err)
|
||||
}
|
||||
t.Total += n
|
||||
if i == 3 || i == 4 {
|
||||
t.Idle += n
|
||||
}
|
||||
}
|
||||
return t, nil
|
||||
}
|
||||
|
||||
// Busy is the percentage of time not idle between two readings.
|
||||
func Busy(before, after CPUTimes) (float64, bool) {
|
||||
if after.Total <= before.Total {
|
||||
return 0, false
|
||||
}
|
||||
total := float64(after.Total - before.Total)
|
||||
idle := float64(after.Idle - before.Idle)
|
||||
return (total - idle) / total * 100, true
|
||||
}
|
||||
@@ -1,180 +0,0 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"path"
|
||||
"sort"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// Supply is one entry of /sys/class/power_supply as the kernel reports it.
|
||||
type Supply struct {
|
||||
Name string `json:"name"`
|
||||
Type string `json:"type"`
|
||||
Scope string `json:"scope,omitempty"`
|
||||
Status string `json:"status,omitempty"`
|
||||
Online *bool `json:"online,omitempty"`
|
||||
}
|
||||
|
||||
// Supplies is every power supply the kernel knows, sorted by name.
|
||||
func (m *Machine) Supplies() []Supply {
|
||||
var out []Supply
|
||||
for _, dir := range m.glob("/sys/class/power_supply/*") {
|
||||
s := Supply{
|
||||
Name: path.Base(dir),
|
||||
Type: m.read(dir + "/type"),
|
||||
Scope: m.read(dir + "/scope"),
|
||||
Status: m.read(dir + "/status"),
|
||||
}
|
||||
if v, ok := m.readInt(dir + "/online"); ok {
|
||||
on := v == 1
|
||||
s.Online = &on
|
||||
}
|
||||
out = append(out, s)
|
||||
}
|
||||
sort.Slice(out, func(i, j int) bool { return out[i].Name < out[j].Name })
|
||||
return out
|
||||
}
|
||||
|
||||
// system is a supply that powers this machine. A mouse's or a headset's battery reports scope
|
||||
// Device, and it says nothing about whether the laptop is on mains.
|
||||
func (s Supply) system() bool { return !strings.EqualFold(s.Scope, "Device") }
|
||||
|
||||
// Source is where the machine draws its power from, and why that was concluded.
|
||||
type Source struct {
|
||||
OnAC bool `json:"on_ac"`
|
||||
Source string `json:"source"`
|
||||
Reason string `json:"reason"`
|
||||
}
|
||||
|
||||
// PowerSource decides mains or battery.
|
||||
//
|
||||
// **A battery that says it is discharging wins over any adapter that says it is online.** The
|
||||
// predecessor's script took any `online` file reading 1 as mains, and a USB-C port reports `online`
|
||||
// for things that do not power the machine. The battery's own status is the one fact that cannot be
|
||||
// misread: it discharges exactly when nothing outside is carrying the load. Only when no battery says
|
||||
// so are the adapters asked, and a machine with no system battery at all is on mains.
|
||||
func PowerSource(supplies []Supply) Source {
|
||||
batteries := 0
|
||||
for _, s := range supplies {
|
||||
if s.Type == "Battery" && s.system() {
|
||||
batteries++
|
||||
if strings.EqualFold(s.Status, "Discharging") {
|
||||
return Source{OnAC: false, Source: "battery", Reason: s.Name + " is discharging"}
|
||||
}
|
||||
}
|
||||
}
|
||||
for _, s := range supplies {
|
||||
if (s.Type == "Mains" || strings.HasPrefix(s.Type, "USB")) && s.system() && s.Online != nil && *s.Online {
|
||||
return Source{OnAC: true, Source: "ac", Reason: s.Name + " (" + s.Type + ") is online"}
|
||||
}
|
||||
}
|
||||
if batteries == 0 {
|
||||
return Source{OnAC: true, Source: "ac", Reason: "this machine has no system battery"}
|
||||
}
|
||||
return Source{OnAC: false, Source: "battery", Reason: "no mains or USB supply is online"}
|
||||
}
|
||||
|
||||
// Battery is what the battery tool answers.
|
||||
type Battery struct {
|
||||
Name string `json:"name"`
|
||||
Status string `json:"status"`
|
||||
ChargePercent *int64 `json:"charge_percent,omitempty"`
|
||||
EnergyWh *float64 `json:"energy_wh,omitempty"`
|
||||
FullWh *float64 `json:"full_wh,omitempty"`
|
||||
DesignWh *float64 `json:"design_wh,omitempty"`
|
||||
HealthPercent *float64 `json:"health_percent,omitempty"`
|
||||
Cycles *int64 `json:"cycles"`
|
||||
CyclesNote string `json:"cycles_note,omitempty"`
|
||||
LimitPercent *int64 `json:"charge_limit_percent,omitempty"`
|
||||
PowerW *float64 `json:"power_w,omitempty"`
|
||||
HoursRemaining *float64 `json:"hours_remaining,omitempty"`
|
||||
Technology string `json:"technology,omitempty"`
|
||||
Model string `json:"model,omitempty"`
|
||||
Manufacturer string `json:"manufacturer,omitempty"`
|
||||
}
|
||||
|
||||
// Batteries reads every system battery.
|
||||
func (m *Machine) Batteries() []Battery {
|
||||
var out []Battery
|
||||
for _, s := range m.Supplies() {
|
||||
if s.Type != "Battery" || !s.system() {
|
||||
continue
|
||||
}
|
||||
out = append(out, m.battery(s))
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func (m *Machine) battery(s Supply) Battery {
|
||||
dir := "/sys/class/power_supply/" + s.Name
|
||||
b := Battery{
|
||||
Name: s.Name, Status: s.Status,
|
||||
Technology: m.read(dir + "/technology"),
|
||||
Model: m.read(dir + "/model_name"),
|
||||
Manufacturer: strings.TrimSpace(m.read(dir + "/manufacturer")),
|
||||
}
|
||||
if v, ok := m.readInt(dir + "/capacity"); ok {
|
||||
b.ChargePercent = &v
|
||||
}
|
||||
// Energy in Wh: energy_* (µWh) where the firmware reports it, else charge_* (µAh) times the
|
||||
// design minimum voltage, which is how upower converts it too.
|
||||
wh := func(energy, charge string) *float64 {
|
||||
if v, ok := m.readInt(dir + "/" + energy); ok {
|
||||
f := round1(float64(v) / 1e6)
|
||||
return &f
|
||||
}
|
||||
c, okc := m.readInt(dir + "/" + charge)
|
||||
volts, okv := m.readInt(dir + "/voltage_min_design")
|
||||
if okc && okv {
|
||||
f := round1(float64(c) * float64(volts) / 1e12)
|
||||
return &f
|
||||
}
|
||||
return nil
|
||||
}
|
||||
b.EnergyWh = wh("energy_now", "charge_now")
|
||||
b.FullWh = wh("energy_full", "charge_full")
|
||||
b.DesignWh = wh("energy_full_design", "charge_full_design")
|
||||
if b.FullWh != nil && b.DesignWh != nil && *b.DesignWh > 0 {
|
||||
h := round1(*b.FullWh / *b.DesignWh * 100)
|
||||
b.HealthPercent = &h
|
||||
}
|
||||
if v, ok := m.readInt(dir + "/cycle_count"); ok && v > 0 {
|
||||
b.Cycles = &v
|
||||
} else {
|
||||
b.CyclesNote = "the firmware does not report a cycle count (it reads 0)"
|
||||
}
|
||||
if v, ok := m.readInt(dir + "/charge_control_end_threshold"); ok {
|
||||
b.LimitPercent = &v
|
||||
}
|
||||
if w := m.batteryWatts(dir); w != nil {
|
||||
b.PowerW = w
|
||||
if strings.EqualFold(s.Status, "Discharging") && b.EnergyWh != nil && *w > 0.5 {
|
||||
h := round1(*b.EnergyWh / *w)
|
||||
b.HoursRemaining = &h
|
||||
}
|
||||
}
|
||||
return b
|
||||
}
|
||||
|
||||
// batteryWatts is how much the battery is giving or taking, in watts, unsigned: power_now where the
|
||||
// firmware reports it, else current times voltage.
|
||||
func (m *Machine) batteryWatts(dir string) *float64 {
|
||||
if v, ok := m.readInt(dir + "/power_now"); ok {
|
||||
f := round1(abs(float64(v)) / 1e6)
|
||||
return &f
|
||||
}
|
||||
i, oki := m.readInt(dir + "/current_now")
|
||||
u, oku := m.readInt(dir + "/voltage_now")
|
||||
if oki && oku {
|
||||
f := round1(abs(float64(i)) * float64(u) / 1e12)
|
||||
return &f
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func abs(f float64) float64 {
|
||||
if f < 0 {
|
||||
return -f
|
||||
}
|
||||
return f
|
||||
}
|
||||
@@ -1,73 +0,0 @@
|
||||
package main
|
||||
|
||||
import "testing"
|
||||
|
||||
func on(b bool) *bool { return &b }
|
||||
|
||||
func TestADischargingBatteryWinsOverAnAdapterThatSaysOnline(t *testing.T) {
|
||||
got := PowerSource([]Supply{
|
||||
{Name: "BAT1", Type: "Battery", Status: "Discharging"},
|
||||
{Name: "ucsi-source-psy-USBC000:001", Type: "USB", Scope: "System", Online: on(true)},
|
||||
})
|
||||
if got.OnAC {
|
||||
t.Fatalf("a USB-C port reporting online while the battery discharges was read as mains: %+v", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMainsOnlineIsAC(t *testing.T) {
|
||||
got := PowerSource([]Supply{
|
||||
{Name: "ACAD", Type: "Mains", Online: on(true)},
|
||||
{Name: "BAT1", Type: "Battery", Status: "Not charging"},
|
||||
})
|
||||
if !got.OnAC || got.Reason != "ACAD (Mains) is online" {
|
||||
t.Fatalf("%+v", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAPeripheralsBatteryDecidesNothing(t *testing.T) {
|
||||
got := PowerSource([]Supply{
|
||||
{Name: "hidpp_battery_0", Type: "Battery", Scope: "Device", Status: "Discharging"},
|
||||
{Name: "ACAD", Type: "Mains", Online: on(true)},
|
||||
{Name: "BAT1", Type: "Battery", Status: "Charging"},
|
||||
})
|
||||
if !got.OnAC {
|
||||
t.Fatalf("a mouse's discharging battery put the laptop on battery: %+v", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNoSupplyOnlineWithABatteryIsBatteryAndNoBatteryIsMains(t *testing.T) {
|
||||
if got := PowerSource([]Supply{{Name: "ACAD", Type: "Mains", Online: on(false)}, {Name: "BAT1", Type: "Battery", Status: "Unknown"}}); got.OnAC {
|
||||
t.Fatalf("%+v", got)
|
||||
}
|
||||
if got := PowerSource(nil); !got.OnAC {
|
||||
t.Fatalf("a machine with no battery is on mains: %+v", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTheBatteryIsReadInWattHoursFromChargeAndHealthAgainstDesign(t *testing.T) {
|
||||
f := newFake(t)
|
||||
// The laptop's own battery, as measured: charge_* in µAh, no energy_* and no power_now.
|
||||
f.supply("BAT1", map[string]string{
|
||||
"type": "Battery", "status": "Discharging", "capacity": "80",
|
||||
"charge_now": "3073000", "charge_full": "3865000", "charge_full_design": "4580000",
|
||||
"voltage_min_design": "15939000", "current_now": "1000000", "voltage_now": "16000000",
|
||||
"cycle_count": "0", "charge_control_end_threshold": "80", "manufacturer": "ASUS ",
|
||||
})
|
||||
bs := f.machine().Batteries()
|
||||
if len(bs) != 1 {
|
||||
t.Fatalf("%+v", bs)
|
||||
}
|
||||
b := bs[0]
|
||||
if *b.EnergyWh != 49 || *b.FullWh != 61.6 || *b.DesignWh != 73 || *b.HealthPercent != 84.4 {
|
||||
t.Fatalf("energy %v full %v design %v health %v", *b.EnergyWh, *b.FullWh, *b.DesignWh, *b.HealthPercent)
|
||||
}
|
||||
if b.Cycles != nil || b.CyclesNote == "" {
|
||||
t.Fatal("a cycle count of 0 is the firmware not reporting one, and said so")
|
||||
}
|
||||
if *b.LimitPercent != 80 || *b.PowerW != 16 || b.HoursRemaining == nil || *b.HoursRemaining != 3.1 {
|
||||
t.Fatalf("limit %v power %v hours %v", *b.LimitPercent, *b.PowerW, b.HoursRemaining)
|
||||
}
|
||||
if b.Manufacturer != "ASUS" {
|
||||
t.Fatalf("manufacturer %q", b.Manufacturer)
|
||||
}
|
||||
}
|
||||
@@ -1,303 +0,0 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"os"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
// The module's long-running code (novox/hq ADR 0198): the profile switcher, launched with the tools
|
||||
// by the node's runtime and running beside them in the same process.
|
||||
//
|
||||
// It replaces the predecessor's `auto-profile`, a user unit that woke every five seconds for ever —
|
||||
// read the adapters, read /proc/stat, maybe call asusctl — on battery too, where its only possible
|
||||
// answer was the one it had already given. Here the kernel's power-supply event is the trigger; the
|
||||
// CPU is sampled only on mains, where the answer depends on it; and on battery the process sleeps
|
||||
// until the adapter comes back.
|
||||
//
|
||||
// **It acts on a change of its decision, never to restore one.** A profile chosen by hand — the
|
||||
// vendor's profile key, asusctl in a terminal, the profile tool — stays until the power source
|
||||
// changes or the load crosses a line. The predecessor re-asserted its choice every five seconds and so
|
||||
// made the profile key useless on battery.
|
||||
|
||||
// Emitter publishes an event as the module; nil when the process is not under the runtime.
|
||||
type Emitter func(eventType string, body any) error
|
||||
|
||||
// Switcher is the switcher's state, shared with the tools that report it.
|
||||
type Switcher struct {
|
||||
m *Machine
|
||||
now func() time.Time
|
||||
emit Emitter
|
||||
|
||||
mu sync.Mutex
|
||||
policy Policy
|
||||
source *Source
|
||||
decision *Decision
|
||||
applied string
|
||||
appliedAt time.Time
|
||||
lastError string
|
||||
holdUntil time.Time
|
||||
holdOf string
|
||||
watching string
|
||||
cpuPrev *CPUTimes
|
||||
disabled string
|
||||
asserted []string
|
||||
}
|
||||
|
||||
func NewSwitcher(m *Machine, emit Emitter) *Switcher {
|
||||
return &Switcher{m: m, now: time.Now, emit: emit}
|
||||
}
|
||||
|
||||
// Model is the machine's product family as its firmware reports it.
|
||||
func (m *Machine) Model() string { return m.read("/sys/class/dmi/id/product_family") }
|
||||
|
||||
// ModelFamily is the family this module is written for.
|
||||
const ModelFamily = "ROG Zephyrus G14"
|
||||
|
||||
// ThisModel says whether the machine is the model this module is written for.
|
||||
func (m *Machine) ThisModel() bool { return strings.EqualFold(m.Model(), ModelFamily) }
|
||||
|
||||
// sampleCPU reads /proc/stat and answers the busy percentage since the previous reading.
|
||||
func (s *Switcher) sampleCPU() (float64, bool) {
|
||||
t, err := ParseProcStat(s.m.read("/proc/stat"))
|
||||
if err != nil {
|
||||
return 0, false
|
||||
}
|
||||
prev := s.cpuPrev
|
||||
s.cpuPrev = &t
|
||||
if prev == nil {
|
||||
return 0, false
|
||||
}
|
||||
return Busy(*prev, t)
|
||||
}
|
||||
|
||||
// Evaluate reads the power source, takes a CPU sample when asked and on mains, decides, and applies
|
||||
// the decision when it changed. It is the whole of one wake-up and what the tests drive.
|
||||
func (s *Switcher) Evaluate(ctx context.Context, sample bool) {
|
||||
if body := s.evaluate(ctx, sample); body != nil && s.emit != nil {
|
||||
// Outside the lock: publishing waits for the bus, and the tools that report the switcher
|
||||
// must not wait with it.
|
||||
if err := s.emit("profile.switched", body); err != nil {
|
||||
fmt.Fprintf(os.Stderr, "profile.switched not published: %v\n", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// evaluate is Evaluate under the lock; it answers the event to publish when it switched.
|
||||
func (s *Switcher) evaluate(ctx context.Context, sample bool) map[string]any {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
if s.disabled != "" {
|
||||
return nil
|
||||
}
|
||||
src := PowerSource(s.m.Supplies())
|
||||
now := s.now()
|
||||
first := s.source == nil
|
||||
if first || s.source.OnAC != src.OnAC {
|
||||
// A new power source: what was learnt about load on the other one says nothing here, and a
|
||||
// hold was for the source it was asked on.
|
||||
s.policy.Reset()
|
||||
s.cpuPrev = nil
|
||||
s.holdUntil = time.Time{}
|
||||
s.holdOf = ""
|
||||
s.sampleCPU() // the first reading on this source, so the next sample is a difference
|
||||
} else if sample && src.OnAC {
|
||||
if busy, ok := s.sampleCPU(); ok {
|
||||
s.policy.Observe(busy, now)
|
||||
}
|
||||
}
|
||||
s.source = &src
|
||||
d := s.policy.Decide(src)
|
||||
s.decision = &d
|
||||
// **Starting is not a reason to switch.** The runtime starts this process on every push that
|
||||
// changes a bundle; at boot and at every change of power source asusd has already applied its own
|
||||
// profile for the source, which AssertVendorSettings made the policy's. So the first decision is
|
||||
// taken as applied, and a profile someone chose by hand survives a push.
|
||||
if first {
|
||||
s.applied = d.Profile
|
||||
return nil
|
||||
}
|
||||
// Compared with what the switcher itself last applied, never with the profile in force: a profile
|
||||
// someone chose by hand is not a reason to act, a new decision is.
|
||||
if d.Profile == s.applied || now.Before(s.holdUntil) {
|
||||
return nil
|
||||
}
|
||||
from := s.applied
|
||||
if err := s.m.SetProfile(ctx, d.Profile); err != nil {
|
||||
s.lastError = err.Error() // and tried again at the next wake-up, since applied did not move
|
||||
return nil
|
||||
}
|
||||
s.lastError = ""
|
||||
s.applied, s.appliedAt = d.Profile, now
|
||||
body := map[string]any{"profile": d.Profile, "reason": d.Reason, "source": src.Source}
|
||||
if from != "" {
|
||||
body["from"] = from
|
||||
}
|
||||
return body
|
||||
}
|
||||
|
||||
// Hold keeps a profile chosen through the tool for a while: the switcher does not move it until the
|
||||
// hold ends or the power source changes.
|
||||
func (s *Switcher) Hold(profile string, d time.Duration) time.Time {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
if d <= 0 {
|
||||
s.holdUntil, s.holdOf = time.Time{}, ""
|
||||
return time.Time{}
|
||||
}
|
||||
s.holdUntil, s.holdOf = s.now().Add(d), profile
|
||||
return s.holdUntil
|
||||
}
|
||||
|
||||
// Run is the switcher's life: assert asusd's settings once, then wake on each power-supply event, on
|
||||
// each CPU sample while on mains, and at SafetyRecheck otherwise.
|
||||
func (s *Switcher) Run(ctx context.Context) {
|
||||
defer func() {
|
||||
if r := recover(); r != nil {
|
||||
s.mu.Lock()
|
||||
s.disabled = fmt.Sprintf("the switcher stopped on a fault: %v", r)
|
||||
s.mu.Unlock()
|
||||
fmt.Fprintln(os.Stderr, s.disabled)
|
||||
}
|
||||
}()
|
||||
if !s.m.ThisModel() {
|
||||
s.mu.Lock()
|
||||
s.disabled = fmt.Sprintf("this machine reports %q, not %q: the switcher does not act on another model",
|
||||
s.m.Model(), ModelFamily)
|
||||
s.mu.Unlock()
|
||||
fmt.Fprintln(os.Stderr, s.disabled)
|
||||
return
|
||||
}
|
||||
s.AssertVendorSettings(ctx)
|
||||
|
||||
events, err := listenPowerSupply(ctx)
|
||||
s.mu.Lock()
|
||||
if err != nil {
|
||||
s.watching = "polling every " + SampleEvery.String() + ": " + err.Error()
|
||||
} else {
|
||||
s.watching = "the kernel's power-supply events"
|
||||
}
|
||||
s.mu.Unlock()
|
||||
|
||||
s.Evaluate(ctx, false)
|
||||
timer := time.NewTimer(s.interval(err != nil))
|
||||
defer timer.Stop()
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case _, open := <-events:
|
||||
if !open {
|
||||
events = nil
|
||||
s.mu.Lock()
|
||||
s.watching = "polling every " + SampleEvery.String() + ": the uevent socket closed"
|
||||
s.mu.Unlock()
|
||||
err = fmt.Errorf("closed")
|
||||
continue
|
||||
}
|
||||
// Settle: an adapter change arrives as several events within a moment.
|
||||
time.Sleep(time.Second)
|
||||
s.Evaluate(ctx, false)
|
||||
case <-timer.C:
|
||||
s.Evaluate(ctx, true)
|
||||
timer.Reset(s.interval(err != nil))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// interval is how long to sleep: a CPU sample's period on mains (or with no events to wake on), the
|
||||
// safety recheck on battery.
|
||||
func (s *Switcher) interval(polling bool) time.Duration {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
if polling || s.source == nil || s.source.OnAC {
|
||||
return SampleEvery
|
||||
}
|
||||
return SafetyRecheck
|
||||
}
|
||||
|
||||
// AssertVendorSettings puts asusd's own settings where the module wants them, once at start: the
|
||||
// battery charge limit, and the profiles asusd itself switches to on mains and on battery, so that the
|
||||
// vendor daemon's own switching and this module's never disagree. Each is read first and set only if
|
||||
// it differs. A value changed later with a tool stands until the next start.
|
||||
func (s *Switcher) AssertVendorSettings(ctx context.Context) []string {
|
||||
var said []string
|
||||
if limit, err := s.m.ChargeLimit(ctx); err != nil {
|
||||
said = append(said, "charge limit not read: "+err.Error())
|
||||
} else if limit != ChargeLimitPercent {
|
||||
if _, err := s.m.Run(ctx, "asusctl", "battery", "limit", strconv.Itoa(ChargeLimitPercent)); err != nil {
|
||||
said = append(said, "charge limit not set: "+vendor("asusctl", err).Error())
|
||||
} else {
|
||||
said = append(said, fmt.Sprintf("charge limit %d%% → %d%%", limit, ChargeLimitPercent))
|
||||
}
|
||||
} else {
|
||||
said = append(said, fmt.Sprintf("charge limit already %d%%", ChargeLimitPercent))
|
||||
}
|
||||
p, err := s.m.Profile(ctx)
|
||||
if err != nil {
|
||||
said = append(said, "asusd's profiles not read: "+err.Error())
|
||||
} else {
|
||||
for _, want := range []struct{ flag, have, want, what string }{
|
||||
{"-a", p.OnAC, ProfileOnAC, "on mains"},
|
||||
{"-b", p.Battery, ProfileOnBattery, "on battery"},
|
||||
} {
|
||||
if want.have == "" || strings.EqualFold(want.have, want.want) {
|
||||
continue
|
||||
}
|
||||
if _, err := s.m.Run(ctx, "asusctl", "profile", "set", want.flag, want.want); err != nil {
|
||||
said = append(said, "asusd's profile "+want.what+" not set: "+err.Error())
|
||||
} else {
|
||||
said = append(said, fmt.Sprintf("asusd's profile %s %s → %s", want.what, want.have, want.want))
|
||||
}
|
||||
}
|
||||
}
|
||||
s.mu.Lock()
|
||||
s.asserted = said
|
||||
s.mu.Unlock()
|
||||
for _, line := range said {
|
||||
fmt.Fprintln(os.Stderr, line)
|
||||
}
|
||||
return said
|
||||
}
|
||||
|
||||
// SwitcherReport is the switcher's state as the profile-policy tool shows it.
|
||||
type SwitcherReport struct {
|
||||
Running bool `json:"running"`
|
||||
Disabled string `json:"disabled,omitempty"`
|
||||
Watching string `json:"woken_by,omitempty"`
|
||||
Source *Source `json:"source,omitempty"`
|
||||
Decision *Decision `json:"decision,omitempty"`
|
||||
Load Policy `json:"load"`
|
||||
LastApplied string `json:"last_applied,omitempty"`
|
||||
LastAppliedAt *time.Time `json:"last_applied_at,omitempty"`
|
||||
LastError string `json:"last_error,omitempty"`
|
||||
HeldUntil *time.Time `json:"held_until,omitempty"`
|
||||
Held string `json:"held_profile,omitempty"`
|
||||
AssertedAtStart []string `json:"asserted_at_start,omitempty"`
|
||||
}
|
||||
|
||||
func (s *Switcher) Report() SwitcherReport {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
r := SwitcherReport{
|
||||
Running: s.watching != "" && s.disabled == "", Disabled: s.disabled, Watching: s.watching,
|
||||
Source: s.source, Decision: s.decision, Load: s.policy, LastApplied: s.applied,
|
||||
LastAppliedAt: when(s.appliedAt), LastError: s.lastError, AssertedAtStart: s.asserted,
|
||||
}
|
||||
if s.now().Before(s.holdUntil) {
|
||||
r.HeldUntil, r.Held = when(s.holdUntil), s.holdOf
|
||||
}
|
||||
return r
|
||||
}
|
||||
|
||||
// when is a time for a report: absent rather than the zero time.
|
||||
func when(t time.Time) *time.Time {
|
||||
if t.IsZero() {
|
||||
return nil
|
||||
}
|
||||
return &t
|
||||
}
|
||||
@@ -1,190 +0,0 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"strconv"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestTheLoadMustBeSustainedToBoostAndToRelaxAndBetweenTheLinesNothingMoves(t *testing.T) {
|
||||
var p Policy
|
||||
at := time.Now()
|
||||
mains := Source{OnAC: true, Reason: "ACAD (Mains) is online"}
|
||||
for i := 0; i < SustainSamples-1; i++ {
|
||||
p.Observe(90, at)
|
||||
}
|
||||
if p.Decide(mains).Profile != ProfileOnAC {
|
||||
t.Fatal("boosted before the load was sustained")
|
||||
}
|
||||
p.Observe(35, at) // between the lines breaks the run
|
||||
p.Observe(90, at)
|
||||
if p.Boosted {
|
||||
t.Fatal("a broken run still counted")
|
||||
}
|
||||
for i := 0; i < SustainSamples; i++ {
|
||||
p.Observe(CPUHighPercent, at)
|
||||
}
|
||||
if d := p.Decide(mains); d.Profile != ProfileUnderLoad {
|
||||
t.Fatalf("%+v", d)
|
||||
}
|
||||
p.Observe(35, at)
|
||||
if !p.Boosted {
|
||||
t.Fatal("load between the lines relaxed the boost")
|
||||
}
|
||||
for i := 0; i < RelaxSamples; i++ {
|
||||
p.Observe(5, at)
|
||||
}
|
||||
if p.Decide(mains).Profile != ProfileOnAC {
|
||||
t.Fatal("did not relax after a sustained low")
|
||||
}
|
||||
p.Boosted = true
|
||||
if d := p.Decide(Source{OnAC: false, Reason: "BAT1 is discharging"}); d.Profile != ProfileOnBattery {
|
||||
t.Fatalf("battery: %+v", d)
|
||||
}
|
||||
}
|
||||
|
||||
func TestIOWaitIsIdle(t *testing.T) {
|
||||
a, err := ParseProcStat("cpu 100 0 100 700 100 0 0 0 0 0\ncpu0 1 2 3\n")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
b, _ := ParseProcStat("cpu 150 0 150 700 200 0 0 0 0 0\n")
|
||||
busy, ok := Busy(a, b)
|
||||
if !ok || busy != 50 {
|
||||
t.Fatalf("%v %v", busy, ok)
|
||||
}
|
||||
if _, ok := Busy(b, b); ok {
|
||||
t.Fatal("no time passed and a load was answered")
|
||||
}
|
||||
if _, err := ParseProcStat("intr 1 2"); err == nil {
|
||||
t.Fatal("a file without the cpu line was read")
|
||||
}
|
||||
}
|
||||
|
||||
func switcherOn(t *testing.T) (*fake, *Switcher, *[]map[string]any) {
|
||||
f := newFake(t)
|
||||
f.onMains()
|
||||
f.file("/proc/stat", "cpu 0 0 0 0 0 0 0 0\n")
|
||||
var emitted []map[string]any
|
||||
sw := NewSwitcher(f.machine(), func(_ string, body any) error {
|
||||
emitted = append(emitted, body.(map[string]any))
|
||||
return nil
|
||||
})
|
||||
return f, sw, &emitted
|
||||
}
|
||||
|
||||
func TestStartingIsNotAReasonToSwitch(t *testing.T) {
|
||||
f, sw, emitted := switcherOn(t)
|
||||
sw.Evaluate(context.Background(), false)
|
||||
if calls := f.callsLike("asusctl profile set"); len(calls) != 0 || len(*emitted) != 0 {
|
||||
t.Fatalf("the first decision acted: %v %v", calls, *emitted)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAChangeOfPowerSourceSwitchesOnceAndPublishesIt(t *testing.T) {
|
||||
f, sw, emitted := switcherOn(t)
|
||||
ctx := context.Background()
|
||||
sw.Evaluate(ctx, false)
|
||||
f.onBattery()
|
||||
sw.Evaluate(ctx, false)
|
||||
sw.Evaluate(ctx, true) // nothing changed: nothing done, and on battery nothing sampled
|
||||
if calls := f.callsLike("asusctl profile set"); len(calls) != 1 || calls[0] != "asusctl profile set Quiet" {
|
||||
t.Fatalf("%v", calls)
|
||||
}
|
||||
if len(*emitted) != 1 || (*emitted)[0]["profile"] != "Quiet" || (*emitted)[0]["from"] != "Balanced" {
|
||||
t.Fatalf("%v", *emitted)
|
||||
}
|
||||
f.onMains()
|
||||
sw.Evaluate(ctx, false)
|
||||
if calls := f.callsLike("asusctl profile set"); len(calls) != 2 || calls[1] != "asusctl profile set Balanced" {
|
||||
t.Fatalf("%v", calls)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSustainedLoadOnMainsBoostsFromSamples(t *testing.T) {
|
||||
f, sw, _ := switcherOn(t)
|
||||
ctx := context.Background()
|
||||
sw.Evaluate(ctx, false)
|
||||
var user int
|
||||
for i := 1; i <= SustainSamples; i++ {
|
||||
user += 90
|
||||
f.file("/proc/stat", "cpu "+itoa(user)+" 0 0 "+itoa(i*10)+" 0 0 0 0\n")
|
||||
sw.Evaluate(ctx, true)
|
||||
}
|
||||
if !f.called("asusctl profile set Performance") {
|
||||
t.Fatalf("%v", f.calls)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAHoldKeepsTheProfileUntilItEndsAndAFailureIsTriedAgain(t *testing.T) {
|
||||
f, sw, _ := switcherOn(t)
|
||||
ctx := context.Background()
|
||||
now := time.Now()
|
||||
sw.now = func() time.Time { return now }
|
||||
sw.Evaluate(ctx, false)
|
||||
f.onBattery()
|
||||
sw.Evaluate(ctx, false) // source change ends any hold; switches to Quiet
|
||||
sw.Hold("Performance", time.Hour)
|
||||
f.fails["asusctl profile set Balanced"] = errors.New("asusd is restarting")
|
||||
f.onMains()
|
||||
sw.Evaluate(ctx, false) // a change of source: the hold ends, the switch is attempted and fails
|
||||
if r := sw.Report(); r.LastError == "" || r.Held != "" {
|
||||
t.Fatalf("%+v", r)
|
||||
}
|
||||
delete(f.fails, "asusctl profile set Balanced")
|
||||
sw.Evaluate(ctx, false)
|
||||
if r := sw.Report(); r.LastApplied != "Balanced" || r.LastError != "" {
|
||||
t.Fatalf("not tried again: %+v", r)
|
||||
}
|
||||
// A hold on the same source keeps a new decision from acting until it ends.
|
||||
sw.Hold("Quiet", time.Hour)
|
||||
sw.policy.Boosted = true
|
||||
sw.Evaluate(ctx, false)
|
||||
if f.called("asusctl profile set Performance") {
|
||||
t.Fatal("switched during a hold")
|
||||
}
|
||||
now = now.Add(2 * time.Hour)
|
||||
sw.Evaluate(ctx, false)
|
||||
if !f.called("asusctl profile set Performance") {
|
||||
t.Fatal("did not act once the hold ended")
|
||||
}
|
||||
}
|
||||
|
||||
func TestAsusdsSettingsAreSetOnlyWhereTheyDiffer(t *testing.T) {
|
||||
f := newFake(t)
|
||||
f.answers["asusctl battery info"] = "Current battery charge limit: 100%\n"
|
||||
f.answers["asusctl profile get"] = "Active profile: Balanced\nAC profile Performance\nBattery profile Quiet\n"
|
||||
sw := NewSwitcher(f.machine(), nil)
|
||||
sw.AssertVendorSettings(context.Background())
|
||||
if !f.called("asusctl battery limit 80") || !f.called("asusctl profile set -a Balanced") || f.called("asusctl profile set -b Quiet") {
|
||||
t.Fatalf("%v", f.calls)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTheSwitcherDoesNotActOnAnotherModel(t *testing.T) {
|
||||
f := newFake(t)
|
||||
f.file("/sys/class/dmi/id/product_family", "ROG Strix\n")
|
||||
sw := NewSwitcher(f.machine(), nil)
|
||||
done := make(chan struct{})
|
||||
go func() { sw.Run(context.Background()); close(done) }()
|
||||
select {
|
||||
case <-done:
|
||||
case <-time.After(2 * time.Second):
|
||||
t.Fatal("the switcher ran on another model")
|
||||
}
|
||||
if r := sw.Report(); r.Running || r.Disabled == "" || len(f.calls) != 0 {
|
||||
t.Fatalf("%+v %v", r, f.calls)
|
||||
}
|
||||
}
|
||||
|
||||
func TestOnlyPowerSupplyUeventsWake(t *testing.T) {
|
||||
yes := []byte("change@/devices/LNXSYSTM:00/ACPI0003:00/power_supply/ACAD\x00ACTION=change\x00SUBSYSTEM=power_supply\x00POWER_SUPPLY_ONLINE=0\x00")
|
||||
no := []byte("change@/devices/virtual/net/wlan0\x00ACTION=change\x00SUBSYSTEM=net\x00")
|
||||
if !powerSupplyEvent(yes) || powerSupplyEvent(no) {
|
||||
t.Fatal("the uevent filter")
|
||||
}
|
||||
}
|
||||
|
||||
func itoa(n int) string { return strconv.Itoa(n) }
|
||||
@@ -1,168 +0,0 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"path"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// Sensor is one temperature, fan or power reading from hwmon.
|
||||
type Sensor struct {
|
||||
Chip string `json:"chip"`
|
||||
Label string `json:"label"`
|
||||
Value float64 `json:"value"`
|
||||
}
|
||||
|
||||
// DGPU is the discrete GPU as the PCI bus and its driver see it.
|
||||
type DGPU struct {
|
||||
Address string `json:"pci_address"`
|
||||
Runtime string `json:"runtime_status"`
|
||||
Name string `json:"name,omitempty"`
|
||||
TempC *float64 `json:"temp_c,omitempty"`
|
||||
PowerW *float64 `json:"power_w,omitempty"`
|
||||
PState string `json:"pstate,omitempty"`
|
||||
Note string `json:"note,omitempty"`
|
||||
}
|
||||
|
||||
// hwmon reads every hwmon reading of one kind: "temp" (°C), "fan" (RPM) or "power" (W).
|
||||
func (m *Machine) hwmon(kind string) []Sensor {
|
||||
var out []Sensor
|
||||
for _, dir := range m.glob("/sys/class/hwmon/hwmon*") {
|
||||
chip := m.read(dir + "/name")
|
||||
inputs := m.glob(dir + "/" + kind + "*_input")
|
||||
if kind == "power" {
|
||||
inputs = append(inputs, m.glob(dir+"/power*_average")...)
|
||||
}
|
||||
for _, in := range inputs {
|
||||
v, ok := m.readInt(in)
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
base := path.Base(in)
|
||||
stem := base[:strings.LastIndex(base, "_")]
|
||||
label := m.read(dir + "/" + stem + "_label")
|
||||
if label == "" {
|
||||
label = base
|
||||
} else if strings.HasSuffix(base, "_average") {
|
||||
label += " (average)"
|
||||
}
|
||||
value := float64(v)
|
||||
switch kind {
|
||||
case "temp":
|
||||
value = round1(value / 1000)
|
||||
case "power":
|
||||
value = round1(value / 1e6)
|
||||
}
|
||||
out = append(out, Sensor{Chip: chip, Label: label, Value: value})
|
||||
}
|
||||
}
|
||||
sort.Slice(out, func(i, j int) bool {
|
||||
if out[i].Chip != out[j].Chip {
|
||||
return out[i].Chip < out[j].Chip
|
||||
}
|
||||
return out[i].Label < out[j].Label
|
||||
})
|
||||
return out
|
||||
}
|
||||
|
||||
// dgpu finds the NVIDIA display controller and, only when it is already awake, asks its driver for
|
||||
// its temperature and draw. **Asking wakes it**: nvidia-smi brings a suspended GPU out of D3, which
|
||||
// is the power a reading of power draw should not cost.
|
||||
func (m *Machine) dgpu(ctx context.Context) *DGPU {
|
||||
for _, dir := range m.glob("/sys/bus/pci/devices/*") {
|
||||
if m.read(dir+"/vendor") != "0x10de" || !strings.HasPrefix(m.read(dir+"/class"), "0x03") {
|
||||
continue
|
||||
}
|
||||
g := &DGPU{Address: path.Base(dir), Runtime: m.read(dir + "/power/runtime_status")}
|
||||
if g.Runtime != "active" {
|
||||
g.Note = "the discrete GPU is " + g.Runtime + "; not woken to be read"
|
||||
return g
|
||||
}
|
||||
out, err := m.Run(ctx, "nvidia-smi", "--query-gpu=name,temperature.gpu,power.draw,pstate", "--format=csv,noheader,nounits")
|
||||
if err != nil {
|
||||
g.Note = "nvidia-smi: " + err.Error()
|
||||
return g
|
||||
}
|
||||
f := strings.Split(strings.TrimSpace(strings.SplitN(out, "\n", 2)[0]), ",")
|
||||
if len(f) >= 4 {
|
||||
g.Name = strings.TrimSpace(f[0])
|
||||
if t, err := strconv.ParseFloat(strings.TrimSpace(f[1]), 64); err == nil {
|
||||
g.TempC = &t
|
||||
}
|
||||
if w, err := strconv.ParseFloat(strings.TrimSpace(f[2]), 64); err == nil {
|
||||
w = round1(w)
|
||||
g.PowerW = &w
|
||||
}
|
||||
g.PState = strings.TrimSpace(f[3])
|
||||
}
|
||||
return g
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Thermals is what the thermals tool answers.
|
||||
type Thermals struct {
|
||||
Temperatures []Sensor `json:"temperatures_c"`
|
||||
Fans []Sensor `json:"fans_rpm"`
|
||||
DGPU *DGPU `json:"dgpu,omitempty"`
|
||||
Profile string `json:"platform_profile,omitempty"`
|
||||
Hottest *Sensor `json:"hottest,omitempty"`
|
||||
}
|
||||
|
||||
func (m *Machine) Thermals(ctx context.Context) Thermals {
|
||||
t := Thermals{Temperatures: m.hwmon("temp"), Fans: m.hwmon("fan"), DGPU: m.dgpu(ctx),
|
||||
Profile: m.read("/sys/firmware/acpi/platform_profile")}
|
||||
if t.Temperatures == nil {
|
||||
t.Temperatures = []Sensor{}
|
||||
}
|
||||
if t.Fans == nil {
|
||||
t.Fans = []Sensor{}
|
||||
}
|
||||
for i := range t.Temperatures {
|
||||
if t.Hottest == nil || t.Temperatures[i].Value > t.Hottest.Value {
|
||||
h := t.Temperatures[i]
|
||||
t.Hottest = &h
|
||||
}
|
||||
}
|
||||
return t
|
||||
}
|
||||
|
||||
// PowerDraw is what the power-draw tool answers.
|
||||
type PowerDraw struct {
|
||||
Source Source `json:"source"`
|
||||
BatteryW *float64 `json:"battery_w,omitempty"`
|
||||
BatteryFlow string `json:"battery_flow,omitempty"`
|
||||
CPUPackageW *float64 `json:"apu_package_w,omitempty"`
|
||||
DGPU *DGPU `json:"dgpu,omitempty"`
|
||||
Note string `json:"note"`
|
||||
}
|
||||
|
||||
func (m *Machine) PowerDraw(ctx context.Context) PowerDraw {
|
||||
p := PowerDraw{Source: PowerSource(m.Supplies()), DGPU: m.dgpu(ctx),
|
||||
Note: "on battery, battery_w is what the whole machine draws; on mains it is only what the battery takes or gives"}
|
||||
for _, b := range m.Batteries() {
|
||||
if b.PowerW != nil {
|
||||
w := *b.PowerW
|
||||
p.BatteryW = &w
|
||||
switch strings.ToLower(b.Status) {
|
||||
case "discharging":
|
||||
p.BatteryFlow = "discharging"
|
||||
case "charging":
|
||||
p.BatteryFlow = "charging"
|
||||
default:
|
||||
p.BatteryFlow = strings.ToLower(b.Status)
|
||||
}
|
||||
break
|
||||
}
|
||||
}
|
||||
// The integrated GPU's hwmon reports the whole APU's package power (PPT) on this model.
|
||||
for _, s := range m.hwmon("power") {
|
||||
if s.Chip == "amdgpu" && s.Label == "PPT" {
|
||||
w := s.Value
|
||||
p.CPUPackageW = &w
|
||||
}
|
||||
}
|
||||
return p
|
||||
}
|
||||
@@ -1,308 +0,0 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"math"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
stdio "git.novox.be/novox/mesh-sdk/go"
|
||||
)
|
||||
|
||||
// Tools is the module's tools, over one machine and its switcher.
|
||||
func Tools(m *Machine, sw *Switcher) []stdio.Tool {
|
||||
ctx := context.Background
|
||||
return []stdio.Tool{
|
||||
{
|
||||
Name: "zephyrus_brightness",
|
||||
Description: "Read or set the internal panel's and the keyboard's backlight. With no argument, reads both. " +
|
||||
"panel is a percentage (40) or a step (+5, -10), never below 1 %; keyboard is off, low, med, high, 0-3, + or -.",
|
||||
Input: map[string]any{
|
||||
"panel": map[string]any{"type": "string", "description": "percentage or step, e.g. 40, +5, -10"},
|
||||
"keyboard": map[string]any{"type": "string", "description": "off, low, med, high, 0-3, + or -"},
|
||||
},
|
||||
Run: func(args map[string]any) (any, error) {
|
||||
out := map[string]any{}
|
||||
if p := str(args, "panel"); p != "" {
|
||||
got, err := m.SetPanel(ctx(), p)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out["panel"] = got
|
||||
} else if got, err := m.PanelBrightness(); err == nil {
|
||||
out["panel"] = got
|
||||
} else {
|
||||
out["panel_error"] = err.Error()
|
||||
}
|
||||
if k := str(args, "keyboard"); k != "" {
|
||||
got, err := m.SetKeyboard(ctx(), k)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out["keyboard"] = got
|
||||
} else if got, err := m.KeyboardBrightness(); err == nil {
|
||||
out["keyboard"] = got
|
||||
} else {
|
||||
out["keyboard_error"] = err.Error()
|
||||
}
|
||||
return out, nil
|
||||
},
|
||||
},
|
||||
{
|
||||
Name: "zephyrus_battery",
|
||||
Description: "The battery: charge, energy, health (full against design), cycles, the charge limit, the power it gives or takes, and time left when discharging.",
|
||||
Run: func(map[string]any) (any, error) {
|
||||
return map[string]any{"source": PowerSource(m.Supplies()), "batteries": orEmpty(m.Batteries())}, nil
|
||||
},
|
||||
},
|
||||
{
|
||||
Name: "zephyrus_charge_limit",
|
||||
Description: fmt.Sprintf("Read or set the battery charge limit through asusd. limit is 20-100; oneshot charges to full once "+
|
||||
"and goes back to the limit. The module asserts %d %% again when its process next starts.", ChargeLimitPercent),
|
||||
Input: map[string]any{
|
||||
"limit": map[string]any{"type": "integer", "description": "20-100"},
|
||||
"oneshot": map[string]any{"type": "boolean", "description": "charge to full once, keeping the limit"},
|
||||
},
|
||||
Run: func(args map[string]any) (any, error) { return ChargeLimitTool(ctx(), m, args) },
|
||||
},
|
||||
{
|
||||
Name: "zephyrus_gpu_mode",
|
||||
Description: "Read or set the hybrid GPU's mode through supergfxd: Integrated, Hybrid or AsusMuxDgpu as the machine supports. " +
|
||||
"Answers the mode, the discrete GPU's power state, any pending mode and the action it waits for (a logout, a reboot), " +
|
||||
"and whether asusd will switch it again on the next change of power source.",
|
||||
Input: map[string]any{
|
||||
"mode": map[string]any{"type": "string", "description": "a supported mode, e.g. Integrated or Hybrid"},
|
||||
},
|
||||
Run: func(args map[string]any) (any, error) { return GPUModeTool(ctx(), m, args) },
|
||||
},
|
||||
{
|
||||
Name: "zephyrus_profile",
|
||||
Description: "Read or set the platform profile (Quiet, Balanced, Performance) through asusd. A profile set here is held " +
|
||||
fmt.Sprintf("for hold_minutes (default %d, 0 for none) before the module's switcher may move it; a change of power source ends the hold.", int(DefaultHold.Minutes())),
|
||||
Input: map[string]any{
|
||||
"profile": map[string]any{"type": "string", "enum": Profiles},
|
||||
"hold_minutes": map[string]any{"type": "integer", "description": "how long the switcher leaves it (default 60, at most 1440)"},
|
||||
},
|
||||
Run: func(args map[string]any) (any, error) { return ProfileTool(ctx(), m, sw, args) },
|
||||
},
|
||||
{
|
||||
Name: "zephyrus_thermals",
|
||||
Description: "Every temperature and fan the hardware reports (°C, RPM), the hottest, the platform profile, and the discrete GPU's temperature when it is awake (it is not woken to be read).",
|
||||
Run: func(map[string]any) (any, error) { return m.Thermals(ctx()), nil },
|
||||
},
|
||||
{
|
||||
Name: "zephyrus_power_draw",
|
||||
Description: "What the machine draws: the battery's flow in watts, the APU's package power, the discrete GPU's draw when awake, and the power source with the reason it was decided.",
|
||||
Run: func(map[string]any) (any, error) { return m.PowerDraw(ctx()), nil },
|
||||
},
|
||||
{
|
||||
Name: "zephyrus_profile_policy",
|
||||
Description: "What the module's profile switcher would choose now and why: the power source, recent CPU load against the thresholds, " +
|
||||
"the decision, the profile in force, any hold, what woke it, and what it asserted in asusd at start.",
|
||||
Run: func(map[string]any) (any, error) { return PolicyTool(ctx(), m, sw), nil },
|
||||
},
|
||||
{
|
||||
Name: "zephyrus_fan_curves",
|
||||
Description: "The fan curves asusd holds for each profile (or one profile): per fan, eight points of temperature and duty.",
|
||||
Input: map[string]any{
|
||||
"profile": map[string]any{"type": "string", "enum": Profiles},
|
||||
},
|
||||
Run: func(args map[string]any) (any, error) { return FanCurvesTool(ctx(), m, args) },
|
||||
},
|
||||
{
|
||||
Name: "zephyrus_check",
|
||||
Description: "Check what this module expects of the machine: the model, the vendor packages and daemons, the NVIDIA options in force, " +
|
||||
"suspend and resume, the charge limit, one authority each over the profile and the GPU mode, and the predecessor's leftovers. Says what it did not check.",
|
||||
Run: func(map[string]any) (any, error) { return m.Check(ctx(), sw), nil },
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// ChargeLimitTool reads or sets the limit.
|
||||
func ChargeLimitTool(ctx context.Context, m *Machine, args map[string]any) (any, error) {
|
||||
out := map[string]any{"module_limit_percent": ChargeLimitPercent}
|
||||
if v, given := args["limit"]; given && v != nil {
|
||||
n, err := whole(v, "limit")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if n < 20 || n > 100 {
|
||||
return nil, fmt.Errorf("limit %d is outside 20-100", n)
|
||||
}
|
||||
if _, err := m.Run(ctx, "asusctl", "battery", "limit", strconv.Itoa(n)); err != nil {
|
||||
return nil, vendor("asusctl", err)
|
||||
}
|
||||
out["set"] = n
|
||||
}
|
||||
if b, _ := args["oneshot"].(bool); b {
|
||||
if _, err := m.Run(ctx, "asusctl", "battery", "oneshot"); err != nil {
|
||||
return nil, vendor("asusctl", err)
|
||||
}
|
||||
out["oneshot"] = "charging to full once; the limit returns after"
|
||||
}
|
||||
if n, err := m.ChargeLimit(ctx); err == nil {
|
||||
out["asusd_limit_percent"] = n
|
||||
} else {
|
||||
out["asusd_error"] = err.Error()
|
||||
}
|
||||
for _, b := range m.Batteries() {
|
||||
if b.LimitPercent != nil {
|
||||
out["kernel_limit_percent"] = *b.LimitPercent
|
||||
}
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// GPUModeTool reads or sets the GPU mode.
|
||||
func GPUModeTool(ctx context.Context, m *Machine, args map[string]any) (any, error) {
|
||||
g, err := m.GPU(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out := map[string]any{}
|
||||
if want := str(args, "mode"); want != "" {
|
||||
mode := ""
|
||||
for _, s := range g.Supported {
|
||||
if strings.EqualFold(s, want) {
|
||||
mode = s
|
||||
}
|
||||
}
|
||||
if mode == "" {
|
||||
return nil, fmt.Errorf("mode %q is not one this machine supports (%s)", want, strings.Join(g.Supported, ", "))
|
||||
}
|
||||
said, err := m.Run(ctx, "supergfxctl", "-m", mode)
|
||||
if err != nil {
|
||||
return nil, vendor("supergfxctl", err)
|
||||
}
|
||||
out["requested"] = mode
|
||||
if s := strings.TrimSpace(said); s != "" {
|
||||
out["supergfxctl_said"] = s
|
||||
}
|
||||
if g, err = m.GPU(ctx); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
out["gpu"] = g
|
||||
if c := m.Asusd(); c != nil && (c.ACCommand != "" || c.BatteryCommand != "") {
|
||||
out["asusd_switches_it"] = map[string]string{"on_ac": c.ACCommand, "on_battery": c.BatteryCommand,
|
||||
"note": "asusd runs these on every change of power source, so a mode set here lasts until the next one"}
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// ProfileTool reads or sets the profile.
|
||||
func ProfileTool(ctx context.Context, m *Machine, sw *Switcher, args map[string]any) (any, error) {
|
||||
out := map[string]any{}
|
||||
if want := str(args, "profile"); want != "" {
|
||||
p, err := canonicalProfile(want)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
hold := DefaultHold
|
||||
if v, given := args["hold_minutes"]; given && v != nil {
|
||||
n, err := whole(v, "hold_minutes")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if n < 0 {
|
||||
return nil, fmt.Errorf("hold_minutes must not be negative")
|
||||
}
|
||||
hold = time.Duration(min(n, 1440)) * time.Minute
|
||||
}
|
||||
if err := m.SetProfile(ctx, p); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out["set"] = p
|
||||
if sw != nil {
|
||||
if until := sw.Hold(p, hold); !until.IsZero() {
|
||||
out["held_until"] = until
|
||||
}
|
||||
}
|
||||
}
|
||||
state, err := m.Profile(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out["profile"] = state
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// PolicyTool reports the switcher and, independently of it, what the policy says now.
|
||||
func PolicyTool(ctx context.Context, m *Machine, sw *Switcher) any {
|
||||
out := map[string]any{
|
||||
"thresholds": map[string]any{
|
||||
"on_battery": ProfileOnBattery, "on_ac": ProfileOnAC, "under_load": ProfileUnderLoad,
|
||||
"cpu_high_percent": CPUHighPercent, "cpu_low_percent": CPULowPercent,
|
||||
"sample_every": SampleEvery.String(), "sustain_samples": SustainSamples, "relax_samples": RelaxSamples,
|
||||
"set_by": "constants until settings exist (novox/hq issue 168)",
|
||||
},
|
||||
}
|
||||
if sw != nil {
|
||||
out["switcher"] = sw.Report()
|
||||
} else {
|
||||
var p Policy
|
||||
out["decision_now"] = p.Decide(PowerSource(m.Supplies()))
|
||||
}
|
||||
if state, err := m.Profile(ctx); err == nil {
|
||||
out["in_force"] = state
|
||||
} else {
|
||||
out["in_force_error"] = err.Error()
|
||||
}
|
||||
if pid, ok := m.predecessorProcess("auto-profile"); ok {
|
||||
out["second_switcher"] = fmt.Sprintf("the predecessor's auto-profile still runs (pid %d) and overrides this every five seconds", pid)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// FanCurvesTool reads asusd's fan curves.
|
||||
func FanCurvesTool(ctx context.Context, m *Machine, args map[string]any) (any, error) {
|
||||
profiles := Profiles
|
||||
if want := str(args, "profile"); want != "" {
|
||||
p, err := canonicalProfile(want)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
profiles = []string{p}
|
||||
}
|
||||
out := map[string]any{}
|
||||
for _, p := range profiles {
|
||||
said, err := m.Run(ctx, "asusctl", "fan-curve", "--mod-profile", strings.ToLower(p))
|
||||
if err != nil {
|
||||
return nil, vendor("asusctl", err)
|
||||
}
|
||||
out[p] = orEmpty(ParseFanCurves(said))
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func str(args map[string]any, key string) string {
|
||||
s, _ := args[key].(string)
|
||||
return strings.TrimSpace(s)
|
||||
}
|
||||
|
||||
// whole is an integer argument given as a JSON number or a numeric string.
|
||||
func whole(v any, key string) (int, error) {
|
||||
switch n := v.(type) {
|
||||
case float64:
|
||||
if n != math.Trunc(n) {
|
||||
return 0, fmt.Errorf("%s must be a whole number, not %v", key, n)
|
||||
}
|
||||
return int(n), nil
|
||||
case string:
|
||||
i, err := strconv.Atoi(strings.TrimSpace(n))
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("%s must be a whole number, not %q", key, n)
|
||||
}
|
||||
return i, nil
|
||||
}
|
||||
return 0, fmt.Errorf("%s must be a whole number", key)
|
||||
}
|
||||
|
||||
func orEmpty[T any](s []T) []T {
|
||||
if s == nil {
|
||||
return []T{}
|
||||
}
|
||||
return s
|
||||
}
|
||||
@@ -1,72 +0,0 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"fmt"
|
||||
"syscall"
|
||||
)
|
||||
|
||||
// The kernel announces every change of a power supply — an adapter plugged or pulled, a battery
|
||||
// starting or stopping to discharge — as a uevent on a netlink socket that any account may listen
|
||||
// on. That is the event the switcher reacts to: no daemon, no bus client, no polling.
|
||||
//
|
||||
// upower re-announces the same changes on the system bus, and listening there would need a D-Bus
|
||||
// client in the bundle; udev's re-broadcast (netlink group 2) carries a libudev header. The kernel's
|
||||
// own group (1) is the source both of them read.
|
||||
|
||||
// powerSupplyEvent says whether a uevent is about a power supply.
|
||||
func powerSupplyEvent(msg []byte) bool {
|
||||
for _, field := range bytes.Split(msg, []byte{0}) {
|
||||
if bytes.Equal(field, []byte("SUBSYSTEM=power_supply")) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// listenPowerSupply opens the kernel's uevent socket and sends on the channel for each power-supply
|
||||
// event, never blocking: a burst of events is one wake-up. It stops when ctx ends.
|
||||
func listenPowerSupply(ctx context.Context) (<-chan struct{}, error) {
|
||||
fd, err := syscall.Socket(syscall.AF_NETLINK, syscall.SOCK_RAW|syscall.SOCK_CLOEXEC, syscall.NETLINK_KOBJECT_UEVENT)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("opening the kernel's uevent socket: %w", err)
|
||||
}
|
||||
if err := syscall.Bind(fd, &syscall.SockaddrNetlink{Family: syscall.AF_NETLINK, Groups: 1}); err != nil {
|
||||
syscall.Close(fd)
|
||||
return nil, fmt.Errorf("joining the kernel's uevent group: %w", err)
|
||||
}
|
||||
events := make(chan struct{}, 1)
|
||||
go func() {
|
||||
<-ctx.Done()
|
||||
syscall.Close(fd)
|
||||
}()
|
||||
go func() {
|
||||
defer close(events)
|
||||
buf := make([]byte, 64*1024)
|
||||
for {
|
||||
n, _, err := syscall.Recvfrom(fd, buf, 0)
|
||||
if err != nil {
|
||||
if err == syscall.EINTR || err == syscall.ENOBUFS {
|
||||
// ENOBUFS: events were dropped. Treat it as one, since a dropped one may have
|
||||
// been the adapter.
|
||||
if err == syscall.ENOBUFS {
|
||||
select {
|
||||
case events <- struct{}{}:
|
||||
default:
|
||||
}
|
||||
}
|
||||
continue
|
||||
}
|
||||
return
|
||||
}
|
||||
if powerSupplyEvent(buf[:n]) {
|
||||
select {
|
||||
case events <- struct{}{}:
|
||||
default:
|
||||
}
|
||||
}
|
||||
}
|
||||
}()
|
||||
return events, nil
|
||||
}
|
||||
@@ -1,33 +0,0 @@
|
||||
#!/bin/bash
|
||||
# zephyrus-backlight + | - | PERCENT — step or set the internal panel's backlight, never below 1 %.
|
||||
# Shipped by the mesh's asus-zephyrus-g14 module; edit the catalogue.
|
||||
#
|
||||
# The panel is the backlight beneath the eDP connector, not a name: in hybrid mode this model also
|
||||
# registers the discrete GPU's backlight (nvidia_0), which moves nothing. Writable by the video group
|
||||
# through the module's udev rule, so the vendor-key trigger needs no root.
|
||||
set -u
|
||||
STEP=5
|
||||
dev=""
|
||||
for d in /sys/class/backlight/*; do
|
||||
[ -e "$d" ] || continue
|
||||
case "$(readlink -f "$d")" in *-eDP-*) dev=$d; break ;; esac
|
||||
done
|
||||
if [ -z "$dev" ]; then
|
||||
for d in /sys/class/backlight/*; do [ -e "$d" ] && { dev=$d; break; }; done
|
||||
fi
|
||||
[ -n "$dev" ] || { echo "zephyrus-backlight: no backlight" >&2; exit 1; }
|
||||
cur=$(cat "$dev/brightness")
|
||||
max=$(cat "$dev/max_brightness")
|
||||
pct=$(( cur * 100 / max ))
|
||||
case "${1:-}" in
|
||||
+|up|Up) pct=$(( pct + STEP )) ;;
|
||||
-|down|Down) pct=$(( pct - STEP )) ;;
|
||||
''|*[!0-9]*) echo "usage: zephyrus-backlight + | - | PERCENT" >&2; exit 2 ;;
|
||||
*) pct=$1 ;;
|
||||
esac
|
||||
(( pct < 1 )) && pct=1
|
||||
(( pct > 100 )) && pct=100
|
||||
new=$(( max * pct / 100 ))
|
||||
(( new < 1 )) && new=1
|
||||
printf '%s' "$new" >"$dev/brightness" || exit 1
|
||||
exec "$(dirname "$0")/zephyrus-notify" 5555 "Brightness: ${pct}%"
|
||||
@@ -1,12 +0,0 @@
|
||||
#!/bin/bash
|
||||
# zephyrus-notify ID SUMMARY — a short desktop notification that replaces the previous one with the
|
||||
# same ID, through the session's notification service on its bus. busctl is the service manager's
|
||||
# own client, so nothing is installed for it. Shipped by the mesh's asus-zephyrus-g14 module.
|
||||
set -u
|
||||
id=${1:-0}
|
||||
summary=${2:-}
|
||||
uid=$(id -u)
|
||||
DBUS_SESSION_BUS_ADDRESS="unix:path=/run/user/${uid}/bus" \
|
||||
busctl --user call org.freedesktop.Notifications /org/freedesktop/Notifications \
|
||||
org.freedesktop.Notifications Notify susssasa{sv}i \
|
||||
asus-zephyrus-g14 "$id" "" "$summary" "" 0 1 urgency y 0 1500 >/dev/null 2>&1 || true
|
||||
@@ -1,38 +0,0 @@
|
||||
#!/bin/bash
|
||||
# zephyrus-session COMMAND [ARG...] — run a command in the operator's graphical session from outside
|
||||
# it: from a vendor-key trigger, which triggerhappy runs as the operator's account but with none of
|
||||
# the session's environment. Shipped by the mesh's asus-zephyrus-g14 module; edit the catalogue.
|
||||
#
|
||||
# What it replaces: the predecessor's `as-user`, which triggerhappy ran as root and which `su`-ed to
|
||||
# a named person with a hard-coded user id and display, and sourced a file of secrets on the way.
|
||||
# Here the account is whoever runs it, the bus is that account's, and the display is the one the
|
||||
# account's own session uses. Nothing is sourced.
|
||||
set -u
|
||||
uid=$(id -u)
|
||||
export XDG_RUNTIME_DIR="/run/user/${uid}"
|
||||
export DBUS_SESSION_BUS_ADDRESS="unix:path=${XDG_RUNTIME_DIR}/bus"
|
||||
home=$(getent passwd "$uid" | cut -d: -f6)
|
||||
[ -n "$home" ] && export HOME="$home"
|
||||
if [ -z "${DISPLAY:-}" ]; then
|
||||
# The login manager may not record the display with logind; any process of this account that
|
||||
# has one says which it is.
|
||||
for s in $(loginctl list-sessions --no-legend 2>/dev/null | awk -v u="$uid" '$2 == u { print $1 }'); do
|
||||
d=$(loginctl show-session "$s" -p Display --value 2>/dev/null)
|
||||
if [ -n "$d" ]; then export DISPLAY="$d"; break; fi
|
||||
done
|
||||
fi
|
||||
if [ -z "${DISPLAY:-}" ]; then
|
||||
for pid in $(pgrep -u "$uid" 2>/dev/null); do
|
||||
env=$(tr '\0' '\n' <"/proc/$pid/environ" 2>/dev/null) || continue
|
||||
d=$(printf '%s\n' "$env" | sed -n 's/^DISPLAY=//p' | head -n1)
|
||||
if [ -n "$d" ]; then
|
||||
export DISPLAY="$d"
|
||||
a=$(printf '%s\n' "$env" | sed -n 's/^XAUTHORITY=//p' | head -n1)
|
||||
[ -n "$a" ] && export XAUTHORITY="$a"
|
||||
break
|
||||
fi
|
||||
done
|
||||
fi
|
||||
: "${XAUTHORITY:=${HOME}/.Xauthority}"
|
||||
export XAUTHORITY
|
||||
exec "$@"
|
||||
@@ -1,29 +0,0 @@
|
||||
#!/bin/bash
|
||||
# zephyrus-touchpad reset | toggle — apply the touchpad's settings again, or switch it on or off.
|
||||
# Shipped by the mesh's asus-zephyrus-g14 module; edit the catalogue.
|
||||
#
|
||||
# The settings themselves are an X input class (/etc/X11/xorg.conf.d/30-asus-zephyrus-g14-touchpad.conf),
|
||||
# which X applies every time the device appears — after a resume too, which is what the predecessor's
|
||||
# sleep hook existed for. This is the manual form, bound to the touchpad key.
|
||||
set -u
|
||||
here=$(dirname "$0")
|
||||
name=$("$here/zephyrus-session" xinput list --name-only 2>/dev/null | grep -m1 -i 'touchpad')
|
||||
[ -n "$name" ] || { echo "zephyrus-touchpad: no touchpad in this session" >&2; exit 1; }
|
||||
x() { "$here/zephyrus-session" xinput "$@"; }
|
||||
case "${1:-reset}" in
|
||||
reset)
|
||||
x set-prop "$name" "libinput Tapping Enabled" 1
|
||||
x set-prop "$name" "libinput Natural Scrolling Enabled" 1
|
||||
x set-prop "$name" "libinput Accel Speed" 0.15
|
||||
x enable "$name"
|
||||
"$here/zephyrus-session" "$here/zephyrus-notify" 7779 "Touchpad: reset"
|
||||
;;
|
||||
toggle)
|
||||
if x list-props "$name" | grep -q 'Device Enabled ([0-9]*):[[:space:]]*1'; then
|
||||
x disable "$name"; "$here/zephyrus-session" "$here/zephyrus-notify" 7779 "Touchpad: off"
|
||||
else
|
||||
x enable "$name"; "$here/zephyrus-session" "$here/zephyrus-notify" 7779 "Touchpad: on"
|
||||
fi
|
||||
;;
|
||||
*) echo "usage: zephyrus-touchpad reset | toggle" >&2; exit 2 ;;
|
||||
esac
|
||||
@@ -1,5 +0,0 @@
|
||||
module asuszephyrusg14
|
||||
|
||||
go 1.22
|
||||
|
||||
require git.novox.be/novox/mesh-sdk/go v0.1.6
|
||||
@@ -1,2 +0,0 @@
|
||||
git.novox.be/novox/mesh-sdk/go v0.1.6 h1:9qzdYONYbJdWcu6sxQcq9v1LI0JxcfkiKYkMUzJSkVQ=
|
||||
git.novox.be/novox/mesh-sdk/go v0.1.6/go.mod h1:GFuZUElBZ9A++mxgIKo97aXXo+kV0uJ/UkbhQPPIbrY=
|
||||
@@ -1,254 +0,0 @@
|
||||
{
|
||||
"module": "asus-zephyrus-g14",
|
||||
"version": "1",
|
||||
"capabilities": [
|
||||
"package-manager",
|
||||
"service-manager"
|
||||
],
|
||||
"emits": [
|
||||
"profile.switched"
|
||||
],
|
||||
"tools": [
|
||||
"zephyrus_brightness",
|
||||
"zephyrus_battery",
|
||||
"zephyrus_charge_limit",
|
||||
"zephyrus_gpu_mode",
|
||||
"zephyrus_profile",
|
||||
"zephyrus_thermals",
|
||||
"zephyrus_power_draw",
|
||||
"zephyrus_profile_policy",
|
||||
"zephyrus_fan_curves",
|
||||
"zephyrus_check"
|
||||
],
|
||||
"resources": [
|
||||
{
|
||||
"id": "asusctl",
|
||||
"type": "package",
|
||||
"package": "asusctl"
|
||||
},
|
||||
{
|
||||
"id": "playerctl",
|
||||
"type": "package",
|
||||
"package": "playerctl"
|
||||
},
|
||||
{
|
||||
"id": "xinput",
|
||||
"type": "package",
|
||||
"package": "xorg-xinput"
|
||||
},
|
||||
{
|
||||
"id": "asusd",
|
||||
"type": "service",
|
||||
"unit": "asusd.service",
|
||||
"state": "running"
|
||||
},
|
||||
{
|
||||
"id": "supergfxd",
|
||||
"type": "service",
|
||||
"unit": "supergfxd.service",
|
||||
"state": "running",
|
||||
"boot": "enabled"
|
||||
},
|
||||
{
|
||||
"id": "scripts",
|
||||
"type": "archive",
|
||||
"path": "/usr/local/lib/asus-zephyrus-g14",
|
||||
"artifact": "scripts"
|
||||
},
|
||||
{
|
||||
"id": "nvidia-options",
|
||||
"type": "file",
|
||||
"path": "/etc/modprobe.d/g14-nvidia-power.conf",
|
||||
"mode": "0644",
|
||||
"content": "# Managed by the mesh (module asus-zephyrus-g14). Replaced on every push; edit the catalogue instead.\n#\n# The discrete GPU's driver options on the ROG Zephyrus G14 (GA403, RTX 40 series, hybrid graphics).\n#\n# NVreg_DynamicPowerManagement=0x00 turns runtime D3 off. With it on, a change of power source sends\n# the driver an ACPI notification it fails to handle on this model (\"RmHandleDNotifierEvent: Failed to\n# handle ACPI D-Notifier event, status=0x62\"), and the GPU stops making progress until the machine is\n# powered off. Off costs a few idle watts in hybrid mode and keeps the machine up.\n#\n# NVreg_PreserveVideoMemoryAllocations=1 saves video memory across suspend, so what used the GPU still\n# works after waking. It needs nvidia-suspend, -hibernate and -resume to run around a sleep, which this\n# module's drop-ins on the sleep services ask for.\n#\n# A change here applies when the driver next loads: at the next boot.\noptions nvidia NVreg_PreserveVideoMemoryAllocations=1\noptions nvidia NVreg_DynamicPowerManagement=0x00\n"
|
||||
},
|
||||
{
|
||||
"id": "video-options",
|
||||
"type": "file",
|
||||
"path": "/etc/modprobe.d/video-brightness-switch.conf",
|
||||
"mode": "0644",
|
||||
"content": "# Managed by the mesh (module asus-zephyrus-g14). Replaced on every push; edit the catalogue instead.\n#\n# The ACPI video driver does not change the backlight itself on the brightness keys: on this model it\n# moves the wrong one. The keys are triggerhappy's (see /etc/triggerhappy/triggers.d/asus-g14.conf).\n# Applies when the module next loads: at the next boot.\noptions video brightness_switch_enabled=0\n"
|
||||
},
|
||||
{
|
||||
"id": "suspend-drop-ins",
|
||||
"type": "directory",
|
||||
"path": "/etc/systemd/system/systemd-suspend.service.d",
|
||||
"mode": "0755"
|
||||
},
|
||||
{
|
||||
"id": "nvidia-on-suspend",
|
||||
"type": "file",
|
||||
"path": "/etc/systemd/system/systemd-suspend.service.d/asus-zephyrus-g14-nvidia.conf",
|
||||
"mode": "0644",
|
||||
"content": "# Managed by the mesh (module asus-zephyrus-g14). Replaced on every push; edit the catalogue instead.\n#\n# The NVIDIA driver's own sleep actions, asked for by the sleep itself rather than enabled as\n# links: the mesh declares files and never makes links (novox/hq ADR 0012), and the host's service\n# shape must not start these units by hand, which would put the GPU to sleep with the machine awake.\n[Unit]\nWants=nvidia-suspend.service nvidia-resume.service\n"
|
||||
},
|
||||
{
|
||||
"id": "hibernate-drop-ins",
|
||||
"type": "directory",
|
||||
"path": "/etc/systemd/system/systemd-hibernate.service.d",
|
||||
"mode": "0755"
|
||||
},
|
||||
{
|
||||
"id": "nvidia-on-hibernate",
|
||||
"type": "file",
|
||||
"path": "/etc/systemd/system/systemd-hibernate.service.d/asus-zephyrus-g14-nvidia.conf",
|
||||
"mode": "0644",
|
||||
"content": "# Managed by the mesh (module asus-zephyrus-g14). Replaced on every push; edit the catalogue instead.\n#\n# The NVIDIA driver's own sleep actions, asked for by the sleep itself rather than enabled as\n# links: the mesh declares files and never makes links (novox/hq ADR 0012), and the host's service\n# shape must not start these units by hand, which would put the GPU to sleep with the machine awake.\n[Unit]\nWants=nvidia-hibernate.service nvidia-resume.service\n"
|
||||
},
|
||||
{
|
||||
"id": "suspend-then-hibernate-drop-ins",
|
||||
"type": "directory",
|
||||
"path": "/etc/systemd/system/systemd-suspend-then-hibernate.service.d",
|
||||
"mode": "0755"
|
||||
},
|
||||
{
|
||||
"id": "nvidia-on-suspend-then-hibernate",
|
||||
"type": "file",
|
||||
"path": "/etc/systemd/system/systemd-suspend-then-hibernate.service.d/asus-zephyrus-g14-nvidia.conf",
|
||||
"mode": "0644",
|
||||
"content": "# Managed by the mesh (module asus-zephyrus-g14). Replaced on every push; edit the catalogue instead.\n#\n# The NVIDIA driver's own sleep actions, asked for by the sleep itself rather than enabled as\n# links: the mesh declares files and never makes links (novox/hq ADR 0012), and the host's service\n# shape must not start these units by hand, which would put the GPU to sleep with the machine awake.\n[Unit]\nWants=nvidia-suspend-then-hibernate.service nvidia-resume.service\n"
|
||||
},
|
||||
{
|
||||
"id": "powerd-drop-ins",
|
||||
"type": "directory",
|
||||
"path": "/etc/systemd/system/nvidia-powerd.service.d",
|
||||
"mode": "0755"
|
||||
},
|
||||
{
|
||||
"id": "powerd-opt-in",
|
||||
"type": "file",
|
||||
"path": "/etc/systemd/system/nvidia-powerd.service.d/asus-zephyrus-g14.conf",
|
||||
"mode": "0644",
|
||||
"content": "# Managed by the mesh (module asus-zephyrus-g14). Replaced on every push; edit the catalogue instead.\n#\n# nvidia-powerd (Dynamic Boost) was the first error in the chain that hung this model's GPU on a change\n# of power source, and asusd starts it on mains. It runs only when the kernel command line says\n# zephyrus.nvidia-powerd — an explicit opt-in, at boot.\n[Unit]\nConditionKernelCommandLine=zephyrus.nvidia-powerd\n"
|
||||
},
|
||||
{
|
||||
"id": "logind-drop-ins",
|
||||
"type": "directory",
|
||||
"path": "/etc/systemd/logind.conf.d",
|
||||
"mode": "0755"
|
||||
},
|
||||
{
|
||||
"id": "logind-power",
|
||||
"type": "file",
|
||||
"path": "/etc/systemd/logind.conf.d/power.conf",
|
||||
"mode": "0644",
|
||||
"content": "# Managed by the mesh (module asus-zephyrus-g14). Replaced on every push; edit the catalogue instead.\n#\n# The power key and the lid suspend, on battery, on mains and docked alike.\n[Login]\nHandlePowerKey=suspend\nHandleLidSwitch=suspend\nHandleLidSwitchExternalPower=suspend\nHandleLidSwitchDocked=suspend\n"
|
||||
},
|
||||
{
|
||||
"id": "logind",
|
||||
"type": "service",
|
||||
"unit": "systemd-logind.service",
|
||||
"reload-on": [
|
||||
"logind-power"
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "backlight-rule",
|
||||
"type": "file",
|
||||
"path": "/etc/udev/rules.d/90-backlight.rules",
|
||||
"mode": "0644",
|
||||
"content": "# Managed by the mesh (module asus-zephyrus-g14). Replaced on every push; edit the catalogue instead.\n#\n# The backlights are writable by the video group, so the brightness keys and the module's brightness tool\n# move the panel without root.\nACTION==\"add\", SUBSYSTEM==\"backlight\", RUN+=\"/usr/bin/chgrp video /sys/class/backlight/%k/brightness\", RUN+=\"/usr/bin/chmod g+w /sys/class/backlight/%k/brightness\"\n"
|
||||
},
|
||||
{
|
||||
"id": "udev",
|
||||
"type": "service",
|
||||
"unit": "systemd-udevd.service",
|
||||
"reload-on": [
|
||||
"backlight-rule"
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "triggerhappy-drop-ins",
|
||||
"type": "directory",
|
||||
"path": "/etc/systemd/system/triggerhappy.service.d",
|
||||
"mode": "0755"
|
||||
},
|
||||
{
|
||||
"id": "triggerhappy-as-account",
|
||||
"type": "file",
|
||||
"path": "/etc/systemd/system/triggerhappy.service.d/asus-zephyrus-g14.conf",
|
||||
"mode": "0644",
|
||||
"content": "# Managed by the mesh (module asus-zephyrus-g14). Replaced on every push; edit the catalogue instead.\n#\n# triggerhappy runs the vendor-key triggers as the operator's account, not as root: it opens the input\n# devices first and then drops to the account with its groups (input, video), so the triggers reach the\n# account's own session bus and the panel through the video group, with no su and no hard-coded user.\n[Service]\nExecStart=\nExecStart=/usr/bin/thd --triggers /etc/triggerhappy/triggers.d/ --socket /run/thd.socket --user ${machine:account} --deviceglob /dev/input/event*\n"
|
||||
},
|
||||
{
|
||||
"id": "vendor-keys",
|
||||
"type": "file",
|
||||
"path": "/etc/triggerhappy/triggers.d/asus-g14.conf",
|
||||
"mode": "0644",
|
||||
"content": "# Managed by the mesh (module asus-zephyrus-g14). Replaced on every push; edit the catalogue instead.\n#\n# The ROG Zephyrus G14's vendor keys, which reach no X client. Run as the operator's account (see the\n# module's drop-in on triggerhappy.service).\nKEY_PROG1\t1\t/usr/local/lib/asus-zephyrus-g14/bin/zephyrus-session playerctl play-pause\nKEY_PROG3\t1\t/usr/local/lib/asus-zephyrus-g14/bin/zephyrus-session playerctl previous\nKEY_PROG4\t1\t/usr/local/lib/asus-zephyrus-g14/bin/zephyrus-session playerctl next\nKEY_BRIGHTNESSDOWN\t1\t/usr/local/lib/asus-zephyrus-g14/bin/zephyrus-backlight -\nKEY_BRIGHTNESSDOWN\t2\t/usr/local/lib/asus-zephyrus-g14/bin/zephyrus-backlight -\nKEY_BRIGHTNESSUP\t1\t/usr/local/lib/asus-zephyrus-g14/bin/zephyrus-backlight +\nKEY_BRIGHTNESSUP\t2\t/usr/local/lib/asus-zephyrus-g14/bin/zephyrus-backlight +\nKEY_F21\t1\t/usr/local/lib/asus-zephyrus-g14/bin/zephyrus-touchpad reset\n"
|
||||
},
|
||||
{
|
||||
"id": "triggerhappy",
|
||||
"type": "service",
|
||||
"unit": "triggerhappy.service",
|
||||
"state": "running",
|
||||
"boot": "enabled",
|
||||
"restart-on": [
|
||||
"triggerhappy-as-account",
|
||||
"vendor-keys",
|
||||
"scripts"
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "upower-package",
|
||||
"type": "package",
|
||||
"package": "upower"
|
||||
},
|
||||
{
|
||||
"id": "upower-drop-ins",
|
||||
"type": "directory",
|
||||
"path": "/etc/UPower/UPower.conf.d",
|
||||
"mode": "0755"
|
||||
},
|
||||
{
|
||||
"id": "low-battery",
|
||||
"type": "file",
|
||||
"path": "/etc/UPower/UPower.conf.d/50-asus-zephyrus-g14.conf",
|
||||
"mode": "0644",
|
||||
"content": "# Managed by the mesh (module asus-zephyrus-g14). Replaced on every push; edit the catalogue instead.\n#\n# On low battery the machine suspends rather than powering off, at 7 % — s2idle still draws a little,\n# so it leaves headroom. A drop-in over the package's own UPower.conf, which stays the package's.\n[UPower]\nUsePercentageForPolicy=true\nPercentageLow=15.0\nPercentageCritical=10.0\nPercentageAction=7.0\nCriticalPowerAction=Suspend\nAllowRiskyCriticalPowerAction=true\n"
|
||||
},
|
||||
{
|
||||
"id": "upower",
|
||||
"type": "service",
|
||||
"unit": "upower.service",
|
||||
"state": "running",
|
||||
"boot": "enabled",
|
||||
"restart-on": [
|
||||
"low-battery"
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "xorg-drop-ins",
|
||||
"type": "directory",
|
||||
"path": "/etc/X11/xorg.conf.d",
|
||||
"mode": "0755"
|
||||
},
|
||||
{
|
||||
"id": "touchpad",
|
||||
"type": "file",
|
||||
"path": "/etc/X11/xorg.conf.d/30-asus-zephyrus-g14-touchpad.conf",
|
||||
"mode": "0644",
|
||||
"content": "# Managed by the mesh (module asus-zephyrus-g14). Replaced on every push; edit the catalogue instead.\n#\n# The touchpad's settings, applied by X every time the device appears — at login and after every\n# resume, when the device is initialised again. This replaces the predecessor's sleep hook, which ran\n# xinput after a resume as a named person on a guessed display.\nSection \"InputClass\"\n Identifier \"asus-zephyrus-g14 touchpad\"\n MatchIsTouchpad \"on\"\n Option \"Tapping\" \"on\"\n Option \"NaturalScrolling\" \"true\"\n Option \"AccelSpeed\" \"0.15\"\nEndSection\n"
|
||||
}
|
||||
],
|
||||
"build": {
|
||||
"artifacts": [
|
||||
{
|
||||
"name": "tools-go",
|
||||
"kind": "bundle",
|
||||
"language": "go",
|
||||
"system": "arch",
|
||||
"from": "cmd/zephyrus",
|
||||
"binary": "zephyrus",
|
||||
"loads": [
|
||||
"zephyrus"
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "scripts",
|
||||
"kind": "archive",
|
||||
"from": "files"
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
# audit-logger's runtime: the shared runtime image, carrying this module's compiled code.
|
||||
#
|
||||
# **Built from this module's own directory and nothing else.** The toolkit is in the base image, so
|
||||
# nothing is copied out of a neighbouring checkout — which is what lets the mesh build this from a
|
||||
# repository and a path (novox/hq ADR 0069) rather than only on a workstation that happens to have
|
||||
# the siblings laid out beside it.
|
||||
|
||||
# Two bases, named rather than pinned: the image this is COMPILED in, and the image it RUNS in.
|
||||
# They are different images on purpose — the first carries a compiler and the second must not, or
|
||||
# every running container would carry one it never invokes. The mesh answers both with the copies it
|
||||
# holds, because a fingerprint written here would name one particular copy and no other mesh has it
|
||||
# (novox/hq issue 044). Declared in module.json's `build.on`; deliberately no defaults, so a build
|
||||
# nobody told stops here and says which module to build first.
|
||||
ARG BUILD_BASE
|
||||
ARG RUNTIME_BASE
|
||||
|
||||
FROM ${BUILD_BASE} AS build
|
||||
# Compiled under /app/modules so `@novox/mesh-sdk` resolves upward into the base's own
|
||||
# node_modules — the module is compiled against exactly the toolkit it will run against.
|
||||
WORKDIR /app/modules/audit-logger
|
||||
COPY . .
|
||||
# The compiler is invoked by its real path rather than through node_modules/.bin, whose entries are
|
||||
# symlinks to a launcher that requires its library relatively — resolved away when the base image
|
||||
# was assembled.
|
||||
RUN node /app/node_modules/typescript/bin/tsc audit.ts index.ts \
|
||||
--module NodeNext --moduleResolution NodeNext --target ES2022 --outDir dist
|
||||
|
||||
FROM ${RUNTIME_BASE}
|
||||
COPY --from=build /app/modules/audit-logger/dist /app/modules/audit-logger/dist
|
||||
# **Served, not run.** This subscribes on import, and the serve mode binds the broker before it
|
||||
# imports anything — `run` exists for a step that works offline and exits, and would leave this
|
||||
# with nothing to subscribe to.
|
||||
ENV MESH_TOOL_MODULES=/app/modules/audit-logger/dist/index.js
|
||||
@@ -5,21 +5,27 @@
|
||||
"consumes": [
|
||||
"**"
|
||||
],
|
||||
"own-secrets": {
|
||||
"broker": "/var/lib/audit-logger/broker"
|
||||
},
|
||||
"build": {
|
||||
"on": [
|
||||
{
|
||||
"arg": "BUILD_BASE",
|
||||
"module": "mesh-tools",
|
||||
"artifact": "build"
|
||||
},
|
||||
{
|
||||
"arg": "RUNTIME_BASE",
|
||||
"module": "mesh-tools",
|
||||
"artifact": "runtime"
|
||||
}
|
||||
],
|
||||
"artifacts": [
|
||||
{
|
||||
"name": "code",
|
||||
"kind": "bundle",
|
||||
"language": "typescript",
|
||||
"entrypoints": [
|
||||
"index.js"
|
||||
],
|
||||
"loads": [
|
||||
"index.js"
|
||||
],
|
||||
"env": {
|
||||
"AUDIT_LOG": "${dir:trail}/audit.log"
|
||||
}
|
||||
"name": "runtime",
|
||||
"kind": "image",
|
||||
"from": "Dockerfile"
|
||||
}
|
||||
]
|
||||
},
|
||||
@@ -27,13 +33,29 @@
|
||||
{
|
||||
"id": "state",
|
||||
"type": "directory",
|
||||
"mode": "0700",
|
||||
"place": "."
|
||||
"path": "/var/lib/audit-logger",
|
||||
"mode": "0700"
|
||||
},
|
||||
{
|
||||
"id": "trail",
|
||||
"type": "directory",
|
||||
"path": "/var/lib/audit-logger/trail",
|
||||
"mode": "0700"
|
||||
},
|
||||
{
|
||||
"id": "run",
|
||||
"type": "container",
|
||||
"name": "mesh-audit-logger",
|
||||
"network": "host",
|
||||
"volumes": [
|
||||
"/var/lib/audit-logger/broker:/run/secrets/broker:ro",
|
||||
"/var/lib/audit-logger/trail:/trail"
|
||||
],
|
||||
"env": {
|
||||
"MESH_BROKER_FILE": "/run/secrets/broker",
|
||||
"AUDIT_LOG": "/trail/audit.log"
|
||||
},
|
||||
"artifact": "runtime"
|
||||
}
|
||||
],
|
||||
"capabilities": [
|
||||
|
||||
@@ -15,7 +15,7 @@ test("audit-logger records every event to the trail as one line each", async ()
|
||||
const path = join(dir, "audit.log");
|
||||
|
||||
// The audit-logger's whole behaviour: consume everything, record it.
|
||||
await on("#", async (event) => record(event, path)); // the pattern index.ts subscribes
|
||||
await on("**", async (event) => record(event, path));
|
||||
|
||||
process.env.MESH_MODULE = "umami";
|
||||
process.env.MESH_NODE = "anchor";
|
||||
@@ -24,9 +24,7 @@ test("audit-logger records every event to the trail as one line each", async ()
|
||||
|
||||
const lines = (await readFile(path, "utf8")).trim().split("\n").map((l) => JSON.parse(l));
|
||||
assert.equal(lines.length, 2);
|
||||
// A module names its events locally (design 29); the module is the `source`, which together with
|
||||
// the type says whose event it was. This broker does no namespacing, so the type is as emitted.
|
||||
assert.deepEqual(lines.map((l) => l.type), ["site.created", "node.anchor.joined"]);
|
||||
assert.deepEqual(lines.map((l) => l.type), ["umami.site.created", "node.anchor.joined"]);
|
||||
assert.equal(lines[0].source, "umami");
|
||||
assert.equal(lines[0].node, "anchor");
|
||||
assert.equal(lines[0].body.domain, "my-app");
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
# baserow's runtime: the tool runtime, carrying this module's compiled code.
|
||||
#
|
||||
# **Built from this module's own directory and nothing else.** The sdk and the tool runtime are in
|
||||
# the base images, published like any other artifact — which is what makes this buildable by the
|
||||
# mesh from a repository and a path (novox/hq ADR 0069) rather than only on a workstation that
|
||||
# happens to have the siblings.
|
||||
#
|
||||
# Two bases, named rather than pinned (novox/hq issue 044): the image this is COMPILED in and the
|
||||
# image it RUNS in — the second must not carry a compiler. Declared in module.json's `build.on`.
|
||||
ARG BUILD_BASE
|
||||
ARG RUNTIME_BASE
|
||||
|
||||
FROM ${BUILD_BASE} AS build
|
||||
WORKDIR /app/modules/baserow
|
||||
COPY . .
|
||||
RUN node /app/node_modules/typescript/bin/tsc client.ts tools/index.ts \
|
||||
--module NodeNext --moduleResolution NodeNext --target ES2022 --outDir dist
|
||||
|
||||
FROM ${RUNTIME_BASE}
|
||||
COPY --from=build /app/modules/baserow/dist /app/modules/baserow/dist
|
||||
# Every serve-time entrypoint, loaded by the runtime in serve mode: tools and events serve, and a
|
||||
# provider's provisioner runs its reconcile loop in the same process, with the broker connected —
|
||||
# the convention novox/hq issues 060/061 settled.
|
||||
ENV MESH_TOOL_MODULES=/app/modules/baserow/dist/tools/index.js
|
||||
+24
-55
@@ -2,15 +2,12 @@
|
||||
// module's tools and anything else baserow-specific import it; nothing outside baserow does.
|
||||
//
|
||||
// Baserow authenticates a person with email + password, exchanged for a JWT at /api/user/token-auth/.
|
||||
// The standard image creates no admin from env, so the account is one a person made in Baserow: its
|
||||
// password is the module's `admin` secret, accepted from the operator, and its email and the public
|
||||
// host Baserow answers to reach the runtime config file the mesh mounts (the email from the
|
||||
// assignment's settings). Until both are there fromEnv throws and the module exposes no tools — the
|
||||
// same dormant-until-configured shape gitea uses for its token.
|
||||
// Those credentials are the mesh's own: a person signs up in Baserow (the standard image creates no
|
||||
// admin from env), and the credential is placed in the runtime config file the mesh mounts. Until
|
||||
// that happens fromEnv throws and the module simply exposes no tools — the same dormant-until-
|
||||
// configured shape gitea uses for its token.
|
||||
|
||||
import { readFileSync } from "node:fs";
|
||||
import { request as httpRequest } from "node:http";
|
||||
import { request as httpsRequest } from "node:https";
|
||||
|
||||
export interface BaserowApplication {
|
||||
id: number;
|
||||
@@ -71,63 +68,35 @@ export class BaserowClient {
|
||||
return h;
|
||||
}
|
||||
|
||||
/**
|
||||
* One HTTP exchange. Not `fetch`: Node's fetch drops a caller's Host header and sends the URL's
|
||||
* own, and Baserow answers only the host of its BASEROW_PUBLIC_URL — any other Host is looked up
|
||||
* as a published builder site and gets 404, `/api/_health/` included. A co-located caller reaching
|
||||
* it by container name must present the public host, so the request is made with node:http, which
|
||||
* sends the Host it is given.
|
||||
*/
|
||||
private send(path: string, method: string, headers: Record<string, string>, body?: string): Promise<{ status: number; text: string }> {
|
||||
const url = new URL(`${this.baseUrl}${path}`);
|
||||
const request = url.protocol === "https:" ? httpsRequest : httpRequest;
|
||||
// A length, never chunked: Baserow's server reads a chunked body as empty.
|
||||
const sent = body === undefined ? headers : { ...headers, "Content-Length": String(Buffer.byteLength(body)) };
|
||||
return new Promise((resolve, reject) => {
|
||||
const req = request(url, { method, headers: sent }, (res) => {
|
||||
let text = "";
|
||||
res.setEncoding("utf8");
|
||||
res.on("data", (chunk: string) => (text += chunk));
|
||||
res.on("end", () => resolve({ status: res.statusCode ?? 0, text }));
|
||||
res.on("error", reject);
|
||||
});
|
||||
req.on("error", reject);
|
||||
if (body !== undefined) req.write(body);
|
||||
req.end();
|
||||
});
|
||||
}
|
||||
|
||||
/** Exchange email + password for a JWT, caching it until Baserow refuses it. Handles both the
|
||||
/** Exchange email + password for a JWT, caching it for the client's lifetime. Handles both the
|
||||
* older `{ token }` and the newer `{ access_token }` response shapes. */
|
||||
async authenticate(): Promise<string> {
|
||||
if (this.token) return this.token;
|
||||
const res = await this.send(
|
||||
"/api/user/token-auth/",
|
||||
"POST",
|
||||
this.headers(),
|
||||
JSON.stringify({ email: this.email, password: this.password }),
|
||||
);
|
||||
if (res.status < 200 || res.status >= 300) throw new Error(`baserow auth failed: ${res.status} ${res.text}`);
|
||||
const data = JSON.parse(res.text) as { token?: string; access_token?: string };
|
||||
const res = await fetch(`${this.baseUrl}/api/user/token-auth/`, {
|
||||
method: "POST",
|
||||
headers: this.headers(),
|
||||
body: JSON.stringify({ email: this.email, password: this.password }),
|
||||
});
|
||||
if (!res.ok) throw new Error(`baserow auth failed: ${res.status} ${await res.text()}`);
|
||||
const data = (await res.json()) as { token?: string; access_token?: string };
|
||||
const token = data.access_token ?? data.token;
|
||||
if (!token) throw new Error("baserow auth returned no token");
|
||||
this.token = token;
|
||||
return token;
|
||||
}
|
||||
|
||||
/** An authenticated GET. A refused token is dropped and the call made once more with a fresh one:
|
||||
* Baserow's access tokens expire after minutes, and the runtime lives for weeks. */
|
||||
private async authed<T>(path: string): Promise<T> {
|
||||
for (let attempt = 0; ; attempt++) {
|
||||
const token = await this.authenticate();
|
||||
const res = await this.send(path, "GET", this.headers({ Authorization: `JWT ${token}` }));
|
||||
if (res.status === 401 && attempt === 0) {
|
||||
this.token = null;
|
||||
continue;
|
||||
}
|
||||
if (res.status < 200 || res.status >= 300) throw new Error(`baserow ${path}: ${res.status} ${res.text}`);
|
||||
return (res.text ? JSON.parse(res.text) : null) as T;
|
||||
}
|
||||
private async authed<T>(path: string, options: RequestInit = {}): Promise<T> {
|
||||
const token = await this.authenticate();
|
||||
const res = await fetch(`${this.baseUrl}${path}`, {
|
||||
...options,
|
||||
headers: this.headers({
|
||||
Authorization: `JWT ${token}`,
|
||||
...(options.headers as Record<string, string> | undefined),
|
||||
}),
|
||||
});
|
||||
if (!res.ok) throw new Error(`baserow ${path}: ${res.status} ${await res.text()}`);
|
||||
const text = await res.text();
|
||||
return (text ? JSON.parse(text) : null) as T;
|
||||
}
|
||||
|
||||
/** The applications (databases) the account can see, across all its workspaces. */
|
||||
|
||||
+54
-31
@@ -18,14 +18,15 @@
|
||||
}
|
||||
},
|
||||
"binds": {
|
||||
"postgres-database": "${dir:state}/database.json",
|
||||
"route": "${dir:state}/route.json"
|
||||
"postgres-database": "/var/lib/baserow/database.json",
|
||||
"route": "/var/lib/baserow/route.json"
|
||||
},
|
||||
"secrets": {
|
||||
"postgres-database": "${dir:state}/database.secret"
|
||||
"postgres-database": "/var/lib/baserow/database.secret"
|
||||
},
|
||||
"own-secrets": {
|
||||
"admin": "${dir:state}/admin.secret"
|
||||
"secret-key": "/var/lib/baserow/secret-key.secret",
|
||||
"broker": "/var/lib/mesh/baserow/broker"
|
||||
},
|
||||
"listens": [
|
||||
{
|
||||
@@ -33,34 +34,35 @@
|
||||
"port": 80,
|
||||
"protocol": "tcp",
|
||||
"from": "mesh",
|
||||
"why": "the Baserow web UI and REST API, served by the image's own Caddy; a public name is the route's"
|
||||
"why": "the Baserow web UI and REST API; a public name is a route grant later"
|
||||
}
|
||||
],
|
||||
"resources": [
|
||||
{
|
||||
"id": "mesh-state",
|
||||
"type": "directory",
|
||||
"mode": "0700",
|
||||
"place": "mesh"
|
||||
"path": "/var/lib/mesh/baserow",
|
||||
"mode": "0700"
|
||||
},
|
||||
{
|
||||
"id": "state",
|
||||
"type": "directory",
|
||||
"mode": "0700",
|
||||
"place": "."
|
||||
"path": "/var/lib/baserow",
|
||||
"mode": "0700"
|
||||
},
|
||||
{
|
||||
"id": "data",
|
||||
"type": "directory",
|
||||
"path": "/services/baserow/data",
|
||||
"mode": "0755",
|
||||
"owner": "9999:9999"
|
||||
},
|
||||
{
|
||||
"id": "server-env",
|
||||
"type": "file",
|
||||
"path": "${dir:state}/server.env",
|
||||
"path": "/var/lib/baserow/server.env",
|
||||
"mode": "0600",
|
||||
"content": "DATABASE_HOST=${bound:postgres-database:at}\nDATABASE_PORT=${bound:postgres-database:port}\nDATABASE_NAME=${bound:postgres-database:as}\nDATABASE_USER=${bound:postgres-database:as}\nDATABASE_PASSWORD_FILE=/run/secrets/database\nDISABLE_EMBEDDED_PSQL=true\nBASEROW_PUBLIC_URL=https://${bound:route:name}\n"
|
||||
"content": "DATABASE_HOST=${bound:postgres-database:at}\nDATABASE_PORT=${bound:postgres-database:port}\nDATABASE_NAME=${bound:postgres-database:as}\nDATABASE_USER=${bound:postgres-database:as}\nDATABASE_PASSWORD=${secret:postgres-database}\nSECRET_KEY=${secret:secret-key}\nBASEROW_PUBLIC_URL=http://localhost\n"
|
||||
},
|
||||
{
|
||||
"id": "net",
|
||||
@@ -71,44 +73,65 @@
|
||||
"id": "server",
|
||||
"type": "container",
|
||||
"name": "baserow",
|
||||
"image": "baserow/baserow@sha256:263ea6c4b72c9eccabcd975ffe9fdebf23913a293a514bec6a3897a5e0a5a080",
|
||||
"image": "baserow/baserow@sha256:834424a10413798567f76428f255dc259445b7f8dcec56598c05b4073bb2a124",
|
||||
"network": "baserow",
|
||||
"env-file": [
|
||||
"${dir:state}/server.env"
|
||||
"/var/lib/baserow/server.env"
|
||||
],
|
||||
"ports": [
|
||||
"80"
|
||||
],
|
||||
"volumes": [
|
||||
"${dir:data}:/baserow/data",
|
||||
"${dir:state}/database.secret:/run/secrets/database:ro"
|
||||
]
|
||||
"/services/baserow/data:/baserow/data"
|
||||
],
|
||||
"secrets-in-environment": "baserow reads DATABASE_PASSWORD and SECRET_KEY with os.getenv and has no _FILE twin (settings/base.py); not convertible"
|
||||
},
|
||||
{
|
||||
"id": "runtime-config",
|
||||
"type": "file",
|
||||
"path": "${dir:mesh-state}/config.json",
|
||||
"path": "/var/lib/mesh/baserow/config.json",
|
||||
"mode": "0600",
|
||||
"content": "{\n \"password\": \"${secret:admin}\",\n \"host\": \"${bound:route:name}\"\n}\n",
|
||||
"content": "{}\n",
|
||||
"merge": "json"
|
||||
},
|
||||
{
|
||||
"id": "runtime",
|
||||
"type": "container",
|
||||
"name": "mesh-baserow",
|
||||
"network": "baserow",
|
||||
"volumes": [
|
||||
"/var/lib/mesh/baserow/broker:/run/secrets/broker:ro",
|
||||
"/var/lib/mesh/baserow/config.json:/run/config/config.json:ro"
|
||||
],
|
||||
"env": {
|
||||
"MESH_BROKER_FILE": "/run/secrets/broker",
|
||||
"MESH_BASEROW_URL": "http://baserow:80",
|
||||
"MESH_BASEROW_CONFIG_FILE": "/run/config/config.json"
|
||||
},
|
||||
"restart-on": [
|
||||
"runtime-config"
|
||||
],
|
||||
"artifact": "runtime"
|
||||
}
|
||||
],
|
||||
"build": {
|
||||
"on": [
|
||||
{
|
||||
"arg": "BUILD_BASE",
|
||||
"module": "mesh-tools",
|
||||
"artifact": "build"
|
||||
},
|
||||
{
|
||||
"arg": "RUNTIME_BASE",
|
||||
"module": "mesh-tools",
|
||||
"artifact": "runtime"
|
||||
}
|
||||
],
|
||||
"artifacts": [
|
||||
{
|
||||
"name": "tools",
|
||||
"kind": "bundle",
|
||||
"language": "typescript",
|
||||
"entrypoints": [
|
||||
"tools/index.js"
|
||||
],
|
||||
"loads": [
|
||||
"tools/index.js"
|
||||
],
|
||||
"env": {
|
||||
"MESH_BASEROW_URL": "http://127.0.0.1:${port:80}",
|
||||
"MESH_BASEROW_CONFIG_FILE": "${dir:mesh-state}/config.json"
|
||||
}
|
||||
"name": "runtime",
|
||||
"kind": "image",
|
||||
"from": "Dockerfile"
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
# bazarr's runtime: the tool runtime, carrying this module's compiled code.
|
||||
#
|
||||
# **Built from this module's own directory and nothing else.** The sdk and the tool runtime are in
|
||||
# the base images, published like any other artifact — which is what makes this buildable by the
|
||||
# mesh from a repository and a path (novox/hq ADR 0069) rather than only on a workstation that
|
||||
# happens to have the siblings.
|
||||
#
|
||||
# Two bases, named rather than pinned (novox/hq issue 044): the image this is COMPILED in and the
|
||||
# image it RUNS in — the second must not carry a compiler. Declared in module.json's `build.on`.
|
||||
ARG BUILD_BASE
|
||||
ARG RUNTIME_BASE
|
||||
|
||||
FROM ${BUILD_BASE} AS build
|
||||
WORKDIR /app/modules/bazarr
|
||||
COPY . .
|
||||
RUN node /app/node_modules/typescript/bin/tsc apikey.ts client.ts index.ts tools/index.ts servarr/settings.ts servarr/index.ts \
|
||||
--module NodeNext --moduleResolution NodeNext --target ES2022 --outDir dist
|
||||
|
||||
FROM ${RUNTIME_BASE}
|
||||
COPY --from=build /app/modules/bazarr/dist /app/modules/bazarr/dist
|
||||
# Every serve-time entrypoint, loaded by the runtime in serve mode: tools and events serve, and a
|
||||
# provider's provisioner runs its reconcile loop in the same process, with the broker connected —
|
||||
# the convention novox/hq issues 060/061 settled.
|
||||
ENV MESH_TOOL_MODULES=/app/modules/bazarr/dist/index.js,/app/modules/bazarr/dist/tools/index.js
|
||||
# NOT dist/servarr/index.js: that is a step the host runs to completion, named by the `servarr`
|
||||
# container's args as `mesh-tools run …` (novox/hq ADR 0052). Listed here it would run inside the
|
||||
# serving sidecar too, and exit it.
|
||||
@@ -0,0 +1,37 @@
|
||||
// bazarr's own API key, found where bazarr keeps it. Shared by the client (tools, events) and the
|
||||
// Servarr step, and kept apart from client.ts so the step and its test load it without the client.
|
||||
|
||||
import { readFileSync } from "node:fs";
|
||||
|
||||
/**
|
||||
* bazarr's own API key, read from where bazarr keeps it: `auth.apikey` in `config/config.yaml` under
|
||||
* its config directory. bazarr makes this key itself on first start and nothing lets the mesh set it,
|
||||
* so a key the mesh minted could never work; reading bazarr's own file needs nothing accepted and
|
||||
* stays right if the operator regenerates the key in bazarr's settings screen. The file is read, never
|
||||
* written. Undefined when the file or the key is not there.
|
||||
*/
|
||||
export function apiKeyFromConfigDir(configDir?: string): string | undefined {
|
||||
if (!configDir) return undefined;
|
||||
let text: string;
|
||||
try { text = readFileSync(`${configDir.replace(/\/$/, "")}/config/config.yaml`, "utf8"); }
|
||||
catch { return undefined; }
|
||||
return apiKeyFromConfigYaml(text);
|
||||
}
|
||||
|
||||
/** `auth.apikey` from the text of bazarr's config.yaml — a top-level `auth:` mapping, one level deep. */
|
||||
export function apiKeyFromConfigYaml(text: string): string | undefined {
|
||||
let inAuth = false;
|
||||
for (const line of text.split(/\r?\n/)) {
|
||||
if (/^\S/.test(line)) {
|
||||
inAuth = /^auth:\s*$/.test(line);
|
||||
continue;
|
||||
}
|
||||
if (!inAuth) continue;
|
||||
const m = line.match(/^\s+apikey:\s*(.*?)\s*$/);
|
||||
if (m) {
|
||||
const v = m[1].replace(/^(['"])(.*)\1$/, "$2").trim();
|
||||
return v || undefined;
|
||||
}
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
@@ -0,0 +1,179 @@
|
||||
// The Bazarr API client — bazarr's own code, living in the module (novox/hq ADR 0039). Bazarr
|
||||
// manages subtitles for a Sonarr/Radarr library: it tracks which episodes and movies are still
|
||||
// missing subtitles, searches providers for them, and records what it downloaded. This client
|
||||
// talks its /api surface (keyed by an X-API-KEY header); bazarr's tools and events import it.
|
||||
|
||||
import { readFileSync } from "node:fs";
|
||||
|
||||
import { apiKeyFromConfigDir } from "./apikey.js";
|
||||
|
||||
export interface WantedSubtitle {
|
||||
kind: "episode" | "movie";
|
||||
title: string; // series + episode, or movie title
|
||||
path?: string;
|
||||
seriesId?: number; // sonarr series id (episodes)
|
||||
episodeId?: number; // sonarr episode id (episodes)
|
||||
radarrId?: number; // radarr movie id (movies)
|
||||
missing: string[]; // language names still missing
|
||||
}
|
||||
|
||||
export interface ProviderSubtitle {
|
||||
provider: string;
|
||||
language: string;
|
||||
hearingImpaired: boolean;
|
||||
forced: boolean;
|
||||
score?: number;
|
||||
release?: string;
|
||||
subtitle: string; // the opaque token Bazarr uses to download this exact result
|
||||
}
|
||||
|
||||
export interface HistoryEntry {
|
||||
kind: "episode" | "movie";
|
||||
id: string; // stable dedup key across polls
|
||||
title: string;
|
||||
language?: string;
|
||||
provider?: string;
|
||||
path?: string;
|
||||
timestamp?: string;
|
||||
description?: string;
|
||||
}
|
||||
|
||||
/** The settings-merged config the mesh delivers (novox/hq ADR 0046): { url, apiKey, token, password, user, ... }. */
|
||||
function meshConfig(file?: string): Record<string, string> {
|
||||
if (!file) return {};
|
||||
try { return JSON.parse(readFileSync(file, "utf8")) as Record<string, string>; }
|
||||
catch { return {}; }
|
||||
}
|
||||
|
||||
/** Read a secret the mesh mounted at a file path (an own-secret delivered by `secret accept`);
|
||||
* absent or unreadable yields undefined so callers fall back rather than crash. */
|
||||
function readSecret(file?: string): string | undefined {
|
||||
if (!file) return undefined;
|
||||
try { return readFileSync(file, "utf8").trim() || undefined; }
|
||||
catch { return undefined; }
|
||||
}
|
||||
|
||||
export class BazarrClient {
|
||||
readonly baseUrl: string;
|
||||
|
||||
constructor(
|
||||
url: string,
|
||||
private readonly apiKey: string,
|
||||
) {
|
||||
this.baseUrl = url.replace(/\/$/, "");
|
||||
}
|
||||
|
||||
/** Build from the module's resolved environment. Bazarr's API is keyed; without URL and key
|
||||
* there is nothing to talk to, so this throws rather than run half-configured. */
|
||||
static fromEnv(env: NodeJS.ProcessEnv = process.env): BazarrClient {
|
||||
const cfg = meshConfig(env.MESH_BAZARR_CONFIG_FILE);
|
||||
const url = cfg.url ?? env.MESH_BAZARR_URL;
|
||||
const apiKey =
|
||||
cfg.apiKey ??
|
||||
apiKeyFromConfigDir(env.MESH_BAZARR_CONFIG_DIR) ??
|
||||
readSecret(env.MESH_BAZARR_API_KEY_FILE) ??
|
||||
env.MESH_BAZARR_API_KEY;
|
||||
if (!url) throw new Error("no Bazarr URL — set MESH_BAZARR_URL");
|
||||
if (!apiKey) throw new Error("no Bazarr API key — bazarr's config/config.yaml under MESH_BAZARR_CONFIG_DIR has none");
|
||||
return new BazarrClient(url, apiKey);
|
||||
}
|
||||
|
||||
private async request(method: string, path: string, params: Record<string, string> = {}): Promise<any> {
|
||||
const url = new URL(`${this.baseUrl}/api${path}`);
|
||||
for (const [k, v] of Object.entries(params)) url.searchParams.set(k, v);
|
||||
const res = await fetch(url.toString(), { method, headers: { "X-API-KEY": this.apiKey, Accept: "application/json" } });
|
||||
if (!res.ok) throw new Error(`Bazarr API ${method} ${path}: ${res.status} ${await res.text()}`);
|
||||
// Downloads/patches return an empty body; only GETs carry JSON.
|
||||
const text = await res.text();
|
||||
return text ? JSON.parse(text) : {};
|
||||
}
|
||||
|
||||
private get(path: string, params?: Record<string, string>): Promise<any> {
|
||||
return this.request("GET", path, params);
|
||||
}
|
||||
|
||||
private languageNames(missing: any[]): string[] {
|
||||
return (missing ?? []).map((m: any) => m?.name ?? m?.code2 ?? m?.code3).filter(Boolean);
|
||||
}
|
||||
|
||||
/** Episodes and movies still missing subtitles — Bazarr's core "what's left to do" list. */
|
||||
async getWanted(limit = 50): Promise<WantedSubtitle[]> {
|
||||
const [eps, movies] = await Promise.all([
|
||||
this.get("/episodes/wanted", { start: "0", length: String(limit) }),
|
||||
this.get("/movies/wanted", { start: "0", length: String(limit) }),
|
||||
]);
|
||||
const episodes: WantedSubtitle[] = (eps?.data ?? []).map((e: any) => ({
|
||||
kind: "episode" as const,
|
||||
title: `${e.seriesTitle ?? e.series ?? "Unknown"} — ${e.episodeTitle ?? e.episode_title ?? ""}`.trim(),
|
||||
path: e.path,
|
||||
seriesId: e.sonarrSeriesId,
|
||||
episodeId: e.sonarrEpisodeId,
|
||||
missing: this.languageNames(e.missing_subtitles),
|
||||
}));
|
||||
const films: WantedSubtitle[] = (movies?.data ?? []).map((m: any) => ({
|
||||
kind: "movie" as const,
|
||||
title: m.title ?? "Unknown",
|
||||
path: m.path,
|
||||
radarrId: m.radarrId,
|
||||
missing: this.languageNames(m.missing_subtitles),
|
||||
}));
|
||||
return [...episodes, ...films];
|
||||
}
|
||||
|
||||
/** Ask providers what subtitles are available for one wanted episode — a manual search. */
|
||||
async searchEpisode(episodeId: number): Promise<ProviderSubtitle[]> {
|
||||
const raw = await this.get("/providers/episodes", { episodeid: String(episodeId) });
|
||||
return this.mapProviderResults(raw);
|
||||
}
|
||||
|
||||
/** Ask providers what subtitles are available for one movie — a manual search. */
|
||||
async searchMovie(radarrId: number): Promise<ProviderSubtitle[]> {
|
||||
const raw = await this.get("/providers/movies", { radarrid: String(radarrId) });
|
||||
return this.mapProviderResults(raw);
|
||||
}
|
||||
|
||||
private mapProviderResults(raw: any): ProviderSubtitle[] {
|
||||
const list = Array.isArray(raw) ? raw : (raw?.data ?? []);
|
||||
return list.map((r: any) => ({
|
||||
provider: r.provider,
|
||||
language: r.language?.name ?? r.language ?? "unknown",
|
||||
hearingImpaired: Boolean(r.hearing_impaired ?? r.hi),
|
||||
forced: Boolean(r.forced),
|
||||
score: r.score,
|
||||
release: r.release_info?.[0] ?? r.release_info,
|
||||
subtitle: r.subtitle,
|
||||
}));
|
||||
}
|
||||
|
||||
/** Recent subtitle-download history, episodes and movies together, newest first. Each entry
|
||||
* carries a stable id so the events poller can tell a fresh download from one already seen. */
|
||||
async getHistory(limit = 40): Promise<HistoryEntry[]> {
|
||||
const [eps, movies] = await Promise.all([
|
||||
this.get("/episodes/history", { start: "0", length: String(limit) }),
|
||||
this.get("/movies/history", { start: "0", length: String(limit) }),
|
||||
]);
|
||||
const key = (kind: string, r: any): string =>
|
||||
`${kind}:${r.timestamp ?? r.parsed_timestamp ?? ""}:${r.subtitles_path ?? r.path ?? ""}:${r.language?.code3 ?? r.language ?? ""}`;
|
||||
const episodes: HistoryEntry[] = (eps?.data ?? []).map((r: any) => ({
|
||||
kind: "episode" as const,
|
||||
id: key("episode", r),
|
||||
title: `${r.seriesTitle ?? "Unknown"} — ${r.episodeTitle ?? ""}`.trim(),
|
||||
language: r.language?.name ?? r.language,
|
||||
provider: r.provider,
|
||||
path: r.subtitles_path,
|
||||
timestamp: r.timestamp,
|
||||
description: r.description,
|
||||
}));
|
||||
const films: HistoryEntry[] = (movies?.data ?? []).map((r: any) => ({
|
||||
kind: "movie" as const,
|
||||
id: key("movie", r),
|
||||
title: r.title ?? "Unknown",
|
||||
language: r.language?.name ?? r.language,
|
||||
provider: r.provider,
|
||||
path: r.subtitles_path,
|
||||
timestamp: r.timestamp,
|
||||
description: r.description,
|
||||
}));
|
||||
return [...episodes, ...films];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
// bazarr's events. The tool runtime imports this once the broker is bound. Bazarr's one genuinely
|
||||
// observable thing is a subtitle arriving: it works away in the background, searching providers for
|
||||
// the missing-subtitle list, and when it succeeds a subtitle appears in its history. That is worth
|
||||
// announcing to the mesh.
|
||||
//
|
||||
// Emits (novox/hq ADR 0041/0042):
|
||||
// module.bazarr.subtitle.downloaded — a subtitle was fetched for an episode or movie
|
||||
//
|
||||
// Bazarr has nothing on the mesh it usefully reacts to (a download completing is Sonarr/Radarr's
|
||||
// business, and they trigger Bazarr directly), so it consumes nothing — a pure emitter.
|
||||
//
|
||||
// The event is observation-based: poll history and diff. Primed silently on the first look, or a
|
||||
// restart would re-announce the whole recent history as freshly downloaded.
|
||||
|
||||
import { emit } from "@novox/mesh-sdk/events";
|
||||
import { BazarrClient } from "./client.js";
|
||||
|
||||
const bazarr = BazarrClient.fromEnv();
|
||||
|
||||
const seen = new Set<string>();
|
||||
let primed = false;
|
||||
async function pollHistory(): Promise<void> {
|
||||
const entries = await bazarr.getHistory(40);
|
||||
for (const entry of entries) {
|
||||
if (seen.has(entry.id)) continue;
|
||||
if (primed) {
|
||||
await emit("subtitle.downloaded", {
|
||||
kind: entry.kind,
|
||||
title: entry.title,
|
||||
language: entry.language,
|
||||
provider: entry.provider,
|
||||
path: entry.path,
|
||||
});
|
||||
}
|
||||
seen.add(entry.id);
|
||||
}
|
||||
primed = true;
|
||||
}
|
||||
|
||||
const tick = (fn: () => Promise<void>, everyMs: number): void => {
|
||||
const run = (): void => void fn().catch((err) => console.error(`[bazarr] ${err}`));
|
||||
setInterval(run, everyMs);
|
||||
run();
|
||||
};
|
||||
tick(pollHistory, 60_000);
|
||||
|
||||
console.log("[bazarr] watching subtitle-download history");
|
||||
@@ -0,0 +1,181 @@
|
||||
{
|
||||
"module": "bazarr",
|
||||
"version": "1",
|
||||
"capabilities": [
|
||||
"container-runtime"
|
||||
],
|
||||
"emits": [
|
||||
"subtitle.downloaded"
|
||||
],
|
||||
"own-secrets": {
|
||||
"broker": "/var/lib/mesh/bazarr/broker"
|
||||
},
|
||||
"listens": [
|
||||
{
|
||||
"name": "web",
|
||||
"port": 6767,
|
||||
"protocol": "tcp",
|
||||
"from": "mesh",
|
||||
"why": "managing subtitles"
|
||||
}
|
||||
],
|
||||
"accesses": [
|
||||
{
|
||||
"path": "/services/media/movies",
|
||||
"mode": "read-write"
|
||||
},
|
||||
{
|
||||
"path": "/services/media/series",
|
||||
"mode": "read-write"
|
||||
},
|
||||
{
|
||||
"path": "/services/media/anime",
|
||||
"mode": "read-write"
|
||||
},
|
||||
{
|
||||
"path": "/services/media/downloads",
|
||||
"mode": "read"
|
||||
}
|
||||
],
|
||||
"resources": [
|
||||
{
|
||||
"id": "mesh-state",
|
||||
"type": "directory",
|
||||
"path": "/var/lib/mesh/bazarr",
|
||||
"mode": "0700"
|
||||
},
|
||||
{
|
||||
"id": "state",
|
||||
"type": "directory",
|
||||
"mode": "0700",
|
||||
"place": "."
|
||||
},
|
||||
{
|
||||
"id": "config",
|
||||
"type": "directory",
|
||||
"mode": "0700",
|
||||
"owner": "1000:1000"
|
||||
},
|
||||
{
|
||||
"id": "server",
|
||||
"type": "container",
|
||||
"name": "bazarr",
|
||||
"image": "lscr.io/linuxserver/bazarr@sha256:d24bd0048c759a468970989e9df11a6b96a7628d556d00f923e60a35ba59237b",
|
||||
"env": {
|
||||
"PUID": "1000",
|
||||
"PGID": "1000",
|
||||
"TZ": "Etc/UTC"
|
||||
},
|
||||
"ports": [
|
||||
"6767"
|
||||
],
|
||||
"volumes": [
|
||||
"${dir:config}:/config",
|
||||
"/services/media/movies:/movies",
|
||||
"/services/media/series:/series",
|
||||
"/services/media/anime:/anime",
|
||||
"/services/media/downloads:/downloads"
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "runtime-config",
|
||||
"type": "file",
|
||||
"path": "${dir:state}/config.json",
|
||||
"mode": "0600",
|
||||
"content": "{}\n",
|
||||
"merge": "json"
|
||||
},
|
||||
{
|
||||
"id": "runtime",
|
||||
"type": "container",
|
||||
"name": "mesh-bazarr",
|
||||
"network": "host",
|
||||
"volumes": [
|
||||
"/var/lib/mesh/bazarr/broker:/run/secrets/broker:ro",
|
||||
"${dir:state}/config.json:/run/config/config.json:ro",
|
||||
"${dir:config}:/var/lib/bazarr/config:ro"
|
||||
],
|
||||
"env": {
|
||||
"MESH_BROKER_FILE": "/run/secrets/broker",
|
||||
"MESH_BAZARR_URL": "http://127.0.0.1:${port:6767}",
|
||||
"MESH_BAZARR_CONFIG_FILE": "/run/config/config.json",
|
||||
"MESH_BAZARR_CONFIG_DIR": "/var/lib/bazarr/config"
|
||||
},
|
||||
"restart-on": [
|
||||
"runtime-config"
|
||||
],
|
||||
"artifact": "runtime"
|
||||
},
|
||||
{
|
||||
"id": "servarr",
|
||||
"type": "container",
|
||||
"name": "mesh-bazarr-servarr",
|
||||
"network": "host",
|
||||
"run-once": true,
|
||||
"volumes": [
|
||||
"${dir:config}:/var/lib/bazarr/config:ro",
|
||||
"${dir:state}/sonarr-api.json:/run/servarr/sonarr-api.json:ro",
|
||||
"${dir:state}/sonarr-api.secret:/run/servarr/sonarr-api.secret:ro",
|
||||
"${dir:state}/radarr-api.json:/run/servarr/radarr-api.json:ro",
|
||||
"${dir:state}/radarr-api.secret:/run/servarr/radarr-api.secret:ro"
|
||||
],
|
||||
"env": {
|
||||
"MESH_BAZARR_URL": "http://127.0.0.1:${port:6767}",
|
||||
"MESH_BAZARR_CONFIG_DIR": "/var/lib/bazarr/config",
|
||||
"MESH_SERVARR_DIR": "/run/servarr"
|
||||
},
|
||||
"args": [
|
||||
"run",
|
||||
"/app/modules/bazarr/dist/servarr/index.js"
|
||||
],
|
||||
"restart-on": [
|
||||
"bound-sonarr-api",
|
||||
"secret-sonarr-api",
|
||||
"bound-radarr-api",
|
||||
"secret-radarr-api"
|
||||
],
|
||||
"artifact": "runtime"
|
||||
}
|
||||
],
|
||||
"requires": [
|
||||
"radarr-api",
|
||||
"route",
|
||||
"sonarr-api"
|
||||
],
|
||||
"contributes": {
|
||||
"route": {
|
||||
"label": "subs",
|
||||
"endpoint": "web"
|
||||
}
|
||||
},
|
||||
"binds": {
|
||||
"route": "${dir:state}/route.json",
|
||||
"sonarr-api": "${dir:state}/sonarr-api.json",
|
||||
"radarr-api": "${dir:state}/radarr-api.json"
|
||||
},
|
||||
"secrets": {
|
||||
"sonarr-api": "${dir:state}/sonarr-api.secret",
|
||||
"radarr-api": "${dir:state}/radarr-api.secret"
|
||||
},
|
||||
"build": {
|
||||
"on": [
|
||||
{
|
||||
"arg": "BUILD_BASE",
|
||||
"module": "mesh-tools",
|
||||
"artifact": "build"
|
||||
},
|
||||
{
|
||||
"arg": "RUNTIME_BASE",
|
||||
"module": "mesh-tools",
|
||||
"artifact": "runtime"
|
||||
}
|
||||
],
|
||||
"artifacts": [
|
||||
{
|
||||
"name": "runtime",
|
||||
"kind": "image",
|
||||
"from": "Dockerfile"
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
{
|
||||
"name": "@novox/module-bazarr",
|
||||
"version": "0.1.0",
|
||||
"description": "bazarr — subtitle management. Its API client, tools and events live here (novox/hq ADR 0039).",
|
||||
"type": "module",
|
||||
"private": true,
|
||||
"scripts": {
|
||||
"build": "tsc apikey.ts client.ts index.ts tools/index.ts servarr/settings.ts servarr/index.ts --module NodeNext --moduleResolution NodeNext --target ES2022 --outDir dist",
|
||||
"typecheck": "tsc -p tsconfig.json",
|
||||
"test": "node --test --experimental-strip-types 'test/*.test.ts'"
|
||||
},
|
||||
"dependencies": {
|
||||
"@novox/mesh-sdk": "^0.1.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^22.0.0",
|
||||
"typescript": "^5.6.0"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
// bazarr's Servarr step — run once by the host after bazarr's server starts, and run again whenever a
|
||||
// binding or pair credential it reads changes (the container's `restart-on`, novox/hq ADR 0099).
|
||||
//
|
||||
// **A step, not a loop**: everything it does is a function of files the mesh writes, and the host
|
||||
// already knows when they change. It connects to no broker.
|
||||
//
|
||||
// Exits non-zero when any app could not be put right — a refused credential, an unreachable app, a
|
||||
// bazarr that would not keep the settings — so the node reports the step failed and the host runs it
|
||||
// again on the next apply. Declared last in the manifest, so its failing gates nothing else of
|
||||
// bazarr's (novox/hq ADR 0136).
|
||||
//
|
||||
// Reads, per app, `<dir>/<provision>.json` (the binding) and `<dir>/<provision>.secret` (the pair
|
||||
// credential), where <dir> is MESH_SERVARR_DIR; and bazarr's own key from bazarr's own config.yaml
|
||||
// under MESH_BAZARR_CONFIG_DIR. Never prints a key.
|
||||
|
||||
import { join } from "node:path";
|
||||
|
||||
import { apiKeyFromConfigDir } from "../apikey.js";
|
||||
import { APPS, bazarrReady, readBinding, readIfThere, reconcileApp, type Http } from "./settings.js";
|
||||
|
||||
const dir = process.env.MESH_SERVARR_DIR ?? "/run/servarr";
|
||||
const url = process.env.MESH_BAZARR_URL ?? "http://127.0.0.1:6767";
|
||||
const waitSeconds = Number(process.env.MESH_BAZARR_WAIT_SECONDS ?? "180");
|
||||
|
||||
const http: Http = { fetch: (u, init) => fetch(u, init) };
|
||||
|
||||
const bazarrUp = await bazarrReady(http, { url, apiKey: "" }, waitSeconds * 1000);
|
||||
if (!bazarrUp) {
|
||||
console.error(`[bazarr-servarr] bazarr did not answer at ${url} within ${waitSeconds}s`);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
// Read after bazarr answers: on a first start bazarr writes its config.yaml, key included, as it boots.
|
||||
const apiKey = apiKeyFromConfigDir(process.env.MESH_BAZARR_CONFIG_DIR);
|
||||
if (!apiKey) {
|
||||
console.error("[bazarr-servarr] no bazarr API key in bazarr's config/config.yaml under MESH_BAZARR_CONFIG_DIR");
|
||||
process.exit(1);
|
||||
}
|
||||
const bazarr = { url, apiKey };
|
||||
|
||||
let failed = 0;
|
||||
for (const spec of APPS) {
|
||||
const outcome = await reconcileApp(
|
||||
http,
|
||||
bazarr,
|
||||
spec,
|
||||
await readBinding(join(dir, `${spec.provision}.json`)),
|
||||
await readIfThere(join(dir, `${spec.provision}.secret`)),
|
||||
);
|
||||
switch (outcome.result) {
|
||||
case "unchanged":
|
||||
console.log(`[bazarr-servarr] ${outcome.app}: already as the mesh says; key taken by ${outcome.app}`);
|
||||
break;
|
||||
case "written":
|
||||
console.log(`[bazarr-servarr] ${outcome.app}: wrote ${outcome.fields.join(", ")}; key taken by ${outcome.app}`);
|
||||
break;
|
||||
case "refused":
|
||||
failed++;
|
||||
console.error(`[bazarr-servarr] ${outcome.app}: ${outcome.problem}`);
|
||||
break;
|
||||
}
|
||||
}
|
||||
process.exitCode = failed > 0 ? 1 : 0;
|
||||
@@ -0,0 +1,290 @@
|
||||
// Where bazarr reaches Sonarr and Radarr — decided by the mesh, written into bazarr by bazarr's own
|
||||
// API.
|
||||
//
|
||||
// **Why this exists.** bazarr keeps its connection to each app in its own `config/config.yaml`, which
|
||||
// it holds in memory and writes back whenever its settings change — so the mesh cannot own that file
|
||||
// without the two overwriting each other. bazarr requires `sonarr-api` and `radarr-api`; the mesh
|
||||
// delivers, for each, a binding (where the app is: `at`, and what it serves: `port`, `scheme`,
|
||||
// `url-base`) and a pair credential (the app's API key, accepted by the operator — a Servarr app has
|
||||
// exactly one key and the mesh cannot mint it, novox/hq ADR 0092). This step reads those files and
|
||||
// makes bazarr's settings say the same thing, through `POST /api/system/settings` — the call bazarr's
|
||||
// own settings screen makes, which also restarts bazarr's SignalR feed from the app.
|
||||
//
|
||||
// **Only the connection, and only when it differs.** Host, port, TLS, base path and API key. Whether
|
||||
// bazarr uses the app at all (`general.use_sonarr`), sync intervals, excluded tags, path mappings and
|
||||
// every other choice the operator made are left exactly as they are: the mesh knows where the app is,
|
||||
// not what bazarr should do with it.
|
||||
//
|
||||
// **A credential the app refuses is never written.** Until the operator accepts the app's key for this
|
||||
// pair the mesh delivers a value it minted, which no Servarr app accepts. Writing it would replace a
|
||||
// working key in bazarr with a dead one, so the key is tried against the app first; refused, nothing
|
||||
// for that app is written and the step fails naming the `secret accept` that fixes it.
|
||||
//
|
||||
// The same shape as ombi's step (modules/ombi/servarr), repeated rather than shared because a module
|
||||
// is built from its own directory and nothing else (novox/hq ADR 0069). Pure logic and a small HTTP
|
||||
// seam, tested against fakes (test/servarr.test.ts).
|
||||
|
||||
import { readFile } from "node:fs/promises";
|
||||
|
||||
/** One Servarr app bazarr connects to. */
|
||||
export interface ServarrApp {
|
||||
/** The section of bazarr's settings that holds the connection: settings.<app>.* */
|
||||
app: "sonarr" | "radarr";
|
||||
/** The provision it is required as — the manifest's `requires`, `binds` and `secrets` key. */
|
||||
provision: string;
|
||||
/** The app's own status endpoint, which answers 401 to a wrong key. */
|
||||
statusPath: string;
|
||||
}
|
||||
|
||||
export const APPS: readonly ServarrApp[] = [
|
||||
{ app: "sonarr", provision: "sonarr-api", statusPath: "/api/v3/system/status" },
|
||||
{ app: "radarr", provision: "radarr-api", statusPath: "/api/v3/system/status" },
|
||||
];
|
||||
|
||||
/** The connection fields bazarr keeps for an app — the only ones this step ever writes. */
|
||||
export interface Connection {
|
||||
ip: string;
|
||||
port: number;
|
||||
ssl: boolean;
|
||||
/** bazarr's base_url: "" at the root, otherwise "/base". */
|
||||
base_url: string;
|
||||
apikey: string;
|
||||
}
|
||||
|
||||
/** What the mesh wrote at `binds.<provision>`: the binding document. */
|
||||
export interface Binding {
|
||||
provision?: string;
|
||||
from?: string;
|
||||
at?: string;
|
||||
as?: string;
|
||||
serves?: Record<string, unknown>;
|
||||
}
|
||||
|
||||
export type Wanted = { ok: true; connection: Connection; from: string } | { ok: false; problem: string };
|
||||
|
||||
/**
|
||||
* The connection the mesh says bazarr should use. Refused rather than guessed when the binding cannot
|
||||
* be dialled from bazarr's own container: a loopback `at` is bazarr's container itself.
|
||||
*/
|
||||
export function wanted(spec: ServarrApp, binding: Binding | undefined, credential: string | undefined): Wanted {
|
||||
if (!binding) {
|
||||
return { ok: false, problem: `no binding for ${spec.provision} was delivered — the mesh writes it before this step runs` };
|
||||
}
|
||||
const at = typeof binding.at === "string" ? binding.at.trim() : "";
|
||||
const serves = binding.serves ?? {};
|
||||
const port = Number(serves.port);
|
||||
if (!at) return { ok: false, problem: `the ${spec.provision} binding names no host (at)` };
|
||||
if (isLoopback(at)) {
|
||||
return {
|
||||
ok: false,
|
||||
problem:
|
||||
`the ${spec.provision} binding says ${spec.app} is at ${at}, which from bazarr's own container is ` +
|
||||
`bazarr itself. The mesh hands loopback to a machine that is not on the private network; put it ` +
|
||||
`on the private network so ${spec.app} has an address bazarr can dial`,
|
||||
};
|
||||
}
|
||||
if (!Number.isInteger(port) || port <= 0 || port > 65535) {
|
||||
return { ok: false, problem: `the ${spec.provision} binding serves no usable port (${String(serves.port)})` };
|
||||
}
|
||||
const scheme = typeof serves.scheme === "string" && serves.scheme ? serves.scheme : "http";
|
||||
if (scheme !== "http" && scheme !== "https") {
|
||||
return { ok: false, problem: `the ${spec.provision} binding serves scheme ${scheme}, which bazarr cannot dial` };
|
||||
}
|
||||
const key = (credential ?? "").trim();
|
||||
if (!key) return { ok: false, problem: `the ${spec.provision} credential is empty or was not delivered` };
|
||||
return {
|
||||
ok: true,
|
||||
from: typeof binding.from === "string" ? binding.from : "",
|
||||
connection: { ip: at, port, ssl: scheme === "https", base_url: baseUrlOf(serves["url-base"]), apikey: key },
|
||||
};
|
||||
}
|
||||
|
||||
/** A URL base as bazarr stores it: "" for none, else one leading slash and no trailing one. */
|
||||
export function baseUrlOf(urlBase: unknown): string {
|
||||
const trimmed = typeof urlBase === "string" ? urlBase.trim().replace(/^\/+|\/+$/g, "") : "";
|
||||
return trimmed === "" ? "" : `/${trimmed}`;
|
||||
}
|
||||
|
||||
function isLoopback(host: string): boolean {
|
||||
const h = host.toLowerCase();
|
||||
return h === "localhost" || h === "::1" || h === "[::1]" || /^127\./.test(h);
|
||||
}
|
||||
|
||||
/** Which connection fields differ between what bazarr holds and what the mesh says. Names only. */
|
||||
export function differing(current: Record<string, unknown> | undefined, want: Connection): (keyof Connection)[] {
|
||||
const now = current ?? {};
|
||||
const out: (keyof Connection)[] = [];
|
||||
if (String(now.ip ?? "") !== want.ip) out.push("ip");
|
||||
if (Number(now.port ?? 0) !== want.port) out.push("port");
|
||||
if (Boolean(now.ssl) !== want.ssl) out.push("ssl");
|
||||
if (baseUrlOf(now.base_url) !== want.base_url) out.push("base_url");
|
||||
if (String(now.apikey ?? "") !== want.apikey) out.push("apikey");
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* The form bazarr's settings endpoint takes for the differing fields: `settings-<app>-<field>`.
|
||||
* bazarr casts "true"/"false" to booleans and digit strings to integers itself.
|
||||
*/
|
||||
export function settingsForm(spec: ServarrApp, want: Connection, fields: readonly (keyof Connection)[]): URLSearchParams {
|
||||
const form = new URLSearchParams();
|
||||
for (const f of fields) {
|
||||
const v = want[f];
|
||||
form.append(`settings-${spec.app}-${f}`, typeof v === "boolean" ? (v ? "true" : "false") : String(v));
|
||||
}
|
||||
return form;
|
||||
}
|
||||
|
||||
/** The app's base URL as the step dials it — the same host and port bazarr will be given. */
|
||||
export function appUrl(want: Connection): string {
|
||||
const scheme = want.ssl ? "https" : "http";
|
||||
const host = want.ip.includes(":") && !want.ip.startsWith("[") ? `[${want.ip}]` : want.ip;
|
||||
return `${scheme}://${host}:${want.port}${want.base_url}`;
|
||||
}
|
||||
|
||||
/** How one app came out. */
|
||||
export type Outcome =
|
||||
| { app: string; result: "unchanged" }
|
||||
| { app: string; result: "written"; fields: string[] }
|
||||
| { app: string; result: "refused"; problem: string };
|
||||
|
||||
/** The HTTP the step needs, so a test can stand fakes in for bazarr and the apps. */
|
||||
export interface Http {
|
||||
fetch(url: string, init?: { method?: string; headers?: Record<string, string>; body?: string }): Promise<{
|
||||
status: number;
|
||||
text(): Promise<string>;
|
||||
}>;
|
||||
}
|
||||
|
||||
export interface Bazarr {
|
||||
url: string;
|
||||
apiKey: string;
|
||||
}
|
||||
|
||||
async function bazarrCall(http: Http, bazarr: Bazarr, method: string, path: string, form?: URLSearchParams): Promise<unknown> {
|
||||
const res = await http.fetch(`${bazarr.url.replace(/\/$/, "")}/api${path}`, {
|
||||
method,
|
||||
headers: {
|
||||
"X-API-KEY": bazarr.apiKey,
|
||||
Accept: "application/json",
|
||||
...(form ? { "Content-Type": "application/x-www-form-urlencoded" } : {}),
|
||||
},
|
||||
body: form ? form.toString() : undefined,
|
||||
});
|
||||
const text = await res.text();
|
||||
if (res.status < 200 || res.status >= 300) {
|
||||
// bazarr's error body is a message, never a request echo, so it carries no key.
|
||||
throw new Error(`bazarr ${method} ${path} answered ${res.status}${text ? `: ${text.slice(0, 200)}` : ""}`);
|
||||
}
|
||||
return text ? (JSON.parse(text) as unknown) : undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* Does the app take this key? `true` it does, `false` it refused it (401/403), and a thrown error
|
||||
* when it could not be asked.
|
||||
*/
|
||||
export async function appTakes(http: Http, spec: ServarrApp, want: Connection): Promise<boolean> {
|
||||
const res = await http.fetch(`${appUrl(want)}${spec.statusPath}`, {
|
||||
method: "GET",
|
||||
headers: { "X-Api-Key": want.apikey, Accept: "application/json" },
|
||||
});
|
||||
if (res.status === 401 || res.status === 403) return false;
|
||||
if (res.status >= 200 && res.status < 300) return true;
|
||||
throw new Error(`${spec.app} answered ${res.status} at ${spec.statusPath}`);
|
||||
}
|
||||
|
||||
/** The remedy for a refused key, in the controller's own words (ADR 0092). */
|
||||
export function acceptRemedy(spec: ServarrApp, from: string): string {
|
||||
return (
|
||||
`${spec.app} refuses the ${spec.provision} credential the mesh delivered, so it was not written ` +
|
||||
`into bazarr. A Servarr app has one API key and the mesh cannot make it: accept ${spec.app}'s own ` +
|
||||
`key for this pair — \`secret accept <this node> bazarr ${spec.provision} --provider ${from || "<its node>"} ` +
|
||||
`--from <file holding ${spec.app}'s ApiKey>\``
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Bring bazarr's connection to one app in line with the mesh: check the key against the app, compare,
|
||||
* write only the differing connection fields, then read bazarr's settings back to confirm they took.
|
||||
* Never throws: every failure is an outcome with a reason.
|
||||
*/
|
||||
export async function reconcileApp(
|
||||
http: Http,
|
||||
bazarr: Bazarr,
|
||||
spec: ServarrApp,
|
||||
binding: Binding | undefined,
|
||||
credential: string | undefined,
|
||||
): Promise<Outcome> {
|
||||
const w = wanted(spec, binding, credential);
|
||||
// `in`, not `!w.ok`: the Dockerfile compiles without strict, where a boolean discriminant does not
|
||||
// narrow.
|
||||
if ("problem" in w) return { app: spec.app, result: "refused", problem: w.problem };
|
||||
const want = w.connection;
|
||||
|
||||
try {
|
||||
if (!(await appTakes(http, spec, want))) {
|
||||
return { app: spec.app, result: "refused", problem: acceptRemedy(spec, w.from) };
|
||||
}
|
||||
} catch (err) {
|
||||
return {
|
||||
app: spec.app,
|
||||
result: "refused",
|
||||
problem: `${spec.app} could not be asked whether it takes the key at ${want.ip}:${want.port}: ${message(err)}`,
|
||||
};
|
||||
}
|
||||
|
||||
try {
|
||||
const before = await sectionOf(http, bazarr, spec);
|
||||
const fields = differing(before, want);
|
||||
if (fields.length === 0) return { app: spec.app, result: "unchanged" };
|
||||
await bazarrCall(http, bazarr, "POST", "/system/settings", settingsForm(spec, want, fields));
|
||||
const still = differing(await sectionOf(http, bazarr, spec), want);
|
||||
if (still.length > 0) {
|
||||
return { app: spec.app, result: "refused", problem: `bazarr did not keep its ${spec.app} settings (${still.join(", ")})` };
|
||||
}
|
||||
return { app: spec.app, result: "written", fields };
|
||||
} catch (err) {
|
||||
return { app: spec.app, result: "refused", problem: message(err) };
|
||||
}
|
||||
}
|
||||
|
||||
async function sectionOf(http: Http, bazarr: Bazarr, spec: ServarrApp): Promise<Record<string, unknown> | undefined> {
|
||||
const doc = (await bazarrCall(http, bazarr, "GET", "/system/settings")) as Record<string, unknown> | undefined;
|
||||
return doc?.[spec.app] as Record<string, unknown> | undefined;
|
||||
}
|
||||
|
||||
/** Wait for bazarr to answer, because the step runs right after its container starts. */
|
||||
export async function bazarrReady(http: Http, bazarr: Bazarr, waitMs: number, pauseMs = 2000): Promise<boolean> {
|
||||
const until = Date.now() + waitMs;
|
||||
for (;;) {
|
||||
try {
|
||||
const res = await http.fetch(`${bazarr.url.replace(/\/$/, "")}/api/system/ping`, { method: "GET" });
|
||||
if (res.status === 200) return true;
|
||||
} catch {
|
||||
// not listening yet
|
||||
}
|
||||
if (Date.now() >= until) return false;
|
||||
await new Promise((r) => setTimeout(r, pauseMs));
|
||||
}
|
||||
}
|
||||
|
||||
/** A file the mesh wrote, or undefined when it is not there. */
|
||||
export async function readIfThere(path: string | undefined): Promise<string | undefined> {
|
||||
if (!path) return undefined;
|
||||
return readFile(path, "utf8").catch(() => undefined);
|
||||
}
|
||||
|
||||
/** A binding file parsed, or undefined when absent or not JSON. */
|
||||
export async function readBinding(path: string | undefined): Promise<Binding | undefined> {
|
||||
const raw = await readIfThere(path);
|
||||
if (raw === undefined) return undefined;
|
||||
try {
|
||||
return JSON.parse(raw) as Binding;
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
function message(err: unknown): string {
|
||||
return err instanceof Error ? err.message : String(err);
|
||||
}
|
||||
@@ -0,0 +1,156 @@
|
||||
// What holds bazarr's Servarr step (servarr/settings.ts): the connection bazarr keeps for Sonarr and
|
||||
// Radarr is made to say what the mesh bound — host, port, TLS, base path, key — and nothing else
|
||||
// bazarr keeps is sent; nothing is written when nothing differs; and a key the app refuses (the mesh's
|
||||
// own minted value, before the operator accepts the app's key) is never written, with the
|
||||
// `secret accept` that fixes it named. Also: bazarr's own key is found in its config.yaml's `auth`
|
||||
// section and not in the `sonarr`/`radarr` sections that also carry an `apikey`.
|
||||
//
|
||||
// bazarr and the apps are fakes answering as the real ones do (checked against
|
||||
// lscr.io/linuxserver/bazarr v1.6.1-ls364: GET/POST /api/system/settings with X-API-KEY, the form
|
||||
// keys `settings-<section>-<field>`, 204 on save).
|
||||
|
||||
import { test } from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
|
||||
import { apiKeyFromConfigYaml } from "../apikey.ts";
|
||||
import { APPS, baseUrlOf, differing, reconcileApp, wanted, type Binding, type Http, type ServarrApp } from "../servarr/settings.ts";
|
||||
|
||||
const SONARR = APPS.find((a) => a.app === "sonarr") as ServarrApp;
|
||||
const RADARR = APPS.find((a) => a.app === "radarr") as ServarrApp;
|
||||
const THE_KEY = "the-apps-own-key";
|
||||
const BAZARR = { url: "http://127.0.0.1:6767", apiKey: "bazarr-key" };
|
||||
|
||||
function binding(provision: string, port: number, at = "ace.internal"): Binding {
|
||||
return { binding: 1, provision, from: "ace", at, as: "mesh_ace_bazarr", serves: { scheme: "http", port, "url-base": "" } } as Binding;
|
||||
}
|
||||
|
||||
interface Call {
|
||||
method: string;
|
||||
url: string;
|
||||
body?: string;
|
||||
}
|
||||
|
||||
/** bazarr's settings (one document, sections per app) and the apps' key check, behind one fetch. */
|
||||
function fakes(settings: Record<string, Record<string, unknown>>, opts: { appKey?: string; reachable?: boolean } = {}) {
|
||||
const calls: Call[] = [];
|
||||
const appKey = opts.appKey ?? THE_KEY;
|
||||
const http: Http = {
|
||||
async fetch(url, init) {
|
||||
const method = init?.method ?? "GET";
|
||||
calls.push({ method, url, body: init?.body });
|
||||
const reply = (status: number, value?: unknown) => ({
|
||||
status,
|
||||
text: async () => (value === undefined ? "" : JSON.stringify(value)),
|
||||
});
|
||||
const u = new URL(url);
|
||||
if (u.pathname.endsWith("/system/status")) {
|
||||
if (opts.reachable === false) throw new Error("connect ECONNREFUSED");
|
||||
return init?.headers?.["X-Api-Key"] === appKey ? reply(200, { version: "4" }) : reply(401);
|
||||
}
|
||||
if (init?.headers?.["X-API-KEY"] !== BAZARR.apiKey) return reply(401);
|
||||
if (u.pathname !== "/api/system/settings") return reply(404);
|
||||
if (method === "GET") return reply(200, settings);
|
||||
// bazarr's save_settings: split the key, cast as bazarr casts, store.
|
||||
for (const [k, raw] of new URLSearchParams(init?.body ?? "")) {
|
||||
const [, section, field] = k.split("-");
|
||||
let v: unknown = raw;
|
||||
if (raw === "true") v = true;
|
||||
else if (raw === "false") v = false;
|
||||
else if (/^\d+$/.test(raw)) v = Number(raw);
|
||||
settings[section] = { ...(settings[section] ?? {}), [field]: v };
|
||||
}
|
||||
return reply(204);
|
||||
},
|
||||
};
|
||||
return { http, calls, settings };
|
||||
}
|
||||
|
||||
/** ace's bazarr today: the apps by container name on HAL's shared network. */
|
||||
function aceToday(): Record<string, Record<string, unknown>> {
|
||||
return {
|
||||
general: { use_sonarr: true, use_radarr: true, port: 6767 },
|
||||
sonarr: { ip: "sonarr", port: 8989, ssl: false, base_url: "", apikey: THE_KEY, series_sync: 15, excluded_series_types: ["anime"] },
|
||||
radarr: { ip: "radarr", port: 7878, ssl: false, base_url: "", apikey: THE_KEY, movies_sync: 15 },
|
||||
};
|
||||
}
|
||||
|
||||
test("moving an app writes only host and port, and leaves every other setting alone", async () => {
|
||||
const f = fakes(aceToday());
|
||||
const out = await reconcileApp(f.http, BAZARR, SONARR, binding("sonarr-api", 20010), THE_KEY);
|
||||
assert.deepEqual(out, { app: "sonarr", result: "written", fields: ["ip", "port"] });
|
||||
const post = f.calls.find((c) => c.method === "POST");
|
||||
assert.ok(post);
|
||||
assert.deepEqual([...new URLSearchParams(post.body ?? "").keys()].sort(), ["settings-sonarr-ip", "settings-sonarr-port"]);
|
||||
assert.equal(f.settings.sonarr.ip, "ace.internal");
|
||||
assert.equal(f.settings.sonarr.port, 20010);
|
||||
assert.deepEqual(f.settings.sonarr.excluded_series_types, ["anime"]);
|
||||
assert.equal(f.settings.radarr.ip, "radarr", "radarr is its own app and was not touched");
|
||||
});
|
||||
|
||||
test("nothing is written when bazarr already says what the mesh says", async () => {
|
||||
const s = aceToday();
|
||||
s.radarr = { ...s.radarr, ip: "ace.internal", port: 20011 };
|
||||
const f = fakes(s);
|
||||
const out = await reconcileApp(f.http, BAZARR, RADARR, binding("radarr-api", 20011), THE_KEY);
|
||||
assert.deepEqual(out, { app: "radarr", result: "unchanged" });
|
||||
assert.equal(f.calls.filter((c) => c.method === "POST").length, 0);
|
||||
});
|
||||
|
||||
test("a key the app refuses is never written, and the remedy is named", async () => {
|
||||
const f = fakes(aceToday());
|
||||
const out = await reconcileApp(f.http, BAZARR, SONARR, binding("sonarr-api", 20010), "a-value-the-mesh-minted");
|
||||
assert.equal(out.result, "refused");
|
||||
assert.match((out as { problem: string }).problem, /secret accept <this node> bazarr sonarr-api --provider ace/);
|
||||
assert.equal(f.calls.filter((c) => c.method === "POST").length, 0);
|
||||
assert.equal(f.settings.sonarr.apikey, THE_KEY, "the working key stays");
|
||||
assert.equal(f.settings.sonarr.ip, "sonarr", "nothing moved either");
|
||||
});
|
||||
|
||||
test("an unreachable app writes nothing", async () => {
|
||||
const f = fakes(aceToday(), { reachable: false });
|
||||
const out = await reconcileApp(f.http, BAZARR, SONARR, binding("sonarr-api", 20010), THE_KEY);
|
||||
assert.equal(out.result, "refused");
|
||||
assert.equal(f.calls.filter((c) => c.method === "POST").length, 0);
|
||||
});
|
||||
|
||||
test("a loopback binding is refused: from bazarr's container that is bazarr", () => {
|
||||
const w = wanted(SONARR, binding("sonarr-api", 8989, "127.0.0.1"), THE_KEY);
|
||||
assert.equal(w.ok, false);
|
||||
});
|
||||
|
||||
test("a new key is written when the operator accepted a different one", async () => {
|
||||
const s = aceToday();
|
||||
s.sonarr = { ...s.sonarr, ip: "ace.internal", port: 20010, apikey: "an-old-key" };
|
||||
const f = fakes(s);
|
||||
const out = await reconcileApp(f.http, BAZARR, SONARR, binding("sonarr-api", 20010), THE_KEY);
|
||||
assert.deepEqual(out, { app: "sonarr", result: "written", fields: ["apikey"] });
|
||||
assert.equal(f.settings.sonarr.apikey, THE_KEY);
|
||||
});
|
||||
|
||||
test("base paths compare as bazarr stores them", () => {
|
||||
assert.equal(baseUrlOf(""), "");
|
||||
assert.equal(baseUrlOf("/"), "");
|
||||
assert.equal(baseUrlOf("sonarr/"), "/sonarr");
|
||||
const want = { ip: "a", port: 1, ssl: false, base_url: "", apikey: "k" };
|
||||
assert.deepEqual(differing({ ip: "a", port: 1, ssl: false, base_url: "/", apikey: "k" }, want), []);
|
||||
});
|
||||
|
||||
test("bazarr's own key is auth.apikey, not an app's", () => {
|
||||
const yaml = [
|
||||
"analytics:",
|
||||
" enabled: false",
|
||||
"auth:",
|
||||
" apikey: 0123456789abcdef0123456789abcdef",
|
||||
" password: ''",
|
||||
" type: form",
|
||||
"general:",
|
||||
" port: 6767",
|
||||
"sonarr:",
|
||||
" apikey: not-this-one",
|
||||
"",
|
||||
].join("\n");
|
||||
assert.equal(apiKeyFromConfigYaml(yaml), "0123456789abcdef0123456789abcdef");
|
||||
assert.equal(apiKeyFromConfigYaml("sonarr:\n apikey: x\n"), undefined);
|
||||
assert.equal(apiKeyFromConfigYaml("auth:\n apikey: ''\n"), undefined);
|
||||
assert.equal(apiKeyFromConfigYaml("auth:\r\n apikey: 'abc'\r\n"), "abc");
|
||||
});
|
||||
@@ -0,0 +1,57 @@
|
||||
// bazarr's tools — its own code (novox/hq ADR 0039), importing bazarr's client. They return
|
||||
// structured data; the mesh serves them through the sdk's tool harness.
|
||||
|
||||
import { registerModuleTools, type ToolDefinition } from "@novox/mesh-sdk/tools";
|
||||
import { BazarrClient } from "../client.js";
|
||||
|
||||
export function getBazarrTools(bazarr: BazarrClient): ToolDefinition[] {
|
||||
return [
|
||||
{
|
||||
name: "bazarr_wanted",
|
||||
description: "Episodes and movies still missing subtitles, with the languages each still needs.",
|
||||
input: { limit: { type: "number", description: "max items per kind (default 50)" } },
|
||||
run: async (args) => {
|
||||
const wanted = await bazarr.getWanted(args.limit ? Number(args.limit) : 50);
|
||||
return { count: wanted.length, wanted };
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "bazarr_search_subtitles",
|
||||
description: "Manually search subtitle providers for one wanted item — pass an episodeId or a radarrId.",
|
||||
input: {
|
||||
episodeId: { type: "number", description: "a Sonarr episode id (from bazarr_wanted)" },
|
||||
radarrId: { type: "number", description: "a Radarr movie id (from bazarr_wanted)" },
|
||||
},
|
||||
run: async (args) => {
|
||||
if (args.episodeId !== undefined) {
|
||||
const results = await bazarr.searchEpisode(Number(args.episodeId));
|
||||
return { kind: "episode", episodeId: Number(args.episodeId), count: results.length, results };
|
||||
}
|
||||
if (args.radarrId !== undefined) {
|
||||
const results = await bazarr.searchMovie(Number(args.radarrId));
|
||||
return { kind: "movie", radarrId: Number(args.radarrId), count: results.length, results };
|
||||
}
|
||||
throw new Error("pass either episodeId or radarrId");
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "bazarr_history",
|
||||
description: "Recent subtitle-download history — what was downloaded, for which title, from which provider.",
|
||||
input: { limit: { type: "number", description: "max entries per kind (default 40)" } },
|
||||
run: async (args) => {
|
||||
const history = await bazarr.getHistory(args.limit ? Number(args.limit) : 40);
|
||||
return { count: history.length, history };
|
||||
},
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
// Exposed only when Bazarr is configured; otherwise bazarr contributes no tools rather than
|
||||
// failing the whole runtime.
|
||||
registerModuleTools("bazarr", (env) => {
|
||||
try {
|
||||
return getBazarrTools(BazarrClient.fromEnv(env));
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
});
|
||||
@@ -8,5 +8,5 @@
|
||||
"skipLibCheck": true,
|
||||
"noEmit": true
|
||||
},
|
||||
"include": ["records.ts", "index.ts", "tools/index.ts"]
|
||||
"include": ["apikey.ts", "client.ts", "index.ts", "tools/index.ts", "servarr/settings.ts", "servarr/index.ts"]
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
# bookshelf's runtime: the tool runtime, carrying this module's compiled code.
|
||||
#
|
||||
# **Built from this module's own directory and nothing else.** The sdk and the tool runtime are in
|
||||
# the base images, published like any other artifact — which is what makes this buildable by the
|
||||
# mesh from a repository and a path (novox/hq ADR 0069) rather than only on a workstation that
|
||||
# happens to have the siblings.
|
||||
#
|
||||
# Two bases, named rather than pinned (novox/hq issue 044): the image this is COMPILED in and the
|
||||
# image it RUNS in — the second must not carry a compiler. Declared in module.json's `build.on`.
|
||||
ARG BUILD_BASE
|
||||
ARG RUNTIME_BASE
|
||||
|
||||
FROM ${BUILD_BASE} AS build
|
||||
WORKDIR /app/modules/bookshelf
|
||||
COPY . .
|
||||
RUN node /app/node_modules/typescript/bin/tsc client.ts index.ts tools/index.ts \
|
||||
--module NodeNext --moduleResolution NodeNext --target ES2022 --outDir dist
|
||||
|
||||
FROM ${RUNTIME_BASE}
|
||||
COPY --from=build /app/modules/bookshelf/dist /app/modules/bookshelf/dist
|
||||
# Every serve-time entrypoint, loaded by the runtime in serve mode: tools and events serve, and a
|
||||
# provider's provisioner runs its reconcile loop in the same process, with the broker connected —
|
||||
# the convention novox/hq issues 060/061 settled.
|
||||
ENV MESH_TOOL_MODULES=/app/modules/bookshelf/dist/index.js,/app/modules/bookshelf/dist/tools/index.js
|
||||
@@ -0,0 +1,136 @@
|
||||
// The Bookshelf API client — bookshelf's own code, living in the module (novox/hq ADR 0039).
|
||||
// Ported from the shared hal `arr` client, but self-contained: in nox each Servarr app owns its own
|
||||
// copy, so a change to Bookshelf's API rebuilds only bookshelf and nothing else. Both this module's
|
||||
// tools and its events entrypoint import it, and nothing outside bookshelf does.
|
||||
//
|
||||
// Bookshelf is a Readarr fork (ghcr.io/pennydreadful/bookshelf). It speaks the Servarr v1 API; its
|
||||
// content is "book". Unlike Sonarr/Radarr it exposes no calendar endpoint, so there is no calendar
|
||||
// tool here — matching hal, which excluded bookshelf from its calendar-capable apps.
|
||||
|
||||
import { existsSync, readFileSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
|
||||
// Bookshelf speaks the v1 API; its content is "book".
|
||||
const API_VERSION = "v1";
|
||||
const CONTENT_ENDPOINT = "book";
|
||||
const APP_NAME = "Bookshelf";
|
||||
|
||||
export interface BookshelfQueueItem {
|
||||
/** The queue record id — stable while the item is in the queue, so events can diff on it. */
|
||||
id: number;
|
||||
title: string;
|
||||
status: string;
|
||||
size: string;
|
||||
sizeleft: string;
|
||||
timeleft?: string;
|
||||
}
|
||||
|
||||
export interface BookshelfContentItem {
|
||||
title: string;
|
||||
author?: string;
|
||||
year?: number;
|
||||
status?: string;
|
||||
monitored: boolean;
|
||||
}
|
||||
|
||||
export class BookshelfClient {
|
||||
readonly baseUrl: string;
|
||||
|
||||
constructor(
|
||||
url: string,
|
||||
private readonly apiKey: string,
|
||||
) {
|
||||
this.baseUrl = url.replace(/\/$/, "");
|
||||
}
|
||||
|
||||
/**
|
||||
* Build from the module's resolved environment. The URL defaults to the server on this node (the
|
||||
* runtime shares its network), and the API key is read from MESH_BOOKSHELF_API_KEY or, failing
|
||||
* that, discovered from the server's own config.xml under MESH_BOOKSHELF_CONFIG_DIR — the same
|
||||
* file Bookshelf writes it to, so a running server needs nothing configured by hand. Throws when
|
||||
* no key can be found, so the tools/events simply do not load (the harness treats the throw as
|
||||
* "exposes nothing").
|
||||
*/
|
||||
static fromEnv(env: NodeJS.ProcessEnv = process.env): BookshelfClient {
|
||||
const url = env.MESH_BOOKSHELF_URL ?? `http://127.0.0.1:${env.MESH_BOOKSHELF_PORT ?? "8787"}`;
|
||||
const configDir = env.MESH_BOOKSHELF_CONFIG_DIR ?? "/config";
|
||||
const apiKey = env.MESH_BOOKSHELF_API_KEY ?? BookshelfClient.detectApiKey(configDir);
|
||||
if (!apiKey) {
|
||||
throw new Error("Bookshelf not configured — set MESH_BOOKSHELF_API_KEY or make the config dir readable");
|
||||
}
|
||||
return new BookshelfClient(url, apiKey);
|
||||
}
|
||||
|
||||
/** Discover the API key from the server's config.xml, falling back to null. Every Servarr app
|
||||
* writes <ApiKey> into config.xml at the root of its config directory. */
|
||||
static detectApiKey(configDir: string): string | null {
|
||||
const config = join(configDir, "config.xml");
|
||||
if (existsSync(config)) {
|
||||
const match = readFileSync(config, "utf8").match(/<ApiKey>([^<]+)<\/ApiKey>/);
|
||||
if (match) return match[1];
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private async get(endpoint: string, params?: Record<string, string>): Promise<unknown> {
|
||||
const url = new URL(`${this.baseUrl}/api/${API_VERSION}/${endpoint}`);
|
||||
if (params) {
|
||||
for (const [k, v] of Object.entries(params)) url.searchParams.set(k, v);
|
||||
}
|
||||
const res = await fetch(url.toString(), { headers: { "X-Api-Key": this.apiKey } });
|
||||
if (!res.ok) throw new Error(`${APP_NAME} API /${endpoint}: ${res.status} ${await res.text()}`);
|
||||
return res.json();
|
||||
}
|
||||
|
||||
async getStatus(): Promise<{ appName: string; version: string }> {
|
||||
const data = (await this.get("system/status")) as { appName?: string; version?: string };
|
||||
return { appName: data.appName || APP_NAME, version: data.version ?? "unknown" };
|
||||
}
|
||||
|
||||
async getContent(limit?: number): Promise<BookshelfContentItem[]> {
|
||||
const data = await this.get(CONTENT_ENDPOINT);
|
||||
const items: any[] = Array.isArray(data) ? data : ((data as any)?.records ?? []);
|
||||
const mapped = items.map((item) => ({
|
||||
title: item.title ?? "Unknown",
|
||||
author: item.author?.authorName ?? item.authorName,
|
||||
year: item.releaseDate ? new Date(item.releaseDate).getFullYear() : item.year,
|
||||
status: item.status,
|
||||
monitored: item.monitored ?? true,
|
||||
}));
|
||||
return limit ? mapped.slice(0, limit) : mapped;
|
||||
}
|
||||
|
||||
/** Library search is a filter over existing content, not an indexer lookup — same as hal's. */
|
||||
async searchContent(term: string): Promise<BookshelfContentItem[]> {
|
||||
const all = await this.getContent();
|
||||
const lower = term.toLowerCase();
|
||||
return all.filter(
|
||||
(item) =>
|
||||
item.title.toLowerCase().includes(lower) ||
|
||||
(item.author?.toLowerCase().includes(lower) ?? false),
|
||||
);
|
||||
}
|
||||
|
||||
async getQueue(): Promise<{ totalRecords: number; items: BookshelfQueueItem[] }> {
|
||||
const data = (await this.get("queue", { pageSize: "50" })) as { totalRecords?: number; records?: any[] };
|
||||
const records = data.records ?? [];
|
||||
return {
|
||||
totalRecords: data.totalRecords ?? records.length,
|
||||
items: records.map((r) => ({
|
||||
id: r.id,
|
||||
title: r.title ?? r.book?.title ?? r.author?.authorName ?? "Unknown",
|
||||
status: r.status ?? "unknown",
|
||||
size: formatBytes(r.size ?? 0),
|
||||
sizeleft: formatBytes(r.sizeleft ?? 0),
|
||||
timeleft: r.timeleft,
|
||||
})),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
function formatBytes(bytes: number): string {
|
||||
if (bytes === 0) return "0 B";
|
||||
const units = ["B", "KB", "MB", "GB", "TB"];
|
||||
const i = Math.floor(Math.log(bytes) / Math.log(1024));
|
||||
return `${(bytes / Math.pow(1024, i)).toFixed(1)} ${units[i]}`;
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
// bookshelf's events. The tool runtime imports this once the broker is bound. It watches the
|
||||
// download queue and turns its comings and goings into mesh events — the same mechanism radarr uses,
|
||||
// applied to a Servarr book manager.
|
||||
//
|
||||
// Emits (novox/hq ADR 0041/0042):
|
||||
// module.bookshelf.book.grabbed — a release entered the queue (Bookshelf grabbed it)
|
||||
// module.bookshelf.download.completed — a release left the queue, imported. This routing key is
|
||||
// what the plex module consumes (module.*.download.completed)
|
||||
// to rescan, so a new audiobook becomes a visible item.
|
||||
// Consumes: none.
|
||||
//
|
||||
// NOTE: the hal bookshelf module emitted no events (its hooks only did install-time provisioning).
|
||||
// This queue watcher is new in nox, modelled exactly on radarr's — bookshelf is a Servarr app with
|
||||
// the same queue semantics, so the diff-and-emit pattern carries over unchanged.
|
||||
//
|
||||
// The queue is polled and diffed, primed silently on the first look (like plex's index.ts) so a
|
||||
// restart mid-download does not re-announce everything already in flight as freshly grabbed.
|
||||
|
||||
import { emit } from "@novox/mesh-sdk/events";
|
||||
import { BookshelfClient, type BookshelfQueueItem } from "./client.js";
|
||||
|
||||
// Building the client throws when Bookshelf has no URL/key yet. Like the tools (see tools/index.ts),
|
||||
// the events entrypoint must not crash the runtime for that — it stays idle until configured.
|
||||
function buildClient(): BookshelfClient | null {
|
||||
try {
|
||||
return BookshelfClient.fromEnv();
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
const bookshelf = buildClient();
|
||||
|
||||
// Bookshelf removes an item from the queue once it has been imported; a "warning"/"failed" status is
|
||||
// how a stuck or broken grab shows itself, so we do not call those a completion when they vanish.
|
||||
const FAILED_STATUSES = new Set(["failed", "warning"]);
|
||||
|
||||
const inQueue = new Map<number, BookshelfQueueItem>();
|
||||
let primed = false;
|
||||
|
||||
async function pollQueue(bookshelf: BookshelfClient): Promise<void> {
|
||||
const { items } = await bookshelf.getQueue();
|
||||
const now = new Map(items.map((i) => [i.id, i]));
|
||||
|
||||
if (primed) {
|
||||
// Entered the queue since last look — Bookshelf grabbed a release.
|
||||
for (const [id, item] of now) {
|
||||
if (!inQueue.has(id)) await emit("book.grabbed", { title: item.title, status: item.status });
|
||||
}
|
||||
// Left the queue — imported and done, unless it was last seen failing.
|
||||
for (const [id, item] of inQueue) {
|
||||
if (!now.has(id) && !FAILED_STATUSES.has(item.status)) {
|
||||
await emit("download.completed", { title: item.title });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
inQueue.clear();
|
||||
for (const [id, item] of now) inQueue.set(id, item);
|
||||
primed = true;
|
||||
}
|
||||
|
||||
const tick = (fn: () => Promise<void>, everyMs: number): void => {
|
||||
const run = (): void => void fn().catch((err) => console.error(`[bookshelf] ${err}`));
|
||||
setInterval(run, everyMs);
|
||||
run();
|
||||
};
|
||||
|
||||
if (bookshelf) {
|
||||
tick(() => pollQueue(bookshelf), 30_000);
|
||||
console.log("[bookshelf] watching the download queue, emitting grabs and completions");
|
||||
} else {
|
||||
console.log("[bookshelf] not configured — events idle until an API key is available");
|
||||
}
|
||||
@@ -0,0 +1,118 @@
|
||||
{
|
||||
"module": "bookshelf",
|
||||
"version": "1",
|
||||
"slug": "books",
|
||||
"capabilities": [
|
||||
"container-runtime"
|
||||
],
|
||||
"emits": [
|
||||
"book.grabbed",
|
||||
"download.completed"
|
||||
],
|
||||
"consumes": [],
|
||||
"own-secrets": {
|
||||
"broker": "/var/lib/mesh/bookshelf/broker"
|
||||
},
|
||||
"listens": [
|
||||
{
|
||||
"name": "web",
|
||||
"port": 8787,
|
||||
"protocol": "tcp",
|
||||
"from": "mesh",
|
||||
"why": "managing the ebook/audiobook library"
|
||||
}
|
||||
],
|
||||
"accesses": [
|
||||
{
|
||||
"path": "/services/media/books",
|
||||
"mode": "read-write"
|
||||
},
|
||||
{
|
||||
"path": "/services/media/downloads",
|
||||
"mode": "read-write"
|
||||
}
|
||||
],
|
||||
"resources": [
|
||||
{
|
||||
"id": "mesh-state",
|
||||
"type": "directory",
|
||||
"path": "/var/lib/mesh/bookshelf",
|
||||
"mode": "0700"
|
||||
},
|
||||
{
|
||||
"id": "config",
|
||||
"type": "directory",
|
||||
"path": "/services/bookshelf/config",
|
||||
"mode": "0700",
|
||||
"owner": "1000:1000"
|
||||
},
|
||||
{
|
||||
"id": "server",
|
||||
"type": "container",
|
||||
"name": "bookshelf",
|
||||
"image": "ghcr.io/pennydreadful/bookshelf@sha256:388eecc94362580eae31ee0a454be6af516f8a311f8432a521c202fb475f4359",
|
||||
"env": {
|
||||
"PUID": "1000",
|
||||
"PGID": "1000",
|
||||
"TZ": "Etc/UTC"
|
||||
},
|
||||
"ports": [
|
||||
"8787"
|
||||
],
|
||||
"volumes": [
|
||||
"/services/bookshelf/config:/config",
|
||||
"/services/media/books:/books",
|
||||
"/services/media/downloads:/downloads"
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "runtime",
|
||||
"type": "container",
|
||||
"name": "mesh-bookshelf",
|
||||
"network": "host",
|
||||
"volumes": [
|
||||
"/var/lib/mesh/bookshelf/broker:/run/secrets/broker:ro",
|
||||
"/services/bookshelf/config:/var/lib/bookshelf/config:ro"
|
||||
],
|
||||
"env": {
|
||||
"MESH_BROKER_FILE": "/run/secrets/broker",
|
||||
"MESH_BOOKSHELF_URL": "http://127.0.0.1:${port:8787}",
|
||||
"MESH_BOOKSHELF_CONFIG_DIR": "/var/lib/bookshelf/config"
|
||||
},
|
||||
"artifact": "runtime"
|
||||
}
|
||||
],
|
||||
"requires": [
|
||||
"route"
|
||||
],
|
||||
"contributes": {
|
||||
"route": {
|
||||
"label": "books",
|
||||
"endpoint": "web"
|
||||
}
|
||||
},
|
||||
"binds": {
|
||||
"route": "/var/lib/mesh/bookshelf/route.json"
|
||||
},
|
||||
"build": {
|
||||
"on": [
|
||||
{
|
||||
"arg": "BUILD_BASE",
|
||||
"module": "mesh-tools",
|
||||
"artifact": "build"
|
||||
},
|
||||
{
|
||||
"arg": "RUNTIME_BASE",
|
||||
"module": "mesh-tools",
|
||||
"artifact": "runtime"
|
||||
}
|
||||
],
|
||||
"artifacts": [
|
||||
{
|
||||
"name": "runtime",
|
||||
"kind": "image",
|
||||
"from": "Dockerfile"
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
{
|
||||
"name": "@novox/module-bookshelf",
|
||||
"version": "0.1.0",
|
||||
"description": "bookshelf — ebook/audiobook management (Readarr fork). Its API client, tools and events live here (novox/hq ADR 0039).",
|
||||
"type": "module",
|
||||
"private": true,
|
||||
"dependencies": {
|
||||
"@novox/mesh-sdk": "^0.1.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^22.0.0",
|
||||
"typescript": "^5.6.0"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
// bookshelf's tools — ported from the shared hal `arr` sdk (novox/hq ADR 0039), importing
|
||||
// bookshelf's own client. They return structured data (not the pre-formatted text hal returned); the
|
||||
// mesh serves them through the sdk's tool harness. Bookshelf has no calendar endpoint, so there is
|
||||
// no calendar tool — matching hal, which excluded it from its calendar-capable apps.
|
||||
|
||||
import { registerModuleTools, type ToolDefinition } from "@novox/mesh-sdk/tools";
|
||||
import { BookshelfClient } from "../client.js";
|
||||
|
||||
export function getBookshelfTools(bookshelf: BookshelfClient): ToolDefinition[] {
|
||||
return [
|
||||
{
|
||||
name: "bookshelf_status",
|
||||
description: "Bookshelf status overview: version, book count, monitored count, queue size.",
|
||||
input: {},
|
||||
run: async () => {
|
||||
const [status, content, queue] = await Promise.all([
|
||||
bookshelf.getStatus(),
|
||||
bookshelf.getContent(),
|
||||
bookshelf.getQueue(),
|
||||
]);
|
||||
return {
|
||||
app: status.appName,
|
||||
version: status.version,
|
||||
books: content.length,
|
||||
monitored: content.filter((c) => c.monitored).length,
|
||||
queue: queue.totalRecords,
|
||||
};
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "bookshelf_library",
|
||||
description: "List books from the Bookshelf library.",
|
||||
input: { limit: { type: "number", description: "max items to return (default 50)" } },
|
||||
run: async (args) => {
|
||||
const items = await bookshelf.getContent(args.limit ? Number(args.limit) : 50);
|
||||
return { count: items.length, books: items };
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "bookshelf_search",
|
||||
description:
|
||||
"Search the Bookshelf library for books by title or author (filters existing content, not indexers).",
|
||||
input: { query: { type: "string", description: "the search term" } },
|
||||
run: async (args) => {
|
||||
const query = String(args.query);
|
||||
return { query, results: await bookshelf.searchContent(query) };
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "bookshelf_queue",
|
||||
description: "Show the Bookshelf download queue — what is downloading and how far along.",
|
||||
input: {},
|
||||
run: async () => {
|
||||
const queue = await bookshelf.getQueue();
|
||||
return { count: queue.totalRecords, items: queue.items };
|
||||
},
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
// The tools exist only when Bookshelf is configured; without a URL and key, bookshelf contributes
|
||||
// none rather than failing the whole runtime.
|
||||
registerModuleTools("bookshelf", (env) => {
|
||||
try {
|
||||
return getBookshelfTools(BookshelfClient.fromEnv(env));
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
});
|
||||
@@ -8,8 +8,5 @@
|
||||
"skipLibCheck": true,
|
||||
"noEmit": true
|
||||
},
|
||||
"include": [
|
||||
"tools/index.ts",
|
||||
"client.ts"
|
||||
]
|
||||
"include": ["client.ts", "index.ts", "tools/index.ts"]
|
||||
}
|
||||
@@ -1,15 +0,0 @@
|
||||
# build-agent
|
||||
|
||||
The mesh's build machine as a role every machine can hold (novox/hq ADR 0190). It holds the node seat
|
||||
`node-build-agent`: every holder pulls one build at a time from the role's one work queue when it is
|
||||
idle, so a tier of many images is built by as many machines as hold the seat and are online, and a
|
||||
machine that is off builds nothing and blocks nothing. The controller asks the role, never a machine;
|
||||
the outcome names the machine that built it.
|
||||
|
||||
What a holding machine needs is what the builder always needed, said here once: a container runtime
|
||||
(the socket is mounted), the artifact store and the package registry as provisions, a workspace, and
|
||||
the bus credential. The code is `cmd/mesh-builder` in the mesh-controller repository, compiled from
|
||||
that repository's main (`build.artifacts[].context`); this module ships the packaging.
|
||||
|
||||
Assign it to every machine with a container runtime. It replaces `builder`, the one-holder form of the
|
||||
same thing; retire that once this is assigned where it was.
|
||||
@@ -1,6 +1,6 @@
|
||||
ARG GO_BASE
|
||||
ARG ALPINE_BASE
|
||||
# build-agent's image: the build machine itself, compiled into a container (novox/hq ADR 0190).
|
||||
# builder's own image: the build machine itself, compiled into a container.
|
||||
#
|
||||
# **The source is not vendored here.** builder's actual code — cmd/mesh-builder, internal/builder,
|
||||
# internal/catalogue — lives in the mesh-controller repository, the same control plane it is one
|
||||
@@ -1,14 +1,13 @@
|
||||
{
|
||||
"module": "build-agent",
|
||||
"module": "builder",
|
||||
"version": "1",
|
||||
"slug": "agent",
|
||||
"capabilities": [
|
||||
"container-runtime"
|
||||
],
|
||||
"claims": [
|
||||
{
|
||||
"name": "node-build-agent",
|
||||
"scope": "node"
|
||||
"name": "mesh-build-machine",
|
||||
"scope": "mesh"
|
||||
}
|
||||
],
|
||||
"requires": [
|
||||
@@ -16,48 +15,49 @@
|
||||
"npm-package-registry"
|
||||
],
|
||||
"binds": {
|
||||
"npm-package-registry": "${dir:mesh-state}/package-registry.json"
|
||||
"npm-package-registry": "/var/lib/mesh/builder/package-registry.json"
|
||||
},
|
||||
"secrets": {
|
||||
"npm-package-registry": "${dir:mesh-state}/package-registry.secret"
|
||||
"npm-package-registry": "/var/lib/mesh/builder/package-registry.secret"
|
||||
},
|
||||
"own-secrets": {
|
||||
"broker": "${dir:mesh-state}/broker"
|
||||
"broker": "/var/lib/mesh/builder/broker"
|
||||
},
|
||||
"resources": [
|
||||
{
|
||||
"id": "mesh-state",
|
||||
"type": "directory",
|
||||
"mode": "0700",
|
||||
"place": "mesh"
|
||||
"path": "/var/lib/mesh/builder",
|
||||
"mode": "0700"
|
||||
},
|
||||
{
|
||||
"id": "workspace",
|
||||
"type": "directory",
|
||||
"path": "/var/lib/builder/workspace",
|
||||
"mode": "0700"
|
||||
},
|
||||
{
|
||||
"id": "agent-env",
|
||||
"id": "builder-env",
|
||||
"type": "file",
|
||||
"path": "${dir:mesh-state}/build-agent.env",
|
||||
"path": "/var/lib/mesh/builder/builder.env",
|
||||
"mode": "0600",
|
||||
"content": "MESH_BROKER_FILE=/run/mesh/broker\nMESH_NODE=${machine:name}\nMESH_REGISTRY=${bound:artifact-store:at}:${bound:artifact-store:port}\nMESH_PACKAGE_BINDING=/run/mesh/package-registry.json\nMESH_NPM_TOKEN_FILE=/run/mesh/package-registry.secret\nMESH_WORKSPACE=${dir:workspace}\n"
|
||||
"content": "MESH_BROKER_FILE=/run/mesh/broker\nMESH_NODE=${machine:name}\nMESH_REGISTRY=${bound:artifact-store:at}:${bound:artifact-store:port}\nMESH_PACKAGE_BINDING=/run/mesh/package-registry.json\nMESH_NPM_TOKEN_FILE=/run/mesh/package-registry.secret\nMESH_WORKSPACE=/var/lib/builder/workspace\n"
|
||||
},
|
||||
{
|
||||
"id": "server",
|
||||
"type": "container",
|
||||
"name": "mesh-build-agent",
|
||||
"name": "mesh-builder",
|
||||
"artifact": "server",
|
||||
"env-file": [
|
||||
"${dir:mesh-state}/build-agent.env"
|
||||
"/var/lib/mesh/builder/builder.env"
|
||||
],
|
||||
"volumes": [
|
||||
"${dir:mesh-state}:/run/mesh:ro",
|
||||
"${dir:workspace}:${dir:workspace}",
|
||||
"/var/lib/mesh/builder:/run/mesh:ro",
|
||||
"/var/lib/builder/workspace:/var/lib/builder/workspace",
|
||||
"/var/run/docker.sock:/var/run/docker.sock"
|
||||
],
|
||||
"restart-on": [
|
||||
"agent-env"
|
||||
"builder-env"
|
||||
],
|
||||
"network": "host"
|
||||
}
|
||||
@@ -69,8 +69,7 @@
|
||||
"kind": "image",
|
||||
"from": "Dockerfile",
|
||||
"context": {
|
||||
"seat": "git",
|
||||
"repository": "novox/mesh-controller",
|
||||
"repository": "https://git.novox.be/novox/mesh-controller.git",
|
||||
"ref": "main"
|
||||
}
|
||||
}
|
||||
@@ -1,74 +0,0 @@
|
||||
# claude-code
|
||||
|
||||
The operator's agent on a machine (novox/hq design 36): its package, its machine-wide managed
|
||||
configuration, and the consumer side of the Anthropic licence manager (design 39, ADR 0183).
|
||||
|
||||
## What it owns
|
||||
|
||||
Two directories, declared, so the mesh refuses a second module owning either:
|
||||
|
||||
- `/etc/claude-code`, the agent's machine-wide managed directory, root's, `0755`.
|
||||
- `~/.claude` under the operator account's home, the operator's, `0700`. The module owns the directory —
|
||||
that it exists, who owns it, its mode — and of what is inside only what it writes. Everything else
|
||||
in it (memory, history, projects, local settings, a person's own rules and skills) is the person's
|
||||
and is never read or written (hq ADR 0182). Unassigned, the module leaves the directory: the host
|
||||
removes a directory only when it is empty.
|
||||
|
||||
## What it writes
|
||||
|
||||
Under the agent's managed directory, `/etc/claude-code`, owned whole by this module and rewritten
|
||||
whenever the node's tool runtime collects the module's tools:
|
||||
|
||||
| file | holds |
|
||||
|---|---|
|
||||
| `managed-mcp.json` | the tool servers every session loads: the mesh's console as `mesh`, and the servers set in this module's `mcp_servers` setting. **Exclusive**: a server not listed here does not load — not one added with `claude mcp add`, not a project's `.mcp.json`, not a plugin's |
|
||||
| `managed-settings.json` | the repositories' attribution convention, the claude.ai connectors kept beside the managed servers, and the key-helper while the node holds an API-key licence |
|
||||
| `CLAUDE.md` | how a session on this mesh works, this node's name and role, the conventions |
|
||||
|
||||
Under the operator's home, only `~/.claude/.credentials.json`, and only when the licence manager hands
|
||||
this node a subscription token. Nothing else under the home is read or written.
|
||||
|
||||
## Over NATS
|
||||
|
||||
Everything between this module and the rest of the mesh is NATS, in three kinds: an **event** says that
|
||||
something happened and carries no secret, because a stream keeps it; a **request** carries a token,
|
||||
because nothing keeps it (hq design 32 §10); and **state** is the current value of something every node
|
||||
must see, a node that joins later included — kept, so it carries no secret either (hq ADR 0201).
|
||||
|
||||
| what | how |
|
||||
|---|---|
|
||||
| the licence manager rotated a licence, or switched this node | its `licence.rotated` / `licence.switched` event; this module then asks `anthropic-licence-manager.current` for its token, sealed to the key it sends |
|
||||
| this node starts | it asks `current` once, so a node that was off catches up |
|
||||
| a person ran `/login` here | the credentials file gains a refresh token this module never writes; it asks `anthropic-licence-manager.adopt` at once with the grant sealed to the manager's key — the one time a refresh token travels, because the login made the manager's stale |
|
||||
| an MCP server registered through this module | a key in the module's `servers` state — `all.<server>` for every node, `<node>.<server>` for one; every node watches it and renders what applies to it, a node's own entry over the one for every node. A node that joins later, or was off, reads the whole current set at start; unregistering is a delete. An entry with a secret in its `env` or `headers` is refused by the runtime |
|
||||
|
||||
## Tools
|
||||
|
||||
`claude_code_status`, `claude_code_render`, `claude_code_pull`, `claude_code_mcp_list`,
|
||||
`claude_code_mcp_register` (this node by default; `nodes: "all"` or a list for more — called for this
|
||||
node alone, its answer names the other nodes running claude-code), `claude_code_mcp_unregister`.
|
||||
|
||||
## Settings
|
||||
|
||||
Per node or for the whole mesh, through `mesh-controller.settings module=claude-code`:
|
||||
|
||||
- `role` — what this node is, in a few words; shown to every session.
|
||||
- `mcp_servers` — extra tool servers, set by the operator for the mesh or a node, beside the ones
|
||||
registered through the tools; keyed by name, in the vendor's `.mcp.json` entry shape
|
||||
(`{"type":"http","url":…}` or `{"type":"stdio","command":…,"args":[…]}`). The name `mesh` is the
|
||||
module's own and cannot be set. Put a person's own servers here, or they stop loading.
|
||||
|
||||
## On a machine that carried the predecessor
|
||||
|
||||
Remove these by hand, once; the mesh removes nothing it did not make (ADR 0182):
|
||||
|
||||
- `~/.claude/CLAUDE.md`
|
||||
- `~/.claude/rules/00-hal-mesh.md`, `~/.claude/rules/conventions.md`
|
||||
- `~/.claude/skills/cleanup/`, `~/.claude/skills/hal-switch-license/`
|
||||
- the hand-made console entry in `~/.claude.json` under `mcpServers` — it is ignored now anyway
|
||||
|
||||
## Escalation
|
||||
|
||||
Writing `/etc/claude-code` needs root. The runtime runs as the operator account, and the module uses
|
||||
that account's passwordless `sudo`; on a machine without it, `claude_code_render` says so and nothing
|
||||
is written.
|
||||
@@ -1,112 +0,0 @@
|
||||
// The agent's credentials file, and whether an offered grant may replace what it holds (novox/hq
|
||||
// ADR 0183, design 36 §5). Pure where it decides, so the rules are tested without a file.
|
||||
//
|
||||
// The file is the vendor's: `{ claudeAiOauth: { accessToken, expiresAt, refreshTokenExpiresAt?,
|
||||
// scopes?, subscriptionType?, rateLimitTier? }, ... }`. A node never holds a refresh token, so the
|
||||
// one this module writes never carries one, and a full grant a login left behind is stripped the
|
||||
// moment the manager hands the node its own.
|
||||
//
|
||||
// The lineage rule is the predecessor's, with the incidents that earned it: a rotation of the same
|
||||
// licence is applied only if newer; a grant re-issued by a login is adopted whatever its expiry; a
|
||||
// switch to another licence is applied regardless, because across licences the expiries are
|
||||
// unrelated numbers.
|
||||
|
||||
import { readFileSync, renameSync, writeFileSync, mkdirSync } from "node:fs";
|
||||
import { dirname } from "node:path";
|
||||
|
||||
export interface Grant {
|
||||
readonly accessToken: string;
|
||||
readonly expiresAt: number;
|
||||
readonly refreshTokenExpiresAt?: number | null;
|
||||
readonly scopes?: readonly string[] | null;
|
||||
readonly subscriptionType?: string | null;
|
||||
readonly rateLimitTier?: string | null;
|
||||
}
|
||||
|
||||
export type ApplySource = "rotation" | "switch";
|
||||
|
||||
export type ApplyDecision =
|
||||
| { apply: true; reissued?: boolean }
|
||||
| { apply: false; reason: "already-current" }
|
||||
| { apply: false; reason: "not-newer"; localExpiresAt: number };
|
||||
|
||||
/** Two refresh-token expiries within a day are one lineage; a login starts a fresh window weeks away. */
|
||||
export const GENERATION_TOLERANCE_MS = 24 * 60 * 60 * 1000;
|
||||
|
||||
export function sameGeneration(a?: number | null, b?: number | null): boolean {
|
||||
if (a == null || b == null) return true;
|
||||
return Math.abs(Number(a) - Number(b)) <= GENERATION_TOLERANCE_MS;
|
||||
}
|
||||
|
||||
export function decideApply(local: Grant | null | undefined, offered: Grant, source: ApplySource): ApplyDecision {
|
||||
if (!local?.accessToken) return { apply: true };
|
||||
if (local.accessToken === offered.accessToken) return { apply: false, reason: "already-current" };
|
||||
const reissued = !sameGeneration(local.refreshTokenExpiresAt, offered.refreshTokenExpiresAt);
|
||||
if (source === "rotation" && !reissued && Number(local.expiresAt) >= Number(offered.expiresAt)) {
|
||||
return { apply: false, reason: "not-newer", localExpiresAt: Number(local.expiresAt) };
|
||||
}
|
||||
return reissued ? { apply: true, reissued: true } : { apply: true };
|
||||
}
|
||||
|
||||
type Oauth = Record<string, unknown> & { accessToken?: string; refreshToken?: string; expiresAt?: number };
|
||||
type Credentials = Record<string, unknown> & { claudeAiOauth?: Oauth };
|
||||
|
||||
export function readCredentials(path: string): Credentials | null {
|
||||
try {
|
||||
const parsed = JSON.parse(readFileSync(path, "utf8")) as Credentials;
|
||||
return parsed && typeof parsed === "object" ? parsed : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** The grant the file holds, or null. */
|
||||
export function grantOf(creds: Credentials | null): Grant | null {
|
||||
const o = creds?.claudeAiOauth;
|
||||
if (!o?.accessToken) return null;
|
||||
return {
|
||||
accessToken: o.accessToken,
|
||||
expiresAt: Number(o.expiresAt ?? 0),
|
||||
refreshTokenExpiresAt: o.refreshTokenExpiresAt == null ? null : Number(o.refreshTokenExpiresAt),
|
||||
};
|
||||
}
|
||||
|
||||
/** Does the file hold a full grant — a refresh token this module never writes, so a person's login? */
|
||||
export function holdsLogin(creds: Credentials | null): boolean {
|
||||
return typeof creds?.claudeAiOauth?.refreshToken === "string" && creds.claudeAiOauth.refreshToken.length > 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* The handed grant laid over what is there — a rotation of the licence the node already holds — or,
|
||||
* for a switch, in place of it: the old licence's grant goes whole, scopes and subscription included,
|
||||
* and only keys outside the grant (another kind of credential the vendor keeps in the file) stay.
|
||||
* Either way, no refresh token survives.
|
||||
*/
|
||||
export function replacedBy(local: Credentials | null, grant: Grant): Credentials {
|
||||
const next: Credentials = { ...(local ?? {}) };
|
||||
delete next.claudeAiOauth;
|
||||
return withGrant(next, grant);
|
||||
}
|
||||
|
||||
/** Overlay the handed grant on what is there, and delete any refresh token. */
|
||||
export function withGrant(local: Credentials | null, grant: Grant): Credentials {
|
||||
const next: Credentials = { ...(local ?? {}) };
|
||||
const oauth: Oauth = { ...(local?.claudeAiOauth ?? {}) };
|
||||
oauth.accessToken = grant.accessToken;
|
||||
oauth.expiresAt = grant.expiresAt;
|
||||
for (const k of ["refreshTokenExpiresAt", "scopes", "subscriptionType", "rateLimitTier"] as const) {
|
||||
const v = grant[k];
|
||||
if (v != null) oauth[k] = v as unknown;
|
||||
}
|
||||
delete oauth.refreshToken;
|
||||
next.claudeAiOauth = oauth;
|
||||
return next;
|
||||
}
|
||||
|
||||
/** Write atomically at 0600: a partial credentials file must never be read as a whole one. */
|
||||
export function writeCredentials(path: string, creds: Credentials): void {
|
||||
mkdirSync(dirname(path), { recursive: true, mode: 0o700 });
|
||||
const tmp = `${path}.mesh-tmp`;
|
||||
writeFileSync(tmp, JSON.stringify(creds, null, 2) + "\n", { mode: 0o600 });
|
||||
renameSync(tmp, path);
|
||||
}
|
||||
@@ -1,50 +0,0 @@
|
||||
// Which account the agent is logged in as (novox/hq ADR 0183): not in the token, but in the agent's
|
||||
// own state file beside the home, `~/.claude.json` → `oauthAccount`. Read to attribute a login; written,
|
||||
// three keys and nothing else, when a licence is switched, so the file Claude Code shows the account from
|
||||
// names the account whose token it now holds (as the predecessor learned: two files that disagree make
|
||||
// a later login look like the wrong account).
|
||||
|
||||
import { readFileSync, renameSync, writeFileSync } from "node:fs";
|
||||
|
||||
export interface Identity {
|
||||
readonly accountUuid: string;
|
||||
readonly emailAddress?: string;
|
||||
readonly organizationUuid?: string;
|
||||
}
|
||||
|
||||
export function readIdentity(stateFile: string): Identity | null {
|
||||
try {
|
||||
const raw = JSON.parse(readFileSync(stateFile, "utf8")) as { oauthAccount?: Record<string, unknown> };
|
||||
const a = raw.oauthAccount;
|
||||
if (!a || typeof a.accountUuid !== "string") return null;
|
||||
return {
|
||||
accountUuid: a.accountUuid,
|
||||
emailAddress: typeof a.emailAddress === "string" ? a.emailAddress : undefined,
|
||||
organizationUuid: typeof a.organizationUuid === "string" ? a.organizationUuid : undefined,
|
||||
};
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Point the state file's account at `id`, keeping every other key as found. Returns whether the file
|
||||
* changed; a file that cannot be read as an object is left alone rather than replaced.
|
||||
*/
|
||||
export function writeIdentity(stateFile: string, id: Identity): boolean {
|
||||
let raw: Record<string, unknown>;
|
||||
try {
|
||||
raw = JSON.parse(readFileSync(stateFile, "utf8")) as Record<string, unknown>;
|
||||
if (!raw || typeof raw !== "object") return false;
|
||||
} catch {
|
||||
raw = {};
|
||||
}
|
||||
const current = (raw.oauthAccount ?? {}) as Record<string, unknown>;
|
||||
if (current.accountUuid === id.accountUuid && current.emailAddress === id.emailAddress
|
||||
&& current.organizationUuid === id.organizationUuid) return false;
|
||||
raw.oauthAccount = { ...current, accountUuid: id.accountUuid, emailAddress: id.emailAddress, organizationUuid: id.organizationUuid };
|
||||
const tmp = `${stateFile}.mesh-tmp`;
|
||||
writeFileSync(tmp, JSON.stringify(raw, null, 2), { mode: 0o600 });
|
||||
renameSync(tmp, stateFile);
|
||||
return true;
|
||||
}
|
||||
@@ -1,90 +0,0 @@
|
||||
{
|
||||
"module": "claude-code",
|
||||
"version": "1",
|
||||
"slug": "agent",
|
||||
"capabilities": [
|
||||
"package-manager"
|
||||
],
|
||||
"requires": [
|
||||
"mcp-endpoint"
|
||||
],
|
||||
"binds": {
|
||||
"mcp-endpoint": "${dir:state}/mcp-endpoint.json"
|
||||
},
|
||||
"consumes": [
|
||||
"claude-licence-manager.licence.rotated",
|
||||
"claude-licence-manager.licence.switched"
|
||||
],
|
||||
"state": [
|
||||
"servers"
|
||||
],
|
||||
"tools": [
|
||||
"claude_code_status",
|
||||
"claude_code_render",
|
||||
"claude_code_pull",
|
||||
"claude_code_mcp_list",
|
||||
"claude_code_mcp_register",
|
||||
"claude_code_mcp_unregister"
|
||||
],
|
||||
"resources": [
|
||||
{
|
||||
"id": "package",
|
||||
"type": "package",
|
||||
"package": "claude-code"
|
||||
},
|
||||
{
|
||||
"id": "managed",
|
||||
"type": "directory",
|
||||
"path": "/etc/claude-code",
|
||||
"mode": "0755"
|
||||
},
|
||||
{
|
||||
"id": "agent-home",
|
||||
"type": "directory",
|
||||
"path": "${machine:account-home}/.claude",
|
||||
"mode": "0700",
|
||||
"owner": "${machine:account}"
|
||||
},
|
||||
{
|
||||
"id": "state",
|
||||
"type": "directory",
|
||||
"mode": "0700",
|
||||
"owner": "${machine:account}",
|
||||
"place": "."
|
||||
},
|
||||
{
|
||||
"id": "facts",
|
||||
"type": "file",
|
||||
"path": "${dir:state}/facts.json",
|
||||
"mode": "0600",
|
||||
"owner": "${machine:account}",
|
||||
"content": "{\n \"node\": \"${machine:name}\",\n \"console\": \"http://127.0.0.1:${bound:mcp-endpoint:port}/mcp\"\n}\n"
|
||||
},
|
||||
{
|
||||
"id": "settings",
|
||||
"type": "file",
|
||||
"path": "${dir:state}/settings.json",
|
||||
"mode": "0600",
|
||||
"owner": "${machine:account}",
|
||||
"merge": "json",
|
||||
"content": "{\n \"role\": \"\",\n \"mcp_servers\": {}\n}\n"
|
||||
}
|
||||
],
|
||||
"build": {
|
||||
"artifacts": [
|
||||
{
|
||||
"name": "tools",
|
||||
"kind": "bundle",
|
||||
"language": "typescript",
|
||||
"entrypoints": [
|
||||
"tools/index.js"
|
||||
],
|
||||
"env": {
|
||||
"MESH_CLAUDE_CODE_STATE": "${dir:state}",
|
||||
"MESH_CLAUDE_CODE_FACTS": "${dir:state}/facts.json",
|
||||
"MESH_CLAUDE_CODE_SETTINGS": "${dir:state}/settings.json"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
@@ -1,271 +0,0 @@
|
||||
// What claude-code does on a node, written against two things it is handed — a way to ask a tool on the
|
||||
// bus and a way to emit an event — so every path is tested without a bus (novox/hq design 36 §4–§5,
|
||||
// ADR 0183, ADR 0198).
|
||||
//
|
||||
// **Over NATS, in two kinds** (design 32 §10): an event says that something happened and carries no
|
||||
// secret, because a stream keeps it; a token travels on a request, which nothing keeps. So:
|
||||
// - the licence manager's `licence.rotated` and `licence.switched` events tell this module to ask the
|
||||
// seat for its current token, sealed to the key it sends with the request;
|
||||
// - a login a person made here — a refresh token this module never writes — is offered to the seat at
|
||||
// once, sealed to the seat's key: the one moment a refresh token travels, because the login made the
|
||||
// manager's stale;
|
||||
// - an MCP server registered through this module is **state, not an event** (novox/hq ADR 0201): one
|
||||
// key per server in the module's `servers` bucket — `all.<server>` for every node, `<node>.<server>`
|
||||
// for one — which every node watches. A node that joins later, or was off, reads the whole current set
|
||||
// at start; unregistering is a delete. A secret never goes in an entry: the runtime refuses one.
|
||||
|
||||
import { chmodSync, existsSync, readFileSync, rmSync, writeFileSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
|
||||
import { render, entryProblem, MANAGED_DIR, type Binding, type Facts, type Settings, type Servers } from "./render.js";
|
||||
import { generateKeyPair, open, seal, type SealedBox } from "./seal.js";
|
||||
import { decideApply, grantOf, holdsLogin, readCredentials, replacedBy, withGrant, writeCredentials, type Grant } from "./grant.js";
|
||||
import { readIdentity, writeIdentity, type Identity } from "./identity.js";
|
||||
|
||||
export const SEAT = "anthropic-licence-manager";
|
||||
|
||||
export interface Paths {
|
||||
state: string;
|
||||
facts: string;
|
||||
settings: string;
|
||||
home: string;
|
||||
node: string;
|
||||
}
|
||||
|
||||
/** A tool on the bus: its address and arguments in, its JSON answer out. */
|
||||
export type Ask = (address: string, args: Record<string, unknown>) => Promise<unknown>;
|
||||
/** An event of this module's, by its local name. */
|
||||
export type Emit = (type: string, body: unknown) => Promise<void>;
|
||||
/** Write one managed file; answers what happened. */
|
||||
export type WriteManaged = (name: string, content: string) => string;
|
||||
|
||||
export const readJson = <T>(p: string, fallback: T): T => {
|
||||
try {
|
||||
return JSON.parse(readFileSync(p, "utf8")) as T;
|
||||
} catch {
|
||||
return fallback;
|
||||
}
|
||||
};
|
||||
|
||||
const credentialsPath = (p: Paths) => join(p.home, ".claude", ".credentials.json");
|
||||
const accountPath = (p: Paths) => join(p.home, ".claude.json");
|
||||
const bindingPath = (p: Paths) => join(p.state, "licence.json");
|
||||
const apiKeyPath = (p: Paths) => join(p.state, "api-key");
|
||||
export const helperPath = (p: Paths) => join(p.state, "api-key-helper");
|
||||
const keyPath = (p: Paths) => join(p.state, "key.pem");
|
||||
const pubPath = (p: Paths) => join(p.state, "key.pub.pem");
|
||||
const registryPath = (p: Paths) => join(p.state, "mcp-servers.json");
|
||||
|
||||
export function keypair(p: Paths): { publicKey: string; privateKey: string } {
|
||||
if (!existsSync(keyPath(p))) {
|
||||
const k = generateKeyPair();
|
||||
writeFileSync(keyPath(p), k.privateKey, { mode: 0o600 });
|
||||
writeFileSync(pubPath(p), k.publicKey, { mode: 0o644 });
|
||||
}
|
||||
return { privateKey: readFileSync(keyPath(p), "utf8"), publicKey: readFileSync(pubPath(p), "utf8") };
|
||||
}
|
||||
|
||||
export function registered(p: Paths): Servers {
|
||||
return readJson<Servers>(registryPath(p), {});
|
||||
}
|
||||
|
||||
export function renderNow(p: Paths, write: WriteManaged): string[] {
|
||||
const facts = readJson<Facts | null>(p.facts, null);
|
||||
if (!facts?.console) throw new Error(`the mesh has not rendered ${p.facts} yet; nothing to write`);
|
||||
const files = render(facts, readJson<Settings>(p.settings, {}), readJson<Binding | null>(bindingPath(p), null),
|
||||
helperPath(p), registered(p));
|
||||
return Object.entries(files).map(([name, content]) => write(name, content));
|
||||
}
|
||||
|
||||
// ---- the licence ----------------------------------------------------------------------------------
|
||||
|
||||
/** What the seat answers to `current`: the licence this node is bound to and its token, sealed. */
|
||||
export interface Current {
|
||||
licence: string;
|
||||
kind: "subscription" | "api-key";
|
||||
sealed: SealedBox;
|
||||
identity?: Identity | null;
|
||||
}
|
||||
|
||||
/** Ask the seat for this node's current token and apply it. */
|
||||
export async function pull(p: Paths, ask: Ask, write: WriteManaged): Promise<Record<string, unknown>> {
|
||||
const answer = (await ask(`${SEAT}.current`, { node: p.node, public_key: keypair(p).publicKey })) as Current | null;
|
||||
if (!answer?.sealed) return { applied: false, reason: "the seat holds no licence for this node" };
|
||||
return apply(p, answer, write);
|
||||
}
|
||||
|
||||
/** Apply what the seat handed over. A switch replaces the grant whole and cleans up after the old licence. */
|
||||
export function apply(p: Paths, handed: Current, write: WriteManaged): Record<string, unknown> {
|
||||
const plain = open(handed.sealed, keypair(p).privateKey);
|
||||
const previous = readJson<Binding | null>(bindingPath(p), null);
|
||||
const switched = previous?.licence !== handed.licence;
|
||||
let outcome: Record<string, unknown> = { applied: true, licence: handed.licence, kind: handed.kind, switched };
|
||||
if (handed.kind === "api-key") {
|
||||
writeFileSync(apiKeyPath(p), plain.trim() + "\n", { mode: 0o600 });
|
||||
writeFileSync(helperPath(p), `#!/bin/sh\nexec cat '${apiKeyPath(p)}'\n`, { mode: 0o700 });
|
||||
chmodSync(helperPath(p), 0o700);
|
||||
} else {
|
||||
const grant = JSON.parse(plain) as Grant;
|
||||
const local = readCredentials(credentialsPath(p));
|
||||
const d = decideApply(grantOf(local), grant, switched ? "switch" : "rotation");
|
||||
if (d.apply) writeCredentials(credentialsPath(p), switched ? replacedBy(local, grant) : withGrant(local, grant));
|
||||
else outcome = { applied: false, licence: handed.licence, reason: "reason" in d ? d.reason : undefined }; // narrowed by hand: the build compiles without strict
|
||||
// Away from the API key: it goes, with its helper.
|
||||
rmSync(apiKeyPath(p), { force: true });
|
||||
rmSync(helperPath(p), { force: true });
|
||||
}
|
||||
if (switched && handed.identity?.accountUuid) {
|
||||
outcome.account = writeIdentity(accountPath(p), handed.identity) ? "updated" : "unchanged";
|
||||
}
|
||||
writeFileSync(bindingPath(p), JSON.stringify({ licence: handed.licence, kind: handed.kind }) + "\n", { mode: 0o600 });
|
||||
try {
|
||||
outcome.rendered = renderNow(p, write); // the key-helper comes or goes with the licence's kind
|
||||
} catch (err) {
|
||||
outcome.rendered = { failed: err instanceof Error ? err.message : String(err) };
|
||||
}
|
||||
return outcome;
|
||||
}
|
||||
|
||||
/** A licence event from the manager: is it for this node? */
|
||||
export function concerns(p: Paths, type: string, body: { licence?: string; node?: string }): boolean {
|
||||
if (type.endsWith("licence.switched")) return body.node === p.node;
|
||||
if (type.endsWith("licence.rotated")) return body.licence === readJson<Binding | null>(bindingPath(p), null)?.licence;
|
||||
return false;
|
||||
}
|
||||
|
||||
/** A refresh token in the credentials file is a login: this module never writes one. Offer it to the seat. */
|
||||
export async function offerLogin(p: Paths, ask: Ask): Promise<Record<string, unknown> | null> {
|
||||
const creds = readCredentials(credentialsPath(p));
|
||||
if (!holdsLogin(creds)) return null;
|
||||
const key = (await ask(`${SEAT}.public_key`, {})) as { public_key?: string } | null;
|
||||
if (!key?.public_key) throw new Error("the licence manager did not say what key to seal a login to");
|
||||
return (await ask(`${SEAT}.adopt`, {
|
||||
node: p.node,
|
||||
identity: readIdentity(accountPath(p)),
|
||||
sealed: seal(JSON.stringify(creds!.claudeAiOauth), key.public_key),
|
||||
})) as Record<string, unknown>;
|
||||
}
|
||||
|
||||
// ---- MCP servers ----------------------------------------------------------------------------------
|
||||
|
||||
export interface Registration {
|
||||
name: string;
|
||||
entry?: Record<string, unknown>;
|
||||
/** Which nodes: this one (absent), every node running the module ("all"), or a list. */
|
||||
nodes?: "all" | string[];
|
||||
}
|
||||
|
||||
/** The `servers` state, as this module reaches it through the runtime (`state("servers")` in the SDK). */
|
||||
export interface ServerState {
|
||||
put(key: string, value: Record<string, unknown>): Promise<number>;
|
||||
delete(key: string): Promise<void>;
|
||||
keys(): Promise<string[]>;
|
||||
}
|
||||
|
||||
/** One change to the `servers` state, as a watch hands it over. */
|
||||
export interface ServerChange {
|
||||
key: string;
|
||||
op: "put" | "delete";
|
||||
value?: Record<string, unknown>;
|
||||
}
|
||||
|
||||
/** The key a registration lives at: `all.<server>` for every node, `<node>.<server>` for one. */
|
||||
export const keyOf = (scope: string, name: string) => `${scope}.${name}`;
|
||||
|
||||
/**
|
||||
* What this node takes from the `servers` state: the entries for every node and for this one, by key —
|
||||
* kept in memory from the watch, and written through to the module's own file whenever what applies here
|
||||
* changes, so the managed directory can be rendered without the bus.
|
||||
*/
|
||||
export class ServerView {
|
||||
private readonly entries = new Map<string, Record<string, unknown>>();
|
||||
constructor(private readonly p: Paths) {}
|
||||
|
||||
/** Take one change; answers whether what applies to this node changed. */
|
||||
take(c: ServerChange): boolean {
|
||||
const dot = c.key.indexOf(".");
|
||||
const scope = c.key.slice(0, dot), name = c.key.slice(dot + 1);
|
||||
if (dot <= 0 || (scope !== "all" && scope !== this.p.node)) return false;
|
||||
if (c.op === "put" && c.value && entryProblem(name, c.value) === null) this.entries.set(c.key, c.value);
|
||||
else this.entries.delete(c.key);
|
||||
return this.writeThrough();
|
||||
}
|
||||
|
||||
/** What applies here: every node's entries, with this node's own laid over them by server name. */
|
||||
effective(): Servers {
|
||||
const out: Record<string, Record<string, unknown>> = {};
|
||||
for (const scope of ["all", this.p.node]) {
|
||||
for (const [key, entry] of [...this.entries].sort(([a], [b]) => a.localeCompare(b))) {
|
||||
if (key.startsWith(scope + ".")) out[key.slice(scope.length + 1)] = entry;
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
private writeThrough(): boolean {
|
||||
const now = JSON.stringify(this.effective(), null, 2) + "\n";
|
||||
let before = "";
|
||||
try {
|
||||
before = readFileSync(registryPath(this.p), "utf8");
|
||||
} catch {
|
||||
/* none yet */
|
||||
}
|
||||
if (now === before) return false;
|
||||
writeFileSync(registryPath(this.p), now, { mode: 0o600 });
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
/** A change from the watch: take it, and render when what applies here changed. */
|
||||
export function onServerChange(view: ServerView, c: ServerChange, p: Paths, write: WriteManaged): string | null {
|
||||
if (!view.take(c)) return null;
|
||||
renderNow(p, write);
|
||||
return `${c.op === "put" ? "registered" : "unregistered"} ${c.key}`;
|
||||
}
|
||||
|
||||
const scopesOf = (p: Paths, nodes: Registration["nodes"]): string[] =>
|
||||
nodes === undefined ? [p.node] : nodes === "all" ? ["all"] : nodes;
|
||||
|
||||
/**
|
||||
* Register (or with no entry, unregister) a server: a put (or delete) per scope in the `servers` state.
|
||||
* Taken into this node's view at once, so the answer says what it did here; every other node takes it
|
||||
* from its watch, and a node that joins later from the current state.
|
||||
*/
|
||||
export async function registerServer(p: Paths, r: Registration, servers: ServerState, view: ServerView,
|
||||
write: WriteManaged, others: () => Promise<string[]>): Promise<Record<string, unknown>> {
|
||||
if (r.entry) {
|
||||
const problem = entryProblem(r.name, r.entry);
|
||||
if (problem) return { registered: false, reason: problem };
|
||||
}
|
||||
const scopes = scopesOf(p, r.nodes);
|
||||
// Compared before and after rather than read from take(): this node's own watch may hand the view the
|
||||
// same change first, and then take() here finds nothing new although this call made it.
|
||||
const before = JSON.stringify(view.effective());
|
||||
for (const scope of scopes) {
|
||||
const key = keyOf(scope, r.name);
|
||||
if (r.entry) await servers.put(key, r.entry);
|
||||
else await servers.delete(key);
|
||||
view.take({ key, op: r.entry ? "put" : "delete", value: r.entry });
|
||||
}
|
||||
const changedHere = JSON.stringify(view.effective()) !== before;
|
||||
const here = scopes.includes("all") || scopes.includes(p.node);
|
||||
const answer: Record<string, unknown> = {
|
||||
[r.entry ? "registered" : "unregistered"]: r.name,
|
||||
on: r.nodes === undefined ? [p.node] : r.nodes,
|
||||
here: here ? (changedHere ? "changed" : "already so") : "not this node",
|
||||
rendered: changedHere ? renderNow(p, write) : [],
|
||||
};
|
||||
if (!r.entry && view.effective()[r.name]) {
|
||||
answer.still = `${r.name} still applies here from another registration (for every node, or for this one); unregister that too`;
|
||||
}
|
||||
if (r.nodes === undefined) {
|
||||
// The question the operator wanted asked: here only, or more?
|
||||
const elsewhere = (await others().catch(() => [] as string[])).filter((n) => n !== p.node);
|
||||
answer.also = elsewhere.length
|
||||
? `claude-code also runs on ${elsewhere.join(", ")}. To ${r.entry ? "register" : "unregister"} it there too, call again with nodes: "all" or a list of those nodes.`
|
||||
: `To do the same on every node running claude-code, call again with nodes: "all".`;
|
||||
}
|
||||
return answer;
|
||||
}
|
||||
|
||||
export { MANAGED_DIR };
|
||||
@@ -1,18 +0,0 @@
|
||||
{
|
||||
"name": "@novox/module-claude-code",
|
||||
"version": "0.1.0",
|
||||
"description": "claude-code — the operator's agent on a machine: its managed configuration, and the consumer side of the Anthropic licence manager (novox/hq design 36).",
|
||||
"type": "module",
|
||||
"private": true,
|
||||
"scripts": {
|
||||
"build": "tsc seal.ts grant.ts identity.ts render.ts node.ts tools/index.ts --module NodeNext --moduleResolution NodeNext --target ES2022 --rootDir . --outDir dist",
|
||||
"test": "npm run build && node --test --experimental-strip-types 'test/*.test.ts'"
|
||||
},
|
||||
"dependencies": {
|
||||
"@novox/mesh-sdk": "^0.1.7"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^22.0.0",
|
||||
"typescript": "^5.6.0"
|
||||
}
|
||||
}
|
||||
@@ -1,135 +0,0 @@
|
||||
// What the module writes into the agent's machine-wide managed directory (novox/hq design 36 §1–§4).
|
||||
// Pure: composed from the facts the mesh rendered, the settings the operator set and the licence the
|
||||
// node holds, so what lands under /etc is tested without a machine.
|
||||
//
|
||||
// Three files, owned whole by this module:
|
||||
// managed-mcp.json the tool servers every session loads: the mesh's console as `mesh`, and the
|
||||
// servers the operator declared for the mesh or this node. Exclusive by the
|
||||
// vendor's rule — a server not listed here does not load — which is why the
|
||||
// list is the module's settings and nothing else (operator's choice, 2026-10-03).
|
||||
// managed-settings.json the mesh's keys only: the repositories' attribution convention, the
|
||||
// claude.ai connectors kept beside the managed servers, and — for an API-key
|
||||
// licence only — the key-helper. A person's preferences are theirs.
|
||||
// CLAUDE.md how a session on this mesh works, who this node is, the conventions.
|
||||
|
||||
export const MANAGED_DIR = "/etc/claude-code";
|
||||
|
||||
export interface Facts {
|
||||
readonly node: string;
|
||||
readonly console: string;
|
||||
}
|
||||
|
||||
export interface Settings {
|
||||
readonly role?: string;
|
||||
/** Extra tool servers, in the vendor's `.mcp.json` entry shape, keyed by name. */
|
||||
readonly mcp_servers?: Readonly<Record<string, Record<string, unknown>>>;
|
||||
}
|
||||
|
||||
export interface Binding {
|
||||
readonly licence: string;
|
||||
readonly kind: "subscription" | "api-key";
|
||||
}
|
||||
|
||||
export interface Rendered {
|
||||
readonly [file: string]: string;
|
||||
}
|
||||
|
||||
const MESH_ENTRY = "mesh";
|
||||
|
||||
export type Servers = Readonly<Record<string, Record<string, unknown>>>;
|
||||
|
||||
/** Whether an entry is one the vendor's managed file takes: a name of letters, digits, `-` and `_`, and
|
||||
* an http/sse server with a url or a stdio server with a command. Returns why not, or null. */
|
||||
export function entryProblem(name: string, entry: Record<string, unknown>): string | null {
|
||||
if (!/^[A-Za-z0-9_-]+$/.test(name)) return `"${name}" is not a name the agent takes: letters, digits, - and _`;
|
||||
if (name === MESH_ENTRY) return `"${MESH_ENTRY}" is the mesh's own entry`;
|
||||
const type = entry?.type ?? "stdio";
|
||||
if (type === "http" || type === "sse" || type === "streamable-http") {
|
||||
return typeof entry.url === "string" && entry.url ? null : `an ${type} server needs a url`;
|
||||
}
|
||||
if (type === "stdio") return typeof entry.command === "string" && entry.command ? null : "a stdio server needs a command";
|
||||
return `"${String(type)}" is not a server type the agent knows (http, sse, stdio)`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Compose the three files. `registered` is the module's own list on this node — what was registered
|
||||
* through its tools — laid over the servers the operator set in its settings.
|
||||
*/
|
||||
export function render(facts: Facts, settings: Settings, binding: Binding | null, helperPath: string,
|
||||
registered: Servers = {}): Rendered {
|
||||
const servers: Record<string, unknown> = {};
|
||||
for (const [name, entry] of Object.entries({ ...(settings.mcp_servers ?? {}), ...registered })) {
|
||||
if (entryProblem(name, entry) !== null) continue; // the mesh's own entry, or one the agent would refuse
|
||||
servers[name] = entry;
|
||||
}
|
||||
servers[MESH_ENTRY] = { type: "http", url: facts.console };
|
||||
|
||||
const managed: Record<string, unknown> = {
|
||||
attribution: { commit: "", pr: "" },
|
||||
allowAllClaudeAiMcps: true,
|
||||
};
|
||||
if (binding?.kind === "api-key") managed.apiKeyHelper = helperPath;
|
||||
|
||||
return {
|
||||
"managed-mcp.json": json({ mcpServers: sortKeys(servers) }),
|
||||
"managed-settings.json": json(managed),
|
||||
"CLAUDE.md": instructions(facts, settings),
|
||||
};
|
||||
}
|
||||
|
||||
function json(v: unknown): string {
|
||||
return JSON.stringify(v, null, 2) + "\n";
|
||||
}
|
||||
|
||||
function sortKeys(o: Record<string, unknown>): Record<string, unknown> {
|
||||
return Object.fromEntries(Object.keys(o).sort().map((k) => [k, o[k]]));
|
||||
}
|
||||
|
||||
export function instructions(facts: Facts, settings: Settings): string {
|
||||
const role = settings.role?.trim() ? settings.role.trim() : "not stated — set it in this module's settings for the node";
|
||||
return `# This machine is a node of a Novox mesh
|
||||
|
||||
Written by the mesh's \`claude-code\` module. Edit the module's settings or the catalogue, never this file:
|
||||
it is rewritten whenever the module renders.
|
||||
|
||||
## Who this node is
|
||||
|
||||
- **Node:** \`${facts.node}\`
|
||||
- **Role:** ${role}
|
||||
- The other nodes, their roles and what runs where: ask the controller (\`mesh-controller.nodes\`,
|
||||
\`mesh-controller.node\`). Nothing here lists them, because a copy drifts.
|
||||
|
||||
## How a session on this mesh works
|
||||
|
||||
The console is the only way to the mesh: the MCP server named \`mesh\`. It offers five tools, and
|
||||
everything else is an address you find and call through them:
|
||||
|
||||
- \`mesh_search\` — words in, matching addresses out. \`mesh_describe\` — one address's arguments.
|
||||
- \`mesh_call\` — call an address. A seat the mesh holds once is \`<seat>.<verb>\` (the mesh's own verbs
|
||||
are \`mesh-controller.<verb>\`: \`status\`, \`plan\`, \`node\`, \`assign\`, \`push\`, \`settings\`);
|
||||
a module on a machine is \`<node>/<module>.<tool>\`.
|
||||
- \`mesh_overview\` and \`mesh_machine\` — the mesh's seats and machines, and what one machine runs.
|
||||
|
||||
- **Symptom first.** For an error, a failing service or anything unexpected, search the record with the
|
||||
literal text before forming a hypothesis: the records module's \`records_search\`, then
|
||||
\`records_read\`.
|
||||
- **Ask the mesh before changing it**, and change it through the controller's verbs or the catalogue.
|
||||
- **A licence** through the \`anthropic-licence-manager\` seat's verbs. Never edit the agent's credentials
|
||||
file by hand, never print or ask for a token.
|
||||
|
||||
## Hard rules
|
||||
|
||||
- A file the mesh manages is changed through the verb or the catalogue that owns it, never on disk. If
|
||||
unsure, \`mesh-controller.plan\` for the node says what the mesh writes there.
|
||||
- Never write to a store's database by hand; schema changes are numbered migrations.
|
||||
- Never push to a main branch: a branch, a pull request, and a human approval for every merge.
|
||||
- The mesh creates no symlinks, and nobody else does either.
|
||||
- A package is declared in a module, never installed by hand.
|
||||
|
||||
## Conventions
|
||||
|
||||
- Commit messages are concise, in the imperative, about why.
|
||||
- Test before pushing: nodes update unattended.
|
||||
- The playbooks in the record say how research, decisions, designs, issues and hand-offs are done.
|
||||
`;
|
||||
}
|
||||
@@ -1,77 +0,0 @@
|
||||
// Sealing a token to one recipient (novox/hq ADR 0183): the manager seals what it hands a node to that
|
||||
// node's agent module key, and a node seals a waiting login to the key the manager names. X25519 for
|
||||
// the agreement, HKDF-SHA256 for the key, AES-256-GCM for the box — all from Node's own library, so a
|
||||
// bundle carries no dependency and no secret ever crosses the bus in the clear.
|
||||
//
|
||||
// A sealed box is `{ v: 1, eph, iv, tag, ct }`, every field base64. `eph` is a one-time public key, so
|
||||
// two boxes of one value to one recipient share nothing, and only the recipient's private key opens it.
|
||||
|
||||
import {
|
||||
createCipheriv, createDecipheriv, createPrivateKey, createPublicKey, diffieHellman,
|
||||
generateKeyPairSync, hkdfSync, randomBytes, type KeyObject,
|
||||
} from "node:crypto";
|
||||
|
||||
export interface SealedBox {
|
||||
readonly v: 1;
|
||||
readonly eph: string;
|
||||
readonly iv: string;
|
||||
readonly tag: string;
|
||||
readonly ct: string;
|
||||
}
|
||||
|
||||
/** A recipient's keypair, as the two PEM strings it is kept and published as. */
|
||||
export interface KeyPairPem {
|
||||
readonly publicKey: string;
|
||||
readonly privateKey: string;
|
||||
}
|
||||
|
||||
const INFO = Buffer.from("novox-mesh sealed box v1");
|
||||
|
||||
export function generateKeyPair(): KeyPairPem {
|
||||
const { publicKey, privateKey } = generateKeyPairSync("x25519");
|
||||
return {
|
||||
publicKey: publicKey.export({ type: "spki", format: "pem" }).toString(),
|
||||
privateKey: privateKey.export({ type: "pkcs8", format: "pem" }).toString(),
|
||||
};
|
||||
}
|
||||
|
||||
function keyFor(secret: Buffer, eph: Buffer, recipient: Buffer): Buffer {
|
||||
// The ephemeral and the recipient's public halves are bound into the key, so a box cannot be
|
||||
// re-addressed to another recipient by swapping its `eph`.
|
||||
return Buffer.from(hkdfSync("sha256", secret, Buffer.concat([eph, recipient]), INFO, 32));
|
||||
}
|
||||
|
||||
function rawPublic(key: KeyObject): Buffer {
|
||||
return key.export({ type: "spki", format: "der" }).subarray(-32);
|
||||
}
|
||||
|
||||
export function seal(plaintext: string, recipientPublicPem: string): SealedBox {
|
||||
const recipient = createPublicKey(recipientPublicPem);
|
||||
const eph = generateKeyPairSync("x25519");
|
||||
const secret = diffieHellman({ privateKey: eph.privateKey, publicKey: recipient });
|
||||
const ephRaw = eph.publicKey.export({ type: "spki", format: "der" });
|
||||
const key = keyFor(secret, ephRaw, rawPublic(recipient));
|
||||
const iv = randomBytes(12);
|
||||
const cipher = createCipheriv("aes-256-gcm", key, iv);
|
||||
const ct = Buffer.concat([cipher.update(plaintext, "utf8"), cipher.final()]);
|
||||
return {
|
||||
v: 1,
|
||||
eph: ephRaw.toString("base64"),
|
||||
iv: iv.toString("base64"),
|
||||
tag: cipher.getAuthTag().toString("base64"),
|
||||
ct: ct.toString("base64"),
|
||||
};
|
||||
}
|
||||
|
||||
/** Open a box with the recipient's private key. Throws on a box for another key or one tampered with. */
|
||||
export function open(box: SealedBox, privateKeyPem: string): string {
|
||||
if (!box || box.v !== 1) throw new Error("not a sealed box this module can open");
|
||||
const priv = createPrivateKey(privateKeyPem);
|
||||
const ephRaw = Buffer.from(box.eph, "base64");
|
||||
const eph = createPublicKey({ key: ephRaw, format: "der", type: "spki" });
|
||||
const secret = diffieHellman({ privateKey: priv, publicKey: eph });
|
||||
const key = keyFor(secret, ephRaw, rawPublic(createPublicKey(priv)));
|
||||
const decipher = createDecipheriv("aes-256-gcm", key, Buffer.from(box.iv, "base64"));
|
||||
decipher.setAuthTag(Buffer.from(box.tag, "base64"));
|
||||
return Buffer.concat([decipher.update(Buffer.from(box.ct, "base64")), decipher.final()]).toString("utf8");
|
||||
}
|
||||
@@ -1,54 +0,0 @@
|
||||
import { test } from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { mkdtempSync, readFileSync, statSync, writeFileSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import {
|
||||
decideApply, grantOf, holdsLogin, readCredentials, withGrant, writeCredentials, type Grant,
|
||||
} from "../dist/grant.js";
|
||||
|
||||
const NOW = 1_700_000_000_000;
|
||||
const HOUR = 3_600_000;
|
||||
const g = (over: Partial<Grant> = {}): Grant => ({
|
||||
accessToken: "tok-A", expiresAt: NOW + HOUR, refreshTokenExpiresAt: NOW + 30 * 24 * HOUR, ...over,
|
||||
});
|
||||
|
||||
test("a rotation applies a newer grant of the same licence", () => {
|
||||
assert.deepEqual(decideApply(g(), g({ accessToken: "tok-B", expiresAt: NOW + 2 * HOUR }), "rotation"), { apply: true });
|
||||
});
|
||||
|
||||
test("a rotation refuses a grant that arrived late and is older", () => {
|
||||
const d = decideApply(g({ accessToken: "new", expiresAt: NOW + 2 * HOUR }), g({ accessToken: "old" }), "rotation");
|
||||
assert.equal(d.apply === false && d.reason, "not-newer");
|
||||
});
|
||||
|
||||
test("a grant re-issued by a login is adopted even though it expires sooner (2026-09-05)", () => {
|
||||
const local = g({ expiresAt: NOW + 8 * HOUR, refreshTokenExpiresAt: NOW + 30 * 24 * HOUR });
|
||||
const offered = g({ accessToken: "reissued", expiresAt: NOW + HOUR, refreshTokenExpiresAt: NOW + 5 * 24 * HOUR });
|
||||
assert.deepEqual(decideApply(local, offered, "rotation"), { apply: true, reissued: true });
|
||||
});
|
||||
|
||||
test("a switch to another licence applies whatever the expiries say", () => {
|
||||
const local = g({ expiresAt: NOW + 8 * HOUR });
|
||||
assert.equal(decideApply(local, g({ accessToken: "other", expiresAt: NOW + HOUR }), "switch").apply, true);
|
||||
});
|
||||
|
||||
test("the same token is not rewritten", () => {
|
||||
assert.deepEqual(decideApply(g(), g(), "switch"), { apply: false, reason: "already-current" });
|
||||
});
|
||||
|
||||
test("a full grant left by a login is seen as a login, and stripped when the node's own is written", () => {
|
||||
const dir = mkdtempSync(join(tmpdir(), "claude-code-"));
|
||||
const path = join(dir, ".claude", ".credentials.json");
|
||||
writeFileSync(join(dir, "x"), "");
|
||||
const login = { claudeAiOauth: { accessToken: "at-login", refreshToken: "rt-login", expiresAt: NOW }, other: 1 };
|
||||
assert.equal(holdsLogin(login), true);
|
||||
writeCredentials(path, withGrant(login, g({ accessToken: "at-mesh", scopes: ["user:inference"] })));
|
||||
const back = readCredentials(path)!;
|
||||
assert.equal(holdsLogin(back), false);
|
||||
assert.equal(grantOf(back)!.accessToken, "at-mesh");
|
||||
assert.deepEqual(back.claudeAiOauth!.scopes, ["user:inference"]);
|
||||
assert.equal(back.other, 1, "a key the module does not know was lost");
|
||||
assert.ok(!readFileSync(path, "utf8").includes("rt-login"));
|
||||
assert.equal(statSync(path).mode & 0o777, 0o600);
|
||||
});
|
||||
@@ -1,19 +0,0 @@
|
||||
import { test } from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { mkdtempSync, writeFileSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { readIdentity } from "../dist/identity.js";
|
||||
|
||||
test("the account is read from the agent's state file", () => {
|
||||
const p = join(mkdtempSync(join(tmpdir(), "cc-id-")), ".claude.json");
|
||||
writeFileSync(p, JSON.stringify({ oauthAccount: { accountUuid: "u-1", emailAddress: "a@example.org" }, other: 2 }));
|
||||
assert.deepEqual(readIdentity(p), { accountUuid: "u-1", emailAddress: "a@example.org", organizationUuid: undefined });
|
||||
});
|
||||
|
||||
test("no state file, or no account in it, is no identity rather than a guess", () => {
|
||||
assert.equal(readIdentity("/nonexistent/.claude.json"), null);
|
||||
const p = join(mkdtempSync(join(tmpdir(), "cc-id-")), ".claude.json");
|
||||
writeFileSync(p, "{}");
|
||||
assert.equal(readIdentity(p), null);
|
||||
});
|
||||
@@ -1,173 +0,0 @@
|
||||
import { test } from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { existsSync, mkdirSync, mkdtempSync, readFileSync, writeFileSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import {
|
||||
apply, concerns, keypair, offerLogin, onServerChange, pull, registerServer, registered, ServerView, type Paths,
|
||||
type ServerChange, type ServerState,
|
||||
} from "../dist/node.js";
|
||||
import { generateKeyPair, open, seal } from "../dist/seal.js";
|
||||
|
||||
const NOW = Date.now();
|
||||
function node(name = "laptop"): { p: Paths; written: Record<string, string> } {
|
||||
const root = mkdtempSync(join(tmpdir(), "cc-node-"));
|
||||
const p = { state: join(root, "state"), facts: join(root, "state", "facts.json"), settings: join(root, "state", "settings.json"), home: join(root, "home"), node: name };
|
||||
mkdirSync(p.state, { recursive: true });
|
||||
mkdirSync(join(p.home, ".claude"), { recursive: true });
|
||||
writeFileSync(p.facts, JSON.stringify({ node: name, console: "http://127.0.0.1:4270/mcp" }));
|
||||
writeFileSync(p.settings, JSON.stringify({ role: "", mcp_servers: {} }));
|
||||
return { p, written: {} };
|
||||
}
|
||||
const writer = (w: Record<string, string>) => (name: string, content: string) => { w[name] = content; return `${name}: written`; };
|
||||
const creds = (p: Paths) => JSON.parse(readFileSync(join(p.home, ".claude", ".credentials.json"), "utf8"));
|
||||
const grantFor = (p: Paths, licence: string, token: string, kind: "subscription" | "api-key" = "subscription", identity?: object) => ({
|
||||
licence, kind, identity,
|
||||
sealed: seal(kind === "api-key" ? token : JSON.stringify({ accessToken: token, expiresAt: NOW + 3_600_000, refreshTokenExpiresAt: NOW + 86_400_000, subscriptionType: licence }), keypair(p).publicKey),
|
||||
});
|
||||
|
||||
test("a pull asks the seat with this node's key and applies what it answers", async () => {
|
||||
const { p, written } = node();
|
||||
let asked: [string, Record<string, unknown>] | null = null;
|
||||
const r = await pull(p, async (address, args) => { asked = [address, args]; return grantFor(p, "personal", "at-1"); }, writer(written));
|
||||
assert.equal(asked![0], "anthropic-licence-manager.current");
|
||||
assert.equal(asked![1].node, "laptop");
|
||||
assert.match(String(asked![1].public_key), /BEGIN PUBLIC KEY/);
|
||||
assert.equal(r.applied, true);
|
||||
assert.equal(creds(p).claudeAiOauth.accessToken, "at-1");
|
||||
assert.ok(written["managed-mcp.json"]);
|
||||
});
|
||||
|
||||
test("a switch replaces the old licence's grant whole and points the account at the new one", () => {
|
||||
const { p, written } = node();
|
||||
writeFileSync(join(p.home, ".claude.json"), JSON.stringify({ oauthAccount: { accountUuid: "old" }, projects: { keep: 1 } }));
|
||||
apply(p, grantFor(p, "personal", "at-1"), writer(written));
|
||||
const r = apply(p, grantFor(p, "work", "at-2", "subscription", { accountUuid: "new", emailAddress: "w@example.org" }), writer(written));
|
||||
assert.equal(r.switched, true);
|
||||
assert.equal(creds(p).claudeAiOauth.accessToken, "at-2");
|
||||
assert.equal(creds(p).claudeAiOauth.subscriptionType, "work", "the old licence's subscription type survived the switch");
|
||||
const account = JSON.parse(readFileSync(join(p.home, ".claude.json"), "utf8"));
|
||||
assert.equal(account.oauthAccount.accountUuid, "new");
|
||||
assert.deepEqual(account.projects, { keep: 1 });
|
||||
});
|
||||
|
||||
test("switching to the API key adds the key-helper; switching away removes the key and the helper", () => {
|
||||
const { p, written } = node();
|
||||
apply(p, grantFor(p, "api", "sk-key", "api-key"), writer(written));
|
||||
assert.ok(JSON.parse(written["managed-settings.json"]).apiKeyHelper);
|
||||
assert.ok(existsSync(join(p.state, "api-key")));
|
||||
apply(p, grantFor(p, "personal", "at-1"), writer(written));
|
||||
assert.ok(!("apiKeyHelper" in JSON.parse(written["managed-settings.json"])));
|
||||
assert.ok(!existsSync(join(p.state, "api-key")) && !existsSync(join(p.state, "api-key-helper")));
|
||||
});
|
||||
|
||||
test("a rotation event concerns the node bound to that licence; a switch event the node it names", () => {
|
||||
const { p, written } = node();
|
||||
apply(p, grantFor(p, "personal", "at-1"), writer(written));
|
||||
assert.equal(concerns(p, "claude-licence-manager.licence.rotated", { licence: "personal" }), true);
|
||||
assert.equal(concerns(p, "claude-licence-manager.licence.rotated", { licence: "work" }), false);
|
||||
assert.equal(concerns(p, "claude-licence-manager.licence.switched", { node: "laptop", licence: "work" }), true);
|
||||
assert.equal(concerns(p, "claude-licence-manager.licence.switched", { node: "server" }), false);
|
||||
});
|
||||
|
||||
test("a login is offered to the seat sealed to the seat's key, with the account it belongs to", async () => {
|
||||
const { p } = node();
|
||||
const manager = generateKeyPair();
|
||||
writeFileSync(join(p.home, ".claude", ".credentials.json"), JSON.stringify({ claudeAiOauth: { accessToken: "at-login", refreshToken: "rt-login", expiresAt: NOW } }));
|
||||
writeFileSync(join(p.home, ".claude.json"), JSON.stringify({ oauthAccount: { accountUuid: "u-9" } }));
|
||||
const calls: [string, Record<string, unknown>][] = [];
|
||||
await offerLogin(p, async (address, args) => { calls.push([address, args]); return address.endsWith("public_key") ? { public_key: manager.publicKey } : { adopted: true }; });
|
||||
assert.deepEqual(calls.map((c) => c[0]), ["anthropic-licence-manager.public_key", "anthropic-licence-manager.adopt"]);
|
||||
const adopt = calls[1][1] as { identity: { accountUuid: string }; sealed: never };
|
||||
assert.equal(adopt.identity.accountUuid, "u-9");
|
||||
assert.equal(JSON.parse(open(adopt.sealed, manager.privateKey)).refreshToken, "rt-login");
|
||||
assert.ok(!JSON.stringify(adopt).includes("rt-login"), "the refresh token crossed in the clear");
|
||||
});
|
||||
|
||||
test("no refresh token in the file is no login, and nothing is asked", async () => {
|
||||
const { p } = node();
|
||||
writeFileSync(join(p.home, ".claude", ".credentials.json"), JSON.stringify({ claudeAiOauth: { accessToken: "at", expiresAt: NOW } }));
|
||||
assert.equal(await offerLogin(p, async () => { throw new Error("asked"); }), null);
|
||||
});
|
||||
|
||||
/** The `servers` state as the bus holds it, shared by every node in a test, with each node's watch. */
|
||||
function bus() {
|
||||
const kept = new Map<string, Record<string, unknown>>();
|
||||
const watchers: ((c: ServerChange) => void)[] = [];
|
||||
const state: ServerState = {
|
||||
put: async (key, value) => { kept.set(key, value); watchers.forEach((w) => w({ key, op: "put", value })); return kept.size; },
|
||||
delete: async (key) => { kept.delete(key); watchers.forEach((w) => w({ key, op: "delete" })); },
|
||||
keys: async () => [...kept.keys()].sort(),
|
||||
};
|
||||
/** A node joining: its view takes the current state, then every change. */
|
||||
const join = (n: { p: Paths; written: Record<string, string> }) => {
|
||||
const view = new ServerView(n.p);
|
||||
for (const [key, value] of kept) onServerChange(view, { key, op: "put", value }, n.p, writer(n.written));
|
||||
watchers.push((c) => onServerChange(view, c, n.p, writer(n.written)));
|
||||
return view;
|
||||
};
|
||||
return { state, join, kept };
|
||||
}
|
||||
|
||||
test("registering a server here puts it under this node's key, renders it, and asks about the other nodes", async () => {
|
||||
const n = node();
|
||||
const b = bus();
|
||||
const view = b.join(n);
|
||||
const r = await registerServer(n.p, { name: "search", entry: { type: "http", url: "https://s.example/mcp" } },
|
||||
b.state, view, writer(n.written), async () => ["laptop", "server", "desktop"]);
|
||||
assert.equal(r.here, "changed");
|
||||
assert.match(String(r.also), /server, desktop/);
|
||||
assert.deepEqual([...b.kept.keys()], ["laptop.search"]);
|
||||
assert.ok(JSON.parse(n.written["managed-mcp.json"]).mcpServers.search);
|
||||
});
|
||||
|
||||
test("registering for every node reaches the others through their watch, and a node joining later reads it", async () => {
|
||||
const a = node("laptop"), s = node("server");
|
||||
const b = bus();
|
||||
const va = b.join(a);
|
||||
b.join(s);
|
||||
await registerServer(a.p, { name: "docs", entry: { type: "stdio", command: "docs-mcp" }, nodes: "all" },
|
||||
b.state, va, writer(a.written), async () => []);
|
||||
assert.deepEqual([...b.kept.keys()], ["all.docs"]);
|
||||
assert.deepEqual(registered(s.p).docs, { type: "stdio", command: "docs-mcp" });
|
||||
assert.ok(JSON.parse(s.written["managed-mcp.json"]).mcpServers.docs);
|
||||
// The gap events left: a node assigned after the registration takes the whole current set at start.
|
||||
const late = node("desktop");
|
||||
b.join(late);
|
||||
assert.deepEqual(registered(late.p).docs, { type: "stdio", command: "docs-mcp" });
|
||||
// Unregistering is a delete, and every node's view drops it.
|
||||
await registerServer(a.p, { name: "docs", nodes: "all" }, b.state, va, writer(a.written), async () => []);
|
||||
assert.equal(registered(s.p).docs, undefined);
|
||||
assert.equal(registered(late.p).docs, undefined);
|
||||
});
|
||||
|
||||
test("a node's own registration overrides the one for every node; other nodes' keys leave this one alone", async () => {
|
||||
const a = node("laptop"), s = node("server");
|
||||
const b = bus();
|
||||
const va = b.join(a);
|
||||
const vs = b.join(s);
|
||||
await registerServer(a.p, { name: "x", entry: { type: "http", url: "https://all" }, nodes: "all" }, b.state, va, writer(a.written), async () => []);
|
||||
await registerServer(a.p, { name: "x", entry: { type: "http", url: "https://laptop" } }, b.state, va, writer(a.written), async () => []);
|
||||
assert.equal(registered(a.p).x.url, "https://laptop");
|
||||
assert.equal(registered(s.p).x.url, "https://all");
|
||||
await registerServer(a.p, { name: "only", entry: { type: "http", url: "https://o" }, nodes: ["server"] }, b.state, va, writer(a.written), async () => []);
|
||||
assert.equal(registered(a.p).only, undefined);
|
||||
assert.equal(registered(s.p).only.url, "https://o");
|
||||
// Unregistering here leaves the every-node one applying, and says so.
|
||||
const r = await registerServer(a.p, { name: "x" }, b.state, va, writer(a.written), async () => []);
|
||||
assert.match(String(r.still), /still applies here/);
|
||||
assert.equal(registered(a.p).x.url, "https://all");
|
||||
assert.equal(vs.effective().x.url, "https://all");
|
||||
});
|
||||
|
||||
test("a bad entry is refused before anything is put; a repeated change changes nothing", async () => {
|
||||
const n = node();
|
||||
const b = bus();
|
||||
const view = b.join(n);
|
||||
const r = await registerServer(n.p, { name: "mesh", entry: { type: "http", url: "https://x" } }, b.state, view, writer(n.written), async () => []);
|
||||
assert.equal(r.registered, false);
|
||||
assert.equal(b.kept.size, 0);
|
||||
assert.equal(onServerChange(view, { key: "all.a", op: "put", value: { type: "http", url: "https://a" } }, n.p, writer(n.written)), "registered all.a");
|
||||
assert.equal(onServerChange(view, { key: "all.a", op: "put", value: { type: "http", url: "https://a" } }, n.p, writer(n.written)), null);
|
||||
assert.equal(onServerChange(view, { key: "server.b", op: "put", value: { type: "http", url: "https://b" } }, n.p, writer(n.written)), null);
|
||||
});
|
||||
@@ -1,40 +0,0 @@
|
||||
import { test } from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { render } from "../dist/render.js";
|
||||
|
||||
const facts = { node: "workstation", console: "http://127.0.0.1:4270/mcp" };
|
||||
|
||||
test("the console is the `mesh` server, and an operator's servers are listed beside it", () => {
|
||||
const out = render(facts, { mcp_servers: { search: { type: "http", url: "https://s.example/mcp" } } }, null, "/h");
|
||||
const mcp = JSON.parse(out["managed-mcp.json"]);
|
||||
assert.deepEqual(Object.keys(mcp.mcpServers), ["mesh", "search"]);
|
||||
assert.deepEqual(mcp.mcpServers.mesh, { type: "http", url: facts.console });
|
||||
});
|
||||
|
||||
test("a setting cannot replace the mesh's own entry, and a name the vendor refuses is left out", () => {
|
||||
const out = render(facts, { mcp_servers: { mesh: { type: "http", url: "http://evil" }, "bad name": {} } }, null, "/h");
|
||||
const mcp = JSON.parse(out["managed-mcp.json"]);
|
||||
assert.equal(mcp.mcpServers.mesh.url, facts.console);
|
||||
assert.ok(!("bad name" in mcp.mcpServers));
|
||||
});
|
||||
|
||||
test("managed settings carry the mesh's keys only, and the key-helper only for an API-key licence", () => {
|
||||
const sub = JSON.parse(render(facts, {}, { licence: "personal", kind: "subscription" }, "/h")["managed-settings.json"]);
|
||||
assert.deepEqual(sub, { attribution: { commit: "", pr: "" }, allowAllClaudeAiMcps: true });
|
||||
const key = JSON.parse(render(facts, {}, { licence: "api", kind: "api-key" }, "/state/api-key-helper")["managed-settings.json"]);
|
||||
assert.equal(key.apiKeyHelper, "/state/api-key-helper");
|
||||
assert.ok(!("model" in key), "a preference is the person's");
|
||||
});
|
||||
|
||||
test("the instruction file names the node and its role, and no other node", () => {
|
||||
const md = render(facts, { role: "the laptop" }, null, "/h")["CLAUDE.md"];
|
||||
assert.match(md, /\*\*Node:\*\* `workstation`/);
|
||||
assert.match(md, /\*\*Role:\*\* the laptop/);
|
||||
assert.match(md, /mesh_call/);
|
||||
assert.match(md, /records_search/);
|
||||
});
|
||||
|
||||
test("rendering is deterministic, so an unchanged input writes nothing", () => {
|
||||
const s = { mcp_servers: { b: { type: "http", url: "https://b" }, a: { type: "http", url: "https://a" } } };
|
||||
assert.deepEqual(render(facts, s, null, "/h"), render(facts, s, null, "/h"));
|
||||
});
|
||||
@@ -1,31 +0,0 @@
|
||||
import { test } from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { generateKeyPair, open, seal } from "../dist/seal.js";
|
||||
|
||||
test("a box opens with its recipient's key and yields the value", () => {
|
||||
const k = generateKeyPair();
|
||||
assert.equal(open(seal("at-secret", k.publicKey), k.privateKey), "at-secret");
|
||||
});
|
||||
|
||||
test("a box sealed for one node does not open with another node's key", () => {
|
||||
const a = generateKeyPair();
|
||||
const b = generateKeyPair();
|
||||
assert.throws(() => open(seal("at-secret", a.publicKey), b.privateKey));
|
||||
});
|
||||
|
||||
test("a tampered box is refused, not opened to garbage", () => {
|
||||
const k = generateKeyPair();
|
||||
const box = seal("at-secret", k.publicKey);
|
||||
const ct = Buffer.from(box.ct, "base64");
|
||||
ct[0] ^= 0xff;
|
||||
assert.throws(() => open({ ...box, ct: ct.toString("base64") }, k.privateKey));
|
||||
});
|
||||
|
||||
test("two boxes of one value share nothing a reader could compare", () => {
|
||||
const k = generateKeyPair();
|
||||
const x = seal("at-secret", k.publicKey);
|
||||
const y = seal("at-secret", k.publicKey);
|
||||
assert.notEqual(x.ct, y.ct);
|
||||
assert.notEqual(x.eph, y.eph);
|
||||
assert.ok(!JSON.stringify(x).includes("at-secret"));
|
||||
});
|
||||
@@ -1,224 +0,0 @@
|
||||
// claude-code's bundle (novox/hq design 36, ADR 0183). The node's runtime launches it over stdio, as the
|
||||
// operator account (ADR 0193), and is its bus (ADR 0198): it asks tools, emits and consumes through the
|
||||
// runtime. It is given its state directory and two files the mesh renders into it (ADR 0192), beside the
|
||||
// runtime's own words. **stdout is the MCP channel**: everything this module says, it says on stderr.
|
||||
//
|
||||
// At start it renders the agent's managed directory, asks the licence manager for this node's token,
|
||||
// begins watching the credentials file for a login, takes the manager's licence events, and watches the
|
||||
// module's `servers` state — every node's MCP server registrations (novox/hq ADR 0201). node.ts holds the
|
||||
// logic.
|
||||
|
||||
import { mkdtempSync, readFileSync, rmSync, watchFile, writeFileSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { spawnSync } from "node:child_process";
|
||||
import { join } from "node:path";
|
||||
import { registerModuleTools, type ToolDefinition } from "@novox/mesh-sdk/tools";
|
||||
import { broker } from "@novox/mesh-sdk/messaging";
|
||||
import { on } from "@novox/mesh-sdk/events";
|
||||
import { state } from "@novox/mesh-sdk/state";
|
||||
|
||||
import {
|
||||
MANAGED_DIR, SEAT, ServerView, concerns, keypair, offerLogin, onServerChange, pull, readJson, registerServer,
|
||||
registered, renderNow, type Ask, type Paths, type Registration, type ServerChange, type ServerState, type WriteManaged,
|
||||
} from "../node.js";
|
||||
import { grantOf, holdsLogin, readCredentials } from "../grant.js";
|
||||
import { createHash } from "node:crypto";
|
||||
|
||||
const say = (line: string) => console.error(`[claude-code] ${line}`);
|
||||
const fingerprint = (s: string) => "sha256:" + createHash("sha256").update(s).digest("hex").slice(0, 16);
|
||||
|
||||
function pathsFrom(env: NodeJS.ProcessEnv): Paths | null {
|
||||
const state = env.MESH_CLAUDE_CODE_STATE, facts = env.MESH_CLAUDE_CODE_FACTS;
|
||||
const settings = env.MESH_CLAUDE_CODE_SETTINGS, home = env.MESH_OPERATOR_HOME, node = env.MESH_NODE;
|
||||
if (!state || !facts || !settings || !home || !node) return null;
|
||||
return { state, facts, settings, home, node };
|
||||
}
|
||||
|
||||
/** Write one managed file as root, only when its content changed. */
|
||||
const writeManaged: WriteManaged = (name, content) => {
|
||||
const path = join(MANAGED_DIR, name);
|
||||
try {
|
||||
if (readFileSync(path, "utf8") === content) return `${name}: unchanged`;
|
||||
} catch {
|
||||
/* absent */
|
||||
}
|
||||
// From a file, never /dev/stdin: Node hands a child its input over a socket, which /dev/stdin cannot
|
||||
// open (ENXIO) — found on the first assignment, where nothing under /etc/claude-code was ever written.
|
||||
const staged = mkdtempSync(join(tmpdir(), "claude-code-"));
|
||||
const source = join(staged, name);
|
||||
writeFileSync(source, content, { mode: 0o644 });
|
||||
const asRoot = process.getuid?.() === 0;
|
||||
const cmd = asRoot ? ["install", "-D", "-m", "0644", source, path] : ["sudo", "-n", "install", "-D", "-m", "0644", source, path];
|
||||
const r = spawnSync(cmd[0], cmd.slice(1), { encoding: "utf8" });
|
||||
rmSync(staged, { recursive: true, force: true });
|
||||
if (r.status !== 0) {
|
||||
throw new Error(`${name}: could not be written to ${MANAGED_DIR} (${(r.stderr || r.error?.message || "").trim()}); ` +
|
||||
`the module writes there through the operator account's passwordless sudo`);
|
||||
}
|
||||
return `${name}: written`;
|
||||
};
|
||||
|
||||
/** A tool on the bus, through the runtime; its MCP answer read back as JSON where it is JSON. */
|
||||
const ask: Ask = async (address, args) => {
|
||||
const answer = (await broker().request<Record<string, unknown>, { content?: { text?: string }[]; isError?: boolean }>(address, args)) ?? {};
|
||||
const text = answer.content?.map((c) => c.text ?? "").join("") ?? "";
|
||||
if (answer.isError) throw new Error(`${address}: ${text}`);
|
||||
try {
|
||||
return JSON.parse(text);
|
||||
} catch {
|
||||
return text;
|
||||
}
|
||||
};
|
||||
|
||||
/** The nodes claude-code runs on, from the controller's list of modules — for the register tool's question. */
|
||||
async function nodesRunningMe(): Promise<string[]> {
|
||||
const out = await ask("mesh-controller.modules", {});
|
||||
const text = typeof out === "string" ? out : String((out as { output?: string })?.output ?? "");
|
||||
const line = text.split("\n").find((l) => /^claude-code\s/.test(l)) ?? "";
|
||||
const on = line.split(" on ")[1] ?? "";
|
||||
return on.trim() === "nothing" ? [] : on.split(",").map((s) => s.trim()).filter(Boolean);
|
||||
}
|
||||
|
||||
function status(p: Paths): Record<string, unknown> {
|
||||
const creds = readCredentials(join(p.home, ".claude", ".credentials.json"));
|
||||
const grant = grantOf(creds);
|
||||
const managed = ["managed-mcp.json", "managed-settings.json", "CLAUDE.md"].map((f) => {
|
||||
try {
|
||||
return { file: join(MANAGED_DIR, f), fingerprint: fingerprint(readFileSync(join(MANAGED_DIR, f), "utf8")) };
|
||||
} catch {
|
||||
return { file: join(MANAGED_DIR, f), fingerprint: null };
|
||||
}
|
||||
});
|
||||
return {
|
||||
node: p.node,
|
||||
licence: readJson(join(p.state, "licence.json"), null),
|
||||
token: grant ? { fingerprint: fingerprint(grant.accessToken), expiresAt: new Date(grant.expiresAt).toISOString(),
|
||||
loginWaiting: holdsLogin(creds) } : null,
|
||||
managed,
|
||||
registered: Object.keys(registered(p)),
|
||||
};
|
||||
}
|
||||
|
||||
/** The module's MCP servers on the bus (ADR 0201): its own state, which every node of it watches. */
|
||||
const servers = () => state<Record<string, unknown>>("servers") as unknown as ServerState;
|
||||
|
||||
/** What this node takes from that state, kept from the watch. One per process. */
|
||||
let view: ServerView | null = null;
|
||||
const viewOf = (p: Paths) => (view ??= new ServerView(p));
|
||||
|
||||
function tools(p: Paths): ToolDefinition[] {
|
||||
const nodesArg = { type: "string", description: 'more nodes: "all" for every node running claude-code, or a comma-separated list; absent is this node only' };
|
||||
const nodesOf = (v: unknown): Registration["nodes"] =>
|
||||
v === undefined || v === "" ? undefined : v === "all" ? "all" : String(v).split(",").map((s) => s.trim()).filter(Boolean);
|
||||
return [
|
||||
{
|
||||
name: "claude_code_status",
|
||||
description: "Claude Code on this machine as the mesh configured it: the licence it holds and when its token expires, the managed files, the MCP servers registered here. Fingerprints only, never a token.",
|
||||
input: {},
|
||||
run: async () => status(p),
|
||||
},
|
||||
{
|
||||
name: "claude_code_render",
|
||||
description: "Write Claude Code's managed directory now, from the mesh's facts, this module's settings and the servers registered here.",
|
||||
input: {},
|
||||
run: async () => ({ rendered: renderNow(p, writeManaged) }),
|
||||
},
|
||||
{
|
||||
name: "claude_code_pull",
|
||||
description: "Ask the licence manager for this node's current token now and apply it, rather than waiting for its next event.",
|
||||
input: {},
|
||||
run: async () => pull(p, ask, writeManaged),
|
||||
},
|
||||
{
|
||||
name: "claude_code_mcp_list",
|
||||
description: "The MCP servers registered through this module: those that apply on this node (beside the console, `mesh`, and those set in the module's settings), and every registration on the mesh, by key — `all.<server>` for every node, `<node>.<server>` for one.",
|
||||
input: {},
|
||||
run: async () => ({ here: registered(p), everywhere: await servers().keys() }),
|
||||
},
|
||||
{
|
||||
name: "claude_code_mcp_register",
|
||||
description: "Register an MCP server with Claude Code on this node, every node, or a list — an http/sse server by url, or a stdio server by command. Kept on the bus, so a node that joins later takes it too. Never put a secret in env or headers: the mesh refuses one.",
|
||||
input: {
|
||||
name: { type: "string", description: "the server's name: letters, digits, - and _" },
|
||||
type: { type: "string", description: "http, sse or stdio (default stdio when a command is given, http when a url is)" },
|
||||
url: { type: "string", description: "an http or sse server's url" },
|
||||
command: { type: "string", description: "a stdio server's program" },
|
||||
args: { type: "array", description: "a stdio server's arguments" },
|
||||
env: { type: "object", description: "a stdio server's environment" },
|
||||
headers: { type: "object", description: "an http server's headers" },
|
||||
nodes: nodesArg,
|
||||
},
|
||||
run: async (a) => {
|
||||
const entry: Record<string, unknown> = { type: a.type ?? (a.url ? "http" : "stdio") };
|
||||
for (const k of ["url", "command", "args", "env", "headers"]) if (a[k] !== undefined) entry[k] = a[k];
|
||||
return registerServer(p, { name: String(a.name ?? ""), entry, nodes: nodesOf(a.nodes) }, servers(), viewOf(p), writeManaged, nodesRunningMe);
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "claude_code_mcp_unregister",
|
||||
description: "Remove an MCP server registered through this module, on this node or more.",
|
||||
input: { name: { type: "string", description: "the server's name" }, nodes: nodesArg },
|
||||
run: async (a) => registerServer(p, { name: String(a.name ?? ""), nodes: nodesOf(a.nodes) }, servers(), viewOf(p), writeManaged, nodesRunningMe),
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
registerModuleTools("claude-code", (env) => {
|
||||
const p = pathsFrom(env);
|
||||
if (!p) return [];
|
||||
try {
|
||||
keypair(p);
|
||||
for (const line of renderNow(p, writeManaged)) if (!line.endsWith("unchanged")) say(line);
|
||||
} catch (err) {
|
||||
say(err instanceof Error ? err.message : String(err));
|
||||
}
|
||||
return tools(p);
|
||||
});
|
||||
|
||||
// Launched by the runtime: the bus is there from the first line (ADR 0198). Outside it — a test, a
|
||||
// build — nothing below runs.
|
||||
const p = process.env.MESH_SERVED_MODULE ? pathsFrom(process.env) : null;
|
||||
if (p) {
|
||||
const loud = (what: string) => (err: unknown) => say(`${what}: ${err instanceof Error ? err.message : String(err)}`);
|
||||
|
||||
void on<{ licence?: string; node?: string }>("claude-licence-manager.licence.*", async (event) => {
|
||||
if (!concerns(p, event.type, event.body ?? {})) return;
|
||||
say(`${event.type} — asking ${SEAT} for this node's token`);
|
||||
say(JSON.stringify(await pull(p, ask, writeManaged).catch((e) => ({ failed: String(e) }))));
|
||||
}).catch(loud("the licence events"));
|
||||
|
||||
// Every node's MCP servers: the whole current set first, then each change (ADR 0201). **Not awaited
|
||||
// where the module is imported**: the runtime waits on the handshake, and a bucket that is not on the
|
||||
// bus yet — or a grant the bus has not reloaded — answers late; awaited here, that left the bundle
|
||||
// unable to answer `initialize` in time and the module unserved (found on its first assignment). So it
|
||||
// watches beside the handshake and asks again until the state answers; until then the managed
|
||||
// directory holds what the file kept from the last run.
|
||||
const watchServers = (attempt = 0): void => {
|
||||
state<Record<string, unknown>>("servers").watch((c) => {
|
||||
try {
|
||||
const done = onServerChange(viewOf(p), c as ServerChange, p, writeManaged);
|
||||
if (done) say(done);
|
||||
} catch (err) {
|
||||
loud(`taking ${c.op} ${c.key}`)(err); // the view took it; the next render writes it
|
||||
}
|
||||
}).then(
|
||||
() => say(`watching the MCP servers${attempt ? ` (after ${attempt} refusal(s))` : ""}`),
|
||||
(err) => {
|
||||
const wait = [2, 5, 10, 30][attempt] ?? 60;
|
||||
say(`the MCP servers cannot be watched yet (${err instanceof Error ? err.message : String(err)}); asking again in ${wait}s`);
|
||||
setTimeout(() => watchServers(attempt + 1), wait * 1000);
|
||||
});
|
||||
};
|
||||
watchServers();
|
||||
|
||||
// Catch up once at start: a node that was off takes its current token now.
|
||||
void pull(p, ask, writeManaged).then((r) => say(`at start: ${JSON.stringify(r)}`), loud("asking for this node's token at start"));
|
||||
|
||||
// A login: a refresh token appears in the credentials file. Polled, because the file is replaced by
|
||||
// rename and a watch on the old inode would go quiet.
|
||||
const credentials = join(p.home, ".claude", ".credentials.json");
|
||||
watchFile(credentials, { interval: 5000 }, () => {
|
||||
void offerLogin(p, ask).then((r) => { if (r) say(`a login here was offered to ${SEAT}: ${JSON.stringify(r)}`); },
|
||||
loud("offering a login to the licence manager"));
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
# cloudflare-dns's runtime: the tool runtime, carrying this module's compiled code.
|
||||
#
|
||||
# **Built from this module's own directory and nothing else.** The sdk and the tool runtime are in
|
||||
# the base images, published like any other artifact — which is what makes this buildable by the
|
||||
# mesh from a repository and a path (novox/hq ADR 0069) rather than only on a workstation that
|
||||
# happens to have the siblings.
|
||||
#
|
||||
# Two bases, named rather than pinned (novox/hq issue 044): the image this is COMPILED in and the
|
||||
# image it RUNS in — the second must not carry a compiler. Declared in module.json's `build.on`.
|
||||
ARG BUILD_BASE
|
||||
ARG RUNTIME_BASE
|
||||
|
||||
FROM ${BUILD_BASE} AS build
|
||||
WORKDIR /app/modules/cloudflare-dns
|
||||
COPY . .
|
||||
RUN node /app/node_modules/typescript/bin/tsc client.ts tools/index.ts provisioner/index.ts \
|
||||
--module NodeNext --moduleResolution NodeNext --target ES2022 --outDir dist
|
||||
|
||||
FROM ${RUNTIME_BASE}
|
||||
COPY --from=build /app/modules/cloudflare-dns/dist /app/modules/cloudflare-dns/dist
|
||||
# Every serve-time entrypoint, loaded by the runtime in serve mode: tools and events serve, and a
|
||||
# provider's provisioner runs its reconcile loop in the same process, with the broker connected —
|
||||
# the convention novox/hq issues 060/061 settled.
|
||||
ENV MESH_TOOL_MODULES=/app/modules/cloudflare-dns/dist/tools/index.js,/app/modules/cloudflare-dns/dist/provisioner/index.js
|
||||
@@ -12,61 +12,87 @@
|
||||
"public-dns": {}
|
||||
},
|
||||
"grants": {
|
||||
"public-dns": "${dir:grants}"
|
||||
"public-dns": "/var/lib/cloudflare-dns/grants"
|
||||
},
|
||||
"receives": {
|
||||
"public-dns": "${dir:grants}/mesh.json"
|
||||
"public-dns": "/var/lib/cloudflare-dns/grants/mesh.json"
|
||||
},
|
||||
"own-secrets": {
|
||||
"token": "${dir:state}/token"
|
||||
"token": "/var/lib/cloudflare-dns/token",
|
||||
"broker": "/var/lib/mesh/cloudflare-dns/broker"
|
||||
},
|
||||
"emits": [
|
||||
"record.created",
|
||||
"record.removed"
|
||||
],
|
||||
"resources": [
|
||||
{
|
||||
"id": "mesh-state",
|
||||
"type": "directory",
|
||||
"path": "/var/lib/mesh/cloudflare-dns",
|
||||
"mode": "0700"
|
||||
},
|
||||
{
|
||||
"id": "state",
|
||||
"type": "directory",
|
||||
"mode": "0700",
|
||||
"place": "."
|
||||
"path": "/var/lib/cloudflare-dns",
|
||||
"mode": "0700"
|
||||
},
|
||||
{
|
||||
"id": "grants",
|
||||
"type": "directory",
|
||||
"path": "/var/lib/cloudflare-dns/grants",
|
||||
"mode": "0700"
|
||||
},
|
||||
{
|
||||
"id": "config",
|
||||
"type": "file",
|
||||
"path": "${dir:state}/config.json",
|
||||
"path": "/var/lib/cloudflare-dns/config.json",
|
||||
"merge": "json",
|
||||
"content": "{}",
|
||||
"mode": "0600"
|
||||
},
|
||||
{
|
||||
"id": "runtime",
|
||||
"type": "container",
|
||||
"name": "mesh-cloudflare-dns",
|
||||
"network": "host",
|
||||
"volumes": [
|
||||
"/var/lib/cloudflare-dns/config.json:/run/config/config.json:ro",
|
||||
"/var/lib/cloudflare-dns/grants:/grants",
|
||||
"/var/lib/cloudflare-dns/token:/run/secrets/token:ro",
|
||||
"/var/lib/mesh/cloudflare-dns/broker:/run/secrets/broker:ro"
|
||||
],
|
||||
"env": {
|
||||
"MESH_CLOUDFLARE_TOKEN_FILE": "/run/secrets/token",
|
||||
"MESH_BROKER_FILE": "/run/secrets/broker",
|
||||
"MESH_CLOUDFLARE_CONFIG_FILE": "/run/config/config.json",
|
||||
"MESH_RECEIVES": "/var/lib/cloudflare-dns/grants/mesh.json"
|
||||
},
|
||||
"artifact": "runtime"
|
||||
}
|
||||
],
|
||||
"capabilities": [
|
||||
"container-runtime"
|
||||
],
|
||||
"build": {
|
||||
"on": [
|
||||
{
|
||||
"arg": "BUILD_BASE",
|
||||
"module": "mesh-tools",
|
||||
"artifact": "build"
|
||||
},
|
||||
{
|
||||
"arg": "RUNTIME_BASE",
|
||||
"module": "mesh-tools",
|
||||
"artifact": "runtime"
|
||||
}
|
||||
],
|
||||
"artifacts": [
|
||||
{
|
||||
"name": "code",
|
||||
"kind": "bundle",
|
||||
"language": "typescript",
|
||||
"entrypoints": [
|
||||
"tools/index.js",
|
||||
"provisioner/index.js"
|
||||
],
|
||||
"loads": [
|
||||
"tools/index.js",
|
||||
"provisioner/index.js"
|
||||
],
|
||||
"env": {
|
||||
"MESH_CLOUDFLARE_TOKEN_FILE": "${dir:state}/token",
|
||||
"MESH_CLOUDFLARE_CONFIG_FILE": "${dir:state}/config.json",
|
||||
"MESH_RECEIVES": "${dir:grants}/mesh.json"
|
||||
}
|
||||
"name": "runtime",
|
||||
"kind": "image",
|
||||
"from": "Dockerfile"
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
# confluence's runtime: the tool runtime, carrying this module's compiled code.
|
||||
#
|
||||
# **Built from this module's own directory and nothing else.** The sdk and the tool runtime are in
|
||||
# the base images, published like any other artifact — which is what makes this buildable by the
|
||||
# mesh from a repository and a path (novox/hq ADR 0069) rather than only on a workstation that
|
||||
# happens to have the siblings.
|
||||
#
|
||||
# Two bases, named rather than pinned (novox/hq issue 044): the image this is COMPILED in and the
|
||||
# image it RUNS in — the second must not carry a compiler. Declared in module.json's `build.on`.
|
||||
ARG BUILD_BASE
|
||||
ARG RUNTIME_BASE
|
||||
|
||||
FROM ${BUILD_BASE} AS build
|
||||
WORKDIR /app/modules/confluence
|
||||
COPY . .
|
||||
RUN node /app/node_modules/typescript/bin/tsc client.ts tools/index.ts \
|
||||
--module NodeNext --moduleResolution NodeNext --target ES2022 --outDir dist
|
||||
|
||||
FROM ${RUNTIME_BASE}
|
||||
COPY --from=build /app/modules/confluence/dist /app/modules/confluence/dist
|
||||
# Every serve-time entrypoint, loaded by the runtime in serve mode: tools and events serve, and a
|
||||
# provider's provisioner runs its reconcile loop in the same process, with the broker connected —
|
||||
# the convention novox/hq issues 060/061 settled.
|
||||
ENV MESH_TOOL_MODULES=/app/modules/confluence/dist/tools/index.js
|
||||
@@ -3,43 +3,69 @@
|
||||
"version": "1",
|
||||
"slug": "confl",
|
||||
"own-secrets": {
|
||||
"token": "${dir:state}/token"
|
||||
"token": "/var/lib/confluence/token",
|
||||
"broker": "/var/lib/mesh/confluence/broker"
|
||||
},
|
||||
"resources": [
|
||||
{
|
||||
"id": "mesh-state",
|
||||
"type": "directory",
|
||||
"path": "/var/lib/mesh/confluence",
|
||||
"mode": "0700"
|
||||
},
|
||||
{
|
||||
"id": "state",
|
||||
"type": "directory",
|
||||
"mode": "0700",
|
||||
"place": "."
|
||||
"path": "/var/lib/confluence",
|
||||
"mode": "0700"
|
||||
},
|
||||
{
|
||||
"id": "config",
|
||||
"type": "file",
|
||||
"path": "${dir:state}/config.json",
|
||||
"path": "/var/lib/confluence/config.json",
|
||||
"merge": "json",
|
||||
"content": "{}",
|
||||
"mode": "0600"
|
||||
},
|
||||
{
|
||||
"id": "runtime",
|
||||
"type": "container",
|
||||
"name": "mesh-runtime-confluence",
|
||||
"network": "host",
|
||||
"volumes": [
|
||||
"/var/lib/confluence/config.json:/run/config/config.json:ro",
|
||||
"/var/lib/confluence/token:/run/secrets/token:ro",
|
||||
"/var/lib/mesh/confluence/broker:/run/secrets/broker:ro"
|
||||
],
|
||||
"env": {
|
||||
"MESH_CONFLUENCE_TOKEN_FILE": "/run/secrets/token",
|
||||
"MESH_CONFLUENCE_CONFIG_FILE": "/run/config/config.json",
|
||||
"MESH_BROKER_FILE": "/run/secrets/broker"
|
||||
},
|
||||
"artifact": "runtime"
|
||||
}
|
||||
],
|
||||
"capabilities": [
|
||||
"container-runtime"
|
||||
],
|
||||
"build": {
|
||||
"on": [
|
||||
{
|
||||
"arg": "BUILD_BASE",
|
||||
"module": "mesh-tools",
|
||||
"artifact": "build"
|
||||
},
|
||||
{
|
||||
"arg": "RUNTIME_BASE",
|
||||
"module": "mesh-tools",
|
||||
"artifact": "runtime"
|
||||
}
|
||||
],
|
||||
"artifacts": [
|
||||
{
|
||||
"name": "tools",
|
||||
"kind": "bundle",
|
||||
"language": "typescript",
|
||||
"entrypoints": [
|
||||
"tools/index.js"
|
||||
],
|
||||
"loads": [
|
||||
"tools/index.js"
|
||||
],
|
||||
"env": {
|
||||
"MESH_CONFLUENCE_TOKEN_FILE": "${dir:state}/token",
|
||||
"MESH_CONFLUENCE_CONFIG_FILE": "${dir:state}/config.json"
|
||||
}
|
||||
"name": "runtime",
|
||||
"kind": "image",
|
||||
"from": "Dockerfile"
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
@@ -15,11 +15,11 @@
|
||||
}
|
||||
},
|
||||
"binds": {
|
||||
"route": "${dir:state}/route.json"
|
||||
"route": "/var/lib/de-spiegel/route.json"
|
||||
},
|
||||
"own-secrets": {
|
||||
"smtp-user": "${dir:state}/smtp-user.secret",
|
||||
"smtp-pass": "${dir:state}/smtp-pass.secret"
|
||||
"smtp-user": "/var/lib/de-spiegel/smtp-user.secret",
|
||||
"smtp-pass": "/var/lib/de-spiegel/smtp-pass.secret"
|
||||
},
|
||||
"listens": [
|
||||
{
|
||||
@@ -27,20 +27,20 @@
|
||||
"port": 35621,
|
||||
"protocol": "tcp",
|
||||
"from": "mesh",
|
||||
"why": "the de-spiegel site and its /contact endpoint over http; its public name is a route grant, and route-proxy reaches it on this published port"
|
||||
"why": "the de-spiegel site and its /contact endpoint over http; the public name de-spiegel.novox.be is a route grant, and route-proxy reaches it on this published port"
|
||||
}
|
||||
],
|
||||
"resources": [
|
||||
{
|
||||
"id": "state",
|
||||
"type": "directory",
|
||||
"mode": "0700",
|
||||
"place": "."
|
||||
"path": "/var/lib/de-spiegel",
|
||||
"mode": "0700"
|
||||
},
|
||||
{
|
||||
"id": "server-env",
|
||||
"type": "file",
|
||||
"path": "${dir:state}/server.env",
|
||||
"path": "/var/lib/de-spiegel/server.env",
|
||||
"mode": "0600",
|
||||
"content": "SMTP_AUTH_USER=${secret:smtp-user}\nSMTP_AUTH_PASS=${secret:smtp-pass}\n"
|
||||
},
|
||||
@@ -56,15 +56,12 @@
|
||||
"image": "registry-api.novox.be/novox/de-spiegel@sha256:e144b72ce9c145870470d765343549f2c60211728cd118b9ff0e4029f36342ba",
|
||||
"network": "de-spiegel",
|
||||
"env-file": [
|
||||
"${dir:state}/server.env"
|
||||
"/var/lib/de-spiegel/server.env"
|
||||
],
|
||||
"ports": [
|
||||
"35621"
|
||||
],
|
||||
"secrets-in-environment": "the application's own code reads SMTP_AUTH_USER/PASS from the environment (de-spiegel server/index.js); converting is that repository's change",
|
||||
"names-on-purpose": {
|
||||
"registry-api.novox.be": "built outside the mesh, from the application's own repository, and pulled from the registry that built it; moves when that repository is a build source on the git seat (novox/hq ADR 0155, issue 122)"
|
||||
}
|
||||
"secrets-in-environment": "the application's own code reads SMTP_AUTH_USER/PASS from the environment (de-spiegel server/index.js); converting is that repository's change"
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
@@ -3,8 +3,7 @@
|
||||
"version": "1",
|
||||
"capabilities": [
|
||||
"package-manager",
|
||||
"service-manager",
|
||||
"uplink-dhcpcd"
|
||||
"service-manager"
|
||||
],
|
||||
"claims": [
|
||||
{
|
||||
|
||||
@@ -9,7 +9,7 @@
|
||||
],
|
||||
"claims": [
|
||||
{
|
||||
"name": "mesh-artifact-store",
|
||||
"name": "the-artifact-store",
|
||||
"scope": "mesh"
|
||||
}
|
||||
],
|
||||
@@ -59,10 +59,7 @@
|
||||
],
|
||||
"volumes": [
|
||||
"/var/lib/mesh-registry:/var/lib/registry"
|
||||
],
|
||||
"env": {
|
||||
"REGISTRY_STORAGE_DELETE_ENABLED": "true"
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
File diff suppressed because one or more lines are too long
+36
-221
@@ -1,236 +1,51 @@
|
||||
// fail2ban's own code, in the module (novox/hq ADR 0039). The jails are composed by the mesh from
|
||||
// the modules a machine runs (to-be 31) and written as declared resources; the daemon is kept
|
||||
// running by one. This code exists only to read and steer the *live* state the daemon owns: who is
|
||||
// banned now and until when, and the ban or release an operator asks for — the node-intrusion-
|
||||
// prevention seat's four verbs (ADR 0179). The daemon's state is fail2ban's, not the mesh's: the
|
||||
// mesh composes the jails and never writes the ban list.
|
||||
//
|
||||
// Spoken through fail2ban-client over the daemon's socket. Client and daemon come from the one
|
||||
// package this module declares on the machine, and the socket is root's: root is the module's
|
||||
// concern (ADR 0175 §4), and the runtime loading this bundle runs as the operator's account (to-be
|
||||
// 38 WP4), so the client is run through sudo without a prompt where the account is not root.
|
||||
// fail2ban's own code, in the module (novox/hq ADR 0039). The jails and the daemon are declared
|
||||
// resources — the mesh writes /etc/fail2ban/jail.d/* and keeps fail2ban.service running (see
|
||||
// module.json). This code exists only to read and steer the *live* state the daemon owns at
|
||||
// runtime: which IPs are banned right now, and the manual ban/unban an operator reaches for. That
|
||||
// state (the running bans, /var/lib/fail2ban's sqlite) is fail2ban's, not the mesh's — the mesh
|
||||
// reconciles the config, never the ban list.
|
||||
|
||||
import { execFile } from "node:child_process";
|
||||
import { accessSync, constants } from "node:fs";
|
||||
import { isIP } from "node:net";
|
||||
import { delimiter, join } from "node:path";
|
||||
import { promisify } from "node:util";
|
||||
|
||||
const execFileP = promisify(execFile);
|
||||
|
||||
/** A command runner, so the verbs can be tested without a daemon. */
|
||||
export type Runner = (cmd: string, args: string[]) => Promise<string>;
|
||||
|
||||
/** The command as it is run: as given when this process is root, else through sudo without a
|
||||
* prompt. The daemon's socket answers only to root. */
|
||||
export function escalated(cmd: string, args: string[], uid: number | undefined = process.getuid?.()): [string, string[]] {
|
||||
if (uid === 0) return [cmd, args];
|
||||
return ["sudo", ["-n", cmd, ...args]];
|
||||
}
|
||||
|
||||
/** Whether a tool is on this machine: an executable of that name on the path, or where the
|
||||
* system keeps its administration. */
|
||||
export function installed(tool: string, path: string = process.env.PATH ?? ""): boolean {
|
||||
const dirs = [...path.split(delimiter), "/usr/sbin", "/sbin", "/usr/bin"].filter((d) => d !== "");
|
||||
return dirs.some((dir) => {
|
||||
try {
|
||||
accessSync(join(dir, tool), constants.X_OK);
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
export const execRunner: Runner = async (cmd, args) => {
|
||||
if (!installed(cmd)) throw new Error(`${cmd} is not installed on this machine`);
|
||||
const [program, argv] = escalated(cmd, args);
|
||||
try {
|
||||
const { stdout } = await execFileP(program, argv, { maxBuffer: 16 * 1024 * 1024 });
|
||||
return stdout;
|
||||
} catch (err) {
|
||||
const e = err as { code?: string | number; stderr?: string; stdout?: string; message?: string };
|
||||
const said = `${e.stdout ?? ""}${e.stderr ?? ""}`.trim();
|
||||
// What failed is named by how it failed: sudo missing is a spawn error, sudo refusing speaks
|
||||
// on its own stderr line, and the rest is the client's own answer.
|
||||
if (program === "sudo") {
|
||||
if (e.code === "ENOENT") throw new Error(`${cmd} needs root, and sudo is not installed here for the runtime's account to escalate with`);
|
||||
if (/^sudo:/m.test(said)) throw new Error(`${cmd} needs root and the runtime's account may not run it without a prompt: ${said}`);
|
||||
}
|
||||
if (/Failed to access socket path|Is fail2ban running|Permission denied to socket/i.test(said)) {
|
||||
throw new Error("fail2ban is not running on this machine, or its socket does not answer the runtime's account");
|
||||
}
|
||||
// fail2ban-client's own last line is the one a person reads ("Sorry but the jail 'x' does not exist").
|
||||
const lines = said.split("\n").map((l) => l.trim()).filter(Boolean);
|
||||
throw new Error(lines.length ? lines[lines.length - 1] : (e.message ?? `${cmd} failed`));
|
||||
}
|
||||
};
|
||||
|
||||
/** One jail as the daemon reports it. */
|
||||
export interface JailStatus {
|
||||
jail: string;
|
||||
/** What the jail is reading: files or journal matches, as fail2ban names them. */
|
||||
watching: string[];
|
||||
/** Addresses with failures counted against them right now, and all failures since the jail started. */
|
||||
failing: { now: number; total: number };
|
||||
/** Addresses held right now, and all bans since the jail started. */
|
||||
banned: { now: number; total: number; addresses: string[] };
|
||||
}
|
||||
|
||||
/** One ban as the daemon holds it. */
|
||||
export interface Ban {
|
||||
ip: string;
|
||||
jail: string;
|
||||
/** When the ban was placed, in the machine's local time as fail2ban prints it. */
|
||||
since: string;
|
||||
/** When the ban ends; "never" for a permanent ban. */
|
||||
until: string;
|
||||
}
|
||||
|
||||
export interface JailSettings {
|
||||
jail: string;
|
||||
bantime: string;
|
||||
findtime: string;
|
||||
maxretry: number;
|
||||
ignoreip: string[];
|
||||
actions: string[];
|
||||
/** The log files the jail reads, when it reads files. */
|
||||
logpath: string[];
|
||||
/** The journal match the jail reads, when it reads the journal. */
|
||||
journalmatch: string;
|
||||
}
|
||||
const run = promisify(execFile);
|
||||
|
||||
export class Fail2banClient {
|
||||
private readonly run: Runner;
|
||||
|
||||
constructor(run: Runner = execRunner) {
|
||||
this.run = run;
|
||||
}
|
||||
|
||||
/** The daemon as this machine has it, through its own client. */
|
||||
static onThisMachine(): Fail2banClient {
|
||||
static fromEnv(_env: NodeJS.ProcessEnv = process.env): Fail2banClient {
|
||||
return new Fail2banClient();
|
||||
}
|
||||
|
||||
private client(...args: string[]): Promise<string> {
|
||||
return this.run("fail2ban-client", args);
|
||||
}
|
||||
|
||||
/** The jails the daemon runs, by name. */
|
||||
async jails(): Promise<string[]> {
|
||||
const out = await this.client("status");
|
||||
const m = out.match(/Jail list:\s*(.*)/);
|
||||
if (!m) return [];
|
||||
return m[1].split(",").map((j) => j.trim()).filter(Boolean);
|
||||
}
|
||||
|
||||
/** Every jail with what it watches and holds, or one jail's detail. */
|
||||
async status(jail?: string): Promise<{ jails: JailStatus[] }> {
|
||||
const names = jail ? [jail] : await this.jails();
|
||||
const jails: JailStatus[] = [];
|
||||
for (const name of names) {
|
||||
jails.push(parseJailStatus(name, await this.client("status", name)));
|
||||
}
|
||||
return { jails };
|
||||
}
|
||||
|
||||
/** Every address banned now, with the jail holding it and when the ban ends. */
|
||||
async banned(jail?: string): Promise<{ banned: Ban[] }> {
|
||||
const names = jail ? [jail] : await this.jails();
|
||||
const banned: Ban[] = [];
|
||||
for (const name of names) {
|
||||
banned.push(...parseBans(name, await this.client("get", name, "banip", "--with-time")));
|
||||
}
|
||||
banned.sort((a, b) => a.until.localeCompare(b.until) || a.ip.localeCompare(b.ip));
|
||||
return { banned };
|
||||
}
|
||||
|
||||
/** Ban one address in one jail now. The daemon's own answer is how many addresses it added. */
|
||||
async ban(ip: string, jail: string): Promise<{ banned: Ban | null; added: number }> {
|
||||
address(ip);
|
||||
name(jail);
|
||||
const out = await this.client("set", jail, "banip", ip);
|
||||
const added = Number.parseInt(out.trim(), 10) || 0;
|
||||
const held = (await this.banned(jail)).banned.find((b) => b.ip === ip) ?? null;
|
||||
return { banned: held, added };
|
||||
}
|
||||
|
||||
/** Let one address go, from one jail or from every jail. The daemon's answer is how many it released. */
|
||||
async unban(ip: string, jail?: string): Promise<{ released: number; ip: string; jail: string | "every jail" }> {
|
||||
address(ip);
|
||||
let out: string;
|
||||
/** Overview of every jail, or the detailed status of one — currently-banned IPs and totals. */
|
||||
async status(jail?: string): Promise<string> {
|
||||
if (jail) {
|
||||
name(jail);
|
||||
out = await this.client("set", jail, "unbanip", ip);
|
||||
} else {
|
||||
out = await this.client("unban", ip);
|
||||
const { stdout } = await run("sudo", ["fail2ban-client", "status", jail]);
|
||||
return stdout;
|
||||
}
|
||||
return { released: Number.parseInt(out.trim(), 10) || 0, ip, jail: jail ?? "every jail" };
|
||||
const { stdout: overview } = await run("sudo", ["fail2ban-client", "status"]);
|
||||
const match = overview.match(/Jail list:\s*(.+)/);
|
||||
if (!match) return overview;
|
||||
|
||||
const jails = match[1].split(",").map((j) => j.trim()).filter(Boolean);
|
||||
const parts: string[] = [overview.trimEnd(), ""];
|
||||
for (const j of jails) {
|
||||
const { stdout } = await run("sudo", ["fail2ban-client", "status", j]);
|
||||
parts.push(`=== ${j} ===`, stdout.trimEnd(), "");
|
||||
}
|
||||
return parts.join("\n");
|
||||
}
|
||||
|
||||
/** One jail's effective settings — the module's own tool, beside the seat's verbs. */
|
||||
async settings(jail: string): Promise<JailSettings> {
|
||||
name(jail);
|
||||
const get = (key: string) => this.client("get", jail, key);
|
||||
const [bantime, findtime, maxretry, ignoreip, actions, logpath, journalmatch] = await Promise.all([
|
||||
get("bantime"), get("findtime"), get("maxretry"), get("ignoreip"), get("actions"), get("logpath"),
|
||||
get("journalmatch"),
|
||||
]);
|
||||
return {
|
||||
jail,
|
||||
bantime: bantime.trim(),
|
||||
findtime: findtime.trim(),
|
||||
maxretry: Number.parseInt(maxretry.trim(), 10),
|
||||
ignoreip: listed(ignoreip),
|
||||
actions: actions.split("\n").slice(1).map((l) => l.trim()).filter(Boolean),
|
||||
logpath: /No file is currently monitored/.test(logpath) ? [] : listed(logpath),
|
||||
journalmatch: journalmatch.split("\n").slice(1).map((l) => l.trim()).filter(Boolean).join(" "),
|
||||
};
|
||||
/** Manually ban an IP in a jail. Mutates live state, not a mesh-managed file. */
|
||||
async ban(jail: string, ip: string): Promise<string> {
|
||||
const { stdout } = await run("sudo", ["fail2ban-client", "set", jail, "banip", ip]);
|
||||
return stdout;
|
||||
}
|
||||
|
||||
/** Unban an IP from one jail, or from every jail when no jail is given. */
|
||||
async unban(ip: string, jail?: string): Promise<string> {
|
||||
const args = jail
|
||||
? ["fail2ban-client", "set", jail, "unbanip", ip]
|
||||
: ["fail2ban-client", "unban", ip];
|
||||
const { stdout } = await run("sudo", args);
|
||||
return stdout;
|
||||
}
|
||||
}
|
||||
|
||||
/** fail2ban's tree listings: lines like "|- 127.0.0.0/8" and "`- ::1", after a heading. */
|
||||
function listed(out: string): string[] {
|
||||
return out
|
||||
.split("\n")
|
||||
.map((l) => l.replace(/^[\s|`-]+/, "").trim())
|
||||
.filter((l, i) => i > 0 && l.length > 0);
|
||||
}
|
||||
|
||||
export function parseJailStatus(jail: string, out: string): JailStatus {
|
||||
const field = (label: string) => {
|
||||
const m = out.match(new RegExp(label.replace(/[.*+?^${}()|[\]\\]/g, "\\$&") + ":\\t?\\s*(.*)"));
|
||||
return m ? m[1].trim() : "";
|
||||
};
|
||||
const num = (label: string) => Number.parseInt(field(label), 10) || 0;
|
||||
const watching = [field("File list"), field("Journal matches")].filter(Boolean);
|
||||
return {
|
||||
jail,
|
||||
watching,
|
||||
failing: { now: num("Currently failed"), total: num("Total failed") },
|
||||
banned: {
|
||||
now: num("Currently banned"),
|
||||
total: num("Total banned"),
|
||||
addresses: field("Banned IP list").split(/\s+/).filter(Boolean),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/** `get <jail> banip --with-time` prints one ban per line: "IP \tsince + seconds = until". */
|
||||
export function parseBans(jail: string, out: string): Ban[] {
|
||||
const bans: Ban[] = [];
|
||||
for (const line of out.split("\n")) {
|
||||
const m = line.match(/^(\S+)\s+(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}) \+ (-?\d+) = (\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}|\S+)/);
|
||||
if (!m) continue;
|
||||
bans.push({ ip: m[1], jail, since: m[2], until: Number(m[3]) < 0 ? "never" : m[4] });
|
||||
}
|
||||
return bans;
|
||||
}
|
||||
|
||||
function address(ip: string): void {
|
||||
if (!isIP(ip)) throw new Error(`${JSON.stringify(ip)} is not an address`);
|
||||
}
|
||||
|
||||
function name(jail: string): void {
|
||||
if (!/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(jail)) throw new Error(`${JSON.stringify(jail)} is not a jail's name`);
|
||||
}
|
||||
|
||||
@@ -7,22 +7,9 @@
|
||||
"claims": [
|
||||
{
|
||||
"name": "node-intrusion-prevention",
|
||||
"scope": "node",
|
||||
"serves": [
|
||||
"status",
|
||||
"banned",
|
||||
"ban",
|
||||
"unban"
|
||||
]
|
||||
"scope": "node"
|
||||
}
|
||||
],
|
||||
"tools": [
|
||||
"fail2ban_settings"
|
||||
],
|
||||
"jailing": {
|
||||
"into": "/etc/fail2ban/jail.d/mesh.conf",
|
||||
"filter-into": "/etc/fail2ban/filter.d"
|
||||
},
|
||||
"resources": [
|
||||
{
|
||||
"id": "package",
|
||||
@@ -41,31 +28,19 @@
|
||||
"path": "/etc/fail2ban/action.d",
|
||||
"mode": "0755"
|
||||
},
|
||||
{
|
||||
"id": "filter-d",
|
||||
"type": "directory",
|
||||
"path": "/etc/fail2ban/filter.d",
|
||||
"mode": "0755"
|
||||
},
|
||||
{
|
||||
"id": "run-dir",
|
||||
"type": "directory",
|
||||
"path": "/var/run/fail2ban",
|
||||
"mode": "0755"
|
||||
},
|
||||
{
|
||||
"id": "jail-local",
|
||||
"type": "file",
|
||||
"path": "/etc/fail2ban/jail.local",
|
||||
"mode": "0644",
|
||||
"content": "[INCLUDES]\n\nbefore = paths-arch.conf\n\n[DEFAULT]\n\n# Never act on the machine itself or on a tunnel peer: the mesh's private range is\n# ${machine:mesh-range}, named here rather than written as a value the module cannot\n# know (novox/hq ADR 0112). Without this, fail2ban could ban the mesh's own nodes.\n# **A ban list never holds a neighbour.** The mesh's own range is named rather than written\n# (novox/hq ADR 0112), and every private range beside it: a source on one is somebody's own\n# network, not the internet. On a machine behind a router that reflects local traffic, every\n# client in the house arrives as the gateway's address — so one mistyped local request banned\n# 192.168.1.1 on the home server and would have cut the whole house off from it (ADR 0186).\nignoreip = 127.0.0.1/8 ::1 ${machine:mesh-range} 10.0.0.0/8 172.16.0.0/12 192.168.0.0/16 169.254.0.0/16 fc00::/7 fe80::/10\n\n# Three failures in a day ban for a day (novox/hq ADR 0179). The attackers this mesh sees pace\n# themselves at one try every ten minutes, under any ten-minute window; a day's window counts\n# them, and a day's ban costs a person who mistyped three times once, from one address, while\n# the mesh's own range is never banned at all.\nbantime = 1d\nfindtime = 1d\nmaxretry = 3\n\n# Ban through iptables, not through a firewall front-end the machine may not have. ufw is\n# installed on two of this mesh's machines and absent on the other two, and fail2ban finds out\n# only at ban time: the service reports healthy, the jail counts the attempt, the ban command\n# exits 127, and nothing is blocked. Proven on 2026-09-28 -- 'ufw: command not found' on a\n# machine the mesh reported as protected.\n#\n# The action below is this module's own, already used by the recidive jail on every machine\n# here, and it bans in DOCKER-USER as well as INPUT, so a container's published port is\n# covered too.\nbanaction = iptables-allports-dualchain\nbanaction_allports = iptables-allports-dualchain\n\n[sshd]\nenabled = true\nport = ssh\nlogpath = %(sshd_log)s\nbackend = %(sshd_backend)s\n"
|
||||
"content": "[INCLUDES]\n\nbefore = paths-arch.conf\n\n[DEFAULT]\n\n# Never act on the machine itself or on a tunnel peer: the mesh's private range is\n# ${machine:mesh-range}, named here rather than written as a value the module cannot\n# know (novox/hq ADR 0112). Without this, fail2ban could ban the mesh's own nodes.\nignoreip = 127.0.0.1/8 ::1 ${machine:mesh-range}\n\nbantime = 10m\nfindtime = 10m\nmaxretry = 5\n\n# Ban through iptables, not through a firewall front-end the machine may not have. ufw is\n# installed on two of this mesh's machines and absent on the other two, and fail2ban finds out\n# only at ban time: the service reports healthy, the jail counts the attempt, the ban command\n# exits 127, and nothing is blocked. Proven on 2026-09-28 -- 'ufw: command not found' on a\n# machine the mesh reported as protected.\n#\n# The action below is this module's own, already used by the recidive jail on every machine\n# here, and it bans in DOCKER-USER as well as INPUT, so a container's published port is\n# covered too.\nbanaction = iptables-allports-dualchain\nbanaction_allports = iptables-allports-dualchain\n\n[sshd]\nenabled = true\nport = ssh\nlogpath = %(sshd_log)s\nbackend = %(sshd_backend)s\n"
|
||||
},
|
||||
{
|
||||
"id": "jail-sshd",
|
||||
"type": "file",
|
||||
"path": "/etc/fail2ban/jail.d/sshd.conf",
|
||||
"mode": "0644",
|
||||
"content": "[sshd]\nenabled = true\nport = ssh\nlogpath = %(sshd_log)s\nbackend = %(sshd_backend)s\nmaxretry = 3\nfindtime = 1d\nbantime = 1d\n"
|
||||
"content": "[sshd]\nenabled = true\nport = ssh\nlogpath = %(sshd_log)s\nbackend = %(sshd_backend)s\nmaxretry = 5\n"
|
||||
},
|
||||
{
|
||||
"id": "log",
|
||||
@@ -80,7 +55,7 @@
|
||||
"type": "file",
|
||||
"path": "/etc/fail2ban/jail.d/recidive.conf",
|
||||
"mode": "0644",
|
||||
"content": "[recidive]\nenabled = true\nlogpath = /var/log/fail2ban.log\n# Ban in both INPUT (host services like SSH) and DOCKER-USER (container services)\nbanaction = iptables-allports-dualchain\n# Banned twice in two weeks, by any jail, is banned for four (novox/hq ADR 0179).\nbantime = 4w\nfindtime = 2w\nmaxretry = 2\n"
|
||||
"content": "[recidive]\nenabled = true\nlogpath = /var/log/fail2ban.log\n# Ban in both INPUT (host services like SSH) and DOCKER-USER (container services)\nbanaction = iptables-allports-dualchain\nbantime = 1w\nfindtime = 1d\n"
|
||||
},
|
||||
{
|
||||
"id": "action-dualchain",
|
||||
@@ -106,21 +81,8 @@
|
||||
"jail-local",
|
||||
"jail-sshd",
|
||||
"jail-recidive",
|
||||
"action-dualchain",
|
||||
"composed-jails"
|
||||
"action-dualchain"
|
||||
]
|
||||
}
|
||||
],
|
||||
"build": {
|
||||
"artifacts": [
|
||||
{
|
||||
"name": "tools",
|
||||
"kind": "bundle",
|
||||
"language": "typescript",
|
||||
"entrypoints": [
|
||||
"tools/index.js"
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
@@ -1,18 +1,14 @@
|
||||
{
|
||||
"name": "@novox/module-fail2ban",
|
||||
"version": "0.1.0",
|
||||
"description": "fail2ban \u2014 intrusion prevention: the mesh composes the jails and keeps the daemon running; this module holds the node-intrusion-prevention seat and serves its verbs status, banned, ban and unban (novox/hq to-be 31, ADR 0179).",
|
||||
"description": "fail2ban — intrusion prevention: the mesh declares the jails and keeps the daemon running; its ban/unban/status tools live here.",
|
||||
"type": "module",
|
||||
"private": true,
|
||||
"dependencies": {
|
||||
"@novox/mesh-sdk": "^0.1.1"
|
||||
"@novox/mesh-sdk": "^0.1.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^22.0.0",
|
||||
"typescript": "^5.6.0"
|
||||
},
|
||||
"scripts": {
|
||||
"build": "tsc client.ts tools/index.ts --module NodeNext --moduleResolution NodeNext --target ES2022 --rootDir . --outDir dist",
|
||||
"test": "node --test --experimental-strip-types 'test/*.test.ts'"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,114 +0,0 @@
|
||||
// The intrusion prevention's verbs over a fake daemon, with the shapes fail2ban-client 1.1.0 printed
|
||||
// on the control node on 2026-10-02 (novox/hq ADR 0179).
|
||||
import { test } from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { Fail2banClient, escalated, installed, parseBans, parseJailStatus, type Runner } from "../client.ts";
|
||||
|
||||
const STATUS = "Status\n|- Number of jail:\t2\n`- Jail list:\trecidive, sshd\n";
|
||||
const RECIDIVE =
|
||||
"Status for the jail: recidive\n|- Filter\n| |- Currently failed:\t36\n| |- Total failed:\t149\n" +
|
||||
"| `- File list:\t/var/log/fail2ban.log\n`- Actions\n |- Currently banned:\t9\n |- Total banned:\t13\n" +
|
||||
" `- Banned IP list:\t195.178.110.30 45.148.10.240 92.118.39.71\n";
|
||||
const SSHD =
|
||||
"Status for the jail: sshd\n|- Filter\n| |- Currently failed:\t5\n| |- Total failed:\t11776\n" +
|
||||
"| `- Journal matches:\t_SYSTEMD_UNIT=sshd.service + _COMM=sshd\n`- Actions\n |- Currently banned:\t0\n" +
|
||||
" |- Total banned:\t150\n `- Banned IP list:\t\n";
|
||||
const WITH_TIME =
|
||||
"195.178.110.30 \t2026-09-26 23:18:47 + 604800 = 2026-10-03 23:18:47\n" +
|
||||
"92.118.39.71 \t2026-09-28 10:33:49 + 604800 = 2026-10-05 10:33:49\n";
|
||||
|
||||
function fake(answers: Record<string, string>, calls: string[][] = []): Runner {
|
||||
return async (cmd, args) => {
|
||||
calls.push([cmd, ...args]);
|
||||
const key = args.join(" ");
|
||||
if (key in answers) return answers[key];
|
||||
throw new Error(`unexpected ${cmd} ${key}`);
|
||||
};
|
||||
}
|
||||
|
||||
test("a jail's status is read into numbers, what it watches and who it holds", () => {
|
||||
const s = parseJailStatus("recidive", RECIDIVE);
|
||||
assert.deepEqual(s, {
|
||||
jail: "recidive",
|
||||
watching: ["/var/log/fail2ban.log"],
|
||||
failing: { now: 36, total: 149 },
|
||||
banned: { now: 9, total: 13, addresses: ["195.178.110.30", "45.148.10.240", "92.118.39.71"] },
|
||||
});
|
||||
const j = parseJailStatus("sshd", SSHD);
|
||||
assert.deepEqual(j.watching, ["_SYSTEMD_UNIT=sshd.service + _COMM=sshd"]);
|
||||
assert.deepEqual(j.banned, { now: 0, total: 150, addresses: [] });
|
||||
});
|
||||
|
||||
test("status covers every jail the daemon lists, or the one named", async () => {
|
||||
const calls: string[][] = [];
|
||||
const f = new Fail2banClient(fake({ status: STATUS, "status recidive": RECIDIVE, "status sshd": SSHD }, calls));
|
||||
const all = await f.status();
|
||||
assert.deepEqual(all.jails.map((j) => j.jail), ["recidive", "sshd"]);
|
||||
const one = await f.status("sshd");
|
||||
assert.equal(one.jails.length, 1);
|
||||
assert.deepEqual(calls[calls.length - 1], ["fail2ban-client", "status", "sshd"]);
|
||||
});
|
||||
|
||||
test("bans are read with when they were placed and when they end, a permanent one as never", () => {
|
||||
const bans = parseBans("recidive", WITH_TIME + "203.0.113.9 \t2026-10-01 00:00:00 + -1 = never\n");
|
||||
assert.equal(bans.length, 3);
|
||||
assert.deepEqual(bans[0], { ip: "195.178.110.30", jail: "recidive", since: "2026-09-26 23:18:47", until: "2026-10-03 23:18:47" });
|
||||
assert.equal(bans[2].until, "never");
|
||||
assert.deepEqual(parseBans("sshd", "\n"), []);
|
||||
});
|
||||
|
||||
test("banned gathers every jail's bans, soonest to end first", async () => {
|
||||
const f = new Fail2banClient(fake({
|
||||
status: STATUS,
|
||||
"get recidive banip --with-time": WITH_TIME,
|
||||
"get sshd banip --with-time": "198.51.100.7 \t2026-10-02 15:06:58 + 600 = 2026-10-02 15:16:58\n",
|
||||
}));
|
||||
const { banned } = await f.banned();
|
||||
assert.deepEqual(banned.map((b) => `${b.ip}@${b.jail}`), ["198.51.100.7@sshd", "195.178.110.30@recidive", "92.118.39.71@recidive"]);
|
||||
});
|
||||
|
||||
test("ban asks the daemon by jail and answers with the ban as held; a non-address is refused before anything runs", async () => {
|
||||
const calls: string[][] = [];
|
||||
const f = new Fail2banClient(fake({
|
||||
"set recidive banip 198.51.100.7": "1\n",
|
||||
"get recidive banip --with-time": WITH_TIME + "198.51.100.7 \t2026-10-02 17:00:00 + 604800 = 2026-10-09 17:00:00\n",
|
||||
}, calls));
|
||||
const r = await f.ban("198.51.100.7", "recidive");
|
||||
assert.equal(r.added, 1);
|
||||
assert.equal(r.banned?.until, "2026-10-09 17:00:00");
|
||||
assert.deepEqual(calls[0], ["fail2ban-client", "set", "recidive", "banip", "198.51.100.7"]);
|
||||
await assert.rejects(() => f.ban("not-an-ip", "recidive"), /is not an address/);
|
||||
await assert.rejects(() => f.ban("198.51.100.7", "a jail; rm"), /is not a jail's name/);
|
||||
assert.equal(calls.length, 2);
|
||||
});
|
||||
|
||||
test("unban releases from one jail or from every jail", async () => {
|
||||
const calls: string[][] = [];
|
||||
const f = new Fail2banClient(fake({ "set sshd unbanip 198.51.100.7": "1\n", "unban 198.51.100.7": "2\n" }, calls));
|
||||
assert.deepEqual(await f.unban("198.51.100.7", "sshd"), { released: 1, ip: "198.51.100.7", jail: "sshd" });
|
||||
assert.deepEqual(await f.unban("198.51.100.7"), { released: 2, ip: "198.51.100.7", jail: "every jail" });
|
||||
assert.deepEqual(calls[1], ["fail2ban-client", "unban", "198.51.100.7"]);
|
||||
});
|
||||
|
||||
test("a jail's settings are read from the daemon's listings", async () => {
|
||||
const f = new Fail2banClient(fake({
|
||||
"get sshd bantime": "86400\n", "get sshd findtime": "86400\n", "get sshd maxretry": "3\n",
|
||||
"get sshd ignoreip": "These IP addresses/networks are ignored:\n|- 127.0.0.0/8\n|- 10.10.0.0/24\n`- ::1\n",
|
||||
"get sshd actions": "The jail sshd has the following actions:\niptables-allports-dualchain\n",
|
||||
"get sshd logpath": "No file is currently monitored\n",
|
||||
"get sshd journalmatch": "Current match filter:\n_SYSTEMD_UNIT=sshd.service + _COMM=sshd\n",
|
||||
}));
|
||||
assert.deepEqual(await f.settings("sshd"), {
|
||||
jail: "sshd", bantime: "86400", findtime: "86400", maxretry: 3,
|
||||
ignoreip: ["127.0.0.0/8", "10.10.0.0/24", "::1"], actions: ["iptables-allports-dualchain"],
|
||||
logpath: [], journalmatch: "_SYSTEMD_UNIT=sshd.service + _COMM=sshd",
|
||||
});
|
||||
});
|
||||
|
||||
test("the client runs as given by root and through sudo without a prompt by anyone else", () => {
|
||||
assert.deepEqual(escalated("fail2ban-client", ["status"], 0), ["fail2ban-client", ["status"]]);
|
||||
assert.deepEqual(escalated("fail2ban-client", ["set", "sshd", "banip", "198.51.100.7"], 1000),
|
||||
["sudo", ["-n", "fail2ban-client", "set", "sshd", "banip", "198.51.100.7"]]);
|
||||
assert.equal(installed("sh"), true);
|
||||
assert.equal(installed("no-such-client-of-the-mesh"), false);
|
||||
});
|
||||
@@ -1,62 +1,55 @@
|
||||
// The intrusion prevention's tools: the node-intrusion-prevention seat's four verbs — who is banned,
|
||||
// the jails' state, ban one, let one go — and the module's own reading of a jail's settings
|
||||
// (novox/hq to-be 31, ADR 0179). The jails themselves are composed by the mesh from the modules a
|
||||
// machine runs and written as declared resources; these touch only what the running daemon holds.
|
||||
// fail2ban's tools — reading and steering the live ban state. The jails themselves are declared
|
||||
// resources (module.json); these three touch what the running daemon holds: what is banned now,
|
||||
// and the manual ban/unban an operator reaches for. The daemon's state is fail2ban's own, so this
|
||||
// is the only way to see or change it — the mesh reconciles the config, not the bans.
|
||||
|
||||
import { registerModuleTools, type ToolDefinition } from "@novox/mesh-sdk/tools";
|
||||
import { Fail2banClient } from "../client.js";
|
||||
|
||||
export function getSeatVerbs(fail2ban: Fail2banClient): ToolDefinition[] {
|
||||
return [
|
||||
{
|
||||
name: "status",
|
||||
description:
|
||||
"Every jail on this machine with what it watches, how many addresses it is counting failures against and holding now, and the totals since it started; one jail's detail when named.",
|
||||
input: { jail: { type: "string", description: "one jail (optional)" } },
|
||||
run: async (args) => fail2ban.status(args.jail ? String(args.jail) : undefined),
|
||||
},
|
||||
{
|
||||
name: "banned",
|
||||
description: "Every address banned on this machine right now, with the jail that holds it, when it was banned and when the ban ends.",
|
||||
input: { jail: { type: "string", description: "one jail (optional)" } },
|
||||
run: async (args) => fail2ban.banned(args.jail ? String(args.jail) : undefined),
|
||||
},
|
||||
{
|
||||
name: "ban",
|
||||
description:
|
||||
"Ban one address in one jail now, for the jail's ban time — an operator's act on the live ban list, which the mesh never writes itself.",
|
||||
input: {
|
||||
ip: { type: "string", description: "the address" },
|
||||
jail: { type: "string", description: "the jail to hold it (recidive for the long ban)" },
|
||||
},
|
||||
run: async (args) => fail2ban.ban(String(args.ip ?? ""), String(args.jail ?? "")),
|
||||
},
|
||||
{
|
||||
name: "unban",
|
||||
description: "Let one address go, from one jail or from every jail when none is named.",
|
||||
input: {
|
||||
ip: { type: "string", description: "the address" },
|
||||
jail: { type: "string", description: "one jail (optional)" },
|
||||
},
|
||||
run: async (args) => fail2ban.unban(String(args.ip ?? ""), args.jail ? String(args.jail) : undefined),
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
export function getFail2banTools(fail2ban: Fail2banClient): ToolDefinition[] {
|
||||
return [
|
||||
{
|
||||
name: "fail2ban_settings",
|
||||
name: "fail2ban_status",
|
||||
description:
|
||||
"One jail's effective settings on this machine: ban time, window, tries, the addresses it never bans, its actions and what it reads.",
|
||||
input: { jail: { type: "string", description: "the jail" } },
|
||||
run: async (args) => fail2ban.settings(String(args.jail ?? "")),
|
||||
"fail2ban status on this node — the jails and their live bans. Omit `jail` for every jail, or name one for its detail.",
|
||||
input: {
|
||||
type: "object",
|
||||
properties: {
|
||||
jail: {
|
||||
type: "string",
|
||||
description: "A specific jail (e.g. sshd, recidive); omit for the overview of all jails.",
|
||||
},
|
||||
},
|
||||
},
|
||||
run: async (args) => ({ status: await fail2ban.status(args.jail as string | undefined) }),
|
||||
},
|
||||
{
|
||||
name: "fail2ban_ban",
|
||||
description: "Manually ban an IP address in a jail — a live change to the running daemon, not a mesh-managed file.",
|
||||
input: {
|
||||
type: "object",
|
||||
properties: {
|
||||
jail: { type: "string", description: "Jail name (e.g. sshd, recidive)." },
|
||||
ip: { type: "string", description: "IP address to ban." },
|
||||
},
|
||||
required: ["jail", "ip"],
|
||||
},
|
||||
run: async (args) => ({ result: await fail2ban.ban(args.jail as string, args.ip as string) }),
|
||||
},
|
||||
{
|
||||
name: "fail2ban_unban",
|
||||
description: "Unban an IP address from one jail, or from every jail when `jail` is omitted.",
|
||||
input: {
|
||||
type: "object",
|
||||
properties: {
|
||||
ip: { type: "string", description: "IP address to unban." },
|
||||
jail: { type: "string", description: "A specific jail; omit to unban from all jails." },
|
||||
},
|
||||
required: ["ip"],
|
||||
},
|
||||
run: async (args) => ({ result: await fail2ban.unban(args.ip as string, args.jail as string | undefined) }),
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
const fail2ban = Fail2banClient.onThisMachine();
|
||||
// The seat's verbs under the seat's name: the runtime serves them on the seat's subjects where this
|
||||
// module holds it (ADR 0159, 0160). The module's own under its own.
|
||||
registerModuleTools("node-intrusion-prevention", () => getSeatVerbs(fail2ban));
|
||||
registerModuleTools("fail2ban", () => getFail2banTools(fail2ban));
|
||||
registerModuleTools("fail2ban", () => getFail2banTools(Fail2banClient.fromEnv()));
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
# gitea's runtime: the tool runtime, carrying this module's compiled provisioner, tools and event
|
||||
# consumer.
|
||||
#
|
||||
# **Built from this module's own directory and nothing else.** The sdk is in the base image, so
|
||||
# nothing is copied out of a neighbouring checkout — which is what lets the mesh build this from a
|
||||
# repository and a path (novox/hq ADR 0069) rather than only on a workstation that happens to have
|
||||
# the siblings.
|
||||
#
|
||||
# Two bases, named rather than pinned: the image this is COMPILED in, and the image it RUNS in.
|
||||
# They are different images on purpose — the first carries a compiler and the second must not, or
|
||||
# every running container would carry one it never invokes. The mesh answers both with the copies it
|
||||
# holds, because a fingerprint written here would name one particular copy and no other mesh has it
|
||||
# (novox/hq issue 044). Declared in module.json's `build.on`; deliberately no defaults, so a build
|
||||
# nobody told stops here and says which module to build first.
|
||||
ARG BUILD_BASE
|
||||
ARG RUNTIME_BASE
|
||||
|
||||
FROM ${BUILD_BASE} AS build
|
||||
# Compiled under /app/modules so `@novox/mesh-sdk` resolves upward into the base's own
|
||||
# node_modules — the module is compiled against exactly the sdk it will run against.
|
||||
WORKDIR /app/modules/gitea
|
||||
COPY . .
|
||||
# The compiler is invoked by its real path rather than through node_modules/.bin, whose entries are
|
||||
# symlinks to a launcher that requires its library relatively — resolved away when the base image
|
||||
# was assembled.
|
||||
RUN node /app/node_modules/typescript/bin/tsc client.ts token.ts index.ts provisioner/index.ts tools/index.ts \
|
||||
--module NodeNext --moduleResolution NodeNext --target ES2022 --outDir dist
|
||||
|
||||
FROM ${RUNTIME_BASE}
|
||||
# **No apt packages.** gitea's provisioner talks to the forge over HTTP (the gitea REST API), not
|
||||
# through a CLI the way postgres drives psql — so the runtime base holds everything this needs.
|
||||
COPY --from=build /app/modules/gitea/dist /app/modules/gitea/dist
|
||||
# What a tool host should load from this module: its event consumer and its tools, which are
|
||||
# separate entrypoints because they are loaded by different things. The provisioner is the third,
|
||||
# and is not listed here — the declaration names it in the container's `args`, because it is what
|
||||
# this module's own container runs. One image, because they are one module and share a client.
|
||||
ENV MESH_TOOL_MODULES=/app/modules/gitea/dist/index.js,/app/modules/gitea/dist/tools/index.js,/app/modules/gitea/dist/provisioner/index.js
|
||||
@@ -45,14 +45,6 @@ export interface GiteaPull {
|
||||
html_url: string;
|
||||
}
|
||||
|
||||
export interface GiteaComment {
|
||||
id: number;
|
||||
user?: string;
|
||||
body: string;
|
||||
created_at?: string;
|
||||
html_url: string;
|
||||
}
|
||||
|
||||
export interface GiteaLabel {
|
||||
id: number;
|
||||
name: string;
|
||||
@@ -103,13 +95,6 @@ export class GiteaClient {
|
||||
if (res.status === 401) {
|
||||
token = await this.tokens.renew(token);
|
||||
res = await this.send(path, options, token);
|
||||
} else if (res.status === 403) {
|
||||
// A kept token minted before a scope was added lacks it. The forge says so; the source
|
||||
// re-mints with the whole list and the call is retried once. Any other 403 stays a 403.
|
||||
const text = await res.text();
|
||||
if (!MintedToken.lacksScope(res.status, text)) throw new Error(`Gitea API ${path}: 403 ${text}`);
|
||||
token = await this.tokens.renew(token);
|
||||
res = await this.send(path, options, token);
|
||||
}
|
||||
if (!res.ok) throw new Error(`Gitea API ${path}: ${res.status} ${await res.text()}`);
|
||||
if (res.status === 204) return null as T;
|
||||
@@ -265,64 +250,6 @@ export class GiteaClient {
|
||||
);
|
||||
}
|
||||
|
||||
/** Close or reopen a pull request without merging it. A pull request is an issue to the forge's
|
||||
* state machine, and the pulls endpoint takes the same `state`. */
|
||||
async setPullState(owner: string, repo: string, index: number, state: "open" | "closed"): Promise<GiteaPull> {
|
||||
return GiteaClient.mapPull(
|
||||
await this.request<any>(`/repos/${owner}/${repo}/pulls/${index}`, { method: "PATCH", body: JSON.stringify({ state }) }),
|
||||
);
|
||||
}
|
||||
|
||||
/** Change a pull request's title or body; a field left undefined is left alone. */
|
||||
async updatePullRequest(owner: string, repo: string, index: number, data: { title?: string; body?: string }): Promise<GiteaPull> {
|
||||
return GiteaClient.mapPull(
|
||||
await this.request<any>(`/repos/${owner}/${repo}/pulls/${index}`, { method: "PATCH", body: JSON.stringify(data) }),
|
||||
);
|
||||
}
|
||||
|
||||
/** The unified diff of a pull request, as text. */
|
||||
async pullDiff(owner: string, repo: string, index: number): Promise<string> {
|
||||
return this.requestText(`/repos/${owner}/${repo}/pulls/${index}.diff`);
|
||||
}
|
||||
|
||||
/** Every comment on an issue or pull request, oldest first. */
|
||||
async listComments(owner: string, repo: string, index: number): Promise<GiteaComment[]> {
|
||||
const raw = await this.request<any[]>(`/repos/${owner}/${repo}/issues/${index}/comments`);
|
||||
return (raw ?? []).map((c) => ({
|
||||
id: Number(c?.id ?? 0),
|
||||
user: c?.user?.login,
|
||||
body: String(c?.body ?? ""),
|
||||
created_at: c?.created_at,
|
||||
html_url: String(c?.html_url ?? ""),
|
||||
}));
|
||||
}
|
||||
|
||||
/** One file's contents at a ref (default the repository's default branch), decoded. */
|
||||
async getFile(owner: string, repo: string, path: string, ref?: string): Promise<{ path: string; ref?: string; sha: string; size: number; content: string }> {
|
||||
const qs = ref ? `?ref=${encodeURIComponent(ref)}` : "";
|
||||
const f = await this.request<any>(`/repos/${owner}/${repo}/contents/${path.split("/").map(encodeURIComponent).join("/")}${qs}`);
|
||||
if (!f || f.type !== "file") throw new Error(`Gitea API: ${path} is not a file`);
|
||||
const content = f.encoding === "base64" ? Buffer.from(String(f.content ?? ""), "base64").toString("utf8") : String(f.content ?? "");
|
||||
return { path, ref, sha: String(f.sha ?? ""), size: Number(f.size ?? content.length), content };
|
||||
}
|
||||
|
||||
async listBranches(owner: string, repo: string): Promise<{ name: string; commit: string; protected: boolean }[]> {
|
||||
const raw = await this.request<any[]>(`/repos/${owner}/${repo}/branches?limit=100`);
|
||||
return (raw ?? []).map((b) => ({ name: String(b?.name ?? ""), commit: String(b?.commit?.id ?? ""), protected: Boolean(b?.protected) }));
|
||||
}
|
||||
|
||||
async deleteBranch(owner: string, repo: string, branch: string): Promise<void> {
|
||||
await this.request(`/repos/${owner}/${repo}/branches/${encodeURIComponent(branch)}`, { method: "DELETE" });
|
||||
}
|
||||
|
||||
/** A request whose answer is text, not JSON — a diff. Same token handling as request(). */
|
||||
private async requestText(path: string): Promise<string> {
|
||||
const token = await this.tokens.current();
|
||||
const res = await this.send(path, { headers: { Accept: "text/plain" } }, token);
|
||||
if (!res.ok) throw new Error(`Gitea API ${path}: ${res.status} ${await res.text()}`);
|
||||
return res.text();
|
||||
}
|
||||
|
||||
async mergePullRequest(owner: string, repo: string, index: number, method = "merge", deleteBranch = false): Promise<void> {
|
||||
await this.request(`/repos/${owner}/${repo}/pulls/${index}/merge`, {
|
||||
method: "POST",
|
||||
|
||||
+50
-35
@@ -85,17 +85,20 @@
|
||||
"scope": "mesh"
|
||||
}
|
||||
],
|
||||
"own-secrets": {
|
||||
"broker": "/var/lib/mesh/gitea/broker"
|
||||
},
|
||||
"resources": [
|
||||
{
|
||||
"id": "mesh-state",
|
||||
"type": "directory",
|
||||
"mode": "0700",
|
||||
"place": "mesh"
|
||||
"path": "/var/lib/mesh/gitea",
|
||||
"mode": "0700"
|
||||
},
|
||||
{
|
||||
"id": "runtime-state",
|
||||
"type": "directory",
|
||||
"path": "${dir:mesh-state}/state",
|
||||
"path": "/var/lib/mesh/gitea/state",
|
||||
"mode": "0700"
|
||||
},
|
||||
{
|
||||
@@ -142,8 +145,7 @@
|
||||
"volumes": [
|
||||
"${dir:data}:/data"
|
||||
],
|
||||
"secrets-in-environment": "gitea honours GITEA__database__PASSWD__FILE and GITEA__security__INTERNAL_TOKEN__FILE; convertible, awaiting a bed that proves it",
|
||||
"logging": "journald"
|
||||
"secrets-in-environment": "gitea honours GITEA__database__PASSWD__FILE and GITEA__security__INTERNAL_TOKEN__FILE; convertible, awaiting a bed that proves it"
|
||||
},
|
||||
{
|
||||
"id": "admin-bootstrap",
|
||||
@@ -173,10 +175,36 @@
|
||||
{
|
||||
"id": "runtime-config",
|
||||
"type": "file",
|
||||
"path": "${dir:mesh-state}/config.json",
|
||||
"path": "/var/lib/mesh/gitea/config.json",
|
||||
"mode": "0600",
|
||||
"content": "{}\n",
|
||||
"merge": "json"
|
||||
},
|
||||
{
|
||||
"id": "runtime",
|
||||
"type": "container",
|
||||
"name": "mesh-gitea",
|
||||
"network": "host",
|
||||
"volumes": [
|
||||
"/var/lib/mesh/gitea/broker:/run/secrets/broker:ro",
|
||||
"/var/lib/mesh/gitea/config.json:/run/config/config.json:ro",
|
||||
"${dir:grants}:${dir:grants}:ro",
|
||||
"${dir:state}/admin.secret:/run/secrets/admin:ro",
|
||||
"/var/lib/mesh/gitea/state:/run/state"
|
||||
],
|
||||
"env": {
|
||||
"MESH_BROKER_FILE": "/run/secrets/broker",
|
||||
"MESH_GITEA_URL": "http://127.0.0.1:${port:3000}",
|
||||
"MESH_GITEA_CONFIG_FILE": "/run/config/config.json",
|
||||
"MESH_GITEA_ADMIN_USER": "mesh-admin",
|
||||
"MESH_GITEA_ADMIN_PASSWORD_FILE": "/run/secrets/admin",
|
||||
"MESH_GITEA_STATE_DIR": "/run/state",
|
||||
"MESH_RECEIVES": "${dir:grants}/npm.json"
|
||||
},
|
||||
"artifact": "runtime",
|
||||
"restart-on": [
|
||||
"runtime-config"
|
||||
]
|
||||
}
|
||||
],
|
||||
"provides": [
|
||||
@@ -190,37 +218,24 @@
|
||||
}
|
||||
],
|
||||
"build": {
|
||||
"on": [
|
||||
{
|
||||
"arg": "BUILD_BASE",
|
||||
"module": "mesh-tools",
|
||||
"artifact": "build"
|
||||
},
|
||||
{
|
||||
"arg": "RUNTIME_BASE",
|
||||
"module": "mesh-tools",
|
||||
"artifact": "runtime"
|
||||
}
|
||||
],
|
||||
"artifacts": [
|
||||
{
|
||||
"name": "code",
|
||||
"kind": "bundle",
|
||||
"language": "typescript",
|
||||
"entrypoints": [
|
||||
"index.js",
|
||||
"tools/index.js",
|
||||
"provisioner/index.js"
|
||||
],
|
||||
"loads": [
|
||||
"index.js",
|
||||
"tools/index.js",
|
||||
"provisioner/index.js"
|
||||
],
|
||||
"env": {
|
||||
"MESH_GITEA_URL": "http://127.0.0.1:${port:3000}",
|
||||
"MESH_GITEA_CONFIG_FILE": "${dir:mesh-state}/config.json",
|
||||
"MESH_GITEA_ADMIN_USER": "mesh-admin",
|
||||
"MESH_GITEA_ADMIN_PASSWORD_FILE": "${dir:state}/admin.secret",
|
||||
"MESH_GITEA_STATE_DIR": "${dir:runtime-state}",
|
||||
"MESH_RECEIVES": "${dir:grants}/npm.json"
|
||||
}
|
||||
"name": "runtime",
|
||||
"kind": "image",
|
||||
"from": "Dockerfile"
|
||||
}
|
||||
]
|
||||
},
|
||||
"jails": [
|
||||
{
|
||||
"name": "gitea",
|
||||
"failregex": "^.*Failed authentication attempt for .* from <HOST>(?::\\d+)?\\s*$\n ^.*Invalid user .* from <HOST> port \\d+\\s*$\n ^.*User \\S+ from <HOST> not allowed because .*$",
|
||||
"jail": "backend = systemd\njournalmatch = CONTAINER_NAME=gitea\nport = http,https,222\nmaxretry = 3\nfindtime = 1d\nbantime = 1d"
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
|
||||
@@ -29,11 +29,7 @@ interface Forge {
|
||||
mints: number;
|
||||
lastScopes: string[] | null;
|
||||
tokens: Map<string, string>;
|
||||
scopesOf: Map<string, string[]>;
|
||||
admins: Map<string, string>;
|
||||
pullState: string;
|
||||
pullTitle: string;
|
||||
branchDeleted: boolean;
|
||||
close(): Promise<void>;
|
||||
}
|
||||
|
||||
@@ -44,9 +40,6 @@ function fakeForge(): Promise<Forge> {
|
||||
tokens: new Map<string, string>(), // name -> value
|
||||
scopesOf: new Map<string, string[]>(), // value -> scopes, so a route can enforce them like gitea does
|
||||
admins: new Map([[ADMIN, PASSWORD]]),
|
||||
pullState: "open",
|
||||
pullTitle: "The console shipped",
|
||||
branchDeleted: false,
|
||||
};
|
||||
// write:X implies read:X — gitea's own rule (models/auth/access_token_scope.go).
|
||||
const covers = (scopes: string[], required: string): boolean =>
|
||||
@@ -92,51 +85,6 @@ function fakeForge(): Promise<Forge> {
|
||||
}
|
||||
return json(res, 405, { message: "method not allowed" });
|
||||
}
|
||||
const tokenOf = (): string => {
|
||||
const h = req.headers.authorization ?? "";
|
||||
return h.startsWith("token ") ? h.slice(6) : "";
|
||||
};
|
||||
const pull = url.pathname.match(/^\/api\/v1\/repos\/novox\/hq\/pulls\/(\d+)(\.diff)?$/);
|
||||
if (pull) {
|
||||
if (![...forge.tokens.values()].includes(tokenOf())) return json(res, 401, { message: "token is required" });
|
||||
if (pull[2]) {
|
||||
res.writeHead(200, { "Content-Type": "text/plain" });
|
||||
return res.end("diff --git a/x b/x\n--- a/x\n+++ b/x\n@@ -1 +1 @@\n-old\n+new\n");
|
||||
}
|
||||
if (req.method === "PATCH") {
|
||||
const patch = await body(req);
|
||||
forge.pullState = patch?.state ?? forge.pullState;
|
||||
forge.pullTitle = patch?.title ?? forge.pullTitle;
|
||||
}
|
||||
return json(res, 200, { number: Number(pull[1]), title: forge.pullTitle, state: forge.pullState, merged: false,
|
||||
user: { login: "mesh-admin" }, head: { ref: "feat/x" }, base: { ref: "main" }, html_url: "http://fake/novox/hq/pulls/" + pull[1] });
|
||||
}
|
||||
if (url.pathname === "/api/v1/repos/novox/hq/issues/223/comments") {
|
||||
return json(res, 200, [{ id: 1, user: { login: "jochen" }, body: "landed elsewhere", created_at: "2026-10-01T00:00:00Z", html_url: "http://fake/c/1" }]);
|
||||
}
|
||||
if (url.pathname === "/api/v1/repos/novox/hq/contents/README.md") {
|
||||
return json(res, 200, { type: "file", encoding: "base64", sha: "abc", size: 5, content: Buffer.from("hello").toString("base64") });
|
||||
}
|
||||
if (url.pathname === "/api/v1/repos/novox/hq/branches") {
|
||||
return json(res, 200, [{ name: "main", protected: true, commit: { id: "aaaa" } }, { name: "feat/x", protected: false, commit: { id: "bbbb" } }]);
|
||||
}
|
||||
if (url.pathname === "/api/v1/repos/novox/hq/branches/feat%2Fx" || url.pathname === "/api/v1/repos/novox/hq/branches/feat/x") {
|
||||
if (req.method === "DELETE") { forge.branchDeleted = true; return json(res, 204, null); }
|
||||
}
|
||||
if (url.pathname === "/api/v1/repos/search") {
|
||||
// The client lists through the search endpoint since 2026-09-28 (the forge's whole view);
|
||||
// it sits under `repository`, which write:repository covers.
|
||||
const h = req.headers.authorization ?? "";
|
||||
const value = h.startsWith("token ") ? h.slice(6) : "";
|
||||
if (![...forge.tokens.values()].includes(value)) return json(res, 401, { message: "token is required" });
|
||||
if (!covers(forge.scopesOf.get(value) ?? [], "read:repository")) {
|
||||
return json(res, 403, { message: `token does not have at least one of required scope(s), required=[read:repository]` });
|
||||
}
|
||||
return json(res, 200, {
|
||||
ok: true,
|
||||
data: [{ full_name: "novox/hq", name: "hq", owner: { login: "novox" }, private: true, html_url: "http://fake/novox/hq" }],
|
||||
});
|
||||
}
|
||||
if (url.pathname === "/api/v1/user/repos") {
|
||||
const h = req.headers.authorization ?? "";
|
||||
const value = h.startsWith("token ") ? h.slice(6) : "";
|
||||
@@ -153,21 +101,6 @@ function fakeForge(): Promise<Forge> {
|
||||
{ full_name: "novox/hq", name: "hq", owner: { login: "novox" }, private: true, html_url: "http://fake/novox/hq" },
|
||||
]);
|
||||
}
|
||||
const adminUser = url.pathname.match(/^\/api\/v1\/admin\/users\/([^/]+)$/);
|
||||
if (adminUser && req.method === "PATCH") {
|
||||
const h = req.headers.authorization ?? "";
|
||||
const value = h.startsWith("token ") ? h.slice(6) : "";
|
||||
if (![...forge.tokens.values()].includes(value)) return json(res, 401, { message: "token is required" });
|
||||
if (!covers(forge.scopesOf.get(value) ?? [], "write:admin")) {
|
||||
return json(res, 403, {
|
||||
message: `token does not have at least one of required scope(s), required=[write:admin]`,
|
||||
});
|
||||
}
|
||||
const login = decodeURIComponent(adminUser[1]);
|
||||
if (login === "untouchable") return json(res, 403, { message: "user untouchable may not be edited" });
|
||||
const patch = await body(req);
|
||||
return json(res, 200, { login, is_admin: patch?.admin === true });
|
||||
}
|
||||
return json(res, 404, { message: "no such route in the fake" });
|
||||
});
|
||||
return new Promise((resolve) => {
|
||||
@@ -177,11 +110,7 @@ function fakeForge(): Promise<Forge> {
|
||||
url: `http://127.0.0.1:${port}`,
|
||||
get mints() { return forge.mints; },
|
||||
get lastScopes() { return forge.lastScopes; },
|
||||
get pullState() { return forge.pullState; },
|
||||
get pullTitle() { return forge.pullTitle; },
|
||||
get branchDeleted() { return forge.branchDeleted; },
|
||||
tokens: forge.tokens,
|
||||
scopesOf: forge.scopesOf,
|
||||
admins: forge.admins,
|
||||
close: () => new Promise((r) => server.close(() => r())),
|
||||
});
|
||||
@@ -223,14 +152,14 @@ function minted(env: NodeJS.ProcessEnv, logs: string[]): GiteaClient {
|
||||
const forge = await fakeForge();
|
||||
after(() => forge.close());
|
||||
|
||||
test("first start: mints with the admin account, keeps the token at 0600, asks for the tools' scopes only", async () => {
|
||||
test("first start: mints with the admin account, keeps the token at 0600, asks for two scopes only", async () => {
|
||||
const { env, file, logs } = await delivered(forge);
|
||||
|
||||
const repos = await minted(env, logs).listRepos();
|
||||
|
||||
assert.equal(repos[0]?.full_name, "novox/hq");
|
||||
assert.equal(forge.mints, 1);
|
||||
assert.deepEqual(forge.lastScopes, ["write:repository", "write:issue", "read:user", "write:admin"]);
|
||||
assert.deepEqual(forge.lastScopes, ["write:repository", "write:issue", "read:user"]);
|
||||
assert.deepEqual(forge.lastScopes, [...TOKEN_SCOPES]);
|
||||
const token = forge.tokens.get("mesh-tools")!;
|
||||
assert.equal(await readFile(file, "utf8"), token + "\n");
|
||||
@@ -268,34 +197,6 @@ test("the forge rejects the kept token (its data was restored): minted afresh, o
|
||||
assert.ok(logs.some((l) => l.startsWith("the forge rejected the kept token")), logs.join("\n"));
|
||||
});
|
||||
|
||||
test("a kept token from before write:admin: the forge refuses the admin route for the scope, the token is re-minted with the whole list, and the call goes through", async () => {
|
||||
const { env, file, logs } = await delivered(forge);
|
||||
const client = minted(env, logs);
|
||||
await client.listRepos();
|
||||
const before = forge.mints;
|
||||
const old = forge.tokens.get("mesh-tools")!;
|
||||
forge.scopesOf.set(old, ["write:repository", "write:issue", "read:user"]); // minted by the previous build
|
||||
|
||||
const user = await client.api<{ login: string; is_admin: boolean }>("/admin/users/mesh_novox_builder", {
|
||||
method: "PATCH",
|
||||
body: JSON.stringify({ admin: true }),
|
||||
});
|
||||
|
||||
assert.equal(user.is_admin, true);
|
||||
assert.equal(forge.mints, before + 1);
|
||||
assert.deepEqual(forge.lastScopes, [...TOKEN_SCOPES]);
|
||||
assert.notEqual(forge.tokens.get("mesh-tools"), old);
|
||||
assert.equal(await readFile(file, "utf8"), forge.tokens.get("mesh-tools") + "\n");
|
||||
assert.ok(logs.some((l) => l.startsWith("the forge rejected the kept token")), logs.join("\n"));
|
||||
// A 403 that is not about scopes is the forge's answer, not a reason to mint.
|
||||
const again = forge.mints;
|
||||
await assert.rejects(
|
||||
client.api("/admin/users/untouchable", { method: "PATCH", body: JSON.stringify({ admin: true }) }),
|
||||
/403 .*untouchable/,
|
||||
);
|
||||
assert.equal(forge.mints, again);
|
||||
});
|
||||
|
||||
test("the kept file is gone but the forge still holds a token by that name: replaced, not refused", async () => {
|
||||
const { env, file, logs } = await delivered(forge);
|
||||
await minted(env, logs).listRepos();
|
||||
@@ -400,16 +301,6 @@ test("the tools register once there is a way to a token, and the first call mint
|
||||
"gitea_list_repos", "gitea_create_repo", "gitea_delete_repo",
|
||||
"gitea_list_issues", "gitea_get_issue", "gitea_create_issue", "gitea_close_issue", "gitea_add_comment",
|
||||
"gitea_list_pull_requests", "gitea_get_pull_request", "gitea_create_pull_request", "gitea_merge_pull_request",
|
||||
"gitea_close_pull_request",
|
||||
"gitea_reopen_pull_request",
|
||||
"gitea_update_pull_request",
|
||||
"gitea_pull_request_files",
|
||||
"gitea_pull_request_diff",
|
||||
"gitea_list_comments",
|
||||
"gitea_reopen_issue",
|
||||
"gitea_get_file",
|
||||
"gitea_list_branches",
|
||||
"gitea_delete_branch",
|
||||
"gitea_list_labels", "gitea_create_label",
|
||||
"gitea_api",
|
||||
],
|
||||
@@ -420,32 +311,3 @@ test("the tools register once there is a way to a token, and the first call mint
|
||||
assert.equal(result.repos.length, 1);
|
||||
assert.equal(forge.mints, before + 1);
|
||||
});
|
||||
|
||||
// The forge's tools reach every action a review needs without a checkout and without the API
|
||||
// escape hatch: close a pull request whose work landed elsewhere, read its diff, its comments, a
|
||||
// file, the branches, and delete the branch left behind. Against the fake forge, through the
|
||||
// compiled tools, the way the console calls them.
|
||||
test("a pull request can be closed, read and cleaned up through the tools", async () => {
|
||||
const { env } = await delivered(forge);
|
||||
const tools = collectTools(env).find((c) => c.module === "gitea")!.tools;
|
||||
const tool = (name: string) => tools.find((t) => t.name === name)!;
|
||||
for (const name of ["gitea_close_pull_request", "gitea_reopen_pull_request", "gitea_update_pull_request", "gitea_pull_request_files",
|
||||
"gitea_pull_request_diff", "gitea_list_comments", "gitea_reopen_issue", "gitea_get_file", "gitea_list_branches", "gitea_delete_branch"]) {
|
||||
assert.ok(tool(name), `${name} is not a tool`);
|
||||
}
|
||||
const closed = (await tool("gitea_close_pull_request").run({ owner: "novox", repo: "hq", number: 223 })) as { pull: { state: string } };
|
||||
assert.equal(closed.pull.state, "closed");
|
||||
assert.equal(forge.pullState, "closed");
|
||||
const renamed = (await tool("gitea_update_pull_request").run({ owner: "novox", repo: "hq", number: 223, title: "Superseded" })) as { pull: { title: string } };
|
||||
assert.equal(renamed.pull.title, "Superseded");
|
||||
const diff = (await tool("gitea_pull_request_diff").run({ owner: "novox", repo: "hq", number: 223 })) as { diff: string };
|
||||
assert.match(diff.diff, /^diff --git/);
|
||||
const comments = (await tool("gitea_list_comments").run({ owner: "novox", repo: "hq", number: 223 })) as { comments: { body: string }[] };
|
||||
assert.equal(comments.comments[0].body, "landed elsewhere");
|
||||
const file = (await tool("gitea_get_file").run({ owner: "novox", repo: "hq", path: "README.md" })) as { file: { content: string } };
|
||||
assert.equal(file.file.content, "hello");
|
||||
const branches = (await tool("gitea_list_branches").run({ owner: "novox", repo: "hq" })) as { branches: { name: string }[] };
|
||||
assert.deepEqual(branches.branches.map((b) => b.name), ["main", "feat/x"]);
|
||||
await tool("gitea_delete_branch").run({ owner: "novox", repo: "hq", branch: "feat/x" });
|
||||
assert.equal(forge.branchDeleted, true);
|
||||
});
|
||||
|
||||
+3
-14
@@ -34,21 +34,15 @@ export const TOKEN_NAME = "mesh-tools";
|
||||
* It sits under the `user` category despite listing repositories, not `repository`
|
||||
* — confirmed against the running forge (1.27.3), which answered
|
||||
* `required=[read:user]` to a token carrying only the other two.
|
||||
* write:admin — /admin/users: the forge's own users are the mesh's to settle, such as making
|
||||
* the builder's login a site admin so every repository the mesh may build is
|
||||
* clonable (novox/hq 229). Nothing under /orgs or write:user.
|
||||
*
|
||||
* A token kept from before a scope was added lacks it: the forge answers such a call with
|
||||
* `403 token does not have at least one of required scope(s)`, and the client treats that like a
|
||||
* 401 — the source re-mints by name, with the whole list, and the call is retried once.
|
||||
* Nothing under /admin, /orgs or write:user — the escape-hatch tool reaches only what these three cover.
|
||||
*/
|
||||
export const TOKEN_SCOPES: readonly string[] = ["write:repository", "write:issue", "read:user", "write:admin"];
|
||||
export const TOKEN_SCOPES: readonly string[] = ["write:repository", "write:issue", "read:user"];
|
||||
|
||||
/** Where a client's token comes from, and what to do when the forge says it is wrong. */
|
||||
export interface TokenSource {
|
||||
/** The token to authenticate with now; minted, read or configured. */
|
||||
current(): Promise<string>;
|
||||
/** The forge answered 401 to `rejected`, or 403 for a scope it lacks. A fresh token, or a plain error when there is nothing to renew with. */
|
||||
/** The forge answered 401 to `rejected`. A fresh token, or a plain error when there is nothing to renew with. */
|
||||
renew(rejected: string): Promise<string>;
|
||||
}
|
||||
|
||||
@@ -176,11 +170,6 @@ export class MintedToken implements TokenSource {
|
||||
return this.mint("the forge rejected the kept token — minting a fresh one");
|
||||
}
|
||||
|
||||
/** What the forge's scoped tokens say when a kept token predates a scope the tools now need. */
|
||||
static lacksScope(status: number, body: string): boolean {
|
||||
return status === 403 && /required scope/i.test(body);
|
||||
}
|
||||
|
||||
/** One mint at a time: concurrent first calls share it, rather than each minting its own. */
|
||||
private mint(why: string): Promise<string> {
|
||||
if (this.inflight === null) {
|
||||
|
||||
@@ -254,131 +254,6 @@ export function getGiteaTools(gitea: GiteaClient): ToolDefinition[] {
|
||||
},
|
||||
},
|
||||
|
||||
{
|
||||
name: "gitea_close_pull_request",
|
||||
description: "Close a pull request without merging it — one whose work landed elsewhere, or was abandoned.",
|
||||
input: {
|
||||
owner: { type: "string", description: "the repository owner" },
|
||||
repo: { type: "string", description: "the repository name" },
|
||||
number: { type: "number", description: "the PR number" },
|
||||
},
|
||||
run: async (args) => ({
|
||||
pull: await gitea.setPullState(String(args.owner), String(args.repo), Number(args.number), "closed"),
|
||||
}),
|
||||
},
|
||||
{
|
||||
name: "gitea_reopen_pull_request",
|
||||
description: "Reopen a closed, unmerged pull request.",
|
||||
input: {
|
||||
owner: { type: "string", description: "the repository owner" },
|
||||
repo: { type: "string", description: "the repository name" },
|
||||
number: { type: "number", description: "the PR number" },
|
||||
},
|
||||
run: async (args) => ({
|
||||
pull: await gitea.setPullState(String(args.owner), String(args.repo), Number(args.number), "open"),
|
||||
}),
|
||||
},
|
||||
{
|
||||
name: "gitea_update_pull_request",
|
||||
description: "Change a pull request's title or body; a field not given is left as it is.",
|
||||
input: {
|
||||
owner: { type: "string", description: "the repository owner" },
|
||||
repo: { type: "string", description: "the repository name" },
|
||||
number: { type: "number", description: "the PR number" },
|
||||
title: { type: "string", description: "the new title (optional)" },
|
||||
body: { type: "string", description: "the new body, markdown (optional)" },
|
||||
},
|
||||
run: async (args) => ({
|
||||
pull: await gitea.updatePullRequest(String(args.owner), String(args.repo), Number(args.number), {
|
||||
title: args.title === undefined ? undefined : String(args.title),
|
||||
body: args.body === undefined ? undefined : String(args.body),
|
||||
}),
|
||||
}),
|
||||
},
|
||||
{
|
||||
name: "gitea_pull_request_files",
|
||||
description: "The files a pull request changes, as paths from the repository's root (up to 100; says when there are more).",
|
||||
input: {
|
||||
owner: { type: "string", description: "the repository owner" },
|
||||
repo: { type: "string", description: "the repository name" },
|
||||
number: { type: "number", description: "the PR number" },
|
||||
},
|
||||
run: async (args) => gitea.listPullFiles(String(args.owner), String(args.repo), Number(args.number)),
|
||||
},
|
||||
{
|
||||
name: "gitea_pull_request_diff",
|
||||
description: "A pull request's unified diff, as text — for reviewing it without a checkout.",
|
||||
input: {
|
||||
owner: { type: "string", description: "the repository owner" },
|
||||
repo: { type: "string", description: "the repository name" },
|
||||
number: { type: "number", description: "the PR number" },
|
||||
},
|
||||
run: async (args) => ({
|
||||
diff: await gitea.pullDiff(String(args.owner), String(args.repo), Number(args.number)),
|
||||
}),
|
||||
},
|
||||
{
|
||||
name: "gitea_list_comments",
|
||||
description: "Every comment on an issue or pull request, oldest first.",
|
||||
input: {
|
||||
owner: { type: "string", description: "the repository owner" },
|
||||
repo: { type: "string", description: "the repository name" },
|
||||
number: { type: "number", description: "the issue or PR number" },
|
||||
},
|
||||
run: async (args) => ({
|
||||
comments: await gitea.listComments(String(args.owner), String(args.repo), Number(args.number)),
|
||||
}),
|
||||
},
|
||||
{
|
||||
name: "gitea_reopen_issue",
|
||||
description: "Reopen a closed issue.",
|
||||
input: {
|
||||
owner: { type: "string", description: "the repository owner" },
|
||||
repo: { type: "string", description: "the repository name" },
|
||||
number: { type: "number", description: "the issue number" },
|
||||
},
|
||||
run: async (args) => ({
|
||||
issue: await gitea.setIssueState(String(args.owner), String(args.repo), Number(args.number), "open"),
|
||||
}),
|
||||
},
|
||||
|
||||
// ---- Contents and branches ----
|
||||
{
|
||||
name: "gitea_get_file",
|
||||
description: "One file's contents from a repository, decoded, at a branch, tag or commit (default the repository's default branch).",
|
||||
input: {
|
||||
owner: { type: "string", description: "the repository owner" },
|
||||
repo: { type: "string", description: "the repository name" },
|
||||
path: { type: "string", description: "the file's path from the repository's root" },
|
||||
ref: { type: "string", description: "branch, tag or commit (optional)" },
|
||||
},
|
||||
run: async (args) => ({
|
||||
file: await gitea.getFile(String(args.owner), String(args.repo), String(args.path), args.ref ? String(args.ref) : undefined),
|
||||
}),
|
||||
},
|
||||
{
|
||||
name: "gitea_list_branches",
|
||||
description: "Every branch of a repository with the commit it points at.",
|
||||
input: {
|
||||
owner: { type: "string", description: "the repository owner" },
|
||||
repo: { type: "string", description: "the repository name" },
|
||||
},
|
||||
run: async (args) => ({ branches: await gitea.listBranches(String(args.owner), String(args.repo)) }),
|
||||
},
|
||||
{
|
||||
name: "gitea_delete_branch",
|
||||
description: "Delete a branch — a feature branch whose pull request was closed rather than merged. Refused by the forge for a protected branch.",
|
||||
input: {
|
||||
owner: { type: "string", description: "the repository owner" },
|
||||
repo: { type: "string", description: "the repository name" },
|
||||
branch: { type: "string", description: "the branch name" },
|
||||
},
|
||||
run: async (args) => {
|
||||
await gitea.deleteBranch(String(args.owner), String(args.repo), String(args.branch));
|
||||
return { deleted: true, branch: String(args.branch) };
|
||||
},
|
||||
},
|
||||
|
||||
// ---- Labels ----
|
||||
{
|
||||
name: "gitea_list_labels",
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
# gitlab's runtime: the tool runtime, carrying this module's compiled code.
|
||||
#
|
||||
# **Built from this module's own directory and nothing else.** The sdk and the tool runtime are in
|
||||
# the base images, published like any other artifact — which is what makes this buildable by the
|
||||
# mesh from a repository and a path (novox/hq ADR 0069) rather than only on a workstation that
|
||||
# happens to have the siblings.
|
||||
#
|
||||
# Two bases, named rather than pinned (novox/hq issue 044): the image this is COMPILED in and the
|
||||
# image it RUNS in — the second must not carry a compiler. Declared in module.json's `build.on`.
|
||||
ARG BUILD_BASE
|
||||
ARG RUNTIME_BASE
|
||||
|
||||
FROM ${BUILD_BASE} AS build
|
||||
WORKDIR /app/modules/gitlab
|
||||
COPY . .
|
||||
RUN node /app/node_modules/typescript/bin/tsc client.ts tools/index.ts \
|
||||
--module NodeNext --moduleResolution NodeNext --target ES2022 --outDir dist
|
||||
|
||||
FROM ${RUNTIME_BASE}
|
||||
COPY --from=build /app/modules/gitlab/dist /app/modules/gitlab/dist
|
||||
# Every serve-time entrypoint, loaded by the runtime in serve mode: tools and events serve, and a
|
||||
# provider's provisioner runs its reconcile loop in the same process, with the broker connected —
|
||||
# the convention novox/hq issues 060/061 settled.
|
||||
ENV MESH_TOOL_MODULES=/app/modules/gitlab/dist/tools/index.js
|
||||
+43
-17
@@ -2,43 +2,69 @@
|
||||
"module": "gitlab",
|
||||
"version": "1",
|
||||
"own-secrets": {
|
||||
"token": "${dir:state}/token"
|
||||
"token": "/var/lib/gitlab/token",
|
||||
"broker": "/var/lib/mesh/gitlab/broker"
|
||||
},
|
||||
"resources": [
|
||||
{
|
||||
"id": "mesh-state",
|
||||
"type": "directory",
|
||||
"path": "/var/lib/mesh/gitlab",
|
||||
"mode": "0700"
|
||||
},
|
||||
{
|
||||
"id": "state",
|
||||
"type": "directory",
|
||||
"mode": "0700",
|
||||
"place": "."
|
||||
"path": "/var/lib/gitlab",
|
||||
"mode": "0700"
|
||||
},
|
||||
{
|
||||
"id": "config",
|
||||
"type": "file",
|
||||
"path": "${dir:state}/config.json",
|
||||
"path": "/var/lib/gitlab/config.json",
|
||||
"merge": "json",
|
||||
"content": "{}",
|
||||
"mode": "0600"
|
||||
},
|
||||
{
|
||||
"id": "runtime",
|
||||
"type": "container",
|
||||
"name": "mesh-runtime-gitlab",
|
||||
"network": "host",
|
||||
"volumes": [
|
||||
"/var/lib/gitlab/config.json:/run/config/config.json:ro",
|
||||
"/var/lib/gitlab/token:/run/secrets/token:ro",
|
||||
"/var/lib/mesh/gitlab/broker:/run/secrets/broker:ro"
|
||||
],
|
||||
"env": {
|
||||
"MESH_GITLAB_TOKEN_FILE": "/run/secrets/token",
|
||||
"MESH_GITLAB_CONFIG_FILE": "/run/config/config.json",
|
||||
"MESH_BROKER_FILE": "/run/secrets/broker"
|
||||
},
|
||||
"artifact": "runtime"
|
||||
}
|
||||
],
|
||||
"capabilities": [
|
||||
"container-runtime"
|
||||
],
|
||||
"build": {
|
||||
"on": [
|
||||
{
|
||||
"arg": "BUILD_BASE",
|
||||
"module": "mesh-tools",
|
||||
"artifact": "build"
|
||||
},
|
||||
{
|
||||
"arg": "RUNTIME_BASE",
|
||||
"module": "mesh-tools",
|
||||
"artifact": "runtime"
|
||||
}
|
||||
],
|
||||
"artifacts": [
|
||||
{
|
||||
"name": "tools",
|
||||
"kind": "bundle",
|
||||
"language": "typescript",
|
||||
"entrypoints": [
|
||||
"tools/index.js"
|
||||
],
|
||||
"loads": [
|
||||
"tools/index.js"
|
||||
],
|
||||
"env": {
|
||||
"MESH_GITLAB_TOKEN_FILE": "${dir:state}/token",
|
||||
"MESH_GITLAB_CONFIG_FILE": "${dir:state}/config.json"
|
||||
}
|
||||
"name": "runtime",
|
||||
"kind": "image",
|
||||
"from": "Dockerfile"
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
# grafana's runtime: the tool runtime, carrying this module's compiled code.
|
||||
#
|
||||
# **Built from this module's own directory and nothing else.** The sdk and the tool runtime are in
|
||||
# the base images, published like any other artifact — which is what makes this buildable by the
|
||||
# mesh from a repository and a path (novox/hq ADR 0069) rather than only on a workstation that
|
||||
# happens to have the siblings.
|
||||
#
|
||||
# Two bases, named rather than pinned (novox/hq issue 044): the image this is COMPILED in and the
|
||||
# image it RUNS in — the second must not carry a compiler. Declared in module.json's `build.on`.
|
||||
ARG BUILD_BASE
|
||||
ARG RUNTIME_BASE
|
||||
|
||||
FROM ${BUILD_BASE} AS build
|
||||
WORKDIR /app/modules/grafana
|
||||
COPY . .
|
||||
RUN node /app/node_modules/typescript/bin/tsc client.ts index.ts tools/index.ts \
|
||||
--module NodeNext --moduleResolution NodeNext --target ES2022 --outDir dist
|
||||
|
||||
FROM ${RUNTIME_BASE}
|
||||
COPY --from=build /app/modules/grafana/dist /app/modules/grafana/dist
|
||||
# Every serve-time entrypoint, loaded by the runtime in serve mode: tools and events serve, and a
|
||||
# provider's provisioner runs its reconcile loop in the same process, with the broker connected —
|
||||
# the convention novox/hq issues 060/061 settled.
|
||||
ENV MESH_TOOL_MODULES=/app/modules/grafana/dist/index.js,/app/modules/grafana/dist/tools/index.js
|
||||
+53
-91
@@ -5,7 +5,8 @@
|
||||
"alert.firing"
|
||||
],
|
||||
"own-secrets": {
|
||||
"admin": "${dir:mesh-state}/admin"
|
||||
"admin": "/var/lib/grafana-module/admin.secret",
|
||||
"broker": "/var/lib/mesh/grafana/broker"
|
||||
},
|
||||
"capabilities": [
|
||||
"container-runtime"
|
||||
@@ -23,142 +24,103 @@
|
||||
{
|
||||
"id": "mesh-state",
|
||||
"type": "directory",
|
||||
"mode": "0700",
|
||||
"place": "mesh"
|
||||
"path": "/var/lib/mesh/grafana",
|
||||
"mode": "0700"
|
||||
},
|
||||
{
|
||||
"id": "state",
|
||||
"type": "directory",
|
||||
"mode": "0700",
|
||||
"place": "."
|
||||
"path": "/var/lib/grafana-module",
|
||||
"mode": "0700"
|
||||
},
|
||||
{
|
||||
"id": "data",
|
||||
"type": "directory",
|
||||
"path": "/services/grafana/data",
|
||||
"mode": "0700",
|
||||
"owner": "472:472"
|
||||
},
|
||||
{
|
||||
"id": "admin-secret",
|
||||
"id": "server-env",
|
||||
"type": "file",
|
||||
"path": "${dir:state}/admin.secret",
|
||||
"mode": "0400",
|
||||
"owner": "472:472",
|
||||
"content": "${secret:admin}"
|
||||
},
|
||||
{
|
||||
"id": "oidc-secret",
|
||||
"type": "file",
|
||||
"path": "${dir:state}/oidc-client.secret",
|
||||
"mode": "0400",
|
||||
"owner": "472:472",
|
||||
"content": "${secret:oidc-client}"
|
||||
},
|
||||
{
|
||||
"id": "oidc-env",
|
||||
"type": "file",
|
||||
"path": "${dir:state}/oidc.env",
|
||||
"mode": "0644",
|
||||
"content": "GF_SERVER_ROOT_URL=https://${bound:route:name}\nGF_AUTH_GENERIC_OAUTH_ENABLED=true\nGF_AUTH_GENERIC_OAUTH_NAME=Keycloak\nGF_AUTH_GENERIC_OAUTH_CLIENT_ID=${bound:oidc-client:as}\nGF_AUTH_GENERIC_OAUTH_CLIENT_SECRET__FILE=/run/secrets/oidc-client\nGF_AUTH_GENERIC_OAUTH_SCOPES=openid email profile roles\nGF_AUTH_GENERIC_OAUTH_AUTH_URL=${bound:oidc-client:issuer}${bound:oidc-client:authorization-path}\nGF_AUTH_GENERIC_OAUTH_TOKEN_URL=${bound:oidc-client:issuer}${bound:oidc-client:token-path}\nGF_AUTH_GENERIC_OAUTH_API_URL=${bound:oidc-client:issuer}${bound:oidc-client:userinfo-path}\nGF_AUTH_GENERIC_OAUTH_ROLE_ATTRIBUTE_PATH=contains(roles[*], 'admin') && 'Admin' || contains(realm_access.roles[*], 'admin') && 'Admin' || 'Viewer'\nGF_AUTH_GENERIC_OAUTH_USE_PKCE=true\nGF_AUTH_GENERIC_OAUTH_ALLOW_SIGN_UP=true\nGF_AUTH_GENERIC_OAUTH_ALLOW_ASSIGN_GRAFANA_ADMIN=true\n"
|
||||
},
|
||||
{
|
||||
"id": "influxdb-secret",
|
||||
"type": "file",
|
||||
"path": "${dir:state}/influxdb-api.secret",
|
||||
"mode": "0400",
|
||||
"owner": "472:472",
|
||||
"content": "${secret:influxdb-api}"
|
||||
},
|
||||
{
|
||||
"id": "influxdb-datasource",
|
||||
"type": "file",
|
||||
"path": "${dir:state}/datasource-influxdb.yaml",
|
||||
"mode": "0644",
|
||||
"content": "apiVersion: 1\n# Written by the mesh from grafana's influxdb-api binding; grafana reads it at start. Its own name and\n# uid, so a data source somebody made in the UI is never overwritten, and read-only in the UI because\n# the mesh resets it. The password is read from the file the mesh delivers, never written here.\ndatasources:\n - name: InfluxDB (mesh)\n uid: mesh-influxdb-api\n type: influxdb\n access: proxy\n url: ${bound:influxdb-api:scheme}://${bound:influxdb-api:at}:${bound:influxdb-api:port}\n user: ${bound:influxdb-api:as}\n isDefault: false\n editable: false\n jsonData:\n dbName: ${bound:influxdb-api:bucket}\n httpMode: POST\n secureJsonData:\n password: $__file{/run/secrets/influxdb-api}\n"
|
||||
"path": "/var/lib/grafana-module/server.env",
|
||||
"mode": "0600",
|
||||
"content": "GF_SECURITY_ADMIN_PASSWORD=${secret:admin}\n"
|
||||
},
|
||||
{
|
||||
"id": "server",
|
||||
"type": "container",
|
||||
"name": "grafana",
|
||||
"image": "grafana/grafana@sha256:ac461fb352abc50da10a51c7d02462e9c05488f11f53f14b3ad79a8145f638a0",
|
||||
"image": "grafana/grafana@sha256:f772d434e8fab0049deb2b1b30abd43342bcfca1537614aa8d36080232cf4283",
|
||||
"ports": [
|
||||
"3000"
|
||||
],
|
||||
"volumes": [
|
||||
"${dir:data}:/var/lib/grafana",
|
||||
"${dir:state}/admin.secret:/run/secrets/admin:ro",
|
||||
"${dir:state}/oidc-client.secret:/run/secrets/oidc-client:ro",
|
||||
"${dir:state}/influxdb-api.secret:/run/secrets/influxdb-api:ro",
|
||||
"${dir:state}/datasource-influxdb.yaml:/etc/grafana/provisioning/datasources/mesh-influxdb.yaml:ro"
|
||||
"/services/grafana/data:/var/lib/grafana"
|
||||
],
|
||||
"env": {
|
||||
"GF_SECURITY_ADMIN_PASSWORD__FILE": "/run/secrets/admin"
|
||||
},
|
||||
"env-file": [
|
||||
"${dir:state}/oidc.env"
|
||||
"/var/lib/grafana-module/server.env"
|
||||
],
|
||||
"restart-on": [
|
||||
"oidc-env",
|
||||
"oidc-secret",
|
||||
"influxdb-datasource",
|
||||
"influxdb-secret"
|
||||
]
|
||||
"secrets-in-environment": "grafana honours GF_SECURITY_ADMIN_PASSWORD__FILE; convertible, awaiting a bed that exercises the admin password (assigned-grafana serves tools only)"
|
||||
},
|
||||
{
|
||||
"id": "runtime-config",
|
||||
"type": "file",
|
||||
"path": "${dir:mesh-state}/config.json",
|
||||
"path": "/var/lib/mesh/grafana/config.json",
|
||||
"mode": "0600",
|
||||
"content": "{\n \"user\": \"admin\",\n \"password\": \"${secret:admin}\"\n}\n",
|
||||
"content": "{}\n",
|
||||
"merge": "json"
|
||||
},
|
||||
{
|
||||
"id": "runtime",
|
||||
"type": "container",
|
||||
"name": "mesh-grafana",
|
||||
"network": "host",
|
||||
"volumes": [
|
||||
"/var/lib/mesh/grafana/broker:/run/secrets/broker:ro",
|
||||
"/var/lib/mesh/grafana/config.json:/run/config/config.json:ro"
|
||||
],
|
||||
"env": {
|
||||
"MESH_BROKER_FILE": "/run/secrets/broker",
|
||||
"MESH_GRAFANA_URL": "http://127.0.0.1:3000",
|
||||
"MESH_GRAFANA_CONFIG_FILE": "/run/config/config.json"
|
||||
},
|
||||
"restart-on": [
|
||||
"runtime-config"
|
||||
],
|
||||
"artifact": "runtime"
|
||||
}
|
||||
],
|
||||
"requires": [
|
||||
"route",
|
||||
"oidc-client",
|
||||
"influxdb-api"
|
||||
"route"
|
||||
],
|
||||
"contributes": {
|
||||
"route": {
|
||||
"label": "grafana",
|
||||
"endpoint": "web"
|
||||
},
|
||||
"oidc-client": {
|
||||
"label": "grafana",
|
||||
"endpoint": "web",
|
||||
"callback": "/login/generic_oauth"
|
||||
},
|
||||
"influxdb-api": {
|
||||
"access": "read"
|
||||
}
|
||||
},
|
||||
"binds": {
|
||||
"route": "${dir:state}/route.json",
|
||||
"oidc-client": "${dir:state}/oidc.json",
|
||||
"influxdb-api": "${dir:state}/influxdb.json"
|
||||
},
|
||||
"secrets": {
|
||||
"oidc-client": "${dir:mesh-state}/oidc-client",
|
||||
"influxdb-api": "${dir:mesh-state}/influxdb-api"
|
||||
"route": "/var/lib/mesh/grafana/route.json"
|
||||
},
|
||||
"build": {
|
||||
"on": [
|
||||
{
|
||||
"arg": "BUILD_BASE",
|
||||
"module": "mesh-tools",
|
||||
"artifact": "build"
|
||||
},
|
||||
{
|
||||
"arg": "RUNTIME_BASE",
|
||||
"module": "mesh-tools",
|
||||
"artifact": "runtime"
|
||||
}
|
||||
],
|
||||
"artifacts": [
|
||||
{
|
||||
"name": "code",
|
||||
"kind": "bundle",
|
||||
"language": "typescript",
|
||||
"entrypoints": [
|
||||
"index.js",
|
||||
"tools/index.js"
|
||||
],
|
||||
"loads": [
|
||||
"index.js",
|
||||
"tools/index.js"
|
||||
],
|
||||
"env": {
|
||||
"MESH_GRAFANA_URL": "http://127.0.0.1:${port:3000}",
|
||||
"MESH_GRAFANA_CONFIG_FILE": "${dir:mesh-state}/config.json"
|
||||
}
|
||||
"name": "runtime",
|
||||
"kind": "image",
|
||||
"from": "Dockerfile"
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
@@ -15,7 +15,7 @@
|
||||
}
|
||||
},
|
||||
"binds": {
|
||||
"route": "${dir:state}/route.json"
|
||||
"route": "/var/lib/hello-web/route.json"
|
||||
},
|
||||
"listens": [
|
||||
{
|
||||
@@ -30,13 +30,13 @@
|
||||
{
|
||||
"id": "state",
|
||||
"type": "directory",
|
||||
"mode": "0700",
|
||||
"place": "."
|
||||
"path": "/var/lib/hello-web",
|
||||
"mode": "0700"
|
||||
},
|
||||
{
|
||||
"id": "page",
|
||||
"type": "file",
|
||||
"path": "${dir:state}/index.html",
|
||||
"path": "/var/lib/hello-web/index.html",
|
||||
"mode": "0644",
|
||||
"content": "hello from hello-web, routed by the mesh\n"
|
||||
},
|
||||
@@ -54,7 +54,7 @@
|
||||
"8080"
|
||||
],
|
||||
"volumes": [
|
||||
"${dir:state}/index.html:/www/index.html:ro"
|
||||
"/var/lib/hello-web/index.html:/www/index.html:ro"
|
||||
],
|
||||
"args": [
|
||||
"sh",
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
# home-assistant's runtime: the tool runtime, carrying this module's compiled code.
|
||||
#
|
||||
# **Built from this module's own directory and nothing else.** The sdk and the tool runtime are in
|
||||
# the base images, published like any other artifact — which is what makes this buildable by the
|
||||
# mesh from a repository and a path (novox/hq ADR 0069) rather than only on a workstation that
|
||||
# happens to have the siblings.
|
||||
#
|
||||
# Two bases, named rather than pinned (novox/hq issue 044): the image this is COMPILED in and the
|
||||
# image it RUNS in — the second must not carry a compiler. Declared in module.json's `build.on`.
|
||||
ARG BUILD_BASE
|
||||
ARG RUNTIME_BASE
|
||||
|
||||
FROM ${BUILD_BASE} AS build
|
||||
WORKDIR /app/modules/home-assistant
|
||||
COPY . .
|
||||
RUN node /app/node_modules/typescript/bin/tsc client.ts index.ts tools/index.ts \
|
||||
--module NodeNext --moduleResolution NodeNext --target ES2022 --outDir dist
|
||||
|
||||
FROM ${RUNTIME_BASE}
|
||||
COPY --from=build /app/modules/home-assistant/dist /app/modules/home-assistant/dist
|
||||
# Every serve-time entrypoint, loaded by the runtime in serve mode: tools and events serve, and a
|
||||
# provider's provisioner runs its reconcile loop in the same process, with the broker connected —
|
||||
# the convention novox/hq issues 060/061 settled.
|
||||
ENV MESH_TOOL_MODULES=/app/modules/home-assistant/dist/index.js,/app/modules/home-assistant/dist/tools/index.js
|
||||
@@ -9,7 +9,8 @@
|
||||
"state.changed"
|
||||
],
|
||||
"own-secrets": {
|
||||
"token": "${dir:mesh-state}/token"
|
||||
"broker": "/var/lib/mesh/home-assistant/broker",
|
||||
"token": "/var/lib/mesh/home-assistant/token"
|
||||
},
|
||||
"listens": [
|
||||
{
|
||||
@@ -17,151 +18,98 @@
|
||||
"port": 8123,
|
||||
"protocol": "tcp",
|
||||
"from": "mesh",
|
||||
"why": "the dashboard, the API and the companion apps"
|
||||
},
|
||||
{
|
||||
"name": "sonos-events",
|
||||
"port": 1400,
|
||||
"protocol": "tcp",
|
||||
"from": "mesh",
|
||||
"why": "the Sonos integration's event callback: speakers push their state changes here"
|
||||
},
|
||||
{
|
||||
"name": "webrtc",
|
||||
"port": 18555,
|
||||
"protocol": "tcp",
|
||||
"from": "mesh",
|
||||
"why": "the bundled go2rtc's WebRTC port, which camera streams to a browser use"
|
||||
"why": "the dashboard and the API"
|
||||
}
|
||||
],
|
||||
"resources": [
|
||||
{
|
||||
"id": "mesh-state",
|
||||
"type": "directory",
|
||||
"mode": "0700",
|
||||
"place": "mesh"
|
||||
},
|
||||
{
|
||||
"id": "state",
|
||||
"type": "directory",
|
||||
"mode": "0700",
|
||||
"place": "."
|
||||
"path": "/var/lib/mesh/home-assistant",
|
||||
"mode": "0700"
|
||||
},
|
||||
{
|
||||
"id": "config",
|
||||
"type": "directory",
|
||||
"mode": "0700"
|
||||
},
|
||||
{
|
||||
"id": "written",
|
||||
"type": "directory",
|
||||
"mode": "0700"
|
||||
"path": "/services/home-assistant/config",
|
||||
"mode": "0700",
|
||||
"owner": "1000:1000"
|
||||
},
|
||||
{
|
||||
"id": "server",
|
||||
"type": "container",
|
||||
"name": "home-assistant",
|
||||
"image": "ghcr.io/home-assistant/home-assistant@sha256:d8922685169707fd91e8b9729902d975f06157d005e422874d201e0261dda196",
|
||||
"image": "ghcr.io/home-assistant/home-assistant@sha256:14931c6b13756317849f46da1d01b45937a1150db66c081cfe529d48215943fe",
|
||||
"network": "host",
|
||||
"env": {
|
||||
"TZ": "Etc/UTC"
|
||||
},
|
||||
"volumes": [
|
||||
"${dir:config}:/config"
|
||||
"/services/home-assistant/config:/config"
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "runtime-config",
|
||||
"type": "file",
|
||||
"path": "${dir:mesh-state}/config.json",
|
||||
"path": "/var/lib/mesh/home-assistant/config.json",
|
||||
"mode": "0600",
|
||||
"content": "{}\n",
|
||||
"merge": "json"
|
||||
},
|
||||
{
|
||||
"id": "provisions-env",
|
||||
"type": "file",
|
||||
"path": "${dir:state}/provisions.env",
|
||||
"mode": "0600",
|
||||
"content": "MESH_HOMEASSISTANT_URL=http://127.0.0.1:${port:8123}\nMESH_HOMEASSISTANT_TOKEN_FILE=${dir:mesh-state}/token\nMESH_PROVISIONS_DIR=${dir:state}\nMESH_WRITTEN_DIR=${dir:written}\n"
|
||||
},
|
||||
{
|
||||
"id": "provisions",
|
||||
"type": "process",
|
||||
"name": "home-assistant-provisions",
|
||||
"artifact": "code",
|
||||
"run": [
|
||||
"node",
|
||||
"provisions/index.js"
|
||||
],
|
||||
"run-once": true,
|
||||
"env-file": [
|
||||
"${dir:state}/provisions.env"
|
||||
"id": "runtime",
|
||||
"type": "container",
|
||||
"name": "mesh-home-assistant",
|
||||
"network": "host",
|
||||
"volumes": [
|
||||
"/var/lib/mesh/home-assistant/broker:/run/secrets/broker:ro",
|
||||
"/var/lib/mesh/home-assistant/token:/run/secrets/token:ro",
|
||||
"/var/lib/mesh/home-assistant/config.json:/run/config/config.json:ro",
|
||||
"/services/home-assistant/config:/var/lib/home-assistant/config:ro"
|
||||
],
|
||||
"env": {
|
||||
"MESH_BROKER_FILE": "/run/secrets/broker",
|
||||
"MESH_HOMEASSISTANT_URL": "http://127.0.0.1:8123",
|
||||
"MESH_HOMEASSISTANT_TOKEN_FILE": "/run/secrets/token",
|
||||
"MESH_HOMEASSISTANT_CONFIG_FILE": "/run/config/config.json",
|
||||
"MESH_HOMEASSISTANT_CONFIG_DIR": "/var/lib/home-assistant/config"
|
||||
},
|
||||
"restart-on": [
|
||||
"provisions-env",
|
||||
"bound-mqtt-topic",
|
||||
"secret-mqtt-topic",
|
||||
"bound-sonarr-api",
|
||||
"secret-sonarr-api",
|
||||
"bound-radarr-api",
|
||||
"secret-radarr-api",
|
||||
"bound-lidarr-api",
|
||||
"secret-lidarr-api"
|
||||
]
|
||||
"runtime-config"
|
||||
],
|
||||
"artifact": "runtime"
|
||||
}
|
||||
],
|
||||
"requires": [
|
||||
"lidarr-api",
|
||||
"mqtt-topic",
|
||||
"radarr-api",
|
||||
"route",
|
||||
"sonarr-api"
|
||||
"route"
|
||||
],
|
||||
"contributes": {
|
||||
"mqtt-topic": {
|
||||
"topics": [
|
||||
"#"
|
||||
]
|
||||
},
|
||||
"route": {
|
||||
"label": "home-assistant",
|
||||
"endpoint": "web"
|
||||
}
|
||||
},
|
||||
"binds": {
|
||||
"route": "${dir:state}/route.json",
|
||||
"mqtt-topic": "${dir:state}/mqtt-topic.json",
|
||||
"sonarr-api": "${dir:state}/sonarr-api.json",
|
||||
"radarr-api": "${dir:state}/radarr-api.json",
|
||||
"lidarr-api": "${dir:state}/lidarr-api.json"
|
||||
},
|
||||
"secrets": {
|
||||
"mqtt-topic": "${dir:state}/mqtt-topic.secret",
|
||||
"sonarr-api": "${dir:state}/sonarr-api.secret",
|
||||
"radarr-api": "${dir:state}/radarr-api.secret",
|
||||
"lidarr-api": "${dir:state}/lidarr-api.secret"
|
||||
"route": "/var/lib/mesh/home-assistant/route.json"
|
||||
},
|
||||
"build": {
|
||||
"on": [
|
||||
{
|
||||
"arg": "BUILD_BASE",
|
||||
"module": "mesh-tools",
|
||||
"artifact": "build"
|
||||
},
|
||||
{
|
||||
"arg": "RUNTIME_BASE",
|
||||
"module": "mesh-tools",
|
||||
"artifact": "runtime"
|
||||
}
|
||||
],
|
||||
"artifacts": [
|
||||
{
|
||||
"name": "code",
|
||||
"kind": "bundle",
|
||||
"language": "typescript",
|
||||
"entrypoints": [
|
||||
"index.js",
|
||||
"tools/index.js",
|
||||
"provisions/index.js"
|
||||
],
|
||||
"loads": [
|
||||
"index.js",
|
||||
"tools/index.js"
|
||||
],
|
||||
"env": {
|
||||
"MESH_HOMEASSISTANT_URL": "http://127.0.0.1:${port:8123}",
|
||||
"MESH_HOMEASSISTANT_TOKEN_FILE": "${dir:mesh-state}/token",
|
||||
"MESH_HOMEASSISTANT_CONFIG_FILE": "${dir:mesh-state}/config.json"
|
||||
}
|
||||
"name": "runtime",
|
||||
"kind": "image",
|
||||
"from": "Dockerfile"
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
@@ -1,14 +1,9 @@
|
||||
{
|
||||
"name": "@novox/module-home-assistant",
|
||||
"version": "0.1.0",
|
||||
"description": "home-assistant \u2014 home automation platform. Its API client, tools and events live here (novox/hq ADR 0039).",
|
||||
"description": "home-assistant — home automation platform. Its API client, tools and events live here (novox/hq ADR 0039).",
|
||||
"type": "module",
|
||||
"private": true,
|
||||
"scripts": {
|
||||
"build": "tsc client.ts index.ts tools/index.ts provisions/hass.ts provisions/probe.ts provisions/connections.ts provisions/mesh.ts provisions/index.ts --module NodeNext --moduleResolution NodeNext --target ES2022 --outDir dist",
|
||||
"typecheck": "tsc -p tsconfig.json",
|
||||
"test": "node --test --experimental-strip-types 'test/*.test.ts'"
|
||||
},
|
||||
"dependencies": {
|
||||
"@novox/mesh-sdk": "^0.1.0"
|
||||
},
|
||||
|
||||
@@ -1,486 +0,0 @@
|
||||
// How home-assistant's provisions step brings Home Assistant's integrations in line with what the
|
||||
// mesh bound: the MQTT integration to `mqtt-topic`, the Sonarr, Radarr and Lidarr integrations to
|
||||
// `sonarr-api`, `radarr-api` and `lidarr-api`. Pure logic over two seams — Home Assistant's config
|
||||
// flows (hass.ts) and the broker/apps — so it is tested against fakes (test/provisions.test.ts).
|
||||
//
|
||||
// The half that reads files and talks HTTP lives beside it (mesh.ts, hass.ts, probe.ts, index.ts).
|
||||
|
||||
import { createHash } from "node:crypto";
|
||||
|
||||
import type { Hass, SchemaField } from "./hass.js";
|
||||
import type { Probe } from "./probe.js";
|
||||
|
||||
/** What the mesh wrote at `binds.<provision>` (the controller's binding document). */
|
||||
export interface Binding {
|
||||
provision?: string;
|
||||
from?: string;
|
||||
at?: string;
|
||||
as?: string;
|
||||
serves?: Record<string, unknown>;
|
||||
}
|
||||
|
||||
/** How one provision came out. Never carries a credential. */
|
||||
export type Outcome =
|
||||
| { what: string; result: "unchanged"; note?: string }
|
||||
| { what: string; result: "written"; fields: string[]; note?: string }
|
||||
| { what: string; result: "equivalent"; note: string }
|
||||
| { what: string; result: "refused"; problem: string };
|
||||
|
||||
/** A port the binding serves, or undefined when it names none usable. */
|
||||
export function portOf(serves: Record<string, unknown> | undefined): number | undefined {
|
||||
const port = Number(serves?.port);
|
||||
return Number.isInteger(port) && port > 0 && port <= 65535 ? port : undefined;
|
||||
}
|
||||
|
||||
/** A host as it goes into a URL: an IPv6 literal bracketed. */
|
||||
export function urlHost(host: string): string {
|
||||
return host.includes(":") && !host.startsWith("[") ? `[${host}]` : host;
|
||||
}
|
||||
|
||||
/**
|
||||
* What this step last wrote, per target, as a digest: the only way to know "already as the mesh
|
||||
* says" for a credential Home Assistant will not show back. A sha256 over the target and the values,
|
||||
* never the values; kept in the module's own placed directory.
|
||||
*/
|
||||
export interface Marks {
|
||||
get(name: string): Promise<string | undefined>;
|
||||
set(name: string, digest: string): Promise<void>;
|
||||
}
|
||||
|
||||
export function digest(...parts: (string | number)[]): string {
|
||||
return createHash("sha256").update(parts.map(String).join("\u0000")).digest("hex");
|
||||
}
|
||||
|
||||
/** An error as text with the credential taken out, raw and URL-encoded. */
|
||||
export function scrub(err: unknown, ...secrets: (string | undefined)[]): string {
|
||||
let text = err instanceof Error ? err.message : String(err);
|
||||
for (const s of secrets) {
|
||||
if (!s) continue;
|
||||
for (const form of new Set([s, encodeURIComponent(s)])) text = text.split(form).join("***");
|
||||
}
|
||||
return text;
|
||||
}
|
||||
|
||||
/**
|
||||
* What a form would submit if a person pressed "submit" without touching it: each field's
|
||||
* suggested value (what Home Assistant pre-fills from the entry), else its default; a section's
|
||||
* fields nested under its name. The step lays only the connection fields over this, so every other
|
||||
* choice the entry carries is sent back exactly as Home Assistant showed it.
|
||||
*/
|
||||
export function formValues(schema: readonly SchemaField[] | null | undefined): Record<string, unknown> {
|
||||
const out: Record<string, unknown> = {};
|
||||
for (const field of schema ?? []) {
|
||||
if (Array.isArray(field.schema)) {
|
||||
out[field.name] = formValues(field.schema);
|
||||
continue;
|
||||
}
|
||||
const suggested = field.description?.suggested_value;
|
||||
if (suggested !== undefined && suggested !== null) out[field.name] = suggested;
|
||||
else if (field.default !== undefined) out[field.name] = field.default;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** Whether a form has a field of this name at its top level. */
|
||||
export function hasField(schema: readonly SchemaField[] | null | undefined, name: string): boolean {
|
||||
return (schema ?? []).some((f) => f.name === name);
|
||||
}
|
||||
|
||||
// ---- MQTT ----
|
||||
|
||||
// Home Assistant's MQTT integration, pointed at the broker the mesh bound — `mqtt-topic`.
|
||||
//
|
||||
// **Why a step.** Home Assistant keeps its broker, login and password in its MQTT config entry
|
||||
// (`.storage/core.config_entries`), not in a file the mesh could fill with `${bound:mqtt-topic:at}`.
|
||||
// So this reads the binding and the pair credential and makes the entry say the same thing, through
|
||||
// the MQTT integration's own reconfigure flow — the flow its "Reconfigure" button runs, which tests
|
||||
// the connection itself and saves nothing it could not connect with.
|
||||
//
|
||||
// **Only the connection, and only when it differs.** Broker, port, username, password. The protocol
|
||||
// version, client id, keepalive, TLS choices and discovery options the entry holds are sent back
|
||||
// exactly as Home Assistant pre-filled them. Whether the password already matches cannot be read
|
||||
// back (Home Assistant never shows a stored password), so the step keeps a digest of what it last
|
||||
// wrote: equal broker/port/username and an equal digest is "already as the mesh says".
|
||||
//
|
||||
// **Nothing loses its connection without someone seeing it.** Before Home Assistant is touched the
|
||||
// broker itself is asked whether it takes the delivered login (the provisioner creates it within
|
||||
// seconds of the grant): if not, nothing is written and the step fails saying why, and Home
|
||||
// Assistant keeps the login it has — the carried `luffy` on ace, which mosquitto keeps. If Home
|
||||
// Assistant's own connection test refuses the new settings, the flow saves nothing, and the step
|
||||
// fails with Home Assistant's reason. A login that may not subscribe to the discovery topics is said
|
||||
// as a warning: discovery would find nothing.
|
||||
|
||||
export const MQTT_PROVISION = "mqtt-topic";
|
||||
/** Home Assistant's discovery prefix, subscribed to whenever discovery is on (the default). */
|
||||
export const DISCOVERY_FILTER = "homeassistant/#";
|
||||
|
||||
export interface MqttWanted {
|
||||
host: string;
|
||||
port: number;
|
||||
username: string;
|
||||
password: string;
|
||||
}
|
||||
|
||||
export type Wanted = { ok: true; want: MqttWanted } | { ok: false; problem: string };
|
||||
|
||||
/** The broker, port and login the mesh says Home Assistant uses. */
|
||||
export function wantedMqtt(binding: Binding | undefined, credential: string | undefined): Wanted {
|
||||
if (!binding) return { ok: false, problem: `no binding for ${MQTT_PROVISION} was delivered — the mesh writes it before this step runs` };
|
||||
const host = typeof binding.at === "string" ? binding.at.trim() : "";
|
||||
if (!host) return { ok: false, problem: `the ${MQTT_PROVISION} binding names no host (at)` };
|
||||
const port = portOf(binding.serves);
|
||||
if (port === undefined) return { ok: false, problem: `the ${MQTT_PROVISION} binding serves no usable port (${String(binding.serves?.port)})` };
|
||||
const scheme = binding.serves?.scheme;
|
||||
if (scheme !== undefined && scheme !== "mqtt") {
|
||||
return { ok: false, problem: `the ${MQTT_PROVISION} binding serves scheme ${String(scheme)}; this step writes plain MQTT` };
|
||||
}
|
||||
const username = typeof binding.as === "string" ? binding.as.trim() : "";
|
||||
if (!username) return { ok: false, problem: `the ${MQTT_PROVISION} binding names no login (as)` };
|
||||
const password = (credential ?? "").replace(/\n$/, "");
|
||||
if (!password) return { ok: false, problem: `the ${MQTT_PROVISION} credential is empty or was not delivered` };
|
||||
return { ok: true, want: { host, port, username, password } };
|
||||
}
|
||||
|
||||
export interface MqttDeps {
|
||||
hass: Hass;
|
||||
probe: Probe;
|
||||
marks: Marks;
|
||||
}
|
||||
|
||||
const markFor = (entryId: string, w: MqttWanted): string => digest("mqtt", entryId, w.host, w.port, w.username, w.password);
|
||||
|
||||
/** Bring Home Assistant's MQTT entry in line with the mesh. Never throws: every failure is an outcome. */
|
||||
export async function reconcileMqtt(deps: MqttDeps, binding: Binding | undefined, credential: string | undefined): Promise<Outcome> {
|
||||
const what = "mqtt";
|
||||
const w = wantedMqtt(binding, credential);
|
||||
if ("problem" in w) return { what, result: "refused", problem: w.problem };
|
||||
const want = w.want;
|
||||
|
||||
// The broker first: a login it does not take is never written into Home Assistant.
|
||||
let note: string | undefined;
|
||||
try {
|
||||
const probe = await deps.probe(want.host, want.port, want.username, want.password, DISCOVERY_FILTER);
|
||||
if (probe.connack === 4 || probe.connack === 5) {
|
||||
return {
|
||||
what,
|
||||
result: "refused",
|
||||
problem:
|
||||
`the broker at ${want.host}:${want.port} does not (yet) take the login ${want.username} with the delivered ` +
|
||||
`password (CONNACK ${probe.connack}); mosquitto's provisioner creates it from the grant — nothing was ` +
|
||||
`written, and Home Assistant keeps the broker login it has`,
|
||||
};
|
||||
}
|
||||
if (probe.connack !== 0) {
|
||||
return { what, result: "refused", problem: `the broker at ${want.host}:${want.port} answered CONNACK ${probe.connack}; nothing was written` };
|
||||
}
|
||||
if (probe.suback === 0x80) {
|
||||
note =
|
||||
`warning: ${want.username} may not subscribe to ${DISCOVERY_FILTER} — MQTT discovery will find nothing; ` +
|
||||
`grant it with the mqtt-topic contribution's \`topics\``;
|
||||
}
|
||||
} catch (err) {
|
||||
return {
|
||||
what,
|
||||
result: "refused",
|
||||
problem: `the broker at ${want.host}:${want.port} could not be asked: ${scrub(err, want.password)}; nothing was written`,
|
||||
};
|
||||
}
|
||||
|
||||
try {
|
||||
const entries = (await deps.hass.entries("mqtt")).filter((e) => e.domain === "mqtt");
|
||||
if (entries.length > 1) {
|
||||
return { what, result: "refused", problem: `Home Assistant has ${entries.length} MQTT entries; which one the mesh owns is not guessed` };
|
||||
}
|
||||
if (entries.length === 0) return await createEntry(deps, want, note);
|
||||
|
||||
const entry = entries[0];
|
||||
const flow = await deps.hass.startFlow("mqtt", entry.entry_id);
|
||||
if (flow.type !== "form" || !flow.flow_id || !flow.data_schema) {
|
||||
if (flow.flow_id) await deps.hass.abortFlow(flow.flow_id);
|
||||
return { what, result: "refused", problem: `Home Assistant's MQTT reconfigure flow answered ${flow.type}${flow.reason ? ` (${flow.reason})` : ""}` };
|
||||
}
|
||||
const current = formValues(flow.data_schema);
|
||||
const fields: string[] = [];
|
||||
if (String(current.broker ?? "") !== want.host) fields.push("broker");
|
||||
if (Number(current.port ?? 0) !== want.port) fields.push("port");
|
||||
if (String(current.username ?? "") !== want.username) fields.push("username");
|
||||
if ((await deps.marks.get("mqtt")) !== markFor(entry.entry_id, want)) fields.push("password");
|
||||
if (fields.length === 0) {
|
||||
await deps.hass.abortFlow(flow.flow_id);
|
||||
return note ? { what, result: "unchanged", note } : { what, result: "unchanged" };
|
||||
}
|
||||
|
||||
const saved = await deps.hass.stepFlow(flow.flow_id, {
|
||||
...current,
|
||||
broker: want.host,
|
||||
port: want.port,
|
||||
username: want.username,
|
||||
password: want.password,
|
||||
});
|
||||
if (saved.type === "abort" && saved.reason === "reconfigure_successful") {
|
||||
await deps.marks.set("mqtt", markFor(entry.entry_id, want));
|
||||
return { what, result: "written", fields, ...(note ? { note } : {}) };
|
||||
}
|
||||
if (saved.flow_id) await deps.hass.abortFlow(saved.flow_id);
|
||||
return {
|
||||
what,
|
||||
result: "refused",
|
||||
problem:
|
||||
`Home Assistant's own connection test refused ${want.username}@${want.host}:${want.port} ` +
|
||||
`(${describe(saved)}); its MQTT entry is unchanged`,
|
||||
};
|
||||
} catch (err) {
|
||||
return { what, result: "refused", problem: scrub(err, want.password) };
|
||||
}
|
||||
}
|
||||
|
||||
/** A fresh Home Assistant has no MQTT entry: made through the integration's user flow. */
|
||||
async function createEntry(deps: MqttDeps, want: MqttWanted, note?: string): Promise<Outcome> {
|
||||
const what = "mqtt";
|
||||
let flow = await deps.hass.startFlow("mqtt");
|
||||
if (flow.type === "form" && flow.step_id !== "broker" && flow.flow_id) {
|
||||
// Anything before the broker form (none outside the Supervisor) is not this step's to answer.
|
||||
await deps.hass.abortFlow(flow.flow_id);
|
||||
return { what, result: "refused", problem: `Home Assistant's MQTT user flow asked ${flow.step_id} before the broker` };
|
||||
}
|
||||
if (flow.type !== "form" || !flow.flow_id) {
|
||||
return { what, result: "refused", problem: `Home Assistant's MQTT user flow answered ${describe(flow)}` };
|
||||
}
|
||||
const shown = formValues(flow.data_schema);
|
||||
// A new entry's form has no value for its two certificate choices (a reconfigure pre-fills them
|
||||
// from the entry): plain MQTT, so neither a CA nor a client certificate.
|
||||
const other = (shown.other_settings ?? {}) as Record<string, unknown>;
|
||||
if (flow.data_schema?.some((f) => f.name === "other_settings")) {
|
||||
shown.other_settings = { set_ca_cert: "off", set_client_cert: false, ...other };
|
||||
}
|
||||
flow = await deps.hass.stepFlow(flow.flow_id, {
|
||||
...shown,
|
||||
broker: want.host,
|
||||
port: want.port,
|
||||
username: want.username,
|
||||
password: want.password,
|
||||
});
|
||||
if (flow.type === "create_entry") {
|
||||
const id = (flow.result as { entry_id?: string } | undefined)?.entry_id;
|
||||
if (id) await deps.marks.set("mqtt", markFor(id, want));
|
||||
return { what, result: "written", fields: ["entry"], ...(note ? { note } : {}) };
|
||||
}
|
||||
if (flow.flow_id) await deps.hass.abortFlow(flow.flow_id);
|
||||
return { what, result: "refused", problem: `Home Assistant refused a new MQTT entry for ${want.host}:${want.port} (${describe(flow)})` };
|
||||
}
|
||||
|
||||
export function describe(r: { type: string; reason?: string; errors?: Record<string, string> | null }): string {
|
||||
const errors = r.errors ? Object.entries(r.errors).map(([k, v]) => `${k}: ${v}`).join(", ") : "";
|
||||
return [r.type, r.reason, errors].filter(Boolean).join(" — ");
|
||||
}
|
||||
|
||||
// ---- Sonarr, Radarr, Lidarr ----
|
||||
|
||||
// Home Assistant's Sonarr, Radarr and Lidarr integrations, pointed at the apps the mesh bound —
|
||||
// `sonarr-api`, `radarr-api`, `lidarr-api` (their providers: mesh-catalog #156).
|
||||
//
|
||||
// **What Home Assistant lets anyone change, and what it does not.** Each integration keeps a URL and
|
||||
// an API key in its config entry. None of the three has a reconfigure flow: Home Assistant changes
|
||||
// them only through the flow its UI runs —
|
||||
// - a **user flow** makes a new entry (validated against the app);
|
||||
// - a **reauth flow**, which Home Assistant starts by itself when the app refuses the key it holds,
|
||||
// takes a new key (Sonarr) or a new URL and key (Radarr, Lidarr);
|
||||
// - anything else — the URL of a working entry — only by removing the integration and adding it
|
||||
// again, which throws away its entities' names, areas and history links. **This step never
|
||||
// removes an entry.**
|
||||
// So, per app:
|
||||
// 1. The bound key is tried against the bound app first. Refused, nothing is written: until the
|
||||
// operator accepts the app's own key for this pair, the mesh delivers a value it minted, which
|
||||
// no Servarr app takes (novox/hq ADR 0092) — the failure names the `secret accept` that fixes it.
|
||||
// 2. No entry: one is made through the user flow.
|
||||
// 3. A reauth flow Home Assistant started for the entry: finished with the bound key (and URL,
|
||||
// where the integration's reauth asks for one).
|
||||
// 4. An entry whose URL (read from the device the integration registered, `configuration_url`)
|
||||
// is the bound one and which is loaded: already as the mesh says. The key needs no digest here:
|
||||
// a Servarr app has one key, so an entry loaded against the app holds the key the app took.
|
||||
// 5. A working entry at a different URL that reaches **the same app** — the same process, by the
|
||||
// app's own status (start time, data folder, version) — is left as it is and said: ace's entries
|
||||
// say `127.0.0.1:<port>` and the binding says `ace.internal:<port>`, one Sonarr either way.
|
||||
// 6. Anything else is refused, loudly, with what the operator can do; nothing is removed.
|
||||
|
||||
|
||||
export interface ServarrApp {
|
||||
/** The integration's domain, also the app. */
|
||||
domain: "sonarr" | "radarr" | "lidarr";
|
||||
/** The provision it is required as: the `requires`, `binds` and `secrets` key. */
|
||||
provision: string;
|
||||
/** The app's status endpoint: answers 401 to a wrong key, and says which process answered. */
|
||||
statusPath: string;
|
||||
}
|
||||
|
||||
export const APPS: readonly ServarrApp[] = [
|
||||
{ domain: "sonarr", provision: "sonarr-api", statusPath: "/api/v3/system/status" },
|
||||
{ domain: "radarr", provision: "radarr-api", statusPath: "/api/v3/system/status" },
|
||||
{ domain: "lidarr", provision: "lidarr-api", statusPath: "/api/v1/system/status" },
|
||||
];
|
||||
|
||||
/** The HTTP the step needs toward the apps, so a test can stand fakes in. */
|
||||
export interface Http {
|
||||
fetch(url: string, init?: { method?: string; headers?: Record<string, string> }): Promise<{ status: number; text(): Promise<string> }>;
|
||||
}
|
||||
|
||||
export type AppWanted = { ok: true; url: string; key: string; from: string } | { ok: false; problem: string };
|
||||
|
||||
/** The URL and key the mesh says Home Assistant uses for this app. */
|
||||
export function wantedApp(spec: ServarrApp, binding: Binding | undefined, credential: string | undefined): AppWanted {
|
||||
if (!binding) return { ok: false, problem: `no binding for ${spec.provision} was delivered — the mesh writes it before this step runs` };
|
||||
const at = typeof binding.at === "string" ? binding.at.trim() : "";
|
||||
if (!at) return { ok: false, problem: `the ${spec.provision} binding names no host (at)` };
|
||||
const port = portOf(binding.serves);
|
||||
if (port === undefined) return { ok: false, problem: `the ${spec.provision} binding serves no usable port (${String(binding.serves?.port)})` };
|
||||
const scheme = typeof binding.serves?.scheme === "string" && binding.serves.scheme ? binding.serves.scheme : "http";
|
||||
if (scheme !== "http" && scheme !== "https") return { ok: false, problem: `the ${spec.provision} binding serves scheme ${scheme}` };
|
||||
const base = typeof binding.serves?.["url-base"] === "string" ? String(binding.serves["url-base"]).trim().replace(/^\/+|\/+$/g, "") : "";
|
||||
const key = (credential ?? "").trim();
|
||||
if (!key) return { ok: false, problem: `the ${spec.provision} credential is empty or was not delivered` };
|
||||
return {
|
||||
ok: true,
|
||||
url: `${scheme}://${urlHost(at)}:${port}${base ? `/${base}` : ""}`,
|
||||
key,
|
||||
from: typeof binding.from === "string" ? binding.from : "",
|
||||
};
|
||||
}
|
||||
|
||||
/** Two URLs naming the same place: scheme, host, port (explicit or default) and base path. */
|
||||
export function sameUrl(a: string | null | undefined, b: string): boolean {
|
||||
if (!a) return false;
|
||||
try {
|
||||
const x = new URL(a);
|
||||
const y = new URL(b);
|
||||
const port = (u: URL) => u.port || (u.protocol === "https:" ? "443" : "80");
|
||||
const path = (u: URL) => u.pathname.replace(/\/+$/, "");
|
||||
return x.protocol === y.protocol && x.hostname.toLowerCase() === y.hostname.toLowerCase() && port(x) === port(y) && path(x) === path(y);
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
type Status = { taken: true; status: Record<string, unknown> } | { taken: false };
|
||||
|
||||
/** The app's status with this key: `taken: false` when it refuses the key; throws when it cannot be asked. */
|
||||
export async function appStatus(http: Http, spec: ServarrApp, url: string, key: string): Promise<Status> {
|
||||
const res = await http.fetch(`${url.replace(/\/+$/, "")}${spec.statusPath}`, {
|
||||
method: "GET",
|
||||
headers: { "X-Api-Key": key, Accept: "application/json" },
|
||||
});
|
||||
if (res.status === 401 || res.status === 403) return { taken: false };
|
||||
if (res.status < 200 || res.status >= 300) throw new Error(`${spec.domain} answered ${res.status} at ${spec.statusPath}`);
|
||||
return { taken: true, status: JSON.parse(await res.text()) as Record<string, unknown> };
|
||||
}
|
||||
|
||||
/** Whether two status answers came from one running app. */
|
||||
export function sameInstance(a: Record<string, unknown>, b: Record<string, unknown>): boolean {
|
||||
const facts = ["startTime", "appData", "version"];
|
||||
return facts.every((k) => a[k] !== undefined && a[k] !== null && a[k] === b[k]);
|
||||
}
|
||||
|
||||
/** The remedy for a refused key, in the controller's words (ADR 0092). */
|
||||
export function acceptRemedy(spec: ServarrApp, from: string): string {
|
||||
return (
|
||||
`${spec.domain} refuses the ${spec.provision} credential the mesh delivered, so nothing was written into ` +
|
||||
`Home Assistant. A Servarr app has one API key and the mesh cannot make it: accept ${spec.domain}'s own key ` +
|
||||
`for this pair — \`secret accept <this node> home-assistant ${spec.provision} --provider ${from || "<its node>"} ` +
|
||||
`--from <file holding ${spec.domain}'s ApiKey>\``
|
||||
);
|
||||
}
|
||||
|
||||
export interface ServarrDeps {
|
||||
hass: Hass;
|
||||
http: Http;
|
||||
}
|
||||
|
||||
/** The input a Servarr form takes: what it shows, with the URL (where asked) and the key laid over. */
|
||||
function servarrInput(schema: readonly SchemaField[] | null | undefined, url: string, key: string): Record<string, unknown> {
|
||||
const input = formValues(schema);
|
||||
if (hasField(schema, "url")) input.url = url;
|
||||
if (hasField(schema, "api_key")) input.api_key = key;
|
||||
return input;
|
||||
}
|
||||
|
||||
/** Bring Home Assistant's entry for one app in line with the mesh. Never throws. */
|
||||
export async function reconcileApp(deps: ServarrDeps, spec: ServarrApp, binding: Binding | undefined, credential: string | undefined): Promise<Outcome> {
|
||||
const what = spec.domain;
|
||||
const w = wantedApp(spec, binding, credential);
|
||||
if ("problem" in w) return { what, result: "refused", problem: w.problem };
|
||||
|
||||
let bound: Status;
|
||||
try {
|
||||
bound = await appStatus(deps.http, spec, w.url, w.key);
|
||||
} catch (err) {
|
||||
return { what, result: "refused", problem: `${spec.domain} could not be asked at ${w.url}: ${scrub(err, w.key)}` };
|
||||
}
|
||||
if (!bound.taken) return { what, result: "refused", problem: acceptRemedy(spec, w.from) };
|
||||
|
||||
try {
|
||||
const entries = (await deps.hass.entries(spec.domain)).filter((e) => e.domain === spec.domain);
|
||||
if (entries.length > 1) {
|
||||
return { what, result: "refused", problem: `Home Assistant has ${entries.length} ${spec.domain} entries; which one the mesh owns is not guessed` };
|
||||
}
|
||||
|
||||
// No entry: made, through the integration's own user flow, which validates the key itself.
|
||||
if (entries.length === 0) {
|
||||
const flow = await deps.hass.startFlow(spec.domain);
|
||||
if (flow.type !== "form" || !flow.flow_id) return { what, result: "refused", problem: `Home Assistant's ${spec.domain} user flow answered ${describe(flow)}` };
|
||||
const made = await deps.hass.stepFlow(flow.flow_id, servarrInput(flow.data_schema, w.url, w.key));
|
||||
if (made.type === "create_entry") return { what, result: "written", fields: ["entry"] };
|
||||
if (made.flow_id) await deps.hass.abortFlow(made.flow_id);
|
||||
return { what, result: "refused", problem: `Home Assistant refused a new ${spec.domain} entry at ${w.url} (${describe(made)})` };
|
||||
}
|
||||
|
||||
const entry = entries[0];
|
||||
if (entry.disabled_by) return { what, result: "unchanged", note: `the ${spec.domain} entry is disabled (by ${entry.disabled_by}); left alone` };
|
||||
|
||||
// A reauth Home Assistant started because the app refused its key: finished with the bound one.
|
||||
const reauth = (await deps.hass.flowsInProgress()).find(
|
||||
(f) => f.handler === spec.domain && f.context?.source === "reauth" && f.context?.entry_id === entry.entry_id,
|
||||
);
|
||||
if (reauth) {
|
||||
let step = await deps.hass.stepFlow(reauth.flow_id, {}); // reauth_confirm: a confirmation, no fields
|
||||
if (step.type === "form" && step.flow_id && step.step_id !== "reauth_confirm") {
|
||||
const input = servarrInput(step.data_schema, w.url, w.key);
|
||||
const fields = ["api_key", ...(hasField(step.data_schema, "url") ? ["url"] : [])];
|
||||
step = await deps.hass.stepFlow(step.flow_id, input);
|
||||
if (step.type === "abort" && step.reason === "reauth_successful") return { what, result: "written", fields };
|
||||
}
|
||||
return { what, result: "refused", problem: `Home Assistant's ${spec.domain} reauth did not take the bound key and URL (${describe(step)})` };
|
||||
}
|
||||
|
||||
const device = (await deps.hass.devices()).find((d) => d.config_entries?.includes(entry.entry_id) && d.configuration_url);
|
||||
const current = device?.configuration_url ?? undefined;
|
||||
if (entry.state === "loaded" && sameUrl(current, w.url)) return { what, result: "unchanged" };
|
||||
|
||||
if (entry.state === "loaded" && current) {
|
||||
let there: Status | undefined;
|
||||
try {
|
||||
there = await appStatus(deps.http, spec, current, w.key);
|
||||
} catch {
|
||||
there = undefined;
|
||||
}
|
||||
if (there?.taken && sameInstance(there.status, bound.status)) {
|
||||
return {
|
||||
what,
|
||||
result: "equivalent",
|
||||
note:
|
||||
`Home Assistant reaches ${spec.domain} at ${current}, the same running app the mesh bound at ${w.url}; ` +
|
||||
`Home Assistant has no way to change a working ${spec.domain} entry's URL short of removing it, so it is left as it is`,
|
||||
};
|
||||
}
|
||||
}
|
||||
return {
|
||||
what,
|
||||
result: "refused",
|
||||
problem:
|
||||
`Home Assistant's ${spec.domain} entry (${entry.state ?? "unknown state"}) points at ${current ?? "an unknown URL"}, ` +
|
||||
`not the ${spec.domain} the mesh bound at ${w.url}. Home Assistant only lets a working entry's URL change by ` +
|
||||
`removing and re-adding the integration, which this step never does: remove it in Home Assistant ` +
|
||||
`(Settings → Devices & services → ${spec.domain}) and the next run adds it at the bound URL`,
|
||||
};
|
||||
} catch (err) {
|
||||
return { what, result: "refused", problem: scrub(err, w.key) };
|
||||
}
|
||||
}
|
||||
@@ -1,160 +0,0 @@
|
||||
// Home Assistant's own configuration API, as the provisions step uses it — the supported way to
|
||||
// change an integration's connection. Home Assistant keeps every integration in
|
||||
// `.storage/core.config_entries`, a file it owns and rewrites; the mesh may not write it, and it is
|
||||
// not a file the mesh could merge into. What Home Assistant offers instead is the same thing its UI
|
||||
// uses: **config flows** over REST (`/api/config/config_entries/flow`) — a user flow creates an
|
||||
// entry, a reconfigure flow changes one, a reauth flow (which Home Assistant starts itself when a
|
||||
// credential stops working) replaces its credential — each validated by the integration's own
|
||||
// connection test before anything is saved. The two things REST does not answer (which flows Home
|
||||
// Assistant has started, which device an entry made) come over its WebSocket API.
|
||||
//
|
||||
// Nothing here reads `.storage`. Authenticated with the module's accepted long-lived access token.
|
||||
|
||||
/** A config entry as `GET /api/config/config_entries/entry` lists it — no data, no credentials. */
|
||||
export interface ConfigEntry {
|
||||
entry_id: string;
|
||||
domain: string;
|
||||
title?: string;
|
||||
source?: string;
|
||||
state?: string;
|
||||
disabled_by?: string | null;
|
||||
}
|
||||
|
||||
/** One field of a flow's form, as Home Assistant serializes a voluptuous schema. */
|
||||
export interface SchemaField {
|
||||
name: string;
|
||||
type?: string;
|
||||
required?: boolean;
|
||||
optional?: boolean;
|
||||
default?: unknown;
|
||||
description?: { suggested_value?: unknown } | null;
|
||||
/** A section (`type: "expandable"`) carries its own fields. */
|
||||
schema?: SchemaField[];
|
||||
}
|
||||
|
||||
/** What a flow answered: another form, an entry made, or the flow ended (abort). */
|
||||
export interface FlowResult {
|
||||
type: string;
|
||||
flow_id?: string;
|
||||
handler?: string;
|
||||
step_id?: string;
|
||||
data_schema?: SchemaField[] | null;
|
||||
errors?: Record<string, string> | null;
|
||||
reason?: string;
|
||||
result?: { entry_id?: string } | unknown;
|
||||
}
|
||||
|
||||
/** A flow in progress that Home Assistant started itself (a reauth, a discovery). */
|
||||
export interface FlowProgress {
|
||||
flow_id: string;
|
||||
handler: string;
|
||||
step_id?: string;
|
||||
context?: { source?: string; entry_id?: string };
|
||||
}
|
||||
|
||||
/** A device from the device registry; an integration names where its app is as configuration_url. */
|
||||
export interface DeviceEntry {
|
||||
id: string;
|
||||
config_entries?: string[];
|
||||
configuration_url?: string | null;
|
||||
}
|
||||
|
||||
export interface Hass {
|
||||
entries(domain: string): Promise<ConfigEntry[]>;
|
||||
/** A user flow for `handler`, or — given an entry — a reconfigure flow for it. */
|
||||
startFlow(handler: string, entryId?: string): Promise<FlowResult>;
|
||||
stepFlow(flowId: string, input: Record<string, unknown>): Promise<FlowResult>;
|
||||
abortFlow(flowId: string): Promise<void>;
|
||||
flowsInProgress(): Promise<FlowProgress[]>;
|
||||
devices(): Promise<DeviceEntry[]>;
|
||||
}
|
||||
|
||||
/** Home Assistant over HTTP: REST for entries and flows, one short WebSocket session per question. */
|
||||
export class HassApi implements Hass {
|
||||
private readonly base: string;
|
||||
|
||||
constructor(url: string, private readonly token: string) {
|
||||
this.base = url.replace(/\/$/, "");
|
||||
}
|
||||
|
||||
private async rest(method: string, path: string, body?: unknown): Promise<unknown> {
|
||||
const res = await fetch(`${this.base}${path}`, {
|
||||
method,
|
||||
headers: {
|
||||
Authorization: `Bearer ${this.token}`,
|
||||
Accept: "application/json",
|
||||
...(body !== undefined ? { "Content-Type": "application/json" } : {}),
|
||||
},
|
||||
body: body !== undefined ? JSON.stringify(body) : undefined,
|
||||
});
|
||||
const text = await res.text();
|
||||
if (!res.ok) {
|
||||
// Home Assistant's error text names fields, never echoes their values.
|
||||
throw new Error(`Home Assistant ${method} ${path} answered ${res.status}${text ? `: ${text.slice(0, 200)}` : ""}`);
|
||||
}
|
||||
return text ? (JSON.parse(text) as unknown) : undefined;
|
||||
}
|
||||
|
||||
async entries(domain: string): Promise<ConfigEntry[]> {
|
||||
return ((await this.rest("GET", `/api/config/config_entries/entry?domain=${encodeURIComponent(domain)}`)) ??
|
||||
[]) as ConfigEntry[];
|
||||
}
|
||||
|
||||
async startFlow(handler: string, entryId?: string): Promise<FlowResult> {
|
||||
return (await this.rest("POST", "/api/config/config_entries/flow", {
|
||||
handler,
|
||||
show_advanced_options: true,
|
||||
...(entryId ? { entry_id: entryId } : {}),
|
||||
})) as FlowResult;
|
||||
}
|
||||
|
||||
async stepFlow(flowId: string, input: Record<string, unknown>): Promise<FlowResult> {
|
||||
return (await this.rest("POST", `/api/config/config_entries/flow/${encodeURIComponent(flowId)}`, input)) as FlowResult;
|
||||
}
|
||||
|
||||
async abortFlow(flowId: string): Promise<void> {
|
||||
await this.rest("DELETE", `/api/config/config_entries/flow/${encodeURIComponent(flowId)}`).catch(() => undefined);
|
||||
}
|
||||
|
||||
async flowsInProgress(): Promise<FlowProgress[]> {
|
||||
return (await this.ws("config_entries/flow/progress")) as FlowProgress[];
|
||||
}
|
||||
|
||||
async devices(): Promise<DeviceEntry[]> {
|
||||
return (await this.ws("config/device_registry/list")) as DeviceEntry[];
|
||||
}
|
||||
|
||||
/** One WebSocket command: connect, authenticate, ask, close. */
|
||||
private ws(type: string): Promise<unknown> {
|
||||
const url = `${this.base.replace(/^http/, "ws")}/api/websocket`;
|
||||
return new Promise((resolve, reject) => {
|
||||
const socket = new WebSocket(url);
|
||||
const timer = setTimeout(() => {
|
||||
socket.close();
|
||||
reject(new Error(`Home Assistant's WebSocket did not answer ${type} within 30s`));
|
||||
}, 30_000);
|
||||
const done = (fn: () => void): void => {
|
||||
clearTimeout(timer);
|
||||
socket.close();
|
||||
fn();
|
||||
};
|
||||
socket.onerror = () => done(() => reject(new Error(`Home Assistant's WebSocket at ${url} failed`)));
|
||||
socket.onmessage = (event: { data: unknown }) => {
|
||||
const msg = JSON.parse(String(event.data)) as {
|
||||
type: string;
|
||||
id?: number;
|
||||
success?: boolean;
|
||||
result?: unknown;
|
||||
error?: { message?: string };
|
||||
};
|
||||
if (msg.type === "auth_required") socket.send(JSON.stringify({ type: "auth", access_token: this.token }));
|
||||
else if (msg.type === "auth_invalid") done(() => reject(new Error("Home Assistant refused the token")));
|
||||
else if (msg.type === "auth_ok") socket.send(JSON.stringify({ id: 1, type }));
|
||||
else if (msg.type === "result" && msg.id === 1) {
|
||||
if (msg.success) done(() => resolve(msg.result));
|
||||
else done(() => reject(new Error(`Home Assistant ${type}: ${msg.error?.message ?? "failed"}`)));
|
||||
}
|
||||
};
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -1,84 +0,0 @@
|
||||
// home-assistant's provisions step — run once by the host after Home Assistant starts, and again
|
||||
// whenever a binding or pair credential it reads changes (the container's `restart-on`, novox/hq
|
||||
// ADR 0099). It points Home Assistant's MQTT integration at the `mqtt-topic` broker and its Sonarr,
|
||||
// Radarr and Lidarr integrations at the `sonarr-api`, `radarr-api` and `lidarr-api` apps, through
|
||||
// Home Assistant's own config flows (connections.ts). It connects to no mesh broker.
|
||||
//
|
||||
// Exits non-zero when anything could not be put right, so the node reports the step failed and the
|
||||
// host runs it again on the next apply. Declared last in the manifest, so its failing gates nothing
|
||||
// else of home-assistant's (novox/hq ADR 0136). Never prints a key or password.
|
||||
|
||||
import { join } from "node:path";
|
||||
|
||||
import { APPS, MQTT_PROVISION, reconcileApp, reconcileMqtt, type Outcome } from "./connections.js";
|
||||
import { HassApi } from "./hass.js";
|
||||
import { marksIn, readBinding, readIfThere } from "./mesh.js";
|
||||
import { probeBroker } from "./probe.js";
|
||||
|
||||
const dir = process.env.MESH_PROVISIONS_DIR ?? "/run/provisions";
|
||||
const url = process.env.MESH_HOMEASSISTANT_URL ?? "http://127.0.0.1:8123";
|
||||
const token = (await readIfThere(process.env.MESH_HOMEASSISTANT_TOKEN_FILE))?.trim() ?? "";
|
||||
const marks = marksIn(process.env.MESH_WRITTEN_DIR ?? "/var/lib/home-assistant-provisions");
|
||||
const waitSeconds = Number(process.env.MESH_HOMEASSISTANT_WAIT_SECONDS ?? "300");
|
||||
|
||||
if (!token) {
|
||||
console.error("[hass-provisions] no Home Assistant token — home-assistant's own `token` secret has not been accepted");
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
/** Home Assistant answers /api/ with 200 once it is up and the token is good. */
|
||||
async function ready(): Promise<boolean> {
|
||||
const until = Date.now() + waitSeconds * 1000;
|
||||
for (;;) {
|
||||
try {
|
||||
const res = await fetch(`${url.replace(/\/$/, "")}/api/`, { headers: { Authorization: `Bearer ${token}` } });
|
||||
if (res.status === 200) return true;
|
||||
if (res.status === 401 || res.status === 403) {
|
||||
console.error("[hass-provisions] Home Assistant refuses the token — accept a long-lived access token it issued");
|
||||
return false;
|
||||
}
|
||||
} catch {
|
||||
// not listening yet
|
||||
}
|
||||
if (Date.now() >= until) return false;
|
||||
await new Promise((r) => setTimeout(r, 3000));
|
||||
}
|
||||
}
|
||||
|
||||
if (!(await ready())) {
|
||||
console.error(`[hass-provisions] Home Assistant did not answer at ${url} within ${waitSeconds}s`);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
const hass = new HassApi(url, token);
|
||||
const read = async (p: string) => [await readBinding(join(dir, `${p}.json`)), await readIfThere(join(dir, `${p}.secret`))] as const;
|
||||
|
||||
const outcomes: Outcome[] = [];
|
||||
{
|
||||
const [binding, secret] = await read(MQTT_PROVISION);
|
||||
outcomes.push(await reconcileMqtt({ hass, probe: probeBroker, marks }, binding, secret));
|
||||
}
|
||||
for (const spec of APPS) {
|
||||
const [binding, secret] = await read(spec.provision);
|
||||
outcomes.push(await reconcileApp({ hass, http: { fetch: (u, init) => fetch(u, init) } }, spec, binding, secret));
|
||||
}
|
||||
|
||||
let failed = 0;
|
||||
for (const o of outcomes) {
|
||||
switch (o.result) {
|
||||
case "unchanged":
|
||||
console.log(`[hass-provisions] ${o.what}: already as the mesh says${o.note ? ` — ${o.note}` : ""}`);
|
||||
break;
|
||||
case "written":
|
||||
console.log(`[hass-provisions] ${o.what}: wrote ${o.fields.join(", ")}; Home Assistant's own test passed${o.note ? ` — ${o.note}` : ""}`);
|
||||
break;
|
||||
case "equivalent":
|
||||
console.log(`[hass-provisions] ${o.what}: ${o.note}`);
|
||||
break;
|
||||
case "refused":
|
||||
failed++;
|
||||
console.error(`[hass-provisions] ${o.what}: ${o.problem}`);
|
||||
break;
|
||||
}
|
||||
}
|
||||
process.exitCode = failed > 0 ? 1 : 0;
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user