# modules/features/pentest/update.nix — `pentest-update`: move the pins in both _pkgs files (default.nix + assets.nix)
# forward, deliberately.
#
# pentest-update report what is newer upstream (changes nothing)
# pentest-update --apply rewrite the revs and hashes in place
#
# It never commits, and it never runs during a rebuild: pinning is a decision,
# not a side effect. After --apply, read `jj diff` and rebuild — if an upstream
# renamed an asset, payloads.nix's `pick` fails the build with the name it
# could not find, which is the point of pinning in the first place.
{ ... }:
{
flake.nixosModules.pentest-update =
{ config, pkgs, lib, ... }:
let
on = config.daemon.pentest.enable;
script = pkgs.writeText "pentest-update.py" ''
"""Re-pin a pentest pin file (_pkgs/default.nix or _pkgs/assets.nix)."""
import json, os, re, subprocess, sys, urllib.error, urllib.request
APPLY = "--apply" in sys.argv
ROOT = os.environ.get("NIXDAEMON", os.path.expanduser("~/NixDaemon"))
# The file to re-pin, chosen by the wrapper so one script serves both
# _pkgs/default.nix (derivations) and _pkgs/assets.nix (the release
# table). Both use the same `url =`/`hash =` and fetchFromGitHub shapes.
PKGS = os.environ.get("PENTEST_PKGS_FILE",
os.path.join(ROOT, "modules/features/pentest/_pkgs/default.nix"))
print("── " + os.path.relpath(PKGS, ROOT))
def api(path):
req = urllib.request.Request(
"https://api.github.com" + path,
headers={"Accept": "application/vnd.github+json",
"User-Agent": "pentest-update"},
)
tok = os.environ.get("GITHUB_TOKEN") or os.environ.get("GH_TOKEN")
if tok:
req.add_header("Authorization", "Bearer " + tok)
with urllib.request.urlopen(req, timeout=30) as r:
return json.load(r)
def prefetch_unpacked(url):
h = subprocess.run(["nix-prefetch-url", "--unpack", "--type", "sha256", url],
capture_output=True, text=True).stdout.strip().splitlines()
if not h:
return None
return subprocess.run(["nix", "hash", "convert", "--hash-algo", "sha256",
"--to", "sri", h[-1]],
capture_output=True, text=True).stdout.strip()
def prefetch_file(url):
out = subprocess.run(["nix", "store", "prefetch-file", "--json", url],
capture_output=True, text=True).stdout
try:
return json.loads(out)["hash"]
except Exception:
return None
if not os.path.exists(PKGS):
sys.exit("pentest-update: cannot find " + PKGS + " (set $NIXDAEMON)")
text = open(PKGS).read()
original = text
changes, problems = [], []
# fetchFromGitHub pins: owner / repo / rev / hash, in that order.
gh = re.compile(
r'owner\s*=\s*"(?P<owner>[^"]+)";\s*\n\s*'
r'repo\s*=\s*"(?P<repo>[^"]+)";\s*\n\s*'
r'rev\s*=\s*"(?P<rev>[0-9a-f]{40})";\s*\n\s*'
r'hash\s*=\s*"(?P<hash>sha256-[^"]+)";')
for m in list(gh.finditer(text)):
slug = m.group("owner") + "/" + m.group("repo")
try:
head = api("/repos/" + slug + "/commits/HEAD")["sha"]
except (urllib.error.URLError, urllib.error.HTTPError, KeyError) as e:
problems.append(slug + ": " + str(e))
continue
if head == m.group("rev"):
print(" up to date " + slug + " @ " + head[:12])
continue
print(" NEWER " + slug + ": " + m.group("rev")[:12] + " -> " + head[:12])
if not APPLY:
continue
new_hash = prefetch_unpacked(
"https://github.com/" + slug + "/archive/" + head + ".tar.gz")
if not new_hash:
problems.append(slug + ": prefetch failed, left alone")
continue
block = m.group(0)
text = text.replace(
block,
block.replace(m.group("rev"), head).replace(m.group("hash"), new_hash),
1)
changes.append(slug)
# Release-asset pins: .../releases/download/<tag>/<asset>
rel = re.compile(
r'https://github\.com/(?P<slug>[^/]+/[^/]+)/releases/download/'
r'(?P<tag>[^/"]+)/(?P<asset>[^"/]+)')
seen = set()
# A derivation that builds its URL with Nix interpolation leaves the
# literal text of that interpolation where the tag should be, e.g.
# a dollar-brace version reference. Comparing THAT against the real
# latest tag reported three pins as newer when all three were current —
# a tool that cries "newer" about nothing is worse than useless. So
# resolve it from the nearest preceding `version = "…";`.
def resolve_tag(text, tag, upto):
if "''${" not in tag:
return tag
vers = re.findall(r'version\s*=\s*"([^"]+)"', text[:upto])
if not vers:
return None
return re.sub(r'\$\{version\}', vers[-1], tag)
for m in rel.finditer(original):
slug = m.group("slug")
tag = resolve_tag(original, m.group("tag"), m.start())
if tag is None:
problems.append(slug + ": pinned tag is interpolated and could "
"not be resolved; check it by hand")
continue
if (slug, tag) in seen:
continue
seen.add((slug, tag))
try:
latest = api("/repos/" + slug + "/releases/latest")["tag_name"]
except (urllib.error.URLError, urllib.error.HTTPError, KeyError) as e:
problems.append(slug + ": " + str(e))
continue
if latest == tag:
print(" up to date " + slug + " release " + tag)
continue
print(" NEWER " + slug + " release: " + tag + " -> " + latest)
if not APPLY:
continue
# Re-point every asset of this slug/tag, hashing each new file.
ok = True
for a in {mm.group("asset") for mm in rel.finditer(original)
if mm.group("slug") == slug and mm.group("tag") == tag}:
url = ("https://github.com/" + slug + "/releases/download/"
+ latest + "/" + a)
h = prefetch_file(url)
if not h:
problems.append(slug + "/" + a + ": not in " + latest + ", left alone")
ok = False
continue
old_url = ("https://github.com/" + slug + "/releases/download/"
+ tag + "/" + a)
old_block = re.search(
re.escape(old_url) + r'";\s*\n\s*hash\s*=\s*"(sha256-[^"]+)"', text)
if old_block:
text = text.replace(old_block.group(1), h, 1)
text = text.replace(old_url, url)
if ok:
changes.append(slug + " (release " + latest + ")")
# The version string often appears separately; flag it.
problems.append(slug + ": check the `version =` string still says "
+ latest)
if problems:
print("\nneeds your attention:")
for p in problems:
print(" " + p)
if not APPLY:
print("\nnothing written. Re-run with --apply to re-pin.")
sys.exit(0)
if text == original:
print("\nno changes to write.")
sys.exit(0)
open(PKGS, "w").write(text)
print("\nrewrote " + PKGS + " (" + ", ".join(changes) + ")")
print("Review it, rebuild, then commit yourself — this never commits.")
'';
pentest-update = pkgs.writeShellScriptBin "pentest-update" ''
set -uo pipefail
PATH=${lib.makeBinPath [ pkgs.nix pkgs.nix-prefetch-scripts pkgs.coreutils ]}:$PATH
ROOT="''${NIXDAEMON:-$HOME/NixDaemon}"
rc=0
# Both pin files, one script. assets.nix is the big release table;
# default.nix is the derivations (SharpCollection, mimikatz, scripts).
for f in \
"$ROOT/modules/features/pentest/_pkgs/default.nix" \
"$ROOT/modules/features/pentest/_pkgs/assets.nix"; do
PENTEST_PKGS_FILE="$f" ${pkgs.python3}/bin/python3 ${script} "$@" || rc=$?
done
exit $rc
'';
in
{
config = lib.mkIf on {
environment.systemPackages = [ pentest-update ];
};
};
}