Files
HermenixandClaude Opus 5 7eb9afdfa3 test(mcp): the store, the token verbs, and every way a request is refused
373 unit tests, up from 266.  Three files, split the way the modules are:
`test_mcp_authorizations.py` is standard library and touches no SDK,
`test_mcp_http.py` drives a real ASGI stack, and the additions to
`test_mcp_server.py` are about the command line now that it has
subcommands.

Four of these exist for properties that a refactor breaks silently rather
than loudly, which is the only reason they are worth their length:

* **the file never holds a token.**  A store that started writing the
  secret instead of its digest would pass every functional test here, so
  one test reads the bytes on disk and looks for the token and for a
  usable prefix of it.
* **a concurrent mint is not lost.**  Thirty threads mint into one table
  and all thirty tokens must still verify.  The atomic replace stops a
  torn read; it does nothing about two writers loading the same table and
  the second replacing the first's addition.  Without the flock this
  fails.
* **`--toolsets` before the subcommand survives it.**  argparse copies a
  subparser's namespace over the top-level one, so an ordinary default on
  the subcommand's copy would overwrite the value with `None` and
  `hhstream-mcp --toolsets=frames serve` would quietly serve all
  twenty-one tools.  `SUPPRESS` prevents it and this test notices if it
  goes.
* **a token verb never claims the transport.**  `mint` prints a secret on
  stdout, which on stdio *is* the transport, so `claim_transport` is
  monkeypatched to fail the test if it is ever reached.

The refusal tests assert the absence of information as much as the status
code: an empty body, no echo of the token in body or headers, and
unknown/revoked/expired arriving as one answer byte for byte -- telling
them apart would tell someone who guessed a real id that they had. An
unknown path is a 401 before a 404, so an unauthenticated caller does not
learn what is mounted; the token is checked before the Host, so it does
not learn the allowlist either.

`test_resources_are_not_narrowed_by_a_token` asserts a *limit*, on
purpose: a token scoped to `frames` can still read `hhstream://sessions`,
and that is written down rather than left for someone to discover.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KchcvnbfhhZhUHy83YL3Ya
2026-10-12 18:00:05 +00:00

1764 lines
78 KiB
Nix

