diff --git a/flake.nix b/flake.nix index 374de5e..5ac5311 100644 --- a/flake.nix +++ b/flake.nix @@ -136,33 +136,7 @@ pkgs.git pkgs.nix ]; - text = '' - set -euo pipefail - - repo_root="$(git rev-parse --show-toplevel 2>/dev/null || true)" - - if [[ -z "''${repo_root}" || ! -f "''${repo_root}/flake.nix" ]]; then - echo "run this helper from inside the proxy-suite-flake repository" >&2 - exit 1 - fi - - options_output_path="$(nix build --no-link --print-out-paths "''${repo_root}#optionsDoc")" - readme_output_path="$(nix build --no-link --print-out-paths "''${repo_root}#readmeDoc")" - - mkdir -p "''${repo_root}/docs" - rm -rf "''${repo_root}/docs/options" - cp -r --no-preserve=mode,ownership "''${options_output_path}" "''${repo_root}/docs/options" - install -Dm644 "''${readme_output_path}" "''${repo_root}/README.md" - - # After the README, whose blocks are among them. - snippets_output_path="$(nix build --no-link --print-out-paths "''${repo_root}#usageSnippets")" - rm -rf "''${repo_root}/docs/usage/.snippets" - cp -r --no-preserve=mode,ownership "''${snippets_output_path}" "''${repo_root}/docs/usage/.snippets" - - echo "updated ''${repo_root}/docs/options/" - echo "updated ''${repo_root}/README.md" - echo "updated ''${repo_root}/docs/usage/.snippets/" - ''; + text = builtins.readFile ./nix/update-docs.sh; }; in { diff --git a/modules/proxy-suite/autoproxy-render.nix b/modules/proxy-suite/autoproxy-render.nix index f2bf589..9fdb3d8 100644 --- a/modules/proxy-suite/autoproxy-render.nix +++ b/modules/proxy-suite/autoproxy-render.nix @@ -10,31 +10,16 @@ ifPrivileged, }: -pkgs.writeShellScript "proxy-suite-autoproxy" '' - set -euo pipefail - # $1 - probe-exits.json (index -> tag -> path), $2 - state.json - export PATH=${ - pkgs.lib.makeBinPath [ +let + fillTemplate = import ./lib/fill-template.nix; +in +pkgs.writeShellScript "proxy-suite-autoproxy" ( + fillTemplate ./autoproxy-render.template.sh { + path = pkgs.lib.makeBinPath [ pkgs.coreutils pkgs.jq - ] + ]; + inherit serviceUser; + groupArg = ifPrivileged "-g ${serviceUser} "; } - - jq -c '.[]' "$1" | while IFS= read -r exit; do - tag=$(jq -r '.tag' <<<"$exit") - path=$(jq -r '.path' <<<"$exit") - # sing-box, running as ${serviceUser}, watches this directory to reload the - # files: that takes read on it, not just the search the state dir grants. - # Asserted on every render, since StateDirectory= re-owns the tree when the - # units' Group= changes. - install -d -m 0750 ${ifPrivileged "-g ${serviceUser} "}"$(dirname "$path")" - # Written aside and renamed into place: sing-box reloads on rename (as well - # as on in-place writes), and it never reads a half-written file. - jq -c --arg t "$tag" ' - [(.domains // {}) | to_entries[] | select(.value.exit == $t) | .key] as $d - | {version: 1, rules: (if ($d | length) > 0 then [{domain_suffix: $d}] else [] end)} - ' "$2" > "$path.tmp" - chmod 644 "$path.tmp" - mv -f "$path.tmp" "$path" - done -'' +) diff --git a/modules/proxy-suite/autoproxy-render.template.sh b/modules/proxy-suite/autoproxy-render.template.sh new file mode 100644 index 0000000..c5f7438 --- /dev/null +++ b/modules/proxy-suite/autoproxy-render.template.sh @@ -0,0 +1,21 @@ +set -euo pipefail +# $1 - probe-exits.json (index -> tag -> path), $2 - state.json +export PATH=@path@ + +jq -c '.[]' "$1" | while IFS= read -r exit; do + tag=$(jq -r '.tag' <<<"$exit") + path=$(jq -r '.path' <<<"$exit") + # sing-box, running as @serviceUser@, watches this directory to reload the + # files: that takes read on it, not just the search the state dir grants. + # Asserted on every render, since StateDirectory= re-owns the tree when the + # units' Group= changes. + install -d -m 0750 @groupArg@"$(dirname "$path")" + # Written aside and renamed into place: sing-box reloads on rename (as well + # as on in-place writes), and it never reads a half-written file. + jq -c --arg t "$tag" ' + [(.domains // {}) | to_entries[] | select(.value.exit == $t) | .key] as $d + | {version: 1, rules: (if ($d | length) > 0 then [{domain_suffix: $d}] else [] end)} + ' "$2" > "$path.tmp" + chmod 644 "$path.tmp" + mv -f "$path.tmp" "$path" +done diff --git a/modules/proxy-suite/autoproxy-run.template.sh b/modules/proxy-suite/autoproxy-run.template.sh new file mode 100644 index 0000000..a74730b --- /dev/null +++ b/modules/proxy-suite/autoproxy-run.template.sh @@ -0,0 +1,381 @@ +set -euo pipefail +export PATH=@path@ + +# --requests-only: just the `proxy-ctl proxy auto learn|forget|clear` requests. +mode=${1:-full} + +# Overridable to rehearse a run against a scratch copy; the units never set them. +state_dir=${AUTOPROXY_STATE_DIR:-@stateDir@} +export PROBE_EXITS_FILE=${PROBE_EXITS_FILE:-@runtimeDir@/proxy-suite-socks/probe-exits.json} +index=$PROBE_EXITS_FILE +state="$state_dir/state.json" +requests="$state_dir/requests" +edits="$state_dir/edits" +now=$(date +%s) +ttl=$(( @ttlDays@ * 86400 )) + +install -d -m @stateDirMode@ "$state_dir" + +# Timer runs and learn requests take turns on the state. +exec 9> "$state_dir/lock" +flock 9 + +# Leftovers of a run that died partway; taken requests go back in line. +rm -f "$state_dir/verdicts.json" "$state_dir/proxied-domains.txt" "$state".?????? "$state_dir/samples.taking" +for queue in "$requests" "$edits"; do + if [ -e "$queue.taking" ]; then + cat "$queue.taking" >> "$queue" + rm -f "$queue.taking" + # Made here by root: the group appends to it too. + chmod 0660 "$queue" + fi +done + +if [ -e "$state" ] && ! jq -e 'type == "object"' "$state" > /dev/null 2>&1; then + echo "$state is unreadable; set aside as $state.broken, starting fresh" >&2 + mv -f "$state" "$state.broken" +fi +[ -s "$state" ] || echo '{"domains":{},"hosts":{},"exits":{},"backlog":{}}' > "$state" + +# Written aside and renamed, so a killed run never truncates the state. +update() { + local tmp + tmp=$(mktemp "$state.XXXXXX") + if ! jq "$@" "$state" > "$tmp"; then + rm -f "$tmp" + echo "could not update $state; it is left as it was" >&2 + return 1 + fi + # mktemp makes it 0600; the state dir is 0751, so group-readable is enough. + chmod 0640 "$tmp" + mv -f "$tmp" "$state" +} + +# --- 0. forget what `proxy-ctl proxy auto forget|relearn|clear` asked to --- +# Before anything else, and even with the proxy stopped: its start renders the +# rule-sets from the state again. +edited="" +if [ -s "$edits" ]; then + mv -f "$edits" "$edits.taking" + while read -r op dom; do + case "$op" in + forget) + [[ "$dom" =~ ^[a-zA-Z0-9._-]+\.[a-zA-Z]{2,}$ ]] || continue + update --arg op forget --arg d "$dom" -f @editJq@ + echo "forgot $dom" + ;; + clear) + update --arg op clear --arg d "" -f @editJq@ + echo "forgot everything learned" + ;; + *) continue ;; + esac + edited=1 + done < "$edits.taking" + rm -f "$edits.taking" +fi + +if [ ! -r "$index" ]; then + echo "no probe listeners - is proxy-suite-socks running with autoProxy on?" + exit 0 +fi + +# Routes through an outbound disabled since (`proxy-ctl proxy outbounds disable`) +# are forgotten like the above, so their domains get probed again without it. +inventory="$(dirname "$index")/outbounds.json" +if [ -r "$inventory" ]; then + while IFS=$'\t' read -r dom exit; do + echo "forgot $dom: its exit $exit is disabled" + update --arg op forget --arg d "$dom" -f @editJq@ + edited=1 + done < <(jq -r --slurpfile inv "$inventory" '($inv[0].disabled // []) as $off + | (.domains // {}) | to_entries[] | select(.value.exit as $e | $off | index([$e])) + | "\(.key)\t\(.value.exit)"' "$state") +fi +[ -z "$edited" ] || @render@ "$index" "$state" + +# $1 JSON array of exit tags, $2 registrable domain, $3 wall:|refused|slow. +strike() { + update --argjson tags "$1" --arg d "$2" --arg why "$3" --argjson now "$now" --argjson ttl "$ttl" \ + -f @strikeJq@ +} + +# $1 registrable domain, $2 host probed, $3 probe JSON. Routes apply to the +# whole domain (geo-blocks are drawn around sites); other verdicts only to +# the host probed. +record() { + update --arg d "$1" --arg h "$2" --argjson r "$3" --argjson now "$now" ' + (if $r.verdict == "destination" then + .domains[$d] = {verdict: "destination", exit: $r.exit, host: $h, + path: ($r.path // "/"), at: $now} + else . end) + | .hosts[$h] = { + domain: $d, + verdict: ($r.verdict // "error"), + exit: (if $r.verdict == "destination" then $r.exit else null end), + at: $now + } + | del(.backlog[$h])' + # Exits refused on the path another egress reached: by a block page + # (wall:, the site turning the address away) or by the origin. + local t why + while IFS=$'\t' read -r t why; do + strike "$(jq -cn --arg t "$t" '[$t]')" "$1" "$why" + done < <(jq -r '(.path // "") as $p | .exit as $x + | ([(.exits // [])[] | select(.tag == $x and .path == $p) | .judgement][0]) as $won + | if $x == null then empty else + # An origin refusal only counts against an exit when the winner got content. + [(.exits // [])[] | select(.path == $p and .tag != "direct" and .tag != $x + and (.judgement == "wall" or (.judgement == "blocked" and $won == "ok"))) + | {tag, why: (if .judgement == "wall" then "wall:" + .block else "refused" end)}] + | unique_by(.tag)[] | "\(.tag)\t\(.why)" + end' <<<"$3") +} + +# Prefixes each host line with "registrable-domain". +# ponytail: last two labels, or three under a short list of two-label +# suffixes. Switch to the Public Suffix List if a domain gets merged wrongly. +to_reg() { + awk -F'\t' ' + BEGIN { + n = split("co.uk org.uk ac.uk gov.uk com.au net.au org.au co.jp ne.jp or.jp com.br com.tr co.kr com.cn com.hk co.in co.za com.ua com.mx co.nz", s, " ") + for (i = 1; i <= n; i++) two[s[i]] = 1 + } + { + n = split($1, l, ".") + if (n < 2) next + k = (n >= 3 && (l[n - 1] "." l[n]) in two) ? l[n - 2] "." l[n - 1] "." l[n] : l[n - 1] "." l[n] + print k "\t" $0 + }' +} + +# The pinned direct listener, since TUN/TProxy capture --noproxy too. +direct_url=$(jq -r '.[0] | "http://127.0.0.1:\(.port)"' "$index") + +# --- 1. verdicts are about this host's address; drop them if it changed --- +egress=$(curl -sS -f --proxy "$direct_url" --max-time 10 https://api.ipify.org 2>/dev/null || true) +# An error page or a captive portal must not pass for a new address: anything +# that is not one discards every verdict this host learned. +[[ "$egress" =~ ^[0-9a-fA-F.:]+$ ]] || egress="" +if [ -n "$egress" ] && [ "$(jq -r '.egress // ""' "$state")" != "$egress" ]; then + echo "egress is now $egress; discarding everything learned for the old address" + update --arg e "$egress" \ + '{egress: $e, domains: {}, hosts: {}, exits: {}, backlog: (.backlog // {}), lastRun: (.lastRun // 0)}' +fi + +# --- 2. which network (AS) each exit leaves from, once per TTL --- +while IFS=$'\t' read -r tag port; do + at=$(jq -r --arg t "$tag" '.exits[$t].at // 0' "$state") + [ $(( now - at )) -ge "$ttl" ] || continue + info=$(curl -sS --proxy "http://127.0.0.1:$port" --max-time 10 https://ipinfo.io/json 2>/dev/null || true) + ip=$(jq -r '.ip // empty' <<<"$info" 2>/dev/null || true) + asn=$(jq -r '(.org // "") | split(" ")[0]' <<<"$info" 2>/dev/null || true) + [ -n "$ip" ] || continue + update --arg t "$tag" --arg ip "$ip" --arg asn "$asn" --argjson now "$now" \ + '.exits[$t] += {ip: $ip, asn: $asn, at: $now}' +done < <(jq -r '.[] | "\(.tag)\t\(.port)"' "$index") + +# --- 2b. strikes older than a TTL stop counting against an exit --- +strike '[]' "" "" + +# See autoproxy-rounds.jq: one exit per AS, then the rest, bad exits last. +rounds=$(jq -c --slurpfile s "$state" -f @roundsJq@ "$index") +round1=$(jq -r .r1 <<<"$rounds") +round2=$(jq -r .r2 <<<"$rounds") + +# Every probe goes through here: a zero exit with nothing on stdout is no verdict +# either, and empty is the one answer that slips through the checks downstream -- +# jq reads it as no input at all, so `.verdict // "error"' yields "" rather than +# "error", and `--argjson r ""' then kills the run. Stdin is the caller's loop. +probe_json() { + local out + out=$(proxy-ctl proxy auto probe --json "$@" < /dev/null 2>/dev/null || true) + [ -n "$out" ] || out='{}' + printf '%s' "$out" +} + +walk() { + local out first verdict + out=$(probe_json --exits "$round1" "$1") + verdict=$(jq -r '.verdict // "error"' <<<"$out") + if { [ "$verdict" = both-fail ] || [ "$verdict" = unreachable ]; } && [ -n "$round2" ]; then + first=$out + out=$(probe_json --exits "$round2" "$1") + # Round 1's refusals count against its exits too (see record). + out=$(jq -c --argjson f "$first" '.exits = ($f.exits // []) + (.exits // [])' <<<"$out") + fi + printf '%s' "$out" +} + +# Route changes take effect immediately, not at the end of the run. +publish() { @render@ "$index" "$state"; } + +requeue=() +if [ "$mode" = full ]; then + # --- 3. re-check remembered exits, once per TTL --- + # Probed routes only; slowness routes are judged by the sampler (4b). + while IFS=$'\t' read -r dom host exit; do + out=$(probe_json --exits "$exit" "$host") + verdict=$(jq -r '.verdict // "error"' <<<"$out") + if [ "$verdict" = destination ] && [ "$(jq -r '.exit // ""' <<<"$out")" = "$exit" ]; then + update --arg d "$dom" --argjson now "$now" '.domains[$d].at = $now' + elif [ "$verdict" = ok ]; then + echo "recheck $dom: reachable directly now, dropping $exit" + update --arg d "$dom" 'del(.domains[$d])' + record "$dom" "$host" "$out" + publish + else + echo "recheck $dom: $exit no longer works ($verdict), walking again" + update --arg d "$dom" 'del(.domains[$d])' + publish + requeue+=("$dom"$'\t'"$host") + fi + done < <(jq -r --argjson now "$now" --argjson every "$ttl" ' + .domains | to_entries[] + | select(.value.verdict == "destination" and ($now - .value.at) >= $every) + | "\(.key)\t\(.value.host)\t\(.value.exit)"' "$state") + + # --- 4. what clients dialled since the last run, counted per host --- + # Hit counts accumulate in a backlog that survives between runs. + last=$(jq -r '.lastRun // 0' "$state") + if [ "$last" -gt 0 ]; then since="@$last"; else since="-@interval@"; fi + dialled=$( + @journalctl@ -u proxy-suite-inbounds --since "$since" --no-pager -o cat 2>/dev/null | + sed -n 's/.* accepted tcp:\([a-zA-Z0-9._-]*\):[0-9]*.*/\1/p' | + grep -E '^[a-zA-Z0-9._-]+\.[a-zA-Z]{2,}$' | + @excludeHosts@ + to_reg || true + ) + counts=$( + printf '%s\n' "$dialled" | + awk -F'\t' 'NF == 2 { n[$2]++; d[$2] = $1 } END { for (h in n) print h "\t" d[h] "\t" n[h] }' | + jq -R -s -c 'split("\n") | map(select(length > 0) | split("\t") + | {key: .[0], value: {domain: .[1], hits: (.[2] | tonumber)}}) | from_entries' + ) + # Skipped: hosts of an already routed domain, hosts judged within the TTL. + # Dropped: entries older than the TTL, and those a route now covers; host + # verdicts past the TTL, which would only be probed again anyway. + update --argjson c "$counts" --argjson now "$now" --argjson ttl "$ttl" ' + . as $s + | .lastRun = $now + | .hosts |= with_entries(select(.value.at + $ttl > $now)) + | .backlog = (reduce ($c | to_entries[]) as $e (($s.backlog // {}); + if ($s.domains[$e.value.domain].exit != null) + or ((($s.hosts[$e.key].at // 0) + $ttl) > $now) + then . + else .[$e.key] = { + domain: $e.value.domain, + hits: ((.[$e.key].hits // 0) + $e.value.hits), + first: (.[$e.key].first // $now) + } end)) + | .backlog |= with_entries(select(.value.first + $ttl > $now + and $s.domains[.value.domain].exit == null))' + + # --- 4b. what the sampler saw crawl (see autoproxy-slow-judge.jq) --- + if [ -s "$state_dir/samples" ]; then + mv -f "$state_dir/samples" "$state_dir/samples.taking" + # Not `|| echo '[]'`: a grep that matches nothing fails the pipeline after + # jq already printed [], and "[]\n[]" is no JSON for --argjson. + obs=$( + grep -E '^[a-zA-Z0-9._-]+\.[a-zA-Z]{2,}'$'\t' "$state_dir/samples.taking" | + @excludeSampleHosts@ + to_reg | + jq -R -s -c 'split("\n") | map(select(length > 0) | split("\t") + | {d: .[0], h: .[1], exit: .[2], slow: (.[3] == "slow"), peak: (.[4] | tonumber)})' || + true + ) + [ -n "$obs" ] || obs='[]' + rm -f "$state_dir/samples.taking" + before=$(jq -c '.domains' "$state") + update --argjson o "$obs" --argjson now "$now" --argjson ttl "$ttl" --argjson hits 3 \ + -f @slowJudgeJq@ + + # Each crawling destination gets the next exit, in probe order, that + # answers it as well as direct does (`probe --via`). None left: it + # stays direct for a TTL. + while IFS=$'\t' read -r dom host tried; do + was=${tried##*,} + # It crawled twice on the exit it was routed through. + [ -z "$was" ] || strike "$(jq -cn --arg t "$was" '[$t]')" "$dom" slow + via="" + while IFS= read -r tag; do + [[ ",$tried," != *",$tag,"* ]] || continue + tried="${tried:+$tried,}$tag" + out=$(probe_json --via "$tag" "$host") + verdict=$(jq -r '.verdict // ""' <<<"$out" 2>/dev/null || true) + if [ "$verdict" = ok ]; then + via=$tag + break + fi + # Refused what direct gets, by a block page or by the origin. + if [ "$verdict" = blocked ]; then + why=$(jq -r --arg t "$tag" '[.exits[] | select(.tag == $t)] as $r + | [$r[] | select(.judgement == "wall") | "wall:" + .block][0] + // (if any($r[]; .judgement == "blocked") then "refused" else "" end)' <<<"$out" 2>/dev/null || true) + [ -z "$why" ] || strike "$(jq -cn --arg t "$tag" '[$t]')" "$dom" "$why" + fi + done < <(jq -r '.ordered[]' <<<"$rounds") + if [ -n "$via" ]; then + echo "slow $dom: crawls ${was:+via $was}${was:-directly}, routed via $via" + update --arg d "$dom" --arg h "$host" --arg e "$via" --arg tried "$tried" --argjson now "$now" ' + .domains[$d] = {verdict: "slow", exit: $e, host: $h, at: $now, tried: ($tried | split(","))} + | del(.slowWant[$d])' + else + echo "slow $dom: crawls ${was:+via $was}${was:-directly}, and no other exit reaches it; left direct" + update --arg d "$dom" --argjson until $(( now + ttl )) '.slowSkip[$d] = $until | del(.slowWant[$d])' + fi + done < <(jq -r '(.slowWant // {}) | to_entries[] + | "\(.key)\t\(.value.host)\t\(.value.tried | join(","))"' "$state") + + [ "$(jq -c '.domains' "$state")" = "$before" ] || publish + fi +fi + +# --- 5. probe: requests (uncapped), then broken routes, then the backlog --- +asked=() +if [ -s "$requests" ]; then + mv -f "$requests" "$requests.taking" + mapfile -t asked < <(grep -E '^[a-zA-Z0-9._-]+\.[a-zA-Z]{2,}$' "$requests.taking" | to_reg || true) + rm -f "$requests.taking" +fi +backlog=() +if [ "$mode" = full ]; then + mapfile -t backlog < <(jq -r --argjson now "$now" --argjson ttl "$ttl" ' + . as $s | (.backlog // {}) | to_entries + | map(select(($s.domains[.value.domain].exit == null) + and ((($s.hosts[.key].at // 0) + $ttl) <= $now))) + | sort_by(-.value.hits) | .[] | "\(.value.domain)\t\(.key)"' "$state") +fi + +declare -A seen routed +probe_row() { + local dom=${1%%$'\t'*} host=${1#*$'\t'} out + { [ -z "${seen[$host]:-}" ] && [ -z "${routed[$dom]:-}" ]; } || return 1 + seen[$host]=1 + out=$(walk "$host") + # A probe that failed to run is no verdict; the host is probed again. + if [ "$(jq -r '.verdict // "error"' <<<"$out")" = error ]; then + echo "probe $host -> error, not recorded" + return 0 + fi + record "$dom" "$host" "$out" + if [ "$(jq -r '.verdict // ""' <<<"$out")" = destination ]; then + routed[$dom]=1 + publish + fi + # A censor verdict names an exit that got through, but zapret owns it. + echo "probe $host -> $(jq -r '(.verdict // "error") + (if .verdict == "destination" then " via " + .exit + elif .exit then " (" + .exit + " reaches it; left to zapret)" else "" end)' <<<"$out")" +} + +for row in "${asked[@]}"; do probe_row "$row" || true; done + +probed=0 +for row in "${requeue[@]}" "${backlog[@]}"; do + [ "$probed" -lt @probesPerRun@ ] || break + if probe_row "$row"; then probed=$(( probed + 1 )); fi +done +echo "probed ${#asked[@]} requested and $probed queued host(s); $(jq '(.backlog // {}) | length' "$state") still waiting" + +# sing-box reloads the rewritten rule-sets itself. +@render@ "$index" "$state" diff --git a/modules/proxy-suite/autoproxy-sample.template.sh b/modules/proxy-suite/autoproxy-sample.template.sh new file mode 100644 index 0000000..b26f550 --- /dev/null +++ b/modules/proxy-suite/autoproxy-sample.template.sh @@ -0,0 +1,21 @@ +set -euo pipefail +export PATH=@path@ +state_dir=${AUTOPROXY_STATE_DIR:-@stateDir@} +index=${PROBE_EXITS_FILE:-@runtimeDir@/proxy-suite-socks/probe-exits.json} +@clashApiBlock@ +if [ -z "$clash_api" ]; then + echo "sing-box has no Clash API (selection = \"first\"?); nothing to sample" + exit 0 +fi +install -d -m @stateDirMode@ "$state_dir" + +# Eleven snapshots a second apart: ten one-second deltas per connection. +lines=$( + for i in $(seq 0 10); do + [ "$i" -eq 0 ] || sleep 1 + curl -sS --noproxy '*' --max-time 1 -H @<(clash_auth_header) "http://$clash_api/connections" 2>/dev/null || + echo '{}' + done | jq -s -r --argjson min @minBytes@ \ + --argjson below @slowBelowBytes@ -f @slowSampleJq@ || true +) +[ -z "$lines" ] || printf '%s\n' "$lines" >> "$state_dir/samples" diff --git a/modules/proxy-suite/autoproxy.nix b/modules/proxy-suite/autoproxy.nix index 51e6959..ef7ec34 100644 --- a/modules/proxy-suite/autoproxy.nix +++ b/modules/proxy-suite/autoproxy.nix @@ -13,6 +13,7 @@ }: let + fillTemplate = import ./lib/fill-template.nix; apCfg = cfg.proxy.autoProxy; derived = import ./derived.nix { inherit lib cfg; }; inherit (derived.constants) rootInSharedDirConfig; @@ -59,415 +60,38 @@ let clash_auth_header() { printf 'Authorization: Bearer %s\n' "$clash_secret"; } ''; - sampler = pkgs.writeShellScript "proxy-suite-autoproxy" '' - set -euo pipefail - export PATH=${bin} - state_dir=''${AUTOPROXY_STATE_DIR:-${lib.escapeShellArg autoProxyStateDir}} - index=''${PROBE_EXITS_FILE:-${runtimeDir}/proxy-suite-socks/probe-exits.json} - ${clashApiBlock} - if [ -z "$clash_api" ]; then - echo "sing-box has no Clash API (selection = \"first\"?); nothing to sample" - exit 0 - fi - install -d -m ${stateDirMode} "$state_dir" - - # Eleven snapshots a second apart: ten one-second deltas per connection. - lines=$( - for i in $(seq 0 10); do - [ "$i" -eq 0 ] || sleep 1 - curl -sS --noproxy '*' --max-time 1 -H @<(clash_auth_header) "http://$clash_api/connections" 2>/dev/null || - echo '{}' - done | jq -s -r --argjson min ${toString (300 * 1024)} \ - --argjson below ${ - toString (apCfg.slowBelowKiBps * 1024) - } -f ${jqFile ./autoproxy-slow-sample.jq} || true - ) - [ -z "$lines" ] || printf '%s\n' "$lines" >> "$state_dir/samples" - ''; - - runner = pkgs.writeShellScript "proxy-suite-autoproxy" '' - set -euo pipefail - export PATH=${bin} - - # --requests-only: just the `proxy-ctl proxy auto learn|forget|clear` requests. - mode=''${1:-full} - - # Overridable to rehearse a run against a scratch copy; the units never set them. - state_dir=''${AUTOPROXY_STATE_DIR:-${lib.escapeShellArg autoProxyStateDir}} - export PROBE_EXITS_FILE=''${PROBE_EXITS_FILE:-${runtimeDir}/proxy-suite-socks/probe-exits.json} - index=$PROBE_EXITS_FILE - state="$state_dir/state.json" - requests="$state_dir/requests" - edits="$state_dir/edits" - now=$(date +%s) - ttl=$(( ${toString apCfg.ttlDays} * 86400 )) - - install -d -m ${stateDirMode} "$state_dir" - - # Timer runs and learn requests take turns on the state. - exec 9> "$state_dir/lock" - flock 9 - - # Leftovers of a run that died partway; taken requests go back in line. - rm -f "$state_dir/verdicts.json" "$state_dir/proxied-domains.txt" "$state".?????? "$state_dir/samples.taking" - for queue in "$requests" "$edits"; do - if [ -e "$queue.taking" ]; then - cat "$queue.taking" >> "$queue" - rm -f "$queue.taking" - # Made here by root: the group appends to it too. - chmod 0660 "$queue" - fi - done - - if [ -e "$state" ] && ! jq -e 'type == "object"' "$state" > /dev/null 2>&1; then - echo "$state is unreadable; set aside as $state.broken, starting fresh" >&2 - mv -f "$state" "$state.broken" - fi - [ -s "$state" ] || echo '{"domains":{},"hosts":{},"exits":{},"backlog":{}}' > "$state" - - # Written aside and renamed, so a killed run never truncates the state. - update() { - local tmp - tmp=$(mktemp "$state.XXXXXX") - if ! jq "$@" "$state" > "$tmp"; then - rm -f "$tmp" - echo "could not update $state; it is left as it was" >&2 - return 1 - fi - # mktemp makes it 0600; the state dir is 0751, so group-readable is enough. - chmod 0640 "$tmp" - mv -f "$tmp" "$state" + sampler = pkgs.writeShellScript "proxy-suite-autoproxy" ( + fillTemplate ./autoproxy-sample.template.sh { + path = bin; + stateDir = lib.escapeShellArg autoProxyStateDir; + inherit runtimeDir clashApiBlock stateDirMode; + minBytes = toString (300 * 1024); + slowBelowBytes = toString (apCfg.slowBelowKiBps * 1024); + slowSampleJq = jqFile ./autoproxy-slow-sample.jq; } + ); - # --- 0. forget what `proxy-ctl proxy auto forget|relearn|clear` asked to --- - # Before anything else, and even with the proxy stopped: its start renders the - # rule-sets from the state again. - edited="" - if [ -s "$edits" ]; then - mv -f "$edits" "$edits.taking" - while read -r op dom; do - case "$op" in - forget) - [[ "$dom" =~ ^[a-zA-Z0-9._-]+\.[a-zA-Z]{2,}$ ]] || continue - update --arg op forget --arg d "$dom" -f ${jqFile ./autoproxy-edit.jq} - echo "forgot $dom" - ;; - clear) - update --arg op clear --arg d "" -f ${jqFile ./autoproxy-edit.jq} - echo "forgot everything learned" - ;; - *) continue ;; - esac - edited=1 - done < "$edits.taking" - rm -f "$edits.taking" - fi - - if [ ! -r "$index" ]; then - echo "no probe listeners - is proxy-suite-socks running with autoProxy on?" - exit 0 - fi - - # Routes through an outbound disabled since (`proxy-ctl proxy outbounds disable`) - # are forgotten like the above, so their domains get probed again without it. - inventory="$(dirname "$index")/outbounds.json" - if [ -r "$inventory" ]; then - while IFS=$'\t' read -r dom exit; do - echo "forgot $dom: its exit $exit is disabled" - update --arg op forget --arg d "$dom" -f ${jqFile ./autoproxy-edit.jq} - edited=1 - done < <(jq -r --slurpfile inv "$inventory" '($inv[0].disabled // []) as $off - | (.domains // {}) | to_entries[] | select(.value.exit as $e | $off | index([$e])) - | "\(.key)\t\(.value.exit)"' "$state") - fi - [ -z "$edited" ] || ${render} "$index" "$state" - - # $1 JSON array of exit tags, $2 registrable domain, $3 wall:|refused|slow. - strike() { - update --argjson tags "$1" --arg d "$2" --arg why "$3" --argjson now "$now" --argjson ttl "$ttl" \ - -f ${jqFile ./autoproxy-strike.jq} + runner = pkgs.writeShellScript "proxy-suite-autoproxy" ( + fillTemplate ./autoproxy-run.template.sh { + path = bin; + stateDir = lib.escapeShellArg autoProxyStateDir; + inherit runtimeDir; + ttlDays = toString apCfg.ttlDays; + inherit stateDirMode; + editJq = jqFile ./autoproxy-edit.jq; + inherit render; + strikeJq = jqFile ./autoproxy-strike.jq; + roundsJq = jqFile ./autoproxy-rounds.jq; + interval = apCfg.interval; + inherit journalctl; + excludeHosts = lib.optionalString (excludePattern != "") "grep -vE '(^|\\.)(${excludePattern})$' |"; + excludeSampleHosts = lib.optionalString ( + excludePattern != "" + ) "grep -vE '(^|\\.)(${excludePattern})'$'\\t' |"; + slowJudgeJq = jqFile ./autoproxy-slow-judge.jq; + probesPerRun = toString apCfg.probesPerRun; } - - # $1 registrable domain, $2 host probed, $3 probe JSON. Routes apply to the - # whole domain (geo-blocks are drawn around sites); other verdicts only to - # the host probed. - record() { - update --arg d "$1" --arg h "$2" --argjson r "$3" --argjson now "$now" ' - (if $r.verdict == "destination" then - .domains[$d] = {verdict: "destination", exit: $r.exit, host: $h, - path: ($r.path // "/"), at: $now} - else . end) - | .hosts[$h] = { - domain: $d, - verdict: ($r.verdict // "error"), - exit: (if $r.verdict == "destination" then $r.exit else null end), - at: $now - } - | del(.backlog[$h])' - # Exits refused on the path another egress reached: by a block page - # (wall:, the site turning the address away) or by the origin. - local t why - while IFS=$'\t' read -r t why; do - strike "$(jq -cn --arg t "$t" '[$t]')" "$1" "$why" - done < <(jq -r '(.path // "") as $p | .exit as $x - | ([(.exits // [])[] | select(.tag == $x and .path == $p) | .judgement][0]) as $won - | if $x == null then empty else - # An origin refusal only counts against an exit when the winner got content. - [(.exits // [])[] | select(.path == $p and .tag != "direct" and .tag != $x - and (.judgement == "wall" or (.judgement == "blocked" and $won == "ok"))) - | {tag, why: (if .judgement == "wall" then "wall:" + .block else "refused" end)}] - | unique_by(.tag)[] | "\(.tag)\t\(.why)" - end' <<<"$3") - } - - # Prefixes each host line with "registrable-domain". - # ponytail: last two labels, or three under a short list of two-label - # suffixes. Switch to the Public Suffix List if a domain gets merged wrongly. - to_reg() { - awk -F'\t' ' - BEGIN { - n = split("co.uk org.uk ac.uk gov.uk com.au net.au org.au co.jp ne.jp or.jp com.br com.tr co.kr com.cn com.hk co.in co.za com.ua com.mx co.nz", s, " ") - for (i = 1; i <= n; i++) two[s[i]] = 1 - } - { - n = split($1, l, ".") - if (n < 2) next - k = (n >= 3 && (l[n - 1] "." l[n]) in two) ? l[n - 2] "." l[n - 1] "." l[n] : l[n - 1] "." l[n] - print k "\t" $0 - }' - } - - # The pinned direct listener, since TUN/TProxy capture --noproxy too. - direct_url=$(jq -r '.[0] | "http://127.0.0.1:\(.port)"' "$index") - - # --- 1. verdicts are about this host's address; drop them if it changed --- - egress=$(curl -sS -f --proxy "$direct_url" --max-time 10 https://api.ipify.org 2>/dev/null || true) - # An error page or a captive portal must not pass for a new address: anything - # that is not one discards every verdict this host learned. - [[ "$egress" =~ ^[0-9a-fA-F.:]+$ ]] || egress="" - if [ -n "$egress" ] && [ "$(jq -r '.egress // ""' "$state")" != "$egress" ]; then - echo "egress is now $egress; discarding everything learned for the old address" - update --arg e "$egress" \ - '{egress: $e, domains: {}, hosts: {}, exits: {}, backlog: (.backlog // {}), lastRun: (.lastRun // 0)}' - fi - - # --- 2. which network (AS) each exit leaves from, once per TTL --- - while IFS=$'\t' read -r tag port; do - at=$(jq -r --arg t "$tag" '.exits[$t].at // 0' "$state") - [ $(( now - at )) -ge "$ttl" ] || continue - info=$(curl -sS --proxy "http://127.0.0.1:$port" --max-time 10 https://ipinfo.io/json 2>/dev/null || true) - ip=$(jq -r '.ip // empty' <<<"$info" 2>/dev/null || true) - asn=$(jq -r '(.org // "") | split(" ")[0]' <<<"$info" 2>/dev/null || true) - [ -n "$ip" ] || continue - update --arg t "$tag" --arg ip "$ip" --arg asn "$asn" --argjson now "$now" \ - '.exits[$t] += {ip: $ip, asn: $asn, at: $now}' - done < <(jq -r '.[] | "\(.tag)\t\(.port)"' "$index") - - # --- 2b. strikes older than a TTL stop counting against an exit --- - strike '[]' "" "" - - # See autoproxy-rounds.jq: one exit per AS, then the rest, bad exits last. - rounds=$(jq -c --slurpfile s "$state" -f ${jqFile ./autoproxy-rounds.jq} "$index") - round1=$(jq -r .r1 <<<"$rounds") - round2=$(jq -r .r2 <<<"$rounds") - - # Every probe goes through here: a zero exit with nothing on stdout is no verdict - # either, and empty is the one answer that slips through the checks downstream -- - # jq reads it as no input at all, so `.verdict // "error"' yields "" rather than - # "error", and `--argjson r ""' then kills the run. Stdin is the caller's loop. - probe_json() { - local out - out=$(proxy-ctl proxy auto probe --json "$@" < /dev/null 2>/dev/null || true) - [ -n "$out" ] || out='{}' - printf '%s' "$out" - } - - walk() { - local out first verdict - out=$(probe_json --exits "$round1" "$1") - verdict=$(jq -r '.verdict // "error"' <<<"$out") - if { [ "$verdict" = both-fail ] || [ "$verdict" = unreachable ]; } && [ -n "$round2" ]; then - first=$out - out=$(probe_json --exits "$round2" "$1") - # Round 1's refusals count against its exits too (see record). - out=$(jq -c --argjson f "$first" '.exits = ($f.exits // []) + (.exits // [])' <<<"$out") - fi - printf '%s' "$out" - } - - # Route changes take effect immediately, not at the end of the run. - publish() { ${render} "$index" "$state"; } - - requeue=() - if [ "$mode" = full ]; then - # --- 3. re-check remembered exits, once per TTL --- - # Probed routes only; slowness routes are judged by the sampler (4b). - while IFS=$'\t' read -r dom host exit; do - out=$(probe_json --exits "$exit" "$host") - verdict=$(jq -r '.verdict // "error"' <<<"$out") - if [ "$verdict" = destination ] && [ "$(jq -r '.exit // ""' <<<"$out")" = "$exit" ]; then - update --arg d "$dom" --argjson now "$now" '.domains[$d].at = $now' - elif [ "$verdict" = ok ]; then - echo "recheck $dom: reachable directly now, dropping $exit" - update --arg d "$dom" 'del(.domains[$d])' - record "$dom" "$host" "$out" - publish - else - echo "recheck $dom: $exit no longer works ($verdict), walking again" - update --arg d "$dom" 'del(.domains[$d])' - publish - requeue+=("$dom"$'\t'"$host") - fi - done < <(jq -r --argjson now "$now" --argjson every "$ttl" ' - .domains | to_entries[] - | select(.value.verdict == "destination" and ($now - .value.at) >= $every) - | "\(.key)\t\(.value.host)\t\(.value.exit)"' "$state") - - # --- 4. what clients dialled since the last run, counted per host --- - # Hit counts accumulate in a backlog that survives between runs. - last=$(jq -r '.lastRun // 0' "$state") - if [ "$last" -gt 0 ]; then since="@$last"; else since="-${apCfg.interval}"; fi - dialled=$( - ${journalctl} -u proxy-suite-inbounds --since "$since" --no-pager -o cat 2>/dev/null | - sed -n 's/.* accepted tcp:\([a-zA-Z0-9._-]*\):[0-9]*.*/\1/p' | - grep -E '^[a-zA-Z0-9._-]+\.[a-zA-Z]{2,}$' | - ${lib.optionalString (excludePattern != "") "grep -vE '(^|\\.)(${excludePattern})$' |"} - to_reg || true - ) - counts=$( - printf '%s\n' "$dialled" | - awk -F'\t' 'NF == 2 { n[$2]++; d[$2] = $1 } END { for (h in n) print h "\t" d[h] "\t" n[h] }' | - jq -R -s -c 'split("\n") | map(select(length > 0) | split("\t") - | {key: .[0], value: {domain: .[1], hits: (.[2] | tonumber)}}) | from_entries' - ) - # Skipped: hosts of an already routed domain, hosts judged within the TTL. - # Dropped: entries older than the TTL, and those a route now covers; host - # verdicts past the TTL, which would only be probed again anyway. - update --argjson c "$counts" --argjson now "$now" --argjson ttl "$ttl" ' - . as $s - | .lastRun = $now - | .hosts |= with_entries(select(.value.at + $ttl > $now)) - | .backlog = (reduce ($c | to_entries[]) as $e (($s.backlog // {}); - if ($s.domains[$e.value.domain].exit != null) - or ((($s.hosts[$e.key].at // 0) + $ttl) > $now) - then . - else .[$e.key] = { - domain: $e.value.domain, - hits: ((.[$e.key].hits // 0) + $e.value.hits), - first: (.[$e.key].first // $now) - } end)) - | .backlog |= with_entries(select(.value.first + $ttl > $now - and $s.domains[.value.domain].exit == null))' - - # --- 4b. what the sampler saw crawl (see autoproxy-slow-judge.jq) --- - if [ -s "$state_dir/samples" ]; then - mv -f "$state_dir/samples" "$state_dir/samples.taking" - # Not `|| echo '[]'`: a grep that matches nothing fails the pipeline after - # jq already printed [], and "[]\n[]" is no JSON for --argjson. - obs=$( - grep -E '^[a-zA-Z0-9._-]+\.[a-zA-Z]{2,}'$'\t' "$state_dir/samples.taking" | - ${lib.optionalString (excludePattern != "") "grep -vE '(^|\\.)(${excludePattern})'$'\\t' |"} - to_reg | - jq -R -s -c 'split("\n") | map(select(length > 0) | split("\t") - | {d: .[0], h: .[1], exit: .[2], slow: (.[3] == "slow"), peak: (.[4] | tonumber)})' || - true - ) - [ -n "$obs" ] || obs='[]' - rm -f "$state_dir/samples.taking" - before=$(jq -c '.domains' "$state") - update --argjson o "$obs" --argjson now "$now" --argjson ttl "$ttl" --argjson hits 3 \ - -f ${jqFile ./autoproxy-slow-judge.jq} - - # Each crawling destination gets the next exit, in probe order, that - # answers it as well as direct does (`probe --via`). None left: it - # stays direct for a TTL. - while IFS=$'\t' read -r dom host tried; do - was=''${tried##*,} - # It crawled twice on the exit it was routed through. - [ -z "$was" ] || strike "$(jq -cn --arg t "$was" '[$t]')" "$dom" slow - via="" - while IFS= read -r tag; do - [[ ",$tried," != *",$tag,"* ]] || continue - tried="''${tried:+$tried,}$tag" - out=$(probe_json --via "$tag" "$host") - verdict=$(jq -r '.verdict // ""' <<<"$out" 2>/dev/null || true) - if [ "$verdict" = ok ]; then - via=$tag - break - fi - # Refused what direct gets, by a block page or by the origin. - if [ "$verdict" = blocked ]; then - why=$(jq -r --arg t "$tag" '[.exits[] | select(.tag == $t)] as $r - | [$r[] | select(.judgement == "wall") | "wall:" + .block][0] - // (if any($r[]; .judgement == "blocked") then "refused" else "" end)' <<<"$out" 2>/dev/null || true) - [ -z "$why" ] || strike "$(jq -cn --arg t "$tag" '[$t]')" "$dom" "$why" - fi - done < <(jq -r '.ordered[]' <<<"$rounds") - if [ -n "$via" ]; then - echo "slow $dom: crawls ''${was:+via $was}''${was:-directly}, routed via $via" - update --arg d "$dom" --arg h "$host" --arg e "$via" --arg tried "$tried" --argjson now "$now" ' - .domains[$d] = {verdict: "slow", exit: $e, host: $h, at: $now, tried: ($tried | split(","))} - | del(.slowWant[$d])' - else - echo "slow $dom: crawls ''${was:+via $was}''${was:-directly}, and no other exit reaches it; left direct" - update --arg d "$dom" --argjson until $(( now + ttl )) '.slowSkip[$d] = $until | del(.slowWant[$d])' - fi - done < <(jq -r '(.slowWant // {}) | to_entries[] - | "\(.key)\t\(.value.host)\t\(.value.tried | join(","))"' "$state") - - [ "$(jq -c '.domains' "$state")" = "$before" ] || publish - fi - fi - - # --- 5. probe: requests (uncapped), then broken routes, then the backlog --- - asked=() - if [ -s "$requests" ]; then - mv -f "$requests" "$requests.taking" - mapfile -t asked < <(grep -E '^[a-zA-Z0-9._-]+\.[a-zA-Z]{2,}$' "$requests.taking" | to_reg || true) - rm -f "$requests.taking" - fi - backlog=() - if [ "$mode" = full ]; then - mapfile -t backlog < <(jq -r --argjson now "$now" --argjson ttl "$ttl" ' - . as $s | (.backlog // {}) | to_entries - | map(select(($s.domains[.value.domain].exit == null) - and ((($s.hosts[.key].at // 0) + $ttl) <= $now))) - | sort_by(-.value.hits) | .[] | "\(.value.domain)\t\(.key)"' "$state") - fi - - declare -A seen routed - probe_row() { - local dom=''${1%%$'\t'*} host=''${1#*$'\t'} out - { [ -z "''${seen[$host]:-}" ] && [ -z "''${routed[$dom]:-}" ]; } || return 1 - seen[$host]=1 - out=$(walk "$host") - # A probe that failed to run is no verdict; the host is probed again. - if [ "$(jq -r '.verdict // "error"' <<<"$out")" = error ]; then - echo "probe $host -> error, not recorded" - return 0 - fi - record "$dom" "$host" "$out" - if [ "$(jq -r '.verdict // ""' <<<"$out")" = destination ]; then - routed[$dom]=1 - publish - fi - # A censor verdict names an exit that got through, but zapret owns it. - echo "probe $host -> $(jq -r '(.verdict // "error") + (if .verdict == "destination" then " via " + .exit - elif .exit then " (" + .exit + " reaches it; left to zapret)" else "" end)' <<<"$out")" - } - - for row in "''${asked[@]}"; do probe_row "$row" || true; done - - probed=0 - for row in "''${requeue[@]}" "''${backlog[@]}"; do - [ "$probed" -lt ${toString apCfg.probesPerRun} ] || break - if probe_row "$row"; then probed=$(( probed + 1 )); fi - done - echo "probed ''${#asked[@]} requested and $probed queued host(s); $(jq '(.backlog // {}) | length' "$state") still waiting" - - # sing-box reloads the rewritten rule-sets itself. - ${render} "$index" "$state" - ''; + ); # Group: `proxy-ctl proxy auto list|queue` reads state.json, `learn` queues requests. # Set on every unit that declares the directory - systemd re-applies the ownership diff --git a/modules/proxy-suite/lib/fill-template.nix b/modules/proxy-suite/lib/fill-template.nix new file mode 100644 index 0000000..872a344 --- /dev/null +++ b/modules/proxy-suite/lib/fill-template.nix @@ -0,0 +1,21 @@ +# A script kept in its own file beside the Nix that runs it, with its @name@ placeholders +# filled from `vars`: replaceVars, but at eval time, so the text still goes to +# writeShellScript, runCommand and the like. Each value is spliced in as "${value}" would +# be, so a path lands in the store. Every name given must be a placeholder in the file and +# every placeholder must be given, so neither side can drift from the other unnoticed. +file: vars: +let + text = builtins.readFile file; + names = builtins.attrNames vars; + placeholders = builtins.concatMap (part: if builtins.isList part then part else [ ]) ( + builtins.split "@([A-Za-z_][A-Za-z0-9_]*)@" text + ); + unused = builtins.filter (name: !builtins.elem name placeholders) names; + unfilled = builtins.filter (name: !(vars ? ${name})) placeholders; +in +if unused != [ ] then + throw "${toString file}: no @${builtins.head unused}@ placeholder to fill" +else if unfilled != [ ] then + throw "${toString file}: @${builtins.head unfilled}@ is not given a value" +else + builtins.replaceStrings (map (name: "@${name}@") names) (map (name: "${vars.${name}}") names) text diff --git a/modules/proxy-suite/rulesets-fetch.template.sh b/modules/proxy-suite/rulesets-fetch.template.sh new file mode 100644 index 0000000..4078982 --- /dev/null +++ b/modules/proxy-suite/rulesets-fetch.template.sh @@ -0,0 +1,50 @@ +set -uo pipefail +proxy=(--proxy socks5h://@proxyHost@:@proxyPort@) +# The listener's login as curl config on a pipe (-K): argv is readable by every local user. +proxy_login() { + [ "$1" = proxy ] || return 0 + @proxyLogin@ +} +failed=0 + +# A download replaces the file only once sing-box has read it back, so a bad one never +# reaches the backend; a failed one keeps what was there. Its domain rules go to the copy +# DNS rules read. +fetch() { + local name=$1 url=$2 path=$3 dns=$4 format=$5 detour=$6 tmp dnsTmp + local args=(--fail --silent --show-error --location --max-time 120 --max-filesize 64M) + [ "$detour" = proxy ] && args+=("${proxy[@]}") + tmp=$(@coreutils@/bin/mktemp "$path.XXXXXX") || { failed=1; return; } + dnsTmp=$(@coreutils@/bin/mktemp "$dns.XXXXXX") || { rm -f "$tmp"; failed=1; return; } + if @curl@ "${args[@]}" -K <(proxy_login "$detour") --output "$tmp" "$url" && valid "$tmp" "$format" && + domains "$tmp" "$format" > "$dnsTmp" && valid "$dnsTmp" source; then + chmod 0644 "$tmp" "$dnsTmp" + mv -f "$dnsTmp" "$dns" + mv -f "$tmp" "$path" + echo "rule set $name: updated" + else + rm -f "$tmp" "$dnsTmp" + echo "rule set $name: not updated from $url; keeping the one it has" >&2 + failed=1 + fi +} +valid() { + if [ "$2" = binary ]; then + @singBox@ rule-set decompile --output /dev/null "$1" 2>/dev/null + else + @singBox@ rule-set compile --output /dev/null "$1" 2>/dev/null + fi +} +domains() { + if [ "$2" = binary ]; then + @singBox@ rule-set decompile --output /dev/stdout "$1" + else + cat "$1" + fi | @jq@/bin/jq '.rules = [(.rules // [])[] + | select((.type // "default") == "default" + and (has("domain") or has("domain_suffix") or has("domain_keyword") or has("domain_regex"))) + | del(.ip_cidr, .ip_is_private)]' +} + +@fetchRuleSets@ +exit "$failed" diff --git a/modules/proxy-suite/rulesets.nix b/modules/proxy-suite/rulesets.nix index 79e95ef..fc4b250 100644 --- a/modules/proxy-suite/rulesets.nix +++ b/modules/proxy-suite/rulesets.nix @@ -8,6 +8,7 @@ }: let + fillTemplate = import ./lib/fill-template.nix; inherit (derived) ruleSets localProxy; inherit (derived.constants) ruleSetsDir unprivilegedServiceConfig serviceUser; inherit (cfg.host) privileged; @@ -35,74 +36,33 @@ let ${singBox} rule-set compile --output "$out" ${emptySource} ''; - fetchScript = pkgs.writeShellScript "proxy-suite-rulesets" '' - set -uo pipefail - proxy=(--proxy socks5h://${localProxy.hostPart}:${toString cfg.proxy.listener.port}) - # The listener's login as curl config on a pipe (-K): argv is readable by every local user. - proxy_login() { - [ "$1" = proxy ] || return 0 - ${lib.optionalString withProxyAuth '' + fetchScript = pkgs.writeShellScript "proxy-suite-rulesets" ( + fillTemplate ./rulesets-fetch.template.sh { + proxyHost = localProxy.hostPart; + proxyPort = toString cfg.proxy.listener.port; + proxyLogin = lib.optionalString withProxyAuth '' local login login=${lib.escapeShellArg auth.username}:"$(< "$CREDENTIALS_DIRECTORY/proxy-password")" login=''${login//\\/\\\\} printf 'proxy-user = "%s"\n' "''${login//\"/\\\"}" - ''} + ''; + coreutils = pkgs.coreutils; + inherit curl singBox; + jq = pkgs.jq; + fetchRuleSets = lib.concatMapStrings (rs: '' + fetch ${ + lib.escapeShellArgs [ + rs.name + rs.url + rs.path + rs.dnsPath + rs.format + rs.detour + ] + } + '') ruleSets; } - failed=0 - - # A download replaces the file only once sing-box has read it back, so a bad one never - # reaches the backend; a failed one keeps what was there. Its domain rules go to the copy - # DNS rules read. - fetch() { - local name=$1 url=$2 path=$3 dns=$4 format=$5 detour=$6 tmp dnsTmp - local args=(--fail --silent --show-error --location --max-time 120 --max-filesize 64M) - [ "$detour" = proxy ] && args+=("''${proxy[@]}") - tmp=$(${pkgs.coreutils}/bin/mktemp "$path.XXXXXX") || { failed=1; return; } - dnsTmp=$(${pkgs.coreutils}/bin/mktemp "$dns.XXXXXX") || { rm -f "$tmp"; failed=1; return; } - if ${curl} "''${args[@]}" -K <(proxy_login "$detour") --output "$tmp" "$url" && valid "$tmp" "$format" && - domains "$tmp" "$format" > "$dnsTmp" && valid "$dnsTmp" source; then - chmod 0644 "$tmp" "$dnsTmp" - mv -f "$dnsTmp" "$dns" - mv -f "$tmp" "$path" - echo "rule set $name: updated" - else - rm -f "$tmp" "$dnsTmp" - echo "rule set $name: not updated from $url; keeping the one it has" >&2 - failed=1 - fi - } - valid() { - if [ "$2" = binary ]; then - ${singBox} rule-set decompile --output /dev/null "$1" 2>/dev/null - else - ${singBox} rule-set compile --output /dev/null "$1" 2>/dev/null - fi - } - domains() { - if [ "$2" = binary ]; then - ${singBox} rule-set decompile --output /dev/stdout "$1" - else - cat "$1" - fi | ${pkgs.jq}/bin/jq '.rules = [(.rules // [])[] - | select((.type // "default") == "default" - and (has("domain") or has("domain_suffix") or has("domain_keyword") or has("domain_regex"))) - | del(.ip_cidr, .ip_is_private)]' - } - - ${lib.concatMapStrings (rs: '' - fetch ${ - lib.escapeShellArgs [ - rs.name - rs.url - rs.path - rs.dnsPath - rs.format - rs.detour - ] - } - '') ruleSets} - exit "$failed" - ''; + ); in { services.proxy-suite.internal = { diff --git a/modules/proxy-suite/service/polkit-rules.template.js b/modules/proxy-suite/service/polkit-rules.template.js new file mode 100644 index 0000000..86def4e --- /dev/null +++ b/modules/proxy-suite/service/polkit-rules.template.js @@ -0,0 +1,47 @@ +var verb = action.lookup("verb"); +if (typeof unit !== "string" || @verbs@.indexOf(verb) === -1) { + return null; +} +var known = @units@.indexOf(unit) !== -1; +var templates = @templates@; +for (var i = 0; !known && i < templates.length; i++) { + var template = templates[i]; + if (unit.indexOf(template) !== 0) { + continue; + } + var instance = unit.slice(template.length).replace(/\.service$/, ""); + if (!/^[A-Za-z0-9:_.\\-]+$/.test(instance) || unit !== template + instance + ".service") { + continue; + } + // Per-app marking follows one user's apps: only that user's own instance. + if (/-user@$/.test(template)) { + try { + var uid = polkit.spawn(["@coreutils@/bin/id", "-u", "--", subject.user]).trim(); + } catch (error) { + return null; + } + if (instance !== uid) { + return null; + } + } + known = true; +} +if (!known) { + return null; +} + +var scopeByUnitPrefix = @scopeByUnitPrefix@; +var scope = "services"; +for (var prefix in scopeByUnitPrefix) { + if (unit.indexOf(prefix) === 0) { + scope = scopeByUnitPrefix[prefix]; + break; + } +} +// Any of the subject's groups that holds the scope. +var groupScopes = @groupScopes@; +for (var group in groupScopes) { + if (groupScopes[group].indexOf(scope) !== -1 && subject.isInGroup(group)) { + return polkit.Result.YES; + } +} diff --git a/modules/proxy-suite/service/polkit.nix b/modules/proxy-suite/service/polkit.nix index addf6e2..1791451 100644 --- a/modules/proxy-suite/service/polkit.nix +++ b/modules/proxy-suite/service/polkit.nix @@ -15,6 +15,7 @@ }: let + fillTemplate = import ../lib/fill-template.nix; # Units a narrower scope starts; every other proxy-suite unit is "services". scopeByUnitPrefix = { "proxy-suite-per-app-" = "perApp"; @@ -48,55 +49,14 @@ let ]; in { - userControlPolkitRules = '' - var verb = action.lookup("verb"); - if (typeof unit !== "string" || ${builtins.toJSON verbs}.indexOf(verb) === -1) { - return null; - } - var known = ${builtins.toJSON units}.indexOf(unit) !== -1; - var templates = ${builtins.toJSON templates}; - for (var i = 0; !known && i < templates.length; i++) { - var template = templates[i]; - if (unit.indexOf(template) !== 0) { - continue; - } - var instance = unit.slice(template.length).replace(/\.service$/, ""); - if (!/^[A-Za-z0-9:_.\\-]+$/.test(instance) || unit !== template + instance + ".service") { - continue; - } - // Per-app marking follows one user's apps: only that user's own instance. - if (/-user@$/.test(template)) { - try { - var uid = polkit.spawn(["${pkgs.coreutils}/bin/id", "-u", "--", subject.user]).trim(); - } catch (error) { - return null; - } - if (instance !== uid) { - return null; - } - } - known = true; - } - if (!known) { - return null; - } - - var scopeByUnitPrefix = ${builtins.toJSON scopeByUnitPrefix}; - var scope = "services"; - for (var prefix in scopeByUnitPrefix) { - if (unit.indexOf(prefix) === 0) { - scope = scopeByUnitPrefix[prefix]; - break; - } - } - // Any of the subject's groups that holds the scope. - var groupScopes = ${builtins.toJSON userControlGroupScopes}; - for (var group in groupScopes) { - if (groupScopes[group].indexOf(scope) !== -1 && subject.isInGroup(group)) { - return polkit.Result.YES; - } - } - ''; + userControlPolkitRules = fillTemplate ./polkit-rules.template.js { + verbs = builtins.toJSON verbs; + units = builtins.toJSON units; + templates = builtins.toJSON templates; + coreutils = pkgs.coreutils; + scopeByUnitPrefix = builtins.toJSON scopeByUnitPrefix; + groupScopes = builtins.toJSON userControlGroupScopes; + }; # Whether the subject is in any userControl group at all: the rule's first test. userControlPolkitMember = lib.concatMapStringsSep " || " ( group: "subject.isInGroup(${builtins.toJSON group})" diff --git a/modules/proxy-suite/service/script-blocks/backend-filter-private-guard.template.jq b/modules/proxy-suite/service/script-blocks/backend-filter-private-guard.template.jq new file mode 100644 index 0000000..524c42b --- /dev/null +++ b/modules/proxy-suite/service/script-blocks/backend-filter-private-guard.template.jq @@ -0,0 +1,15 @@ +# inbounds.routing.blockPrivate, enforced here because the listener passes names unresolved. +# Just before the first direct rule (or last, for a direct final), so names that the +# proxy rules above take stay unresolved and none reaches a direct dial unchecked. Local +# mixed-in clients lose names that resolve private. Rules for other inbounds do not count: +# autoProxy's direct probe pin would put the guard first, resolving every name, .onion too. +| [{inbound: ["mixed-in"], action: "resolve"@resolveStrategy@}, + {inbound: ["mixed-in"], ip_is_private: true, action: "reject"}] as $guard +| (.route.rules + | map((.outbound? // "") == "direct" and ((.inbound? // ["mixed-in"]) | index(["mixed-in"])) != null) + | index(true)) as $first_direct +| if $first_direct != null then + .route.rules = .route.rules[:$first_direct] + $guard + .route.rules[$first_direct:] + elif (.route.final // "direct") == "direct" then + .route.rules += $guard + else . end diff --git a/modules/proxy-suite/service/script-blocks/backend-filter-sing-box.template.jq b/modules/proxy-suite/service/script-blocks/backend-filter-sing-box.template.jq new file mode 100644 index 0000000..9a9b61a --- /dev/null +++ b/modules/proxy-suite/service/script-blocks/backend-filter-sing-box.template.jq @@ -0,0 +1,29 @@ +def sing_box_preserved_rules: + [.route.rules[] + | select(((.action? // "") == "hijack-dns") + and (((.inbound? // []) | index("xray-dns-in")) != null))]; +.outbounds = ($obs[0] + .outbounds) + | if $auth_enabled then + (.inbounds[] | select(.type == "mixed" and .tag == "mixed-in") | .users) = [{username:$user,password:$password}] + else . end + | if $route_enabled then + .route.rules = (sing_box_preserved_rules + $route_rules) + | .route.final = $route_final + | .dns.final = $dns_final + | if $clear_dns_rules then + .dns.rules = .dns.rules[:@userDnsRuleCount@] + + [.dns.rules[@userDnsRuleCount@:][] | select(.server? == "fakeip" or .domain_suffix? == ["onion"])] + else . end + else . end + # autoProxy rules, after the route-mode replace so no mode drops them: pins first + # (they only match their own listener), learned rules last before final, so + # explicit rules win. All [] when off. + | .inbounds += $probe_inbounds + # The loopback probe and test listeners reach every exit: with listener.auth, the + # same login, or any local user would get past it through them. + | if $auth_enabled then + (.inbounds[] | select(.type == "mixed" and (.tag == "proxy-suite-test-in" or (.tag | startswith("probe-in-")))) | .users) + = [{username:$user,password:$password}] + else . end + | .route.rule_set = ((.route.rule_set // []) + $autoproxy_rule_sets) + | .route.rules = ($probe_pin_rules + .route.rules + $autoproxy_rules) diff --git a/modules/proxy-suite/service/script-blocks/backend-filter-xray.template.jq b/modules/proxy-suite/service/script-blocks/backend-filter-xray.template.jq new file mode 100644 index 0000000..e01ecb3 --- /dev/null +++ b/modules/proxy-suite/service/script-blocks/backend-filter-xray.template.jq @@ -0,0 +1,79 @@ +def xray_proxy_rule_target($single_tag): + if $single_tag != "" then + {outboundTag:$single_tag} + else + {balancerTag:"proxy"} + end; +def xray_rewrite_proxy_rule($single_tag): + # "proxy" is a balancer in urltest and no outbound at all in "first": either way, the one exit. + if $single_tag != "" and ((.balancerTag? // .outboundTag? // "") == "proxy") then + .outboundTag = $single_tag | del(.balancerTag) + else + . + end; +def xray_preserved_rules: + [.routing.rules[] + | select((.ruleTag? // "") | . == "dns-hijack" or . == "dns-upstream-direct" or . == "dns-upstream-remote")]; +def xray_final_rule($tag; $single_tag): + if $tag == "proxy" and "@selectionMode@" == "urltest" then + {type:"field",network:"tcp,udp",ruleTag:"final-default"} + xray_proxy_rule_target($single_tag) + else + {type:"field",network:"tcp,udp",ruleTag:"final-default",outboundTag:$tag} + end; +def xray_dns_server_order($dns_final): + if $dns_final == "" then + .dns.servers + else + ([.dns.servers[] | select((.tag? // "") == "fakedns")] + + [.dns.servers[] | select((.tag? // "") == $dns_final)] + + [.dns.servers[] | select((.tag? // "") != "fakedns" and (.tag? // "") != $dns_final)]) + end; +# Names of proxy servers, which XRay's DNS resolves once a dial has a domainStrategy. +def xray_server_names: + [.outbounds[].settings + | (.vnext[]?.address, .servers[]?.address, .address?) + | strings | select(test("^[0-9.]+$|:|^localhost$") | not)] + | unique; +# A copy of "local" answering only for them: routed direct by its tag, so looking up a +# proxy server never waits on that proxy. +def xray_pin_server_names: + xray_server_names as $names + | if $names == [] then . + else .dns.servers += [.dns.servers[] | select((.tag? // "") == "local") + | . + {domains: ($names | map("full:" + .)), skipFallback: true}] + end; +.outbounds = ($obs[0] + .outbounds) + | if $xray_loglevel == "" then . else .log.loglevel = $xray_loglevel end + | if $auth_enabled then + (.inbounds[] | select(.protocol == "socks" and .tag == "mixed-in") | .settings.auth) = "password" + | (.inbounds[] | select(.protocol == "socks" and .tag == "mixed-in") | .settings.accounts) = [{user:$user,pass:$password}] + else . end + | .dns.servers = xray_dns_server_order($dns_final) + | xray_pin_server_names + | if $xray_tun_dns_runtime then + # Without a domainStrategy a dial resolves through the system resolver, whose upstream + # queries the TUN answers with fake IPs and TProxy sends through the proxy being + # dialed. XRay's own DNS client skips fakedns. + .outbounds |= map( + if .protocol == "blackhole" or .protocol == "dns" or .protocol == "loopback" then . + else .streamSettings.sockopt.domainStrategy //= "UseIPv4v6" end) + else . end + | if $route_enabled then + .routing.rules = (xray_preserved_rules + $route_rules + [xray_final_rule($route_final; $xray_single_proxy_tag)]) + else . end + # The balancer's prefix would take in proxy.selectionExclude and disabled outbounds + # too: name the rest instead. Disabling is a runtime decision, so always. + # ponytail: selectors are prefixes still, so "de" also takes in an excluded "de-hop"; + # rename one of them if that matters. + | if $ARGS.named.xray_selectable == null then . else + ($ARGS.named.xray_selectable | map("proxy-suite-ob-" + .)) as $candidates + | if .routing.balancers then .routing.balancers |= map(.selector = $candidates) else . end + | if .observatory then .observatory.subjectSelector = $candidates else . end + end + | if $xray_single_proxy_tag == "" then + . + else + .routing.rules |= map(xray_rewrite_proxy_rule($xray_single_proxy_tag)) + | del(.routing.balancers) + | del(.observatory) + end diff --git a/modules/proxy-suite/service/script-blocks/backend-jq-filter.nix b/modules/proxy-suite/service/script-blocks/backend-jq-filter.nix index 101a3d1..ddc5137 100644 --- a/modules/proxy-suite/service/script-blocks/backend-jq-filter.nix +++ b/modules/proxy-suite/service/script-blocks/backend-jq-filter.nix @@ -7,138 +7,19 @@ userDnsRules ? [ ], }: +let + fillTemplate = import ../../lib/fill-template.nix; +in if pureXrayEnabled then - '' - def xray_proxy_rule_target($single_tag): - if $single_tag != "" then - {outboundTag:$single_tag} - else - {balancerTag:"proxy"} - end; - def xray_rewrite_proxy_rule($single_tag): - # "proxy" is a balancer in urltest and no outbound at all in "first": either way, the one exit. - if $single_tag != "" and ((.balancerTag? // .outboundTag? // "") == "proxy") then - .outboundTag = $single_tag | del(.balancerTag) - else - . - end; - def xray_preserved_rules: - [.routing.rules[] - | select((.ruleTag? // "") | . == "dns-hijack" or . == "dns-upstream-direct" or . == "dns-upstream-remote")]; - def xray_final_rule($tag; $single_tag): - if $tag == "proxy" and "${selectionMode}" == "urltest" then - {type:"field",network:"tcp,udp",ruleTag:"final-default"} + xray_proxy_rule_target($single_tag) - else - {type:"field",network:"tcp,udp",ruleTag:"final-default",outboundTag:$tag} - end; - def xray_dns_server_order($dns_final): - if $dns_final == "" then - .dns.servers - else - ([.dns.servers[] | select((.tag? // "") == "fakedns")] - + [.dns.servers[] | select((.tag? // "") == $dns_final)] - + [.dns.servers[] | select((.tag? // "") != "fakedns" and (.tag? // "") != $dns_final)]) - end; - # Names of proxy servers, which XRay's DNS resolves once a dial has a domainStrategy. - def xray_server_names: - [.outbounds[].settings - | (.vnext[]?.address, .servers[]?.address, .address?) - | strings | select(test("^[0-9.]+$|:|^localhost$") | not)] - | unique; - # A copy of "local" answering only for them: routed direct by its tag, so looking up a - # proxy server never waits on that proxy. - def xray_pin_server_names: - xray_server_names as $names - | if $names == [] then . - else .dns.servers += [.dns.servers[] | select((.tag? // "") == "local") - | . + {domains: ($names | map("full:" + .)), skipFallback: true}] - end; - .outbounds = ($obs[0] + .outbounds) - | if $xray_loglevel == "" then . else .log.loglevel = $xray_loglevel end - | if $auth_enabled then - (.inbounds[] | select(.protocol == "socks" and .tag == "mixed-in") | .settings.auth) = "password" - | (.inbounds[] | select(.protocol == "socks" and .tag == "mixed-in") | .settings.accounts) = [{user:$user,pass:$password}] - else . end - | .dns.servers = xray_dns_server_order($dns_final) - | xray_pin_server_names - | if $xray_tun_dns_runtime then - # Without a domainStrategy a dial resolves through the system resolver, whose upstream - # queries the TUN answers with fake IPs and TProxy sends through the proxy being - # dialed. XRay's own DNS client skips fakedns. - .outbounds |= map( - if .protocol == "blackhole" or .protocol == "dns" or .protocol == "loopback" then . - else .streamSettings.sockopt.domainStrategy //= "UseIPv4v6" end) - else . end - | if $route_enabled then - .routing.rules = (xray_preserved_rules + $route_rules + [xray_final_rule($route_final; $xray_single_proxy_tag)]) - else . end - # The balancer's prefix would take in proxy.selectionExclude and disabled outbounds - # too: name the rest instead. Disabling is a runtime decision, so always. - # ponytail: selectors are prefixes still, so "de" also takes in an excluded "de-hop"; - # rename one of them if that matters. - | if $ARGS.named.xray_selectable == null then . else - ($ARGS.named.xray_selectable | map("proxy-suite-ob-" + .)) as $candidates - | if .routing.balancers then .routing.balancers |= map(.selector = $candidates) else . end - | if .observatory then .observatory.subjectSelector = $candidates else . end - end - | if $xray_single_proxy_tag == "" then - . - else - .routing.rules |= map(xray_rewrite_proxy_rule($xray_single_proxy_tag)) - | del(.routing.balancers) - | del(.observatory) - end - '' + (fillTemplate ./backend-filter-xray.template.jq { inherit selectionMode; }) else - '' - def sing_box_preserved_rules: - [.route.rules[] - | select(((.action? // "") == "hijack-dns") - and (((.inbound? // []) | index("xray-dns-in")) != null))]; - .outbounds = ($obs[0] + .outbounds) - | if $auth_enabled then - (.inbounds[] | select(.type == "mixed" and .tag == "mixed-in") | .users) = [{username:$user,password:$password}] - else . end - | if $route_enabled then - .route.rules = (sing_box_preserved_rules + $route_rules) - | .route.final = $route_final - | .dns.final = $dns_final - | if $clear_dns_rules then - .dns.rules = .dns.rules[:${toString (builtins.length userDnsRules)}] - + [.dns.rules[${toString (builtins.length userDnsRules)}:][] | select(.server? == "fakeip" or .domain_suffix? == ["onion"])] - else . end - else . end - # autoProxy rules, after the route-mode replace so no mode drops them: pins first - # (they only match their own listener), learned rules last before final, so - # explicit rules win. All [] when off. - | .inbounds += $probe_inbounds - # The loopback probe and test listeners reach every exit: with listener.auth, the - # same login, or any local user would get past it through them. - | if $auth_enabled then - (.inbounds[] | select(.type == "mixed" and (.tag == "proxy-suite-test-in" or (.tag | startswith("probe-in-")))) | .users) - = [{username:$user,password:$password}] - else . end - | .route.rule_set = ((.route.rule_set // []) + $autoproxy_rule_sets) - | .route.rules = ($probe_pin_rules + .route.rules + $autoproxy_rules) - '' - + lib.optionalString proxyInboundsGuardPrivate '' - # inbounds.routing.blockPrivate, enforced here because the listener passes names unresolved. - # Just before the first direct rule (or last, for a direct final), so names that the - # proxy rules above take stay unresolved and none reaches a direct dial unchecked. Local - # mixed-in clients lose names that resolve private. Rules for other inbounds do not count: - # autoProxy's direct probe pin would put the guard first, resolving every name, .onion too. - | [{inbound: ["mixed-in"], action: "resolve"${ - lib.optionalString ( + (fillTemplate ./backend-filter-sing-box.template.jq { + userDnsRuleCount = toString (builtins.length userDnsRules); + }) + + lib.optionalString proxyInboundsGuardPrivate ( + fillTemplate ./backend-filter-private-guard.template.jq { + resolveStrategy = lib.optionalString ( proxyInboundsGuardStrategy != null - ) ", strategy: \"${proxyInboundsGuardStrategy}\"" - }}, - {inbound: ["mixed-in"], ip_is_private: true, action: "reject"}] as $guard - | (.route.rules - | map((.outbound? // "") == "direct" and ((.inbound? // ["mixed-in"]) | index(["mixed-in"])) != null) - | index(true)) as $first_direct - | if $first_direct != null then - .route.rules = .route.rules[:$first_direct] + $guard + .route.rules[$first_direct:] - elif (.route.final // "direct") == "direct" then - .route.rules += $guard - else . end - '' + ) ", strategy: \"${proxyInboundsGuardStrategy}\""; + } + ) diff --git a/modules/proxy-suite/service/script-blocks/hybrid-runtime-helpers.nix b/modules/proxy-suite/service/script-blocks/hybrid-runtime-helpers.nix index dcbcb78..fa259e3 100644 --- a/modules/proxy-suite/service/script-blocks/hybrid-runtime-helpers.nix +++ b/modules/proxy-suite/service/script-blocks/hybrid-runtime-helpers.nix @@ -1,6 +1,7 @@ { ctx }: let + fillTemplate = import ../../lib/fill-template.nix; inherit (ctx) lib jq @@ -11,107 +12,17 @@ in routingMark: xraySidecarPort: xrayDnsBridgePort: -lib.optionalString hybridEnabled '' - XRAY_OUTBOUNDS_JSON='[]' - XRAY_CLIENTS_JSON='[]' - XRAY_ROUTE_RULES_JSON='[]' - XRAY_SIDECAR_PORT=${toString xraySidecarPort} - XRAY_SIDECAR_DNS_PORT=${toString xrayDnsBridgePort} - # Client ids: this run's random prefix plus a counter, so every sidecar outbound has its - # own and no other local user can guess one. - XRAY_SIDECAR_SECRET=$(cat /proc/sys/kernel/random/uuid) - XRAY_SIDECAR_NEXT_ID=0 - - _proxy_suite_add_sing_box_ob() { - local ob="$1" - OUTBOUNDS_JSON=$(${jq} --slurpfile ob <(printf '%s' "$ob") '. + $ob' <<< "$OUTBOUNDS_JSON") +lib.optionalString hybridEnabled ( + fillTemplate ./hybrid-runtime-helpers.template.sh { + sidecarPort = toString xraySidecarPort; + dnsBridgePort = toString xrayDnsBridgePort; + inherit jq; + sidecarMark = if xraySidecarRoutingMark == null then "null" else toString xraySidecarRoutingMark; + setSidecarMark = lib.optionalString ( + xraySidecarRoutingMark != null + ) "| .streamSettings.sockopt.mark = $mark"; + hopRoutingMark = lib.optionalString ( + routingMark != null + ) " + {routing_mark: ${toString routingMark}}"; } - - # $1 a JSON array of XRay outbounds, each tagged. One jq pass for the lot: each gets a - # client on the sidecar's one loopback VLESS inbound, routed to it by its email, and - # stands in sing-box as a hop to it. VLESS rather than SOCKS: UDP rides the stream - # (XUDP) with the client id, where SOCKS UDP datagrams carry no user to route by. - _proxy_suite_add_xray_sidecar_obs() { - local batch - batch=$(${jq} -c \ - --argjson next "$XRAY_SIDECAR_NEXT_ID" \ - --rawfile secret <(printf '%s' "$XRAY_SIDECAR_SECRET") \ - --argjson port "$XRAY_SIDECAR_PORT" \ - --argjson mark ${ - if xraySidecarRoutingMark == null then "null" else toString xraySidecarRoutingMark - } ' - def hex12: [range(11; -1; -1) as $i | (. / pow(16; $i) | floor) % 16 | "0123456789abcdef"[.:. + 1]] | add; - to_entries | map( - ($secret[:24] + ($next + .key | hex12)) as $id - | .value.tag as $tag - | {outbound: (.value - ${lib.optionalString ( - xraySidecarRoutingMark != null - ) "| .streamSettings.sockopt.mark = $mark"} - | .streamSettings.sockopt.domainStrategy = (.streamSettings.sockopt.domainStrategy // "UseIP")), - client: {id: $id, email: $tag}, - rule: {type: "field", inboundTag: ["sidecar-in"], user: [$tag], outboundTag: $tag}, - hop: ({type: "vless", tag: $tag, server: "127.0.0.1", server_port: $port, uuid: $id, - packet_encoding: "xudp"}${ - lib.optionalString (routingMark != null) " + {routing_mark: ${toString routingMark}}" - })}) - | {outbounds: map(.outbound), clients: map(.client), rules: map(.rule), hops: map(.hop)} - ' <<< "$1") - XRAY_SIDECAR_NEXT_ID=$((XRAY_SIDECAR_NEXT_ID + $(${jq} '.outbounds | length' <<< "$batch"))) - # Through a file, not --argjson: a big subscription's batch outgrows the kernel's - # 128 KiB limit on one argument. - XRAY_OUTBOUNDS_JSON=$(${jq} -c --slurpfile b <(printf '%s' "$batch") '. + $b[0].outbounds' <<< "$XRAY_OUTBOUNDS_JSON") - XRAY_CLIENTS_JSON=$(${jq} -c --slurpfile b <(printf '%s' "$batch") '. + $b[0].clients' <<< "$XRAY_CLIENTS_JSON") - XRAY_ROUTE_RULES_JSON=$(${jq} -c --slurpfile b <(printf '%s' "$batch") '. + $b[0].rules' <<< "$XRAY_ROUTE_RULES_JSON") - OUTBOUNDS_JSON=$(${jq} -c --slurpfile b <(printf '%s' "$batch") '. + $b[0].hops' <<< "$OUTBOUNDS_JSON") - } - - # $1 one XRay outbound, $2 its tag. - _proxy_suite_add_xray_sidecar_ob() { - _proxy_suite_add_xray_sidecar_obs "$(${jq} -c --arg tag "$2" '[.tag = $tag]' <<< "$1")" - } - - _proxy_suite_write_xray_sidecar_config() { - if [ "$(${jq} 'length' <<< "$XRAY_OUTBOUNDS_JSON")" -eq 0 ]; then - return 0 - fi - ${jq} -n \ - --arg loglevel "$XRAY_LOGLEVEL" \ - --argjson dns_port "$XRAY_SIDECAR_DNS_PORT" \ - --argjson port "$XRAY_SIDECAR_PORT" \ - --slurpfile clients <(printf '%s' "$XRAY_CLIENTS_JSON") \ - --slurpfile outbounds <(printf '%s' "$XRAY_OUTBOUNDS_JSON") \ - --slurpfile route_rules <(printf '%s' "$XRAY_ROUTE_RULES_JSON") \ - ' - { - log: { - loglevel: (if $loglevel == "" then "warning" else $loglevel end), - access: "none" - }, - dns: { - servers: [ - { - address: "127.0.0.1", - port: $dns_port, - queryStrategy: "UseIP", - skipFallBack: true - } - ] - }, - inbounds: [ - { - tag: "sidecar-in", - listen: "127.0.0.1", - port: $port, - protocol: "vless", - settings: {clients: $clients[0], decryption: "none"} - } - ], - outbounds: ($outbounds[0] + [{protocol:"freedom",tag:"direct"}]), - routing: { - domainStrategy: "AsIs", - rules: ($route_rules[0] + [{type:"field",ip:["127.0.0.1"],port:$dns_port,outboundTag:"direct"}]) - } - }' > "$RUNTIME_DIR/xray-sidecar.json" - } -'' +) diff --git a/modules/proxy-suite/service/script-blocks/hybrid-runtime-helpers.template.sh b/modules/proxy-suite/service/script-blocks/hybrid-runtime-helpers.template.sh new file mode 100644 index 0000000..d9c7c0e --- /dev/null +++ b/modules/proxy-suite/service/script-blocks/hybrid-runtime-helpers.template.sh @@ -0,0 +1,96 @@ +XRAY_OUTBOUNDS_JSON='[]' +XRAY_CLIENTS_JSON='[]' +XRAY_ROUTE_RULES_JSON='[]' +XRAY_SIDECAR_PORT=@sidecarPort@ +XRAY_SIDECAR_DNS_PORT=@dnsBridgePort@ +# Client ids: this run's random prefix plus a counter, so every sidecar outbound has its +# own and no other local user can guess one. +XRAY_SIDECAR_SECRET=$(cat /proc/sys/kernel/random/uuid) +XRAY_SIDECAR_NEXT_ID=0 + +_proxy_suite_add_sing_box_ob() { + local ob="$1" + OUTBOUNDS_JSON=$(@jq@ --slurpfile ob <(printf '%s' "$ob") '. + $ob' <<< "$OUTBOUNDS_JSON") +} + +# $1 a JSON array of XRay outbounds, each tagged. One jq pass for the lot: each gets a +# client on the sidecar's one loopback VLESS inbound, routed to it by its email, and +# stands in sing-box as a hop to it. VLESS rather than SOCKS: UDP rides the stream +# (XUDP) with the client id, where SOCKS UDP datagrams carry no user to route by. +_proxy_suite_add_xray_sidecar_obs() { + local batch + batch=$(@jq@ -c \ + --argjson next "$XRAY_SIDECAR_NEXT_ID" \ + --rawfile secret <(printf '%s' "$XRAY_SIDECAR_SECRET") \ + --argjson port "$XRAY_SIDECAR_PORT" \ + --argjson mark @sidecarMark@ ' + def hex12: [range(11; -1; -1) as $i | (. / pow(16; $i) | floor) % 16 | "0123456789abcdef"[.:. + 1]] | add; + to_entries | map( + ($secret[:24] + ($next + .key | hex12)) as $id + | .value.tag as $tag + | {outbound: (.value + @setSidecarMark@ + | .streamSettings.sockopt.domainStrategy = (.streamSettings.sockopt.domainStrategy // "UseIP")), + client: {id: $id, email: $tag}, + rule: {type: "field", inboundTag: ["sidecar-in"], user: [$tag], outboundTag: $tag}, + hop: ({type: "vless", tag: $tag, server: "127.0.0.1", server_port: $port, uuid: $id, + packet_encoding: "xudp"}@hopRoutingMark@)}) + | {outbounds: map(.outbound), clients: map(.client), rules: map(.rule), hops: map(.hop)} + ' <<< "$1") + XRAY_SIDECAR_NEXT_ID=$((XRAY_SIDECAR_NEXT_ID + $(@jq@ '.outbounds | length' <<< "$batch"))) + # Through a file, not --argjson: a big subscription's batch outgrows the kernel's + # 128 KiB limit on one argument. + XRAY_OUTBOUNDS_JSON=$(@jq@ -c --slurpfile b <(printf '%s' "$batch") '. + $b[0].outbounds' <<< "$XRAY_OUTBOUNDS_JSON") + XRAY_CLIENTS_JSON=$(@jq@ -c --slurpfile b <(printf '%s' "$batch") '. + $b[0].clients' <<< "$XRAY_CLIENTS_JSON") + XRAY_ROUTE_RULES_JSON=$(@jq@ -c --slurpfile b <(printf '%s' "$batch") '. + $b[0].rules' <<< "$XRAY_ROUTE_RULES_JSON") + OUTBOUNDS_JSON=$(@jq@ -c --slurpfile b <(printf '%s' "$batch") '. + $b[0].hops' <<< "$OUTBOUNDS_JSON") +} + +# $1 one XRay outbound, $2 its tag. +_proxy_suite_add_xray_sidecar_ob() { + _proxy_suite_add_xray_sidecar_obs "$(@jq@ -c --arg tag "$2" '[.tag = $tag]' <<< "$1")" +} + +_proxy_suite_write_xray_sidecar_config() { + if [ "$(@jq@ 'length' <<< "$XRAY_OUTBOUNDS_JSON")" -eq 0 ]; then + return 0 + fi + @jq@ -n \ + --arg loglevel "$XRAY_LOGLEVEL" \ + --argjson dns_port "$XRAY_SIDECAR_DNS_PORT" \ + --argjson port "$XRAY_SIDECAR_PORT" \ + --slurpfile clients <(printf '%s' "$XRAY_CLIENTS_JSON") \ + --slurpfile outbounds <(printf '%s' "$XRAY_OUTBOUNDS_JSON") \ + --slurpfile route_rules <(printf '%s' "$XRAY_ROUTE_RULES_JSON") \ + ' + { + log: { + loglevel: (if $loglevel == "" then "warning" else $loglevel end), + access: "none" + }, + dns: { + servers: [ + { + address: "127.0.0.1", + port: $dns_port, + queryStrategy: "UseIP", + skipFallBack: true + } + ] + }, + inbounds: [ + { + tag: "sidecar-in", + listen: "127.0.0.1", + port: $port, + protocol: "vless", + settings: {clients: $clients[0], decryption: "none"} + } + ], + outbounds: ($outbounds[0] + [{protocol:"freedom",tag:"direct"}]), + routing: { + domainStrategy: "AsIs", + rules: ($route_rules[0] + [{type:"field",ip:["127.0.0.1"],port:$dns_port,outboundTag:"direct"}]) + } + }' > "$RUNTIME_DIR/xray-sidecar.json" +} diff --git a/modules/proxy-suite/service/script-blocks/subscription-cache-helpers.template.sh b/modules/proxy-suite/service/script-blocks/subscription-cache-helpers.template.sh new file mode 100644 index 0000000..29befdc --- /dev/null +++ b/modules/proxy-suite/service/script-blocks/subscription-cache-helpers.template.sh @@ -0,0 +1,67 @@ +@readSourceFunction@ +SUB_CACHE_DIR="@cacheDir@" +RUNTIME_SUBS_DIR="@runtimeSubscriptionsDir@" + +_proxy_suite_valid_subscription_cache() { + [ -s "$1" ] && @jq@ -e @validCacheFilter@ "$1" >/dev/null 2>&1 +} + +# Set when a fetch leaves a cache different from before, so the update unit restarts the +# proxy only for a change: a restart cuts every connection through it. +SUB_CACHE_CHANGED=0 + +_proxy_suite_commit_subscription_cache() { + local tmp="$1" target="$2" tag="$3" + if _proxy_suite_valid_subscription_cache "$tmp"; then + if [ -f "$target" ] && @diffutils@/bin/cmp -s "$tmp" "$target"; then + rm -f "$tmp" + else + mv "$tmp" "$target" + SUB_CACHE_CHANGED=1 + fi + return 0 + fi + rm -f "$tmp" + echo "proxy-suite: warning: subscription '$tag' produced an invalid cache; ignoring it" >&2 + return 1 +} + +_proxy_suite_drop_invalid_subscription_cache() { + local target="$1" tag="$2" + if [ -f "$target" ] && ! _proxy_suite_valid_subscription_cache "$target"; then + rm -f "$target" + echo "proxy-suite: warning: removed invalid subscription cache for '$tag'" >&2 + fi +} + +# $1 tag, $2 file holding the subscription URL. Writes the cache atomically, +# and next to it .links: each entry's original URI, for proxy-ctl to share. +_proxy_suite_fetch_subscription() { + local tag="$1" src="$2" cache="$SUB_CACHE_DIR/$1.json" links="$SUB_CACHE_DIR/$1.links" + mkdir -p "$SUB_CACHE_DIR" + if printf '%s' "$(_proxy_suite_read_source "$src")" \ + | PYTHONPATH="@pythonPath@" @python3@ @fetchSubscriptionPy@ \ + @backendArg@ --tag-prefix "$tag" --links-out "$links.tmp" > "$cache.tmp"; then + if _proxy_suite_commit_subscription_cache "$cache.tmp" "$cache" "$tag"; then + mv "$links.tmp" "$links" + return 0 + fi + rm -f "$links.tmp" + return 1 + fi + rm -f "$cache.tmp" "$links.tmp" + echo "proxy-suite: failed to update subscription '$tag'" >&2 + return 1 +} + +# Every runtime subscription, as "\t" lines. +_proxy_suite_runtime_subscriptions() { + local f tag + [ -d "$RUNTIME_SUBS_DIR" ] || return 0 + for f in "$RUNTIME_SUBS_DIR"/*.url; do + [ -f "$f" ] && [ ! -L "$f" ] || continue + tag="${f##*/}" + tag="${tag%.url}" + printf '%s\t%s\n' "$tag" "$f" + done +} diff --git a/modules/proxy-suite/service/script-blocks/subscriptions.nix b/modules/proxy-suite/service/script-blocks/subscriptions.nix index 90e5651..311509b 100644 --- a/modules/proxy-suite/service/script-blocks/subscriptions.nix +++ b/modules/proxy-suite/service/script-blocks/subscriptions.nix @@ -6,6 +6,7 @@ { ctx }: let + fillTemplate = import ../../lib/fill-template.nix; inherit (ctx) lib pkgs @@ -30,82 +31,21 @@ let # Defined in every script that touches a cache: the start scripts and the # update unit. - subscriptionCacheHelpersBlock = '' - ${constants.readSourceFunction pkgs} - SUB_CACHE_DIR="${subscriptionCacheDir}" - RUNTIME_SUBS_DIR="${runtimeSubscriptionsDir}" - - _proxy_suite_valid_subscription_cache() { - [ -s "$1" ] && ${jq} -e ${ - lib.escapeShellArg ( - if hybridEnabled then - ''type == "object" and (.singBox | type == "array") and (.xray | type == "array")'' - else - ''type == "array"'' - ) - } "$1" >/dev/null 2>&1 - } - - # Set when a fetch leaves a cache different from before, so the update unit restarts the - # proxy only for a change: a restart cuts every connection through it. - SUB_CACHE_CHANGED=0 - - _proxy_suite_commit_subscription_cache() { - local tmp="$1" target="$2" tag="$3" - if _proxy_suite_valid_subscription_cache "$tmp"; then - if [ -f "$target" ] && ${pkgs.diffutils}/bin/cmp -s "$tmp" "$target"; then - rm -f "$tmp" - else - mv "$tmp" "$target" - SUB_CACHE_CHANGED=1 - fi - return 0 - fi - rm -f "$tmp" - echo "proxy-suite: warning: subscription '$tag' produced an invalid cache; ignoring it" >&2 - return 1 - } - - _proxy_suite_drop_invalid_subscription_cache() { - local target="$1" tag="$2" - if [ -f "$target" ] && ! _proxy_suite_valid_subscription_cache "$target"; then - rm -f "$target" - echo "proxy-suite: warning: removed invalid subscription cache for '$tag'" >&2 - fi - } - - # $1 tag, $2 file holding the subscription URL. Writes the cache atomically, - # and next to it .links: each entry's original URI, for proxy-ctl to share. - _proxy_suite_fetch_subscription() { - local tag="$1" src="$2" cache="$SUB_CACHE_DIR/$1.json" links="$SUB_CACHE_DIR/$1.links" - mkdir -p "$SUB_CACHE_DIR" - if printf '%s' "$(_proxy_suite_read_source "$src")" \ - | PYTHONPATH="${parserScriptsPythonPath}" ${python3} ${fetchSubscriptionPy} \ - ${subscriptionBackendArg} --tag-prefix "$tag" --links-out "$links.tmp" > "$cache.tmp"; then - if _proxy_suite_commit_subscription_cache "$cache.tmp" "$cache" "$tag"; then - mv "$links.tmp" "$links" - return 0 - fi - rm -f "$links.tmp" - return 1 - fi - rm -f "$cache.tmp" "$links.tmp" - echo "proxy-suite: failed to update subscription '$tag'" >&2 - return 1 - } - - # Every runtime subscription, as "\t" lines. - _proxy_suite_runtime_subscriptions() { - local f tag - [ -d "$RUNTIME_SUBS_DIR" ] || return 0 - for f in "$RUNTIME_SUBS_DIR"/*.url; do - [ -f "$f" ] && [ ! -L "$f" ] || continue - tag="''${f##*/}" - tag="''${tag%.url}" - printf '%s\t%s\n' "$tag" "$f" - done - } - ''; + subscriptionCacheHelpersBlock = fillTemplate ./subscription-cache-helpers.template.sh { + readSourceFunction = constants.readSourceFunction pkgs; + cacheDir = subscriptionCacheDir; + inherit runtimeSubscriptionsDir jq; + validCacheFilter = lib.escapeShellArg ( + if hybridEnabled then + ''type == "object" and (.singBox | type == "array") and (.xray | type == "array")'' + else + ''type == "array"'' + ); + diffutils = pkgs.diffutils; + pythonPath = parserScriptsPythonPath; + inherit python3 fetchSubscriptionPy; + backendArg = subscriptionBackendArg; + }; # Merging a cache into OUTBOUNDS_JSON needs the routing mark, which differs per # start script, so this one is emitted separately from the cache helpers. diff --git a/modules/proxy-suite/zapret2/cutoff-probe.template.sh b/modules/proxy-suite/zapret2/cutoff-probe.template.sh new file mode 100644 index 0000000..47d2401 --- /dev/null +++ b/modules/proxy-suite/zapret2/cutoff-probe.template.sh @@ -0,0 +1,77 @@ +set -euo pipefail +export PATH=@path@ +cd @dir@ +# Root works only here, which nobody else writes to now; the group's probe requests +# come through requests/. Anything left from when the group could write here goes: +# a symlink under a name below would have root write, or read, where it points. +for f in asn.txt sni.txt asn.new sni.new proxy.json proxy.json.tmp egress ts force; do + if [ -L "$f" ] || { [ -e "$f" ] && [ ! -O "$f" ]; }; then + rm -f -- "$f" + fi +done +touch asn.txt sni.txt +force=0 +if [ -e requests/force ]; then + force=1 + rm -f requests/force +fi +now=$(date +%s) +# Digits only: $(( )) would run what a[$(...)] in it names. +last=$(cat ts 2>/dev/null || true) +[[ $last =~ ^[0-9]+$ ]] || last=0 + +# The name map belongs to this line: probe again when its network changes, else +# once a day. No answer (offline, captive portal) is no reason to probe. +info=$(curl -sS --max-time 10 https://ipinfo.io/json 2>/dev/null || true) +egress=$(jq -r '((.org // "") | split(" ")[0]) as $as + | if ($as | test("^AS[0-9]+$")) then $as else (.ip // "") end' <<<"$info" 2>/dev/null || true) +if [ -z "$egress" ]; then + echo "no answer about this line's address; not probing" + exit 0 +fi +if [ "$force" = 0 ] && [ "$egress" = "$(cat egress 2>/dev/null || true)" ] && + [ $((now - last)) -lt 86400 ]; then + exit 0 +fi +echo "probing the line from $egress" + +rc=0 +z2k-detect tcp16 -targets @lists@/tcp16_targets.txt -parallel 50 -asn-out asn.new || rc=$? +case "$rc" in + 1) + rc=0 + z2k-detect tcp16 -targets @lists@/tcp16_targets.txt -scan @lists@/sni_wl_candidates.txt \ + -per-asn -batch 5 -parallel 50 -sni-out sni.new || rc=$? + # 2: no network took any name; the list of cut-off networks still stands. + if [ "$rc" != 0 ] && [ "$rc" != 2 ]; then + rm -f asn.new sni.new + echo "name search failed ($rc); keeping the previous maps" + exit 0 + fi + [ -e sni.new ] || : >sni.new + ;; + 0) + : >asn.new + : >sni.new + ;; + *) + rm -f asn.new + echo "the probe did not run ($rc); keeping the previous maps" + exit 0 + ;; +esac + +changed=0 +{ cmp -s asn.new asn.txt && cmp -s sni.new sni.txt; } || changed=1 +mv -f asn.new asn.txt +mv -f sni.new sni.txt +@proxyRules@ asn.txt sni.txt @lists@/tcp16_nets.txt >proxy.json.tmp +mv -f proxy.json.tmp proxy.json +printf '%s\n' "$egress" >egress +printf '%s\n' "$now" >ts +echo "cut-off networks: $(grep -c '^[0-9]' asn.txt || true), with a name: $(grep -c '^[0-9]' sni.txt || true)" + +# nfqws2 reads the maps once; learned strategies survive the restart. +if [ "$changed" = 1 ]; then + systemctl try-restart @restartUnits@ +fi diff --git a/modules/proxy-suite/zapret2/cutoff.nix b/modules/proxy-suite/zapret2/cutoff.nix index cee0ee7..17b600a 100644 --- a/modules/proxy-suite/zapret2/cutoff.nix +++ b/modules/proxy-suite/zapret2/cutoff.nix @@ -12,6 +12,7 @@ }: let + fillTemplate = import ../lib/fill-template.nix; inherit (import ../derived.nix { inherit lib cfg; }) constants userControlAllows @@ -53,10 +54,9 @@ let | {version: 1, rules: (if length > 0 then [{ip_cidr: .}] else [] end)}' ''; - probe = pkgs.writeShellScript "proxy-suite-zapret2" '' - set -euo pipefail - export PATH=${ - lib.makeBinPath [ + probe = pkgs.writeShellScript "proxy-suite-zapret2" ( + fillTemplate ./cutoff-probe.template.sh { + path = lib.makeBinPath [ pkgs.coreutils pkgs.curl pkgs.diffutils @@ -64,84 +64,12 @@ let pkgs.jq pkgs.systemd z2kDetect - ] + ]; + dir = lib.escapeShellArg dir; + inherit lists proxyRules; + restartUnits = lib.escapeShellArgs restartUnits; } - cd ${lib.escapeShellArg dir} - # Root works only here, which nobody else writes to now; the group's probe requests - # come through requests/. Anything left from when the group could write here goes: - # a symlink under a name below would have root write, or read, where it points. - for f in asn.txt sni.txt asn.new sni.new proxy.json proxy.json.tmp egress ts force; do - if [ -L "$f" ] || { [ -e "$f" ] && [ ! -O "$f" ]; }; then - rm -f -- "$f" - fi - done - touch asn.txt sni.txt - force=0 - if [ -e requests/force ]; then - force=1 - rm -f requests/force - fi - now=$(date +%s) - # Digits only: $(( )) would run what a[$(...)] in it names. - last=$(cat ts 2>/dev/null || true) - [[ $last =~ ^[0-9]+$ ]] || last=0 - - # The name map belongs to this line: probe again when its network changes, else - # once a day. No answer (offline, captive portal) is no reason to probe. - info=$(curl -sS --max-time 10 https://ipinfo.io/json 2>/dev/null || true) - egress=$(jq -r '((.org // "") | split(" ")[0]) as $as - | if ($as | test("^AS[0-9]+$")) then $as else (.ip // "") end' <<<"$info" 2>/dev/null || true) - if [ -z "$egress" ]; then - echo "no answer about this line's address; not probing" - exit 0 - fi - if [ "$force" = 0 ] && [ "$egress" = "$(cat egress 2>/dev/null || true)" ] && - [ $((now - last)) -lt 86400 ]; then - exit 0 - fi - echo "probing the line from $egress" - - rc=0 - z2k-detect tcp16 -targets ${lists}/tcp16_targets.txt -parallel 50 -asn-out asn.new || rc=$? - case "$rc" in - 1) - rc=0 - z2k-detect tcp16 -targets ${lists}/tcp16_targets.txt -scan ${lists}/sni_wl_candidates.txt \ - -per-asn -batch 5 -parallel 50 -sni-out sni.new || rc=$? - # 2: no network took any name; the list of cut-off networks still stands. - if [ "$rc" != 0 ] && [ "$rc" != 2 ]; then - rm -f asn.new sni.new - echo "name search failed ($rc); keeping the previous maps" - exit 0 - fi - [ -e sni.new ] || : >sni.new - ;; - 0) - : >asn.new - : >sni.new - ;; - *) - rm -f asn.new - echo "the probe did not run ($rc); keeping the previous maps" - exit 0 - ;; - esac - - changed=0 - { cmp -s asn.new asn.txt && cmp -s sni.new sni.txt; } || changed=1 - mv -f asn.new asn.txt - mv -f sni.new sni.txt - ${proxyRules} asn.txt sni.txt ${lists}/tcp16_nets.txt >proxy.json.tmp - mv -f proxy.json.tmp proxy.json - printf '%s\n' "$egress" >egress - printf '%s\n' "$now" >ts - echo "cut-off networks: $(grep -c '^[0-9]' asn.txt || true), with a name: $(grep -c '^[0-9]' sni.txt || true)" - - # nfqws2 reads the maps once; learned strategies survive the restart. - if [ "$changed" = 1 ]; then - systemctl try-restart ${lib.escapeShellArgs restartUnits} - fi - ''; + ); # The probe measures this line, so its traffic leaves directly: proxyMark keeps it # out of TUN/TProxy like the backend's own, and the conntrack bit keeps zapret2 from diff --git a/modules/proxy-suite/zapret2/runtime.nix b/modules/proxy-suite/zapret2/runtime.nix index c5b3210..663536c 100644 --- a/modules/proxy-suite/zapret2/runtime.nix +++ b/modules/proxy-suite/zapret2/runtime.nix @@ -8,6 +8,7 @@ }: let + fillTemplate = import ../lib/fill-template.nix; zapret2Cfg = cfg.zapret.zapret2; autoCfg = zapret2Cfg.autoHostlist; @@ -226,50 +227,9 @@ let # templates apart; a profile that imports a template rotates over its strategies. mkStrategies = config: - pkgs.runCommand "proxy-suite-zapret2-strategies.json" { nativeBuildInputs = [ pkgs.gawk ]; } '' - . ${config} - set -f - printf '%s\n' $NFQWS2_OPT | awk ' - function js(s) { gsub(/\\/, "\\\\", s); gsub(/"/, "\\\"", s); return "\"" s "\"" } - # Numeric from the start: an unset s indexes the first section as "", not 0. - BEGIN { s = 0 } - $0 == "--new" { s++; next } - /^--template=/ { tpl[substr($0, 12)] = s; istpl[s] = 1; next } - /^--import=/ { imp[s] = substr($0, 10); next } - /^--lua-desync=/ { - fn[s]++ - spec = substr($0, 14) - if (spec ~ /^circular(:|$)/) { - circ[s] = fn[s] - if (match(spec, /:key=[^:]+/)) key[s] = substr(spec, RSTART + 5, RLENGTH - 5) - } else if (match(spec, /:strategy=[0-9]+/)) { - n = substr(spec, RSTART + 10, RLENGTH - 10) - spec = substr(spec, 1, RSTART - 1) substr(spec, RSTART + RLENGTH) - if (!((s, n) in strat)) order[s] = order[s] " " n - strat[s, n] = ((s, n) in strat ? strat[s, n] "," : "") js(spec) - } - } - END { - printf "{" - for (i = 0; i <= s; i++) { - if (istpl[i]) continue - p++ - if (!(i in circ)) continue - k = (i in key) ? key[i] : "circular_" p "_" circ[i] - src = (i in imp && imp[i] in tpl) ? tpl[imp[i]] : "" - printf "%s%s:{", (out++ ? "," : ""), js(k) - m = 0 - for (pass = 0; pass < 2; pass++) { - j = pass ? src : i - if (j == "") continue - c = split(order[j], ns, " ") - for (x = 1; x <= c; x++) printf "%s%s:[%s]", (m++ ? "," : ""), js(ns[x]), strat[j, ns[x]] - } - printf "}" - } - print "}" - }' >"$out" - ''; + pkgs.runCommand "proxy-suite-zapret2-strategies.json" { nativeBuildInputs = [ pkgs.gawk ]; } ( + fillTemplate ./strategies.template.sh { inherit config; } + ); # Keep desync off TUN interfaces (it breaks proxied handshakes), off per-app # traffic, and off exempted subnets (e.g. NATed VMs whose traffic it would break). diff --git a/modules/proxy-suite/zapret2/sources.nix b/modules/proxy-suite/zapret2/sources.nix index 17f52be..d20a952 100644 --- a/modules/proxy-suite/zapret2/sources.nix +++ b/modules/proxy-suite/zapret2/sources.nix @@ -6,6 +6,7 @@ }: let + fillTemplate = import ../lib/fill-template.nix; inherit (lib) concatStringsSep filter @@ -110,101 +111,17 @@ let # under $out because the generated options point into it. mkProfiles = { hostlistSuffix, excludeSuffix }: - pkgs.runCommand "proxy-suite-zapret2-z2k-profiles" - { - nativeBuildInputs = with pkgs; [ - bash - coreutils - findutils - gawk - gnugrep - gnused - ]; - inherit hostlistSuffix excludeSuffix; - } - '' - root=$out/root - mkdir -p "$root/lists" "$root/lua" conf - cp -r ${src}/files/lists/extra_strats "$root/" - chmod -R u+w "$root" - cp "$root/extra_strats/TCP/RKN/Discord.txt" "$root/extra_strats/TCP_Discord.txt" - cp ${src}/files/lists/cf_extra_check_ips.txt "$root/lists/" - : >"$root/lists/discovered-domains.txt" - # Its cutoff name step is emitted only on lines its probe flagged; ours is - # a no-op until the cutoff probe writes maps, so emit it unconditionally. - mkdir -p "$root/state" - echo 1 >"$root/state/tcp16.flag" - # The generator wires its detectors only when their Lua files exist. - ln -s ${src}/files/lua/*.lua "$root/lua/" - - export ZAPRET2_DIR="$root" CONFIG_DIR="$PWD/conf" LISTS_DIR="$root/lists" - ( - cd ${src} - bash -c ' - . lib/utils.sh && . lib/config.sh && . lib/strategies.sh && . lib/config_official.sh || exit 1 - print_info() { echo "$*" >&2; } - print_success() { echo "$*" >&2; } - print_warning() { echo "$*" >&2; } - print_error() { echo "$*" >&2; } - create_base_config >&2 && - generate_strategies_conf strats_new2.txt "$STRATEGIES_CONF" >&2 && - generate_quic_strategies_conf quic_strats.ini "$QUIC_STRATEGIES_CONF" >&2 && - create_default_strategy_files >&2 && - generate_nfqws2_opt_from_strategies - ' - ) >generated - - sed -n '/^NFQWS2_OPT="/,/^"$/p' generated | sed '1s/^NFQWS2_OPT="//; $d' | tr '\n' ' ' >raw - grep -q -- '--lua-desync=circular' raw || { echo "z2k generator produced no profiles" >&2; exit 1; } - - # Its learned-host list becomes ours, its whitelist gains our excludes, and - # the circular args it pins to the zapret2 docs are dropped so autoHostlist - # fills them in. A profile with --hostlist-auto wins every flow with a known - # name (nfq2/desync.c), so learning goes in a last profile of its own with no - # strategies, as z2k's own autohostlist does: on rkn_tcp it would take - # YouTube from yt_tcp/gv_tcp below it. rkn_tcp then leaves their hosts to - # them even once learned or added by hand. - awk -v disc="--hostlist=$root/lists/discovered-domains.txt" \ - -v wl="--hostlist-exclude=$root/lists/whitelist.txt" \ - -v yt="--hostlist-exclude=$root/extra_strats/TCP/YT/List.txt --hostlist-exclude=$root/extra_strats/TCP/YT_GV/List.txt" \ - -v hsuf="$hostlistSuffix" -v esuf="$excludeSuffix" ' - { - for (i = 1; i <= NF; i++) { - t = $i - if (t == "--new") { - prof++ - } else if (t ~ /^--filter-tcp=/ && !(prof in ports)) { - ports[prof] = substr(t, 14) - } - if (t == disc) { - t = "" hsuf - if (!seen++) { t = t " " yt; learner = prof } - } else if (t == wl) { - t = t esuf - } else if (t ~ /^--lua-desync=circular:/) { - n = split(substr(t, 23), p, ":") - t = "--lua-desync=circular" - for (j = 1; j <= n; j++) - if (p[j] !~ /^(retrans|maxseq|inseq)=/ && p[j] != "reset") t = t ":" p[j] - } - printf "%s%s", (i > 1 ? " " : ""), t - } - } - END { - if (!seen || !(learner in ports)) { print "z2k general TLS profile not found" > "/dev/stderr"; exit 1 } - printf " --new --filter-tcp=%s --filter-l7=tls %s%s %s", ports[learner], wl, esuf, hsuf - }' raw >body - - awk -v z=${src} ' - match($0, /^([A-Z0-9_]+_BLOB)="\$ZAPRET_BASE\/([^"]+)"/, m) { file[m[1]] = m[2] } - match($0, /--blob=([a-z0-9_]+):@\$([A-Z0-9_]+_BLOB)/, m) { printf "--blob=%s:@%s/%s ", m[1], z, file[m[2]] } - ' ${src}/files/S99zapret2.new >blobs - grep -q -- '--blob=' blobs || { echo "z2k blob registrations not found" >&2; exit 1; } - - mkdir -p "$out" - cp blobs "$out/blobs" - cp body "$out/profiles" - ''; + pkgs.runCommand "proxy-suite-zapret2-z2k-profiles" { + nativeBuildInputs = with pkgs; [ + bash + coreutils + findutils + gawk + gnugrep + gnused + ]; + inherit hostlistSuffix excludeSuffix; + } (fillTemplate ./z2k-profiles.template.sh { z2k = src; }); }; in { diff --git a/modules/proxy-suite/zapret2/strategies.template.sh b/modules/proxy-suite/zapret2/strategies.template.sh new file mode 100644 index 0000000..8a63402 --- /dev/null +++ b/modules/proxy-suite/zapret2/strategies.template.sh @@ -0,0 +1,42 @@ +. @config@ +set -f +printf '%s\n' $NFQWS2_OPT | awk ' + function js(s) { gsub(/\\/, "\\\\", s); gsub(/"/, "\\\"", s); return "\"" s "\"" } + # Numeric from the start: an unset s indexes the first section as "", not 0. + BEGIN { s = 0 } + $0 == "--new" { s++; next } + /^--template=/ { tpl[substr($0, 12)] = s; istpl[s] = 1; next } + /^--import=/ { imp[s] = substr($0, 10); next } + /^--lua-desync=/ { + fn[s]++ + spec = substr($0, 14) + if (spec ~ /^circular(:|$)/) { + circ[s] = fn[s] + if (match(spec, /:key=[^:]+/)) key[s] = substr(spec, RSTART + 5, RLENGTH - 5) + } else if (match(spec, /:strategy=[0-9]+/)) { + n = substr(spec, RSTART + 10, RLENGTH - 10) + spec = substr(spec, 1, RSTART - 1) substr(spec, RSTART + RLENGTH) + if (!((s, n) in strat)) order[s] = order[s] " " n + strat[s, n] = ((s, n) in strat ? strat[s, n] "," : "") js(spec) + } + } + END { + printf "{" + for (i = 0; i <= s; i++) { + if (istpl[i]) continue + p++ + if (!(i in circ)) continue + k = (i in key) ? key[i] : "circular_" p "_" circ[i] + src = (i in imp && imp[i] in tpl) ? tpl[imp[i]] : "" + printf "%s%s:{", (out++ ? "," : ""), js(k) + m = 0 + for (pass = 0; pass < 2; pass++) { + j = pass ? src : i + if (j == "") continue + c = split(order[j], ns, " ") + for (x = 1; x <= c; x++) printf "%s%s:[%s]", (m++ ? "," : ""), js(ns[x]), strat[j, ns[x]] + } + printf "}" + } + print "}" + }' >"$out" diff --git a/modules/proxy-suite/zapret2/z2k-profiles.template.sh b/modules/proxy-suite/zapret2/z2k-profiles.template.sh new file mode 100644 index 0000000..53a792c --- /dev/null +++ b/modules/proxy-suite/zapret2/z2k-profiles.template.sh @@ -0,0 +1,81 @@ +root=$out/root +mkdir -p "$root/lists" "$root/lua" conf +cp -r @z2k@/files/lists/extra_strats "$root/" +chmod -R u+w "$root" +cp "$root/extra_strats/TCP/RKN/Discord.txt" "$root/extra_strats/TCP_Discord.txt" +cp @z2k@/files/lists/cf_extra_check_ips.txt "$root/lists/" +: >"$root/lists/discovered-domains.txt" +# Its cutoff name step is emitted only on lines its probe flagged; ours is +# a no-op until the cutoff probe writes maps, so emit it unconditionally. +mkdir -p "$root/state" +echo 1 >"$root/state/tcp16.flag" +# The generator wires its detectors only when their Lua files exist. +ln -s @z2k@/files/lua/*.lua "$root/lua/" + +export ZAPRET2_DIR="$root" CONFIG_DIR="$PWD/conf" LISTS_DIR="$root/lists" +( + cd @z2k@ + bash -c ' + . lib/utils.sh && . lib/config.sh && . lib/strategies.sh && . lib/config_official.sh || exit 1 + print_info() { echo "$*" >&2; } + print_success() { echo "$*" >&2; } + print_warning() { echo "$*" >&2; } + print_error() { echo "$*" >&2; } + create_base_config >&2 && + generate_strategies_conf strats_new2.txt "$STRATEGIES_CONF" >&2 && + generate_quic_strategies_conf quic_strats.ini "$QUIC_STRATEGIES_CONF" >&2 && + create_default_strategy_files >&2 && + generate_nfqws2_opt_from_strategies + ' +) >generated + +sed -n '/^NFQWS2_OPT="/,/^"$/p' generated | sed '1s/^NFQWS2_OPT="//; $d' | tr '\n' ' ' >raw +grep -q -- '--lua-desync=circular' raw || { echo "z2k generator produced no profiles" >&2; exit 1; } + +# Its learned-host list becomes ours, its whitelist gains our excludes, and +# the circular args it pins to the zapret2 docs are dropped so autoHostlist +# fills them in. A profile with --hostlist-auto wins every flow with a known +# name (nfq2/desync.c), so learning goes in a last profile of its own with no +# strategies, as z2k's own autohostlist does: on rkn_tcp it would take +# YouTube from yt_tcp/gv_tcp below it. rkn_tcp then leaves their hosts to +# them even once learned or added by hand. +awk -v disc="--hostlist=$root/lists/discovered-domains.txt" \ + -v wl="--hostlist-exclude=$root/lists/whitelist.txt" \ + -v yt="--hostlist-exclude=$root/extra_strats/TCP/YT/List.txt --hostlist-exclude=$root/extra_strats/TCP/YT_GV/List.txt" \ + -v hsuf="$hostlistSuffix" -v esuf="$excludeSuffix" ' + { + for (i = 1; i <= NF; i++) { + t = $i + if (t == "--new") { + prof++ + } else if (t ~ /^--filter-tcp=/ && !(prof in ports)) { + ports[prof] = substr(t, 14) + } + if (t == disc) { + t = "" hsuf + if (!seen++) { t = t " " yt; learner = prof } + } else if (t == wl) { + t = t esuf + } else if (t ~ /^--lua-desync=circular:/) { + n = split(substr(t, 23), p, ":") + t = "--lua-desync=circular" + for (j = 1; j <= n; j++) + if (p[j] !~ /^(retrans|maxseq|inseq)=/ && p[j] != "reset") t = t ":" p[j] + } + printf "%s%s", (i > 1 ? " " : ""), t + } + } + END { + if (!seen || !(learner in ports)) { print "z2k general TLS profile not found" > "/dev/stderr"; exit 1 } + printf " --new --filter-tcp=%s --filter-l7=tls %s%s %s", ports[learner], wl, esuf, hsuf + }' raw >body + +awk -v z=@z2k@ ' + match($0, /^([A-Z0-9_]+_BLOB)="\$ZAPRET_BASE\/([^"]+)"/, m) { file[m[1]] = m[2] } + match($0, /--blob=([a-z0-9_]+):@\$([A-Z0-9_]+_BLOB)/, m) { printf "--blob=%s:@%s/%s ", m[1], z, file[m[2]] } +' @z2k@/files/S99zapret2.new >blobs +grep -q -- '--blob=' blobs || { echo "z2k blob registrations not found" >&2; exit 1; } + +mkdir -p "$out" +cp blobs "$out/blobs" +cp body "$out/profiles" diff --git a/nix/checks/repo.nix b/nix/checks/repo.nix index a4a28dd..6328115 100644 --- a/nix/checks/repo.nix +++ b/nix/checks/repo.nix @@ -10,6 +10,7 @@ }: let + fillTemplate = import ../../modules/proxy-suite/lib/fill-template.nix; # Every proxy-ctl CLI check runs against the same disabled-feature defaults; only the # files and the feature under test differ. perAppRoutingOff = '' @@ -286,146 +287,12 @@ in pkgs.jq ]; } - '' - proxy_ctl=${../../pkgs/proxy-ctl/proxy_ctl.py} - - # systemd is not in the sandbox. The reload stub stands in for the start - # script, which is what actually republishes the inventory. - mkdir -p stub - { - printf '%s\n' '#!/bin/sh' - printf '%s\n' 'if [ "$1" = start ] && [ "$2" = proxy-suite-outbound-reload.service ]; then' - printf '%s\n' ' ls "$RUNTIME_OUTBOUNDS_DIR" > "$OUTBOUND_INVENTORY_FILE.spool"' - printf '%s\n' ' jq --rawfile spool "$OUTBOUND_INVENTORY_FILE.spool" '"'"'($spool | split("\n") | map(select(endswith(".url") or endswith(".json")) | sub("\\.(url|json)$"; ""))) as $new | .tags = (.tags + $new | unique) | .sources = reduce $new[] as $t (.sources; .[$t] = "runtime")'"'"' "$OUTBOUND_INVENTORY_FILE" > "$OUTBOUND_INVENTORY_FILE.tmp"' - printf '%s\n' ' mv "$OUTBOUND_INVENTORY_FILE.tmp" "$OUTBOUND_INVENTORY_FILE"' - printf '%s\n' ' jq --rawfile spool "$OUTBOUND_INVENTORY_FILE.spool" '"'"'.disabled = ($spool | split("\n") | map(select(endswith(".disabled")) | sub("\\.disabled$"; ""))) | .excluded = (.excluded + .disabled | unique)'"'"' "$OUTBOUND_INVENTORY_FILE" > "$OUTBOUND_INVENTORY_FILE.tmp"' - printf '%s\n' ' mv "$OUTBOUND_INVENTORY_FILE.tmp" "$OUTBOUND_INVENTORY_FILE"' - printf '%s\n' 'fi' - printf '%s\n' 'exit 0' - } > stub/systemctl - printf '#!/bin/sh\nprintf %%s "$2"\n' > stub/systemd-escape - chmod +x stub/systemctl stub/systemd-escape - export PATH="$PWD/stub:$PATH" - - mkdir -p obd subd cache - printf '%s\n' '["community"]' > tags.json - jq -n '{tags:["own-vps","community-de"], - sources:{"own-vps":"static","community-de":"sub:community"}, - pinned:"community-de", selection:"urltest", - detours:{"community-de":"own-vps"}, excluded:["own-vps"]}' > inventory.json - - run() { - env \ - SUB_TAGS_FILE="$PWD/tags.json" \ - SUB_CACHE_DIR="$PWD/cache" \ - OUTBOUND_INVENTORY_FILE="$PWD/inventory.json" \ - RUNTIME_OUTBOUNDS_DIR="$PWD/obd" \ - RUNTIME_SUBS_DIR="$PWD/subd" \ - USER_CONTROL_GROUP="proxy-suite" \ - CLASH_API="http://127.0.0.1:1" \ - SELECTION="urltest" \ - ${perAppRoutingOff} python3 "$proxy_ctl" "$@" + ( + fillTemplate ./repo/proxy-ctl-outbounds.template.sh { + proxyCtl = ../../pkgs/proxy-ctl/proxy_ctl.py; + inherit perAppRoutingOff; } - - # Listing works from the inventory alone, with no Clash API answering. - run proxy outbounds > listing - grep -q 'Selection: urltest' listing - grep -q 'Pinned: community-de' listing - grep -q '\*community-de' listing - grep -q 'own-vps *static' listing - # What each one chains through, and what selection leaves alone. - grep -q 'community-de *sub:community, via own-vps$' listing - grep -q 'own-vps *static, never picked$' listing - # The old spelling still dispatches. - run outbounds | cmp - listing - - # Reserved and malformed tags are refused before anything is written. - for bad in proxy direct block "has space" "-leading"; do - if run proxy outbounds add "$bad" http://example.com:1 2>/dev/null; then - echo "accepted invalid tag: $bad" >&2 - exit 1 - fi - done - # Tags that already exist are refused too, declared or not. - ! run proxy outbounds add own-vps http://example.com:1 2>/dev/null - ! run proxy subs add community https://example.com/sub 2>/dev/null - # A URL with whitespace is refused. - ! run proxy outbounds add ok-tag "http://example.com:1 x" 2>/dev/null - # Nothing above touched the spool. - [ -z "$(ls -A obd)" ] - - # Removing something that was never added says so. - ! run proxy outbounds rm nope 2>/dev/null - - # A good add lands in the spool group-readable, not world-readable. - run proxy outbounds add spool-one http://example.com:1 | grep -q 'Added outbound: spool-one' - [ "$(cat obd/spool-one.url)" = "http://example.com:1" ] - [ "$(stat -c %a obd/spool-one.url)" = "640" ] - run proxy outbounds | grep -q 'spool-one *runtime' - # Adding it twice is refused. - ! run proxy outbounds add spool-one http://example.com:1 2>/dev/null - run proxy outbounds rm spool-one | grep -q 'Removed outbound: spool-one' - [ ! -e obd/spool-one.url ] - - # --detour leaves the hop next to the entry, and only names an outbound that exists. - ! run proxy outbounds add bad-hop http://example.com:1 --detour nope 2>/dev/null - [ ! -e obd/bad-hop.url ] - run proxy outbounds add chained http://example.com:1 --detour own-vps | grep -q 'Added outbound: chained' - [ "$(cat obd/chained.detour)" = own-vps ] - run proxy outbounds rm chained > /dev/null - [ ! -e obd/chained.detour ] - # A hop left behind does not chain a later entry of the same name. - echo own-vps > obd/unchained.detour - run proxy outbounds add unchained http://example.com:1 > /dev/null - [ ! -e obd/unchained.detour ] - run proxy outbounds rm unchained > /dev/null - - # JSON, as `link --json` prints it, lands as .json without its own tag; stdin too. - run proxy outbounds add from-json '{"type":"trojan","tag":"x","server":"t.test","server_port":443,"password":"p"}' \ - | grep -q 'Added outbound: from-json' - [ "$(jq -r 'has("tag"), .server' obd/from-json.json | paste -sd,)" = "false,t.test" ] - printf '%s' '{"protocol":"vless","settings":{}}' | run proxy outbounds add from-stdin - | grep -q 'Added outbound: from-stdin' - ! run proxy outbounds add from-json '{"type":"trojan"}' 2>/dev/null - ! run proxy outbounds add bad-json '{"server":"t.test"}' 2>/dev/null - ! run proxy outbounds add bad-json '{nope' 2>/dev/null - [ ! -e obd/bad-json.json ] - run proxy outbounds rm from-json | grep -q 'Removed outbound: from-json' - [ ! -e obd/from-json.json ] - - # Without a tag one is made from the link; a tag after the link is a mix-up. - run proxy outbounds add 'vless://u@de.example.net:443#DE%201' > named - grep -q 'Tag: DE-1 (none given' named - grep -q 'Added outbound: DE-1' named - ! run proxy outbounds add http://example.com:1 x 2>/dev/null - run proxy outbounds rm DE-1 > /dev/null - - # Disabling leaves a marker the start script reads; a pin refuses it until enabled. - run proxy outbounds disable own-vps | grep -q 'Disabled: own-vps' - [ -e obd/own-vps.disabled ] - run proxy outbounds | grep -q -- '-own-vps *static, disabled$' - ! run proxy pin own-vps 2>/dev/null - run proxy outbounds enable own-vps | grep -q 'Enabled: own-vps' - [ ! -e obd/own-vps.disabled ] - - # Subscriptions use the same spool machinery, verified by cache file. - printf '%s\n' '[{},{}]' > cache/extra.json - run proxy subs add extra https://example.com/sub | grep -q 'Added subscription: extra (2 proxies)' - run proxy subs list > subs - grep -q 'community .* static' subs - grep -q 'extra .* runtime' subs - - # A spool entry the backend refused is reported, not silently accepted. - run proxy subs add rejected https://example.com/sub > rejected 2>&1 && exit 1 - grep -q 'did not come up' rejected - - # Pinning and unpinning go through their units. - run proxy pin community-de | grep -q 'Pinned: community-de' - run proxy unpin | grep -q 'Unpinned' - # Without a terminal and without a tag there is nothing to pick from. - ! run proxy pin /dev/null - - touch "$out" - ''; + ); proxy-ctl-zapret-auto = pkgs.runCommand "proxy-suite-proxy-ctl-zapret-auto-check" @@ -437,70 +304,11 @@ in pkgs.gnugrep ]; } - '' - proxy_ctl=${../../pkgs/proxy-ctl/proxy_ctl.py} - - state="$PWD/state" - mkdir -p "$state" - printf 'blocked.example\nother.example\n' > "$state/zapret-hosts-auto.txt" - : > "$state/zapret-hosts-user.txt" - : > "$state/zapret-hosts-user-exclude.txt" - - run() { - env ZAPRET_AUTO_ENABLED=1 ZAPRET_STATE_DIR="$state" python3 "$proxy_ctl" zapret auto "$@" + ( + fillTemplate ./repo/proxy-ctl-zapret-auto.template.sh { + proxyCtl = ../../pkgs/proxy-ctl/proxy_ctl.py; } - - run list | grep -qx blocked.example - - # exclude must also blacklist, or the host is relearned. - run exclude blocked.example > /dev/null - ! grep -qx blocked.example "$state/zapret-hosts-auto.txt" - grep -qx blocked.example "$state/zapret-hosts-user-exclude.txt" - - # Pinning is idempotent, so repeated runs cannot grow the list. - run add pinned.example > /dev/null - run add pinned.example > /dev/null - test "$(grep -c -x pinned.example "$state/zapret-hosts-user.txt")" = 1 - - # unpin and include undo add and exclude. - run unpin pinned.example > /dev/null - ! grep -qx pinned.example "$state/zapret-hosts-user.txt" - run include blocked.example > /dev/null - ! grep -qx blocked.example "$state/zapret-hosts-user-exclude.txt" - run add pinned.example > /dev/null - - # The lists stay readable by unprivileged proxy-ctl after a rewrite. - test "$(stat -c %a "$state/zapret-hosts-user.txt")" = 644 - - # Forgetting a host also drops the strategy remembered for its apex. - mkdir -p "$state/circular" - printf '# key\thost\tstrategy\tts\tmode\tsni\nrkn_tcp\tyoutube.com\t3\t1\tauto\t\nrkn_tcp\tother.example\t2\t1\tauto\t\nyt_tcp\tyoutube.com\t5\t1\tauto\t\n' > "$state/circular/state.tsv" - run forget www.youtube.com > /dev/null - ! grep -q 'youtube.com' "$state/circular/state.tsv" - grep -q 'other.example' "$state/circular/state.tsv" - grep -q '^# key' "$state/circular/state.tsv" - - run clear > /dev/null - run list | grep -q 'No hostnames learned' - test ! -s "$state/circular/state.tsv" - - # The cutoff verdict names each cut-off network's way through. - mkdir -p "$state/cutoff" - printf '1789000000\n' > "$state/cutoff/ts" - printf 'AS12389\n' > "$state/cutoff/egress" - printf '24940\n14061\n' > "$state/cutoff/asn.txt" - printf '24940\t300.ya.ru\n' > "$state/cutoff/sni.txt" - cutoff=$(env ZAPRET_CUTOFF_ENABLED=1 ZAPRET_CUTOFF_DIR="$state/cutoff" python3 "$proxy_ctl" zapret cutoff) - printf '%s\n' "$cutoff" | grep -q 'from AS12389$' - printf '%s\n' "$cutoff" | grep -qx 'Cutoff: 2 network(s)' - printf '%s\n' "$cutoff" | grep -qE '^ AS24940 +300\.ya\.ru$' - printf '%s\n' "$cutoff" | grep -qE '^ AS14061 +no name - proxy fallback$' - - # Without the zapret2 engine there is nothing to inspect. - ! env ZAPRET_AUTO_ENABLED=0 ZAPRET_STATE_DIR="$state" python3 "$proxy_ctl" zapret auto list - - touch "$out" - ''; + ); proxy-ctl-complete = pkgs.runCommand "proxy-suite-proxy-ctl-complete-check" @@ -513,75 +321,16 @@ in pkgs.jq ]; } - '' - proxy_ctl=${../../pkgs/proxy-ctl/proxy_ctl.py} - - printf '%s\n' '["home","work"]' > awg.json - jq -n '[{name:"torrent",route:"direct"}]' > profiles.json - jq -n '{tags:["own-vps","community-de"],sources:{"own-vps":"proxy.outbounds"}}' > inventory.json - - run() { - env AWG_PROFILES_FILE="$PWD/awg.json" \ - PER_APP_ROUTING_PROFILES_FILE="$PWD/profiles.json" \ - OUTBOUND_INVENTORY_FILE="$PWD/inventory.json" \ - python3 "$proxy_ctl" __complete "$@" + ( + fillTemplate ./repo/proxy-ctl-complete.template.sh { + proxyCtl = ../../pkgs/proxy-ctl/proxy_ctl.py; + bashCompletion = ../../pkgs/proxy-ctl/completions/proxy-ctl.bash; + zsh = pkgs.zsh; + zshCompletion = ../../pkgs/proxy-ctl/completions/_proxy-ctl; + fish = pkgs.fish; + fishCompletion = ../../pkgs/proxy-ctl/completions/proxy-ctl.fish; } - - # Every group the help lists must complete, or the table has drifted. - python3 "$proxy_ctl" help | awk '/^ [a-z]/ { print $1 }' | sort -u > groups - run | cut -f1 > top - while read -r group; do - grep -qx "$group" top || { echo "help lists $group, completion does not" >&2; exit 1; } - done < groups - - # Piping into `grep -q` would race the script against SIGPIPE. - has() { - local want="$1" - shift - run "$@" | cut -f1 > words - grep -qx -- "$want" words - } - - has outbounds proxy - has all-bypass proxy mode - has exclude zapret auto - has proxy-suite-awg-work logs - has work awg on - has add awg - has rm awg - has torrent apps run - has unpin proxy - has newnym tor - has --onion inbounds link - has community-de proxy pin - - # Flags, and completion past the first of several arguments. - has --delay proxy outbounds test - has community-de proxy outbounds test own-vps - has --download proxy outbounds test own-vps --ping - has own-vps proxy auto probe example.com --via - has community-de proxy outbounds add hop https://example.com --detour - # chain takes the outbound to copy, then the hop it dials through. - has community-de proxy outbounds chain own-vps - has outbound inbounds stats --by - # Unreadable state loses the values, not the flags. - has --qr inbounds sub - - # Candidates carry a description after a tab. - run proxy pin > words - grep -qx "$(printf 'own-vps\tproxy.outbounds')" words - - # A shell completing must never die, however unreadable the state is. - run inbounds link > /dev/null - env AWG_PROFILES_FILE=/nonexistent python3 "$proxy_ctl" __complete awg on - - # Every shell's completion file at least parses. - bash -n ${../../pkgs/proxy-ctl/completions/proxy-ctl.bash} - ${pkgs.zsh}/bin/zsh -n ${../../pkgs/proxy-ctl/completions/_proxy-ctl} - HOME="$TMPDIR" ${pkgs.fish}/bin/fish --no-execute ${../../pkgs/proxy-ctl/completions/proxy-ctl.fish} - - touch "$out" - ''; + ); proxy-ctl-where = pkgs.runCommand "proxy-suite-proxy-ctl-where-check" @@ -593,179 +342,40 @@ in pkgs.jq ]; } - '' - proxy_ctl=${../../pkgs/proxy-ctl/proxy_ctl.py} - - mkdir -p ap zap - jq -n '{domains:{"spotify.com":{exit:"community-de",host:"open.spotify.com",at:0}}}' > ap/state.json - printf 'nyt.com\n' > zap/zapret-hosts-auto.txt - printf 'discord.com\n' > zap/zapret-hosts-user.txt - printf 'ok.ru\n' > zap/zapret-hosts-user-exclude.txt - - run() { - env AUTOPROXY_ENABLED=1 AUTOPROXY_STATE_DIR="$PWD/ap" \ - ZAPRET_AUTO_ENABLED=1 ZAPRET_STATE_DIR="$PWD/zap" \ - python3 "$proxy_ctl" where "$@" - } - - # Piping into `grep -q` would race the script against SIGPIPE. - verdict() { - run "$1" > where - grep -q -- "$2" where - } - - # Both stores key on an apex, so a subdomain has to match its parent. - verdict open.spotify.com '-> proxied via community-de' - grep -q 'autoProxy .*routed via community-de' where - # What proxy-ctl cannot see has to be said out loud. - grep -q 'sing-box config is not readable' where - - verdict discord.com '-> direct, with the zapret bypass' - verdict nyt.com '-> direct, with the zapret bypass' - # Excluded is not bypassed: it must not read as a zapret2 verdict. - verdict ok.ru '-> nothing runtime matches it' - verdict example.org '-> nothing runtime matches it' - - # A URL is accepted where a hostname is. - verdict https://open.spotify.com/track/x '^ domain *open.spotify.com$' - - ! python3 "$proxy_ctl" where 2>/dev/null - - touch "$out" - ''; + (fillTemplate ./repo/proxy-ctl-where.template.sh { proxyCtl = ../../pkgs/proxy-ctl/proxy_ctl.py; }); # autoProxy slowness routing: sampler and judge. autoproxy-slowness = pkgs.runCommand "proxy-suite-autoproxy-slowness-check" { nativeBuildInputs = [ pkgs.jq ]; } - '' - sample=${../../modules/proxy-suite/autoproxy-slow-sample.jq} - judge=${../../modules/proxy-suite/autoproxy-slow-judge.jq} - - # A steady crawl, a burst, probe and outbound-test traffic, and a tiny flow. - res="$(jq -n -c '[range(0; 11) as $t | {connections: [ - {id: "a", metadata: {host: "i.pximg.net", type: "mixed/mixed-in"}, chains: ["direct"], download: ($t * 50000)}, - {id: "b", metadata: {host: "audio.example", type: "mixed/mixed-in"}, chains: ["direct"], download: (if $t >= 5 then 2000000 else 0 end)}, - {id: "c", metadata: {host: "probe.example", type: "mixed/probe-in-0"}, chains: ["direct"], download: ($t * 50000)}, - {id: "d", metadata: {host: "tiny.example", type: "mixed/mixed-in"}, chains: ["direct"], download: ($t * 1000)}, - {id: "e", metadata: {host: "far.example", type: "mixed/mixed-in"}, chains: ["primary", "proxy"], download: ($t * 50000)}, - {id: "f", metadata: {host: "speed.example", type: "mixed/proxy-suite-test-in"}, chains: ["primary", "proxy-suite-test"], download: ($t * 50000)} - ]}][]' | jq -s -r --argjson min 307200 --argjson below 153600 -f "$sample")" - printf '%s\n' "$res" - test "$(wc -l <<<"$res")" = 3 - grep -qx "$(printf 'i.pximg.net\tdirect\tslow\t50000')" <<<"$res" - grep -qx "$(printf 'audio.example\tdirect\tfast\t2000000')" <<<"$res" - # chains[0] is the exit that carried it, not the selector. - grep -qx "$(printf 'far.example\tprimary\tslow\t50000')" <<<"$res" - - j() { - jq -c --argjson o "$1" --argjson now 1000 --argjson ttl 100 --argjson hits 3 -f "$judge" <<<"$2" + ( + fillTemplate ./repo/autoproxy-slowness.template.sh { + slowSampleJq = ../../modules/proxy-suite/autoproxy-slow-sample.jq; + slowJudgeJq = ../../modules/proxy-suite/autoproxy-slow-judge.jq; } - slow='[{"d":"pximg.net","h":"i.pximg.net","exit":"direct","slow":true,"peak":50000}]' - onExitSlow='[{"d":"pximg.net","h":"i.pximg.net","exit":"primary","slow":true,"peak":1}]' - onExitFast='[{"d":"pximg.net","h":"i.pximg.net","exit":"primary","slow":false,"peak":900000}]' - s='{"domains":{},"hosts":{"x.twimg.com":{"verdict":"censor"}},"exits":{},"backlog":{}}' - - # Three crawls within a day make the domain owed an exit; two do not. - s="$(j "$slow" "$s")"; s="$(j "$slow" "$s")" - jq -e '.slowWant == {}' <<<"$s" > /dev/null - s="$(j "$slow" "$s")" - jq -e '.slowWant["pximg.net"] == {host: "i.pximg.net", tried: []}' <<<"$s" > /dev/null - - # Left to zapret: never moved, however slow. - z='[{"d":"twimg.com","h":"x.twimg.com","exit":"direct","slow":true,"peak":1}]' - t="$(j "$z" "$s")"; t="$(j "$z" "$t")"; t="$(j "$z" "$t")" - jq -e '.slowWant["twimg.com"] == null' <<<"$t" > /dev/null - - # Once routed -- the prober picks the exit -- judged on that exit alone. - r='{"domains":{"pximg.net":{"verdict":"slow","exit":"primary","host":"i.pximg.net","at":0,"tried":["primary"]}}, - "hosts":{},"exits":{},"backlog":{}}' - # Fast there: kept, and a strike against it forgotten. - k="$(j "$onExitSlow" "$r")"; k="$(j "$onExitFast" "$k")" - jq -e '.domains["pximg.net"] | .bad == 0 and .at == 1000' <<<"$k" > /dev/null - # Crawling there too, twice: owed the next exit, the ones tried remembered. - u="$(j "$onExitSlow" "$r")"; u="$(j "$onExitSlow" "$u")" - jq -e '.domains["pximg.net"] == null and .slowWant["pximg.net"].tried == ["primary"]' <<<"$u" > /dev/null - - # Every exit failed it: left direct until slowSkip expires, however slow. - w='{"domains":{},"hosts":{},"exits":{},"backlog":{},"slowSkip":{"pximg.net":1100}}' - w="$(j "$slow" "$w")"; w="$(j "$slow" "$w")"; w="$(j "$slow" "$w")" - jq -e '.slowWant == {} and .slowSkip["pximg.net"] == 1100' <<<"$w" > /dev/null - - touch "$out" - ''; + ); # autoProxy probe order: one exit per network first, bad exits last; and the # strikes that make an exit bad. autoproxy-rounds = pkgs.runCommand "proxy-suite-autoproxy-rounds-check" { nativeBuildInputs = [ pkgs.jq ]; } - '' - echo '[{"tag":"direct"},{"tag":"a"},{"tag":"b"},{"tag":"a2"},{"tag":"b2"},{"tag":"c"}]' > index.json - echo '{"exits":{"a":{"asn":"AS1","bad":true},"b":{"asn":"AS2"},"a2":{"asn":"AS1"}, - "b2":{"asn":"AS2"},"c":{"asn":"AS3","bad":false}}}' > state.json - r="$(jq -c --slurpfile s state.json -f ${../../modules/proxy-suite/autoproxy-rounds.jq} index.json)" - printf '%s\n' "$r" - # A refused a takes neither AS1's first place (a2 does) nor any place before b2. - jq -e '. == {r1: "b,a2,c", r2: "b2,a", ordered: ["b", "a2", "b2", "c", "a"]}' <<<"$r" > /dev/null - - k() { - jq -c --argjson tags "$1" --arg d "$2" --arg why "$3" --argjson now "$4" --argjson ttl 100 \ - -f ${../../modules/proxy-suite/autoproxy-strike.jq} <<<"$5" + ( + fillTemplate ./repo/autoproxy-rounds.template.sh { + roundsJq = ../../modules/proxy-suite/autoproxy-rounds.jq; + strikeJq = ../../modules/proxy-suite/autoproxy-strike.jq; } - s='{"exits":{"a":{"asn":"AS1"},"b":{}}}' - # One destination is not enough, however often it strikes. - s="$(k '["a"]' sekai.test refused 1000 "$s")" - s="$(k '["a","b"]' sekai.test refused 1010 "$s")" - jq -e '.exits.a.bad == false and .exits.a.asn == "AS1" and .exits.b.bad == false' <<<"$s" > /dev/null - # A second one is. - s="$(k '["a"]' pximg.net slow 1020 "$s")" - jq -e '.exits.a | .bad and .badBy == ["sekai.test refused", "pximg.net slow"]' <<<"$s" > /dev/null - jq -e '.exits.b.bad == false' <<<"$s" > /dev/null - # A TTL later the older strike has expired. - s="$(k '[]' "" "" 1115 "$s")" - jq -e '.exits.a | (.bad | not) and .badBy == ["pximg.net slow"]' <<<"$s" > /dev/null - # A block page may be a passing challenge: one is not enough either. - s="$(k '["b"]' colorfulpalette.org wall:aws-waf 1120 "$s")" - jq -e '.exits.b | (.bad | not) and .badBy == ["colorfulpalette.org wall:aws-waf"]' <<<"$s" > /dev/null - s="$(k '["b"]' fandom.com wall:cloudflare 1130 "$s")" - jq -e '.exits.b | .bad and .badBy == ["colorfulpalette.org wall:aws-waf", "fandom.com wall:cloudflare"]' <<<"$s" > /dev/null - touch "$out" - ''; + ); # `proxy-ctl proxy auto forget|clear`, as the runner applies them. autoproxy-edit = - pkgs.runCommand "proxy-suite-autoproxy-edit-check" { nativeBuildInputs = [ pkgs.jq ]; } - '' - edit() { jq -c --arg op "$1" --arg d "$2" -f ${../../modules/proxy-suite/autoproxy-edit.jq} <<<"$3"; } - s='{ - "domains": {"last.fm": {"exit": "a", "host": "www.last.fm"}, "pximg.net": {"exit": "b", "host": "i.pximg.net"}}, - "hosts": {"www.last.fm": {"domain": "last.fm"}, "cdn.last.fm": {"domain": "last.fm"}, "i.pximg.net": {"domain": "pximg.net"}}, - "backlog": {"api.last.fm": {"domain": "last.fm", "hits": 3}, "x.test": {"domain": "x.test", "hits": 1}}, - "slowWant": {"last.fm": 1}, "slowSkip": {"pximg.net": 1}, - "exits": { - "a": {"asn": "AS1", "strikes": {"last.fm": {"why": "refused", "at": 1}, "sekai.test": {"why": "slow", "at": 2}}, "bad": true, - "badBy": ["last.fm refused", "sekai.test slow"]}, - "b": {"asn": "AS2"} - }, - "egress": "203.0.113.1", "lastRun": 5 - }' - - # Forget: every trace of the one domain, and a strike it made no longer counts. - f="$(edit forget last.fm "$s")" - jq -e '(.domains | keys) == ["pximg.net"]' <<<"$f" > /dev/null - jq -e '(.hosts | keys) == ["i.pximg.net"] and (.backlog | keys) == ["x.test"]' <<<"$f" > /dev/null - jq -e '.slowWant == {} and .slowSkip == {"pximg.net": 1}' <<<"$f" > /dev/null - jq -e '.exits.a | .asn == "AS1" and (.bad | not) and .badBy == ["sekai.test slow"]' <<<"$f" > /dev/null - jq -e '.exits.b == {"asn": "AS2"}' <<<"$f" > /dev/null - # A domain it never knew changes nothing. - jq -e --argjson s "$s" '. == $s' <<<"$(edit forget nope.test "$s")" > /dev/null - - # Clear: every route and verdict; the exits, backlog and egress stay. - c="$(edit clear "" "$s")" - jq -e '.domains == {} and .hosts == {} and (has("slowWant") | not) and (has("slowSkip") | not)' <<<"$c" > /dev/null - jq -e '.exits.a | .asn == "AS1" and .strikes == {} and (.bad | not) and .badBy == []' <<<"$c" > /dev/null - jq -e '(.backlog | keys) == ["api.last.fm", "x.test"] and .egress == "203.0.113.1" and .lastRun == 5' <<<"$c" > /dev/null - touch "$out" - ''; + pkgs.runCommand "proxy-suite-autoproxy-edit-check" + { + nativeBuildInputs = [ pkgs.jq ]; + } + ( + fillTemplate ./repo/autoproxy-edit.template.sh { + editJq = ../../modules/proxy-suite/autoproxy-edit.jq; + } + ); # A probe that exits 0 printing nothing: jq reads "" as no input at all, so the # "error" guard downstream saw "" instead of "error" and let it through to @@ -781,7 +391,7 @@ in ]; } '' - sed -n '/^ probe_json() {$/,/^ }$/p' ${../../modules/proxy-suite/autoproxy.nix} > helper.sh + sed -n '/^probe_json() {$/,/^}$/p' ${../../modules/proxy-suite/autoproxy-run.template.sh} > helper.sh test -s helper.sh mkdir -p stub @@ -808,50 +418,11 @@ in { nativeBuildInputs = [ pkgs.jq ]; } - '' - add=${../../modules/proxy-suite/inbound-stats-add.jq} - now=1789135690 # 2026-09-11 - a() { jq -c --argjson q "$1" --argjson online "''${3:-{\}}" --argjson awg "''${4:-[]}" --arg day 2026-09-11 --argjson now "$now" -f "$add" <<<"$2"; } - - # XRay gives values as strings and leaves a zero counter without one. - r='{"stat":[{"name":"user>>>fufsob>>>traffic>>>downlink","value":"3000000"}, - {"name":"user>>>fufsob>>>traffic>>>uplink","value":"2000"}, - {"name":"user>>>phone>>>traffic>>>uplink"}, - {"name":"inbound>>>vless-in>>>traffic>>>downlink","value":5}, - {"name":"outbound>>>direct>>>traffic>>>uplink","value":6}]}' - s="$(a "$r" '{}')" - s="$(a "$r" "$s")" - jq -e '.days["2026-09-11"] | .user.fufsob == {down: 6000000, up: 4000} - and .user.phone.up == 0 and .inbound["vless-in"].down == 10 and .outbound.direct.up == 12' <<<"$s" > /dev/null - jq -e '.at == 1789135690' <<<"$s" > /dev/null - # Nothing counted since the last reading: nothing changes. - jq -e --argjson s "$s" '.days == $s.days' <<<"$(a '{}' "$s")" > /dev/null - # An online user's last seen time is kept, and never goes back. - o='{"users":[{"email":"phone","ips":[{"ip":"203.0.113.7","lastSeen":1789135000},{"ip":"203.0.113.8","lastSeen":1789135600}]}]}' - s="$(a '{}' "$s" "$o")" - jq -e '.seen.phone == 1789135600' <<<"$s" > /dev/null - s="$(a '{}' "$s" '{"users":[{"email":"phone","ips":[{"ip":"203.0.113.7","lastSeen":1}]}]}')" - jq -e '.seen.phone == 1789135600' <<<"$s" > /dev/null - # Days more than a year old are let go. - old="$(jq -c '.days["2024-01-01"] = {user: {fufsob: {up: 1}}}' <<<"$s")" - jq -e '.days["2024-01-01"] == null' <<<"$(a '{}' "$old")" > /dev/null - - # AmneziaWG peers come with raw interface counters, of which only the growth is added. - p() { echo '[{"interface":"awgi-home","key":"K","tag":"home","user":"tablet","rx":'"$1"',"tx":'"$2"',"handshake":'"$3"',"endpoint":"203.0.113.9:4000"}]'; } - s="$(a '{}' "$s" '{}' "$(p 1000 5000 1789135500)")" - jq -e '.days["2026-09-11"].user.tablet == {up: 1000, down: 5000} and .seen.tablet == 1789135500 - and .awgPeers.tablet == {tag: "home", handshake: 1789135500, endpoint: "203.0.113.9:4000"}' <<<"$s" > /dev/null - s="$(a '{}' "$s" '{}' "$(p 1500 5200 1789135600)")" - jq -e '.days["2026-09-11"].user.tablet == {up: 1500, down: 5200} and .seen.tablet == 1789135600' <<<"$s" > /dev/null - # A counter below the last one restarted with its interface. - s="$(a '{}' "$s" '{}' "$(p 100 100 0)")" - jq -e '.days["2026-09-11"].user.tablet == {up: 1600, down: 5300} and .seen.tablet == 1789135600 - and .awgPeers == {}' <<<"$s" > /dev/null - # A peer gone from the listeners leaves no counters behind. - jq -e '.awgCounters == {}' <<<"$(a '{}' "$s")" > /dev/null - - touch "$out" - ''; + ( + fillTemplate ./repo/inbound-stats.template.sh { + statsAddJq = ../../modules/proxy-suite/inbound-stats-add.jq; + } + ); # Proxy chains, resolved at start once subscription entries exist. outbound-detours = @@ -859,33 +430,11 @@ in { nativeBuildInputs = [ pkgs.jq ]; } - '' - f=${../../modules/proxy-suite/outbound-detours.jq} - d() { jq -c -f "$f" --argjson d "$1" --argjson sources "$2" --arg kind "$3" <<<"$4"; } - - # sing-box: a declared outbound and every entry of a subscription. - r="$(d '{"outbounds":{"de":"ru"},"subscriptions":{"s":"warp"}}' '{"ru":"static","de":"static","s-a":"sub:s","warp":"warp"}' sing-box \ - '{"outbounds":[{"tag":"ru"},{"tag":"de"},{"tag":"s-a"},{"tag":"warp"}],"xray":[]}')" - jq -e '.errors == [] and ([.outbounds[] | .detour] == [null, "ru", "warp", null])' <<<"$r" > /dev/null - # XRay: dialerProxy, next to what sockopt already had. - r="$(d '{"outbounds":{"de":"ru"},"subscriptions":{}}' '{"ru":"static","de":"static"}' xray \ - '{"outbounds":[{"tag":"ru"},{"tag":"de","streamSettings":{"sockopt":{"mark":1}}}],"xray":[]}')" - jq -e '.outbounds[1].streamSettings.sockopt == {mark: 1, dialerProxy: "ru"}' <<<"$r" > /dev/null - # Hybrid: sidecar outbounds chain in the sidecar, sing-box ones through anything. - r="$(d '{"outbounds":{"x1":"x2","sb":"x1"},"subscriptions":{}}' '{"x1":"static","x2":"static","sb":"static"}' hybrid \ - '{"outbounds":[{"tag":"x1"},{"tag":"x2"},{"tag":"sb"}],"xray":[{"tag":"x1"},{"tag":"x2"}]}')" - jq -e '.errors == [] and .xray[0].streamSettings.sockopt.dialerProxy == "x2" - and .outbounds[0].detour == null and .outbounds[2].detour == "x1"' <<<"$r" > /dev/null - r="$(d '{"outbounds":{"x1":"sb"},"subscriptions":{}}' '{"x1":"static","sb":"static"}' hybrid \ - '{"outbounds":[{"tag":"x1"},{"tag":"sb"}],"xray":[{"tag":"x1"}]}')" - jq -e '[.errors[].message] == ["outbound '"'x1'"' runs on XRay and can only chain through another XRay outbound, not '"'sb'"'"]' <<<"$r" > /dev/null - # A missing hop and a loop are errors, and nothing is rewritten. - r="$(d '{"outbounds":{"a":"b","b":"a","c":"gone"},"subscriptions":{}}' '{"a":"static","b":"static","c":"static"}' sing-box \ - '{"outbounds":[{"tag":"a"},{"tag":"b"},{"tag":"c"}],"xray":[]}')" - jq -e '(.errors | length) == 3 and all(.outbounds[]; .detour == null)' <<<"$r" > /dev/null - - touch "$out" - ''; + ( + fillTemplate ./repo/outbound-detours.template.sh { + detoursJq = ../../modules/proxy-suite/outbound-detours.jq; + } + ); # `proxy-ctl proxy outbounds disable` markers, as the start script reads them. outbound-disabled = @@ -915,63 +464,11 @@ in }; }; in - pkgs.runCommand "proxy-suite-outbound-disabled-check" { nativeBuildInputs = [ pkgs.jq ]; } '' - mkdir obd - export RUNTIME_DIR="$PWD" OUTBOUND_SOURCES_JSON='{}' - # No group here: `g` names members that are not running, so it blocks, with a warning. - export OUTBOUNDS_JSON='[{"tag":"x"}]' - ${grouped} 2> err - grep -q "group 'g': member 'b' is not available" err - grep -q "group 'g' has no available member" err - jq -e '.top == ["x", "g"] and .groups.g.members == ["block"]' outbounds.json > /dev/null - - # With its members: they leave the top level, the group takes their place and order. - export OUTBOUNDS_JSON='[{"tag":"x"},{"tag":"a"},{"tag":"b"}]' - ${grouped} - jq -e '.top == ["x", "g"] and .groups.g.members == ["b", "a"] and .groups.g.strategy == "failover"' outbounds.json > /dev/null - # A group pin, a runtime group, and a runtime priority putting it first. - mkdir group-pins - echo a > group-pins/g - echo '{"outbounds": ["x"], "strategy": "urltest"}' > obd/h.group - echo '{"h": 1}' > obd/priority.json - _proxy_suite_read_source() { cat -- "$1"; } - export -f _proxy_suite_read_source - ${grouped} - jq -e '.top == ["h", "g"] and .groups.g.pinned == "a" and .groups.h.runtime and .priority.h == 1' outbounds.json > /dev/null - # The spool is group-writable: a runtime group inside itself, one that is not a group, and - # one taking a reserved name are left out, and the start goes on without them. - echo '{"outbounds": ["h3"]}' > obd/h2.group - echo '{"outbounds": ["h2"]}' > obd/h3.group - echo '{"outbounds": ["x"], "interval": {"s": 1}}' > obd/h4.group - echo '{"outbounds": ["x"]}' > obd/proxy.group - ${grouped} 2> err - grep -q "ignoring runtime group 'h2': it contains itself" err - grep -q "ignoring runtime group 'h3': it contains itself" err - grep -q "ignoring runtime group 'h4': not a valid group" err - grep -q "ignoring runtime group 'proxy': reserved or invalid name" err - jq -e '.groups | (has("h2") or has("h3") or has("h4") or has("proxy")) | not' outbounds.json > /dev/null - jq -e '.groups.h.runtime' outbounds.json > /dev/null - rm -r obd/h.group obd/h2.group obd/h3.group obd/h4.group obd/proxy.group obd/priority.json group-pins - - export OUTBOUNDS_JSON='[{"tag":"a"},{"tag":"b"},{"tag":"ex"}]' - - # A marker takes its outbound out of selection and drops a pin on it; stale markers do nothing. - touch obd/a.disabled obd/gone.disabled - echo a > pinned - ${selection} 2> err - grep -q "pinned outbound 'a' is disabled" err - jq -e '.pinned == "" and .disabled == ["a"] and .excluded == ["a", "ex"]' outbounds.json > /dev/null - - # With nothing left to select and no pin the start fails, saying how out. - touch obd/b.disabled - ! ${selection} 2> err - grep -q "outbounds enable" err - # A pin on one still enabled carries it. - echo ex > pinned - ${selection} - jq -e '.pinned == "ex" and .disabled == ["a", "b"]' outbounds.json > /dev/null - touch "$out" - ''; + pkgs.runCommand "proxy-suite-outbound-disabled-check" { nativeBuildInputs = [ pkgs.jq ]; } ( + fillTemplate ./repo/outbound-disabled.template.sh { + inherit grouped selection; + } + ); # The spool is group-writable and the backend privileged: a runtime JSON outbound naming a program # or a file to read or write is left out, and a runtime AmneziaWG port must be a port. @@ -1010,54 +507,12 @@ in pkgs.jq ]; } - '' - proxy_ctl=${../../pkgs/proxy-ctl/proxy_ctl.py} - - mkdir -p bin - cat > bin/systemctl <<'SH' - #!${pkgs.bash}/bin/bash - case "$1" in - cat) exit 0 ;; - is-active) - if [ "''${3:-''${2:-}}" = "proxy-suite-awg-home" ] || [ "''${2:-}" = "proxy-suite-awg-home" ]; then - if [ "''${2:-}" != "--quiet" ]; then - echo active - fi - exit 0 - fi - if [ "''${2:-}" != "--quiet" ]; then - echo inactive - fi - exit 3 - ;; - start|stop|restart) - printf '%s %s\n' "$1" "$2" >> "$SYSTEMCTL_LOG" - ;; - esac - SH - chmod +x bin/systemctl - - printf '%s\n' '["home","work"]' > awg-profiles.json - export PATH="$PWD/bin:$PATH" - export SYSTEMCTL_LOG="$PWD/systemctl.log" - export AWG_PROFILES_FILE="$PWD/awg-profiles.json" - - python3 "$proxy_ctl" awg list > list-output - grep -q 'home.*active' list-output - grep -q 'work.*inactive' list-output - python3 "$proxy_ctl" awg on work - python3 "$proxy_ctl" awg off home - python3 "$proxy_ctl" awg restart home - grep -q '^start proxy-suite-awg-work$' "$SYSTEMCTL_LOG" - grep -q '^stop proxy-suite-awg-home$' "$SYSTEMCTL_LOG" - grep -q '^restart proxy-suite-awg-home$' "$SYSTEMCTL_LOG" - - if python3 "$proxy_ctl" awg on missing 2> error-output; then - exit 1 - fi - grep -q 'Unknown AmneziaWG profile' error-output - touch "$out" - ''; + ( + fillTemplate ./repo/proxy-ctl-amneziawg.template.sh { + proxyCtl = ../../pkgs/proxy-ctl/proxy_ctl.py; + bash = pkgs.bash; + } + ); readme-doc-source = builtins.seq ( assert !(pkgs.lib.hasInfix "environment.systemPackages" readmeDocSource); diff --git a/nix/checks/repo/autoproxy-edit.template.sh b/nix/checks/repo/autoproxy-edit.template.sh new file mode 100644 index 0000000..13edd6c --- /dev/null +++ b/nix/checks/repo/autoproxy-edit.template.sh @@ -0,0 +1,30 @@ +edit() { jq -c --arg op "$1" --arg d "$2" -f @editJq@ <<<"$3"; } +s='{ + "domains": {"last.fm": {"exit": "a", "host": "www.last.fm"}, "pximg.net": {"exit": "b", "host": "i.pximg.net"}}, + "hosts": {"www.last.fm": {"domain": "last.fm"}, "cdn.last.fm": {"domain": "last.fm"}, "i.pximg.net": {"domain": "pximg.net"}}, + "backlog": {"api.last.fm": {"domain": "last.fm", "hits": 3}, "x.test": {"domain": "x.test", "hits": 1}}, + "slowWant": {"last.fm": 1}, "slowSkip": {"pximg.net": 1}, + "exits": { + "a": {"asn": "AS1", "strikes": {"last.fm": {"why": "refused", "at": 1}, "sekai.test": {"why": "slow", "at": 2}}, "bad": true, + "badBy": ["last.fm refused", "sekai.test slow"]}, + "b": {"asn": "AS2"} + }, + "egress": "203.0.113.1", "lastRun": 5 +}' + +# Forget: every trace of the one domain, and a strike it made no longer counts. +f="$(edit forget last.fm "$s")" +jq -e '(.domains | keys) == ["pximg.net"]' <<<"$f" > /dev/null +jq -e '(.hosts | keys) == ["i.pximg.net"] and (.backlog | keys) == ["x.test"]' <<<"$f" > /dev/null +jq -e '.slowWant == {} and .slowSkip == {"pximg.net": 1}' <<<"$f" > /dev/null +jq -e '.exits.a | .asn == "AS1" and (.bad | not) and .badBy == ["sekai.test slow"]' <<<"$f" > /dev/null +jq -e '.exits.b == {"asn": "AS2"}' <<<"$f" > /dev/null +# A domain it never knew changes nothing. +jq -e --argjson s "$s" '. == $s' <<<"$(edit forget nope.test "$s")" > /dev/null + +# Clear: every route and verdict; the exits, backlog and egress stay. +c="$(edit clear "" "$s")" +jq -e '.domains == {} and .hosts == {} and (has("slowWant") | not) and (has("slowSkip") | not)' <<<"$c" > /dev/null +jq -e '.exits.a | .asn == "AS1" and .strikes == {} and (.bad | not) and .badBy == []' <<<"$c" > /dev/null +jq -e '(.backlog | keys) == ["api.last.fm", "x.test"] and .egress == "203.0.113.1" and .lastRun == 5' <<<"$c" > /dev/null +touch "$out" diff --git a/nix/checks/repo/autoproxy-rounds.template.sh b/nix/checks/repo/autoproxy-rounds.template.sh new file mode 100644 index 0000000..b312591 --- /dev/null +++ b/nix/checks/repo/autoproxy-rounds.template.sh @@ -0,0 +1,30 @@ +echo '[{"tag":"direct"},{"tag":"a"},{"tag":"b"},{"tag":"a2"},{"tag":"b2"},{"tag":"c"}]' > index.json +echo '{"exits":{"a":{"asn":"AS1","bad":true},"b":{"asn":"AS2"},"a2":{"asn":"AS1"}, + "b2":{"asn":"AS2"},"c":{"asn":"AS3","bad":false}}}' > state.json +r="$(jq -c --slurpfile s state.json -f @roundsJq@ index.json)" +printf '%s\n' "$r" +# A refused a takes neither AS1's first place (a2 does) nor any place before b2. +jq -e '. == {r1: "b,a2,c", r2: "b2,a", ordered: ["b", "a2", "b2", "c", "a"]}' <<<"$r" > /dev/null + +k() { + jq -c --argjson tags "$1" --arg d "$2" --arg why "$3" --argjson now "$4" --argjson ttl 100 \ + -f @strikeJq@ <<<"$5" +} +s='{"exits":{"a":{"asn":"AS1"},"b":{}}}' +# One destination is not enough, however often it strikes. +s="$(k '["a"]' sekai.test refused 1000 "$s")" +s="$(k '["a","b"]' sekai.test refused 1010 "$s")" +jq -e '.exits.a.bad == false and .exits.a.asn == "AS1" and .exits.b.bad == false' <<<"$s" > /dev/null +# A second one is. +s="$(k '["a"]' pximg.net slow 1020 "$s")" +jq -e '.exits.a | .bad and .badBy == ["sekai.test refused", "pximg.net slow"]' <<<"$s" > /dev/null +jq -e '.exits.b.bad == false' <<<"$s" > /dev/null +# A TTL later the older strike has expired. +s="$(k '[]' "" "" 1115 "$s")" +jq -e '.exits.a | (.bad | not) and .badBy == ["pximg.net slow"]' <<<"$s" > /dev/null +# A block page may be a passing challenge: one is not enough either. +s="$(k '["b"]' colorfulpalette.org wall:aws-waf 1120 "$s")" +jq -e '.exits.b | (.bad | not) and .badBy == ["colorfulpalette.org wall:aws-waf"]' <<<"$s" > /dev/null +s="$(k '["b"]' fandom.com wall:cloudflare 1130 "$s")" +jq -e '.exits.b | .bad and .badBy == ["colorfulpalette.org wall:aws-waf", "fandom.com wall:cloudflare"]' <<<"$s" > /dev/null +touch "$out" diff --git a/nix/checks/repo/autoproxy-slowness.template.sh b/nix/checks/repo/autoproxy-slowness.template.sh new file mode 100644 index 0000000..df3986d --- /dev/null +++ b/nix/checks/repo/autoproxy-slowness.template.sh @@ -0,0 +1,54 @@ +sample=@slowSampleJq@ +judge=@slowJudgeJq@ + +# A steady crawl, a burst, probe and outbound-test traffic, and a tiny flow. +res="$(jq -n -c '[range(0; 11) as $t | {connections: [ + {id: "a", metadata: {host: "i.pximg.net", type: "mixed/mixed-in"}, chains: ["direct"], download: ($t * 50000)}, + {id: "b", metadata: {host: "audio.example", type: "mixed/mixed-in"}, chains: ["direct"], download: (if $t >= 5 then 2000000 else 0 end)}, + {id: "c", metadata: {host: "probe.example", type: "mixed/probe-in-0"}, chains: ["direct"], download: ($t * 50000)}, + {id: "d", metadata: {host: "tiny.example", type: "mixed/mixed-in"}, chains: ["direct"], download: ($t * 1000)}, + {id: "e", metadata: {host: "far.example", type: "mixed/mixed-in"}, chains: ["primary", "proxy"], download: ($t * 50000)}, + {id: "f", metadata: {host: "speed.example", type: "mixed/proxy-suite-test-in"}, chains: ["primary", "proxy-suite-test"], download: ($t * 50000)} + ]}][]' | jq -s -r --argjson min 307200 --argjson below 153600 -f "$sample")" +printf '%s\n' "$res" +test "$(wc -l <<<"$res")" = 3 +grep -qx "$(printf 'i.pximg.net\tdirect\tslow\t50000')" <<<"$res" +grep -qx "$(printf 'audio.example\tdirect\tfast\t2000000')" <<<"$res" +# chains[0] is the exit that carried it, not the selector. +grep -qx "$(printf 'far.example\tprimary\tslow\t50000')" <<<"$res" + +j() { + jq -c --argjson o "$1" --argjson now 1000 --argjson ttl 100 --argjson hits 3 -f "$judge" <<<"$2" +} +slow='[{"d":"pximg.net","h":"i.pximg.net","exit":"direct","slow":true,"peak":50000}]' +onExitSlow='[{"d":"pximg.net","h":"i.pximg.net","exit":"primary","slow":true,"peak":1}]' +onExitFast='[{"d":"pximg.net","h":"i.pximg.net","exit":"primary","slow":false,"peak":900000}]' +s='{"domains":{},"hosts":{"x.twimg.com":{"verdict":"censor"}},"exits":{},"backlog":{}}' + +# Three crawls within a day make the domain owed an exit; two do not. +s="$(j "$slow" "$s")"; s="$(j "$slow" "$s")" +jq -e '.slowWant == {}' <<<"$s" > /dev/null +s="$(j "$slow" "$s")" +jq -e '.slowWant["pximg.net"] == {host: "i.pximg.net", tried: []}' <<<"$s" > /dev/null + +# Left to zapret: never moved, however slow. +z='[{"d":"twimg.com","h":"x.twimg.com","exit":"direct","slow":true,"peak":1}]' +t="$(j "$z" "$s")"; t="$(j "$z" "$t")"; t="$(j "$z" "$t")" +jq -e '.slowWant["twimg.com"] == null' <<<"$t" > /dev/null + +# Once routed -- the prober picks the exit -- judged on that exit alone. +r='{"domains":{"pximg.net":{"verdict":"slow","exit":"primary","host":"i.pximg.net","at":0,"tried":["primary"]}}, + "hosts":{},"exits":{},"backlog":{}}' +# Fast there: kept, and a strike against it forgotten. +k="$(j "$onExitSlow" "$r")"; k="$(j "$onExitFast" "$k")" +jq -e '.domains["pximg.net"] | .bad == 0 and .at == 1000' <<<"$k" > /dev/null +# Crawling there too, twice: owed the next exit, the ones tried remembered. +u="$(j "$onExitSlow" "$r")"; u="$(j "$onExitSlow" "$u")" +jq -e '.domains["pximg.net"] == null and .slowWant["pximg.net"].tried == ["primary"]' <<<"$u" > /dev/null + +# Every exit failed it: left direct until slowSkip expires, however slow. +w='{"domains":{},"hosts":{},"exits":{},"backlog":{},"slowSkip":{"pximg.net":1100}}' +w="$(j "$slow" "$w")"; w="$(j "$slow" "$w")"; w="$(j "$slow" "$w")" +jq -e '.slowWant == {} and .slowSkip["pximg.net"] == 1100' <<<"$w" > /dev/null + +touch "$out" diff --git a/nix/checks/repo/inbound-stats.template.sh b/nix/checks/repo/inbound-stats.template.sh new file mode 100644 index 0000000..7a3d38d --- /dev/null +++ b/nix/checks/repo/inbound-stats.template.sh @@ -0,0 +1,42 @@ +add=@statsAddJq@ +now=1789135690 # 2026-09-11 +a() { jq -c --argjson q "$1" --argjson online "${3:-{\}}" --argjson awg "${4:-[]}" --arg day 2026-09-11 --argjson now "$now" -f "$add" <<<"$2"; } + +# XRay gives values as strings and leaves a zero counter without one. +r='{"stat":[{"name":"user>>>fufsob>>>traffic>>>downlink","value":"3000000"}, + {"name":"user>>>fufsob>>>traffic>>>uplink","value":"2000"}, + {"name":"user>>>phone>>>traffic>>>uplink"}, + {"name":"inbound>>>vless-in>>>traffic>>>downlink","value":5}, + {"name":"outbound>>>direct>>>traffic>>>uplink","value":6}]}' +s="$(a "$r" '{}')" +s="$(a "$r" "$s")" +jq -e '.days["2026-09-11"] | .user.fufsob == {down: 6000000, up: 4000} + and .user.phone.up == 0 and .inbound["vless-in"].down == 10 and .outbound.direct.up == 12' <<<"$s" > /dev/null +jq -e '.at == 1789135690' <<<"$s" > /dev/null +# Nothing counted since the last reading: nothing changes. +jq -e --argjson s "$s" '.days == $s.days' <<<"$(a '{}' "$s")" > /dev/null +# An online user's last seen time is kept, and never goes back. +o='{"users":[{"email":"phone","ips":[{"ip":"203.0.113.7","lastSeen":1789135000},{"ip":"203.0.113.8","lastSeen":1789135600}]}]}' +s="$(a '{}' "$s" "$o")" +jq -e '.seen.phone == 1789135600' <<<"$s" > /dev/null +s="$(a '{}' "$s" '{"users":[{"email":"phone","ips":[{"ip":"203.0.113.7","lastSeen":1}]}]}')" +jq -e '.seen.phone == 1789135600' <<<"$s" > /dev/null +# Days more than a year old are let go. +old="$(jq -c '.days["2024-01-01"] = {user: {fufsob: {up: 1}}}' <<<"$s")" +jq -e '.days["2024-01-01"] == null' <<<"$(a '{}' "$old")" > /dev/null + +# AmneziaWG peers come with raw interface counters, of which only the growth is added. +p() { echo '[{"interface":"awgi-home","key":"K","tag":"home","user":"tablet","rx":'"$1"',"tx":'"$2"',"handshake":'"$3"',"endpoint":"203.0.113.9:4000"}]'; } +s="$(a '{}' "$s" '{}' "$(p 1000 5000 1789135500)")" +jq -e '.days["2026-09-11"].user.tablet == {up: 1000, down: 5000} and .seen.tablet == 1789135500 + and .awgPeers.tablet == {tag: "home", handshake: 1789135500, endpoint: "203.0.113.9:4000"}' <<<"$s" > /dev/null +s="$(a '{}' "$s" '{}' "$(p 1500 5200 1789135600)")" +jq -e '.days["2026-09-11"].user.tablet == {up: 1500, down: 5200} and .seen.tablet == 1789135600' <<<"$s" > /dev/null +# A counter below the last one restarted with its interface. +s="$(a '{}' "$s" '{}' "$(p 100 100 0)")" +jq -e '.days["2026-09-11"].user.tablet == {up: 1600, down: 5300} and .seen.tablet == 1789135600 + and .awgPeers == {}' <<<"$s" > /dev/null +# A peer gone from the listeners leaves no counters behind. +jq -e '.awgCounters == {}' <<<"$(a '{}' "$s")" > /dev/null + +touch "$out" diff --git a/nix/checks/repo/outbound-detours.template.sh b/nix/checks/repo/outbound-detours.template.sh new file mode 100644 index 0000000..0e13b92 --- /dev/null +++ b/nix/checks/repo/outbound-detours.template.sh @@ -0,0 +1,25 @@ +f=@detoursJq@ +d() { jq -c -f "$f" --argjson d "$1" --argjson sources "$2" --arg kind "$3" <<<"$4"; } + +# sing-box: a declared outbound and every entry of a subscription. +r="$(d '{"outbounds":{"de":"ru"},"subscriptions":{"s":"warp"}}' '{"ru":"static","de":"static","s-a":"sub:s","warp":"warp"}' sing-box \ + '{"outbounds":[{"tag":"ru"},{"tag":"de"},{"tag":"s-a"},{"tag":"warp"}],"xray":[]}')" +jq -e '.errors == [] and ([.outbounds[] | .detour] == [null, "ru", "warp", null])' <<<"$r" > /dev/null +# XRay: dialerProxy, next to what sockopt already had. +r="$(d '{"outbounds":{"de":"ru"},"subscriptions":{}}' '{"ru":"static","de":"static"}' xray \ + '{"outbounds":[{"tag":"ru"},{"tag":"de","streamSettings":{"sockopt":{"mark":1}}}],"xray":[]}')" +jq -e '.outbounds[1].streamSettings.sockopt == {mark: 1, dialerProxy: "ru"}' <<<"$r" > /dev/null +# Hybrid: sidecar outbounds chain in the sidecar, sing-box ones through anything. +r="$(d '{"outbounds":{"x1":"x2","sb":"x1"},"subscriptions":{}}' '{"x1":"static","x2":"static","sb":"static"}' hybrid \ + '{"outbounds":[{"tag":"x1"},{"tag":"x2"},{"tag":"sb"}],"xray":[{"tag":"x1"},{"tag":"x2"}]}')" +jq -e '.errors == [] and .xray[0].streamSettings.sockopt.dialerProxy == "x2" + and .outbounds[0].detour == null and .outbounds[2].detour == "x1"' <<<"$r" > /dev/null +r="$(d '{"outbounds":{"x1":"sb"},"subscriptions":{}}' '{"x1":"static","sb":"static"}' hybrid \ + '{"outbounds":[{"tag":"x1"},{"tag":"sb"}],"xray":[{"tag":"x1"}]}')" +jq -e '[.errors[].message] == ["outbound '"'x1'"' runs on XRay and can only chain through another XRay outbound, not '"'sb'"'"]' <<<"$r" > /dev/null +# A missing hop and a loop are errors, and nothing is rewritten. +r="$(d '{"outbounds":{"a":"b","b":"a","c":"gone"},"subscriptions":{}}' '{"a":"static","b":"static","c":"static"}' sing-box \ + '{"outbounds":[{"tag":"a"},{"tag":"b"},{"tag":"c"}],"xray":[]}')" +jq -e '(.errors | length) == 3 and all(.outbounds[]; .detour == null)' <<<"$r" > /dev/null + +touch "$out" diff --git a/nix/checks/repo/outbound-disabled.template.sh b/nix/checks/repo/outbound-disabled.template.sh new file mode 100644 index 0000000..123802d --- /dev/null +++ b/nix/checks/repo/outbound-disabled.template.sh @@ -0,0 +1,55 @@ +mkdir obd +export RUNTIME_DIR="$PWD" OUTBOUND_SOURCES_JSON='{}' +# No group here: `g` names members that are not running, so it blocks, with a warning. +export OUTBOUNDS_JSON='[{"tag":"x"}]' +@grouped@ 2> err +grep -q "group 'g': member 'b' is not available" err +grep -q "group 'g' has no available member" err +jq -e '.top == ["x", "g"] and .groups.g.members == ["block"]' outbounds.json > /dev/null + +# With its members: they leave the top level, the group takes their place and order. +export OUTBOUNDS_JSON='[{"tag":"x"},{"tag":"a"},{"tag":"b"}]' +@grouped@ +jq -e '.top == ["x", "g"] and .groups.g.members == ["b", "a"] and .groups.g.strategy == "failover"' outbounds.json > /dev/null +# A group pin, a runtime group, and a runtime priority putting it first. +mkdir group-pins +echo a > group-pins/g +echo '{"outbounds": ["x"], "strategy": "urltest"}' > obd/h.group +echo '{"h": 1}' > obd/priority.json +_proxy_suite_read_source() { cat -- "$1"; } +export -f _proxy_suite_read_source +@grouped@ +jq -e '.top == ["h", "g"] and .groups.g.pinned == "a" and .groups.h.runtime and .priority.h == 1' outbounds.json > /dev/null +# The spool is group-writable: a runtime group inside itself, one that is not a group, and +# one taking a reserved name are left out, and the start goes on without them. +echo '{"outbounds": ["h3"]}' > obd/h2.group +echo '{"outbounds": ["h2"]}' > obd/h3.group +echo '{"outbounds": ["x"], "interval": {"s": 1}}' > obd/h4.group +echo '{"outbounds": ["x"]}' > obd/proxy.group +@grouped@ 2> err +grep -q "ignoring runtime group 'h2': it contains itself" err +grep -q "ignoring runtime group 'h3': it contains itself" err +grep -q "ignoring runtime group 'h4': not a valid group" err +grep -q "ignoring runtime group 'proxy': reserved or invalid name" err +jq -e '.groups | (has("h2") or has("h3") or has("h4") or has("proxy")) | not' outbounds.json > /dev/null +jq -e '.groups.h.runtime' outbounds.json > /dev/null +rm -r obd/h.group obd/h2.group obd/h3.group obd/h4.group obd/proxy.group obd/priority.json group-pins + +export OUTBOUNDS_JSON='[{"tag":"a"},{"tag":"b"},{"tag":"ex"}]' + +# A marker takes its outbound out of selection and drops a pin on it; stale markers do nothing. +touch obd/a.disabled obd/gone.disabled +echo a > pinned +@selection@ 2> err +grep -q "pinned outbound 'a' is disabled" err +jq -e '.pinned == "" and .disabled == ["a"] and .excluded == ["a", "ex"]' outbounds.json > /dev/null + +# With nothing left to select and no pin the start fails, saying how out. +touch obd/b.disabled +! @selection@ 2> err +grep -q "outbounds enable" err +# A pin on one still enabled carries it. +echo ex > pinned +@selection@ +jq -e '.pinned == "ex" and .disabled == ["a", "b"]' outbounds.json > /dev/null +touch "$out" diff --git a/nix/checks/repo/proxy-ctl-amneziawg.template.sh b/nix/checks/repo/proxy-ctl-amneziawg.template.sh new file mode 100644 index 0000000..4fd8f03 --- /dev/null +++ b/nix/checks/repo/proxy-ctl-amneziawg.template.sh @@ -0,0 +1,46 @@ +proxy_ctl=@proxyCtl@ + +mkdir -p bin +cat > bin/systemctl <<'SH' +#!@bash@/bin/bash +case "$1" in + cat) exit 0 ;; + is-active) + if [ "${3:-${2:-}}" = "proxy-suite-awg-home" ] || [ "${2:-}" = "proxy-suite-awg-home" ]; then + if [ "${2:-}" != "--quiet" ]; then + echo active + fi + exit 0 + fi + if [ "${2:-}" != "--quiet" ]; then + echo inactive + fi + exit 3 + ;; + start|stop|restart) + printf '%s %s\n' "$1" "$2" >> "$SYSTEMCTL_LOG" + ;; +esac +SH +chmod +x bin/systemctl + +printf '%s\n' '["home","work"]' > awg-profiles.json +export PATH="$PWD/bin:$PATH" +export SYSTEMCTL_LOG="$PWD/systemctl.log" +export AWG_PROFILES_FILE="$PWD/awg-profiles.json" + +python3 "$proxy_ctl" awg list > list-output +grep -q 'home.*active' list-output +grep -q 'work.*inactive' list-output +python3 "$proxy_ctl" awg on work +python3 "$proxy_ctl" awg off home +python3 "$proxy_ctl" awg restart home +grep -q '^start proxy-suite-awg-work$' "$SYSTEMCTL_LOG" +grep -q '^stop proxy-suite-awg-home$' "$SYSTEMCTL_LOG" +grep -q '^restart proxy-suite-awg-home$' "$SYSTEMCTL_LOG" + +if python3 "$proxy_ctl" awg on missing 2> error-output; then + exit 1 +fi +grep -q 'Unknown AmneziaWG profile' error-output +touch "$out" diff --git a/nix/checks/repo/proxy-ctl-complete.template.sh b/nix/checks/repo/proxy-ctl-complete.template.sh new file mode 100644 index 0000000..52eb672 --- /dev/null +++ b/nix/checks/repo/proxy-ctl-complete.template.sh @@ -0,0 +1,67 @@ +proxy_ctl=@proxyCtl@ + +printf '%s\n' '["home","work"]' > awg.json +jq -n '[{name:"torrent",route:"direct"}]' > profiles.json +jq -n '{tags:["own-vps","community-de"],sources:{"own-vps":"proxy.outbounds"}}' > inventory.json + +run() { + env AWG_PROFILES_FILE="$PWD/awg.json" \ + PER_APP_ROUTING_PROFILES_FILE="$PWD/profiles.json" \ + OUTBOUND_INVENTORY_FILE="$PWD/inventory.json" \ + python3 "$proxy_ctl" __complete "$@" +} + +# Every group the help lists must complete, or the table has drifted. +python3 "$proxy_ctl" help | awk '/^ [a-z]/ { print $1 }' | sort -u > groups +run | cut -f1 > top +while read -r group; do + grep -qx "$group" top || { echo "help lists $group, completion does not" >&2; exit 1; } +done < groups + +# Piping into `grep -q` would race the script against SIGPIPE. +has() { + local want="$1" + shift + run "$@" | cut -f1 > words + grep -qx -- "$want" words +} + +has outbounds proxy +has all-bypass proxy mode +has exclude zapret auto +has proxy-suite-awg-work logs +has work awg on +has add awg +has rm awg +has torrent apps run +has unpin proxy +has newnym tor +has --onion inbounds link +has community-de proxy pin + +# Flags, and completion past the first of several arguments. +has --delay proxy outbounds test +has community-de proxy outbounds test own-vps +has --download proxy outbounds test own-vps --ping +has own-vps proxy auto probe example.com --via +has community-de proxy outbounds add hop https://example.com --detour +# chain takes the outbound to copy, then the hop it dials through. +has community-de proxy outbounds chain own-vps +has outbound inbounds stats --by +# Unreadable state loses the values, not the flags. +has --qr inbounds sub + +# Candidates carry a description after a tab. +run proxy pin > words +grep -qx "$(printf 'own-vps\tproxy.outbounds')" words + +# A shell completing must never die, however unreadable the state is. +run inbounds link > /dev/null +env AWG_PROFILES_FILE=/nonexistent python3 "$proxy_ctl" __complete awg on + +# Every shell's completion file at least parses. +bash -n @bashCompletion@ +@zsh@/bin/zsh -n @zshCompletion@ +HOME="$TMPDIR" @fish@/bin/fish --no-execute @fishCompletion@ + +touch "$out" diff --git a/nix/checks/repo/proxy-ctl-outbounds.template.sh b/nix/checks/repo/proxy-ctl-outbounds.template.sh new file mode 100644 index 0000000..6b24713 --- /dev/null +++ b/nix/checks/repo/proxy-ctl-outbounds.template.sh @@ -0,0 +1,138 @@ +proxy_ctl=@proxyCtl@ + +# systemd is not in the sandbox. The reload stub stands in for the start +# script, which is what actually republishes the inventory. +mkdir -p stub +{ + printf '%s\n' '#!/bin/sh' + printf '%s\n' 'if [ "$1" = start ] && [ "$2" = proxy-suite-outbound-reload.service ]; then' + printf '%s\n' ' ls "$RUNTIME_OUTBOUNDS_DIR" > "$OUTBOUND_INVENTORY_FILE.spool"' + printf '%s\n' ' jq --rawfile spool "$OUTBOUND_INVENTORY_FILE.spool" '"'"'($spool | split("\n") | map(select(endswith(".url") or endswith(".json")) | sub("\\.(url|json)$"; ""))) as $new | .tags = (.tags + $new | unique) | .sources = reduce $new[] as $t (.sources; .[$t] = "runtime")'"'"' "$OUTBOUND_INVENTORY_FILE" > "$OUTBOUND_INVENTORY_FILE.tmp"' + printf '%s\n' ' mv "$OUTBOUND_INVENTORY_FILE.tmp" "$OUTBOUND_INVENTORY_FILE"' + printf '%s\n' ' jq --rawfile spool "$OUTBOUND_INVENTORY_FILE.spool" '"'"'.disabled = ($spool | split("\n") | map(select(endswith(".disabled")) | sub("\\.disabled$"; ""))) | .excluded = (.excluded + .disabled | unique)'"'"' "$OUTBOUND_INVENTORY_FILE" > "$OUTBOUND_INVENTORY_FILE.tmp"' + printf '%s\n' ' mv "$OUTBOUND_INVENTORY_FILE.tmp" "$OUTBOUND_INVENTORY_FILE"' + printf '%s\n' 'fi' + printf '%s\n' 'exit 0' +} > stub/systemctl +printf '#!/bin/sh\nprintf %%s "$2"\n' > stub/systemd-escape +chmod +x stub/systemctl stub/systemd-escape +export PATH="$PWD/stub:$PATH" + +mkdir -p obd subd cache +printf '%s\n' '["community"]' > tags.json +jq -n '{tags:["own-vps","community-de"], + sources:{"own-vps":"static","community-de":"sub:community"}, + pinned:"community-de", selection:"urltest", + detours:{"community-de":"own-vps"}, excluded:["own-vps"]}' > inventory.json + +run() { + env \ + SUB_TAGS_FILE="$PWD/tags.json" \ + SUB_CACHE_DIR="$PWD/cache" \ + OUTBOUND_INVENTORY_FILE="$PWD/inventory.json" \ + RUNTIME_OUTBOUNDS_DIR="$PWD/obd" \ + RUNTIME_SUBS_DIR="$PWD/subd" \ + USER_CONTROL_GROUP="proxy-suite" \ + CLASH_API="http://127.0.0.1:1" \ + SELECTION="urltest" \ + @perAppRoutingOff@ python3 "$proxy_ctl" "$@" +} + +# Listing works from the inventory alone, with no Clash API answering. +run proxy outbounds > listing +grep -q 'Selection: urltest' listing +grep -q 'Pinned: community-de' listing +grep -q '\*community-de' listing +grep -q 'own-vps *static' listing +# What each one chains through, and what selection leaves alone. +grep -q 'community-de *sub:community, via own-vps$' listing +grep -q 'own-vps *static, never picked$' listing +# The old spelling still dispatches. +run outbounds | cmp - listing + +# Reserved and malformed tags are refused before anything is written. +for bad in proxy direct block "has space" "-leading"; do + if run proxy outbounds add "$bad" http://example.com:1 2>/dev/null; then + echo "accepted invalid tag: $bad" >&2 + exit 1 + fi +done +# Tags that already exist are refused too, declared or not. +! run proxy outbounds add own-vps http://example.com:1 2>/dev/null +! run proxy subs add community https://example.com/sub 2>/dev/null +# A URL with whitespace is refused. +! run proxy outbounds add ok-tag "http://example.com:1 x" 2>/dev/null +# Nothing above touched the spool. +[ -z "$(ls -A obd)" ] + +# Removing something that was never added says so. +! run proxy outbounds rm nope 2>/dev/null + +# A good add lands in the spool group-readable, not world-readable. +run proxy outbounds add spool-one http://example.com:1 | grep -q 'Added outbound: spool-one' +[ "$(cat obd/spool-one.url)" = "http://example.com:1" ] +[ "$(stat -c %a obd/spool-one.url)" = "640" ] +run proxy outbounds | grep -q 'spool-one *runtime' +# Adding it twice is refused. +! run proxy outbounds add spool-one http://example.com:1 2>/dev/null +run proxy outbounds rm spool-one | grep -q 'Removed outbound: spool-one' +[ ! -e obd/spool-one.url ] + +# --detour leaves the hop next to the entry, and only names an outbound that exists. +! run proxy outbounds add bad-hop http://example.com:1 --detour nope 2>/dev/null +[ ! -e obd/bad-hop.url ] +run proxy outbounds add chained http://example.com:1 --detour own-vps | grep -q 'Added outbound: chained' +[ "$(cat obd/chained.detour)" = own-vps ] +run proxy outbounds rm chained > /dev/null +[ ! -e obd/chained.detour ] +# A hop left behind does not chain a later entry of the same name. +echo own-vps > obd/unchained.detour +run proxy outbounds add unchained http://example.com:1 > /dev/null +[ ! -e obd/unchained.detour ] +run proxy outbounds rm unchained > /dev/null + +# JSON, as `link --json` prints it, lands as .json without its own tag; stdin too. +run proxy outbounds add from-json '{"type":"trojan","tag":"x","server":"t.test","server_port":443,"password":"p"}' \ + | grep -q 'Added outbound: from-json' +[ "$(jq -r 'has("tag"), .server' obd/from-json.json | paste -sd,)" = "false,t.test" ] +printf '%s' '{"protocol":"vless","settings":{}}' | run proxy outbounds add from-stdin - | grep -q 'Added outbound: from-stdin' +! run proxy outbounds add from-json '{"type":"trojan"}' 2>/dev/null +! run proxy outbounds add bad-json '{"server":"t.test"}' 2>/dev/null +! run proxy outbounds add bad-json '{nope' 2>/dev/null +[ ! -e obd/bad-json.json ] +run proxy outbounds rm from-json | grep -q 'Removed outbound: from-json' +[ ! -e obd/from-json.json ] + +# Without a tag one is made from the link; a tag after the link is a mix-up. +run proxy outbounds add 'vless://u@de.example.net:443#DE%201' > named +grep -q 'Tag: DE-1 (none given' named +grep -q 'Added outbound: DE-1' named +! run proxy outbounds add http://example.com:1 x 2>/dev/null +run proxy outbounds rm DE-1 > /dev/null + +# Disabling leaves a marker the start script reads; a pin refuses it until enabled. +run proxy outbounds disable own-vps | grep -q 'Disabled: own-vps' +[ -e obd/own-vps.disabled ] +run proxy outbounds | grep -q -- '-own-vps *static, disabled$' +! run proxy pin own-vps 2>/dev/null +run proxy outbounds enable own-vps | grep -q 'Enabled: own-vps' +[ ! -e obd/own-vps.disabled ] + +# Subscriptions use the same spool machinery, verified by cache file. +printf '%s\n' '[{},{}]' > cache/extra.json +run proxy subs add extra https://example.com/sub | grep -q 'Added subscription: extra (2 proxies)' +run proxy subs list > subs +grep -q 'community .* static' subs +grep -q 'extra .* runtime' subs + +# A spool entry the backend refused is reported, not silently accepted. +run proxy subs add rejected https://example.com/sub > rejected 2>&1 && exit 1 +grep -q 'did not come up' rejected + +# Pinning and unpinning go through their units. +run proxy pin community-de | grep -q 'Pinned: community-de' +run proxy unpin | grep -q 'Unpinned' +# Without a terminal and without a tag there is nothing to pick from. +! run proxy pin /dev/null + +touch "$out" diff --git a/nix/checks/repo/proxy-ctl-where.template.sh b/nix/checks/repo/proxy-ctl-where.template.sh new file mode 100644 index 0000000..6b8933d --- /dev/null +++ b/nix/checks/repo/proxy-ctl-where.template.sh @@ -0,0 +1,38 @@ +proxy_ctl=@proxyCtl@ + +mkdir -p ap zap +jq -n '{domains:{"spotify.com":{exit:"community-de",host:"open.spotify.com",at:0}}}' > ap/state.json +printf 'nyt.com\n' > zap/zapret-hosts-auto.txt +printf 'discord.com\n' > zap/zapret-hosts-user.txt +printf 'ok.ru\n' > zap/zapret-hosts-user-exclude.txt + +run() { + env AUTOPROXY_ENABLED=1 AUTOPROXY_STATE_DIR="$PWD/ap" \ + ZAPRET_AUTO_ENABLED=1 ZAPRET_STATE_DIR="$PWD/zap" \ + python3 "$proxy_ctl" where "$@" +} + +# Piping into `grep -q` would race the script against SIGPIPE. +verdict() { + run "$1" > where + grep -q -- "$2" where +} + +# Both stores key on an apex, so a subdomain has to match its parent. +verdict open.spotify.com '-> proxied via community-de' +grep -q 'autoProxy .*routed via community-de' where +# What proxy-ctl cannot see has to be said out loud. +grep -q 'sing-box config is not readable' where + +verdict discord.com '-> direct, with the zapret bypass' +verdict nyt.com '-> direct, with the zapret bypass' +# Excluded is not bypassed: it must not read as a zapret2 verdict. +verdict ok.ru '-> nothing runtime matches it' +verdict example.org '-> nothing runtime matches it' + +# A URL is accepted where a hostname is. +verdict https://open.spotify.com/track/x '^ domain *open.spotify.com$' + +! python3 "$proxy_ctl" where 2>/dev/null + +touch "$out" diff --git a/nix/checks/repo/proxy-ctl-zapret-auto.template.sh b/nix/checks/repo/proxy-ctl-zapret-auto.template.sh new file mode 100644 index 0000000..0147aa1 --- /dev/null +++ b/nix/checks/repo/proxy-ctl-zapret-auto.template.sh @@ -0,0 +1,62 @@ +proxy_ctl=@proxyCtl@ + +state="$PWD/state" +mkdir -p "$state" +printf 'blocked.example\nother.example\n' > "$state/zapret-hosts-auto.txt" +: > "$state/zapret-hosts-user.txt" +: > "$state/zapret-hosts-user-exclude.txt" + +run() { + env ZAPRET_AUTO_ENABLED=1 ZAPRET_STATE_DIR="$state" python3 "$proxy_ctl" zapret auto "$@" +} + +run list | grep -qx blocked.example + +# exclude must also blacklist, or the host is relearned. +run exclude blocked.example > /dev/null +! grep -qx blocked.example "$state/zapret-hosts-auto.txt" +grep -qx blocked.example "$state/zapret-hosts-user-exclude.txt" + +# Pinning is idempotent, so repeated runs cannot grow the list. +run add pinned.example > /dev/null +run add pinned.example > /dev/null +test "$(grep -c -x pinned.example "$state/zapret-hosts-user.txt")" = 1 + +# unpin and include undo add and exclude. +run unpin pinned.example > /dev/null +! grep -qx pinned.example "$state/zapret-hosts-user.txt" +run include blocked.example > /dev/null +! grep -qx blocked.example "$state/zapret-hosts-user-exclude.txt" +run add pinned.example > /dev/null + +# The lists stay readable by unprivileged proxy-ctl after a rewrite. +test "$(stat -c %a "$state/zapret-hosts-user.txt")" = 644 + +# Forgetting a host also drops the strategy remembered for its apex. +mkdir -p "$state/circular" +printf '# key\thost\tstrategy\tts\tmode\tsni\nrkn_tcp\tyoutube.com\t3\t1\tauto\t\nrkn_tcp\tother.example\t2\t1\tauto\t\nyt_tcp\tyoutube.com\t5\t1\tauto\t\n' > "$state/circular/state.tsv" +run forget www.youtube.com > /dev/null +! grep -q 'youtube.com' "$state/circular/state.tsv" +grep -q 'other.example' "$state/circular/state.tsv" +grep -q '^# key' "$state/circular/state.tsv" + +run clear > /dev/null +run list | grep -q 'No hostnames learned' +test ! -s "$state/circular/state.tsv" + +# The cutoff verdict names each cut-off network's way through. +mkdir -p "$state/cutoff" +printf '1789000000\n' > "$state/cutoff/ts" +printf 'AS12389\n' > "$state/cutoff/egress" +printf '24940\n14061\n' > "$state/cutoff/asn.txt" +printf '24940\t300.ya.ru\n' > "$state/cutoff/sni.txt" +cutoff=$(env ZAPRET_CUTOFF_ENABLED=1 ZAPRET_CUTOFF_DIR="$state/cutoff" python3 "$proxy_ctl" zapret cutoff) +printf '%s\n' "$cutoff" | grep -q 'from AS12389$' +printf '%s\n' "$cutoff" | grep -qx 'Cutoff: 2 network(s)' +printf '%s\n' "$cutoff" | grep -qE '^ AS24940 +300\.ya\.ru$' +printf '%s\n' "$cutoff" | grep -qE '^ AS14061 +no name - proxy fallback$' + +# Without the zapret2 engine there is nothing to inspect. +! env ZAPRET_AUTO_ENABLED=0 ZAPRET_STATE_DIR="$state" python3 "$proxy_ctl" zapret auto list + +touch "$out" diff --git a/nix/checks/xray-backend-runtime.nix b/nix/checks/xray-backend-runtime.nix index da502fd..7835702 100644 --- a/nix/checks/xray-backend-runtime.nix +++ b/nix/checks/xray-backend-runtime.nix @@ -10,6 +10,7 @@ }: let + fillTemplate = import ../../modules/proxy-suite/lib/fill-template.nix; fixtures = import ./xray-backend-runtime/fixtures.nix { inherit checkLib; inherit @@ -43,55 +44,13 @@ let ; xrayJqFilterRuntimeCheck = pkgs.runCommand "proxy-suite-xray-jq-filter-runtime-check" { nativeBuildInputs = [ pkgs.jq ]; } - '' - OBS='[{"protocol":"freedom","tag":"proxy-suite-ob-primary"}, - {"protocol":"vless","tag":"proxy-suite-ob-edge","settings":{"vnext":[{"address":"edge.example.com","port":443}]}}, - {"protocol":"trojan","tag":"proxy-suite-ob-ip","settings":{"servers":[{"address":"203.0.113.1","port":443}]}}]' - - check_runtime() { - local name="$1" - local input="$2" - local output="$TMPDIR/$name.json" - - jq \ - --slurpfile obs <(printf "%s" "$OBS") \ - --argjson auth_enabled false \ - --arg user "" \ - --arg password "" \ - --argjson route_enabled true \ - --argjson route_rules '[]' \ - --arg route_final "proxy" \ - --arg dns_final "remote" \ - --argjson clear_dns_rules false \ - --arg xray_loglevel "" \ - --arg xray_single_proxy_tag "proxy-suite-ob-primary" \ - --argjson xray_tun_dns_runtime true \ - -f ${pkgs.lib.escapeShellArg xrayBackendJqFilterFile} \ - "$input" > "$output" - - jq -e \ - ' - type == "object" - and (.dns.servers | length) >= 3 - and .dns.servers[0].tag == "fakedns" - and ([.routing.rules[] | select((.ruleTag? // "") == "dns-hijack")] | length) == 1 - and ([.routing.rules[] | select((.ruleTag? // "") == "dns-upstream-direct")] | length) == 1 - and ([.routing.rules[] | select((.ruleTag? // "") == "dns-upstream-remote")] | length) == 1 - and ([.dns.servers[] | select(.domains?)] == [.dns.servers[] | select(.tag == "local" and (has("domains") | not)) - | . + {domains: ["full:edge.example.com"], skipFallback: true}]) - and ([.outbounds[] | select(.streamSettings.sockopt.interface?)] | length) == 0 - and ([.outbounds[] | select(.protocol == "freedom" or .tag == "proxy-suite-ob-primary") | .streamSettings.sockopt.domainStrategy] | all(. == "UseIPv4v6")) - and ([.outbounds[] | select(.protocol == "dns") | .streamSettings.sockopt.domainStrategy?] | all(. == null)) - and ([.inbounds[] | select(.tag == "tun-in") | .settings | has("dns") or has("autoOutboundsInterface")] | any | not) - and ((.routing | has("balancers")) | not) - and ((has("observatory")) | not) - ' "$output" >/dev/null + ( + fillTemplate ./xray-backend-runtime/jq-filter-runtime.template.sh { + jqFilter = pkgs.lib.escapeShellArg xrayBackendJqFilterFile; + tunConfig = pkgs.lib.escapeShellArg xrayTunConfigJson; + perAppTunConfig = pkgs.lib.escapeShellArg xrayPerAppTunConfigJson; } - - check_runtime global ${pkgs.lib.escapeShellArg xrayTunConfigJson} - check_runtime per-app ${pkgs.lib.escapeShellArg xrayPerAppTunConfigJson} - touch "$out" - ''; + ); serviceShapeChecks = import ./xray-backend-runtime/service-shape.nix { inherit diff --git a/nix/checks/xray-backend-runtime/jq-filter-runtime.template.sh b/nix/checks/xray-backend-runtime/jq-filter-runtime.template.sh new file mode 100644 index 0000000..6b41cc6 --- /dev/null +++ b/nix/checks/xray-backend-runtime/jq-filter-runtime.template.sh @@ -0,0 +1,47 @@ +OBS='[{"protocol":"freedom","tag":"proxy-suite-ob-primary"}, + {"protocol":"vless","tag":"proxy-suite-ob-edge","settings":{"vnext":[{"address":"edge.example.com","port":443}]}}, + {"protocol":"trojan","tag":"proxy-suite-ob-ip","settings":{"servers":[{"address":"203.0.113.1","port":443}]}}]' + +check_runtime() { + local name="$1" + local input="$2" + local output="$TMPDIR/$name.json" + + jq \ + --slurpfile obs <(printf "%s" "$OBS") \ + --argjson auth_enabled false \ + --arg user "" \ + --arg password "" \ + --argjson route_enabled true \ + --argjson route_rules '[]' \ + --arg route_final "proxy" \ + --arg dns_final "remote" \ + --argjson clear_dns_rules false \ + --arg xray_loglevel "" \ + --arg xray_single_proxy_tag "proxy-suite-ob-primary" \ + --argjson xray_tun_dns_runtime true \ + -f @jqFilter@ \ + "$input" > "$output" + + jq -e \ + ' + type == "object" + and (.dns.servers | length) >= 3 + and .dns.servers[0].tag == "fakedns" + and ([.routing.rules[] | select((.ruleTag? // "") == "dns-hijack")] | length) == 1 + and ([.routing.rules[] | select((.ruleTag? // "") == "dns-upstream-direct")] | length) == 1 + and ([.routing.rules[] | select((.ruleTag? // "") == "dns-upstream-remote")] | length) == 1 + and ([.dns.servers[] | select(.domains?)] == [.dns.servers[] | select(.tag == "local" and (has("domains") | not)) + | . + {domains: ["full:edge.example.com"], skipFallback: true}]) + and ([.outbounds[] | select(.streamSettings.sockopt.interface?)] | length) == 0 + and ([.outbounds[] | select(.protocol == "freedom" or .tag == "proxy-suite-ob-primary") | .streamSettings.sockopt.domainStrategy] | all(. == "UseIPv4v6")) + and ([.outbounds[] | select(.protocol == "dns") | .streamSettings.sockopt.domainStrategy?] | all(. == null)) + and ([.inbounds[] | select(.tag == "tun-in") | .settings | has("dns") or has("autoOutboundsInterface")] | any | not) + and ((.routing | has("balancers")) | not) + and ((has("observatory")) | not) + ' "$output" >/dev/null +} + +check_runtime global @tunConfig@ +check_runtime per-app @perAppTunConfig@ +touch "$out" diff --git a/nix/options-doc/compact-fields.py b/nix/options-doc/compact-fields.py new file mode 100644 index 0000000..c0d8c6c --- /dev/null +++ b/nix/options-doc/compact-fields.py @@ -0,0 +1,75 @@ +import re +import sys +from pathlib import Path + +FIELD = re.compile(r"^\*(Type|Default|Example):\*$") +FENCE = re.compile(r"^`{3,}") + +path = Path(sys.argv[1]) +lines = path.read_text().split("\n") +out = [] +option_type = None +para = [] +i = 0 + + +def flush(): + # Hard line breaks, not a list: a list would merge with one that ends the + # description. + if para: + if out[-1] != "": + out.append("") + out.append("\\\n".join(para)) + para.clear() + + +def flat(code): + # `[ "a" "b" ]` and `{ a = 1; }` read fine on one line; multi-line strings do not. + if any("'" * 2 in line or "`" in line for line in code): + return None + text = " ".join(line.strip() for line in code) + return text if len(text) <= 72 else None + + +while i < len(lines): + match = FIELD.match(lines[i]) + if not match: + out.append(lines[i]) + i += 1 + continue + name = match.group(1) + i += 1 + if lines[i] == "" and FENCE.match(lines[i + 1]): + fence = FENCE.match(lines[i + 1]).group(0) + end = lines.index(fence, i + 2) + code, text = lines[i + 2 : end], None + i = end + 1 + else: + end = lines.index("", i) + code, text = None, " ".join(lines[i:end]) + i = end + + if name == "Type": + option_type = text + # mkEnableOption's example says nothing. + if not (name == "Example" and option_type == "boolean" and code == ["true"]): + label = f"**{name}:**" + if code is None: + para.append(f"{label} {text}") + elif flat(code) is not None: + para.append(f"{label} `{flat(code)}`") + else: + para.append(label) + flush() + out.extend(["", f"{fence}nix", *code, fence]) + + # Keep the fields of one option together. + after = i + while after < len(lines) and lines[after] == "": + after += 1 + if after < len(lines) and FIELD.match(lines[after]): + i = after + else: + flush() + +path.write_text("\n".join(out)) diff --git a/nix/options-doc/render-options-markdown.nix b/nix/options-doc/render-options-markdown.nix index 62462ae..ebe7d87 100644 --- a/nix/options-doc/render-options-markdown.nix +++ b/nix/options-doc/render-options-markdown.nix @@ -6,85 +6,10 @@ }: let + fillTemplate = import ../../modules/proxy-suite/lib/fill-template.nix; # Type, Default and Example as one short paragraph per option instead of three # headed blocks each; short values inline, the rest as code after it. - compactFields = pkgs.writeText "compact-fields.py" '' - import re - import sys - from pathlib import Path - - FIELD = re.compile(r"^\*(Type|Default|Example):\*$") - FENCE = re.compile(r"^`{3,}") - - path = Path(sys.argv[1]) - lines = path.read_text().split("\n") - out = [] - option_type = None - para = [] - i = 0 - - - def flush(): - # Hard line breaks, not a list: a list would merge with one that ends the - # description. - if para: - if out[-1] != "": - out.append("") - out.append("\\\n".join(para)) - para.clear() - - - def flat(code): - # `[ "a" "b" ]` and `{ a = 1; }` read fine on one line; multi-line strings do not. - if any("'" * 2 in line or "`" in line for line in code): - return None - text = " ".join(line.strip() for line in code) - return text if len(text) <= 72 else None - - - while i < len(lines): - match = FIELD.match(lines[i]) - if not match: - out.append(lines[i]) - i += 1 - continue - name = match.group(1) - i += 1 - if lines[i] == "" and FENCE.match(lines[i + 1]): - fence = FENCE.match(lines[i + 1]).group(0) - end = lines.index(fence, i + 2) - code, text = lines[i + 2 : end], None - i = end + 1 - else: - end = lines.index("", i) - code, text = None, " ".join(lines[i:end]) - i = end - - if name == "Type": - option_type = text - # mkEnableOption's example says nothing. - if not (name == "Example" and option_type == "boolean" and code == ["true"]): - label = f"**{name}:**" - if code is None: - para.append(f"{label} {text}") - elif flat(code) is not None: - para.append(f"{label} `{flat(code)}`") - else: - para.append(label) - flush() - out.extend(["", f"{fence}nix", *code, fence]) - - # Keep the fields of one option together. - after = i - while after < len(lines) and lines[after] == "": - after += 1 - if after < len(lines) and FIELD.match(lines[after]): - i = after - else: - flush() - - path.write_text("\n".join(out)) - ''; + compactFields = pkgs.writeText "compact-fields.py" (builtins.readFile ./compact-fields.py); summaryTsv = pkgs.writeText "group-summaries.tsv" ( pkgs.lib.concatMapStrings (group: "${group.name}\t${group.summary}\n") groupSummaries @@ -92,158 +17,10 @@ let in # One file per top-level option group, plus an index. The single 6k-line page was # not navigable. -pkgs.runCommand "proxy-suite-options-doc" { nativeBuildInputs = [ pkgs.python3 ]; } '' - mkdir -p "$out" "$TMPDIR/bodies" - all="$TMPDIR/all.md" - index_tsv="$TMPDIR/sections-index.tsv" - - cat ${optionDocs.optionsCommonMark} >"$all" - python ${compactFields} "$all" - - summary() { awk -F '\t' -v want="$1" '$1 == want { print $2 }' ${summaryTsv}; } - - # Anchor every section and file it under its top-level group. Options directly - # under services.proxy-suite (only `enable`) stay on the index. - : >"$index_tsv" - awk -v outdir="$TMPDIR/bodies" -v index_tsv="$index_tsv" ' - function slugify(text, slug) { - slug = text - gsub(/\\/, "", slug) - slug = tolower(slug) - gsub(/[^a-z0-9]+/, "-", slug) - sub(/^-+/, "", slug) - sub(/-+$/, "", slug) - return slug - } - - /^## / { - title = substr($0, 4) - normalized = title - gsub(/\\/, "", normalized) - count = split(normalized, parts, /\./) - group = (count <= 3) ? "index" : parts[3] - slug = slugify(title) - current = outdir "/" group ".md" - - print title "\t" slug "\t" group >> index_tsv - print "" >> current - print $0 >> current - next - } - - { if (current != "") print >> current } - ' "$all" - - groups="$(cut -f3 "$index_tsv" | grep -v '^index$' | awk '!seen[$0]++')" - - # Per-group table of contents, nested by option path. - mkToc() { - awk -F '\t' -v want="$1" ' - function indent(depth, i, prefix) { - prefix = "" - for (i = 0; i < depth; i++) { - prefix = prefix " " - } - return prefix - } - - function displayLabel(label) { - if (label == "*") { - return "item" - } - if (label ~ /^<.*>$/) { - return "`" label "`" - } - return label - } - - function addChild(parent, child, key) { - key = parent SUBSEP child - if (!(key in seenChild)) { - seenChild[key] = 1 - childCount[parent]++ - childOrder[parent, childCount[parent]] = child - } - } - - function printNode(path, label, depth, i, child, childPath, text) { - text = displayLabel(label) - if (path in slugByPath) { - text = "[" text "](#" slugByPath[path] ")" - } - print indent(depth) "- " text - for (i = 1; i <= childCount[path]; i++) { - child = childOrder[path, i] - childPath = path "." child - printNode(childPath, child, depth + 1) - } - } - - $3 == want { - normalized = $1 - gsub(/\\/, "", normalized) - slugByPath[normalized] = $2 - - count = split(normalized, parts, /\./) - parent = "services.proxy-suite" - for (i = 3; i <= count; i++) { - child = parts[i] - addChild(parent, child) - parent = parent "." child - } - } - - END { printNode("services.proxy-suite." want, want, 0) } - ' "$index_tsv" +pkgs.runCommand "proxy-suite-options-doc" { nativeBuildInputs = [ pkgs.python3 ]; } ( + fillTemplate ./render-options-markdown.template.sh { + optionsCommonMark = optionDocs.optionsCommonMark; + inherit compactFields summaryTsv; + defaultConfig = pkgs.lib.escapeShellArg defaultConfigText; } - - # Groups in the summary list's order, then any it misses. - ordered="$( - { cut -f1 ${summaryTsv}; printf '%s\n' $groups; } \ - | awk -v groups=" $(echo $groups) " 'index(groups, " " $0 " ") && !seen[$0]++' - )" - - for group in $groups; do - { - printf '# services.proxy-suite.%s\n\n' "$group" - text="$(summary "$group")" - if [ -n "$text" ]; then printf '%s\n\n' "$text"; fi - printf 'Part of the [proxy-suite options reference](./index.md).\n\n' - printf '## Options\n\n' - mkToc "$group" - printf '\n' - cat "$TMPDIR/bodies/$group.md" - } >"$TMPDIR/$group.out" - done - - { - printf '# proxy-suite options\n\n' - printf 'Generated from the `services.proxy-suite` option descriptions under\n' - printf '[`modules/proxy-suite/options/`](/modules/proxy-suite/options/).\n' - printf 'Update the module option docs there instead of editing these files by hand.\n\n' - - printf '## Option groups\n\n' - printf '| Group | What it covers |\n|---|---|\n' - for group in $ordered; do - printf '| [%s](./%s.md) | %s |\n' "$group" "$group" "$(summary "$group")" - done - printf '\n' - - if [ -f "$TMPDIR/bodies/index.md" ]; then - cat "$TMPDIR/bodies/index.md" - printf '\n' - fi - - printf '## Complete default config\n\n' - printf '
\nEvery option at its default\n\n' - printf '```nix\n' - printf 'services.proxy-suite = %s;\n' ${pkgs.lib.escapeShellArg defaultConfigText} - printf '```\n\n
\n' - } >"$TMPDIR/index.out" - - # Collapse runs of blank lines, drop trailing ones. - for group in $groups index; do - awk 'NF { if (blank) print ""; blank = 0; print; next } { blank = 1 }' \ - "$TMPDIR/$group.out" >"$out/$group.md" - done -'' +) diff --git a/nix/options-doc/render-options-markdown.template.sh b/nix/options-doc/render-options-markdown.template.sh new file mode 100644 index 0000000..ddfd42d --- /dev/null +++ b/nix/options-doc/render-options-markdown.template.sh @@ -0,0 +1,153 @@ +mkdir -p "$out" "$TMPDIR/bodies" +all="$TMPDIR/all.md" +index_tsv="$TMPDIR/sections-index.tsv" + +cat @optionsCommonMark@ >"$all" +python @compactFields@ "$all" + +summary() { awk -F '\t' -v want="$1" '$1 == want { print $2 }' @summaryTsv@; } + +# Anchor every section and file it under its top-level group. Options directly +# under services.proxy-suite (only `enable`) stay on the index. +: >"$index_tsv" +awk -v outdir="$TMPDIR/bodies" -v index_tsv="$index_tsv" ' + function slugify(text, slug) { + slug = text + gsub(/\\/, "", slug) + slug = tolower(slug) + gsub(/[^a-z0-9]+/, "-", slug) + sub(/^-+/, "", slug) + sub(/-+$/, "", slug) + return slug + } + + /^## / { + title = substr($0, 4) + normalized = title + gsub(/\\/, "", normalized) + count = split(normalized, parts, /\./) + group = (count <= 3) ? "index" : parts[3] + slug = slugify(title) + current = outdir "/" group ".md" + + print title "\t" slug "\t" group >> index_tsv + print "" >> current + print $0 >> current + next + } + + { if (current != "") print >> current } +' "$all" + +groups="$(cut -f3 "$index_tsv" | grep -v '^index$' | awk '!seen[$0]++')" + +# Per-group table of contents, nested by option path. +mkToc() { + awk -F '\t' -v want="$1" ' + function indent(depth, i, prefix) { + prefix = "" + for (i = 0; i < depth; i++) { + prefix = prefix " " + } + return prefix + } + + function displayLabel(label) { + if (label == "*") { + return "item" + } + if (label ~ /^<.*>$/) { + return "`" label "`" + } + return label + } + + function addChild(parent, child, key) { + key = parent SUBSEP child + if (!(key in seenChild)) { + seenChild[key] = 1 + childCount[parent]++ + childOrder[parent, childCount[parent]] = child + } + } + + function printNode(path, label, depth, i, child, childPath, text) { + text = displayLabel(label) + if (path in slugByPath) { + text = "[" text "](#" slugByPath[path] ")" + } + print indent(depth) "- " text + for (i = 1; i <= childCount[path]; i++) { + child = childOrder[path, i] + childPath = path "." child + printNode(childPath, child, depth + 1) + } + } + + $3 == want { + normalized = $1 + gsub(/\\/, "", normalized) + slugByPath[normalized] = $2 + + count = split(normalized, parts, /\./) + parent = "services.proxy-suite" + for (i = 3; i <= count; i++) { + child = parts[i] + addChild(parent, child) + parent = parent "." child + } + } + + END { printNode("services.proxy-suite." want, want, 0) } + ' "$index_tsv" +} + +# Groups in the summary list's order, then any it misses. +ordered="$( + { cut -f1 @summaryTsv@; printf '%s\n' $groups; } \ + | awk -v groups=" $(echo $groups) " 'index(groups, " " $0 " ") && !seen[$0]++' +)" + +for group in $groups; do + { + printf '# services.proxy-suite.%s\n\n' "$group" + text="$(summary "$group")" + if [ -n "$text" ]; then printf '%s\n\n' "$text"; fi + printf 'Part of the [proxy-suite options reference](./index.md).\n\n' + printf '## Options\n\n' + mkToc "$group" + printf '\n' + cat "$TMPDIR/bodies/$group.md" + } >"$TMPDIR/$group.out" +done + +{ + printf '# proxy-suite options\n\n' + printf 'Generated from the `services.proxy-suite` option descriptions under\n' + printf '[`modules/proxy-suite/options/`](/modules/proxy-suite/options/).\n' + printf 'Update the module option docs there instead of editing these files by hand.\n\n' + + printf '## Option groups\n\n' + printf '| Group | What it covers |\n|---|---|\n' + for group in $ordered; do + printf '| [%s](./%s.md) | %s |\n' "$group" "$group" "$(summary "$group")" + done + printf '\n' + + if [ -f "$TMPDIR/bodies/index.md" ]; then + cat "$TMPDIR/bodies/index.md" + printf '\n' + fi + + printf '## Complete default config\n\n' + printf '
\nEvery option at its default\n\n' + printf '```nix\n' + printf 'services.proxy-suite = %s;\n' @defaultConfig@ + printf '```\n\n
\n' +} >"$TMPDIR/index.out" + +# Collapse runs of blank lines, drop trailing ones. +for group in $groups index; do + awk 'NF { if (blank) print ""; blank = 0; print; next } { blank = 1 }' \ + "$TMPDIR/$group.out" >"$out/$group.md" +done diff --git a/nix/readme-doc.nix b/nix/readme-doc.nix index 484f966..2a3496b 100644 --- a/nix/readme-doc.nix +++ b/nix/readme-doc.nix @@ -8,6 +8,7 @@ system: let + fillTemplate = import ../modules/proxy-suite/lib/fill-template.nix; pkgs = pkgsFor system; packages = import ../pkgs/default.nix { inherit pkgs; }; fixture = import ./readme-doc-fixture.nix; @@ -32,34 +33,9 @@ let context ; in -pkgs.runCommand "proxy-suite-README.md" { nativeBuildInputs = [ pkgs.python3 ]; } '' - src=${../README.md} - help_file="$TMPDIR/proxy-ctl-help.txt" - export src help_file - - ${context.control.proxyCtl}/bin/proxy-ctl help > "$help_file" - - python <<'PY' - from pathlib import Path - import os - - src = Path(os.environ["src"]) - help_file = Path(os.environ["help_file"]) - out = Path(os.environ["out"]) - - start_marker = "" - end_marker = "" - - readme = src.read_text() - help_text = help_file.read_text().rstrip("\n") - replacement = f"{start_marker}\n```text\n{help_text}\n```\n{end_marker}" - - try: - start = readme.index(start_marker) - end = readme.index(end_marker) + len(end_marker) - except ValueError as exc: - raise SystemExit(f"README markers missing: {exc}") - - out.write_text(readme[:start] + replacement + readme[end:]) - PY -'' +pkgs.runCommand "proxy-suite-README.md" { nativeBuildInputs = [ pkgs.python3 ]; } ( + fillTemplate ./readme-doc.template.sh { + readme = ../README.md; + proxyCtl = context.control.proxyCtl; + } +) diff --git a/nix/readme-doc.template.sh b/nix/readme-doc.template.sh new file mode 100644 index 0000000..1e22495 --- /dev/null +++ b/nix/readme-doc.template.sh @@ -0,0 +1,29 @@ +src=@readme@ +help_file="$TMPDIR/proxy-ctl-help.txt" +export src help_file + +@proxyCtl@/bin/proxy-ctl help > "$help_file" + +python <<'PY' +from pathlib import Path +import os + +src = Path(os.environ["src"]) +help_file = Path(os.environ["help_file"]) +out = Path(os.environ["out"]) + +start_marker = "" +end_marker = "" + +readme = src.read_text() +help_text = help_file.read_text().rstrip("\n") +replacement = f"{start_marker}\n```text\n{help_text}\n```\n{end_marker}" + +try: + start = readme.index(start_marker) + end = readme.index(end_marker) + len(end_marker) +except ValueError as exc: + raise SystemExit(f"README markers missing: {exc}") + +out.write_text(readme[:start] + replacement + readme[end:]) +PY diff --git a/nix/update-docs.sh b/nix/update-docs.sh new file mode 100644 index 0000000..e36e632 --- /dev/null +++ b/nix/update-docs.sh @@ -0,0 +1,25 @@ +set -euo pipefail + +repo_root="$(git rev-parse --show-toplevel 2>/dev/null || true)" + +if [[ -z "${repo_root}" || ! -f "${repo_root}/flake.nix" ]]; then + echo "run this helper from inside the proxy-suite-flake repository" >&2 + exit 1 +fi + +options_output_path="$(nix build --no-link --print-out-paths "${repo_root}#optionsDoc")" +readme_output_path="$(nix build --no-link --print-out-paths "${repo_root}#readmeDoc")" + +mkdir -p "${repo_root}/docs" +rm -rf "${repo_root}/docs/options" +cp -r --no-preserve=mode,ownership "${options_output_path}" "${repo_root}/docs/options" +install -Dm644 "${readme_output_path}" "${repo_root}/README.md" + +# After the README, whose blocks are among them. +snippets_output_path="$(nix build --no-link --print-out-paths "${repo_root}#usageSnippets")" +rm -rf "${repo_root}/docs/usage/.snippets" +cp -r --no-preserve=mode,ownership "${snippets_output_path}" "${repo_root}/docs/usage/.snippets" + +echo "updated ${repo_root}/docs/options/" +echo "updated ${repo_root}/README.md" +echo "updated ${repo_root}/docs/usage/.snippets/" diff --git a/pkgs/tg-ws-proxy.nix b/pkgs/tg-ws-proxy.nix index 19e6cd5..76b98bf 100644 --- a/pkgs/tg-ws-proxy.nix +++ b/pkgs/tg-ws-proxy.nix @@ -1,6 +1,7 @@ { pkgs }: let + fillTemplate = import ../modules/proxy-suite/lib/fill-template.nix; src = pkgs.fetchFromGitHub { owner = "Flowseal"; repo = "tg-ws-proxy"; @@ -19,57 +20,5 @@ in pkgs.writeShellApplication { name = "tg-ws-proxy"; runtimeInputs = [ pythonEnv ]; - text = '' - set -euo pipefail - - secret="" - script_path="${src}/proxy/tg_ws_proxy.py" - args=() - - while [ "$#" -gt 0 ]; do - case "$1" in - --secret-file=*) - secret=$(tr -d '\r\n' < "''${1#--secret-file=}") - shift - ;; - --secret-file) - secret=$(tr -d '\r\n' < "$2") - shift 2 - ;; - --secret=*) - secret="''${1#--secret=}" - shift - ;; - --secret) - secret="$2" - shift 2 - ;; - *) - args+=("$1") - shift - ;; - esac - done - - export PYTHONPATH="${src}" - if [ -n "$secret" ]; then - export TG_WS_PROXY_SECRET="$secret" - fi - - exec python - "$script_path" "''${args[@]}" <<'PY' - import os - import runpy - import sys - - script_path = sys.argv[1] - args = sys.argv[2:] - secret = os.environ.get("TG_WS_PROXY_SECRET") - - if secret is not None: - args.extend(["--secret", secret]) - - sys.argv = ["tg_ws_proxy.py", *args] - runpy.run_path(script_path, run_name="__main__") - PY - ''; + text = fillTemplate ./tg-ws-proxy.template.sh { inherit src; }; } diff --git a/pkgs/tg-ws-proxy.template.sh b/pkgs/tg-ws-proxy.template.sh new file mode 100644 index 0000000..9ca7445 --- /dev/null +++ b/pkgs/tg-ws-proxy.template.sh @@ -0,0 +1,51 @@ +set -euo pipefail + +secret="" +script_path="@src@/proxy/tg_ws_proxy.py" +args=() + +while [ "$#" -gt 0 ]; do + case "$1" in + --secret-file=*) + secret=$(tr -d '\r\n' < "${1#--secret-file=}") + shift + ;; + --secret-file) + secret=$(tr -d '\r\n' < "$2") + shift 2 + ;; + --secret=*) + secret="${1#--secret=}" + shift + ;; + --secret) + secret="$2" + shift 2 + ;; + *) + args+=("$1") + shift + ;; + esac +done + +export PYTHONPATH="@src@" +if [ -n "$secret" ]; then + export TG_WS_PROXY_SECRET="$secret" +fi + +exec python - "$script_path" "${args[@]}" <<'PY' +import os +import runpy +import sys + +script_path = sys.argv[1] +args = sys.argv[2:] +secret = os.environ.get("TG_WS_PROXY_SECRET") + +if secret is not None: + args.extend(["--secret", secret]) + +sys.argv = ["tg_ws_proxy.py", *args] +runpy.run_path(script_path, run_name="__main__") +PY