diff --git a/nixosModules/clanCore/zerotier/default.nix b/nixosModules/clanCore/zerotier/default.nix index 92d83c19..19b10cf5 100644 --- a/nixosModules/clanCore/zerotier/default.nix +++ b/nixosModules/clanCore/zerotier/default.nix @@ -2,6 +2,10 @@ let cfg = config.clan.networking.zerotier; facts = config.clanCore.secrets.zerotier.facts or { }; + genMoonScript = pkgs.runCommand "genmoon" { nativeBuildInputs = [ pkgs.python3 ]; } '' + install -Dm755 ${./genmoon.py} $out/bin/genmoon + patchShebangs $out/bin/genmoon + ''; networkConfig = { authTokens = [ null @@ -59,6 +63,17 @@ in zerotier network name ''; }; + moon = { + stableEndpoints = lib.mkOption { + type = lib.types.listOf lib.types.str; + default = [ ]; + description = '' + Make this machine a moon. + Other machines can join this moon by adding this moon in their config. + It will be reachable under the given stable endpoints. + ''; + }; + }; subnet = lib.mkOption { type = lib.types.nullOr lib.types.str; readOnly = true; @@ -120,11 +135,18 @@ in systemd.services.zerotierone.serviceConfig.ExecStartPre = [ "+${pkgs.writeShellScript "init-zerotier" '' cp ${config.clanCore.secrets.zerotier.secrets.zerotier-identity-secret.path} /var/lib/zerotier-one/identity.secret + zerotier-idtool getpublic /var/lib/zerotier-one/identity.secret > /var/lib/zerotier-one/identity.public ${lib.optionalString (cfg.controller.enable) '' mkdir -p /var/lib/zerotier-one/controller.d/network ln -sfT ${pkgs.writeText "net.json" (builtins.toJSON networkConfig)} /var/lib/zerotier-one/controller.d/network/${cfg.networkId}.json ''} + ${lib.optionalString (cfg.moon.stableEndpoints != []) '' + if [[ ! -f /var/lib/zerotier-one/moon.json ]]; then + zerotier-idtool initmoon /var/lib/zerotier-one/identity.public > /var/lib/zerotier-one/moon.json + fi + ${genMoonScript}/bin/genmoon /var/lib/zerotier-one/moon.json ${builtins.toFile "moon.json" (builtins.toJSON cfg.moon.stableEndpoints)} /var/lib/zerotier-one/moons.d + ''} # cleanup old networks if [[ -d /var/lib/zerotier-one/networks.d ]]; then diff --git a/nixosModules/clanCore/zerotier/genmoon.py b/nixosModules/clanCore/zerotier/genmoon.py new file mode 100644 index 00000000..4f48a90a --- /dev/null +++ b/nixosModules/clanCore/zerotier/genmoon.py @@ -0,0 +1,31 @@ +#!/usr/bin/env python3 + +import json +import subprocess +import sys +from pathlib import Path +from tempfile import NamedTemporaryFile + + +def main() -> None: + if len(sys.argv) != 4: + print("Usage: genmoon.py ") + sys.exit(1) + moon_json = sys.argv[1] + endpoint_config = sys.argv[2] + moons_d = sys.argv[3] + + moon_json = json.loads(Path(moon_json).read_text()) + moon_json["roots"][0]["stableEndpoints"] = json.loads( + Path(endpoint_config).read_text() + ) + + with NamedTemporaryFile("w") as f: + f.write(json.dumps(moon_json)) + f.flush() + Path(moons_d).mkdir(parents=True, exist_ok=True) + subprocess.run(["zerotier-idtool", "genmoon", f.name], cwd=moons_d) + + +if __name__ == "__main__": + main()