refactor: overhaul of options and features
Includes, but not limited to: - zapret2 support - declarative inbounds - proxy-ctl revamp - automatic proxy learning
This commit is contained in:
144 files changed
+13198
-14066
No files matched your search
@@ -10,7 +10,7 @@ from proxy_inbound import build_inbounds
|
||||
|
||||
def main() -> None:
|
||||
ap = argparse.ArgumentParser(
|
||||
description="Render services.proxy-suite.proxyInbounds into XRay inbounds."
|
||||
description="Render services.proxy-suite.inbounds into XRay inbounds."
|
||||
)
|
||||
ap.add_argument("--spec", required=True, help="path to the generated inbound spec JSON")
|
||||
ap.add_argument(
|
||||
|
||||
@@ -2,13 +2,14 @@
|
||||
"""Render server-side proxy inbounds and their client share links.
|
||||
|
||||
The input spec is backend-neutral: it mirrors the
|
||||
services.proxy-suite.proxyInbounds option tree, with secrets given as file
|
||||
services.proxy-suite.inbounds option tree, with secrets given as file
|
||||
paths that are read here rather than at Nix evaluation time. Only XRay is
|
||||
rendered today; a render_sing_box_inbound would sit beside render_xray_inbound
|
||||
without changing the spec or the link generator.
|
||||
"""
|
||||
|
||||
import base64
|
||||
import hashlib
|
||||
import json
|
||||
import urllib.parse
|
||||
|
||||
@@ -122,6 +123,9 @@ def _xray_stream(listener: dict, tag: str) -> dict:
|
||||
stream["tlsSettings"] = {"certificates": [certificate]}
|
||||
if tls.get("serverName"):
|
||||
stream["tlsSettings"]["serverName"] = tls["serverName"]
|
||||
# ["h3"] alone is what makes an xhttp listener serve HTTP/3, on UDP.
|
||||
if tls.get("alpn"):
|
||||
stream["tlsSettings"]["alpn"] = tls["alpn"]
|
||||
else:
|
||||
stream["security"] = "none"
|
||||
|
||||
@@ -209,11 +213,16 @@ def _link_security_params(listener: dict, server_address: str) -> dict:
|
||||
params["sid"] = short_ids[0]
|
||||
return params
|
||||
if tls["enable"] or listener["type"] == "trojan":
|
||||
return {
|
||||
params = {
|
||||
"security": "tls",
|
||||
"sni": tls.get("serverName") or server_address,
|
||||
"fp": "chrome",
|
||||
}
|
||||
# A client left to its own ALPN offers h2 and http/1.1, and so never
|
||||
# reaches an HTTP/3-only listener at all.
|
||||
if tls.get("alpn"):
|
||||
params["alpn"] = ",".join(tls["alpn"])
|
||||
return params
|
||||
return {"security": "none"}
|
||||
|
||||
|
||||
@@ -304,22 +313,52 @@ def build_listener(listener: dict, server_address: str, share_links: bool) -> di
|
||||
return {"tag": tag, "type": listener["type"], "port": _share_port(listener), "inbound": inbound, "links": links}
|
||||
|
||||
|
||||
def subscription_token(name: str, secrets: list[str]) -> str:
|
||||
"""Name of a user's subscription file, and so the secret part of its URL.
|
||||
|
||||
Derived from the user's own credentials rather than stored: there is no
|
||||
second secret to manage, it stays put for as long as they do, and rotating
|
||||
the user's uuid rotates the URL with it.
|
||||
"""
|
||||
material = "\n".join(["proxy-suite-subscription", name, *sorted(set(secrets))])
|
||||
return hashlib.sha256(material.encode("utf-8")).hexdigest()[:32]
|
||||
|
||||
|
||||
def build_inbounds(spec: dict, server_address: str) -> dict:
|
||||
"""Render a whole spec into {"inbounds": [...], "links": [...]}."""
|
||||
"""Render a whole spec into {"inbounds": [...], "links": [...],
|
||||
"subscriptions": [...]}.
|
||||
|
||||
A subscription gathers one user's links from every listener -- users are
|
||||
matched by name -- as base64 of the newline-joined links, which is what
|
||||
v2rayNG, Hiddify and NekoBox import.
|
||||
"""
|
||||
inbounds = []
|
||||
links = []
|
||||
by_user: dict[str, dict] = {}
|
||||
for listener in spec["listeners"]:
|
||||
rendered = build_listener(listener, server_address, spec.get("shareLinks", True))
|
||||
inbounds.append(rendered["inbound"])
|
||||
for index, link in enumerate(rendered["links"]):
|
||||
user = listener["users"][index]
|
||||
name = user.get("name") or f"{rendered['tag']}-{index}"
|
||||
links.append(
|
||||
{
|
||||
"tag": rendered["tag"],
|
||||
"user": user.get("name") or f"{rendered['tag']}-{index}",
|
||||
"user": name,
|
||||
"type": rendered.get("type", ""),
|
||||
"port": rendered.get("port", 0),
|
||||
"link": link,
|
||||
}
|
||||
)
|
||||
return {"inbounds": inbounds, "links": links}
|
||||
entry = by_user.setdefault(name, {"links": [], "secrets": []})
|
||||
entry["links"].append(link)
|
||||
entry["secrets"].append(_user_secret(user, listener["type"], rendered["tag"]))
|
||||
subscriptions = [
|
||||
{
|
||||
"user": name,
|
||||
"token": subscription_token(name, entry["secrets"]),
|
||||
"body": base64.b64encode("\n".join(entry["links"]).encode("utf-8")).decode("ascii"),
|
||||
}
|
||||
for name, entry in by_user.items()
|
||||
]
|
||||
return {"inbounds": inbounds, "links": links, "subscriptions": subscriptions}
|
||||
@@ -212,6 +212,11 @@ def build_outbound(
|
||||
|
||||
|
||||
def fetch_raw(url: str) -> bytes:
|
||||
# urlopen also speaks file:, ftp: and data:. This runs as root over a URL that
|
||||
# reaches it from a group-writable spool, so only the two a subscription is
|
||||
# ever served over.
|
||||
if urllib.parse.urlsplit(url).scheme not in ("http", "https"):
|
||||
raise ValueError("subscription URL must be http:// or https://")
|
||||
request = urllib.request.Request(
|
||||
url,
|
||||
headers={"User-Agent": "v2rayN/6.0"},
|
||||
|
||||
@@ -117,6 +117,21 @@ def _mk_transport(
|
||||
return None
|
||||
|
||||
|
||||
# sing-box refuses to start on a transport it does not know, so one bad share
|
||||
# link would otherwise take the whole config down with it.
|
||||
def _check_transport(transport: str, backend: str, protocol: str) -> str:
|
||||
normalized = transport.lower()
|
||||
supported = (
|
||||
SUPPORTED_XRAY_TRANSPORTS if backend == "xray" else SUPPORTED_VLESS_TRANSPORTS
|
||||
)
|
||||
if normalized not in supported:
|
||||
raise ValueError(
|
||||
f"unsupported {protocol} transport '{transport}': proxy-suite only maps "
|
||||
f"{backend}-documented transports; use raw JSON or another client/core"
|
||||
)
|
||||
return normalized
|
||||
|
||||
|
||||
def _require(params: dict, name: str, security: str) -> str:
|
||||
if name not in params:
|
||||
raise ValueError(f"{security} link is missing the '{name}' parameter")
|
||||
@@ -168,8 +183,6 @@ def _mk_auth(userinfo: str) -> "tuple[str | None, str | None]":
|
||||
def parse_vless(url: str, tag: str, backend: str = "sing-box") -> dict:
|
||||
userinfo, host, port, params = _parse_url_parts(url, "vless")
|
||||
security = params.get("security", "none")
|
||||
transport = params.get("type", "tcp")
|
||||
normalized_transport = transport.lower()
|
||||
|
||||
if "ech" in params and backend != "xray":
|
||||
raise ValueError(
|
||||
@@ -177,14 +190,9 @@ def parse_vless(url: str, tag: str, backend: str = "sing-box") -> dict:
|
||||
"share-link ECH blobs into sing-box TLS config"
|
||||
)
|
||||
|
||||
supported_transports = (
|
||||
SUPPORTED_XRAY_TRANSPORTS if backend == "xray" else SUPPORTED_VLESS_TRANSPORTS
|
||||
normalized_transport = _check_transport(
|
||||
params.get("type", "tcp"), backend, "VLESS"
|
||||
)
|
||||
if normalized_transport not in supported_transports:
|
||||
raise ValueError(
|
||||
f"unsupported VLESS transport '{transport}': proxy-suite only maps "
|
||||
f"{backend}-documented transports; use raw JSON or another client/core"
|
||||
)
|
||||
|
||||
ob: dict = {
|
||||
"type": "vless",
|
||||
@@ -237,7 +245,7 @@ def parse_vless(url: str, tag: str, backend: str = "sing-box") -> dict:
|
||||
return ob
|
||||
|
||||
|
||||
def parse_vmess(url: str, tag: str) -> dict:
|
||||
def parse_vmess(url: str, tag: str, backend: str = "sing-box") -> dict:
|
||||
b64 = url[len("vmess://") :]
|
||||
b64, _, _ = b64.partition("#")
|
||||
b64, _, _ = b64.partition("?")
|
||||
@@ -250,7 +258,7 @@ def parse_vmess(url: str, tag: str) -> dict:
|
||||
|
||||
host = str(data["add"])
|
||||
port = int(data["port"])
|
||||
net = data.get("net", "tcp")
|
||||
net = _check_transport(str(data.get("net", "tcp")), backend, "VMess")
|
||||
tls_field = str(data.get("tls", ""))
|
||||
sni = str(data.get("sni") or data.get("host") or host)
|
||||
|
||||
@@ -269,6 +277,7 @@ def parse_vmess(url: str, tag: str) -> dict:
|
||||
sni,
|
||||
fp=str(data["fp"]) if data.get("fp") else None,
|
||||
alpn=str(data["alpn"]) if data.get("alpn") else None,
|
||||
backend=backend,
|
||||
)
|
||||
|
||||
path = str(data.get("path") or "/")
|
||||
@@ -286,9 +295,9 @@ def parse_vmess(url: str, tag: str) -> dict:
|
||||
return ob
|
||||
|
||||
|
||||
def parse_trojan(url: str, tag: str) -> dict:
|
||||
def parse_trojan(url: str, tag: str, backend: str = "sing-box") -> dict:
|
||||
userinfo, host, port, params = _parse_url_parts(url, "trojan")
|
||||
transport = params.get("type", "tcp")
|
||||
transport = _check_transport(params.get("type", "tcp"), backend, "Trojan")
|
||||
|
||||
ob: dict = {
|
||||
"type": "trojan",
|
||||
@@ -297,7 +306,10 @@ def parse_trojan(url: str, tag: str) -> dict:
|
||||
"server_port": int(port),
|
||||
"password": urllib.parse.unquote(userinfo),
|
||||
"tls": _mk_tls(
|
||||
params.get("sni", host), fp=params.get("fp"), alpn=params.get("alpn")
|
||||
params.get("sni", host),
|
||||
fp=params.get("fp"),
|
||||
alpn=params.get("alpn"),
|
||||
backend=backend,
|
||||
),
|
||||
}
|
||||
|
||||
@@ -459,4 +471,6 @@ PARSERS = {
|
||||
|
||||
BACKEND_AWARE_PARSERS = {
|
||||
"vless",
|
||||
"vmess",
|
||||
"trojan",
|
||||
}
|
||||
@@ -7,7 +7,7 @@ import tempfile
|
||||
import unittest
|
||||
import urllib.parse
|
||||
|
||||
from proxy_inbound import build_inbounds, build_share_link, render_xray_inbound
|
||||
from proxy_inbound import build_inbounds, build_share_link, render_xray_inbound, subscription_token
|
||||
from proxy_parsing import build_outbound
|
||||
|
||||
|
||||
@@ -368,6 +368,56 @@ class BuildInboundsTests(unittest.TestCase):
|
||||
# what breaks XHTTP behind an HTTP/1.1 reverse proxy.
|
||||
self.assertEqual(link_params(build_share_link(spec, "vpn.example.com"))["mode"], "packet-up")
|
||||
|
||||
def test_alpn_reaches_the_inbound_and_the_link(self):
|
||||
spec = listener(
|
||||
transport={"type": "xhttp", "path": "/h3", "host": None, "mode": None, "serviceName": ""},
|
||||
tls={"enable": True, "certificateFile": "/c", "keyFile": "/k", "serverName": None, "alpn": ["h3"]},
|
||||
)
|
||||
# h3 alone is what makes XRay serve the listener as HTTP/3, on UDP.
|
||||
self.assertEqual(render_xray_inbound(spec)["streamSettings"]["tlsSettings"]["alpn"], ["h3"])
|
||||
# A client left to its own ALPN offers h2 and http/1.1 and never gets in.
|
||||
self.assertEqual(link_params(build_share_link(spec, "vpn.example.com"))["alpn"], "h3")
|
||||
plain = listener(tls={"enable": True, "certificateFile": "/c", "keyFile": "/k", "serverName": None})
|
||||
self.assertNotIn("alpn", render_xray_inbound(plain)["streamSettings"]["tlsSettings"])
|
||||
self.assertNotIn("alpn", link_params(build_share_link(plain, "vpn.example.com")))
|
||||
|
||||
def test_subscriptions_gather_each_users_links(self):
|
||||
def users(uuid_a):
|
||||
return [
|
||||
{"name": "fufsob", "uuid": uuid_a, "password": None, "passwordFile": None},
|
||||
{"name": "teri", "uuid": "uuid-teri", "password": None, "passwordFile": None},
|
||||
]
|
||||
|
||||
def spec(uuid_a="uuid-fufsob", share=True):
|
||||
return {
|
||||
"serverAddress": "vpn.example.com",
|
||||
"shareLinks": share,
|
||||
"listeners": [
|
||||
listener(tag="ws", users=users(uuid_a)),
|
||||
listener(tag="h3", port=8443, users=users(uuid_a)),
|
||||
],
|
||||
}
|
||||
|
||||
result = build_inbounds(spec(), "vpn.example.com")
|
||||
subs = {s["user"]: s for s in result["subscriptions"]}
|
||||
self.assertEqual(sorted(subs), ["fufsob", "teri"])
|
||||
# Every listener's link for that user, as clients import them.
|
||||
body = base64.b64decode(subs["fufsob"]["body"]).decode()
|
||||
self.assertEqual(
|
||||
body.split("\n"),
|
||||
[entry["link"] for entry in result["links"] if entry["user"] == "fufsob"],
|
||||
)
|
||||
self.assertEqual(len(body.split("\n")), 2)
|
||||
# Stable while the credentials are, rotated with them, never shared.
|
||||
token = subs["fufsob"]["token"]
|
||||
self.assertRegex(token, "^[0-9a-f]{32}$")
|
||||
self.assertEqual(token, subscription_token("fufsob", ["uuid-fufsob"]))
|
||||
self.assertNotEqual(token, subs["teri"]["token"])
|
||||
rotated = build_inbounds(spec(uuid_a="uuid-new"), "vpn.example.com")["subscriptions"]
|
||||
self.assertNotEqual(token, next(s["token"] for s in rotated if s["user"] == "fufsob"))
|
||||
# No links, nothing to subscribe to.
|
||||
self.assertEqual(build_inbounds(spec(share=False), "vpn.example.com")["subscriptions"], [])
|
||||
|
||||
def test_share_port_overrides_the_bound_port(self):
|
||||
spec = {
|
||||
"serverAddress": "vpn.example.com",
|
||||
|
||||
@@ -16,6 +16,11 @@ def run_xray_parser(url: str):
|
||||
return build_outbound(url, "test-outbound", backend="xray")
|
||||
|
||||
|
||||
def vmess_url(extra: dict) -> str:
|
||||
body = {"add": "example.com", "port": 443, "id": "uuid", "net": "tcp", **extra}
|
||||
return "vmess://" + base64.b64encode(json.dumps(body).encode()).decode()
|
||||
|
||||
|
||||
class BuildOutboundTests(unittest.TestCase):
|
||||
def test_vless_reality(self):
|
||||
ob = run_parser(
|
||||
@@ -290,6 +295,34 @@ class BuildOutboundTests(unittest.TestCase):
|
||||
with self.assertRaisesRegex(ValueError, "unsupported scheme"):
|
||||
run_parser("wireguard://example.com")
|
||||
|
||||
def test_trojan_xhttp_fails_loudly_on_sing_box(self):
|
||||
url = "trojan://pw@example.com:443?security=tls&type=xhttp&path=/p"
|
||||
with self.assertRaisesRegex(ValueError, "unsupported Trojan transport 'xhttp'"):
|
||||
run_parser(url)
|
||||
self.assertEqual(
|
||||
run_xray_parser(url)["streamSettings"]["network"], "xhttp"
|
||||
)
|
||||
|
||||
def test_vmess_kcp_fails_loudly(self):
|
||||
with self.assertRaisesRegex(ValueError, "unsupported VMess transport 'kcp'"):
|
||||
run_parser(vmess_url({"net": "kcp"}))
|
||||
|
||||
def test_xray_only_fingerprint_rejected_for_sing_box_trojan_and_vmess(self):
|
||||
trojan = "trojan://pw@example.com:443?security=tls&fp=unsafe"
|
||||
with self.assertRaises(ValueError):
|
||||
run_parser(trojan)
|
||||
self.assertEqual(
|
||||
run_xray_parser(trojan)["streamSettings"]["tlsSettings"]["fingerprint"],
|
||||
"unsafe",
|
||||
)
|
||||
vmess = vmess_url({"tls": "tls", "fp": "unsafe"})
|
||||
with self.assertRaises(ValueError):
|
||||
run_parser(vmess)
|
||||
self.assertEqual(
|
||||
run_xray_parser(vmess)["streamSettings"]["tlsSettings"]["fingerprint"],
|
||||
"unsafe",
|
||||
)
|
||||
|
||||
def test_backend_aware_parser_type_error_is_not_arity_fallback(self):
|
||||
def broken_parser(url: str, tag: str, backend: str):
|
||||
raise TypeError("real parser bug")
|
||||
|
||||
@@ -2,7 +2,12 @@
|
||||
|
||||
import base64
|
||||
import unittest
|
||||
from proxy_parsing import decode_subscription, parse_hybrid_subscription, parse_subscription
|
||||
from proxy_parsing import (
|
||||
decode_subscription,
|
||||
fetch_raw,
|
||||
parse_hybrid_subscription,
|
||||
parse_subscription,
|
||||
)
|
||||
|
||||
VLESS_URI = "vless://uuid@example.com:443?security=reality&pbk=pubkey&fp=chrome&sni=cdn.example.com&sid=abcd"
|
||||
VLESS_XHTTP_URI = "vless://uuid@example.com:443?type=xhttp&security=tls&sni=cdn.example.com&host=cdn.example.com&path=%2Fx"
|
||||
@@ -33,6 +38,11 @@ def run_fetcher(
|
||||
|
||||
|
||||
class FetchSubscriptionTests(unittest.TestCase):
|
||||
def test_fetch_rejects_non_http_schemes(self):
|
||||
for url in ("file:///etc/shadow", "ftp://example.com/sub", "data:text/plain,x"):
|
||||
with self.assertRaisesRegex(ValueError, "http"):
|
||||
fetch_raw(url)
|
||||
|
||||
|
||||
def test_base64_payload_mixed_protocols(self):
|
||||
payload = _make_b64_payload(VLESS_URI, SS_URI, HY2_URI)
|
||||
|
||||
Executable
+194
@@ -0,0 +1,194 @@
|
||||
#!/usr/bin/env bash
|
||||
# Refresh every hand-pinned GitHub source under pkgs/ to its latest release tag,
|
||||
# including the Go vendorHash where the package has one.
|
||||
#
|
||||
# Table columns: nix-file|owner|repo|version-key|flake-attr
|
||||
# version-key the `<key> = "...";` line holding the tag. A leading "=" means
|
||||
# "do not query GitHub, reuse the value of that key" - for sources
|
||||
# that must stay in lockstep (AWG kernel module follows tools).
|
||||
# flake-attr package built to recompute vendorHash; "-" when there is none.
|
||||
#
|
||||
# Prints one "updated <repo>: <old> -> <new>" line per change on stdout; progress
|
||||
# and errors go to stderr. `--attrs` lists the flake attrs instead.
|
||||
set -euo pipefail
|
||||
|
||||
PINS=(
|
||||
"pkgs/tg-ws-proxy.nix|Flowseal|tg-ws-proxy|rev|tg-ws-proxy"
|
||||
"pkgs/zapret2.nix|bol-van|zapret2|version|zapret2"
|
||||
"pkgs/xray.nix|XTLS|Xray-core|version|xray"
|
||||
"pkgs/amneziawg.nix|amnezia-vpn|amneziawg-tools|version|amneziawg-tools"
|
||||
"pkgs/amneziawg.nix|amnezia-vpn|amneziawg-go|userspaceVersion|amneziawg-go"
|
||||
"pkgs/amneziawg.nix|amnezia-vpn|amneziawg-linux-kernel-module|=version|-"
|
||||
)
|
||||
|
||||
FAKE_HASH="sha256-AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA="
|
||||
|
||||
if [[ "${1:-}" == "--attrs" ]]; then
|
||||
for pin in "${PINS[@]}"; do
|
||||
IFS='|' read -r _ _ _ _ attr <<<"$pin"
|
||||
[[ "$attr" == "-" ]] || printf '.#%s\n' "$attr"
|
||||
done | sort -u
|
||||
exit 0
|
||||
fi
|
||||
|
||||
cd "$(git rev-parse --show-toplevel 2>/dev/null || pwd)"
|
||||
|
||||
for cmd in curl jq nix awk; do
|
||||
command -v "$cmd" >/dev/null || { echo "$cmd is required" >&2; exit 1; }
|
||||
done
|
||||
|
||||
gh_api() {
|
||||
if [[ -n "${GITHUB_TOKEN:-}" ]]; then
|
||||
curl -fsSL -H "Authorization: Bearer ${GITHUB_TOKEN}" "$1"
|
||||
else
|
||||
curl -fsSL "$1"
|
||||
fi
|
||||
}
|
||||
|
||||
# The tags list, not releases/latest: some of these repos cut prereleases or no
|
||||
# releases at all, and releases/latest skips both (it reported v26.3.27 while
|
||||
# Xray-core was already on v26.9.9, and 404s for amneziawg-go).
|
||||
latest_tag() {
|
||||
local owner=$1 repo=$2 tag
|
||||
tag=$(gh_api "https://api.github.com/repos/${owner}/${repo}/tags?per_page=100" |
|
||||
jq -r '.[].name' | grep -E '^v?[0-9]' | sort -V | tail -n1)
|
||||
[[ -n "$tag" ]] || { echo "unable to resolve latest tag for ${owner}/${repo}" >&2; return 1; }
|
||||
printf '%s\n' "$tag"
|
||||
}
|
||||
|
||||
newest() { printf '%s\n%s\n' "$1" "$2" | sort -V | tail -n1; }
|
||||
|
||||
get_key() {
|
||||
sed -n -E "s/^[[:space:]]*$2 = \"([^\"]+)\";.*/\1/p" "$1" | head -n1
|
||||
}
|
||||
|
||||
# Replace `<attr> = "...";` with val. When repo is non-empty the search is scoped
|
||||
# to the fetchFromGitHub block of that repo, so sibling pins in the same file
|
||||
# (amneziawg.nix holds three) never clobber each other. Returns 1 if not found.
|
||||
set_attr() {
|
||||
local file=$1 repo=$2 attr=$3 val=$4 tmp
|
||||
tmp=$(mktemp)
|
||||
if awk -v repo="$repo" -v attr="$attr" -v val="$val" '
|
||||
BEGIN { region = (repo == "") }
|
||||
{
|
||||
if (repo != "" && $0 ~ ("repo = \"" repo "\";")) { region = 1 }
|
||||
else if (repo != "" && region && $0 ~ /repo = "/) { region = 0 }
|
||||
else if (region && !done && $0 ~ ("^[ \t]*" attr " = \"")) {
|
||||
sub(/"[^"]*"/, "\"" val "\""); done = 1
|
||||
}
|
||||
print
|
||||
}
|
||||
END { exit(done ? 0 : 1) }
|
||||
' "$file" >"$tmp"; then
|
||||
mv "$tmp" "$file"
|
||||
else
|
||||
rm -f "$tmp"
|
||||
return 1
|
||||
fi
|
||||
}
|
||||
|
||||
# Go packages pin a vendorHash that a source bump invalidates: poison it and let
|
||||
# the failing build report the real one.
|
||||
refresh_vendor_hash() {
|
||||
local file=$1 repo=$2 attr=$3 log got
|
||||
[[ "$attr" != "-" ]] || return 0
|
||||
set_attr "$file" "$repo" vendorHash "$FAKE_HASH" || return 0
|
||||
echo "recomputing vendorHash for ${attr}" >&2
|
||||
if log=$(nix build --no-link ".#${attr}" 2>&1); then
|
||||
echo "build of ${attr} succeeded with a placeholder vendorHash" >&2
|
||||
return 1
|
||||
fi
|
||||
got=$(grep -oE 'sha256-[A-Za-z0-9+/]{43}=' <<<"$log" | grep -vxF "$FAKE_HASH" | tail -n1)
|
||||
if [[ -z "$got" ]]; then
|
||||
echo "could not extract vendorHash for ${attr}:" >&2
|
||||
tail -n 30 <<<"$log" >&2
|
||||
return 1
|
||||
fi
|
||||
set_attr "$file" "$repo" vendorHash "$got"
|
||||
echo "updated ${repo} vendorHash: ${got}"
|
||||
}
|
||||
|
||||
|
||||
# `--self-test`: the one thing that must not break is set_attr's block scoping -
|
||||
# amneziawg.nix holds three fetchFromGitHub blocks and a vendorHash that belongs
|
||||
# to exactly one of them.
|
||||
self_test() {
|
||||
local d f
|
||||
d=$(mktemp -d)
|
||||
trap 'rm -rf "$d"' RETURN
|
||||
f="$d/fixture.nix"
|
||||
cat >"$f" <<'FIXTURE'
|
||||
version = "1.0";
|
||||
other = pkgs.a.overrideAttrs (_: {
|
||||
src = pkgs.fetchFromGitHub {
|
||||
repo = "alpha";
|
||||
hash = "sha256-ALPHA";
|
||||
};
|
||||
});
|
||||
more = pkgs.b.overrideAttrs (_: {
|
||||
src = pkgs.fetchFromGitHub {
|
||||
repo = "beta";
|
||||
hash = "sha256-BETA";
|
||||
};
|
||||
vendorHash = "sha256-VENDOR";
|
||||
});
|
||||
FIXTURE
|
||||
set_attr "$f" "" version 2.0
|
||||
set_attr "$f" alpha hash sha256-NEW
|
||||
set_attr "$f" alpha vendorHash sha256-WRONG && { echo "self-test: vendorHash leaked out of the alpha block" >&2; return 1; }
|
||||
set_attr "$f" beta vendorHash sha256-OK
|
||||
[[ "$(get_key "$f" version)" == "2.0" ]] || { echo "self-test: version not written" >&2; return 1; }
|
||||
grep -q 'hash = "sha256-NEW";' "$f" || { echo "self-test: alpha hash not written" >&2; return 1; }
|
||||
grep -q 'hash = "sha256-BETA";' "$f" || { echo "self-test: beta hash was clobbered" >&2; return 1; }
|
||||
grep -q 'vendorHash = "sha256-OK";' "$f" || { echo "self-test: beta vendorHash not written" >&2; return 1; }
|
||||
echo "self-test ok"
|
||||
}
|
||||
|
||||
if [[ "${1:-}" == "--self-test" ]]; then
|
||||
self_test
|
||||
exit 0
|
||||
fi
|
||||
|
||||
declare -A BUMPED=()
|
||||
|
||||
for pin in "${PINS[@]}"; do
|
||||
IFS='|' read -r file owner repo key attr <<<"$pin"
|
||||
[[ -f "$file" ]] || { echo "missing ${file}" >&2; exit 1; }
|
||||
|
||||
if [[ "$key" == =* ]]; then
|
||||
# Lockstep source: refetch only when the key it follows actually moved.
|
||||
key=${key#=}
|
||||
[[ -n "${BUMPED[$key]:-}" ]] || { echo "${repo}: follows ${key}, unchanged" >&2; continue; }
|
||||
new=$(get_key "$file" "$key")
|
||||
current=$new
|
||||
else
|
||||
current=$(get_key "$file" "$key")
|
||||
[[ -n "$current" ]] || { echo "could not read ${key} from ${file}" >&2; exit 1; }
|
||||
tag=$(latest_tag "$owner" "$repo")
|
||||
# Keep whatever "v" convention the file already uses.
|
||||
if [[ "$current" == v* ]]; then new=$tag; else new=${tag#v}; fi
|
||||
if [[ "$current" == "$new" ]]; then
|
||||
echo "${repo}: already at ${current}" >&2
|
||||
continue
|
||||
fi
|
||||
# These pins exist because they are ahead of nixpkgs; never walk one back.
|
||||
if [[ "$(newest "$current" "$new")" != "$new" ]]; then
|
||||
echo "${repo}: pinned ${current} is newer than upstream ${new}, keeping it" >&2
|
||||
continue
|
||||
fi
|
||||
fi
|
||||
|
||||
tag_ref=$new
|
||||
[[ "$tag_ref" == v* ]] || tag_ref="v${tag_ref}"
|
||||
hash=$(nix store prefetch-file --json --unpack \
|
||||
"https://github.com/${owner}/${repo}/archive/refs/tags/${tag_ref}.tar.gz" | jq -r '.hash')
|
||||
[[ -n "$hash" && "$hash" != "null" ]] || { echo "could not hash ${repo} ${tag_ref}" >&2; exit 1; }
|
||||
|
||||
if [[ "$current" != "$new" ]]; then
|
||||
set_attr "$file" "" "$key" "$new" || { echo "could not write ${key} in ${file}" >&2; exit 1; }
|
||||
BUMPED[$key]=1
|
||||
echo "updated ${repo}: ${current} -> ${new}"
|
||||
fi
|
||||
set_attr "$file" "$repo" hash "$hash" || { echo "could not write hash for ${repo}" >&2; exit 1; }
|
||||
refresh_vendor_hash "$file" "$repo" "$attr"
|
||||
done
|
||||
@@ -1,73 +0,0 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
|
||||
repo_root="$(git rev-parse --show-toplevel 2>/dev/null || pwd)"
|
||||
cd "$repo_root"
|
||||
|
||||
target_file="pkgs/tg-ws-proxy.nix"
|
||||
|
||||
if [[ ! -f "$target_file" ]]; then
|
||||
echo "Cannot find ${target_file}" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
if ! command -v curl >/dev/null 2>&1; then
|
||||
echo "curl command is required" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
if ! command -v jq >/dev/null 2>&1; then
|
||||
echo "jq command is required" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
if ! command -v nix >/dev/null 2>&1; then
|
||||
echo "nix command is required" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
latest_tag="$(
|
||||
curl -fsSL "https://api.github.com/repos/Flowseal/tg-ws-proxy/releases/latest" |
|
||||
jq -r '.tag_name // empty'
|
||||
)"
|
||||
|
||||
if [[ -z "$latest_tag" ]]; then
|
||||
latest_tag="$(
|
||||
curl -fsSL "https://api.github.com/repos/Flowseal/tg-ws-proxy/tags?per_page=1" |
|
||||
jq -r '.[0].name // empty'
|
||||
)"
|
||||
fi
|
||||
|
||||
if [[ -z "$latest_tag" ]]; then
|
||||
echo "Unable to resolve latest tg-ws-proxy tag" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
archive_url="https://github.com/Flowseal/tg-ws-proxy/archive/refs/tags/${latest_tag}.tar.gz"
|
||||
latest_hash="$(
|
||||
nix store prefetch-file --json --unpack "$archive_url" | jq -r '.hash'
|
||||
)"
|
||||
|
||||
if [[ -z "$latest_hash" || "$latest_hash" == "null" ]]; then
|
||||
echo "Unable to compute tg-ws-proxy source hash for ${latest_tag}" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
current_rev="$(sed -n -E 's/^[[:space:]]*rev = "([^"]+)";/\1/p' "$target_file" | head -n1)"
|
||||
current_hash="$(sed -n -E 's/^[[:space:]]*hash = "([^"]+)";/\1/p' "$target_file" | head -n1)"
|
||||
|
||||
if [[ -z "$current_rev" || -z "$current_hash" ]]; then
|
||||
echo "Could not parse current rev/hash from ${target_file}" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
if [[ "$current_rev" == "$latest_tag" && "$current_hash" == "$latest_hash" ]]; then
|
||||
echo "tg-ws-proxy is already up to date (${latest_tag})"
|
||||
exit 0
|
||||
fi
|
||||
|
||||
sed -i -E "s|(^[[:space:]]*rev = \").*(\";)|\1${latest_tag}\2|" "$target_file"
|
||||
sed -i -E "s|(^[[:space:]]*hash = \").*(\";)|\1${latest_hash}\2|" "$target_file"
|
||||
|
||||
echo "Updated tg-ws-proxy pin: ${current_rev} -> ${latest_tag}"
|
||||
echo "Updated tg-ws-proxy hash: ${current_hash} -> ${latest_hash}"
|
||||
Reference in new issue
Block a user