{
lib,
config,
pkgs,
...
}:
# The option surface below is the interface described in docs/CONTRACT.md
# ("NixOS module surface"); the `config` block wires it to the two services
# named there.
let
cfg = config.services.hyprland-headless-stream;
# One private runtime directory, shared by both units: it holds the Wayland
# socket of the session and, by default, the published frame socket too.
# `RuntimeDirectoryPreserve` keeps it (and the Wayland socket) alive across a
# restart of either unit.
#
# The name is short on purpose, and the assertion below is what keeps it that
# way. A Unix socket address carries its path inside `sun_path`, which is 108
# bytes including the terminating NUL (linux/un.h), and the compositor puts
# its IPC sockets under this directory:
#
# <runtimeDir>/hypr/<HYPRLAND_INSTANCE_SIGNATURE>/.socket.sock requests
# <runtimeDir>/hypr/<HYPRLAND_INSTANCE_SIGNATURE>/.socket2.sock events
#
# Of that budget, 20 characters are fixed and the instance signature (~30) is
# Hyprland's to choose; this directory's name is the only part we control. At
# the previous name -- `/run/hyprland-headless-stream`, 29 characters -- the
# event socket did not fit and the compositor refused to bind it:
#
# ERR ]: Socket2 path is too long. (2) IPC will not work.
#
# The *request* socket kept answering `hyprctl` anyway (both ends agreed on a
# residual truncated path), which is why the broken event socket went
# unnoticed. docs/CONTRACT-sessions.md §5 freezes the ceiling at 25.
runtimeDirName = "hypr-stream";
runtimeDir = "/run/${runtimeDirName}";
runtimeDirMaxLength = 25;
# The broker's own runtime directory: its control socket and, when the
# pointer driver is enabled, the private socket the two speak over. Both
# paths are frozen in docs/CONTRACT-sessions.md §5, and the driver's command
# line is frozen with them, so this is a name for a constant rather than
# something a consumer may move.
brokerRuntimeDirName = "hhstream";
brokerRuntimeDir = "/run/${brokerRuntimeDirName}";
controlSocket = "${brokerRuntimeDir}/control.sock";
pointerSocket = "${brokerRuntimeDir}/pointer.sock";
liveSocket = "${brokerRuntimeDir}/live.sock";
# Addresses that mean "this listener answers on loopback only". The spelling
# `localhost` is included because it is what a person writes; it is not a
# resolution the module performs.
loopbackBinds = [ "127.0.0.1" "::1" "localhost" ];
socketDir = builtins.dirOf cfg.socketPath;
# Hyprland refuses `--socket` unless it is paired with `--wayland-fd` (that
# pair is the socket-handover path), so the socket name is not ours to choose:
# the compositor calls wl_display_add_socket_auto, which takes the first free
# `wayland-N` starting at 0.
#
# N is therefore not fixed. The runtime directory is preserved across restarts
# (`RuntimeDirectoryPreserve=yes`), so a crashed compositor leaves its
# `wayland-0` behind and the next start binds `wayland-1` — measured in the VM
# test, where the frame server then waited forever for a socket that would
# never exist. Neither unit may hardcode the name:
#
# * the compositor clears leftover sockets first (the directory is private to
# this session, so nothing else can own them) — that alone makes it
# `wayland-0` again, but the units below do not depend on that;
# * the server discovers whichever socket is actually there.
clearStaleSockets = pkgs.writeShellScript "hhstream-clear-stale-sockets" ''
for stale in "$XDG_RUNTIME_DIR"/wayland-* "$XDG_RUNTIME_DIR"/wayland-*.lock; do
if [ -e "$stale" ]; then
${lib.getExe' pkgs.coreutils "rm"} -f "$stale"
fi
done
'';
# Exit 0 once *any* Wayland socket is bound, and print its name so callers that
# want it do not have to glob again.
findSession = pkgs.writeShellScript "hhstream-find-session" ''
for _ in $(${lib.getExe' pkgs.coreutils "seq"} 1 300); do
for candidate in "$XDG_RUNTIME_DIR"/wayland-*; do
if [ -S "$candidate" ]; then
echo "''${candidate##*/}"
exit 0
fi
done
${lib.getExe' pkgs.coreutils "sleep"} 0.1
done
echo "no Wayland socket in $XDG_RUNTIME_DIR after 30s; is the compositor up?" >&2
exit 1
'';
# Open the compositor's IPC directory to its own group.
#
# MEASURED, in checks/vm-ipc.nix, which is the check that exists to find
# exactly this:
#
# drwxr-x--- hhstream hhstream /run/hypr-stream
# drwx------ hhstream hhstream /run/hypr-stream/hypr <-- 0700
# srw-rw---- hhstream hhstream /run/hypr-stream/stream.sock
# srwxrwx--- hhstream hhstream /run/hypr-stream/wayland-1
#
# The unit's `UMask=0007` reaches everything the compositor creates with a
# permissive mode -- the Wayland socket is group-accessible, which is how a
# launched application connects at all -- but Hyprland creates its *instance*
# directory with `S_IRWXU`, i.e. 0700 with no umask left to subtract. So the
# request and event sockets underneath it are reachable by `hhstream` and by
# nobody else.
#
# The broker runs as the operator's account with `hhstream` as a supplementary
# group, deliberately (it starts processes that must be the operator's). It
# therefore could not open the IPC directory at all, and the symptom was not
# an error: `HyprlandIPC.discover` raised `CompositorUnavailable`, the broker
# degraded exactly as it is designed to, and every session got
# `container: degraded` while `container.list` said `compositor: absent`. A
# whole capability silently absent, on a machine where nothing looked wrong.
#
# Group access, not world: the directory stays 0750 and the sockets 0660, so
# this grants the compositor's own group what it already has on the Wayland
# socket beside it, and nothing more.
#
# Run only when the broker is enabled (nothing else needs the IPC sockets),
# and allowed to fail the unit: a compositor whose IPC the broker cannot
# reach is a session with no containers and no pointer, and discovering that
# from a half-working desktop is how this went unnoticed in the first place.
openIpcDirectory = pkgs.writeShellScript "hhstream-open-ipc-directory" ''
set -eu
hypr="$XDG_RUNTIME_DIR/hypr"
for _ in $(${lib.getExe' pkgs.coreutils "seq"} 1 300); do
if [ -n "$(${lib.getExe' pkgs.coreutils "ls"} -1 "$hypr" 2>/dev/null)" ]; then
break
fi
${lib.getExe' pkgs.coreutils "sleep"} 0.1
done
if [ ! -d "$hypr" ]; then
echo "no $hypr after 30s: the compositor bound no IPC socket" >&2
exit 1
fi
${lib.getExe' pkgs.coreutils "chmod"} 0750 "$hypr"
for instance in "$hypr"/*; do
[ -d "$instance" ] || continue
${lib.getExe' pkgs.coreutils "chmod"} 0750 "$instance"
for sock in "$instance"/.socket.sock "$instance"/.socket2.sock; do
[ -S "$sock" ] || continue
${lib.getExe' pkgs.coreutils "chmod"} 0660 "$sock"
done
${lib.getExe' pkgs.coreutils "ls"} -la "$instance"
done
'';
# The server needs WAYLAND_DISPLAY pointing at the socket the compositor
# actually bound. This cannot be an `Environment=` line, because the name is
# only known once the compositor is up — systemd's ExecStartPre cannot export
# into the main process.
execServer = pkgs.writeShellScript "hhstream-exec-server" ''
for candidate in "$XDG_RUNTIME_DIR"/wayland-*; do
if [ -S "$candidate" ]; then
export WAYLAND_DISPLAY="''${candidate##*/}"
break
fi
done
exec ${lib.getExe' cfg.package "hhstream-server"} "$@"
'';
# The same problem, for the stream daemon, one step worse.
#
# `grim` is an ordinary Wayland client: it needs XDG_RUNTIME_DIR *and* the
# name of the socket the compositor actually bound, and that name is only
# known once the compositor is up -- so, exactly as above, it cannot be an
# `Environment=` line.
#
# MEASURED, in checks/vm-stream.nix, which is the check that exists to find
# this: with the group but without the environment, the unit came up
# `active (running)`, the broker attached, `stream status` said
# `attached: true`, and every capture failed with
#
# grim: error: XDG_RUNTIME_DIR is invalid or not set in the environment.
#
# until the publisher gave up after ten in a row. A viewer with the right
# phrase got a page and no frames, and nothing in the session's own state
# said why -- the sibling failure to
# docs/TODO/capture-binary-and-the-unit-path.md, and the reason this unit
# spells out the whole capture command *and* hands it a session.
execLive = pkgs.writeShellScript "hhstream-exec-live" ''
for candidate in "$XDG_RUNTIME_DIR"/wayland-*; do
if [ -S "$candidate" ]; then
export WAYLAND_DISPLAY="''${candidate##*/}"
break
fi
done
exec ${lib.getExe' cfg.package "hhstream-live"} "$@"
'';
hyprlandConf = pkgs.writeText "hyprland.conf" (import ./hyprland-conf.nix {
inherit lib;
inherit (cfg) outputs extraConfig;
});
# `BindsTo=` already stops the frame server when the compositor goes away, but
# the compositor is only *ready* once its Wayland socket is bound. The
# compositor unit is `Type=notify`, so `findSession` above is a second line of
# defence for compositor builds that do not sd_notify, and it is why this is
# not a plain `After=` ordering.
# The session broker's config, in the daemon's own format (PLAN §10). It
# carries the app allowlist, which is what makes `sessions.enable = true`
# useful rather than decorative: the daemon treats a missing file as an empty
# allowlist and refuses every `start` with the path it looked for.
#
# ─── A GAP, STATED HERE RATHER THAN HIDDEN ───────────────────────────────
# `hhstreamd/policy.py:policy_from_dict` reads `[defaults]` and `[apps]` and
# nothing else, and `hhstreamd/__main__.py:serve` builds its `ManagerConfig`
# from command-line flags that have no counterpart for any of these numbers.
# So the `[compositor]` and `[pointer]` tables below, and `max_containers`,
# are written and *not read*: the broker falls back to its own defaults
# (container band 1000, 4 slots, 1280x720; lease 30 s / 300 s), which happen
# to agree with the defaults here, so a deployment that leaves these options
# alone behaves exactly as this file says. One that changes them is ignored.
#
# They are rendered anyway, and with §10's own key names, because that is the
# interface the broker is specified to read and writing it is what makes the
# omission a one-file fix rather than a redesign. `sessions.pointer.enable`
# is the one option here with teeth today: it decides whether the driver unit
# exists, which is what the broker's `pointer_socket` finds or does not find.
#
# Two key names differ from §10 on purpose. §10 puts `max_sessions` and
# `max_containers` under `[broker]`, but the broker reads `max_sessions` from
# `[defaults]` — so `max_containers` is written beside it, where the code
# that will read it already looks. And §10 has no key for
# `containers.enable`, so `containers_enabled` is named here.
# ──────────────────────────────────────────────────────────────────────────
sessionsConfig = pkgs.writeText "hhstream-sessions.toml" ''
[defaults]
max_sessions = ${toString cfg.sessions.maxSessions}
idle_timeout_s = ${toString cfg.sessions.idleTimeout}
max_containers = ${toString cfg.sessions.containers.max}
[compositor]
runtime_dir = ${builtins.toJSON runtimeDir}
containers_enabled = ${lib.boolToString cfg.sessions.containers.enable}
workspace_base = ${toString cfg.sessions.containers.workspaceBase}
container_mode = ${builtins.toJSON cfg.sessions.containers.mode}
[pointer]
enabled = ${lib.boolToString cfg.sessions.pointer.enable}
lease_ttl_s = ${toString cfg.sessions.pointer.leaseTtl}
lease_max_s = ${toString cfg.sessions.pointer.leaseMax}
${lib.concatStringsSep "\n" (
lib.mapAttrsToList (name: app: ''
[apps.${name}]
exec = ${builtins.toJSON (toString app.exec)}
args_allow = [${
lib.concatStringsSep ", " (map (arg: builtins.toJSON arg) app.argsAllow)
}]
'') cfg.sessions.apps
)}
'';
serverArgs =
[
"--socket"
cfg.socketPath
"--fps"
(toString cfg.frameRate)
"--format"
cfg.format
]
# One occurrence per argv word. The capture command is a list whose words
# start with `-` (`grim -t png -`), and repeating the flag is the only
# shape that survives that without inventing a quoting convention.
# `hhstream.server.build_parser()` is still a stub, so this is the one
# place the module guesses at the server's CLI rather than reading it.
++ lib.concatMap (word: ["--capture-command" word]) cfg.captureCommand;
# Shared by both units: a private session, no parent display to nest in.
sessionEnvironment = {
XDG_RUNTIME_DIR = runtimeDir;
HOME = runtimeDir;
XDG_SESSION_TYPE = "wayland";
};
commonServiceConfig = {
User = cfg.user;
Group = cfg.group;
RuntimeDirectory = runtimeDirName;
RuntimeDirectoryMode = "0750";
RuntimeDirectoryPreserve = "yes";
WorkingDirectory = runtimeDir;
# docs/CONTRACT.md: the socket is owned by the service user, mode 0660.
UMask = "0007";
Restart = "always";
RestartSec = 2;
# A GPU render node is the one piece of hardware a headless session still
# needs; everything else is virtual.
SupplementaryGroups = ["video" "render"];
NoNewPrivileges = true;
PrivateTmp = true;
ProtectHome = true;
ProtectSystem = "strict";
ProtectControlGroups = true;
ProtectKernelTunables = true;
ProtectKernelModules = true;
RestrictSUIDSGID = true;
ReadWritePaths = lib.optional (socketDir != runtimeDir) socketDir;
};
in {
options.services.hyprland-headless-stream = {
enable = lib.mkEnableOption "a headless Hyprland session streamed to a Unix socket";
socketPath = lib.mkOption {
type = lib.types.str;
default = "/run/hypr-stream/stream.sock";
description = "Where the frame server publishes frames.";
};
user = lib.mkOption {
type = lib.types.str;
default = "hhstream";
description = "User the compositor and frame server run as.";
};
group = lib.mkOption {
type = lib.types.str;
default = "hhstream";
description = "Group owning the socket.";
};
frameRate = lib.mkOption {
type = lib.types.ints.positive;
default = 30;
description = "Target capture rate; becomes `fps` in the protocol Hello.";
};
format = lib.mkOption {
type = lib.types.enum ["png" "jpeg"];
default = "png";
description = "Frame encoding.";
};
outputs = lib.mkOption {
type = lib.types.listOf (lib.types.submodule {
options = {
name = lib.mkOption {
type = lib.types.str;
default = "";
description = ''
Regex matched against the names of the outputs this machine has
(`eDP-1`, `Virtual-1`, ...). Empty is Hyprland's wildcard form and
matches every output; a name no connector has is a rule that is
silently ignored.
'';
};
width = lib.mkOption {
type = lib.types.ints.positive;
default = 1280;
};
height = lib.mkOption {
type = lib.types.ints.positive;
default = 720;
};
refresh = lib.mkOption {
type = lib.types.ints.positive;
default = 30;
};
# Was `lib.types.positive`, which does not exist in nixpkgs and made
# `outputs` unreadable; `numbers.positive` is the int-or-float type
# that name meant.
scale = lib.mkOption {
type = lib.types.numbers.positive;
default = 1.0;
};
};
});
default = [
{
name = "";
width = 1280;
height = 720;
refresh = 30;
scale = 1.0;
}
];
description = ''
Monitor rules applied to the outputs the machine has. Each entry becomes
one `monitor = <name>, <width>x<height>@<refresh>, auto, <scale>` line.
These are *not* outputs the compositor creates: aquamarine's headless
backend has no allocator of its own and rides on the DRM backend, so a
session started by this module always has the GPU's own connectors and
whatever names the host gives them. The default therefore uses the empty
name -- Hyprland's wildcard, as in its own shipped
`monitor=,preferred,auto,1` -- so that `enable = true` alone gives a
session at a known size on any machine. Naming a connector that does not
exist is not an error; the rule is simply never applied.
'';
};
extraConfig = lib.mkOption {
type = lib.types.lines;
default = "";
description = "Extra lines appended to hyprland.conf.";
};
hyprlandPackage = lib.mkOption {
type = lib.types.package;
default = pkgs.hyprland;
defaultText = lib.literalExpression "pkgs.hyprland";
description = "Compositor to run.";
};
package = lib.mkOption {
type = lib.types.package;
description = "The frame server / client package.";
};
captureCommand = lib.mkOption {
type = lib.types.listOf lib.types.str;
default = ["grim" "-t" "png" "-"];
description = "Command that writes one frame to stdout; overridable for tests.";
};
sessions = {
enable = lib.mkOption {
type = lib.types.bool;
default = false;
description = ''
Run the session broker (`hhstreamd`) that launches GUI applications
into this compositor as *tracked sessions*: started by name, kept
alive by an explicit `touch`, killed by name, and reaped when they go
quiet for {option}`sessions.idleTimeout`.
It is off by default because it is a different capability from
streaming frames: a frame server can be read by anyone in the group,
while this one starts processes on the machine.
Its CLI is `hhstream session …` on the same binary as the frame
commands; the daemon itself is the unit `hhstream-sessions.service`.
'';
};
user = lib.mkOption {
type = lib.types.str;
default = config.services.hyprland-headless-stream.user;
defaultText = lib.literalExpression "services.hyprland-headless-stream.user";
description = ''
The account the broker runs as, and the account every launched
application runs as. It must already exist: the module does not create
it, because its whole point is usually to be a real person's account
whose home directory and files the applications should see.
Set it to the account that will actually drive the CLI. The broker is
granted {option}`sessions.group` as a supplementary group so the
applications it launches can reach the compositor's socket.
'';
};
group = lib.mkOption {
type = lib.types.str;
default = config.services.hyprland-headless-stream.group;
defaultText = lib.literalExpression "services.hyprland-headless-stream.group";
description = ''
The group that owns the compositor's runtime directory. The broker gets
it as a supplementary group, and passes it to every application it
launches — without it a launched GUI client cannot open the Wayland
socket and dies at startup.
'';
};
idleTimeout = lib.mkOption {
type = lib.types.ints.positive;
default = 10800;
description = ''
Seconds a session may go without a `touch` before the broker kills it
and everything it spawned. The clock lives in the broker, not in the
CLI, so it keeps running after the CLI exits.
Only `touch` resets it: `list`, `status`, `logs` and `gc` deliberately
do not, or a monitoring loop would keep abandoned sessions alive
forever.
'';
};
maxSessions = lib.mkOption {
type = lib.types.ints.positive;
default = 4;
description = ''
Hard cap on live sessions. Without cgroup limits this is the main
containment control against a looping caller spawning applications
until the machine gives up.
'';
};
apps = lib.mkOption {
type = lib.types.attrsOf (lib.types.submodule {
options = {
exec = lib.mkOption {
type = lib.types.path;
description = "Absolute path to the executable. Never a shell command.";
};
argsAllow = lib.mkOption {
type = lib.types.listOf lib.types.str;
default = [];
description = ''
Arguments a caller may pass to this application. Anything else is
refused, so `exec` must be able to do its job with these and
nothing more. A trailing `*` matches a prefix
(`--user-data-dir=*`).
'';
};
};
});
default = {};
description = ''
The allowlist: which applications may be started as a session, and with
which arguments. This is the primary security control —
without it, `session start /bin/sh` would make every other control
decorative. An application that is not listed here cannot be started
at all.
'';
example = lib.literalExpression ''
{
chromium.exec = "''${pkgs.chromium}/bin/chromium";
chromium.argsAllow = [ "--new-window" "--user-data-dir=*" "https://*" ];
}
'';
};
configFile = lib.mkOption {
type = lib.types.nullOr lib.types.path;
default = null;
description = ''
Use this TOML allowlist instead of the one generated from
{option}`sessions.apps`, for configurations the option shape cannot
express.
'';
};
containers = {
enable = lib.mkOption {
type = lib.types.bool;
default = true;
description = ''
Give each session its own headless output and workspace — a
*container* (PLAN §5). The broker creates `hh-<session-id>` on
`start`, binds a window rule to it so the application's window
lands there and nowhere else, and removes the output on teardown,
which takes the container with it.
Without it every application shares the main output, so two
sessions see each other's windows and `grim -o` has nothing to
aim at. It is on by default because every other part of this
option tree assumes it; turn it off to run a single application
on the main screen, as the pre-container module did.
'';
};
max = lib.mkOption {
type = lib.types.ints.positive;
default = 2;
description = ''
How many containers may exist at once.
Each one is a real render target: at `vfr = false` the compositor
renders every output every frame, so this is a CPU budget and not
a preference. The default of 2 is the plan's conservative starting
point for a two-core machine and is explicitly waiting on a
measurement (PLAN §5.5, experiment 2) — raise it from a number you
measured, not from one you hoped for.
Distinct from {option}`sessions.maxSessions`: a session may run
without a container (degraded, if the compositor was unreachable),
so the two caps bound different things. Exhausting this one refuses
the `start` with exit 6 rather than quietly sharing a screen.
'';
};
mode = lib.mkOption {
type = lib.types.strMatching "[0-9]+x[0-9]+";
default = "1280x720";
description = ''
The size each container's output is set to, `WIDTHxHEIGHT`
(docs/CONTRACT-sessions.md §5 freezes the default at 1280x720).
This is the resolution an application sees and the resolution
`grim -o hh-<id>` captures, so it is also the cost per container.
'';
};
workspaceBase = lib.mkOption {
type = lib.types.ints.positive;
default = 1000;
description = ''
First workspace number of the reserved band containers are
allocated from; a container gets `workspaceBase + slot`.
The band exists so a container never collides with a workspace the
operator uses by hand. Numbers this high are not reachable by the
default keybindings, which is the point.
'';
};
};
pointer = {
enable = lib.mkOption {
type = lib.types.bool;
default = false;
description = ''
Run `hhstream-pointer`, the driver that moves this session's one
cursor on the broker's instruction (`hhstream session pointer …`).
Off by default, and the default is the honest one: input injection
is a capability distinct from running applications, the cursor is
singular so it has to be leased, and nothing in the compositor
stops a *hostile* client from creating its own virtual pointer
(PLAN §6.6) — the lease disciplines our sessions, it does not
enforce against theirs.
With it off, every pointer verb answers `driver_unavailable`
(exit 10) rather than pretending: the broker looks for the driver's
socket and does not find one.
'';
};
leaseTtl = lib.mkOption {
type = lib.types.ints.positive;
default = 30;
description = ''
Seconds a pointer lease may go without a pointer verb before the
broker force-releases it and lifts anything still pressed.
This is what makes the lease a promise rather than a hope: an agent
that acquired the cursor, pressed a button and died holds neither
for longer than this. Every gesture verb refreshes it.
'';
};
leaseMax = lib.mkOption {
type = lib.types.ints.positive;
default = 300;
description = ''
Hard ceiling on a single lease, in seconds, refreshed or not.
{option}`sessions.pointer.leaseTtl` can be extended indefinitely by
a caller that keeps sending verbs; this one cannot, so one session
can never own the cursor forever.
'';
};
};
# The keyboard has no `enable` of its own: it is the same unit, the same
# process and the same lease as the pointer (`hhstream session keyboard
# …` refuses with exit 9 until `pointer acquire`). What it needs from an
# operator is a layout, because the keymap the driver uploads is the only
# thing that decides which keycode a keysym is -- Hyprland's own
# `input:kb_layout` is not read and does not affect injected keys.
keyboard = {
layout = lib.mkOption {
# `strMatching` and not `str`, and the pattern is the point: it is
# what refuses `us,ru`. A comma-separated layout compiles perfectly
# well into a two-group keymap, and v1 sends `group = 0` in every
# `modifiers` request -- so the second group would be unreachable and
# an agent asking for a Cyrillic character would silently get a Latin
# one. The driver refuses a comma too, for a binary run by hand.
type = lib.types.strMatching "[A-Za-z0-9_-]+";
default = "us";
example = "de";
description = ''
XKB layout the `hhstream-pointer` unit compiles once at start-up and
uploads as its virtual keyboard's keymap (rules `evdev`, model from
{option}`sessions.keyboard.model`).
**This is the only thing that decides what an injected key means.**
Every `hhstream session keyboard` verb names an XKB *keysym*
(`a`, `A`, `Return`, `Control_L`), and the driver resolves that name
against this keymap to get the evdev code and the modifier mask the
compositor is sent. A character this layout cannot produce is
refused with exit 2 and nothing is typed -- there is no partial
type, so `é` on `us` fails the whole string rather than the letter.
Hyprland's `input:kb_layout` is **not** read. It describes the
layout for physical keyboards, of which a headless session has none,
and reading it would mean a `hyprctl` reload could silently change
what every agent types. One group only: see the type.
'';
};
model = lib.mkOption {
type = lib.types.strMatching "[A-Za-z0-9_-]*";
default = "pc105";
description = ''
XKB model for the same keymap. `pc105` unless an operator knows
otherwise; it decides little beyond which keys exist at all.
'';
};
variant = lib.mkOption {
type = lib.types.str;
default = "";
example = "intl";
description = ''
XKB variant, empty by default.
Worth knowing before setting one: a variant whose characters are
**dead keys** -- `us(intl)`'s accents, for instance -- cannot be
typed by this version. A dead key is half of a compose sequence and
v1 emits one event per character, so the driver refuses the name
rather than arming the next keystroke in the focused application.
'';
};
options = lib.mkOption {
type = lib.types.str;
default = "";
example = "ctrl:nocaps";
description = ''
XKB options, empty by default. Passed through to
`xkb_keymap_new_from_names`; a value it rejects stops the driver
with exit 2 before it connects to the compositor, so a typo here is
a failed unit rather than a session that types the wrong thing.
'';
};
};
# The session-stream web app — `hhstream-live`, the router that serves a
# live view of one session per phrase, over one port
# (`docs/plans/2026-10-04-session-stream-webapp.md`, Stage 2 and 3).
#
# `enable` runs the unit and hands the broker `/run/hhstream/live.sock`,
# over which `hhstream session stream enable <id>` switches one stream
# on. Everything else here is the *reach* of it: the port every stream
# shares, the address it binds, and whether that port is opened in the
# firewall.
#
# Running it still turns nothing on. A stream exists only for the
# sessions it was enabled on — a stream is switched on per session, never
# for all of them — so `enable = true` is a listener serving one form
# until somebody asks for a session.
stream = {
enable = lib.mkOption {
type = lib.types.bool;
default = false;
description = ''
Run `hhstream-live`, the web app that publishes one session's
screen at a URL whose path is a spoken phrase, and give the broker
the socket it switches streams on over
(`/run/hhstream/live.sock`).
Off by default, and running it turns **nothing** on: a stream
exists only for the sessions `hhstream session stream enable` was
called on, and until then this is a listener serving one form.
That is deliberate — a live view of a desktop is readable by
anyone who can reach the port and guess the phrase, so switching
one on is a per-session act and never a consequence of the service
being up.
Needs {option}`sessions.enable`: the phrase lives in the session
record, and there are no sessions without the broker.
'';
};
fps = lib.mkOption {
type = lib.types.ints.positive;
default = 5;
description = ''
Frames a second a stream captures at when nobody says otherwise.
Five is one frame per ~200 ms plus a ~46 ms `grim`, measured rather
than guessed; the daemon's own hard cap is 10, because this box is
also running the compositor and the main frame publisher. Capture
happens **only while somebody is connected**, so an enabled stream
nobody is watching costs nothing at any rate.
`hhstream session stream enable --fps N` overrides it per stream.
'';
};
port = lib.mkOption {
type = lib.types.port;
default = 9988;
description = ''
The single TCP port every stream shares.
One listener rather than one per session is what makes the phrase
speakable: there is one address to give a person, one thing to
firewall and one thing to stop. It is also why this is a fixed
number with no range to fall back on — a stream at a port nobody
was told about is worse than a stream that is down, so a taken port
fails loudly instead of moving.
'';
};
bind = lib.mkOption {
type = lib.types.str;
default = "127.0.0.1";
description = ''
The address the web app will bind.
Loopback by default, where the reachable path is an ssh tunnel
(`ssh -L 9988:127.0.0.1:9988`) and nothing else. Set it to an
address a peer can reach (`"0.0.0.0"`) when
{option}`sessions.stream.openFirewall` is set: opening the port for
a listener that is not on it is a hole with no service behind it,
which is why that pairing is refused rather than allowed.
'';
};
openFirewall = lib.mkOption {
type = lib.types.bool;
default = false;
description = ''
Open {option}`sessions.stream.port` in the firewall.
Off by default, and deliberately not implied by
{option}`sessions.enable`: a live view of this desktop is readable
by anyone who can reach the port, and the phrase in the URL is its
only credential — no TLS, no second factor
(`docs/plans/2026-10-04-…` §4). Opening it is an explicit act, and
it opens exactly one port.
'';
};
};
stateDir = lib.mkOption {
type = lib.types.str;
default = "/var/lib/hhstream";
description = ''
Where the broker keeps what outlives a broker restart: the live-record
mirrors it adopts on the way back up, tombstones of ended sessions, and
`events.jsonl`, the audit trail of every accepted command.
Point this at durable storage. The default is a system path, which on a
machine whose root is rebuilt from scratch — the usual shape of a
declaratively-managed server — means the audit trail dies with the
next reinstall. On such a machine this belongs on the same disk as the
rest of the state that cannot be rebuilt.
'';
};
};
# The Model Context Protocol server -- `hhstream-mcp`, the `hhstream` CLI
# as typed tools, so an agent drives this desktop without shelling out.
#
# Its own top-level block rather than one under `sessions`, because it is
# not the broker's: four of its tools (`status`, `shot`, `record`, `run`)
# are frame-socket verbs that work with the broker switched off.
#
# `mcp.enable` is still not a unit, and that is still the point: the stdio
# transport is one process per client, spawned by whichever client wants
# it, so "installing" it means exactly putting the binary on PATH.
#
# `mcp.http.enable` IS a unit, and it is the second thing to supervise that
# the comment here used to say was never worth inventing. What changed is
# not the cost of supervising it but what it buys: a port can be reached by
# a caller who never touched this filesystem, which is the first time an
# authorization token on this surface means anything at all. Over stdio the
# client spawns the server and already holds the broker's socket, so a
# token there guards a lock whose key is in the same pocket. The two
# options are therefore independent -- one is a binary on PATH for a local
# client, the other is a listener with a credential -- and neither implies
# the other.
mcp = {
enable = lib.mkOption {
type = lib.types.bool;
default = false;
description = ''
Put `hhstream-mcp` on the system PATH, so an MCP client on this
machine can spawn it.
Off by default, and deliberately not implied by
{option}`sessions.enable`: this is the surface through which a
language model starts applications, clicks and types on this desktop,
and whether that is wanted is a decision, not a consequence of the
broker being up. Installing it starts nothing — the server is stdio
and short-lived, spawned per client — and it grants no access the
`hhstream` CLI does not already grant to whoever runs it.
The client configures the sockets through the CLI's own environment,
`HHSTREAM_SOCKET` and `HHSTREAM_FRAME_SOCKET`; see the README section
on registering it.
'';
};
package = lib.mkOption {
type = lib.types.package;
description = ''
The MCP server package. Defaults to this flake's `hhstream-mcp`,
built against {option}`package` so the server and the CLI it drives
are the same build.
'';
};
stateDir = lib.mkOption {
type = lib.types.str;
default = "/var/lib/hhstream-mcp";
description = ''
Where `hhstream-mcp` keeps its authorization table — the SHA-256
digests of the bearer tokens {option}`mcp.http.enable` accepts, and
nothing else.
Deliberately **not** {option}`sessions.stateDir`. That directory is
`0700` owned by {option}`sessions.user` and holds `events.jsonl`, the
broker's audit trail; parking a token file in it would mean granting
this shim write access to the audit trail's directory for no reason.
The two also have different lifetimes: revoking every token should
not be able to touch a session record, and vice versa.
The file holds digests rather than tokens, so it is not itself a
credential — but it is the list of who may drive this desktop, and it
is created `0700`.
'';
};
http = {
enable = lib.mkOption {
type = lib.types.bool;
default = false;
description = ''
Serve the MCP surface over Streamable HTTP on
{option}`mcp.http.port`, as a system unit, authenticated by a
bearer token.
This is the one shape of this server where a credential means
something: the stdio transport is spawned by its client, so that
caller has already passed a filesystem permission check and holds
the broker's `0660` control socket either way. A port is reachable
by someone who did neither.
Mint a token with `hhstream-mcp token mint`, run as
{option}`sessions.user`, and give it to the client as an
`Authorization: Bearer …` header.
**The unit refuses to start while the table is empty**, because a
listener that 401s every request is almost always a forgotten mint,
and "connection works, auth fails" is far worse to debug than a
`systemctl status` that names the remedy. It retries every five
seconds rather than giving up, so it comes up on its own within one
interval of the first `token mint` — no `systemctl start` needed.
Pass `--allow-no-tokens` through {option}`mcp.http.extraArgs` to
start anyway.
Not MCP's authorization specification, which is OAuth 2.1 plus
RFC 9728 metadata discovery. A client that can only *discover* an
authorization server will not connect; one that lets you set a
header will. See `docs/TODO/mcp-http-auth-is-not-oauth.md`.
'';
};
address = lib.mkOption {
type = lib.types.str;
default = "127.0.0.1";
description = ''
The address to bind.
Loopback by default. Binding somewhere the LAN can reach means a
bearer token is the only thing between the network and a desktop
something can type into, over plain HTTP with no TLS — put a
reverse proxy in front if that is the intent.
`0.0.0.0` is accepted but then {option}`mcp.http.allowedHosts` must
be set: DNS-rebinding protection is on, the allowlist has no
implicit localhost, and the `Host` header a client will send cannot
be derived from a wildcard bind.
'';
};
port = lib.mkOption {
type = lib.types.port;
default = 9989;
description = ''
The port to bind. One past {option}`sessions.stream.port`'s default,
so a machine running both has no collision.
'';
};
path = lib.mkOption {
type = lib.types.str;
default = "/mcp";
description = "The path the endpoint is mounted at.";
};
allowedHosts = lib.mkOption {
type = lib.types.listOf lib.types.str;
default = [];
example = ["desk.lan:9989" "desk.lan:*"];
description = ''
`Host` header values to accept, for DNS-rebinding protection.
Empty, the server derives them from {option}`mcp.http.address` —
which covers the loopback default and fails for a wildcard bind,
where nothing can be derived. A trailing `:*` is a wildcard port.
'';
};
allowedOrigins = lib.mkOption {
type = lib.types.listOf lib.types.str;
default = [];
description = ''
`Origin` header values to accept. Nothing needs this unless a
browser is the client: a request with no `Origin` is allowed, and
any present one not named here is refused. A browser page is the
attacker in the DNS-rebinding story, not a user of this server.
'';
};
toolsets = lib.mkOption {
type = lib.types.nullOr (lib.types.listOf lib.types.str);
default = null;
example = ["frames" "sessions"];
description = ''
Families to offer as tools, process-wide: `frames`, `sessions`,
`pointer`, `keyboard`. `null` offers every tool.
A ceiling, not a grant: a token may carry its own narrower list
(`token mint --toolsets`), and a tool has to survive both. Resources
are not filtered by either.
'';
};
openFirewall = lib.mkOption {
type = lib.types.bool;
default = false;
description = ''
Open {option}`mcp.http.port` in the firewall.
Off by default and not implied by {option}`mcp.http.enable`, the
same way {option}`sessions.stream.openFirewall` is not implied by
the stream: this port is a language model's path to starting
applications and typing on this desktop, and a bearer token over
plain HTTP is its only protection. Opening it is an explicit act.
'';
};
extraArgs = lib.mkOption {
type = lib.types.listOf lib.types.str;
default = [];
example = ["--stateless" "--allow-no-tokens"];
description = ''
Extra arguments for `hhstream-mcp serve --http`, appended last.
'';
};
};
};
};
config = lib.mkIf cfg.enable {
assertions = [
{
assertion = cfg.outputs != [];
message = "services.hyprland-headless-stream.outputs must not be empty.";
}
{
assertion = lib.hasPrefix "/" cfg.socketPath;
message = "services.hyprland-headless-stream.socketPath must be an absolute path.";
}
# The HTTP server is a unit, so it needs an account -- and the one it
# needs is the broker's, because its tools are the CLI's handlers and
# that CLI opens the broker's control socket and the compositor's runtime
# directory. `sessions.enable` is what declares that identity.
#
# An assertion and not a warning, unlike `mcp.enable` against the same
# condition: there, every session tool answers exit 5 and the frame tools
# still work, so it is a thing worth saying. Here the unit would fail to
# start at all, with `User=` naming an account that does not exist, and a
# listener that never comes up is not a degraded mode.
{
assertion = !cfg.mcp.http.enable || cfg.sessions.enable;
message = ''
services.hyprland-headless-stream.mcp.http.enable needs sessions.enable.
The HTTP transport runs as sessions.user with sessions.group, because
the tools it serves are the `hhstream` CLI's own handlers and that CLI
opens the broker's 0660 control socket and the compositor's runtime
directory. With sessions.enable off, that account is not declared and
the unit fails to start.
For a frame-only surface, use mcp.enable (stdio, no unit) instead.
'';
}
# `--address 0.0.0.0` and no allowedHosts is a server that 421s every
# request: DNS-rebinding protection is on, the allowlist has no implicit
# localhost, and the Host header a client will send cannot be derived
# from a wildcard bind. Caught here rather than at start-up, because a
# rebuild that produces a unit which refuses everything is worse than a
# rebuild that does not evaluate.
{
assertion =
!cfg.mcp.http.enable
|| !(builtins.elem cfg.mcp.http.address ["0.0.0.0" "::" "*"])
|| cfg.mcp.http.allowedHosts != [];
message = ''
services.hyprland-headless-stream.mcp.http.address is
"${cfg.mcp.http.address}", which binds every interface, so
mcp.http.allowedHosts must name the Host values to accept.
DNS-rebinding protection is on and its allowlist has no implicit
localhost, so an empty list refuses every request with a 421. Name the
hostnames clients will use (a trailing ":*" is a wildcard port), or
bind one address.
'';
}
# Structural, not cosmetic: see the `runtimeDirName` comment above. The
# ceiling exists so the compositor's *event* socket still fits in
# `sun_path`, and the symptom of breaking it is silent -- the request
# socket keeps answering, so `hyprctl` looks fine while every event-driven
# feature is dead.
{
assertion = builtins.stringLength runtimeDir <= runtimeDirMaxLength;
message = ''
The compositor runtime directory "${runtimeDir}" is ${
toString (builtins.stringLength runtimeDir)
} characters; it must be at most ${toString runtimeDirMaxLength}.
Hyprland's event socket is <runtime dir>/hypr/<instance signature>/.socket2.sock.
A longer directory pushes that path past the 108 bytes a Unix socket address
has for `sun_path`, and the compositor then refuses to bind it:
ERR ]: Socket2 path is too long. (2) IPC will not work.
Nothing appears broken when that happens -- the shorter request socket still
answers `hyprctl` -- but the event stream never arrives, so every feature that
watches the compositor (window and workspace tracking, session containers)
stops working. docs/CONTRACT-sessions.md §5 freezes this limit; shorten the
directory rather than raising it.
'';
}
{
assertion = cfg.sessions.pointer.leaseTtl <= cfg.sessions.pointer.leaseMax;
message = ''
services.hyprland-headless-stream.sessions.pointer.leaseTtl
(${toString cfg.sessions.pointer.leaseTtl}s) is longer than leaseMax
(${toString cfg.sessions.pointer.leaseMax}s), so the hard ceiling would fire
before the idle timeout could and the idle timeout would never be reached.
leaseMax is the cap a caller cannot refresh past; leaseTtl is the one it can.
'';
}
{
# A driver with no broker is a process holding a Wayland connection and
# a socket nobody will ever connect to: the broker owns the lease, and
# the driver is deliberately stateless (CONTRACT-sessions.md §3.4).
assertion = !cfg.sessions.pointer.enable || cfg.sessions.enable;
message = ''
services.hyprland-headless-stream.sessions.pointer.enable needs
sessions.enable = true. The pointer driver takes its instructions from the
session broker -- it holds no lease of its own and has no other client --
so without the broker it would bind a socket nothing connects to.
'';
}
{
assertion =
!cfg.sessions.stream.openFirewall
|| !(lib.elem cfg.sessions.stream.bind loopbackBinds);
message = ''
services.hyprland-headless-stream.sessions.stream.openFirewall is true
while sessions.stream.bind is "${cfg.sessions.stream.bind}" — a loopback
address. The port would be open in the firewall with nothing answering on
it from anywhere but this machine, which is a hole rather than a feature.
Set sessions.stream.bind to an address a peer can reach ("0.0.0.0"), or
leave the firewall closed and reach the stream through a tunnel
(`ssh -L 9988:127.0.0.1:9988`).
'';
}
{
assertion = !cfg.sessions.enable || lib.hasAttr cfg.sessions.user config.users.users;
message = ''
services.hyprland-headless-stream.sessions.user = "${cfg.sessions.user}" is not a
declared user. The module deliberately does not create it: launched applications
run as that account, so it is normally a real person's account whose home
directory and files they should see. Declare it (or point the option at an
existing account).
'';
}
];
# The flake's own build, as docs/CONTRACT.md says; `mkDefault` so a
# consumer (or the test harness) can still point this at its own package.
services.hyprland-headless-stream.package =
lib.mkDefault (pkgs.callPackage ./package.nix {});
# Built against `cfg.package`, so the server and the CLI it runs are one
# build: the tools are argv lists against that CLI's parser, and a server
# paired with a different one would refuse flags for reasons no agent could
# read. `mkDefault` for the same reason as above.
services.hyprland-headless-stream.mcp.package =
lib.mkDefault (pkgs.callPackage ./mcp.nix { hhstream = cfg.package; });
# Installing it IS the whole of `mcp.enable`: the stdio server is spawned
# by a client, so that option declares no unit and no socket.
#
# `mcp.http.enable` also puts it on PATH, and not only because the unit
# needs it: `hhstream-mcp token mint` is how an operator issues the
# credential that unit demands, and a listener nobody can mint a token for
# is a listener that 401s for ever.
environment.systemPackages =
lib.mkIf (cfg.mcp.enable || cfg.mcp.http.enable) [ cfg.mcp.package ];
# A warning and not an assertion: twenty of the twenty-three tools and
# seven of the ten resources need the broker, and an agent handed them against
# a machine where it is off gets exit 5 from every one of them -- which is
# a true answer, badly timed. The frame tools are genuinely useful on their
# own, so this is a thing worth saying rather than a thing worth refusing.
warnings =
# Plain HTTP, no TLS, and one bearer token. Said out loud because the
# option that gets you here reads like a bind address and not like a
# decision about what is on the wire.
lib.optional
(cfg.mcp.http.enable && !(builtins.elem cfg.mcp.http.address ["127.0.0.1" "::1" "localhost"]))
''
services.hyprland-headless-stream.mcp.http.address is
"${cfg.mcp.http.address}", which is reachable beyond this machine.
There is no TLS here: the bearer token travels in a header in clear text,
and it authorizes starting applications, clicking and typing on this
desktop. Put a reverse proxy that terminates TLS in front of it, or keep
the bind on loopback and reach it through an SSH tunnel.
''
++ lib.optional (cfg.mcp.http.enable && cfg.mcp.http.openFirewall) ''
services.hyprland-headless-stream.mcp.http.openFirewall is on: port
${toString cfg.mcp.http.port} is open to the network, and a bearer token
is the only thing between it and a language model driving this desktop.
Mint tokens with an expiry (`hhstream-mcp token mint --expires-in 30d`)
and revoke them when a client is retired.
''
++ lib.optional (cfg.mcp.enable && !cfg.sessions.enable) ''
services.hyprland-headless-stream.mcp.enable is on while sessions.enable
is off: the MCP server's session, pointer and keyboard tools, and every
resource but hhstream://status and hhstream://screen, will fail because
the broker is unreachable (exit 5). Only shot, record, run and those two
resources will work.
'';
# The broker's state directory and the moved socket directory are two
# different reasons to write a tmpfiles entry, and this option takes one
# definition — so they are merged here rather than assigned twice (which
# does not evaluate at all).
systemd.tmpfiles.settings = lib.mkMerge [
# The broker keeps the records it adopts on the way back up, its
# tombstones, and `events.jsonl`, the audit trail of every accepted
# command. It is declared here rather than left to the daemon so its owner
# and mode are declarative and survive a restart of the unit.
(lib.mkIf cfg.sessions.enable {
"10-hhstream-sessions".${cfg.sessions.stateDir}.d = {
user = cfg.sessions.user;
group = cfg.sessions.group;
mode = "0700";
};
})
# The broker's runtime directory, which is also the pointer driver's: the
# control socket and the private broker-driver socket both live in it
# (CONTRACT-sessions.md §5), and it is declared here because *two* units
# now need it to exist.
#
# `RuntimeDirectory=` on the broker alone is not enough. systemd removes
# a unit's RuntimeDirectory when that unit stops, so a `systemctl restart
# hhstream-sessions` would delete /run/hhstream and take the driver's
# pointer.sock with it -- leaving the driver listening on an unlinked
# inode and the broker unable to reach a driver that is running. Hence
# this entry, and `RuntimeDirectoryPreserve` on the broker below.
(lib.mkIf cfg.sessions.pointer.enable {
"10-hhstream-pointer".${brokerRuntimeDir}.d = {
user = cfg.sessions.user;
group = cfg.sessions.group;
mode = "0750";
};
})
# The MCP server's own state directory: the authorization table, and
# nothing else. A tmpfiles entry rather than `StateDirectory=` on the
# unit, for the reason the broker's is one -- `StateDirectory=` can only
# name a directory under /var/lib and would stop applying the moment
# `mcp.stateDir` is pointed anywhere else, whereas this is declarative
# for any path.
#
# `mcp.enable` alone does not create it. The stdio transport reads no
# tokens, so a directory for them would be a directory nothing opens.
(lib.mkIf cfg.mcp.http.enable {
"10-hhstream-mcp".${cfg.mcp.stateDir}.d = {
user = cfg.sessions.user;
group = cfg.sessions.group;
mode = "0700";
};
})
# Only needed when the socket was moved out of the runtime directory that
# `RuntimeDirectory=` already creates for us.
(lib.mkIf (socketDir != runtimeDir) {
"10-hyprland-headless-stream".${socketDir}.d = {
user = cfg.user;
group = cfg.group;
mode = "0750";
};
})
];
# The stream's one port, in the firewall.
#
# `lib.optional`, not a conditional block: the option is one line and its
# effect is one port in the rule set, so there is nothing here that could
# open a second one. Everything else about the app — the phrase per
# session, the capture, the enable/disable verbs — is later stages of the
# plan; this is the only part of the stream that a machine declares before
# any of that exists.
networking.firewall.allowedTCPPorts =
lib.optional cfg.sessions.stream.openFirewall cfg.sessions.stream.port
++ lib.optional (cfg.mcp.http.enable && cfg.mcp.http.openFirewall) cfg.mcp.http.port;
users.users.${cfg.user} = {
isSystemUser = true;
group = cfg.group;
description = "Headless Hyprland stream session";
};
users.groups.${cfg.group} = {};
systemd.services.hyprland-headless = {
description = "Headless Hyprland session";
documentation = ["file://${hyprlandConf}"];
wantedBy = ["multi-user.target"];
# No WAYLAND_DISPLAY and no DISPLAY here on purpose: with either set the
# compositor would pick its nested backend and try to connect to a parent
# session. Without them it drives DRM directly, and the monitor rules in
# hyprland.conf set the mode of whatever connectors it finds there.
environment =
sessionEnvironment
// {
# We are a system service: there is no user bus and no user manager to
# import the session environment into.
HYPRLAND_NO_SD_VARS = "1";
HYPRLAND_NO_CRASHREPORTER = "1";
# Ignored by aquamarine-era Hyprland, honoured by wlroots-era builds
# someone may pin in `hyprlandPackage`.
WLR_BACKENDS = "headless";
WLR_LIBINPUT_NO_DEVICES = "1";
WLR_RENDERER_ALLOW_SOFTWARE = "1";
# Ask libseat's embedded seatd for a seat with no VT.
#
# This unit is a system service, not a login, so libseat finds no
# /run/seatd.sock and no logind session and falls back to the seatd it
# links in -- whose seat is VT-bound by default. That seatd then opens
# /dev/tty0, which `cfg.user` cannot, so its client never goes active
# and every device open is refused:
#
# [libseat] Could not open target tty: Permission denied
# [libseat] Could not open VT for client
# libseat: Couldn't open device at /dev/dri/card0
# drm: Found no gpus to use, cannot continue
#
# and with the DRM backend gone there is no allocator, so
# `CBackend::create()` aborts -- the headless backend takes its
# allocator from the DRM one. SEATD_VTBOUND=0 (seatd/server.c) is the
# truth about this session on any host: there is no terminal to switch
# away from.
SEATD_VTBOUND = "0";
};
serviceConfig =
commonServiceConfig
// {
# Hyprland sends READY=1 once the session is up, so the frame server's
# `After=` is an ordering on readiness, not just on fork.
Type = "notify";
NotifyAccess = "all";
TimeoutStartSec = 60;
# A preserved runtime directory can still hold the previous run's
# sockets, and that would push the new session to `wayland-1` (and
# leave the server waiting on a dead one).
ExecStartPre = "${clearStaleSockets}";
ExecStart = lib.escapeShellArgs [
(lib.getExe cfg.hyprlandPackage)
"--config"
"${hyprlandConf}"
];
# See `openIpcDirectory` above for what this fixes and why it is
# allowed to fail the unit.
ExecStartPost = lib.mkIf cfg.sessions.enable "${openIpcDirectory}";
};
};
systemd.services.hyprland-headless-stream = {
description = "Frame server for the headless Hyprland session";
wantedBy = ["multi-user.target"];
after = ["hyprland-headless.service"];
bindsTo = ["hyprland-headless.service"];
# `captureCommand` defaults to an unqualified `grim`.
path = [pkgs.grim];
environment =
sessionEnvironment
// {
# WAYLAND_DISPLAY is set by `execServer` at start, because the socket
# name is only known once the compositor has bound it.
PYTHONUNBUFFERED = "1";
};
serviceConfig =
commonServiceConfig
// {
Type = "simple";
ExecStartPre = "${findSession} >/dev/null";
ExecStart = lib.escapeShellArgs ([execServer] ++ serverArgs);
};
};
# ── the session broker ─────────────────────────────────────────────
#
# A different capability from the frame server, and a different account: this
# one starts processes, so it runs as the operator's own user and everything
# it launches runs as that user too.
systemd.services.hhstream-sessions = lib.mkIf cfg.sessions.enable {
description = "Session broker for the headless Hyprland desktop";
wantedBy = ["multi-user.target"];
after = ["hyprland-headless.service"];
bindsTo = ["hyprland-headless.service"];
environment = {
PYTHONUNBUFFERED = "1";
};
serviceConfig = {
Type = "simple";
User = cfg.sessions.user;
# The broker does not need the group itself -- but the applications it
# launches do, and they inherit its supplementary groups. Without it a
# GUI client cannot open the compositor's socket (0770, this group) and
# dies with "Failed to connect to Wayland display".
SupplementaryGroups = [cfg.sessions.group];
RuntimeDirectory = brokerRuntimeDirName;
RuntimeDirectoryMode = "0750";
# Kept across a restart of this unit, because it is no longer only this
# unit's: the pointer driver's socket lives in it too, and systemd's
# default is to delete the directory when the unit stops. See the
# tmpfiles entry above for the failure that causes.
RuntimeDirectoryPreserve = "yes";
WorkingDirectory = brokerRuntimeDir;
UMask = "0007";
Restart = "on-failure";
RestartSec = 1;
NoNewPrivileges = true;
# Sessions must outlive the broker, because a broker restart is an
# ordinary event (an upgrade, a crash, `systemctl restart`) and the whole
# point of the registry is to adopt what it finds afterwards.
#
# systemd's default is KillMode=control-group, which SIGTERMs every
# process in the unit's cgroup when the unit stops -- i.e. it kills the
# applications from outside, undoing the broker's own care (it spawns
# them with a plain Popen precisely so its own death does not reach them).
# KillMode=process signals only the broker; the applications are left
# running and are adopted on the way back up.
KillMode = "process";
ExecStart = lib.escapeShellArgs [
(lib.getExe' cfg.package "hhstreamd")
"--socket"
controlSocket
"--runtime-dir"
brokerRuntimeDir
"--state-dir"
cfg.sessions.stateDir
"--config"
(toString (
if cfg.sessions.configFile != null then cfg.sessions.configFile else sessionsConfig
))
# Where the compositor's own session lives. The broker discovers the
# `wayland-N` socket in there and hands XDG_RUNTIME_DIR / WAYLAND_DISPLAY
# to every application it launches; the daemon was built to fail loudly
# if this directory holds no usable socket.
"--compositor-runtime-dir"
runtimeDir
];
};
};
# ── the pointer driver ─────────────────────────────────────────────
#
# A third unit, and a third capability: this one injects input. It is a
# separate process from the broker because a Wayland client needs its own
# connection and a driver blocked on the compositor must not stall session
# lifecycle (PLAN §6.5). It holds no lease -- the broker owns that -- so it
# is an executor that can be restarted at any moment.
systemd.services.hhstream-pointer = lib.mkIf (cfg.sessions.enable && cfg.sessions.pointer.enable) {
description = "Pointer input driver for the headless Hyprland desktop";
wantedBy = ["multi-user.target"];
after = ["hyprland-headless.service"];
# `BindsTo` and not merely `After`: the driver's whole state is a Wayland
# connection to that compositor, so when the compositor goes the driver
# has nothing left to drive. The broker force-releases the lease when the
# driver's socket stops answering, which is how the cursor comes back.
bindsTo = ["hyprland-headless.service"];
environment = {
PYTHONUNBUFFERED = "1";
};
serviceConfig = {
Type = "simple";
User = cfg.sessions.user;
# The compositor's runtime directory is 0750 and owned by this group,
# and the driver is a Wayland client of it: without the group it cannot
# open wayland-N at all. Same reason the broker has it, one step
# further -- the broker only needs to *find* the socket for the
# applications it launches, the driver has to connect to it itself.
SupplementaryGroups = [cfg.sessions.group];
# No `RuntimeDirectory`: /run/hhstream belongs to the broker's unit and
# to the tmpfiles entry above, and a second RuntimeDirectory= on the
# same path would delete the broker's control socket when this unit
# stopped.
WorkingDirectory = brokerRuntimeDir;
UMask = "0007";
Restart = "on-failure";
RestartSec = 1;
NoNewPrivileges = true;
# The same reasoning as the broker's, for the same reason: a driver
# restart must not take sessions down. The applications the broker
# launched are in the broker's cgroup, not this one, so `control-group`
# would not reach them today -- but this unit is `After=` the
# compositor and shares the broker's account, and KillMode=process says
# plainly that stopping the driver stops the driver and nothing else.
KillMode = "process";
# The first two flags are frozen in docs/CONTRACT-sessions.md §3.4,
# word for word. The driver defaults to both of those paths anyway;
# they are passed explicitly because the contract specifies the command
# line, and a unit that relied on the defaults would stop matching it
# the moment either default moved.
#
# The four XKB flags are the **only** path a layout has to the uploaded
# keymap, and that is worth being blunt about: the broker's TOML has a
# `[pointer]` table that `hhstreamd` reads for its lease numbers, and
# this is a different unit that never opens that file. A `[keyboard]`
# table there would be a setting an operator could change while every
# injected key stayed on `us`.
ExecStart = lib.escapeShellArgs [
(lib.getExe' cfg.package "hhstream-pointer")
"--socket"
pointerSocket
"--compositor-runtime-dir"
runtimeDir
"--xkb-layout"
cfg.sessions.keyboard.layout
"--xkb-model"
cfg.sessions.keyboard.model
"--xkb-variant"
cfg.sessions.keyboard.variant
"--xkb-options"
cfg.sessions.keyboard.options
];
};
};
# The stream daemon. A third executor beside the pointer driver, and the
# split is the driver's: `grim` blocks tens to hundreds of milliseconds, so
# the capture must not run where `touch` and `kill` are answered, and a
# LAN-facing HTTP parser must not run in the frame server whose one-socket
# contract cannot grow one (docs/CONTRACT-sessions.md §3.5).
systemd.services.hhstream-live = lib.mkIf (cfg.sessions.enable && cfg.sessions.stream.enable) {
description = "Per-session live stream for the headless Hyprland desktop";
wantedBy = ["multi-user.target"];
after = ["hyprland-headless.service"];
# `BindsTo` for the pointer driver's reason: this process captures from
# that compositor's outputs through `grim`, so when the compositor goes
# it has nothing left to capture. The broker reports such a stream as
# `attached: false` rather than pretending, and re-enabling re-attaches.
bindsTo = ["hyprland-headless.service"];
environment = {
PYTHONUNBUFFERED = "1";
# The compositor's session, not this unit's own: `grim` has to find the
# Wayland socket in here. `WAYLAND_DISPLAY` is set by `execLive` at
# start, because the socket's name is only known once the compositor
# has bound it. HOME is deliberately NOT redirected here the way the
# frame server's is -- this unit runs as the operator's account, and
# the compositor's runtime directory is not writable by it.
XDG_RUNTIME_DIR = runtimeDir;
};
serviceConfig = {
Type = "simple";
User = cfg.sessions.user;
# The compositor's runtime directory is 0750 and owned by this group,
# and `grim` is a Wayland client of it -- same reason the pointer
# driver needs the group, one step further: this one has to *capture*,
# not merely find the socket.
SupplementaryGroups = [cfg.sessions.group];
# No `RuntimeDirectory`: /run/hhstream belongs to the broker's unit and
# to the tmpfiles entry above, and a second RuntimeDirectory= on the
# same path would delete the broker's control socket when this unit
# stopped. The plan calls this out by name as the Stage 3 risk.
WorkingDirectory = brokerRuntimeDir;
UMask = "0007";
Restart = "on-failure";
RestartSec = 1;
NoNewPrivileges = true;
KillMode = "process";
# `grim` is NOT on a unit's PATH, and the symptom of leaving it off is
# a stream that serves an empty frame area without saying why --
# docs/TODO/capture-binary-and-the-unit-path.md, found the first time
# the capture ran as a unit rather than from a login shell. So the
# whole capture command is spelled out here, with grim's store path.
#
# `--capture-command=<word>` and not `--capture-command <word>`:
# MEASURED, as a unit crash-looping with
#
# hhstream-live serve: error: argument --capture-command: expected
# one argument
#
# because grim's last word is a bare `-` (its "write to stdout"), and
# argparse reads a lone dash as an option prefix rather than a value.
# The `=` form is unambiguous for every word, so it is used for every
# word rather than only the one that needs it.
# Same second line of defence as the frame server's: `BindsTo=` stops
# this unit when the compositor goes, but the compositor is only
# *ready* once its socket is bound, and `execLive` has to find that
# socket to export its name.
ExecStartPre = "${findSession} >/dev/null";
ExecStart = lib.escapeShellArgs (
[
execLive
"serve"
"--control-socket=${liveSocket}"
"--bind=${cfg.sessions.stream.bind}"
"--port=${toString cfg.sessions.stream.port}"
"--fps=${toString cfg.sessions.stream.fps}"
]
++ map (word: "--capture-command=${word}") [
(lib.getExe pkgs.grim)
"-c" # include the cursor
"-t"
"jpeg"
"-q"
"80"
"-" # write to stdout
]
);
};
};
# ── the MCP server, over HTTP ──────────────────────────────────────
#
# The fourth unit, and the first one that listens on a port rather than a
# Unix socket. That is the whole reason it exists: `mcp.enable` puts a
# stdio binary on PATH and declares nothing, because a client spawns it and
# has already passed a filesystem permission check to do so. A port is
# reachable by a caller who has not, which is the first time the bearer
# token this unit demands means anything.
#
# It runs as the broker's user, with the broker's group, for the same
# reason the pointer driver does: its tools are the `hhstream` CLI's own
# handlers called in process, and that CLI talks to a `0660` control socket
# owned by that user and opens a compositor runtime directory owned by that
# group. Running it as anything else would mean a listener that
# authenticates a caller and then cannot do a thing for them.
systemd.services.hhstream-mcp = lib.mkIf cfg.mcp.http.enable {
description = "MCP server for the headless Hyprland desktop (HTTP)";
wantedBy = ["multi-user.target"];
after = ["hyprland-headless.service" "hhstream-sessions.service"];
# `After` and `Wants`, not `BindsTo`: three of the twenty-one tools and
# two of the five resources are frame-socket verbs that answer with the
# broker down, and the rest answer exit 5, which is a true answer. A
# listener that vanished with the broker would turn that into a
# connection refused, which tells a client nothing.
wants = ["hhstream-sessions.service"];
environment = {
PYTHONUNBUFFERED = "1";
# The sockets are the CLI's own environment and there is no flag for
# them (`docs/CONTRACT-mcp.md` §2); this is the unit's half of that
# contract. The state directory is passed the same way rather than as
# `--state-dir`, so `hhstream-mcp token mint` run by an operator with
# this variable set and the unit agree by construction.
HHSTREAM_SOCKET = controlSocket;
HHSTREAM_FRAME_SOCKET = cfg.socketPath;
HHSTREAM_MCP_STATE_DIR = cfg.mcp.stateDir;
};
serviceConfig = {
Type = "simple";
User = cfg.sessions.user;
Group = cfg.sessions.group;
SupplementaryGroups = [cfg.sessions.group];
WorkingDirectory = cfg.mcp.stateDir;
# The CLI's own umask and not a tighter one, deliberately. This unit's
# tools write files an operator then reads: `shot --output` and
# `record` produce exactly the files the same verbs produce from a
# shell, and a unit that made them 0600 would be a surprising
# difference between the CLI and the tool that wraps it -- the sort
# that ends with a web server unable to read a capture and nothing
# saying why.
#
# The authorization table is not protected by this. It is `0600` by an
# explicit chmod, inside a `0700` directory declared by the tmpfiles
# entry above, which is what actually guards it.
UMask = "0022";
Restart = "on-failure";
RestartSec = 5;
# No start-rate limit, which is what makes the empty-table refusal
# usable rather than merely correct.
#
# The server exits 2 while no token exists, because a listener that
# 401s every request is almost always a forgotten `token mint` and
# "connection works, auth fails" is a far worse thing to debug than a
# unit whose `systemctl status` names the remedy. But that puts a
# freshly provisioned machine in a failed state until an operator acts,
# and systemd's default (5 starts in 10s, then give up) would leave it
# there for good -- so minting the first token would also need a
# `systemctl start` nothing told anyone about.
#
# With the limit off, the unit retries every 5 seconds and comes up on
# its own within one interval of the first mint. The cost is a journal
# line every 5 seconds while the table is empty, which names exactly
# what is wrong.
StartLimitIntervalSec = 0;
NoNewPrivileges = true;
# This unit launches nothing and adopts nothing: it is a listener in
# front of a CLI, and every process it starts (`grim`, `ffmpeg`) is
# part of answering one request. So the systemd default is right here
# and `KillMode=process` -- which the broker and the driver both need
# -- would be wrong: stopping this unit should take its children with
# it. Sessions are the broker's and live in the broker's cgroup.
ExecStart = lib.escapeShellArgs (
[
(lib.getExe' cfg.mcp.package "hhstream-mcp")
"serve"
"--http"
"--address"
cfg.mcp.http.address
"--port"
(toString cfg.mcp.http.port)
"--path"
cfg.mcp.http.path
]
++ lib.optionals (cfg.mcp.http.toolsets != null) [
"--toolsets"
(lib.concatStringsSep "," cfg.mcp.http.toolsets)
]
++ lib.concatMap (host: ["--allowed-host" host]) cfg.mcp.http.allowedHosts
++ lib.concatMap (origin: ["--allowed-origin" origin]) cfg.mcp.http.allowedOrigins
++ cfg.mcp.http.extraArgs
);
};
};
};
}