hyperhive/nix/modules/hive-forge.nix
atlas f037056015 nix/hive-{forge,gateway}: move forge to forge.<hive-domain> sub-domain (#749, mara verdict)
mara on #749:9609: "we will go with sub domains for forge and matrix
(redirected in well known in the latter case, not user visible). close /
fix PRs you have open that dont match this."

Reshapes the v1 sub-path (`<host>/forge/`) approach into a sub-domain
vhost (`forge.<host>/`) per the mara verdict. matrix gets the same
treatment in damocles's #751 follow-up.

## Why sub-domain

- forgejo's default `ROOT_URL = http://<host>/` works without any
  `X-Forwarded-Prefix` gymnastics — sub-domain hosting is the
  canonical Forgejo deploy shape, matches every upstream-doc example.
- Cookie / storage isolation between the dashboard and forge (XSS blast
  radius shrinks; a future forge XSS can't reach dashboard session).
- matches the matrix-spec pattern that #751 wires up for the
  homeserver.

## Mechanics

**forge options:**
- `services.hyperhive.forge.subdomain` — nullable str, default `"forge"`
  → rendered sub-domain is `forge.<hive-domain>`. Set to `null` to opt
  out (forge stays direct on `httpPort`); set to `""` for bare-domain
  landing (advanced, collides with dashboard).
- `services.hyperhive.forge.rootUrl` — nullable str override. When
  null, auto-derived: `http://<subdomain>.<hive>/` when gateway is on
  + subdomain set, else `http://<domain>:<httpPort>/` (direct).
- **Asserts** rootUrl ends with `/` (argus 🟡 on #754: forgejo's
  ROOT_URL contract requires trailing slash, else emits
  `https://forge.example.com.user.id` shaped garbage). Asserts
  `subdomain != null` requires `hyperhive.domain` set.

**gateway:**
- New `virtualHosts."<subdomain>.<hive-domain>"` server block —
  separate from the `"_"` catch-all. Proxies all `/` →
  `http://127.0.0.1:<forge.httpPort>/` so forgejo handles requests at
  root (no prefix translation needed; matches the upstream-default
  ROOT_URL shape).
- Git-tuned: `client_max_body_size 1G`, `proxy_read_timeout 1h`,
  `proxy_send_timeout 1h`, `proxy_buffering off`,
  `proxyWebsockets = true`. SSH stays direct on `cfg.sshPort`.
- `networking.hosts` (when `localHostsEntry = true`) now also adds
  `forge.<hive-domain> -> 127.0.0.1` for the dev loop.

## Verified

- `nix eval ROOT_URL` → `http://forge.test.local/` (default with
  gateway on)
- `nix eval ROOT_URL` with `gateway.enable = false` → `http://localhost:3000/`
  (current direct shape preserved)
- `nix eval virtualHosts attrs` → `["_", "forge.test.local"]`
- `nix eval networking.hosts` with `localHostsEntry = true` →
  `{"127.0.0.1": ["test.local", "forge.test.local"], ...}`
- bad rootUrl (no trailing /) triggers assertion at toplevel build
  with the spelled-out forgejo failure mode
- full container toplevel builds clean
  (`nixos-system-hive-gateway-26.05pre-git`)

## Migration

ROOT_URL change is a one-way migration on rebuild:
- Existing agent `git remote origin` URLs (`http://localhost:3000/...`)
  **keep working** — forgejo accepts any inbound URL; the URL on the
  agent side is unchanged.
- New clone-link copy-paste from forge UI uses `forge.<hive>/...` —
  operators copying clones after this lands need to go through the
  new sub-domain.
- Direct browsing on `:3000` shows pages with `forge.<hive>` links →
  works if hosts entry / DNS resolves, broken otherwise. Operators
  should switch to `http://forge.<hive>/`.

## Out of scope

- TLS termination (mara explicit on #15: no TLS v0)
- SSH-over-HTTPS / wildcard cert provisioning
- matrix sub-domain (damocles's #751, sibling work)

Closes #749. Addresses argus 🟡 on #754.
2026-05-31 13:38:25 +02:00

362 lines
15 KiB
Nix

{
pkgs,
lib,
config,
...
}:
let
cfg = config.services.hyperhive.forge;
gatewayCfg = config.services.hyperhive.gateway;
hyperhiveDomain = config.services.hyperhive.domain;
# Sub-domain forgejo lives at when served behind the gateway (#749,
# mara verdict at issue:9609 — sub-domain over sub-path). Defaults
# to `forge.<hive-domain>`; set to `null` to opt out of subdomain
# routing (forge stays direct on `cfg.httpPort`).
subdomain =
if cfg.subdomain == null then null else if cfg.subdomain == "" then hyperhiveDomain else "${cfg.subdomain}.${hyperhiveDomain}";
# ROOT_URL forgejo advertises in clone links + outbound URLs. When
# served behind the gateway (#749), use the sub-domain so generated
# URLs resolve cleanly through the per-subdomain server-block. When
# direct (gateway off, or operator nulled `cfg.subdomain`), keep the
# original port-3000 shape. Operators can override via `cfg.rootUrl`
# for TLS / non-default gateway ports / bespoke sub-domains.
defaultRootUrl =
if subdomain != null && gatewayCfg.enable or false then
let
portSuffix = if gatewayCfg.port == 80 then "" else ":${toString gatewayCfg.port}";
in
"http://${subdomain}${portSuffix}/"
else
"http://${cfg.domain}:${toString cfg.httpPort}/";
effectiveRootUrl = if cfg.rootUrl != null then cfg.rootUrl else defaultRootUrl;
in
{
# Private Forgejo for hyperhive agents, wrapped in a nixos-container
# so it doesn't fight any `services.forgejo` the operator already
# runs on the host. The container shares the host network namespace
# (`privateNetwork = false`) so agents reach the forge at
# `http://localhost:<httpPort>` without any extra plumbing —
# nixos-container is just here for state + systemd-unit isolation,
# not network isolation.
#
# Container name is `hive-forge` (not `h-*`), so hive-c0re's
# lifecycle scanner ignores it; the operator manages it via the
# standard `nixos-container` CLI.
#
# State lives at `/var/lib/nixos-containers/hive-forge/var/lib/forgejo/`
# and survives container restart / host reboot. To wipe, destroy the
# container.
options.services.hyperhive.forge = {
enable = lib.mkOption {
type = lib.types.bool;
default = true;
description = ''
Run hive-forge a private Forgejo (in a nixos-container) for
hyperhive agents. On by default: hive-c0re mirrors every
agent's applied config repo into the forge's `agent-configs`
org, so the forge is part of the standard install. Set
`services.hyperhive.forge.enable = false` to opt out.
'';
};
httpPort = lib.mkOption {
type = lib.types.port;
default = 3000;
description = ''
TCP port the forge serves HTTP on. Default 3000 sits outside
hyperhive's claimed ranges (dashboard 7000, every agent in
8100..8999 via FNV-1a hash). Change this if you already have
another forgejo bound to 3000.
'';
};
sshPort = lib.mkOption {
type = lib.types.port;
default = 2222;
description = ''
TCP port the forge's built-in SSH server listens on. Kept off
22 so it doesn't clash with the host's openssh. Agents push
with `ssh -p <sshPort> git@<domain>:<owner>/<repo>.git`.
'';
};
domain = lib.mkOption {
type = lib.types.str;
default = "localhost";
example = "forge.internal";
description = ''
Hostname used in repo clone URLs the forge advertises. The
container shares host netns so `localhost` works for any
agent on the same host; set a real hostname when you want
clones from outside the host to look canonical.
'';
};
package = lib.mkOption {
type = lib.types.package;
default = pkgs.forgejo;
defaultText = lib.literalExpression "pkgs.forgejo";
description = ''
Forgejo package to run inside the container. Defaults to
`pkgs.forgejo` (the latest release line) rather than the
nixpkgs-module default of `pkgs.forgejo-lts`, because LTS
lags far behind on schema and the DB easily ends up "newer
than the binary" if the operator ever ran a non-LTS forgejo
against the same state dir. Override to `pkgs.forgejo-lts`
if you actively want the slower release train.
'';
};
subdomain = lib.mkOption {
type = lib.types.nullOr lib.types.str;
default = "forge";
example = "git";
description = ''
Sub-domain label for the gateway vhost that serves forgejo
(#749). The gateway adds a `server { server_name ''${subdomain}.''${hyperhive.domain}; }`
block that proxies all `/` `http://127.0.0.1:''${httpPort}/`.
Forgejo's `ROOT_URL` auto-flips to
`http://''${subdomain}.''${hyperhive.domain}/` so clone-links +
asset references resolve cleanly through the sub-domain.
Defaults to `"forge"` ( `forge.''${hyperhive.domain}`).
Set to `null` to opt out forge stays direct on `httpPort`,
no gateway vhost. Set to the empty string `""` for a bare-domain
landing (advanced: collides with the dashboard server block).
Requires `services.hyperhive.domain` to be set. Requires
`services.hyperhive.gateway.enable = true` for the vhost to
actually exist.
The mara-call on #749:9609 picks sub-domain over sub-path for
forge + matrix (both are external standard apps with sub-domain-
native config defaults). Per-agent UIs stay on sub-path
(`/agent/<name>/`) because they're hyperhive-internal +
already base-path-aware via #731.
'';
};
rootUrl = lib.mkOption {
type = lib.types.nullOr lib.types.str;
default = null;
example = "https://forge.example.com/";
description = ''
Override the auto-derived forgejo `ROOT_URL`. When `null`
(default), `ROOT_URL` is derived from `subdomain` + gateway
state:
- gateway on + `subdomain != null` `http://<subdomain>.<hive>/`
(uses `services.hyperhive.gateway.port` when non-80)
- otherwise `http://<domain>:<httpPort>/` (direct)
Set this to a fully-qualified URL when running behind TLS
termination, a non-default gateway port, or a bespoke
sub-domain shape (e.g. `https://forge.example.com/`). Must
end with `/` per forgejo's `ROOT_URL` contract.
'';
};
openFirewall = lib.mkOption {
type = lib.types.bool;
default = false;
example = true;
description = ''
Open `httpPort` + `sshPort` in the host firewall. Off by
default (#651, secure-by-default): the forge is reachable
from the host + every agent container via `localhost` either
way (shared netns), so the firewall opens only matter for
access from outside the host. Flip to `true` when you want
the operator's browser / external git clients to hit the
forge directly. (The container shares host netns, so this
is the only firewall layer that matters.)
**Breaking change as of #651**: this used to default to
`true`. If you relied on the old default for external
reach, add `services.hyperhive.forge.openFirewall = true;`
to your host config before rebuilding.
'';
};
};
config = lib.mkIf cfg.enable {
assertions = [
{
assertion = cfg.rootUrl == null || lib.hasSuffix "/" cfg.rootUrl;
message = ''
services.hyperhive.forge.rootUrl must end with "/". forgejo's
ROOT_URL contract requires a trailing slash for correct
relative-link generation; without it forgejo emits URLs like
`https://forge.example.com.user.id` instead of
`https://forge.example.com/user.id`. Got: ${toString cfg.rootUrl}
'';
}
{
assertion =
cfg.subdomain == null
|| hyperhiveDomain != null
|| cfg.rootUrl != null;
message = ''
services.hyperhive.forge.subdomain = "${toString cfg.subdomain}"
requires services.hyperhive.domain to be set (sub-domain is
rendered as "<subdomain>.<hive-domain>"). Either set
services.hyperhive.domain, override services.hyperhive.forge.rootUrl
directly, or set services.hyperhive.forge.subdomain = null to opt
out of sub-domain routing.
'';
}
];
containers.hive-forge = {
autoStart = true;
ephemeral = false;
# Share host netns — forgejo's HTTP / SSH listeners then look
# exactly like a host-side service, no port forwarding dance,
# and agent containers (which also share host netns) reach it
# via plain `localhost`.
privateNetwork = false;
config =
{ pkgs, ... }:
let
# Build a custom static-root that is the standard forgejo data
# output with our theme CSS added. Using STATIC_ROOT_PATH instead
# of tmpfiles / bind-mounts means the theme is always present in
# the nix store — no separate hive-forge container rebuild needed,
# and no persistent-state directory involved.
staticRootWithTheme = pkgs.runCommand "forgejo-static-with-theme" { } ''
cp -r --no-preserve=mode,ownership ${cfg.package.data}/. $out/
mkdir -p $out/public/assets/css
cp ${../forge-theme/theme-catppuccin-vibec0re.css} \
$out/public/assets/css/theme-catppuccin-vibec0re.css
# Replace the default Forgejo logo + favicon with the hyperhive
# mark. Files in public/assets/img/ are served before built-ins.
mkdir -p $out/public/assets/img
cp ${../../branding/hyperhive.svg} $out/public/assets/img/logo.svg
cp ${../../branding/hyperhive.svg} $out/public/assets/img/favicon.svg
cp ${../../branding/hyperhive.png} $out/public/assets/img/logo.png
cp ${../../branding/hyperhive.png} $out/public/assets/img/favicon.png
cp ${../../branding/hyperhive.png} $out/public/assets/img/avatar_default.png
'';
in
{
system.stateVersion = "25.11";
services.forgejo = {
enable = true;
package = cfg.package;
database.type = "sqlite3";
lfs.enable = true;
settings = {
DEFAULT.APP_NAME = "HyperHive";
server = {
DOMAIN = cfg.domain;
ROOT_URL = effectiveRootUrl;
HTTP_PORT = cfg.httpPort;
START_SSH_SERVER = true;
SSH_PORT = cfg.sshPort;
SSH_LISTEN_PORT = cfg.sshPort;
BUILTIN_SSH_SERVER_USER = "git";
DISABLE_SSH = false;
# Point forgejo at our extended static root that includes
# the custom theme CSS baked straight into the nix store.
STATIC_ROOT_PATH = staticRootWithTheme;
};
# Registration off — operator seeds agent users via
# `nixos-container run hive-forge -- forgejo admin
# user create …`.
service = {
DISABLE_REGISTRATION = true;
REQUIRE_SIGNIN_VIEW = false;
};
repository = {
DEFAULT_BRANCH = "main";
DEFAULT_PRIVATE = "private";
};
# Repo migrations / pull-mirrors fetch from the source
# URL *inside* Forgejo. hyperhive code is synced from
# `localhost` (and the host LAN), which Forgejo's
# migration guard blocks by default ("cannot import from
# disallowed hosts"). Allow loopback + RFC-1918 sources
# so an in-hive mirror of the hyperhive repo works.
migrations.ALLOW_LOCALNETWORKS = true;
log.LEVEL = "Warn";
ui = {
DEFAULT_THEME = "catppuccin-vibec0re";
THEMES = "catppuccin-vibec0re,forgejo-auto,forgejo-light,forgejo-dark,gitea-auto,gitea-light,gitea-dark";
};
# Point forgejo at the GPG key generated by the
# forgejo-gpg-init oneshot below. "default" resolves to
# the first secret key found in GNUPGHOME. GNUPGHOME
# must be absolute and writeable by the forgejo user.
"repository.signing" = {
SIGNING_KEY = "default";
GNUPGHOME = "/var/lib/forgejo/.gnupg";
};
# F3 (federation) computes its data dir relative to the
# forgejo binary, which lands in the read-only nix
# store and crashes anything that touches the F3
# subsystem — including `forgejo admin user create`,
# which init-ses F3 even when ENABLED=false. Pin the
# path absolute alongside the disable so the init
# resolution succeeds before the flag is checked.
"F3" = {
ENABLED = false;
PATH = "/var/lib/forgejo/data/f3";
};
};
};
environment.systemPackages = [
pkgs.forgejo
pkgs.gnupg
];
# Generate a GPG signing key for Forgejo on first boot so UI
# merges produce signed commits instead of erroring "no key to
# sign with". The key lives in forgejo's persistent state dir
# (/var/lib/forgejo/.gnupg) and survives container restarts.
# The stamp file prevents re-generation on subsequent boots.
# Service runs as the forgejo user so file ownership is correct.
systemd.services.forgejo-gpg-init = {
description = "generate GPG signing key for Forgejo (once)";
# Start before forgejo so the key is ready when forgejo reads
# repository.signing config on startup.
wantedBy = [ "forgejo.service" ];
before = [ "forgejo.service" ];
unitConfig.ConditionPathExists = "!/var/lib/forgejo/.gnupg/hive-key-init.stamp";
serviceConfig = {
Type = "oneshot";
RemainAfterExit = true;
User = "forgejo";
Group = "forgejo";
};
environment.GNUPGHOME = "/var/lib/forgejo/.gnupg";
path = [
pkgs.gnupg
pkgs.coreutils
];
script = ''
mkdir -p "$GNUPGHOME"
chmod 700 "$GNUPGHOME"
gpg --batch --gen-key <<'EOF'
%no-protection
Key-Type: RSA
Key-Length: 4096
Name-Real: HyperHive Forge
Name-Email: forgejo@hive
Expire-Date: 0
EOF
touch "$GNUPGHOME/hive-key-init.stamp"
'';
};
};
};
networking.firewall = lib.mkIf cfg.openFirewall {
allowedTCPPorts = [
cfg.httpPort
cfg.sshPort
];
};
};
}