Compare commits
87
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c36e7038cb | ||
|
|
b70085406e | ||
|
|
bd304373e0 | ||
|
|
29304452f7 | ||
|
|
aa44527082 | ||
|
|
32ff264c81 | ||
|
|
ddc1bbe686 | ||
|
|
d25e6cbd31 | ||
|
|
d675fdddb5 | ||
|
|
2dd563ed61 | ||
|
|
e9de863c4b | ||
|
|
803e18db9d | ||
|
|
d33f05c62c | ||
|
|
5bd47f7676 | ||
|
|
ed9275250b | ||
|
|
fe291fab2b | ||
|
|
7cdd33f05e | ||
|
|
36532bcf47 | ||
|
|
e71f6bf5aa | ||
|
|
514ffb97ca | ||
|
|
9eed225ccc | ||
|
|
0a7d8d99c0 | ||
|
|
5cf3a237e6 | ||
|
|
95ec15e14a | ||
|
|
694e176353 | ||
|
|
5a89b8d11d | ||
|
|
69e70d6f74 | ||
|
|
8d9705cd3a | ||
|
|
ae58bd1f12 | ||
|
|
ae31e499ca | ||
|
|
b6e54f963d | ||
|
|
610e36a28b | ||
|
|
1f4fcf540d | ||
|
|
2c4cdee7d3 | ||
|
|
62adadc207 | ||
|
|
d9d52c49b6 | ||
|
|
ed2159f7b6 | ||
|
|
40221e7981 | ||
|
|
82fe4d8e65 | ||
|
|
fb6c5962d0 | ||
|
|
88c8b88a49 | ||
|
|
c0b089dea8 | ||
|
|
adcd734479 | ||
|
|
6ed7a3b1c6 | ||
|
|
757bebbb1d | ||
|
|
7565e62571 | ||
|
|
77becc235c | ||
|
|
a7bf347859 | ||
|
|
69759cfbce | ||
|
|
23c1687118 | ||
|
|
a839d48e02 | ||
|
|
7dfb3129f4 | ||
|
|
c9ce7a1982 | ||
|
|
d3ba00087d | ||
|
|
63aede0dc1 | ||
|
|
4ae30dac3c | ||
|
|
da6aafaf1d | ||
|
|
363caf912a | ||
|
|
e84d42a10c | ||
|
|
8af7b2e628 | ||
|
|
28cc7b2cbe | ||
|
|
d1bce9db94 | ||
|
|
bceb754e65 | ||
|
|
9b0d7021f9 | ||
|
|
817de77d28 | ||
|
|
68b496cafa | ||
|
|
b878dd93db | ||
|
|
cd0bcae4c9 | ||
|
|
d678976c2d | ||
|
|
41c8ed4406 | ||
|
|
918cdc9a75 | ||
|
|
130c020151 | ||
|
|
3665f7f5a0 | ||
|
|
c01538fec9 | ||
|
|
96958c4e61 | ||
|
|
77d4cefe0e | ||
|
|
c837db1c18 | ||
|
|
9d81e975ea | ||
|
|
a60b2a1286 | ||
|
|
564ea9e24f | ||
|
|
20f1bdd110 | ||
|
|
a41fbc10e6 | ||
|
|
2fc8ef5567 | ||
|
|
c39921a72c | ||
|
|
9f7ad91f39 | ||
|
|
2f8414455d | ||
|
|
2be98214ed |
No files matched your search
@@ -0,0 +1,175 @@
|
||||
name: Windows release
|
||||
|
||||
# The Windows port (windows/). On a tag windows-v<version> it builds the setup program and the
|
||||
# release zip and publishes them as a Gitea release, with the notes in
|
||||
# windows/release-notes/<version>.md. Run by hand, it only builds: they are the run's artifact.
|
||||
#
|
||||
# Two jobs, as upstream's dependency updates: the one that runs fetched code (crates,
|
||||
# components, wheels, the Nix closure) holds no token that can write. Only the publishing job
|
||||
# sees RELEASE_TOKEN (write:repository), and it runs nothing it fetched: curl and jq on the
|
||||
# first job's artifact. Gitea ignores `permissions:`; they are here to say what each job needs.
|
||||
on:
|
||||
push:
|
||||
tags: ["windows-v*"]
|
||||
workflow_dispatch:
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
build:
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 150
|
||||
env:
|
||||
# Single-user Nix without a daemon: the job's container has no init to run one, nor
|
||||
# the namespaces a build sandbox needs. Set for the job, so the installer has it too.
|
||||
NIX_CONFIG: |
|
||||
experimental-features = nix-command flakes
|
||||
sandbox = false
|
||||
build-users-group =
|
||||
defaults:
|
||||
run:
|
||||
shell: bash
|
||||
steps:
|
||||
# Full history: the flake is windows/ inside this repository, fetched by Nix as git.
|
||||
- name: Check out
|
||||
uses: https://github.com/actions/checkout@v4
|
||||
with:
|
||||
fetch-depth: 0
|
||||
persist-credentials: false
|
||||
|
||||
- name: Check the version
|
||||
working-directory: windows
|
||||
run: |
|
||||
set -euo pipefail
|
||||
version=$(sed -n 's/^version = "\(.*\)"/\1/p' Cargo.toml | head -1)
|
||||
if [[ "$GITHUB_REF" == refs/tags/* ]]; then
|
||||
[[ "$GITHUB_REF_NAME" == "windows-v$version" ]] ||
|
||||
{ echo "::error::the tag is $GITHUB_REF_NAME, but windows/Cargo.toml says $version"; exit 1; }
|
||||
[ -f "release-notes/$version.md" ] ||
|
||||
{ echo "::error::no windows/release-notes/$version.md"; exit 1; }
|
||||
fi
|
||||
echo "Proxy Suite for Windows $version"
|
||||
|
||||
# Pinned: this installer checks the hash of the Nix it downloads, and is checked here.
|
||||
- name: Install Nix
|
||||
env:
|
||||
NIX_VERSION: 2.34.9
|
||||
NIX_INSTALL_SHA256: a03ce2e9eaf4ea1560260b9a93e311dbaf589d28fb5c9318f8d9e768ee6339d8
|
||||
run: |
|
||||
set -euo pipefail
|
||||
# The runner may run as root (no sudo in the image) or as a user with sudo.
|
||||
as_root() { if [ "$(id -u)" -eq 0 ]; then "$@"; else sudo "$@"; fi; }
|
||||
if ! command -v xz >/dev/null 2>&1; then
|
||||
as_root apt-get update -qq
|
||||
as_root apt-get install -y -qq xz-utils
|
||||
fi
|
||||
as_root install -d -m 0755 -o "$(id -u)" -g "$(id -g)" /nix
|
||||
tmp=$(mktemp -d)
|
||||
curl -sSfL -o "$tmp/install" "https://releases.nixos.org/nix/nix-$NIX_VERSION/install"
|
||||
echo "$NIX_INSTALL_SHA256 $tmp/install" | sha256sum -c --quiet
|
||||
USER=${USER:-$(id -un)} sh "$tmp/install" --no-daemon --no-modify-profile --no-channel-add
|
||||
echo "$HOME/.nix-profile/bin" >> "$GITHUB_PATH"
|
||||
|
||||
- name: Dev shell and Rust toolchain
|
||||
working-directory: windows
|
||||
run: nix develop --command rustup toolchain install
|
||||
|
||||
# The SSH tunnel's end-to-end test runs an sshd of its own. As root (the job's user in the
|
||||
# runner's container) sshd separates privileges: it needs its empty, root-owned directory
|
||||
# and its unprivileged user, which the image does not have.
|
||||
- name: Test prerequisites
|
||||
run: |
|
||||
set -euo pipefail
|
||||
if [ "$(id -u)" = 0 ]; then
|
||||
install -d -m 0755 -o root -g root /var/empty
|
||||
id sshd >/dev/null 2>&1 || useradd --system --no-create-home --home-dir /var/empty --shell /usr/sbin/nologin sshd
|
||||
fi
|
||||
|
||||
# The default members: the service, proxy-ctl, the client and core (the app's crate is
|
||||
# built by Package).
|
||||
- name: Test
|
||||
working-directory: windows
|
||||
run: nix develop --command cargo test --locked
|
||||
|
||||
- name: Package
|
||||
working-directory: windows
|
||||
run: nix develop --command tools/package.sh
|
||||
|
||||
- name: Collect
|
||||
working-directory: windows
|
||||
run: |
|
||||
set -euo pipefail
|
||||
version=$(sed -n 's/^version = "\(.*\)"/\1/p' Cargo.toml | head -1)
|
||||
mkdir -p ../release
|
||||
for f in "ProxySuite-$version-windows-x64-setup.exe" "ProxySuite-$version-windows-x64.zip"; do
|
||||
cp "dist/$f" "dist/$f.sha256" ../release/
|
||||
done
|
||||
if [ -f "release-notes/$version.md" ]; then cp "release-notes/$version.md" ../release/notes.md; fi
|
||||
|
||||
- name: Upload
|
||||
uses: https://github.com/actions/upload-artifact@v4
|
||||
with:
|
||||
name: windows-release
|
||||
path: release/
|
||||
if-no-files-found: error
|
||||
|
||||
publish:
|
||||
needs: build
|
||||
if: startsWith(github.ref, 'refs/tags/windows-v')
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 20
|
||||
permissions:
|
||||
contents: write
|
||||
defaults:
|
||||
run:
|
||||
shell: bash
|
||||
steps:
|
||||
- name: Download
|
||||
uses: https://github.com/actions/download-artifact@v4
|
||||
with:
|
||||
name: windows-release
|
||||
path: release
|
||||
|
||||
# The release for the tag, made if it is not there yet (a pre-release for a version with
|
||||
# a "-"), and its assets, replacing any of the same name, so a rerun is harmless.
|
||||
- name: Publish
|
||||
env:
|
||||
TOKEN: ${{ secrets.RELEASE_TOKEN }}
|
||||
API: ${{ github.server_url }}/api/v1/repos/${{ github.repository }}
|
||||
TAG: ${{ github.ref_name }}
|
||||
SHA: ${{ github.sha }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
as_root() { if [ "$(id -u)" -eq 0 ]; then "$@"; else sudo "$@"; fi; }
|
||||
if ! command -v jq >/dev/null 2>&1; then
|
||||
as_root apt-get update -qq
|
||||
as_root apt-get install -y -qq jq
|
||||
fi
|
||||
[ -n "$TOKEN" ] || { echo "::error::the RELEASE_TOKEN secret is not set"; exit 1; }
|
||||
api() { curl -sS --fail-with-body -H "Authorization: token $TOKEN" "$@"; }
|
||||
version=${TAG#windows-v}
|
||||
|
||||
code=$(curl -sS -o found.json -w '%{http_code}' -H "Authorization: token $TOKEN" "$API/releases/tags/$TAG")
|
||||
case $code in
|
||||
200) id=$(jq -r .id found.json) ;;
|
||||
404)
|
||||
pre=false
|
||||
[[ "$version" == *-* ]] && pre=true
|
||||
id=$(jq -n --arg tag "$TAG" --arg sha "$SHA" --arg name "Proxy Suite for Windows $version" \
|
||||
--rawfile body release/notes.md --argjson pre "$pre" \
|
||||
'{tag_name: $tag, target_commitish: $sha, name: $name, body: $body, prerelease: $pre, draft: false}' |
|
||||
api -H 'Content-Type: application/json' --data-binary @- "$API/releases" | jq -r .id)
|
||||
echo "made the release for $TAG" ;;
|
||||
*) echo "::error::looking up the release for $TAG: HTTP $code: $(cat found.json)"; exit 1 ;;
|
||||
esac
|
||||
|
||||
for f in release/*.exe release/*.zip release/*.sha256; do
|
||||
name=$(basename "$f")
|
||||
for old in $(api "$API/releases/$id/assets" | jq -r --arg n "$name" '.[] | select(.name == $n) | .id'); do
|
||||
api -X DELETE "$API/releases/$id/assets/$old" >/dev/null
|
||||
done
|
||||
api -F "attachment=@$f" "$API/releases/$id/assets?name=$name" >/dev/null
|
||||
echo "uploaded $name"
|
||||
done
|
||||
echo "$GITHUB_SERVER_URL/$GITHUB_REPOSITORY/releases/tag/$TAG"
|
||||
@@ -0,0 +1,19 @@
|
||||
# The workflows pin actions by commit SHA; Dependabot moves the SHA and its version
|
||||
# comment together. Nix inputs and pinned sources are dependency-updates.yml's job.
|
||||
version: 2
|
||||
updates:
|
||||
- package-ecosystem: github-actions
|
||||
directory: /
|
||||
schedule:
|
||||
interval: weekly
|
||||
day: monday
|
||||
labels:
|
||||
- dependencies
|
||||
- github-actions
|
||||
commit-message:
|
||||
prefix: "chore(ci)"
|
||||
# Every action bump in one pull request, not one each.
|
||||
groups:
|
||||
github-actions:
|
||||
patterns:
|
||||
- "*"
|
||||
@@ -25,17 +25,19 @@ jobs:
|
||||
runs-on: ubuntu-24.04
|
||||
outputs:
|
||||
has_changes: ${{ steps.changes.outputs.has_changes }}
|
||||
checks_failed: ${{ steps.checks.outputs.failed }}
|
||||
# A skipped pin, failed package build or failed check: the pull request opens as a
|
||||
# draft and the run ends red.
|
||||
failed: ${{ (steps.pins.outputs.skipped == 'true' || steps.builds.outputs.failed == 'true' || steps.checks.outputs.failed == 'true') && 'true' || 'false' }}
|
||||
steps:
|
||||
# No token left in .git/config for the steps that run fetched code (flake updates,
|
||||
# update-pins.sh, nix builds); create-pull-request authenticates on its own.
|
||||
- name: Checkout
|
||||
uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0
|
||||
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
persist-credentials: false
|
||||
|
||||
- name: Install Nix
|
||||
uses: DeterminateSystems/nix-installer-action@ef8a148080ab6020fd15196c2084a2eea5ff2d25 # v22
|
||||
uses: DeterminateSystems/nix-installer-action@3138316df39ed29be04236d7ffc686fa525866aa # v23
|
||||
|
||||
- name: Decide whether nixpkgs should be updated
|
||||
id: nixpkgs_gate
|
||||
@@ -55,15 +57,24 @@ jobs:
|
||||
else
|
||||
echo "Skipping nixpkgs update: watched package versions on nixos-unstable are unchanged."
|
||||
fi
|
||||
nix flake update zapret
|
||||
# Every other input, every run; update-pins.sh then refreshes the hashes of the
|
||||
# sources that follow one (z2k-detect follows z2k).
|
||||
nix flake update zapret z2k nfqws2-keenetic disko
|
||||
|
||||
# A pin that cannot be updated is put back and listed as "skipped"; the rest go through.
|
||||
- name: Update pinned sources
|
||||
id: pins
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ github.token }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
scripts/update-pins.sh --self-test
|
||||
scripts/update-pins.sh | tee "$RUNNER_TEMP/pin-updates.txt"
|
||||
if grep -q '^skipped ' "$RUNNER_TEMP/pin-updates.txt"; then
|
||||
echo "skipped=true" >> "$GITHUB_OUTPUT"
|
||||
else
|
||||
echo "skipped=false" >> "$GITHUB_OUTPUT"
|
||||
fi
|
||||
|
||||
# A nixpkgs bump can bring a nixfmt whose style differs; restyle the tree with
|
||||
# it so the nix-format check passes and the restyle rides along in the PR.
|
||||
@@ -80,12 +91,25 @@ jobs:
|
||||
echo "has_changes=true" >> "$GITHUB_OUTPUT"
|
||||
fi
|
||||
|
||||
# One build per package, so a failure names it; like the checks, a failure makes the
|
||||
# pull request a draft instead of holding the update back.
|
||||
- name: Build updated packages
|
||||
id: builds
|
||||
if: steps.changes.outputs.has_changes == 'true'
|
||||
run: |
|
||||
set -euo pipefail
|
||||
set -uo pipefail
|
||||
mapfile -t attrs < <(scripts/update-pins.sh --attrs)
|
||||
nix build --no-link "${attrs[@]}"
|
||||
: > "$RUNNER_TEMP/failed-builds.txt"
|
||||
for attr in "${attrs[@]}"; do
|
||||
echo "::group::nix build ${attr}"
|
||||
nix build --no-link --print-build-logs "$attr" || echo "${attr#.#}" >> "$RUNNER_TEMP/failed-builds.txt"
|
||||
echo "::endgroup::"
|
||||
done
|
||||
if [[ -s "$RUNNER_TEMP/failed-builds.txt" ]]; then
|
||||
echo "failed=true" >> "$GITHUB_OUTPUT"
|
||||
else
|
||||
echo "failed=false" >> "$GITHUB_OUTPUT"
|
||||
fi
|
||||
|
||||
# A failing check does not hold the update back: the pull request opens as a draft
|
||||
# naming the failures, and the run still ends red (open-pull-request's last step).
|
||||
@@ -112,6 +136,8 @@ jobs:
|
||||
env:
|
||||
SHOULD_UPDATE_NIXPKGS: ${{ steps.nixpkgs_gate.outputs.should_update_nixpkgs }}
|
||||
CHANGED_WATCH_ATTRS: ${{ steps.nixpkgs_gate.outputs.nixpkgs_changed_watch_attrs }}
|
||||
PINS_SKIPPED: ${{ steps.pins.outputs.skipped }}
|
||||
BUILDS_FAILED: ${{ steps.builds.outputs.failed }}
|
||||
CHECKS_FAILED: ${{ steps.checks.outputs.failed }}
|
||||
RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}
|
||||
run: |
|
||||
@@ -122,6 +148,9 @@ jobs:
|
||||
echo "Managed by CI; the \`ci/update-dependencies\` branch is reused across runs."
|
||||
echo
|
||||
echo "### Pinned sources"
|
||||
if [[ "$PINS_SKIPPED" == "true" ]]; then
|
||||
echo "Some could not be updated and were kept, so this pull request is a draft ([run log]($RUN_URL))."
|
||||
fi
|
||||
if [[ -s "$RUNNER_TEMP/pin-updates.txt" ]]; then
|
||||
sed 's/^/- /' "$RUNNER_TEMP/pin-updates.txt"
|
||||
else
|
||||
@@ -131,7 +160,21 @@ jobs:
|
||||
echo "### Flake inputs"
|
||||
echo "- nixpkgs updated: \`$SHOULD_UPDATE_NIXPKGS\`"
|
||||
echo "- changed watched attrs: \`$CHANGED_WATCH_ATTRS\`"
|
||||
echo "- zapret: refreshed every run"
|
||||
# The locked revs that moved, against the checked-out lock file.
|
||||
git show HEAD:flake.lock | jq -r --slurpfile new flake.lock '
|
||||
.nodes as $old | $new[0].nodes | to_entries[]
|
||||
| select(.value.locked.rev? != null)
|
||||
| (.value.locked.rev) as $rev | ($old[.key].locked.rev // "none") as $prev
|
||||
| select($rev != $prev)
|
||||
| "- \(.key): `\($prev[0:7])` -> `\($rev[0:7])`"'
|
||||
echo
|
||||
echo "### Package builds"
|
||||
if [[ "$BUILDS_FAILED" == "true" ]]; then
|
||||
echo "Failed, so this pull request is a draft ([run log]($RUN_URL)):"
|
||||
while IFS= read -r attr; do echo "- \`$attr\`"; done < "$RUNNER_TEMP/failed-builds.txt"
|
||||
else
|
||||
echo "- all built"
|
||||
fi
|
||||
echo
|
||||
echo "### Flake checks"
|
||||
if [[ "$CHECKS_FAILED" == "true" ]]; then
|
||||
@@ -162,7 +205,7 @@ jobs:
|
||||
|
||||
- name: Upload the changes
|
||||
if: steps.changes.outputs.has_changes == 'true'
|
||||
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
|
||||
uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
|
||||
with:
|
||||
name: dependency-updates
|
||||
path: |
|
||||
@@ -170,9 +213,18 @@ jobs:
|
||||
${{ runner.temp }}/dependency-updates.md
|
||||
retention-days: 1
|
||||
|
||||
# With nothing else to propose there is no pull request to carry a skipped pin.
|
||||
- name: No dependency changes
|
||||
if: steps.changes.outputs.has_changes != 'true'
|
||||
run: echo "No dependency updates detected."
|
||||
env:
|
||||
PINS_SKIPPED: ${{ steps.pins.outputs.skipped }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
if [[ "$PINS_SKIPPED" == "true" ]]; then
|
||||
grep '^skipped ' "$RUNNER_TEMP/pin-updates.txt" | sed 's/^/::error::/'
|
||||
exit 1
|
||||
fi
|
||||
echo "No dependency updates detected."
|
||||
|
||||
open-pull-request:
|
||||
needs: update-dependencies
|
||||
@@ -183,12 +235,12 @@ jobs:
|
||||
pull-requests: write
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0
|
||||
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
persist-credentials: false
|
||||
|
||||
- name: Download the changes
|
||||
uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1
|
||||
uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2
|
||||
with:
|
||||
name: dependency-updates
|
||||
path: ${{ runner.temp }}/dependency-updates
|
||||
@@ -210,7 +262,7 @@ jobs:
|
||||
uses: peter-evans/create-pull-request@5f6978faf089d4d20b00c7766989d076bb2fc7f1 # v8.1.1
|
||||
with:
|
||||
# always-true also turns an open pull request back into a draft.
|
||||
draft: ${{ needs.update-dependencies.outputs.checks_failed == 'true' && 'always-true' || 'false' }}
|
||||
draft: ${{ needs.update-dependencies.outputs.failed == 'true' && 'always-true' || 'false' }}
|
||||
branch: ci/update-dependencies
|
||||
delete-branch: false
|
||||
add-paths: |
|
||||
@@ -224,9 +276,9 @@ jobs:
|
||||
dependencies
|
||||
nix
|
||||
|
||||
# draft: false leaves an existing draft alone; once the checks pass, mark it ready.
|
||||
# draft: false leaves an existing draft alone; once nothing was skipped or failed, mark it ready.
|
||||
- name: Mark the pull request ready for review
|
||||
if: needs.update-dependencies.outputs.checks_failed != 'true' && steps.pr.outputs.pull-request-operation == 'updated'
|
||||
if: needs.update-dependencies.outputs.failed != 'true' && steps.pr.outputs.pull-request-operation == 'updated'
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
PR_NUMBER: ${{ steps.pr.outputs.pull-request-number }}
|
||||
@@ -236,10 +288,10 @@ jobs:
|
||||
gh pr ready "$PR_NUMBER" --repo "$GITHUB_REPOSITORY"
|
||||
fi
|
||||
|
||||
- name: Fail the run on failed checks
|
||||
if: needs.update-dependencies.outputs.checks_failed == 'true'
|
||||
- name: Fail the run on skipped pins, failed builds or checks
|
||||
if: needs.update-dependencies.outputs.failed == 'true'
|
||||
env:
|
||||
PR_URL: ${{ steps.pr.outputs.pull-request-url }}
|
||||
run: |
|
||||
echo "::error::Flake checks failed; the update is a draft pull request: $PR_URL"
|
||||
echo "::error::Pins were skipped, or package builds or flake checks failed; the update is a draft pull request: $PR_URL"
|
||||
exit 1
|
||||
@@ -24,7 +24,7 @@ Bundles [sing-box](https://github.com/SagerNet/sing-box), [XRay](https://github.
|
||||
- AmneziaWG 1.x–3.x from `.conf`, `vpn://` or Nix
|
||||
- Cloudflare WARP, Tor (with bridges and an onion service), an SSH tunnel and a Telegram proxy
|
||||
- Tunnels through video-call servers, to get past mobile internet whitelists
|
||||
- Server inbounds (XRay protocols, hysteria2, AmneziaWG) with share links, QR codes, subscriptions and traffic stats
|
||||
- Server inbounds (XRay protocols, hysteria2, AmneziaWG) with share links, QR codes, subscriptions in each client's format (links, Clash, sing-box, a web page) and traffic stats; users with expiry, traffic, device and speed limits
|
||||
- A desktop GUI with a tray icon, the `proxy-ctl` CLI and the `proxy-tui` terminal UI
|
||||
|
||||
## Setup
|
||||
@@ -279,5 +279,28 @@ Changes and secrets need root or the userControl group.
|
||||
inbounds rm <tag> remove a runtime listener
|
||||
inbounds show <tag> a runtime listener's JSON
|
||||
inbounds online who is online, and when others were last seen
|
||||
|
||||
With inbounds.manager (users' policies; the API proxy-ctl and bots use):
|
||||
inbounds users [list] [--json] users, whether they may connect, traffic, expiry
|
||||
inbounds users show <name> [--json] one user: policy, traffic, online, subscription
|
||||
inbounds users add <name> [...] [policy flags]
|
||||
add a runtime user with a policy
|
||||
inbounds users set <name> [--expires 2026-12-31|+30d] [--on-hold 30d] [--traffic 50G]
|
||||
[--period monthly] [--ips 2] [--speed 20M/5M] [--enable|--disable] [--meta key=value]...
|
||||
change a user's policy (declared users too);
|
||||
--on-hold: a term that starts on the first connection
|
||||
inbounds users unset <name> <expires|hold|traffic|period|ips|speed|meta|enabled>...
|
||||
back to the config's value, or none
|
||||
inbounds users enable|disable <name> switch a user on or off
|
||||
inbounds users reset <name> start their traffic over
|
||||
inbounds users extend <name> 30d [--reset]
|
||||
move the expiry on (from now, or from it if later;
|
||||
on hold: a longer term); --reset: traffic anew too
|
||||
inbounds users extend <name> --until <time> [--reset]
|
||||
inbounds users rotate-sub <name> a new subscription URL, the old one stops answering
|
||||
inbounds bans [rm <address>] addresses banned past a user's ipLimit
|
||||
inbounds export [file] [--no-stats] users, policies, keys and traffic, to move them
|
||||
inbounds import <file|-> [--replace] take them in on this server
|
||||
inbounds events [N] what the manager did and told its webhooks
|
||||
```
|
||||
<!-- proxy-ctl-help:end -->
|
||||
@@ -113,10 +113,41 @@ Part of the [proxy-suite options reference](./index.md).
|
||||
- [users](#services-proxy-suite-inbounds-listeners-name-users)
|
||||
- [via](#services-proxy-suite-inbounds-listeners-name-via)
|
||||
- [xrayJson](#services-proxy-suite-inbounds-listeners-name-xrayjson)
|
||||
- manager
|
||||
- [enable](#services-proxy-suite-inbounds-manager-enable)
|
||||
- api
|
||||
- [group](#services-proxy-suite-inbounds-manager-api-group)
|
||||
- [listen](#services-proxy-suite-inbounds-manager-api-listen)
|
||||
- [tokensFile](#services-proxy-suite-inbounds-manager-api-tokensfile)
|
||||
- [deleteExpiredAfter](#services-proxy-suite-inbounds-manager-deleteexpiredafter)
|
||||
- [interval](#services-proxy-suite-inbounds-manager-interval)
|
||||
- ipLimit
|
||||
- [banTime](#services-proxy-suite-inbounds-manager-iplimit-bantime)
|
||||
- notify
|
||||
- [expiryDays](#services-proxy-suite-inbounds-manager-notify-expirydays)
|
||||
- [trafficPercent](#services-proxy-suite-inbounds-manager-notify-trafficpercent)
|
||||
- speedLimits
|
||||
- [enable](#services-proxy-suite-inbounds-manager-speedlimits-enable)
|
||||
- [slots](#services-proxy-suite-inbounds-manager-speedlimits-slots)
|
||||
- subscriptions
|
||||
- [enable](#services-proxy-suite-inbounds-manager-subscriptions-enable)
|
||||
- [group](#services-proxy-suite-inbounds-manager-subscriptions-group)
|
||||
- [listen](#services-proxy-suite-inbounds-manager-subscriptions-listen)
|
||||
- [profileTitle](#services-proxy-suite-inbounds-manager-subscriptions-profiletitle)
|
||||
- [supportUrl](#services-proxy-suite-inbounds-manager-subscriptions-supporturl)
|
||||
- [updateInterval](#services-proxy-suite-inbounds-manager-subscriptions-updateinterval)
|
||||
- [webPageUrl](#services-proxy-suite-inbounds-manager-subscriptions-webpageurl)
|
||||
- [webhooks](#services-proxy-suite-inbounds-manager-webhooks)
|
||||
- item
|
||||
- [events](#services-proxy-suite-inbounds-manager-webhooks-events)
|
||||
- [secretFile](#services-proxy-suite-inbounds-manager-webhooks-secretfile)
|
||||
- [url](#services-proxy-suite-inbounds-manager-webhooks-url)
|
||||
- [openFirewall](#services-proxy-suite-inbounds-openfirewall)
|
||||
- routing
|
||||
- [blockPorts](#services-proxy-suite-inbounds-routing-blockports)
|
||||
- [blockPrivate](#services-proxy-suite-inbounds-routing-blockprivate)
|
||||
- [blockRu](#services-proxy-suite-inbounds-routing-blockru)
|
||||
- [blockTorrent](#services-proxy-suite-inbounds-routing-blocktorrent)
|
||||
- proxy
|
||||
- [domains](#services-proxy-suite-inbounds-routing-proxy-domains)
|
||||
- [geoips](#services-proxy-suite-inbounds-routing-proxy-geoips)
|
||||
@@ -146,12 +177,21 @@ Part of the [proxy-suite options reference](./index.md).
|
||||
- [enable](#services-proxy-suite-inbounds-subscriptions-enable)
|
||||
- [baseUrl](#services-proxy-suite-inbounds-subscriptions-baseurl)
|
||||
- [group](#services-proxy-suite-inbounds-subscriptions-group)
|
||||
- [keyFile](#services-proxy-suite-inbounds-subscriptions-keyfile)
|
||||
- [users](#services-proxy-suite-inbounds-users)
|
||||
- `<name>`
|
||||
- [address](#services-proxy-suite-inbounds-users-name-address)
|
||||
- [order](#services-proxy-suite-inbounds-users-name-order)
|
||||
- [password](#services-proxy-suite-inbounds-users-name-password)
|
||||
- [passwordFile](#services-proxy-suite-inbounds-users-name-passwordfile)
|
||||
- policy
|
||||
- [enabled](#services-proxy-suite-inbounds-users-name-policy-enabled)
|
||||
- [expiresAfter](#services-proxy-suite-inbounds-users-name-policy-expiresafter)
|
||||
- [expiresAt](#services-proxy-suite-inbounds-users-name-policy-expiresat)
|
||||
- [ipLimit](#services-proxy-suite-inbounds-users-name-policy-iplimit)
|
||||
- [speedLimit](#services-proxy-suite-inbounds-users-name-policy-speedlimit)
|
||||
- [trafficLimit](#services-proxy-suite-inbounds-users-name-policy-trafficlimit)
|
||||
- [trafficPeriod](#services-proxy-suite-inbounds-users-name-policy-trafficperiod)
|
||||
- [presharedKeyFile](#services-proxy-suite-inbounds-users-name-presharedkeyfile)
|
||||
- [privateKeyFile](#services-proxy-suite-inbounds-users-name-privatekeyfile)
|
||||
- [publicKey](#services-proxy-suite-inbounds-users-name-publickey)
|
||||
@@ -1132,6 +1172,219 @@ Raw XRay inbound JSON (ends up in the Nix store)\. Its tag is replaced; a missin
|
||||
**Default:** `null`\
|
||||
**Example:** `{ protocol = "dokodemo-door"; settings = { port = 8080; }; }`
|
||||
|
||||
<a id="services-proxy-suite-inbounds-manager-enable"></a>
|
||||
## services\.proxy-suite\.inbounds\.manager\.enable
|
||||
|
||||
The inbound manager, a daemon that keeps the users’ policies (` inbounds.users.<name>.policy `,
|
||||
and what it is told at runtime): who is switched off, whose time ran out, who used up
|
||||
their traffic, how many addresses and how much speed each may have\. It applies them to
|
||||
the running inbounds without a restart, answers an HTTP+JSON API for proxy-ctl and bots,
|
||||
serves subscriptions with the traffic and expiry clients show, and calls webhooks\.
|
||||
Users and listeners added through it need ` inbounds.runtime `\.
|
||||
|
||||
**Type:** boolean\
|
||||
**Default:** `false`
|
||||
|
||||
<a id="services-proxy-suite-inbounds-manager-api-group"></a>
|
||||
## services\.proxy-suite\.inbounds\.manager\.api\.group
|
||||
|
||||
Group that may use the API socket, /run/proxy-suite-inbounds-manager/api\.sock: all of
|
||||
it, every user’s secrets included\. ` null `: ` userControl.group ` when it has the
|
||||
“inbounds” scope, root only otherwise\.
|
||||
|
||||
**Type:** null or string\
|
||||
**Default:** `null`\
|
||||
**Example:** `"vpn-admins"`
|
||||
|
||||
<a id="services-proxy-suite-inbounds-manager-api-listen"></a>
|
||||
## services\.proxy-suite\.inbounds\.manager\.api\.listen
|
||||
|
||||
Address and port the API also listens on over TCP, for a bot on another host\. Plain
|
||||
HTTP: put it on loopback behind a TLS proxy\. Needs ` tokensFile `; the firewall is not
|
||||
opened for it\.
|
||||
|
||||
**Type:** null or string matching the pattern (\[\[]\[0-9A-Fa-f:\.]+\[]]|\[0-9\.]+|localhost):\[0-9]{1,5}\
|
||||
**Default:** `null`\
|
||||
**Example:** `"127.0.0.1:9180"`
|
||||
|
||||
<a id="services-proxy-suite-inbounds-manager-api-tokensfile"></a>
|
||||
## services\.proxy-suite\.inbounds\.manager\.api\.tokensFile
|
||||
|
||||
File with the bearer tokens the TCP API takes, one per line, “name:token” or the token
|
||||
alone\. Read at start\.
|
||||
|
||||
**Type:** null or string\
|
||||
**Default:** `null`\
|
||||
**Example:** `"/run/secrets/inbounds-manager-tokens"`
|
||||
|
||||
<a id="services-proxy-suite-inbounds-manager-deleteexpiredafter"></a>
|
||||
## services\.proxy-suite\.inbounds\.manager\.deleteExpiredAfter
|
||||
|
||||
Delete runtime users this long after their ` expiresAt `, as ` proxy-ctl inbounds users rm `
|
||||
would: their secrets, policy and subscription go\. A number with m, h, d or w\. Users
|
||||
declared in the config stay\. ` null `: never\.
|
||||
|
||||
**Type:** null or string matching the pattern \[0-9]+\[mhdw]\
|
||||
**Default:** `null`\
|
||||
**Example:** `"30d"`
|
||||
|
||||
<a id="services-proxy-suite-inbounds-manager-interval"></a>
|
||||
## services\.proxy-suite\.inbounds\.manager\.interval
|
||||
|
||||
Seconds between two rounds of counting traffic and checking the policies\.
|
||||
|
||||
**Type:** integer between 5 and 3600 (both inclusive)\
|
||||
**Default:** `30`
|
||||
|
||||
<a id="services-proxy-suite-inbounds-manager-iplimit-bantime"></a>
|
||||
## services\.proxy-suite\.inbounds\.manager\.ipLimit\.banTime
|
||||
|
||||
Seconds an address past a user’s ` ipLimit ` is banned for\.
|
||||
|
||||
**Type:** positive integer, meaning >0\
|
||||
**Default:** `600`
|
||||
|
||||
<a id="services-proxy-suite-inbounds-manager-notify-expirydays"></a>
|
||||
## services\.proxy-suite\.inbounds\.manager\.notify\.expiryDays
|
||||
|
||||
Days before the expiry that send a user\.expiring event\.
|
||||
|
||||
**Type:** list of (positive integer, meaning >0)\
|
||||
**Default:** `[ 3 1 ]`
|
||||
|
||||
<a id="services-proxy-suite-inbounds-manager-notify-trafficpercent"></a>
|
||||
## services\.proxy-suite\.inbounds\.manager\.notify\.trafficPercent
|
||||
|
||||
Shares of the traffic allowance used that send a user\.traffic event, once per period\.
|
||||
|
||||
**Type:** list of integer between 1 and 100 (both inclusive)\
|
||||
**Default:** `[ 80 100 ]`
|
||||
|
||||
<a id="services-proxy-suite-inbounds-manager-speedlimits-enable"></a>
|
||||
## services\.proxy-suite\.inbounds\.manager\.speedLimits\.enable
|
||||
|
||||
Speed limits (` policy.speedLimit `)\. XRay marks the sockets its exits dial for a limited
|
||||
user with the user’s slot, which proxy-suite’s XRay build carries a patch for
|
||||
(pkgs/patches/xray-user-level-mark\.patch), and nftables polices each mark’s
|
||||
traffic both ways\. AmneziaWG peers are policed by their tunnel address\. Needs root\.
|
||||
|
||||
**Type:** boolean\
|
||||
**Default:** `false`
|
||||
|
||||
<a id="services-proxy-suite-inbounds-manager-speedlimits-slots"></a>
|
||||
## services\.proxy-suite\.inbounds\.manager\.speedLimits\.slots
|
||||
|
||||
How many users may have a speed limit at once: an XRay user level each\.
|
||||
|
||||
**Type:** integer between 1 and 65535 (both inclusive)\
|
||||
**Default:** `512`
|
||||
|
||||
<a id="services-proxy-suite-inbounds-manager-subscriptions-enable"></a>
|
||||
## services\.proxy-suite\.inbounds\.manager\.subscriptions\.enable
|
||||
|
||||
Serve each user’s subscription from /run/proxy-suite-inbounds-manager/sub\.sock, with the
|
||||
headers clients read their traffic, allowance and expiry from (subscription-userinfo),
|
||||
a title and an update interval\. The token is the last part of the path, the same
|
||||
as the static files’ (` inbounds.subscriptions `), so their URLs keep working:
|
||||
|
||||
```nix
|
||||
services.nginx.virtualHosts."vpn.example.com".locations."/sub/".proxyPass =
|
||||
"http://unix:/run/proxy-suite-inbounds-manager/sub.sock:";
|
||||
```
|
||||
|
||||
**Type:** boolean\
|
||||
**Default:** `config.services.proxy-suite.inbounds.shareLinks`
|
||||
|
||||
<a id="services-proxy-suite-inbounds-manager-subscriptions-group"></a>
|
||||
## services\.proxy-suite\.inbounds\.manager\.subscriptions\.group
|
||||
|
||||
Group of the web server that connects to the subscription socket\.
|
||||
|
||||
**Type:** string\
|
||||
**Default:** `config.services.proxy-suite.inbounds.subscriptions.group`
|
||||
|
||||
<a id="services-proxy-suite-inbounds-manager-subscriptions-listen"></a>
|
||||
## services\.proxy-suite\.inbounds\.manager\.subscriptions\.listen
|
||||
|
||||
Address and port the subscriptions are also served on over TCP, for a web server that cannot reach the socket\.
|
||||
|
||||
**Type:** null or string matching the pattern (\[\[]\[0-9A-Fa-f:\.]+\[]]|\[0-9\.]+|localhost):\[0-9]{1,5}\
|
||||
**Default:** `null`\
|
||||
**Example:** `"127.0.0.1:9181"`
|
||||
|
||||
<a id="services-proxy-suite-inbounds-manager-subscriptions-profiletitle"></a>
|
||||
## services\.proxy-suite\.inbounds\.manager\.subscriptions\.profileTitle
|
||||
|
||||
The profile’s name in clients; {user} is the user’s\.
|
||||
|
||||
**Type:** string\
|
||||
**Default:** `"{user}"`\
|
||||
**Example:** `"My VPN ({user})"`
|
||||
|
||||
<a id="services-proxy-suite-inbounds-manager-subscriptions-supporturl"></a>
|
||||
## services\.proxy-suite\.inbounds\.manager\.subscriptions\.supportUrl
|
||||
|
||||
Where clients send users for help (support-url), such as a Telegram link\.
|
||||
|
||||
**Type:** null or string\
|
||||
**Default:** `null`\
|
||||
**Example:** `"https://t.me/my_vpn_support"`
|
||||
|
||||
<a id="services-proxy-suite-inbounds-manager-subscriptions-updateinterval"></a>
|
||||
## services\.proxy-suite\.inbounds\.manager\.subscriptions\.updateInterval
|
||||
|
||||
Hours between clients’ updates of the subscription (profile-update-interval)\.
|
||||
|
||||
**Type:** null or (positive integer, meaning >0)\
|
||||
**Default:** `12`
|
||||
|
||||
<a id="services-proxy-suite-inbounds-manager-subscriptions-webpageurl"></a>
|
||||
## services\.proxy-suite\.inbounds\.manager\.subscriptions\.webPageUrl
|
||||
|
||||
The service’s page (profile-web-page-url)\.
|
||||
|
||||
**Type:** null or string\
|
||||
**Default:** `null`
|
||||
|
||||
<a id="services-proxy-suite-inbounds-manager-webhooks"></a>
|
||||
## services\.proxy-suite\.inbounds\.manager\.webhooks
|
||||
|
||||
Where to tell about users created, deleted, updated, switched off (with why) and back
|
||||
on, their traffic reset, their term started on their first connection (user\.activated), thresholds of their allowance, coming expiries and addresses
|
||||
banned past their ipLimit\. Retried a few times; a hook that stays down misses them\.
|
||||
|
||||
**Type:** list of (submodule)\
|
||||
**Default:** `[ ]`\
|
||||
**Example:**
|
||||
|
||||
```nix
|
||||
[ { url = "http://127.0.0.1:8088/proxy-suite"; secretFile = "/run/secrets/hook"; } ]
|
||||
|
||||
```
|
||||
|
||||
<a id="services-proxy-suite-inbounds-manager-webhooks-events"></a>
|
||||
## services\.proxy-suite\.inbounds\.manager\.webhooks\.\*\.events
|
||||
|
||||
Events to send\. Empty: all of them\.
|
||||
|
||||
**Type:** list of (one of “user\.created”, “user\.deleted”, “user\.updated”, “user\.enabled”, “user\.disabled”, “user\.reset”, “user\.activated”, “user\.traffic”, “user\.expiring”, “user\.ip-limit”)\
|
||||
**Default:** `[ ]`
|
||||
|
||||
<a id="services-proxy-suite-inbounds-manager-webhooks-secretfile"></a>
|
||||
## services\.proxy-suite\.inbounds\.manager\.webhooks\.\*\.secretFile
|
||||
|
||||
File with a secret: each body is signed, X-Proxy-Suite-Signature: sha256=\<HMAC-SHA256 hex>\.
|
||||
|
||||
**Type:** null or string\
|
||||
**Default:** `null`
|
||||
|
||||
<a id="services-proxy-suite-inbounds-manager-webhooks-url"></a>
|
||||
## services\.proxy-suite\.inbounds\.manager\.webhooks\.\*\.url
|
||||
|
||||
URL the events are POSTed to as JSON: {event, user, at, data}\.
|
||||
|
||||
**Type:** string
|
||||
|
||||
<a id="services-proxy-suite-inbounds-openfirewall"></a>
|
||||
## services\.proxy-suite\.inbounds\.openFirewall
|
||||
|
||||
@@ -1140,6 +1393,17 @@ Open the firewall for every listener not on loopback\.
|
||||
**Type:** boolean\
|
||||
**Default:** `true`
|
||||
|
||||
<a id="services-proxy-suite-inbounds-routing-blockports"></a>
|
||||
## services\.proxy-suite\.inbounds\.routing\.blockPorts
|
||||
|
||||
Destination ports clients may not reach, TCP and UDP: single ports and “from-to”
|
||||
ranges\. Port 25 by default: mail sent straight to other servers, which spam goes
|
||||
out by and hosters close\. Mail clients’ own ports (465, 587) stay open\.
|
||||
|
||||
**Type:** list of (16 bit unsigned integer; between 0 and 65535 (both inclusive) or string matching the pattern \[0-9]±\[0-9]+)\
|
||||
**Default:** `[ 25 ]`\
|
||||
**Example:** `[ 25 "6881-6889" ]`
|
||||
|
||||
<a id="services-proxy-suite-inbounds-routing-blockprivate"></a>
|
||||
## services\.proxy-suite\.inbounds\.routing\.blockPrivate
|
||||
|
||||
@@ -1159,6 +1423,17 @@ Block Russian destinations (geosite “category-ru”, geoip “ru”)\.
|
||||
**Type:** boolean\
|
||||
**Default:** `true`
|
||||
|
||||
<a id="services-proxy-suite-inbounds-routing-blocktorrent"></a>
|
||||
## services\.proxy-suite\.inbounds\.routing\.blockTorrent
|
||||
|
||||
Block BitTorrent: connections XRay’s sniffing recognizes by the peers’ handshake, and µTP\.
|
||||
Not trackers or DHT, nor what a client encrypts (MSE): it makes downloading slow, not
|
||||
impossible\. Hosters act on the copyright notices torrents bring\. Listeners given as raw
|
||||
XRay JSON need sniffing on for it\.
|
||||
|
||||
**Type:** boolean\
|
||||
**Default:** `true`
|
||||
|
||||
<a id="services-proxy-suite-inbounds-routing-proxy-domains"></a>
|
||||
## services\.proxy-suite\.inbounds\.routing\.proxy\.domains
|
||||
|
||||
@@ -1427,6 +1702,25 @@ Group of the web server that serves the subscription files\.
|
||||
**Default:** `"nginx"`\
|
||||
**Example:** `"caddy"`
|
||||
|
||||
<a id="services-proxy-suite-inbounds-subscriptions-keyfile"></a>
|
||||
## services\.proxy-suite\.inbounds\.subscriptions\.keyFile
|
||||
|
||||
The key the subscription tokens are an HMAC under\. Changing it changes every user’s
|
||||
URL\.
|
||||
|
||||
- ` null `: generated on first start and kept in the state directory
|
||||
(inbounds/subscription-key), where ` proxy-ctl inbounds export ` takes it from\.
|
||||
- a file with a secret, such as ` openssl rand -hex 32 `: that one, read at start and
|
||||
at each runtime change\.
|
||||
- ` false `: no key\. A token is a hash of the user’s name and credentials alone, as
|
||||
before there was a key: whoever learns one of a user’s links can work out their
|
||||
subscription URL, and from it every other link of theirs\. For a server that gave
|
||||
URLs out before\.
|
||||
|
||||
**Type:** null or value false (singular enum) or string\
|
||||
**Default:** `null`\
|
||||
**Example:** `"/run/secrets/inbounds-subscription-key"`
|
||||
|
||||
<a id="services-proxy-suite-inbounds-users"></a>
|
||||
## services\.proxy-suite\.inbounds\.users
|
||||
|
||||
@@ -1489,6 +1783,78 @@ File with the password\.
|
||||
**Default:** `null`\
|
||||
**Example:** `"/run/secrets/proxy-inbound-password"`
|
||||
|
||||
<a id="services-proxy-suite-inbounds-users-name-policy-enabled"></a>
|
||||
## services\.proxy-suite\.inbounds\.users\.\<name>\.policy\.enabled
|
||||
|
||||
Whether the user may connect\. Needs ` inbounds.manager `, as every ` policy ` field does\.
|
||||
|
||||
**Type:** boolean\
|
||||
**Default:** `true`
|
||||
|
||||
<a id="services-proxy-suite-inbounds-users-name-policy-expiresafter"></a>
|
||||
## services\.proxy-suite\.inbounds\.users\.\<name>\.policy\.expiresAfter
|
||||
|
||||
A term that starts with the user’s first connection, for access sold ahead: seconds,
|
||||
or a number with m, h, d or w\. Until they connect the user is on hold, and when
|
||||
they do ` expiresAt ` is set to that much later\. An ` expiresAt ` given wins\.
|
||||
|
||||
**Type:** null or positive integer, meaning >0, or string matching the pattern \[0-9]+\[mhdw]\
|
||||
**Default:** `null`\
|
||||
**Example:** `"30d"`
|
||||
|
||||
<a id="services-proxy-suite-inbounds-users-name-policy-expiresat"></a>
|
||||
## services\.proxy-suite\.inbounds\.users\.\<name>\.policy\.expiresAt
|
||||
|
||||
When the user’s access ends: a date (the end of that day, local time), an ISO time,
|
||||
or a Unix time\. Their connections are cut then, and their subscription still says
|
||||
when it ended\.
|
||||
|
||||
**Type:** null or unsigned integer, meaning >=0, or string matching the pattern \[0-9]{4}-\[0-9]{2}-\[0-9]{2}(\[T ]\[0-9:\.]+(\[±]\[0-9:]+|Z)?)?\
|
||||
**Default:** `null`\
|
||||
**Example:** `"2026-12-31"`
|
||||
|
||||
<a id="services-proxy-suite-inbounds-users-name-policy-iplimit"></a>
|
||||
## services\.proxy-suite\.inbounds\.users\.\<name>\.policy\.ipLimit
|
||||
|
||||
How many addresses may use the user at once\. The ones past it that came last are
|
||||
banned for ` inbounds.manager.ipLimit.banTime ` from the user’s ports\. Not on
|
||||
AmneziaWG, whose peer has one address anyway, nor behind a PROXY-protocol front\.
|
||||
|
||||
**Type:** null or (positive integer, meaning >0)\
|
||||
**Default:** `null`\
|
||||
**Example:** `2`
|
||||
|
||||
<a id="services-proxy-suite-inbounds-users-name-policy-speedlimit"></a>
|
||||
## services\.proxy-suite\.inbounds\.users\.\<name>\.policy\.speedLimit
|
||||
|
||||
Speed limit in bits per second, decimal (k, M, G): one rate for both ways, or
|
||||
“down/up”\. Needs ` inbounds.manager.speedLimits.enable `\. On socks and http listeners
|
||||
it does not apply\.
|
||||
|
||||
**Type:** null or string matching the pattern \[0-9]+(\\\.\[0-9]+)?\[kKMG]?(/\[0-9]+(\\\.\[0-9]+)?\[kKMG]?)?\
|
||||
**Default:** `null`\
|
||||
**Example:** `"20M/5M"`
|
||||
|
||||
<a id="services-proxy-suite-inbounds-users-name-policy-trafficlimit"></a>
|
||||
## services\.proxy-suite\.inbounds\.users\.\<name>\.policy\.trafficLimit
|
||||
|
||||
Traffic allowance, up and down together: bytes, or with K, M, G, T (binary units, as
|
||||
clients show them)\. Past it the user is switched off until the period renews or the
|
||||
traffic is reset\.
|
||||
|
||||
**Type:** null or unsigned integer, meaning >=0, or string matching the pattern \[0-9]+(\\\.\[0-9]+)?\[KMGTP]?(i?B)?\
|
||||
**Default:** `null`\
|
||||
**Example:** `"50G"`
|
||||
|
||||
<a id="services-proxy-suite-inbounds-users-name-policy-trafficperiod"></a>
|
||||
## services\.proxy-suite\.inbounds\.users\.\<name>\.policy\.trafficPeriod
|
||||
|
||||
How often the allowance renews, at local midnight: daily, weekly, or monthly on the
|
||||
day the count began\. ` null `: never; only a reset starts it over\.
|
||||
|
||||
**Type:** null or one of “daily”, “weekly”, “monthly”\
|
||||
**Default:** `null`
|
||||
|
||||
<a id="services-proxy-suite-inbounds-users-name-presharedkeyfile"></a>
|
||||
## services\.proxy-suite\.inbounds\.users\.\<name>\.presharedKeyFile
|
||||
|
||||
|
||||
@@ -91,11 +91,52 @@ services.proxy-suite = {
|
||||
accessLog = false;
|
||||
enable = false;
|
||||
listeners = { };
|
||||
manager = {
|
||||
api = {
|
||||
group = null;
|
||||
listen = null;
|
||||
tokensFile = null;
|
||||
};
|
||||
deleteExpiredAfter = null;
|
||||
enable = false;
|
||||
interval = 30;
|
||||
ipLimit = {
|
||||
banTime = 600;
|
||||
};
|
||||
notify = {
|
||||
expiryDays = [
|
||||
3
|
||||
1
|
||||
];
|
||||
trafficPercent = [
|
||||
80
|
||||
100
|
||||
];
|
||||
};
|
||||
speedLimits = {
|
||||
enable = false;
|
||||
slots = 512;
|
||||
};
|
||||
subscriptions = {
|
||||
enable = config.services.proxy-suite.inbounds.shareLinks;
|
||||
group = config.services.proxy-suite.inbounds.subscriptions.group;
|
||||
listen = null;
|
||||
profileTitle = "{user}";
|
||||
supportUrl = null;
|
||||
updateInterval = 12;
|
||||
webPageUrl = null;
|
||||
};
|
||||
webhooks = [ ];
|
||||
};
|
||||
openFirewall = true;
|
||||
package = ‹proxy-suite's xray (pkgs/xray.nix)›;
|
||||
routing = {
|
||||
blockPorts = [
|
||||
25
|
||||
];
|
||||
blockPrivate = true;
|
||||
blockRu = true;
|
||||
blockTorrent = true;
|
||||
proxy = {
|
||||
domains = [ ];
|
||||
geoips = [ ];
|
||||
@@ -125,6 +166,7 @@ services.proxy-suite = {
|
||||
baseUrl = null;
|
||||
enable = false;
|
||||
group = "nginx";
|
||||
keyFile = null;
|
||||
};
|
||||
users = { };
|
||||
};
|
||||
@@ -293,6 +335,7 @@ services.proxy-suite = {
|
||||
};
|
||||
xray = {
|
||||
package = ‹proxy-suite's xray (pkgs/xray.nix)›;
|
||||
xhttpXmux = null;
|
||||
};
|
||||
};
|
||||
sshProxy = {
|
||||
@@ -359,6 +402,7 @@ services.proxy-suite = {
|
||||
clientOnly = true;
|
||||
enable = false;
|
||||
extraConfig = "";
|
||||
keepAwake = false;
|
||||
lyrebirdPackage = pkgs.lyrebird;
|
||||
onionService = {
|
||||
enable = false;
|
||||
|
||||
@@ -140,6 +140,7 @@ Part of the [proxy-suite options reference](./index.md).
|
||||
- [url](#services-proxy-suite-proxy-urltest-url)
|
||||
- xray
|
||||
- [package](#services-proxy-suite-proxy-xray-package)
|
||||
- [xhttpXmux](#services-proxy-suite-proxy-xray-xhttpxmux)
|
||||
|
||||
<a id="services-proxy-suite-proxy-enable"></a>
|
||||
## services\.proxy-suite\.proxy\.enable
|
||||
@@ -1213,3 +1214,28 @@ XRay package, for the “xray” and “hybrid” backends\.
|
||||
**Type:** package\
|
||||
**Default:** proxy-suite’s ` xray ` (` pkgs/xray.nix `)\
|
||||
**Example:** `pkgs.xray`
|
||||
|
||||
<a id="services-proxy-suite-proxy-xray-xhttpxmux"></a>
|
||||
## services\.proxy-suite\.proxy\.xray\.xhttpXmux
|
||||
|
||||
XRay’s ` xmux ` for every XHTTP outbound whose link sets none (in its ` extra `): how
|
||||
its connections are spread over HTTP/2 or HTTP/3 connections to the server, and how
|
||||
soon a dead one is noticed\. XRay notices a connection that stopped answering only by
|
||||
` hKeepAlivePeriod `’s ping: after that many seconds without a frame, plus 15 for the
|
||||
ping, default 45, so a minute in which everything on it hangs, new connections too\.
|
||||
XRay applies its own defaults (` maxConnections ` 3, ` hMaxRequestTimes ` “600-900”,
|
||||
` hMaxReusableSecs ` “1800-3000”) only to an empty ` xmux `: give them here too\.
|
||||
` null `: XRay’s defaults\.
|
||||
|
||||
**Type:** null or (attribute set of (signed integer or string matching the pattern \[0-9]+(-\[0-9]+)?))\
|
||||
**Default:** `null`\
|
||||
**Example:**
|
||||
|
||||
```nix
|
||||
{
|
||||
hKeepAlivePeriod = 10;
|
||||
hMaxRequestTimes = "600-900";
|
||||
hMaxReusableSecs = "1800-3000";
|
||||
maxConnections = 3;
|
||||
}
|
||||
```
|
||||
@@ -15,6 +15,7 @@ Part of the [proxy-suite options reference](./index.md).
|
||||
- [lines](#services-proxy-suite-tor-bridges-lines)
|
||||
- [clientOnly](#services-proxy-suite-tor-clientonly)
|
||||
- [extraConfig](#services-proxy-suite-tor-extraconfig)
|
||||
- [keepAwake](#services-proxy-suite-tor-keepawake)
|
||||
- [lyrebirdPackage](#services-proxy-suite-tor-lyrebirdpackage)
|
||||
- onionService
|
||||
- [enable](#services-proxy-suite-tor-onionservice-enable)
|
||||
@@ -101,6 +102,17 @@ Extra torrc lines\.
|
||||
''
|
||||
```
|
||||
|
||||
<a id="services-proxy-suite-tor-keepawake"></a>
|
||||
## services\.proxy-suite\.tor\.keepAwake
|
||||
|
||||
Never let Tor go dormant\. By default it does after a day without use, and from then on
|
||||
only rebuilds its circuits when the next connection comes: the first \.onion after a quiet
|
||||
spell may wait long enough to fail\. Turn on where clients expect \.onion at once, as on a
|
||||
server whose inbounds route it\. A dormant Tor also starts dormant again; this wakes it\.
|
||||
|
||||
**Type:** boolean\
|
||||
**Default:** `false`
|
||||
|
||||
<a id="services-proxy-suite-tor-lyrebirdpackage"></a>
|
||||
## services\.proxy-suite\.tor\.lyrebirdPackage
|
||||
|
||||
|
||||
+11
-5
@@ -315,7 +315,9 @@ Extra IPs or CIDRs to unblock\.
|
||||
## services\.proxy-suite\.zapret\.zapret2\.autoHostlist\.enable
|
||||
|
||||
Learn blocked sites: after ` failThreshold ` failed connections, a site is treated as
|
||||
blocked\. When off, only ` zapret2.domains ` and ` proxy-ctl zapret auto add ` are used\.
|
||||
blocked\. When off, only ` zapret2.domains ` and ` proxy-ctl zapret auto add ` are used:
|
||||
the sites already learned are kept but ignored, by zapret2 and ` zapret.directSync `
|
||||
alike, until it is back on\. Each site’s strategy is still remembered\.
|
||||
|
||||
**Type:** boolean\
|
||||
**Default:** `true`
|
||||
@@ -326,7 +328,9 @@ blocked\. When off, only ` zapret2.domains ` and ` proxy-ctl zapret auto add ` a
|
||||
Learn with proxy-suite’s detector instead of nfqws2’s\. It also learns sites blocked
|
||||
only some of the time (a working connection no longer clears the failures before it),
|
||||
downloads that stall partway (the 16 KB cutoff), and requests that never get an
|
||||
answer\. Learned sites are logged with ` strategyLog `\. Only with the source’s own
|
||||
answer\. It also follows learned sites past the first 4 KB a strategy is judged on:
|
||||
one whose downloads keep stalling keeps the proxy’s route (` zapret.directSync `)\.
|
||||
Learned sites are logged with ` strategyLog `\. Only with the source’s own
|
||||
` profiles `, and for TLS: nfqws2-keenetic no longer learns plain HTTP sites\.
|
||||
|
||||
**Type:** boolean\
|
||||
@@ -409,9 +413,11 @@ Extra fake payloads by name (blob=\<name>): a file in zapret2’s files/fake, or
|
||||
## services\.proxy-suite\.zapret\.zapret2\.cutoff\.enable
|
||||
|
||||
Work around ISPs that cut TLS to some hosting networks after about 16 KB, which no
|
||||
strategy fixes\. A daily probe finds the affected networks and a whitelisted name that
|
||||
gets through for each\. Only with ` strategySource = "z2k" `\. Each run makes thousands of
|
||||
short direct connections\. ` proxy-ctl zapret cutoff ` shows the results\.
|
||||
strategy fixes\. A daily probe finds the affected networks, and with
|
||||
` strategySource = "z2k" ` (and its own ` profiles `) a whitelisted name that gets
|
||||
through for each, which z2k puts into a fake ClientHello\. Otherwise no name is
|
||||
searched for, and every affected network is left to ` proxyFallback `\. Each run makes
|
||||
thousands of short direct connections\. ` proxy-ctl zapret cutoff ` shows the results\.
|
||||
|
||||
**Type:** boolean\
|
||||
**Default:** `true`
|
||||
|
||||
@@ -4,6 +4,8 @@
|
||||
enable = true;
|
||||
baseUrl = "https://vpn.example.com/sub";
|
||||
};
|
||||
services.nginx.virtualHosts."vpn.example.com".locations."/sub/".alias =
|
||||
"/run/proxy-suite-inbounds/subscriptions/";
|
||||
services.nginx.virtualHosts."vpn.example.com".locations."/sub/" = {
|
||||
alias = "/run/proxy-suite-inbounds/subscriptions/";
|
||||
extraConfig = "access_log off;"; # the token is the URL's secret
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
{ config, lib, pkgs, ... }:
|
||||
{
|
||||
services.proxy-suite.inbounds = {
|
||||
manager = {
|
||||
enable = true;
|
||||
speedLimits.enable = true; # nftables, and proxy-suite's XRay patch
|
||||
};
|
||||
# Declared users take a policy in the config; runtime ones get theirs from proxy-ctl or the API.
|
||||
users.phone.policy = {
|
||||
expiresAt = "2026-12-31";
|
||||
trafficLimit = "100G";
|
||||
trafficPeriod = "monthly";
|
||||
ipLimit = 2;
|
||||
speedLimit = "50M/10M"; # down/up, bits per second
|
||||
};
|
||||
};
|
||||
}
|
||||
@@ -101,6 +101,12 @@ outbound, a subscription URL a subscription. An AmneziaWG `vpn://` link or a who
|
||||
becomes a global profile, or an outbound when pasted onto the Outbounds tab. See
|
||||
[Use an AmneziaWG config](./amneziawg.md).
|
||||
|
||||
The app also opens `proxy-suite://install-config?url=<subscription URL>` links, which the
|
||||
subscription page of a proxy-suite server offers on Linux: it shows the `proxy subs add` it
|
||||
would run and waits for you to confirm it. The link's `name` becomes the subscription's tag
|
||||
(`VPN alice` as `VPN-alice`, with `-2` after it when taken); without one, it is named after
|
||||
the URL's host.
|
||||
|
||||
Adding a rule, an outbound, a group, a listener or a user opens a form with one field per
|
||||
parameter. Optional fields are marked, and the values the field knows (outbounds, users,
|
||||
listeners, strategies) are offered: in the TUI, → completes one, and in the app, a list beside
|
||||
|
||||
+181
-2
@@ -101,12 +101,22 @@ services.proxy-suite.inbounds.subscriptions = {
|
||||
enable = true;
|
||||
baseUrl = "https://vpn.example.com/sub";
|
||||
};
|
||||
services.nginx.virtualHosts."vpn.example.com".locations."/sub/".alias =
|
||||
"/run/proxy-suite-inbounds/subscriptions/";
|
||||
services.nginx.virtualHosts."vpn.example.com".locations."/sub/" = {
|
||||
alias = "/run/proxy-suite-inbounds/subscriptions/";
|
||||
extraConfig = "access_log off;"; # the token is the URL's secret
|
||||
};
|
||||
```
|
||||
|
||||
Then `proxy-ctl inbounds sub phone --qr` prints that user's subscription.
|
||||
|
||||
The token at the end of the URL is all that guards a subscription. It is an HMAC under a key
|
||||
generated on first start (/var/lib/proxy-suite/inbounds/subscription-key, carried by
|
||||
`proxy-ctl inbounds export`), or under `subscriptions.keyFile` when you keep your own. A
|
||||
server that handed out URLs before there was a key keeps them with
|
||||
`subscriptions.keyFile = false`: its tokens stay a hash of the user's name and
|
||||
credentials, which anyone who has one of the user's links can work out, and with it the rest
|
||||
of their links. Turning the key on later changes every user's URL.
|
||||
|
||||
## Add users and listeners at runtime
|
||||
|
||||
With `inbounds.runtime`, users and listeners can be added with `proxy-ctl`, the TUI or the app,
|
||||
@@ -144,10 +154,179 @@ up is refused, and anything that stops working later (a certificate removed from
|
||||
say) is left out with a warning in `proxy-ctl logs proxy-suite-inbounds` while the rest runs.
|
||||
Without root, members of `userControl.group` need the `inbounds` scope.
|
||||
|
||||
## Policies: expiry, traffic, devices, speed
|
||||
|
||||
`inbounds.manager` runs a daemon that keeps each user's policy and applies it to the running
|
||||
inbounds without a restart: users switched off, out of time or out of traffic leave XRay
|
||||
through its API (their open connections are cut), the others keep theirs.
|
||||
|
||||
```nix
|
||||
services.proxy-suite.inbounds = {
|
||||
manager = {
|
||||
enable = true;
|
||||
speedLimits.enable = true; # nftables, and proxy-suite's XRay patch
|
||||
};
|
||||
# Declared users take a policy in the config; runtime ones get theirs from proxy-ctl or the API.
|
||||
users.phone.policy = {
|
||||
expiresAt = "2026-12-31";
|
||||
trafficLimit = "100G";
|
||||
trafficPeriod = "monthly";
|
||||
ipLimit = 2;
|
||||
speedLimit = "50M/10M"; # down/up, bits per second
|
||||
};
|
||||
};
|
||||
```
|
||||
|
||||
```sh
|
||||
proxy-ctl inbounds users add alice --listener vless-reality --expires +30d --traffic 50G --period monthly --ips 2
|
||||
proxy-ctl inbounds users # status, traffic used of the allowance, expiry
|
||||
proxy-ctl inbounds users show alice
|
||||
proxy-ctl inbounds users set alice --speed 20M/5M
|
||||
proxy-ctl inbounds users extend alice 30d # from the expiry, or from now if it passed
|
||||
proxy-ctl inbounds users extend alice 30d --reset # a renewal: the traffic starts over too
|
||||
proxy-ctl inbounds users add bob --listener vless-reality --on-hold 30d --traffic 50G
|
||||
proxy-ctl inbounds users reset alice # start the traffic over
|
||||
proxy-ctl inbounds users rotate-sub alice # a new subscription URL; the old one stops answering
|
||||
proxy-ctl inbounds users disable alice
|
||||
proxy-ctl inbounds bans # addresses past an ipLimit, banned for a while
|
||||
```
|
||||
|
||||
What a policy holds:
|
||||
|
||||
- `expiresAt`: past it the user is switched off, and their subscription still says when.
|
||||
- `expiresAfter` (`--on-hold`): a term that starts with the first connection, for access sold
|
||||
ahead. Until the user connects they are on hold; then `expiresAt` is set that much later
|
||||
(event user.activated). `extend` lengthens the term while on hold. An `expiresAt` given wins.
|
||||
- `trafficLimit`, `trafficPeriod`: up and down together, counted from the day the user came
|
||||
or was reset; a period renews at local midnight, monthly on that day of the month.
|
||||
- `ipLimit`: past it, the addresses that came last are banned from the user's ports for
|
||||
`manager.ipLimit.banTime`. Not on AmneziaWG (a peer has one address anyway), nor behind
|
||||
a PROXY-protocol front.
|
||||
- `speedLimit`: XRay marks the sockets its exits dial for the user with their slot, and
|
||||
nftables polices that mark both ways; AmneziaWG peers by their tunnel address.
|
||||
- `meta`: strings for a bot of yours, such as a Telegram ID.
|
||||
|
||||
Runtime users expired long ago can go by themselves: `manager.deleteExpiredAfter = "30d"`
|
||||
deletes each that long after its expiry (event user.deleted, with the reason). Declared users
|
||||
stay.
|
||||
|
||||
Subscriptions served by the manager carry the traffic, the allowance and the expiry
|
||||
(`subscription-userinfo`), which v2rayN, Hiddify, Happ and Streisand show, plus a title and
|
||||
an update interval. The same URL answers each client in what it reads:
|
||||
|
||||
- Clash and mihomo apps (Clash Meta, Clash Verge, FlClash, Stash): a mihomo config, the
|
||||
user's servers in a group that picks the fastest and one to choose by hand.
|
||||
- The sing-box apps (SFA, SFI, SFM): a sing-box config with TUN.
|
||||
- A browser: a page with the state, traffic and expiry, a QR code, buttons that add the
|
||||
subscription to an app, and each link to copy. In Russian when the browser asks for it.
|
||||
The buttons for the browser's system come first (Android, iOS, macOS, Windows, Linux), the
|
||||
rest under "Other apps": Happ, Hiddify, v2rayNG, Streisand, Karing, sing-box, Clash (Clash
|
||||
Meta, FlClash, Clash Verge Rev, Clash Party, Stash) and, on Linux, proxy-suite's own desktop
|
||||
app (`gui.enable`), which asks before it adds the subscription.
|
||||
- Everything else, Hiddify included: base64 of the links, as before.
|
||||
|
||||
`?format=base64|links|clash|sing-box|html` picks one by hand. Listeners only XRay dials
|
||||
(XHTTP, ECH) are left out of the Clash and sing-box configs, and AmneziaWG out of all of them.
|
||||
The page's QR code, drawn by the browser, is of `inbounds.subscriptions.baseUrl`; without it,
|
||||
of the address the browser asked for, as the web server passes it on in `Host` and
|
||||
`X-Forwarded-Proto`. Set `baseUrl`: then no header decides what the page offers. The page
|
||||
runs nothing but its own script and stylesheet (a CSP with their hashes), and no answer is
|
||||
cached, sent on as a referrer or indexed.
|
||||
|
||||
Point the web server at the manager's socket instead of the static files; the tokens and so
|
||||
the URLs stay the same. Keep the tokens out of its access log, and slow down whoever guesses:
|
||||
|
||||
```nix
|
||||
services.nginx.appendHttpConfig = "limit_req_zone $binary_remote_addr zone=sub:1m rate=30r/m;";
|
||||
services.nginx.virtualHosts."vpn.example.com".locations."/sub/" = {
|
||||
proxyPass = "http://unix:/run/proxy-suite-inbounds-manager/sub.sock:";
|
||||
recommendedProxySettings = true; # Host, X-Forwarded-Proto, X-Real-IP
|
||||
extraConfig = ''
|
||||
access_log off;
|
||||
limit_req zone=sub burst=20 nodelay;
|
||||
'';
|
||||
};
|
||||
```
|
||||
|
||||
A token that is not there gets a 404 and a line in the manager's journal, at most one a minute
|
||||
per address (X-Real-IP from the web server), with how many came since:
|
||||
`subscription: unknown token from 203.0.113.7 (12 more since the last line)`. A fail2ban
|
||||
filter on it bans whoever keeps guessing.
|
||||
|
||||
`proxy-ctl inbounds users rotate-sub <name>` gives a user a new URL with their credentials
|
||||
left as they are, for a URL that got out; their clients need the new one. It stays with the
|
||||
user through an export and import.
|
||||
|
||||
Worth knowing:
|
||||
|
||||
- A user switched off by the manager loses their open connections too: TCP ones are closed
|
||||
(`ss -K`), UDP ones (Hysteria2, XHTTP over HTTP/3) dropped for a while. Others behind the
|
||||
same address reconnect once. Without the manager, removing a runtime user cuts its TCP
|
||||
connections only.
|
||||
- Giving a user a speed limit, or taking it away, changes their XRay level: their
|
||||
connections drop once.
|
||||
- An exit whose own JSON or URL sets `sockopt.mark` keeps it, and its users are not
|
||||
speed-limited there. Socks and http listeners take no speed limit either.
|
||||
|
||||
### The API
|
||||
|
||||
The manager answers HTTP+JSON on `/run/proxy-suite-inbounds-manager/api.sock` (root, and
|
||||
`userControl.group` with the "inbounds" scope, or `manager.api.group`), and with
|
||||
`manager.api.listen` and bearer tokens over TCP, for a bot elsewhere (behind TLS):
|
||||
|
||||
```sh
|
||||
curl --unix-socket /run/proxy-suite-inbounds-manager/api.sock http://x/api/v1/users
|
||||
curl --unix-socket /run/proxy-suite-inbounds-manager/api.sock http://x/api/v1/users \
|
||||
-d '{"name": "bob", "listeners": ["vless-reality"], "policy": {"expiresAt": "+30d", "trafficLimit": "50G"}}'
|
||||
```
|
||||
|
||||
| Call | What |
|
||||
| --- | --- |
|
||||
| `GET /api/v1/users`, `GET /api/v1/users/<name>` | users: policy, status and why, traffic, online addresses, subscription |
|
||||
| `POST /api/v1/users` | `{name, listeners, order?, policy?}`: a runtime user, secrets generated |
|
||||
| `PATCH /api/v1/users/<name>` | policy fields, and `unset: [fields]` to drop runtime ones |
|
||||
| `DELETE /api/v1/users/<name>` | a runtime user, and their policy |
|
||||
| `POST /api/v1/users/<name>/enable`, `/disable`, `/reset-traffic` | |
|
||||
| `POST /api/v1/users/<name>/extend` | `{by: "30d"}` or `{until: "2027-01-31"}`, and `resetTraffic: true` to start the traffic over |
|
||||
| `POST /api/v1/users/<name>/rotate-subscription` | a new subscription URL; the old one stops answering |
|
||||
| `PUT /api/v1/users/<name>/listeners` | `{listeners: [...]}` |
|
||||
| `GET /api/v1/users/<name>/links` | share links and client configs |
|
||||
| `GET /api/v1/listeners`, `/online`, `/bans`; `DELETE /api/v1/bans/<address>` | |
|
||||
| `GET /api/v1/export`, `POST /api/v1/import` | see below |
|
||||
| `GET /api/v1/events` | the latest events |
|
||||
|
||||
Sizes take K, M, G, T (binary), speeds k, M, G bits per second, times a date, an ISO time,
|
||||
a Unix time or `+30d`. Errors come as `{"error": "..."}` with a 4xx status.
|
||||
|
||||
`manager.webhooks` POST each event as JSON (`{event, user, at, data}`), signed with
|
||||
`X-Proxy-Suite-Signature: sha256=<HMAC>` when given a secret: user.created, user.deleted,
|
||||
user.updated, user.enabled, user.disabled (with the reasons), user.reset, user.activated
|
||||
(a term on hold started), user.traffic (80 % and 100 % of the allowance), user.expiring
|
||||
(3 days and 1 day before) and user.ip-limit.
|
||||
|
||||
### Moving to another server
|
||||
|
||||
```sh
|
||||
proxy-ctl inbounds export users.json # on the old one: 0600, it holds every secret
|
||||
proxy-ctl inbounds import users.json # on the new one, with the same listeners
|
||||
```
|
||||
|
||||
The export holds the runtime users and listeners (their UUIDs, passwords and REALITY keys),
|
||||
the policies and what they are measured against, the AmneziaWG listeners' keys and
|
||||
addresses, the Salamander passwords proxy-suite generated, and the traffic counted. Secrets
|
||||
the config names by file (sops and the like) are not in it. Runtime users and listeners
|
||||
already on the new server are refused and policies already there kept, unless `--replace`;
|
||||
an AmneziaWG listener that has a key already keeps it unless `--replace`, which its existing
|
||||
clients need.
|
||||
|
||||
## Good to know
|
||||
|
||||
- Clients cannot reach this host's LAN or Russian sites by default
|
||||
(`inbounds.routing.blockPrivate`, `blockRu`).
|
||||
- Nor, by default, BitTorrent or port 25 (`routing.blockTorrent`, `routing.blockPorts`):
|
||||
copyright notices and spam are what hosters close servers over. XRay's sniffing catches
|
||||
the peers' handshake, not trackers, DHT or encrypted connections: torrents get slow, not
|
||||
impossible. Should a complaint come anyway, `inbounds.accessLog` logs who went where.
|
||||
- Through "direct", clients reach this host itself only on the listeners' ports and
|
||||
`inbounds.serverPorts` (80/443 with subscriptions), whatever it listens on. Its addresses
|
||||
are read when the inbounds start: restart them after the address changes.
|
||||
|
||||
Generated
+3
-3
@@ -38,11 +38,11 @@
|
||||
},
|
||||
"nixpkgs": {
|
||||
"locked": {
|
||||
"lastModified": 1791179034,
|
||||
"narHash": "sha256-Ni0LBydzaCi8oek12r4mVreuFHqYlM1eTD6SfiENKfw=",
|
||||
"lastModified": 1791594108,
|
||||
"narHash": "sha256-XK4KceonkwD8LuMAt/vNrz982mXJM5jeHAxMwsUXXAQ=",
|
||||
"owner": "NixOS",
|
||||
"repo": "nixpkgs",
|
||||
"rev": "494ce7fd23ff6a5dff39e1fb11e9b6f2ac74bf25",
|
||||
"rev": "6510408d147d8c5e6d76043e899e9251756f6a75",
|
||||
"type": "github"
|
||||
},
|
||||
"original": {
|
||||
|
||||
@@ -146,6 +146,7 @@
|
||||
tg-ws-proxy
|
||||
whitelist-bypass
|
||||
wireproxy-awg
|
||||
z2k-detect
|
||||
zapret2
|
||||
;
|
||||
xray = import ./pkgs/xray.nix { inherit pkgs; };
|
||||
|
||||
@@ -129,16 +129,29 @@ in
|
||||
}
|
||||
];
|
||||
stats = { };
|
||||
# Handler and Routing: users, rules and outbounds changed in place (scripts/inbound_apply.py).
|
||||
api = {
|
||||
tag = "api";
|
||||
services = [ "StatsService" ];
|
||||
services = [
|
||||
"StatsService"
|
||||
"HandlerService"
|
||||
"RoutingService"
|
||||
];
|
||||
};
|
||||
policy = {
|
||||
levels."0" = {
|
||||
statsUserUplink = true;
|
||||
statsUserDownlink = true;
|
||||
statsUserOnline = true;
|
||||
};
|
||||
# Level 0, and with speed limits one more per slot: a limited user's level, which the
|
||||
# exits mark its sockets with. A level XRay has no policy for would count no stats.
|
||||
levels =
|
||||
let
|
||||
level = {
|
||||
statsUserUplink = true;
|
||||
statsUserDownlink = true;
|
||||
statsUserOnline = true;
|
||||
};
|
||||
slots =
|
||||
if derived.proxyInboundsSpeedLimits then derived.proxyInboundsManagerCfg.speedLimits.slots else 0;
|
||||
in
|
||||
lib.genAttrs (map toString (lib.range 0 slots)) (_: level);
|
||||
system = {
|
||||
statsInboundUplink = true;
|
||||
statsInboundDownlink = true;
|
||||
|
||||
@@ -114,6 +114,18 @@ let
|
||||
# appear here only as paths; the script reads them at runtime.
|
||||
proxyInboundsSpec = {
|
||||
runtime = if derived.proxyInboundsRuntimeEnabled then runtimeSpec else null;
|
||||
# inbounds.manager, for inbound_policy.py: where the policies and what they are measured
|
||||
# against are. null: every user active, at level 0, as without it.
|
||||
manager =
|
||||
if derived.proxyInboundsManagerEnabled then
|
||||
{
|
||||
policyFile = "${derived.constants.inboundsManagerDir}/policy.json";
|
||||
stateFile = "${derived.constants.inboundsManagerDir}/state.json";
|
||||
statsFile = derived.constants.inboundStatsFile;
|
||||
speedLimits = derived.proxyInboundsSpeedLimits;
|
||||
}
|
||||
else
|
||||
null;
|
||||
# Every declared user, on a listener or not, and their serverSource numbers: what
|
||||
# `proxy-ctl inbounds users` lists, and what runtime users go around. Secrets as paths.
|
||||
users = derived.proxyInboundsCfg.users;
|
||||
@@ -126,6 +138,18 @@ let
|
||||
};
|
||||
serverAddress = derived.proxyInboundsCfg.serverAddress;
|
||||
shareLinks = derived.proxyInboundsCfg.shareLinks;
|
||||
# The config's key (a path), or where the generated one is kept (null: the renderer makes
|
||||
# it on first start), or neither (false).
|
||||
subscriptionKeyFile =
|
||||
let
|
||||
keyFile = derived.proxyInboundsCfg.subscriptions.keyFile;
|
||||
in
|
||||
if builtins.isString keyFile then keyFile else null;
|
||||
subscriptionKeyStateFile =
|
||||
if derived.proxyInboundsCfg.subscriptions.keyFile == null then
|
||||
"${cfg.host.stateDir}/inbounds/subscription-key"
|
||||
else
|
||||
null;
|
||||
# Listeners the onion service carries, which get a second set of links to it.
|
||||
onionListeners = map (ib: ib.tag) derived.torOnionInbounds;
|
||||
inherit (inboundRules) sniffDomainsExcluded;
|
||||
|
||||
@@ -323,6 +323,11 @@ let
|
||||
# inbounds.runtime: listeners added with proxy-ctl may exit by these, so everything built
|
||||
# per exit (rules, outbounds, the local proxy, name resolution) is there for them too.
|
||||
proxyInboundsRuntimeEnabled = proxyInboundsEnabled && proxyInboundsCfg.runtime.enable;
|
||||
# inbounds.manager: users' policies kept by a daemon; speed limits need root (nftables).
|
||||
proxyInboundsManagerCfg = proxyInboundsCfg.manager;
|
||||
proxyInboundsManagerEnabled = proxyInboundsEnabled && proxyInboundsManagerCfg.enable;
|
||||
proxyInboundsSpeedLimits =
|
||||
proxyInboundsManagerEnabled && proxyInboundsManagerCfg.speedLimits.enable && cfg.host.privileged;
|
||||
proxyInboundsRuntimeVias = lib.optionals proxyInboundsRuntimeEnabled (
|
||||
lib.unique ([ proxyInboundsCfg.routing.via ] ++ proxyInboundsCfg.runtime.vias ++ [ "block" ])
|
||||
);
|
||||
@@ -639,6 +644,12 @@ let
|
||||
}
|
||||
.${cfg.debug.logLevel};
|
||||
connectionLogEnabled = cfg.enable && clashApiEnabled && cfg.debug.connectionLog.enable;
|
||||
# proxy.xray.xhttpXmux, as a jq step over one XRay outbound: an XHTTP one whose link set no
|
||||
# xmux takes it. JSON is a jq literal.
|
||||
xhttpXmuxJq = lib.optionalString (xrayCfg.xhttpXmux != null) ''
|
||||
| if .streamSettings.network? == "xhttp" and ((.streamSettings.xhttpSettings.extra.xmux? // {}) == {})
|
||||
then .streamSettings.xhttpSettings.extra.xmux = ${builtins.toJSON xrayCfg.xhttpXmux}
|
||||
else . end'';
|
||||
perAppZapretEnabled = perAppZapretCfg.enable;
|
||||
# The global units each per-app backend steps aside for (constants.refuseUnderGlobal), as
|
||||
# systemctl patterns: they stop it as they start, and the standby unit waits them out.
|
||||
@@ -1185,6 +1196,15 @@ let
|
||||
# Loopback listener behind the selector `proxy-ctl proxy outbounds test` switches.
|
||||
outboundTestPort = 18537;
|
||||
inboundStatsFile = "${stateDir}/inbound-stats.json";
|
||||
# inbounds.manager: its policy and state files (root's), its sockets, and its nftables
|
||||
# table (scripts/inbound_netfilter.py). The exits' sockopt.mark when speed limits are on:
|
||||
# the XRay patch's flag (0x40000000) and the base users' levels are added to (0x04000000).
|
||||
inboundsManagerDir = "${stateDir}/inbounds-manager";
|
||||
inboundsManagerRuntimeDir = "${runtimeDir}/proxy-suite-inbounds-manager";
|
||||
inboundsManagerApiSocket = "${runtimeDir}/proxy-suite-inbounds-manager/api.sock";
|
||||
inboundsManagerSubSocket = "${runtimeDir}/proxy-suite-inbounds-manager/sub.sock";
|
||||
inboundLimitsTable = "proxy_suite_inbound_limits";
|
||||
inboundExitMark = 1140850688;
|
||||
# Written by proxy-suite-tor as it starts, before it reaches the network.
|
||||
torOnionHostnameFile = "${stateDir}/tor/onion/hostname";
|
||||
# proxy-ctl tor status|newnym.
|
||||
@@ -1246,6 +1266,7 @@ in
|
||||
singBoxLogLevel
|
||||
xrayLogLevel
|
||||
connectionLogEnabled
|
||||
xhttpXmuxJq
|
||||
singBoxCfg
|
||||
xrayCfg
|
||||
proxyEnabled
|
||||
@@ -1324,6 +1345,9 @@ in
|
||||
proxyInboundsEnabled
|
||||
proxyInbounds
|
||||
proxyInboundsRuntimeEnabled
|
||||
proxyInboundsManagerCfg
|
||||
proxyInboundsManagerEnabled
|
||||
proxyInboundsSpeedLimits
|
||||
proxyInboundsRuntimeVias
|
||||
proxyInboundRuntimePorts
|
||||
proxyInboundRuntimeSinglePorts
|
||||
|
||||
@@ -9,6 +9,7 @@
|
||||
./proxy-tun.nix
|
||||
./proxy-tproxy.nix
|
||||
./inbounds.nix
|
||||
./inbounds-manager.nix
|
||||
./per-app-routing.nix
|
||||
./zapret.nix
|
||||
./zapret2.nix
|
||||
|
||||
@@ -0,0 +1,215 @@
|
||||
{ config, lib, ... }:
|
||||
|
||||
let
|
||||
inherit (lib)
|
||||
literalExpression
|
||||
mkEnableOption
|
||||
mkOption
|
||||
types
|
||||
;
|
||||
cfg = config.services.proxy-suite.inbounds;
|
||||
listenType = types.strMatching "([[][0-9A-Fa-f:.]+[]]|[0-9.]+|localhost):[0-9]{1,5}";
|
||||
# scripts/inbound_manager.py's EVENTS.
|
||||
events = [
|
||||
"user.created"
|
||||
"user.deleted"
|
||||
"user.updated"
|
||||
"user.enabled"
|
||||
"user.disabled"
|
||||
"user.reset"
|
||||
"user.activated"
|
||||
"user.traffic"
|
||||
"user.expiring"
|
||||
"user.ip-limit"
|
||||
];
|
||||
in
|
||||
{
|
||||
# Consumed by scripts/inbound_manager.py (manager.json, service/inbounds-manager.nix) and
|
||||
# scripts/inbound_policy.py (the spec's "manager").
|
||||
options.services.proxy-suite.inbounds.manager = {
|
||||
enable = mkEnableOption "" // {
|
||||
description = ''
|
||||
The inbound manager, a daemon that keeps the users' policies (`inbounds.users.<name>.policy`,
|
||||
and what it is told at runtime): who is switched off, whose time ran out, who used up
|
||||
their traffic, how many addresses and how much speed each may have. It applies them to
|
||||
the running inbounds without a restart, answers an HTTP+JSON API for proxy-ctl and bots,
|
||||
serves subscriptions with the traffic and expiry clients show, and calls webhooks.
|
||||
Users and listeners added through it need `inbounds.runtime`.
|
||||
'';
|
||||
};
|
||||
|
||||
interval = mkOption {
|
||||
type = types.ints.between 5 3600;
|
||||
default = 30;
|
||||
description = "Seconds between two rounds of counting traffic and checking the policies.";
|
||||
};
|
||||
|
||||
api = {
|
||||
group = mkOption {
|
||||
type = types.nullOr types.str;
|
||||
default = null;
|
||||
description = ''
|
||||
Group that may use the API socket, /run/proxy-suite-inbounds-manager/api.sock: all of
|
||||
it, every user's secrets included. `null`: `userControl.group` when it has the
|
||||
"inbounds" scope, root only otherwise.
|
||||
'';
|
||||
example = "vpn-admins";
|
||||
};
|
||||
listen = mkOption {
|
||||
type = types.nullOr listenType;
|
||||
default = null;
|
||||
description = ''
|
||||
Address and port the API also listens on over TCP, for a bot on another host. Plain
|
||||
HTTP: put it on loopback behind a TLS proxy. Needs `tokensFile`; the firewall is not
|
||||
opened for it.
|
||||
'';
|
||||
example = "127.0.0.1:9180";
|
||||
};
|
||||
tokensFile = mkOption {
|
||||
type = types.nullOr types.str;
|
||||
default = null;
|
||||
description = ''
|
||||
File with the bearer tokens the TCP API takes, one per line, "name:token" or the token
|
||||
alone. Read at start.
|
||||
'';
|
||||
example = "/run/secrets/inbounds-manager-tokens";
|
||||
};
|
||||
};
|
||||
|
||||
subscriptions = {
|
||||
enable = mkOption {
|
||||
type = types.bool;
|
||||
default = cfg.shareLinks;
|
||||
defaultText = literalExpression "config.services.proxy-suite.inbounds.shareLinks";
|
||||
description = ''
|
||||
Serve each user's subscription from /run/proxy-suite-inbounds-manager/sub.sock, with the
|
||||
headers clients read their traffic, allowance and expiry from (subscription-userinfo),
|
||||
a title and an update interval. The token is the last part of the path, the same
|
||||
as the static files' (`inbounds.subscriptions`), so their URLs keep working:
|
||||
```nix
|
||||
services.nginx.virtualHosts."vpn.example.com".locations."/sub/".proxyPass =
|
||||
"http://unix:/run/proxy-suite-inbounds-manager/sub.sock:";
|
||||
```
|
||||
'';
|
||||
};
|
||||
group = mkOption {
|
||||
type = types.str;
|
||||
default = cfg.subscriptions.group;
|
||||
defaultText = literalExpression "config.services.proxy-suite.inbounds.subscriptions.group";
|
||||
description = "Group of the web server that connects to the subscription socket.";
|
||||
};
|
||||
listen = mkOption {
|
||||
type = types.nullOr listenType;
|
||||
default = null;
|
||||
description = "Address and port the subscriptions are also served on over TCP, for a web server that cannot reach the socket.";
|
||||
example = "127.0.0.1:9181";
|
||||
};
|
||||
profileTitle = mkOption {
|
||||
type = types.str;
|
||||
default = "{user}";
|
||||
description = "The profile's name in clients; {user} is the user's.";
|
||||
example = "My VPN ({user})";
|
||||
};
|
||||
updateInterval = mkOption {
|
||||
type = types.nullOr types.ints.positive;
|
||||
default = 12;
|
||||
description = "Hours between clients' updates of the subscription (profile-update-interval).";
|
||||
};
|
||||
supportUrl = mkOption {
|
||||
type = types.nullOr types.str;
|
||||
default = null;
|
||||
description = "Where clients send users for help (support-url), such as a Telegram link.";
|
||||
example = "https://t.me/my_vpn_support";
|
||||
};
|
||||
webPageUrl = mkOption {
|
||||
type = types.nullOr types.str;
|
||||
default = null;
|
||||
description = "The service's page (profile-web-page-url).";
|
||||
};
|
||||
};
|
||||
|
||||
speedLimits = {
|
||||
enable = mkEnableOption "" // {
|
||||
description = ''
|
||||
Speed limits (`policy.speedLimit`). XRay marks the sockets its exits dial for a limited
|
||||
user with the user's slot, which proxy-suite's XRay build carries a patch for
|
||||
(pkgs/patches/xray-user-level-mark.patch), and nftables polices each mark's
|
||||
traffic both ways. AmneziaWG peers are policed by their tunnel address. Needs root.
|
||||
'';
|
||||
};
|
||||
slots = mkOption {
|
||||
type = types.ints.between 1 65535;
|
||||
default = 512;
|
||||
description = "How many users may have a speed limit at once: an XRay user level each.";
|
||||
};
|
||||
};
|
||||
|
||||
deleteExpiredAfter = mkOption {
|
||||
type = types.nullOr (types.strMatching "[0-9]+[mhdw]");
|
||||
default = null;
|
||||
description = ''
|
||||
Delete runtime users this long after their `expiresAt`, as `proxy-ctl inbounds users rm`
|
||||
would: their secrets, policy and subscription go. A number with m, h, d or w. Users
|
||||
declared in the config stay. `null`: never.
|
||||
'';
|
||||
example = "30d";
|
||||
};
|
||||
|
||||
ipLimit.banTime = mkOption {
|
||||
type = types.ints.positive;
|
||||
default = 600;
|
||||
description = "Seconds an address past a user's `ipLimit` is banned for.";
|
||||
};
|
||||
|
||||
notify = {
|
||||
trafficPercent = mkOption {
|
||||
type = types.listOf (types.ints.between 1 100);
|
||||
default = [
|
||||
80
|
||||
100
|
||||
];
|
||||
description = "Shares of the traffic allowance used that send a user.traffic event, once per period.";
|
||||
};
|
||||
expiryDays = mkOption {
|
||||
type = types.listOf types.ints.positive;
|
||||
default = [
|
||||
3
|
||||
1
|
||||
];
|
||||
description = "Days before the expiry that send a user.expiring event.";
|
||||
};
|
||||
};
|
||||
|
||||
webhooks = mkOption {
|
||||
type = types.listOf (
|
||||
types.submodule {
|
||||
options = {
|
||||
url = mkOption {
|
||||
type = types.str;
|
||||
description = "URL the events are POSTed to as JSON: {event, user, at, data}.";
|
||||
};
|
||||
events = mkOption {
|
||||
type = types.listOf (types.enum events);
|
||||
default = [ ];
|
||||
description = "Events to send. Empty: all of them.";
|
||||
};
|
||||
secretFile = mkOption {
|
||||
type = types.nullOr types.str;
|
||||
default = null;
|
||||
description = "File with a secret: each body is signed, X-Proxy-Suite-Signature: sha256=<HMAC-SHA256 hex>.";
|
||||
};
|
||||
};
|
||||
}
|
||||
);
|
||||
default = [ ];
|
||||
description = ''
|
||||
Where to tell about users created, deleted, updated, switched off (with why) and back
|
||||
on, their traffic reset, their term started on their first connection (user.activated), thresholds of their allowance, coming expiries and addresses
|
||||
banned past their ipLimit. Retried a few times; a hook that stays down misses them.
|
||||
'';
|
||||
example = literalExpression ''
|
||||
[ { url = "http://127.0.0.1:8088/proxy-suite"; secretFile = "/run/secrets/hook"; } ]
|
||||
'';
|
||||
};
|
||||
};
|
||||
}
|
||||
@@ -106,6 +106,24 @@ in
|
||||
description = "Public URL of the subscription directory, used by `proxy-ctl inbounds sub`.";
|
||||
example = "https://vpn.example.com/sub";
|
||||
};
|
||||
|
||||
keyFile = mkOption {
|
||||
type = types.nullOr (types.either (types.enum [ false ]) types.str);
|
||||
default = null;
|
||||
description = ''
|
||||
The key the subscription tokens are an HMAC under. Changing it changes every user's
|
||||
URL.
|
||||
- `null`: generated on first start and kept in the state directory
|
||||
(inbounds/subscription-key), where `proxy-ctl inbounds export` takes it from.
|
||||
- a file with a secret, such as `openssl rand -hex 32`: that one, read at start and
|
||||
at each runtime change.
|
||||
- `false`: no key. A token is a hash of the user's name and credentials alone, as
|
||||
before there was a key: whoever learns one of a user's links can work out their
|
||||
subscription URL, and from it every other link of theirs. For a server that gave
|
||||
URLs out before.
|
||||
'';
|
||||
example = "/run/secrets/inbounds-subscription-key";
|
||||
};
|
||||
};
|
||||
|
||||
# Mirrors proxy.routing, for traffic arriving from outside instead of from this host.
|
||||
@@ -132,6 +150,25 @@ in
|
||||
addresses (loopback, and its public ones as its interfaces carry them at start) are
|
||||
reachable only on the listener ports and `serverPorts`, whichever `via` a client takes.
|
||||
'';
|
||||
blockTorrent = bool true ''
|
||||
Block BitTorrent: connections XRay's sniffing recognizes by the peers' handshake, and µTP.
|
||||
Not trackers or DHT, nor what a client encrypts (MSE): it makes downloading slow, not
|
||||
impossible. Hosters act on the copyright notices torrents bring. Listeners given as raw
|
||||
XRay JSON need sniffing on for it.
|
||||
'';
|
||||
blockPorts = mkOption {
|
||||
type = types.listOf (types.either types.port (types.strMatching "[0-9]+-[0-9]+"));
|
||||
default = [ 25 ];
|
||||
description = ''
|
||||
Destination ports clients may not reach, TCP and UDP: single ports and "from-to"
|
||||
ranges. Port 25 by default: mail sent straight to other servers, which spam goes
|
||||
out by and hosters close. Mail clients' own ports (465, 587) stay open.
|
||||
'';
|
||||
example = [
|
||||
25
|
||||
"6881-6889"
|
||||
];
|
||||
};
|
||||
|
||||
zapretDirect = bool true "Send zapret hostlist sites direct, so this host's zapret unblocks them. Only for the default `via`. With a direct listener or the XRay backend, only by IP: XRay matches names by what a client puts in its handshake, whatever address it connects to.";
|
||||
|
||||
|
||||
@@ -195,6 +195,28 @@ in
|
||||
example = literalExpression "pkgs.xray";
|
||||
description = ''XRay package, for the "xray" and "hybrid" backends.'';
|
||||
};
|
||||
|
||||
xhttpXmux = mkOption {
|
||||
# A number, or a range XRay picks from at random.
|
||||
type = types.nullOr (types.attrsOf (types.either types.int (types.strMatching "[0-9]+(-[0-9]+)?")));
|
||||
default = null;
|
||||
description = ''
|
||||
XRay's `xmux` for every XHTTP outbound whose link sets none (in its `extra`): how
|
||||
its connections are spread over HTTP/2 or HTTP/3 connections to the server, and how
|
||||
soon a dead one is noticed. XRay notices a connection that stopped answering only by
|
||||
`hKeepAlivePeriod`'s ping: after that many seconds without a frame, plus 15 for the
|
||||
ping, default 45, so a minute in which everything on it hangs, new connections too.
|
||||
XRay applies its own defaults (`maxConnections` 3, `hMaxRequestTimes` "600-900",
|
||||
`hMaxReusableSecs` "1800-3000") only to an empty `xmux`: give them here too.
|
||||
`null`: XRay's defaults.
|
||||
'';
|
||||
example = {
|
||||
maxConnections = 3;
|
||||
hMaxRequestTimes = "600-900";
|
||||
hMaxReusableSecs = "1800-3000";
|
||||
hKeepAlivePeriod = 10;
|
||||
};
|
||||
};
|
||||
};
|
||||
};
|
||||
}
|
||||
@@ -56,6 +56,17 @@ in
|
||||
'';
|
||||
};
|
||||
|
||||
keepAwake = mkOption {
|
||||
type = types.bool;
|
||||
default = false;
|
||||
description = ''
|
||||
Never let Tor go dormant. By default it does after a day without use, and from then on
|
||||
only rebuilds its circuits when the next connection comes: the first .onion after a quiet
|
||||
spell may wait long enough to fail. Turn on where clients expect .onion at once, as on a
|
||||
server whose inbounds route it. A dormant Tor also starts dormant again; this wakes it.
|
||||
'';
|
||||
};
|
||||
|
||||
upstream = mkOption {
|
||||
type = types.enum [
|
||||
"direct"
|
||||
|
||||
@@ -35,6 +35,86 @@ let
|
||||
AmneziaWG tunnel IPv4 address, inside `amneziaWg.subnet`. `null`: the lowest free one,
|
||||
kept for as long as the user exists.
|
||||
'' "10.66.0.10";
|
||||
|
||||
# Read by scripts/inbound_policy.py, with inbounds.manager. What the manager is told at
|
||||
# runtime (`proxy-ctl inbounds users set`, its API) overrides these field by field.
|
||||
policy = {
|
||||
enabled = mkOption {
|
||||
type = types.bool;
|
||||
default = true;
|
||||
description = "Whether the user may connect. Needs `inbounds.manager`, as every `policy` field does.";
|
||||
};
|
||||
expiresAt = mkOption {
|
||||
type = types.nullOr (
|
||||
types.either types.ints.unsigned (
|
||||
types.strMatching "[0-9]{4}-[0-9]{2}-[0-9]{2}([T ][0-9:.]+([+-][0-9:]+|Z)?)?"
|
||||
)
|
||||
);
|
||||
default = null;
|
||||
description = ''
|
||||
When the user's access ends: a date (the end of that day, local time), an ISO time,
|
||||
or a Unix time. Their connections are cut then, and their subscription still says
|
||||
when it ended.
|
||||
'';
|
||||
example = "2026-12-31";
|
||||
};
|
||||
expiresAfter = mkOption {
|
||||
type = types.nullOr (types.either types.ints.positive (types.strMatching "[0-9]+[mhdw]"));
|
||||
default = null;
|
||||
description = ''
|
||||
A term that starts with the user's first connection, for access sold ahead: seconds,
|
||||
or a number with m, h, d or w. Until they connect the user is on hold, and when
|
||||
they do `expiresAt` is set to that much later. An `expiresAt` given wins.
|
||||
'';
|
||||
example = "30d";
|
||||
};
|
||||
trafficLimit = mkOption {
|
||||
type = types.nullOr (
|
||||
types.either types.ints.unsigned (types.strMatching "[0-9]+(\\.[0-9]+)?[KMGTP]?(i?B)?")
|
||||
);
|
||||
default = null;
|
||||
description = ''
|
||||
Traffic allowance, up and down together: bytes, or with K, M, G, T (binary units, as
|
||||
clients show them). Past it the user is switched off until the period renews or the
|
||||
traffic is reset.
|
||||
'';
|
||||
example = "50G";
|
||||
};
|
||||
trafficPeriod = mkOption {
|
||||
type = types.nullOr (
|
||||
types.enum [
|
||||
"daily"
|
||||
"weekly"
|
||||
"monthly"
|
||||
]
|
||||
);
|
||||
default = null;
|
||||
description = ''
|
||||
How often the allowance renews, at local midnight: daily, weekly, or monthly on the
|
||||
day the count began. `null`: never; only a reset starts it over.
|
||||
'';
|
||||
};
|
||||
ipLimit = mkOption {
|
||||
type = types.nullOr types.ints.positive;
|
||||
default = null;
|
||||
description = ''
|
||||
How many addresses may use the user at once. The ones past it that came last are
|
||||
banned for `inbounds.manager.ipLimit.banTime` from the user's ports. Not on
|
||||
AmneziaWG, whose peer has one address anyway, nor behind a PROXY-protocol front.
|
||||
'';
|
||||
example = 2;
|
||||
};
|
||||
speedLimit = mkOption {
|
||||
type = types.nullOr (types.strMatching "[0-9]+(\\.[0-9]+)?[kKMG]?(/[0-9]+(\\.[0-9]+)?[kKMG]?)?");
|
||||
default = null;
|
||||
description = ''
|
||||
Speed limit in bits per second, decimal (k, M, G): one rate for both ways, or
|
||||
"down/up". Needs `inbounds.manager.speedLimits.enable`. On socks and http listeners
|
||||
it does not apply.
|
||||
'';
|
||||
example = "20M/5M";
|
||||
};
|
||||
};
|
||||
};
|
||||
};
|
||||
|
||||
|
||||
@@ -136,7 +136,9 @@ in
|
||||
default = true;
|
||||
description = ''
|
||||
Learn blocked sites: after `failThreshold` failed connections, a site is treated as
|
||||
blocked. When off, only `zapret2.domains` and `proxy-ctl zapret auto add` are used.
|
||||
blocked. When off, only `zapret2.domains` and `proxy-ctl zapret auto add` are used:
|
||||
the sites already learned are kept but ignored, by zapret2 and `zapret.directSync`
|
||||
alike, until it is back on. Each site's strategy is still remembered.
|
||||
'';
|
||||
};
|
||||
|
||||
@@ -162,7 +164,9 @@ in
|
||||
Learn with proxy-suite's detector instead of nfqws2's. It also learns sites blocked
|
||||
only some of the time (a working connection no longer clears the failures before it),
|
||||
downloads that stall partway (the 16 KB cutoff), and requests that never get an
|
||||
answer. Learned sites are logged with `strategyLog`. Only with the source's own
|
||||
answer. It also follows learned sites past the first 4 KB a strategy is judged on:
|
||||
one whose downloads keep stalling keeps the proxy's route (`zapret.directSync`).
|
||||
Learned sites are logged with `strategyLog`. Only with the source's own
|
||||
`profiles`, and for TLS: nfqws2-keenetic no longer learns plain HTTP sites.
|
||||
'';
|
||||
};
|
||||
@@ -173,9 +177,11 @@ in
|
||||
default = true;
|
||||
description = ''
|
||||
Work around ISPs that cut TLS to some hosting networks after about 16 KB, which no
|
||||
strategy fixes. A daily probe finds the affected networks and a whitelisted name that
|
||||
gets through for each. Only with `strategySource = "z2k"`. Each run makes thousands of
|
||||
short direct connections. `proxy-ctl zapret cutoff` shows the results.
|
||||
strategy fixes. A daily probe finds the affected networks, and with
|
||||
`strategySource = "z2k"` (and its own `profiles`) a whitelisted name that gets
|
||||
through for each, which z2k puts into a fake ClientHello. Otherwise no name is
|
||||
searched for, and every affected network is left to `proxyFallback`. Each run makes
|
||||
thousands of short direct connections. `proxy-ctl zapret cutoff` shows the results.
|
||||
'';
|
||||
};
|
||||
|
||||
|
||||
@@ -61,6 +61,22 @@ let
|
||||
outboundTag = "block";
|
||||
};
|
||||
|
||||
# Whatever the listener, its via, or a proxy exception: what hosters close servers over.
|
||||
# Sniffing tells BitTorrent apart whatever destOverride lists (proxy_inbound.py).
|
||||
abuseRules =
|
||||
lib.optional proxyInboundsCfg.routing.blockTorrent {
|
||||
type = "field";
|
||||
ruleTag = "inbound-block-torrent";
|
||||
protocol = [ "bittorrent" ];
|
||||
outboundTag = "block";
|
||||
}
|
||||
++ lib.optional (proxyInboundsCfg.routing.blockPorts != [ ]) {
|
||||
type = "field";
|
||||
ruleTag = "inbound-block-ports";
|
||||
port = lib.concatMapStringsSep "," toString proxyInboundsCfg.routing.blockPorts;
|
||||
outboundTag = "block";
|
||||
};
|
||||
|
||||
# The address clients dial must stay reachable even when blockRu covers it
|
||||
# (a .ru domain or IP). After blockPrivate, so it cannot open the LAN. Its aliases
|
||||
# too: routing.via usually cannot loop back to this host, so they would fail there.
|
||||
@@ -308,6 +324,7 @@ let
|
||||
xrayInboundRules =
|
||||
onionRule
|
||||
++ blockPrivateRule
|
||||
++ abuseRules
|
||||
++ serverAddressRule
|
||||
++ proxyDomainRule
|
||||
++ proxyIpRule
|
||||
|
||||
@@ -665,6 +665,57 @@ let
|
||||
(mkAssertion (!derived.proxyInboundsRuntimeEnabled || derived.proxyInboundRuntimePorts != [ ])
|
||||
"proxy-suite: inbounds.runtime.enable needs inbounds.runtime.ports, the ports runtime listeners may use"
|
||||
)
|
||||
]
|
||||
# inbounds.manager and the users' policies.
|
||||
++ (
|
||||
let
|
||||
mgr = cfg.inbounds.manager;
|
||||
defaultPolicy = {
|
||||
enabled = true;
|
||||
expiresAt = null;
|
||||
expiresAfter = null;
|
||||
trafficLimit = null;
|
||||
trafficPeriod = null;
|
||||
ipLimit = null;
|
||||
speedLimit = null;
|
||||
};
|
||||
withPolicy = lib.attrNames (
|
||||
lib.filterAttrs (_: user: user.policy != defaultPolicy) cfg.inbounds.users
|
||||
);
|
||||
withSpeed = lib.attrNames (
|
||||
lib.filterAttrs (_: user: user.policy.speedLimit != null) cfg.inbounds.users
|
||||
);
|
||||
withIpLimit = lib.attrNames (
|
||||
lib.filterAttrs (_: user: user.policy.ipLimit != null) cfg.inbounds.users
|
||||
);
|
||||
speedOn = mgr.enable && mgr.speedLimits.enable;
|
||||
in
|
||||
[
|
||||
(mkAssertion (withPolicy == [ ] || derived.proxyInboundsManagerEnabled)
|
||||
"proxy-suite: inbounds.users.<name>.policy needs inbounds.manager.enable, which keeps it (set on: ${lib.concatStringsSep ", " withPolicy})"
|
||||
)
|
||||
(mkAssertion (withSpeed == [ ] || speedOn)
|
||||
"proxy-suite: inbounds.users.<name>.policy.speedLimit needs inbounds.manager.speedLimits.enable (set on: ${lib.concatStringsSep ", " withSpeed})"
|
||||
)
|
||||
(mkAssertion (
|
||||
!speedOn || cfg.host.privileged
|
||||
) "proxy-suite: inbounds.manager.speedLimits needs root: nftables polices the users' traffic")
|
||||
# Without root the manager has no nftables, and an ipLimit would hold nobody back.
|
||||
(mkAssertion (withIpLimit == [ ] || cfg.host.privileged)
|
||||
"proxy-suite: inbounds.users.<name>.policy.ipLimit needs root: nftables bans the addresses past it (set on: ${lib.concatStringsSep ", " withIpLimit})"
|
||||
)
|
||||
(mkAssertion (!speedOn || (cfg.inbounds.package.passthru.userLevelMark or false))
|
||||
"proxy-suite: inbounds.manager.speedLimits needs proxy-suite's XRay (inbounds.package), whose patch marks a limited user's sockets"
|
||||
)
|
||||
(mkAssertion (mgr.api.listen == null || mgr.api.tokensFile != null)
|
||||
"proxy-suite: inbounds.manager.api.listen needs inbounds.manager.api.tokensFile: the TCP API takes bearer tokens only"
|
||||
)
|
||||
(mkAssertion (
|
||||
!mgr.subscriptions.enable || !mgr.enable || cfg.inbounds.shareLinks
|
||||
) "proxy-suite: inbounds.manager.subscriptions.enable needs inbounds.shareLinks")
|
||||
]
|
||||
)
|
||||
++ [
|
||||
(requireEnabled proxyInboundsNeedLocalProxy proxyEnabled
|
||||
"proxy-suite: inbounds.routing.via = \"proxy\" relays through the local proxy stack, which requires proxy.enable = true. Use via = \"direct\" for a plain exit node."
|
||||
)
|
||||
|
||||
@@ -159,6 +159,9 @@ in
|
||||
INBOUNDS_RUNTIME_ENABLED = flag proxyInboundsRuntimeEnabled;
|
||||
INBOUNDS_RUNTIME_TOOL = "${proxySuiteScriptsDir}/inbound_runtime.py";
|
||||
INBOUNDS_SPEC_FILE = "${proxyInboundsSpecFile}";
|
||||
# inbounds.manager: `inbounds users show|set|...`, bans, export and import go to its API.
|
||||
INBOUNDS_MANAGER_SOCKET =
|
||||
if ctx.proxyInboundsManagerEnabled then constants.inboundsManagerApiSocket else "";
|
||||
# Only the system-wide instance reads the site lists; per-app zapret handles all traffic.
|
||||
ZAPRET_AUTO_ENABLED = flag (zapretEngine == "zapret2" && zapretGlobalEnabled);
|
||||
ZAPRET_STATE_DIR = constants.zapret2StateDir;
|
||||
|
||||
@@ -28,8 +28,13 @@ let
|
||||
proxyInboundsSpecFile
|
||||
proxyInboundsSelfSources
|
||||
proxyInboundsRuntimeEnabled
|
||||
proxyInboundsManagerEnabled
|
||||
proxyInboundsManagerCfg
|
||||
proxyInboundsSpeedLimits
|
||||
proxySuiteScriptsDir
|
||||
builders
|
||||
constants
|
||||
cfg
|
||||
;
|
||||
# A value in a shell comment, on that one line: a newline in a tag (types.str) would end
|
||||
# the comment and run the rest as root.
|
||||
@@ -198,6 +203,11 @@ let
|
||||
--spec ${proxyInboundsSpecFile} \
|
||||
--server-address "$SERVER_ADDRESS" \
|
||||
--onion-address "$ONION_ADDRESS"${lib.optionalString proxyInboundsRuntimeEnabled " \\\n --template ${proxyInboundsFile}"})
|
||||
# What runs, and from what: inbound_apply.py renders again with these and changes the
|
||||
# difference through XRay's API instead of restarting.
|
||||
printf '%s' "$RENDERED" > "$RUNTIME_DIR/rendered.json"
|
||||
${jq} -n --arg server "$SERVER_ADDRESS" --arg onion "$ONION_ADDRESS" \
|
||||
'{serverAddress: $server, onionAddress: $onion}' > "$RUNTIME_DIR/render-args.json"
|
||||
|
||||
INBOUNDS_JSON=$(${jq} -c '.inbounds' <<< "$RENDERED")
|
||||
|
||||
@@ -230,6 +240,9 @@ let
|
||||
"--arg password ''"
|
||||
} \
|
||||
--argjson runtime ${if proxyInboundsRuntimeEnabled then "true" else "false"} \
|
||||
--argjson exit_mark ${
|
||||
if proxyInboundsSpeedLimits then toString constants.inboundExitMark else "null"
|
||||
} \
|
||||
--slurpfile rendered <(printf '%s' "$RENDERED") \
|
||||
--argjson host_addresses "$HOST_ADDRESSES" \
|
||||
'.inbounds += $ibs[0]
|
||||
@@ -251,6 +264,13 @@ let
|
||||
| if $auth_enabled then
|
||||
(.outbounds[] | select(.tag == "proxy") | .settings.servers[0].users)
|
||||
= [{user:$user,pass:$password}]
|
||||
else . end
|
||||
# Speed limits: every exit marks the sockets of a limited user with their level (the
|
||||
# XRay patch), for nftables. Not the serverSource outbounds, nor one marked already.
|
||||
| if $exit_mark != null then
|
||||
(.outbounds[] | select(.protocol != "blackhole" and .tag != "api"
|
||||
and ((.tag // "") | startswith("direct-self") | not)))
|
||||
|= (.streamSettings.sockopt.mark //= $exit_mark)
|
||||
else . end' \
|
||||
${proxyInboundsFile} > "$RUNTIME_DIR/config.json.tmp"
|
||||
|
||||
@@ -368,16 +388,108 @@ let
|
||||
'';
|
||||
# inbounds.runtime: after proxy-ctl changes the spool. The AmneziaWG interfaces only when
|
||||
# their peers changed: restarting them cuts off every one of their clients for a moment.
|
||||
# Users through XRay's API and AmneziaWG peers through `awg syncconf`, so the others keep
|
||||
# their connections; a restart only for what those cannot change (inbound_apply.py).
|
||||
reloadInbounds = pkgs.writeShellScript "proxy-suite-inbounds" ''
|
||||
set -euo pipefail
|
||||
restart=$(PYTHONPATH="${parserScriptsPythonPath}" ${python3} ${parserScriptsPythonPath}/inbound_runtime.py \
|
||||
--spec ${proxyInboundsSpecFile} check${
|
||||
lib.optionalString (
|
||||
proxyInboundsAwg != [ ]
|
||||
) " --awg-users ${constants.runtimeDir}/proxy-suite-inbounds-awg/users.json"
|
||||
})
|
||||
# shellcheck disable=SC2086
|
||||
${constants.systemctl} try-restart $restart proxy-suite-inbounds.service
|
||||
PYTHONPATH="${parserScriptsPythonPath}" exec ${python3} ${parserScriptsPythonPath}/inbound_apply.py \
|
||||
--config ${applyConfigFile} --spec ${proxyInboundsSpecFile}
|
||||
'';
|
||||
|
||||
# The links and subscriptions of a rendering saved by the start script, written as it
|
||||
# writes them: for inbound_apply.py, after users changed without a restart.
|
||||
writeInboundOutputs = pkgs.writeShellScript "proxy-suite-inbounds" ''
|
||||
set -euo pipefail
|
||||
umask 077
|
||||
RENDERED=$(cat "$1")
|
||||
${writeLinksBlock}
|
||||
${writeSubscriptionsBlock}
|
||||
'';
|
||||
|
||||
# What inbound_apply.py works with: the binaries, units and names it may touch.
|
||||
applyConfig = {
|
||||
inherit runtimeDir;
|
||||
unit = "proxy-suite-inbounds.service";
|
||||
template = "${proxyInboundsFile}";
|
||||
inherit xray;
|
||||
api = "unix://${constants.inboundStatsApiSocket}";
|
||||
ip = "${pkgs.iproute2}/bin/ip";
|
||||
selfInterface =
|
||||
if selfInterfaceWanted then proxyInboundsCfg.routing.serverSource.interface else null;
|
||||
outputsScript = "${writeInboundOutputs}";
|
||||
inherit (constants) systemctl;
|
||||
tmpDir = runtimeDir;
|
||||
env = lib.optionalAttrs (cfg.geodata.xray.assets != null) {
|
||||
XRAY_LOCATION_ASSET = "${cfg.geodata.xray.assets}/share/v2ray";
|
||||
};
|
||||
}
|
||||
# Killing a cut user's sockets, and the table their UDP is dropped in, take root.
|
||||
// lib.optionalAttrs constants.privileged {
|
||||
ss = "${pkgs.iproute2}/bin/ss";
|
||||
}
|
||||
// lib.optionalAttrs (constants.privileged && proxyInboundsManagerEnabled) {
|
||||
nft = "${pkgs.nftables}/bin/nft";
|
||||
nftTable = constants.inboundLimitsTable;
|
||||
}
|
||||
// lib.optionalAttrs (proxyInboundsAwg != [ ]) {
|
||||
awg = awgBin;
|
||||
awgRuntimeDir = "${constants.runtimeDir}/proxy-suite-inbounds-awg";
|
||||
awgUnit = "proxy-suite-inbounds-awg.service";
|
||||
};
|
||||
applyConfigFile = pkgs.writeText "proxy-suite-inbounds" (builtins.toJSON applyConfig);
|
||||
|
||||
# The manager's own: where it keeps things, what it serves, whom it tells.
|
||||
mgr = proxyInboundsManagerCfg;
|
||||
managerApiGroup =
|
||||
if mgr.api.group != null then
|
||||
mgr.api.group
|
||||
else if userControlAllows "inbounds" then
|
||||
userControlCfg.group
|
||||
else
|
||||
null;
|
||||
managerConfig = {
|
||||
apply = applyConfig;
|
||||
policyFile = "${constants.inboundsManagerDir}/policy.json";
|
||||
stateFile = "${constants.inboundsManagerDir}/state.json";
|
||||
statsFile = constants.inboundStatsFile;
|
||||
collector = "${collectInboundStats}";
|
||||
inherit (mgr)
|
||||
interval
|
||||
webhooks
|
||||
notify
|
||||
deleteExpiredAfter
|
||||
;
|
||||
api = {
|
||||
socket = constants.inboundsManagerApiSocket;
|
||||
group = managerApiGroup;
|
||||
mode = if managerApiGroup == null then "0600" else "0660";
|
||||
inherit (mgr.api) listen tokensFile;
|
||||
};
|
||||
subscriptions = {
|
||||
socket = if mgr.subscriptions.enable then constants.inboundsManagerSubSocket else null;
|
||||
inherit (mgr.subscriptions)
|
||||
group
|
||||
listen
|
||||
profileTitle
|
||||
updateInterval
|
||||
supportUrl
|
||||
webPageUrl
|
||||
;
|
||||
inherit (subsCfg) baseUrl;
|
||||
};
|
||||
ipLimit.banSeconds = mgr.ipLimit.banTime;
|
||||
speedLimits = proxyInboundsSpeedLimits;
|
||||
inherit (mgr.speedLimits) slots;
|
||||
nft = if constants.privileged then "${pkgs.nftables}/bin/nft" else null;
|
||||
};
|
||||
managerConfigFile = pkgs.writeText "proxy-suite-inbounds-manager" (builtins.toJSON managerConfig);
|
||||
runManager = pkgs.writeShellScript "proxy-suite-inbounds-manager" ''
|
||||
set -euo pipefail
|
||||
umask 077
|
||||
mkdir -p ${lib.escapeShellArg constants.inboundsManagerDir}
|
||||
export PYTHONPATH=${proxySuiteScriptsDir}
|
||||
exec ${python3} ${proxySuiteScriptsDir}/inbound_manager.py \
|
||||
--config ${managerConfigFile} --spec ${proxyInboundsSpecFile} serve
|
||||
'';
|
||||
|
||||
stopInboundsInterface =
|
||||
@@ -392,6 +504,7 @@ in
|
||||
stopInboundsInterface
|
||||
collectInboundStats
|
||||
reloadInbounds
|
||||
runManager
|
||||
linksFile
|
||||
subscriptionsFile
|
||||
;
|
||||
|
||||
@@ -46,6 +46,8 @@ def xray_pin_server_names:
|
||||
# Slurped (a list of one), not an argument: it grows with the rules.
|
||||
$route_rules[0] as $route_rules
|
||||
| .outbounds = ($obs[0] + .outbounds)
|
||||
# proxy.xray.xhttpXmux.
|
||||
| .outbounds |= map(. @setXhttpXmux@)
|
||||
| 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"
|
||||
|
||||
@@ -15,6 +15,8 @@
|
||||
awgRuntimeDnsServer ? null,
|
||||
# proxy.listener on an address other machines reach (0.0.0.0, a LAN address).
|
||||
listenerExposed ? false,
|
||||
# derived.xhttpXmuxJq.
|
||||
xhttpXmuxJq ? "",
|
||||
}:
|
||||
|
||||
let
|
||||
@@ -60,6 +62,7 @@ if pureXrayEnabled then
|
||||
(fillTemplate ./backend-filter-xray.template.jq {
|
||||
inherit selectionMode;
|
||||
hostClosedPorts = lib.concatStringsSep "," closedPorts;
|
||||
setXhttpXmux = xhttpXmuxJq;
|
||||
})
|
||||
else
|
||||
(fillTemplate ./backend-filter-sing-box.template.jq {
|
||||
|
||||
@@ -7,6 +7,7 @@ let
|
||||
jq
|
||||
hybridEnabled
|
||||
xraySidecarRoutingMark
|
||||
xhttpXmuxJq
|
||||
;
|
||||
in
|
||||
|
||||
@@ -21,6 +22,7 @@ lib.optionalString hybridEnabled (
|
||||
setSidecarMark = lib.optionalString (
|
||||
xraySidecarRoutingMark != null
|
||||
) "| .streamSettings.sockopt.mark = $mark";
|
||||
setXhttpXmux = xhttpXmuxJq;
|
||||
hopRoutingMark = lib.optionalString (
|
||||
routingMark != null
|
||||
) " + {routing_mark: ${toString routingMark}}";
|
||||
|
||||
@@ -30,6 +30,7 @@ _proxy_suite_add_xray_sidecar_obs() {
|
||||
| .value.tag as $tag
|
||||
| {outbound: (.value
|
||||
@setSidecarMark@
|
||||
@setXhttpXmux@
|
||||
| .streamSettings.sockopt.domainStrategy = (.streamSettings.sockopt.domainStrategy // "UseIP")),
|
||||
client: {id: $id, email: $tag},
|
||||
rule: {type: "field", inboundTag: ["sidecar-in"], user: [$tag], outboundTag: $tag},
|
||||
|
||||
@@ -167,7 +167,7 @@ let
|
||||
proxyInboundsGuardStrategy
|
||||
;
|
||||
proxyInboundsBlockPrivate = proxyInboundsCfg.routing.blockPrivate;
|
||||
inherit (ctx) proxyInboundsLoopback proxyInboundsHostClosedPorts;
|
||||
inherit (ctx) proxyInboundsLoopback proxyInboundsHostClosedPorts xhttpXmuxJq;
|
||||
listenerExposed =
|
||||
let
|
||||
address = proxyCfg.listener.address;
|
||||
@@ -197,6 +197,7 @@ let
|
||||
stopInboundsInterface
|
||||
collectInboundStats
|
||||
reloadInbounds
|
||||
runManager
|
||||
;
|
||||
proxyInboundsLinksFile = proxyInboundsScripts.linksFile;
|
||||
proxyInboundsSubscriptionsFile = proxyInboundsScripts.subscriptionsFile;
|
||||
@@ -236,6 +237,7 @@ in
|
||||
stopInboundsInterface
|
||||
collectInboundStats
|
||||
reloadInbounds
|
||||
runManager
|
||||
;
|
||||
inherit
|
||||
proxyInboundsLinksFile
|
||||
|
||||
@@ -24,6 +24,8 @@ let
|
||||
whitelistBypassJoiners
|
||||
proxyInboundsEnabled
|
||||
proxyInboundsRuntimeEnabled
|
||||
proxyInboundsManagerEnabled
|
||||
proxyInboundsAwg
|
||||
proxyInboundsNeedLocalProxy
|
||||
scripts
|
||||
perAppRouting
|
||||
@@ -60,6 +62,7 @@ let
|
||||
subscriptionUpdate = "proxy-suite-subscription-update";
|
||||
inbounds = "proxy-suite-inbounds";
|
||||
inboundStats = "proxy-suite-inbound-stats";
|
||||
inboundsManager = "proxy-suite-inbounds-manager";
|
||||
};
|
||||
|
||||
backendDescription =
|
||||
@@ -267,6 +270,10 @@ let
|
||||
// lib.optionalAttrs (extra != [ ]) { ReadWritePaths = map (path: "-${path}") extra; }
|
||||
);
|
||||
socksRuntimeDir = "${ctx.constants.runtimeDir}/${serviceNames.socks}";
|
||||
inboundsRuntimeDirs = [
|
||||
"${ctx.constants.runtimeDir}/${serviceNames.inbounds}"
|
||||
"${ctx.constants.runtimeDir}/proxy-suite-inbounds-awg"
|
||||
];
|
||||
|
||||
# XRay finds geoip.dat/geosite.dat through this; sing-box ignores it.
|
||||
xrayAssetEnv = lib.optionalAttrs (geodata.xray.assets != null) {
|
||||
@@ -361,11 +368,30 @@ let
|
||||
description = "Apply proxy-suite inbound users and listeners added at runtime";
|
||||
execStart = scripts.reloadInbounds;
|
||||
stateDirectory = "proxy-suite";
|
||||
# Root, over the spool userControl's group writes.
|
||||
# Root, over the spool userControl's group writes. It renders into the inbounds' and
|
||||
# the AmneziaWG listeners' runtime directories, and changes the running ones in place.
|
||||
extraServiceConfig = {
|
||||
RemainAfterExit = false;
|
||||
}
|
||||
// spoolReaderSandbox [ ];
|
||||
// spoolReaderSandbox inboundsRuntimeDirs;
|
||||
};
|
||||
}
|
||||
{
|
||||
enable = proxyInboundsManagerEnabled;
|
||||
name = serviceNames.inboundsManager;
|
||||
value = mkRestartingService {
|
||||
description = "proxy-suite inbound manager - users' policies, API and subscriptions";
|
||||
after = [
|
||||
"${serviceNames.inbounds}.service"
|
||||
"nftables.service"
|
||||
]
|
||||
++ lib.optional (proxyInboundsAwg != [ ]) "proxy-suite-inbounds-awg.service";
|
||||
wants = [ "${serviceNames.inbounds}.service" ];
|
||||
wantedBy = [ "multi-user.target" ];
|
||||
execStart = scripts.runManager;
|
||||
runtimeDirectory = serviceNames.inboundsManager;
|
||||
stateDirectory = "proxy-suite";
|
||||
extraServiceConfig = spoolReaderSandbox inboundsRuntimeDirs;
|
||||
};
|
||||
}
|
||||
{
|
||||
|
||||
@@ -89,6 +89,10 @@ let
|
||||
"CookieAuthentication 0"
|
||||
]
|
||||
++ lib.optional t.clientOnly "ClientOnly 1"
|
||||
++ lib.optionals t.keepAwake [
|
||||
"DormantTimeoutEnabled 0"
|
||||
"DormantCanceledByStartup 1"
|
||||
]
|
||||
++ (if t.asOutbound then [ "SocksPort 127.0.0.1:${toString t.socksPort}" ] else [ "SocksPort 0" ])
|
||||
++ lib.optionals bridgesEnabled [
|
||||
"UseBridges 1"
|
||||
|
||||
@@ -109,6 +109,21 @@ let
|
||||
touch ${runtime.autoHostlistFile} ${runtime.userHostlistFile} ${runtime.excludeHostlistFile}
|
||||
# In this unit's sandbox: a name a member left here leads nowhere else.
|
||||
${constants.grantDirAcl pkgs runtime.stateDir (userControlExtraGroupsFor "zapret") "rwX"}
|
||||
${lib.optionalString (userControlAnyAllows "zapret") ''
|
||||
# A list a member renamed in is theirs: nfqws2 appends to it through the group
|
||||
# (after the ACLs, whose mask the group bits are).
|
||||
for f in ${
|
||||
lib.escapeShellArgs [
|
||||
runtime.autoHostlistFile
|
||||
runtime.userHostlistFile
|
||||
runtime.excludeHostlistFile
|
||||
"${runtime.stateDir}/verdicts.tsv"
|
||||
"${runtime.circularStateDir}/state.tsv"
|
||||
]
|
||||
}; do
|
||||
if [ -f "$f" ] && [ ! -L "$f" ]; then chmod g+w -- "$f"; fi
|
||||
done
|
||||
''}
|
||||
${runtime.initScript} start_fw
|
||||
'';
|
||||
|
||||
@@ -125,6 +140,11 @@ let
|
||||
# systemd gives the state directory the unit's group on every start: the group's, which
|
||||
# edits the lists (as autoProxy's units do).
|
||||
// lib.optionalAttrs (userControlAllows "zapret") { Group = cfg.userControl.group; }
|
||||
# userControl.groups' members own what they rename in, writable by their ACL groups:
|
||||
# nfqws2 keeps these groups (runtime.daemonScript) to append to it.
|
||||
// lib.optionalAttrs (userControlExtraGroupsFor "zapret" != [ ]) {
|
||||
SupplementaryGroups = userControlExtraGroupsFor "zapret";
|
||||
}
|
||||
# nfqws2 runs as root and writes its lists in a directory the zapret scope's group
|
||||
# writes to as well.
|
||||
// constants.rootInSharedDirConfig
|
||||
@@ -135,6 +155,7 @@ let
|
||||
lib
|
||||
pkgs
|
||||
cfg
|
||||
packages
|
||||
zapret2Sources
|
||||
nft
|
||||
;
|
||||
|
||||
@@ -10,6 +10,22 @@ for f in asn.txt sni.txt asn.new sni.new proxy.json proxy.json.tmp egress ts for
|
||||
fi
|
||||
done
|
||||
touch asn.txt sni.txt
|
||||
# The rule-set from the maps as they stand, rewritten only when it changes: sing-box
|
||||
# reloads it on every rename.
|
||||
rules() {
|
||||
@proxyRules@ asn.txt sni.txt @lists@/tcp16_nets.txt >proxy.json.tmp
|
||||
if cmp -s proxy.json.tmp proxy.json; then
|
||||
rm -f proxy.json.tmp
|
||||
else
|
||||
mv -f proxy.json.tmp proxy.json
|
||||
fi
|
||||
}
|
||||
# Names no profile puts in fix nothing: none kept from when one did, so every cut-off
|
||||
# network goes to the proxy now, not after the next probe.
|
||||
if [ @names@ = 0 ] && [ -s sni.txt ]; then
|
||||
: >sni.txt
|
||||
rules
|
||||
fi
|
||||
force=0
|
||||
if [ -e requests/force ] || [ -L requests/force ]; then
|
||||
force=1
|
||||
@@ -59,8 +75,13 @@ z2k-detect tcp16 -targets @lists@/tcp16_targets.txt -parallel 50 -asn-out asn.ne
|
||||
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=$?
|
||||
# No profile puts a name in: the cut-off networks are all there is to know.
|
||||
if [ @names@ = 0 ]; then
|
||||
: >sni.new
|
||||
else
|
||||
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=$?
|
||||
fi
|
||||
# 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
|
||||
@@ -84,8 +105,7 @@ 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
|
||||
rules
|
||||
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)"
|
||||
|
||||
@@ -7,6 +7,7 @@
|
||||
lib,
|
||||
pkgs,
|
||||
cfg,
|
||||
packages,
|
||||
zapret2Sources,
|
||||
nft,
|
||||
}:
|
||||
@@ -29,16 +30,13 @@ let
|
||||
lib.optional zapretGlobalEnabled "proxy-suite-zapret.service"
|
||||
++ lib.optional cfg.perAppRouting.zapret.enable "proxy-suite-per-app-zapret.service";
|
||||
|
||||
z2kDetect = pkgs.buildGoModule {
|
||||
pname = "z2k-detect";
|
||||
version = "0-unstable-${z2k.shortRev or "local"}";
|
||||
src = "${z2k}/z2k-detect";
|
||||
vendorHash = "sha256-9Qv6O6/8MP9N44GPSDULEV/NcrHdEC3YZmIQmpaa1nE=";
|
||||
subPackages = [ "cmd/z2k-detect" ];
|
||||
# Its tests open raw sockets and dial out.
|
||||
doCheck = false;
|
||||
meta.mainProgram = "z2k-detect";
|
||||
};
|
||||
# The z2k flake.lock holds, whatever `z2k` the consumer passes (pkgs/z2k-detect.nix).
|
||||
z2kDetect = packages.z2k-detect;
|
||||
|
||||
# Only z2k's own profiles put the name in (z2k-tcp16.lua, ahead of rotation; ahead of
|
||||
# the nfqws2-keenetic strategies it broke hosts, sources.nix). Elsewhere a name found
|
||||
# fixes nothing: every cut-off network goes to the proxy, and no name is searched for.
|
||||
namesApply = cfg.zapret.zapret2.strategySource == "z2k" && cfg.zapret.zapret2.profiles == null;
|
||||
|
||||
# $1 asn.txt, $2 sni.txt, $3 AS-to-prefix map; prints a sing-box source rule-set
|
||||
# with the prefixes of every cut-off network that no whitelisted name fixes.
|
||||
@@ -66,6 +64,7 @@ let
|
||||
z2kDetect
|
||||
];
|
||||
dir = lib.escapeShellArg dir;
|
||||
names = if namesApply then "1" else "0";
|
||||
inherit lists proxyRules;
|
||||
restartUnits = lib.escapeShellArgs restartUnits;
|
||||
}
|
||||
|
||||
@@ -19,8 +19,9 @@
|
||||
-- "kind<TAB>name<TAB>proto<TAB>note<TAB>time" (the last line per name and proto wins), for
|
||||
-- direct-sync.template.sh and proxy-ctl:
|
||||
-- - works <site> tcp|udp: a strategy got through; only then does a learned site go direct;
|
||||
-- - stalls <host> cutoff: learned from transfers cut short (the 16 KB cutoff); such a site
|
||||
-- keeps the proxy's route whatever "works" says, as success is judged on the first 4 KB;
|
||||
-- - stalls <host> cutoff: learned from transfers cut short (the 16 KB cutoff), or learned
|
||||
-- otherwise and cut short since (ps_watch); such a site keeps the proxy's route whatever
|
||||
-- "works" says, as success is judged on the first 4 KB;
|
||||
-- - unfixable <site> tcp|udp: every strategy failed in turn; the proxy carries it;
|
||||
-- - blocked <ip> ip: connections to it go unanswered (blocked by address, ps_syn), and
|
||||
-- reachable <ip> ip once one is answered again;
|
||||
@@ -355,6 +356,30 @@ local function feed(st, data)
|
||||
end
|
||||
end
|
||||
|
||||
-- The server's next segment: fed in order, one that came early held until the gap fills.
|
||||
local function receive(st, desync, payload)
|
||||
local s = pos_get(desync, "s")
|
||||
if s == st.next then
|
||||
feed(st, payload)
|
||||
st.next = s + #payload
|
||||
while st.pending[st.next] do
|
||||
local p = st.pending[st.next]
|
||||
st.pending[st.next] = nil
|
||||
feed(st, p)
|
||||
st.next = st.next + #p
|
||||
end
|
||||
elseif s > st.next then
|
||||
st.pending[s] = payload
|
||||
end
|
||||
end
|
||||
|
||||
-- The server went quiet inside a TLS record, while the window still showed its packets.
|
||||
-- Past the NFQUEUE window nothing more is seen: no telling a stall from the rest.
|
||||
local function cut_short(st, arg)
|
||||
if st.done or st.notls or st.inpk >= (tonumber(arg.win) or 15) then return false end
|
||||
return st.need > 0 or #st.hdr > 0 or next(st.pending) ~= nil
|
||||
end
|
||||
|
||||
-- nfqws2's own fast fail: a reset to the client retransmitting into silence, so it
|
||||
-- gives up (and tries again) instead of waiting out its timeouts.
|
||||
local function reset_client(desync)
|
||||
@@ -377,9 +402,7 @@ end
|
||||
|
||||
function ps_learn_stall(_, data)
|
||||
local st = data.st
|
||||
-- Past the NFQUEUE window nothing more is seen: no telling a stall from the rest.
|
||||
if st.done or st.notls or st.inpk >= (tonumber(data.arg.win) or 15) then return end
|
||||
if st.need > 0 or #st.hdr > 0 or next(st.pending) then
|
||||
if cut_short(st, data.arg) then
|
||||
failure(st, data.arg, "transfer stalled after " .. math.floor((st.next - 1) / 1024) .. " KB", true)
|
||||
end
|
||||
end
|
||||
@@ -419,19 +442,7 @@ function ps_learn(_, desync)
|
||||
end
|
||||
if #payload > 0 then
|
||||
st.answered = true
|
||||
local s = pos_get(desync, "s")
|
||||
if s == st.next then
|
||||
feed(st, payload)
|
||||
st.next = s + #payload
|
||||
while st.pending[st.next] do
|
||||
local p = st.pending[st.next]
|
||||
st.pending[st.next] = nil
|
||||
feed(st, p)
|
||||
st.next = st.next + #p
|
||||
end
|
||||
elseif s > st.next then
|
||||
st.pending[s] = payload
|
||||
end
|
||||
receive(st, desync, payload)
|
||||
if st.name then
|
||||
-- Replacing the timer restarts its countdown: it fires once the server goes quiet.
|
||||
timer_set("psls_" .. st.name, ps_learn_stall, STALL_MS, true, { st = st, arg = desync.arg })
|
||||
@@ -440,6 +451,56 @@ function ps_learn(_, desync)
|
||||
if bitand(flags, TH_FIN) ~= 0 then st.done = true end
|
||||
end
|
||||
|
||||
-- --- learned sites cut off ---------------------------------------------------------------
|
||||
|
||||
-- A learned site goes direct once a strategy gets it through, judged on the first 4 KB,
|
||||
-- which the 16 KB cutoff lets through; a site learned for another failure (a ClientHello
|
||||
-- retransmitted) carries no "stalls" verdict from ps_learn, which sees no listed site.
|
||||
-- ps_watch, ahead of rotation in the profile that takes the learned sites, follows each
|
||||
-- transfer on: one cut short `fails` times within `time` seconds is a "stalls" verdict,
|
||||
-- and the site keeps the proxy's route.
|
||||
|
||||
function ps_watch_stall(_, data)
|
||||
local st = data.st
|
||||
if not cut_short(st, data.arg) then return end
|
||||
st.done = true
|
||||
local n, need = tally("cut " .. st.host, tonumber(data.arg.time) or 300), tonumber(data.arg.fails) or 3
|
||||
if data.arg.log then
|
||||
say(st.host .. ": transfer stalled after " .. math.floor((st.next - 1) / 1024) .. " KB (" .. n .. "/" .. need .. " to keep it on the proxy)")
|
||||
end
|
||||
if n >= need then
|
||||
if status[st.host .. " cutoff"] ~= "stalls" then say(st.host .. ": its transfers are cut short, the proxy carries it") end
|
||||
verdict("stalls", st.host, "cutoff", "transfers cut short")
|
||||
end
|
||||
end
|
||||
|
||||
function ps_watch(_, desync)
|
||||
local track, dis = desync.track, desync.dis
|
||||
if not (track and dis and dis.tcp) or not track.hostname or track.hostname_is_ip then return end
|
||||
local st = track.lua_state.ps_watch
|
||||
if not st then
|
||||
st = { host = track.hostname:lower(), next = 1, need = 0, hdr = "", pending = {}, inpk = 0 }
|
||||
track.lua_state.ps_watch = st
|
||||
end
|
||||
if st.done then return end
|
||||
local flags = dis.tcp.th_flags
|
||||
-- A client that hangs up mid-transfer (a cancelled page) says nothing of the site.
|
||||
if bitand(flags, TH_RST) ~= 0 or (desync.outgoing and bitand(flags, TH_FIN) ~= 0) then
|
||||
st.done = true
|
||||
return
|
||||
end
|
||||
if desync.outgoing then return end
|
||||
st.inpk = pos_get(desync, "n") or (st.inpk + 1)
|
||||
local payload = dis.payload or ""
|
||||
if #payload > 0 then
|
||||
receive(st, desync, payload)
|
||||
-- Named by the server's direction, the one it is reset by.
|
||||
st.name = st.name or dis_timer_name(dis)
|
||||
timer_set("psws_" .. st.name, ps_watch_stall, STALL_MS, true, { st = st, arg = desync.arg })
|
||||
end
|
||||
if bitand(flags, TH_FIN) ~= 0 then st.done = true end
|
||||
end
|
||||
|
||||
-- --- addresses blocked outright ------------------------------------------------------------
|
||||
|
||||
-- No strategy helps where the connection itself goes unanswered: the address is blocked,
|
||||
|
||||
@@ -15,9 +15,12 @@ let
|
||||
inherit (import ../derived.nix { inherit lib cfg; }) constants;
|
||||
stateDir = constants.zapret2StateDir;
|
||||
outDir = constants.zapret2DirectDir;
|
||||
# Without learning nfqws2 no longer reads the learned list: neither does the sync.
|
||||
learn = cfg.zapret.zapret2.autoHostlist.enable;
|
||||
|
||||
sync = pkgs.writeShellScript "proxy-suite-zapret2" (
|
||||
fillTemplate ./direct-sync.template.sh {
|
||||
learned = if learn then "1" else "0";
|
||||
path = lib.makeBinPath [
|
||||
pkgs.coreutils
|
||||
pkgs.diffutils
|
||||
@@ -38,6 +41,9 @@ in
|
||||
# Ahead of the proxy at boot, so it starts with the hosts already in.
|
||||
before = [ "proxy-suite-socks.service" ];
|
||||
wantedBy = [ "multi-user.target" ];
|
||||
# nfqws2 writes verdicts in bursts (a page's unanswered addresses), each a start: the
|
||||
# start limit would fail the path unit with it, and nothing would sync until a reboot.
|
||||
startLimitIntervalSec = 0;
|
||||
serviceConfig = {
|
||||
Type = "oneshot";
|
||||
ExecStart = "${sync} ${lib.escapeShellArg stateDir} ${lib.escapeShellArg outDir}";
|
||||
@@ -52,11 +58,13 @@ in
|
||||
path = {
|
||||
description = "proxy-suite - watch zapret2's host lists and verdicts";
|
||||
wantedBy = [ "paths.target" ];
|
||||
pathConfig.PathChanged = map (name: "${stateDir}/${name}") [
|
||||
"zapret-hosts-user.txt"
|
||||
"zapret-hosts-auto.txt"
|
||||
"zapret-hosts-user-exclude.txt"
|
||||
"verdicts.tsv"
|
||||
];
|
||||
pathConfig.PathChanged = map (name: "${stateDir}/${name}") (
|
||||
[ "zapret-hosts-user.txt" ]
|
||||
++ lib.optional learn "zapret-hosts-auto.txt"
|
||||
++ [
|
||||
"zapret-hosts-user-exclude.txt"
|
||||
"verdicts.tsv"
|
||||
]
|
||||
);
|
||||
};
|
||||
}
|
||||
@@ -3,7 +3,8 @@
|
||||
# direct.json: the hosts zapret2 handles, so the proxy sends them direct and zapret2 sees
|
||||
# them: the pinned ones, and the learned ones once a strategy got through for them
|
||||
# (detect.lua's "works"), unless learned from transfers cut short ("stalls"); a learned
|
||||
# site zapret2 cannot fix keeps the proxy's route.
|
||||
# site zapret2 cannot fix keeps the proxy's route. With learning off
|
||||
# (autoHostlist.enable), the pinned ones alone: nfqws2 no longer reads the learned list.
|
||||
# proxy.json: what zapret2 cannot fix, for the proxy to carry: sites every strategy failed
|
||||
# for ("unfixable": all of a site's TCP, or only its QUIC), and addresses that leave
|
||||
# connections unanswered ("blocked").
|
||||
@@ -18,6 +19,7 @@ export PATH=@path@
|
||||
dir=$1
|
||||
out=$2
|
||||
cache=${3:-}
|
||||
learned=@learned@
|
||||
|
||||
# The zapret scope's group writes these: never through a symlink it left (to a file only
|
||||
# root may read, which would land in the world-readable rule-sets), nor into a FIFO.
|
||||
@@ -67,7 +69,7 @@ hosts='def octet: "(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])";
|
||||
|
||||
jq -n -c \
|
||||
--rawfile user <(lists "$dir/zapret-hosts-user.txt") \
|
||||
--rawfile auto <(lists "$dir/zapret-hosts-auto.txt") \
|
||||
--rawfile auto <(if [ "$learned" = 1 ]; then lists "$dir/zapret-hosts-auto.txt"; fi) \
|
||||
--rawfile excluded <(lists "$dir/zapret-hosts-user-exclude.txt") \
|
||||
--rawfile verdicts <(lists "$dir/verdicts.tsv") \
|
||||
"$hosts"'
|
||||
|
||||
@@ -70,11 +70,13 @@ let
|
||||
|
||||
# lib.trim drops string context: without it the source's list paths are no build input,
|
||||
# so lazy trees never materialize them and the closure omits them.
|
||||
# <STALLWATCH>: where the source's profile for learned sites takes stallWatch.
|
||||
renderProfile =
|
||||
profile:
|
||||
lib.replaceStrings hostlistMarkers (map (
|
||||
marker: marker + withSpaces staticListArgs
|
||||
) hostlistMarkers) (lib.addContextFrom profile (lib.trim profile));
|
||||
lib.replaceStrings (hostlistMarkers ++ [ "<STALLWATCH> " ]) (
|
||||
map (marker: marker + withSpaces staticListArgs) hostlistMarkers
|
||||
++ [ (lib.optionalString (stallWatch != "") (stallWatch + " ")) ]
|
||||
) (lib.addContextFrom profile (lib.trim profile));
|
||||
|
||||
# detect.lua learns in place of nfqws2's autohostlist, in a last TLS profile of its
|
||||
# own: z2k-profiles.template.sh puts it there, tailProfiles for nfqws2-keenetic.
|
||||
@@ -97,8 +99,25 @@ let
|
||||
)
|
||||
);
|
||||
|
||||
# detect.lua's ps_watch, ahead of every other instance of the profile that takes the
|
||||
# learned sites, so rotation (an orchestrator: it runs the instances after it) leaves it
|
||||
# be; it sees the server's bytes past what rotation judges a success on, and the
|
||||
# profile's filters are back at nfqws2's defaults after it.
|
||||
stallWatch = lib.optionalString learnLua (
|
||||
"--in-range=-s65536 --payload=all --lua-desync=ps_watch:"
|
||||
+ lib.concatStringsSep ":" (
|
||||
[
|
||||
"fails=${toString autoCfg.failThreshold}"
|
||||
"time=${toString autoCfg.failTime}"
|
||||
"win=${toString packetWindow.tcpIn}"
|
||||
]
|
||||
++ lib.optional zapret2Cfg.strategyLog "log"
|
||||
)
|
||||
+ " --in-range=x --payload=all"
|
||||
);
|
||||
|
||||
z2kGenerated = sources.z2k.mkProfiles {
|
||||
inherit learnArgs;
|
||||
inherit learnArgs stallWatch;
|
||||
hostlistSuffix = withSpaces staticListArgs;
|
||||
# z2k's category profiles filter on their own lists, not on a marker.
|
||||
excludeSuffix = withSpaces ([ "--hostlist-exclude=${excludeHostlistFile}" ] ++ excludeDomainArgs);
|
||||
@@ -437,8 +456,14 @@ let
|
||||
. "$ZAPRET_BASE/init.d/sysv/functions"
|
||||
opt="--qnum=$QNUM $NFQWS2_OPT"
|
||||
filter_apply_hostlist_target opt
|
||||
# --user=root leaves nfqws2 root's own groups (initgroups), and with them only
|
||||
# CAP_NET_ADMIN and CAP_NET_RAW: the unit's Group= and SupplementaryGroups=, through
|
||||
# which it appends to the lists the zapret scope's group renames in (theirs, then),
|
||||
# would be gone. --uid after it keeps uid 0 and the groups the unit started it with.
|
||||
uid=
|
||||
if [ "$(id -u)" = 0 ]; then uid="--uid=0:$(id -G | tr ' ' ,)"; fi
|
||||
set -f
|
||||
exec "$NFQWS2" $NFQWS2_OPT_BASE $opt
|
||||
exec "$NFQWS2" $NFQWS2_OPT_BASE $uid $opt
|
||||
'';
|
||||
in
|
||||
{
|
||||
|
||||
@@ -83,9 +83,12 @@ let
|
||||
# No 16 KB cutoff name step: its fake ClientHello ahead of these strategies
|
||||
# broke every host on a line where the strategies alone work. Its HTTP strategy
|
||||
# has no strategy=N, so circular must not take http_req: it would skip it.
|
||||
# <STALLWATCH>: it takes the learned sites (runtime.nix). ps_watch there makes
|
||||
# circular the profile's second instance: keyed as nfqws2 named it before
|
||||
# (<func>_<profile>_<nth instance>), its sites keep the strategies remembered.
|
||||
"${
|
||||
patch "NFQWS_ARGS" "${tcpPayload} ${circular}"
|
||||
"--in-range=-s5556 ${tcpPayload},tls_server_hello,empty,unknown ${circular} --in-range=x ${tcpPayload}"
|
||||
"<STALLWATCH> --in-range=-s5556 ${tcpPayload},tls_server_hello,empty,unknown ${circular}:key=circular_3_1 --in-range=x ${tcpPayload}"
|
||||
(args "NFQWS_ARGS")
|
||||
} <HOSTLIST> ${lists}"
|
||||
];
|
||||
@@ -166,6 +169,7 @@ let
|
||||
hostlistSuffix,
|
||||
excludeSuffix,
|
||||
learnArgs ? "",
|
||||
stallWatch ? "",
|
||||
}:
|
||||
pkgs.runCommand "proxy-suite-zapret2-z2k-profiles" {
|
||||
nativeBuildInputs = with pkgs; [
|
||||
@@ -176,7 +180,12 @@ let
|
||||
gnugrep
|
||||
gnused
|
||||
];
|
||||
inherit hostlistSuffix excludeSuffix learnArgs;
|
||||
inherit
|
||||
hostlistSuffix
|
||||
excludeSuffix
|
||||
learnArgs
|
||||
stallWatch
|
||||
;
|
||||
} (fillTemplate ./z2k-profiles.template.sh { z2k = src; });
|
||||
};
|
||||
in
|
||||
|
||||
@@ -44,11 +44,14 @@ grep -q -- '--lua-desync=circular' raw || { echo "z2k generator produced no prof
|
||||
# instead, in the same last place. It cannot ride along on the autohostlist profile:
|
||||
# nfqws2 applies nothing there to a host in no list, Lua included. It writes the
|
||||
# same auto list and reads the same excludes, which it checks itself.
|
||||
#
|
||||
# $stallWatch (detect.lua's ps_watch) goes first among the instances of the profile
|
||||
# that takes the learned sites, ahead of its in-profile filters, which it resets after.
|
||||
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" \
|
||||
-v learn="$learnArgs" -v wlfile="$root/lists/whitelist.txt" '
|
||||
-v learn="$learnArgs" -v wlfile="$root/lists/whitelist.txt" -v watch="$stallWatch" '
|
||||
{
|
||||
for (i = 1; i <= NF; i++) {
|
||||
t = $i
|
||||
@@ -57,9 +60,18 @@ awk -v disc="--hostlist=$root/lists/discovered-domains.txt" \
|
||||
} else if (t ~ /^--filter-tcp=/ && !(prof in ports)) {
|
||||
ports[prof] = substr(t, 14)
|
||||
}
|
||||
pre = ""
|
||||
if (t ~ /^--(in-range|out-range|payload|lua-desync)=/) {
|
||||
if (watch != "" && seen && prof == learner && !watched++) pre = watch " "
|
||||
filtered[prof] = 1
|
||||
}
|
||||
if (t == disc) {
|
||||
t = "<HOSTLIST_NOAUTO>" hsuf
|
||||
if (!seen++) { t = t " " yt; learner = prof }
|
||||
if (!seen++) {
|
||||
t = t " " yt
|
||||
learner = prof
|
||||
if (prof in filtered) { print "z2k general TLS profile: hostlist after its instances" > "/dev/stderr"; exit 1 }
|
||||
}
|
||||
} else if (t == wl) {
|
||||
t = t esuf
|
||||
} else if (t ~ /^--lua-desync=circular:/) {
|
||||
@@ -68,11 +80,12 @@ awk -v disc="--hostlist=$root/lists/discovered-domains.txt" \
|
||||
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
|
||||
printf "%s%s%s", (i > 1 ? " " : ""), pre, t
|
||||
}
|
||||
}
|
||||
END {
|
||||
if (!seen || !(learner in ports)) { print "z2k general TLS profile not found" > "/dev/stderr"; exit 1 }
|
||||
if (watch != "" && !watched) { print "z2k general TLS profile has no instances" > "/dev/stderr"; exit 1 }
|
||||
if (learn == "")
|
||||
printf " --new --filter-tcp=%s --filter-l7=tls %s%s <HOSTLIST>%s", ports[learner], wl, esuf, hsuf
|
||||
else {
|
||||
|
||||
@@ -223,9 +223,11 @@ pkgs.testers.runNixOSTest {
|
||||
assert server.succeed("jq -S .users /var/lib/proxy-suite/awg-inbounds/roam/state.json") == before
|
||||
through_server(alice, timeout=90)
|
||||
|
||||
with subtest("a runtime user becomes a peer, and only its listener's interfaces restart"):
|
||||
with subtest("a runtime user becomes a peer, synced in: the interfaces do not restart"):
|
||||
since = server.succeed("systemctl show -p ActiveEnterTimestampMonotonic --value proxy-suite-inbounds-awg.service").strip()
|
||||
server.succeed("proxy-ctl inbounds users add ring --listener roam")
|
||||
server.wait_until_succeeds("awg show awgi-roam peers | wc -l | grep -qx 3", timeout=30)
|
||||
assert server.succeed("systemctl show -p ActiveEnterTimestampMonotonic --value proxy-suite-inbounds-awg.service").strip() == since
|
||||
server.succeed("jq -e '.users.ring.publicKey' /var/lib/proxy-suite/awg-inbounds/roam/state.json")
|
||||
server.succeed("proxy-ctl inbounds link roam ring --config | grep -q '^PrivateKey'")
|
||||
# A change that leaves the peers alone restarts only XRay.
|
||||
|
||||
@@ -52,6 +52,11 @@ let
|
||||
enable = true;
|
||||
serverAddress = "vpn.example.com";
|
||||
users.user.uuidFile = "/run/secrets/uuid";
|
||||
# A policy level per speed slot and the API services the manager uses: XRay must take them.
|
||||
manager = {
|
||||
enable = true;
|
||||
speedLimits.enable = true;
|
||||
};
|
||||
listeners.vless-in = {
|
||||
type = "vless";
|
||||
port = 443;
|
||||
|
||||
@@ -30,6 +30,7 @@ let
|
||||
hybridTproxyConfig
|
||||
hybridTunConfig
|
||||
hybridTunStartScript
|
||||
hybridXmuxStartScript
|
||||
hybridXrayRawStartScript
|
||||
;
|
||||
in
|
||||
@@ -90,6 +91,10 @@ in
|
||||
assert pkgs.lib.hasInfix "--backend sing-box" hybridStartScript;
|
||||
assert pkgs.lib.hasInfix "--backend xray" hybridStartScript;
|
||||
assert pkgs.lib.hasInfix "_proxy_suite_add_xray_sidecar_ob" hybridStartScript;
|
||||
# proxy.xray.xhttpXmux reaches the sidecar's outbounds, and nothing without it.
|
||||
assert !pkgs.lib.hasInfix "xmux" hybridStartScript;
|
||||
assert pkgs.lib.hasInfix ''.streamSettings.xhttpSettings.extra.xmux = {"hKeepAlivePeriod":10}''
|
||||
hybridXmuxStartScript;
|
||||
# The outbounds test pings a sidecar outbound's real server, over UDP when XRay dials
|
||||
# XHTTP over HTTP/3 or mKCP: no TCP handshake to time there.
|
||||
assert pkgs.lib.hasInfix ''.streamSettings.tlsSettings.alpn? == ["h3"]'' hybridStartScript;
|
||||
|
||||
@@ -36,6 +36,10 @@ let
|
||||
};
|
||||
};
|
||||
hybridFixture = evalProxySuite [ hybridModule ];
|
||||
hybridXmuxStartScript = startScript (evalProxySuite [
|
||||
hybridModule
|
||||
{ services.proxy-suite.proxy.xray.xhttpXmux.hKeepAlivePeriod = 10; }
|
||||
]);
|
||||
hybridTproxyConfig = mkTProxyConfig hybridFixture;
|
||||
hybridTunConfig = mkTunConfig hybridFixture;
|
||||
hybridStartScript = startScript hybridFixture;
|
||||
@@ -106,6 +110,7 @@ in
|
||||
hybridTproxyConfig
|
||||
hybridTunConfig
|
||||
hybridTunStartScript
|
||||
hybridXmuxStartScript
|
||||
hybridXrayRawStartScript
|
||||
;
|
||||
}
|
||||
@@ -13,6 +13,10 @@ let
|
||||
serverAddress = "11.0.0.1";
|
||||
# XRay refuses plain VLESS to a public IP, so the client dials a private one.
|
||||
serverPrivateAddress = "10.0.0.1";
|
||||
# The inbounds' own XRay, for its API.
|
||||
xrayApi = "${
|
||||
import ../../pkgs/xray.nix { inherit pkgs; }
|
||||
}/bin/xray api inbounduser --server=unix:///run/proxy-suite-inbounds/api/stats.sock -tag=vless-in";
|
||||
|
||||
network = public: private: {
|
||||
networking.useDHCP = false;
|
||||
@@ -191,10 +195,12 @@ pkgs.testers.runNixOSTest {
|
||||
|
||||
with subtest("runtime users and listeners"):
|
||||
cfg = "/run/proxy-suite-inbounds/config.json"
|
||||
# A user comes through XRay's API: the same XRay, config.json kept in step with it.
|
||||
pid = server.succeed("systemctl show -p MainPID --value proxy-suite-inbounds.service").strip()
|
||||
server.succeed("proxy-ctl inbounds users add friend --listener vless-in")
|
||||
# The reload's restart returns once the start script is forked: config.json is
|
||||
# gone until it renders it again.
|
||||
server.wait_until_succeeds(f"jq -e '.inbounds[] | select(.tag == \"vless-in\") | .settings.clients | map(.email) == [\"tester\", \"friend\"]' {cfg}")
|
||||
server.succeed("${xrayApi} | grep -q friend")
|
||||
assert server.succeed("systemctl show -p MainPID --value proxy-suite-inbounds.service").strip() == pid
|
||||
server.succeed("proxy-ctl inbounds add rt vless --port 9001 --user friend")
|
||||
server.wait_for_open_port(9001)
|
||||
server.succeed("proxy-ctl inbounds users | grep friend | grep -q rt")
|
||||
@@ -225,7 +231,10 @@ pkgs.testers.runNixOSTest {
|
||||
server.succeed(f"jq -e '[.inbounds[].tag] | index(\"rt\") == null' {cfg}")
|
||||
server.succeed("journalctl -u proxy-suite-inbounds | grep -q \"ignoring runtime listener 'rt'\"")
|
||||
server.succeed("rm /var/lib/proxy-suite/inbounds.d/listeners/rt.json")
|
||||
pid = server.succeed("systemctl show -p MainPID --value proxy-suite-inbounds.service").strip()
|
||||
server.succeed("proxy-ctl inbounds users rm friend")
|
||||
server.wait_until_succeeds(f"jq -e '.inbounds[] | select(.tag == \"vless-in\") | .settings.clients | map(.email) == [\"tester\"]' {cfg}")
|
||||
server.fail("${xrayApi} | grep -q friend")
|
||||
assert server.succeed("systemctl show -p MainPID --value proxy-suite-inbounds.service").strip() == pid
|
||||
'';
|
||||
}
|
||||
@@ -251,10 +251,58 @@ let
|
||||
);
|
||||
runtimeNoPortsFixture = mkInbounds (runtimeInbounds // { runtime.enable = true; });
|
||||
|
||||
# inbounds.manager: the daemon, its spec and the XRay config it changes in place.
|
||||
managerInbounds = runtimeInbounds // {
|
||||
manager = {
|
||||
enable = true;
|
||||
speedLimits = {
|
||||
enable = true;
|
||||
slots = 3;
|
||||
};
|
||||
api = {
|
||||
listen = "127.0.0.1:9180";
|
||||
tokensFile = "/run/secrets/manager-tokens";
|
||||
};
|
||||
webhooks = [ { url = "http://127.0.0.1:8088/hook"; } ];
|
||||
};
|
||||
};
|
||||
managerFixture = mkInbounds managerInbounds;
|
||||
managerConfig = mkInboundsConfig managerFixture;
|
||||
managerSpec = mkInboundsSpec managerFixture;
|
||||
managerService = managerFixture.config.systemd.services."proxy-suite-inbounds-manager";
|
||||
policyWithoutManagerFixture = evalWithUsers [
|
||||
baseModule
|
||||
{
|
||||
services.proxy-suite.inbounds = {
|
||||
enable = true;
|
||||
listeners.vless-in = realityListener;
|
||||
users.user.policy.trafficLimit = "10G";
|
||||
};
|
||||
}
|
||||
];
|
||||
speedWithoutLimitsFixture = mkInbounds (
|
||||
lib.recursiveUpdate managerInbounds {
|
||||
manager.speedLimits.enable = false;
|
||||
users.user.policy.speedLimit = "20M/5M";
|
||||
}
|
||||
);
|
||||
unpatchedXrayFixture = mkInbounds (managerInbounds // { package = pkgs.xray; });
|
||||
tokenlessApiFixture = mkInbounds (
|
||||
lib.recursiveUpdate managerInbounds { manager.api.tokensFile = null; }
|
||||
);
|
||||
# subscriptions.keyFile: null generates one, a path is the config's, false is none.
|
||||
keySpec =
|
||||
keyFile:
|
||||
mkInboundsSpec (
|
||||
mkInbounds (lib.recursiveUpdate runtimeInbounds { subscriptions.keyFile = keyFile; })
|
||||
);
|
||||
|
||||
unguardedFixture = mkInbounds {
|
||||
routing = {
|
||||
blockRu = false;
|
||||
blockPrivate = false;
|
||||
blockTorrent = false;
|
||||
blockPorts = [ ];
|
||||
};
|
||||
listeners.vless-in = realityListener;
|
||||
};
|
||||
@@ -915,14 +963,23 @@ let
|
||||
(ok ((ruleByTag relayConfig "inbound-block-ru-domain").domain == [ "geosite:category-ru" ]))
|
||||
(ok ((ruleByTag relayConfig "inbound-block-ru-ip").ip == [ "geoip:ru" ]))
|
||||
(ok (!builtins.elem "inbound-block-private" (ruleTags unguardedConfig)))
|
||||
# What hosters close servers over, ahead of every exception: no listener or via lets it by.
|
||||
(ok ((ruleByTag relayConfig "inbound-block-torrent").protocol == [ "bittorrent" ]))
|
||||
(ok (!(ruleByTag relayConfig "inbound-block-torrent") ? inboundTag))
|
||||
(ok ((ruleByTag relayConfig "inbound-block-ports").port == "25"))
|
||||
(ok ((ruleByTag relayConfig "inbound-block-ports").outboundTag == "block"))
|
||||
(ok (!builtins.elem "inbound-block-torrent" (ruleTags unguardedConfig)))
|
||||
(ok (!builtins.elem "inbound-block-ports" (ruleTags unguardedConfig)))
|
||||
# serverAddress is exempt after blockPrivate, before the country blocks. Sniffing is
|
||||
# routeOnly, so a connection to another IP naming this host in its handshake would match
|
||||
# the name: the guard before it sends those the listener's way.
|
||||
(
|
||||
assert
|
||||
lib.take 5 (ruleTags namedConfig) == [
|
||||
lib.take 7 (ruleTags namedConfig) == [
|
||||
"inbound-stats-api"
|
||||
"inbound-block-private"
|
||||
"inbound-block-torrent"
|
||||
"inbound-block-ports"
|
||||
"inbound-server-address-sniffed-proxy"
|
||||
"inbound-server-address-direct"
|
||||
"inbound-block-ru-domain"
|
||||
@@ -1502,6 +1559,80 @@ let
|
||||
)
|
||||
(ok (!lib.hasInfix "masquerade" (awgRules awgProxyFixture)))
|
||||
|
||||
(
|
||||
let
|
||||
generated = keySpec null;
|
||||
own = keySpec "/run/secrets/sub-key";
|
||||
none = keySpec false;
|
||||
in
|
||||
assert generated.subscriptionKeyFile == null;
|
||||
assert generated.subscriptionKeyStateFile == "/var/lib/proxy-suite/inbounds/subscription-key";
|
||||
assert own.subscriptionKeyFile == "/run/secrets/sub-key";
|
||||
assert own.subscriptionKeyStateFile == null;
|
||||
assert none.subscriptionKeyFile == null;
|
||||
assert none.subscriptionKeyStateFile == null;
|
||||
true
|
||||
)
|
||||
|
||||
# inbounds.manager
|
||||
(
|
||||
assert
|
||||
managerSpec.manager == {
|
||||
policyFile = "/var/lib/proxy-suite/inbounds-manager/policy.json";
|
||||
stateFile = "/var/lib/proxy-suite/inbounds-manager/state.json";
|
||||
statsFile = "/var/lib/proxy-suite/inbound-stats.json";
|
||||
speedLimits = true;
|
||||
};
|
||||
assert runtimeSpec.manager == null;
|
||||
# A level per speed slot, and the API services that change users and rules in place.
|
||||
assert
|
||||
builtins.attrNames managerConfig.policy.levels == [
|
||||
"0"
|
||||
"1"
|
||||
"2"
|
||||
"3"
|
||||
];
|
||||
assert builtins.attrNames relayConfig.policy.levels == [ "0" ];
|
||||
assert builtins.elem "HandlerService" relayConfig.api.services;
|
||||
assert builtins.elem "RoutingService" relayConfig.api.services;
|
||||
true
|
||||
)
|
||||
(
|
||||
let
|
||||
start = readInboundsStart managerFixture;
|
||||
in
|
||||
assert lib.hasInfix "rendered.json" start;
|
||||
assert lib.hasInfix "render-args.json" start;
|
||||
assert lib.hasInfix "--argjson exit_mark 1140850688" start;
|
||||
assert lib.hasInfix "--argjson exit_mark null" (readInboundsStart relayFixture);
|
||||
true
|
||||
)
|
||||
(
|
||||
assert builtins.elem "multi-user.target" managerService.wantedBy;
|
||||
assert builtins.elem "proxy-suite-inbounds.service" managerService.after;
|
||||
assert managerService.serviceConfig.RuntimeDirectory == "proxy-suite-inbounds-manager";
|
||||
assert lib.hasInfix "inbound_manager.py" (
|
||||
(import ./read-generated.nix).readDerivation managerService.serviceConfig.ExecStart
|
||||
);
|
||||
assert !(runtimeFixture.config.systemd.services ? "proxy-suite-inbounds-manager");
|
||||
# Runtime changes go through the API now, a restart only where it cannot.
|
||||
assert lib.hasInfix "inbound_apply.py" (
|
||||
(import ./read-generated.nix).readDerivation
|
||||
runtimeFixture.config.systemd.services."proxy-suite-inbounds-reload".serviceConfig.ExecStart
|
||||
);
|
||||
assert builtins.elem "-/run/proxy-suite-inbounds" (
|
||||
runtimeFixture.config.systemd.services."proxy-suite-inbounds-reload".serviceConfig.ReadWritePaths
|
||||
);
|
||||
true
|
||||
)
|
||||
(ok (failedMessages managerFixture == [ ]))
|
||||
(ok (hasFailed policyWithoutManagerFixture "policy needs inbounds.manager.enable"))
|
||||
(ok (
|
||||
hasFailed speedWithoutLimitsFixture "policy.speedLimit needs inbounds.manager.speedLimits.enable"
|
||||
))
|
||||
(ok (hasFailed unpatchedXrayFixture "needs proxy-suite's XRay"))
|
||||
(ok (hasFailed tokenlessApiFixture "api.listen needs inbounds.manager.api.tokensFile"))
|
||||
|
||||
]
|
||||
++ failing;
|
||||
in
|
||||
|
||||
@@ -67,6 +67,40 @@ pkgs.lib.mapAttrs mkPythonCheck {
|
||||
file = "${scripts}/test-inbound-runtime.py";
|
||||
env = withPath scripts;
|
||||
};
|
||||
# inbounds.manager: policies and the traffic they are measured by, the statuses the
|
||||
# renderers take; changes through XRay's API, against proxy-suite's own XRay; the daemon,
|
||||
# its API and subscriptions, with apply and nftables stubbed.
|
||||
inbound-policy = {
|
||||
file = "${scripts}/test-inbound-policy.py";
|
||||
env = withPath scripts;
|
||||
};
|
||||
inbound-apply = {
|
||||
file = "${scripts}/test-inbound-apply.py";
|
||||
env = withPath scripts // {
|
||||
XRAY = "${import ../../pkgs/xray.nix { inherit pkgs; }}/bin/xray";
|
||||
};
|
||||
};
|
||||
inbound-manager = {
|
||||
file = "${scripts}/test-inbound-manager.py";
|
||||
env = withPath scripts;
|
||||
};
|
||||
# The subscription in each client's format: sing-box checks its config; node runs the page's
|
||||
# QR encoder and zbar reads what it drew.
|
||||
inbound-subscription = {
|
||||
file = "${scripts}/test-inbound-subscription.py";
|
||||
env =
|
||||
withPath scripts
|
||||
// singBox
|
||||
// {
|
||||
NODE = "${pkgs.nodejs-slim}/bin/node";
|
||||
ZBARIMG = "${pkgs.zbar}/bin/zbarimg";
|
||||
};
|
||||
};
|
||||
# The per-app routes' DNS forwarder: its log lines, and a lost query asked again.
|
||||
per-app-dns = {
|
||||
file = "${scripts}/test-per-app-dns.py";
|
||||
env = withPath scripts;
|
||||
};
|
||||
# The NFQWS_OPT rewrites the zapret v1 package build applies.
|
||||
patch-zapret-config = {
|
||||
file = "${scripts}/test-patch-zapret-config.py";
|
||||
|
||||
@@ -88,6 +88,8 @@ let
|
||||
|
||||
relayTorStart = torStartOf (mkFixture "sing-box" { tor.clientOnly = false; });
|
||||
|
||||
awakeTorStart = torStartOf (mkFixture "sing-box" { tor.keepAwake = true; });
|
||||
|
||||
noOnion = mkFixture "sing-box" { tor.routeOnion = false; };
|
||||
noOnionTun = mkTunConfig noOnion;
|
||||
|
||||
@@ -469,6 +471,9 @@ in
|
||||
&& hasInfix "DNSPort 0" singBoxTorStart
|
||||
&& hasInfix "ClientOnly 1" singBoxTorStart
|
||||
&& !(hasInfix "ClientOnly" relayTorStart)
|
||||
&& !(hasInfix "Dormant" singBoxTorStart)
|
||||
&& hasInfix "DormantTimeoutEnabled 0" awakeTorStart
|
||||
&& hasInfix "DormantCanceledByStartup 1" awakeTorStart
|
||||
&& hasInfix "ControlSocket unix:$RUNTIME_DIRECTORY/control/socket" singBoxTorStart
|
||||
&& !(hasInfix "UseBridges" singBoxTorStart)
|
||||
&& !(hasInfix "Socks5Proxy" singBoxTorStart)
|
||||
|
||||
@@ -90,8 +90,14 @@ pkgs.testers.runNixOSTest {
|
||||
];
|
||||
networking.hosts."203.0.113.3" = [ "blocked.test" ];
|
||||
environment.systemPackages = [ pkgs.curl ];
|
||||
# A member of the group, whose edits leave the lists theirs.
|
||||
users.users.alice = {
|
||||
isNormalUser = true;
|
||||
extraGroups = [ "proxy-suite" ];
|
||||
};
|
||||
services.proxy-suite = {
|
||||
enable = true;
|
||||
userControl.enable = true;
|
||||
# An outbound to hand what zapret2 cannot fix to; nothing here dials it.
|
||||
proxy = {
|
||||
enable = true;
|
||||
@@ -147,6 +153,11 @@ pkgs.testers.runNixOSTest {
|
||||
def learned(host):
|
||||
return f"grep -qx {host} ${state}/zapret-hosts-auto.txt"
|
||||
|
||||
with subtest("lists a member rewrote are theirs, and nfqws2 still writes to them"):
|
||||
client.succeed("touch ${state}/verdicts.tsv", "su - alice -c 'proxy-ctl zapret auto clear'")
|
||||
client.succeed("test \"$(stat -c %U ${state}/zapret-hosts-auto.txt ${state}/verdicts.tsv | sort -u)\" = alice")
|
||||
# Everything below learns into them and judges into them.
|
||||
|
||||
with subtest("a site blocked two times in three is learned, successes in between"):
|
||||
for _ in range(9):
|
||||
curl("flaky.test")
|
||||
|
||||
+25
-3
@@ -50,10 +50,16 @@ let
|
||||
daemonStart = zapret2Global.config.systemd.services.${globalService}.serviceConfig.ExecStart;
|
||||
cutoffProbe =
|
||||
zapret2Global.config.systemd.services.proxy-suite-zapret2-cutoff.serviceConfig.ExecStart;
|
||||
z2kCutoffProbe =
|
||||
zapret2Z2k.config.systemd.services.proxy-suite-zapret2-cutoff.serviceConfig.ExecStart;
|
||||
socksStart = fixture: fixture.config.systemd.services.proxy-suite-socks.serviceConfig.ExecStart;
|
||||
directSync = builtins.head (
|
||||
lib.splitString " " zapret2Global.config.systemd.services.proxy-suite-zapret2-direct.serviceConfig.ExecStart
|
||||
);
|
||||
directSyncOf =
|
||||
fixture:
|
||||
builtins.head (
|
||||
lib.splitString " " fixture.config.systemd.services.proxy-suite-zapret2-direct.serviceConfig.ExecStart
|
||||
);
|
||||
directSync = directSyncOf zapret2Global;
|
||||
noAutoDirectSync = directSyncOf zapret2NoAuto;
|
||||
|
||||
proxyCtlEnv = fixture: (mkProxyCtlDerived fixture).wrapperEnv;
|
||||
in
|
||||
@@ -319,6 +325,13 @@ in
|
||||
# nfqws2-keenetic learns with detect.lua too: its own profile only reads the auto list.
|
||||
grep -qE -- " --new --filter-tcp=443 --filter-l7=tls --in-range=-s65536 --out-range=-s32768 --payload=all --lua-desync=ps_learn:auto=[^ ]+:exclude=[^ ]+/etc/nfqws2/lists/exclude.list,[^ ]+zapret-hosts-user-exclude.txt:" "${globalRuntime}/config"
|
||||
test "$(grep -oF -- '<HOSTLIST>' "${globalRuntime}/config" | wc -l)" = 0
|
||||
# The profile that takes the learned sites follows their transfers ahead of rotation,
|
||||
# its filters back at their defaults after; circular keeps its name for its sites.
|
||||
grep -qE -- " --in-range=-s65536 --payload=all --lua-desync=ps_watch:fails=3:time=300:win=32:log --in-range=x --payload=all --in-range=-s5556 [^ ]+ --lua-desync=circular:[^ ]*:key=circular_3_1:" "${globalRuntime}/config"
|
||||
grep -qE -- " --lua-desync=ps_watch:fails=3:time=300:win=32:log --in-range=x --payload=all --out-range=-s34228 --in-range=-s5556 --lua-desync=z2k_sni_pick:[^ ]*:key=rkn_tcp:" "${z2kRuntime}/config"
|
||||
test "$(grep -oF -- 'ps_watch:' "${z2kRuntime}/config" | wc -l)" = 1
|
||||
if grep -qF -- 'ps_watch' "${tunedRuntime}/config"; then exit 1; fi
|
||||
if grep -qF -- '<STALLWATCH>' "${tunedRuntime}/config"; then exit 1; fi
|
||||
# Counted failures and switches, named by circular key and host; the switch
|
||||
# is the one that stuck, after the state layer's revert.
|
||||
LOG=$(grep -oE '/nix/store/[^ ]+-strategy-log\.lua' "${z2kRuntime}/config") lua -e '
|
||||
@@ -456,6 +469,11 @@ in
|
||||
printf '24940\t300.ya.ru\n14061\tad.adriver.ru\n' >sni.txt
|
||||
test "$("$rules" asn.txt sni.txt nets.txt)" = '{"version":1,"rules":[]}'
|
||||
|
||||
# A name helps only where z2k's profiles put it in: elsewhere none is searched for,
|
||||
# one kept from before is dropped, and every cut-off network goes to the proxy.
|
||||
grep -qF -- 'if [ 0 = 0 ] && [ -s sni.txt ]; then' ${cutoffProbe}
|
||||
grep -qF -- 'if [ 1 = 0 ] && [ -s sni.txt ]; then' ${z2kCutoffProbe}
|
||||
|
||||
# The probe is built from z2k's source and knows its tcp16 mode.
|
||||
detect=$(grep -o '/nix/store/[^:]*-z2k-detect-[^:/]*/bin' ${cutoffProbe} | head -n1)
|
||||
"$detect/z2k-detect" tcp16 -h 2>/dev/null
|
||||
@@ -509,6 +527,10 @@ in
|
||||
${directSync} direct-lists out dns-cache
|
||||
test "$(stat -c %i out/direct.json)" = "$inode"
|
||||
test "$(cat out/names.tsv)" = "$(printf '149.154.167.99\tother.example,www.example.com')"
|
||||
# Learning off: nfqws2 ignores what was learned, so the proxy does too.
|
||||
mkdir no-auto-out
|
||||
${noAutoDirectSync} direct-lists no-auto-out dns-cache
|
||||
test "$(cat no-auto-out/direct.json)" = '{"version":1,"rules":[{"domain_suffix":["pinned.example"]}]}'
|
||||
${directSync} empty-lists empty-out
|
||||
test "$(cat empty-out/direct.json)" = '{"version":1,"rules":[]}'
|
||||
test "$(cat empty-out/proxy.json)" = '{"version":1,"rules":[]}'
|
||||
|
||||
@@ -235,6 +235,34 @@ end
|
||||
assert(verdicts()["149.154.167.99 ip"] == "blocked" and not verdicts()["192.168.1.1 ip"], "blocked by address")
|
||||
syn("149.154.167.99", true)
|
||||
assert(verdicts()["149.154.167.99 ip"] == "reachable", "an answer clears it")
|
||||
-- A learned site a strategy got through, cut short past the first 4 KB since: three cut
|
||||
-- transfers keep it on the proxy. Finished ones, ones the client hung up on, and ones
|
||||
-- past the queue window say nothing.
|
||||
local function watch(track, outgoing, opts) ps_watch(nil, packet(track, outgoing, opts)) end
|
||||
for i = 1, 3 do
|
||||
local t = flow("i.scdn.co")
|
||||
watch(t, true, { l7 = "tls_client_hello", payload = "hello" })
|
||||
watch(t, false, { s = 1, payload = record(16000) .. string.rep("x", 6000), n = 5 })
|
||||
watch(t, false, { s = 6006, payload = string.rep("x", 2000), n = 7 })
|
||||
fire("psws_")
|
||||
assert((verdicts()["i.scdn.co cutoff"] == "stalls") == (i == 3), "stalls after three cut transfers")
|
||||
end
|
||||
for _, case in ipairs({ "whole", "hangup", "big" }) do
|
||||
for _ = 1, 3 do
|
||||
local t = flow(case .. ".example")
|
||||
if case == "whole" then
|
||||
watch(t, false, { s = 1, payload = record(3) .. "abc", n = 2 })
|
||||
elseif case == "hangup" then
|
||||
watch(t, false, { s = 1, payload = record(16000) .. "x", n = 2 })
|
||||
watch(t, true, { flags = TH_FIN + 16 })
|
||||
else
|
||||
watch(t, false, { s = 1, payload = record(60000) .. "z", n = 32 })
|
||||
end
|
||||
fire("psws_")
|
||||
end
|
||||
assert(not verdicts()[case .. ".example cutoff"], case .. ": no verdict")
|
||||
end
|
||||
|
||||
-- A wildcard domain whose every fresh name resets: past its share of the list, the site
|
||||
-- itself is learned, which covers the rest, rather than one more name of it.
|
||||
local f2 = io.open(auto, "a")
|
||||
|
||||
@@ -4,6 +4,7 @@ let
|
||||
mkTgWsProxy = _args: import ./tg-ws-proxy.nix { inherit pkgs; };
|
||||
zapret2 = import ./zapret2.nix { inherit pkgs; };
|
||||
whitelist-bypass = import ./whitelist-bypass.nix { inherit pkgs; };
|
||||
z2k-detect = import ./z2k-detect.nix { inherit pkgs; };
|
||||
mkProxySuiteSupervisor = import ./proxy-suite-supervisor.nix {
|
||||
lib = pkgs.lib;
|
||||
inherit pkgs;
|
||||
@@ -24,6 +25,7 @@ in
|
||||
mkProxySuiteSupervisor
|
||||
zapret2
|
||||
whitelist-bypass
|
||||
z2k-detect
|
||||
;
|
||||
tg-ws-proxy = mkTgWsProxy { };
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
--- a/transport/internet/system_dialer.go
|
||||
+++ b/transport/internet/system_dialer.go
|
||||
@@ -6,8 +6,11 @@
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
+ "google.golang.org/protobuf/proto"
|
||||
+
|
||||
"github.com/xtls/xray-core/common/errors"
|
||||
"github.com/xtls/xray-core/common/net"
|
||||
+ "github.com/xtls/xray-core/common/session"
|
||||
"github.com/xtls/xray-core/features/dns"
|
||||
"github.com/xtls/xray-core/features/outbound"
|
||||
)
|
||||
@@ -46,8 +49,32 @@
|
||||
}
|
||||
}
|
||||
|
||||
+// proxy-suite: an outbound whose sockopt.mark carries userLevelMarkFlag marks each socket
|
||||
+// with the rest of the mark plus the level of the inbound user it dials for, and leaves
|
||||
+// those of level 0 unmarked: one outbound, and one routing rule, for users the kernel
|
||||
+// tells apart (their speed limits).
|
||||
+const userLevelMarkFlag = 0x40000000
|
||||
+
|
||||
+func userLevelMark(ctx context.Context, sockopt *SocketConfig) *SocketConfig {
|
||||
+ if sockopt == nil || sockopt.Mark&userLevelMarkFlag == 0 {
|
||||
+ return sockopt
|
||||
+ }
|
||||
+ var level int32
|
||||
+ if inbound := session.InboundFromContext(ctx); inbound != nil && inbound.User != nil {
|
||||
+ level = int32(inbound.User.Level)
|
||||
+ }
|
||||
+ marked := proto.Clone(sockopt).(*SocketConfig)
|
||||
+ if level == 0 {
|
||||
+ marked.Mark = 0
|
||||
+ } else {
|
||||
+ marked.Mark = sockopt.Mark&^userLevelMarkFlag + level
|
||||
+ }
|
||||
+ return marked
|
||||
+}
|
||||
+
|
||||
func (d *DefaultSystemDialer) Dial(ctx context.Context, src net.Address, dest net.Destination, sockopt *SocketConfig) (net.Conn, error) {
|
||||
errors.LogDebug(ctx, "dialing to "+dest.String())
|
||||
+ sockopt = userLevelMark(ctx, sockopt)
|
||||
|
||||
if dest.Network == net.Network_UDP {
|
||||
destAddr, err := net.ResolveUDPAddr("udp", dest.NetAddr())
|
||||
+2
-1
@@ -115,9 +115,10 @@ let
|
||||
Name=Proxy Suite
|
||||
GenericName=Proxy Control
|
||||
Comment=Control proxy-suite services, routing and outbounds
|
||||
Exec=$out/bin/proxy-suite-gui
|
||||
Exec=$out/bin/proxy-suite-gui %u
|
||||
Icon=io.github.FUFSoB.ProxySuite
|
||||
Categories=Network;System;
|
||||
MimeType=x-scheme-handler/proxy-suite;
|
||||
Keywords=proxy;vpn;sing-box;zapret;tray;
|
||||
StartupNotify=true
|
||||
Terminal=false
|
||||
|
||||
+395
-11
@@ -204,6 +204,29 @@ Changes and secrets need root or the userControl group.
|
||||
inbounds rm <tag> remove a runtime listener
|
||||
inbounds show <tag> a runtime listener's JSON
|
||||
inbounds online who is online, and when others were last seen
|
||||
|
||||
With inbounds.manager (users' policies; the API proxy-ctl and bots use):
|
||||
inbounds users [list] [--json] users, whether they may connect, traffic, expiry
|
||||
inbounds users show <name> [--json] one user: policy, traffic, online, subscription
|
||||
inbounds users add <name> [...] [policy flags]
|
||||
add a runtime user with a policy
|
||||
inbounds users set <name> [--expires 2026-12-31|+30d] [--on-hold 30d] [--traffic 50G]
|
||||
[--period monthly] [--ips 2] [--speed 20M/5M] [--enable|--disable] [--meta key=value]...
|
||||
change a user's policy (declared users too);
|
||||
--on-hold: a term that starts on the first connection
|
||||
inbounds users unset <name> <expires|hold|traffic|period|ips|speed|meta|enabled>...
|
||||
back to the config's value, or none
|
||||
inbounds users enable|disable <name> switch a user on or off
|
||||
inbounds users reset <name> start their traffic over
|
||||
inbounds users extend <name> 30d [--reset]
|
||||
move the expiry on (from now, or from it if later;
|
||||
on hold: a longer term); --reset: traffic anew too
|
||||
inbounds users extend <name> --until <time> [--reset]
|
||||
inbounds users rotate-sub <name> a new subscription URL, the old one stops answering
|
||||
inbounds bans [rm <address>] addresses banned past a user's ipLimit
|
||||
inbounds export [file] [--no-stats] users, policies, keys and traffic, to move them
|
||||
inbounds import <file|-> [--replace] take them in on this server
|
||||
inbounds events [N] what the manager did and told its webhooks
|
||||
"""
|
||||
|
||||
ROUTE_MODES = ["whitelist", "blacklist", "all-proxy", "all-bypass"]
|
||||
@@ -1016,19 +1039,46 @@ COMPLETE = {
|
||||
"add": "add a listener at runtime",
|
||||
"rm": "remove a runtime listener",
|
||||
"show": "a runtime listener's JSON",
|
||||
"bans": "addresses banned past a user's ipLimit",
|
||||
"export": "users, policies, keys and traffic as JSON",
|
||||
"import": "take an export in",
|
||||
"events": "what the inbound manager did",
|
||||
}
|
||||
},
|
||||
"inbounds import": {"flags": {"--replace": "the export wins over what is here"}},
|
||||
"inbounds export": {"flags": {"--no-stats": "leave the traffic counts out"}},
|
||||
"inbounds stats": {"flags": {"--by": "user, inbound or outbound"}},
|
||||
"inbounds users": {
|
||||
"words": {
|
||||
"list": "users, their order, address and listeners",
|
||||
"show": "one user's policy, traffic and subscription",
|
||||
"add": "add a user at runtime",
|
||||
"rm": "remove a runtime user",
|
||||
"order": "set a runtime user's order",
|
||||
"listeners": "put a user on exactly these listeners",
|
||||
"on": "put exactly these users on a listener",
|
||||
"set": "change a user's policy",
|
||||
"unset": "drop policy fields set at runtime",
|
||||
"enable": "switch a user on",
|
||||
"disable": "switch a user off",
|
||||
"reset": "start a user's traffic over",
|
||||
"extend": "move a user's expiry on",
|
||||
"rotate-sub": "give a user a new subscription URL",
|
||||
}
|
||||
},
|
||||
"inbounds users show": {"args": lambda: _inbound_runtime_names("users")},
|
||||
"inbounds users set": {
|
||||
"args": lambda: _inbound_runtime_names("users"),
|
||||
"flags": {"--expires": "a date, +30d, never", "--on-hold": "30d: from the first connection", "--traffic": "50G, none", "--period": "daily, weekly, monthly, none",
|
||||
"--ips": "addresses at once", "--speed": "20M or down/up", "--enable": "switch on",
|
||||
"--disable": "switch off", "--meta": "key=value"},
|
||||
},
|
||||
"inbounds users unset": {"args": lambda: {**_inbound_runtime_names("users"), **{k: "" for k in POLICY_NAMES}}, "repeat": True},
|
||||
"inbounds users enable": {"args": lambda: _inbound_runtime_names("users")},
|
||||
"inbounds users disable": {"args": lambda: _inbound_runtime_names("users")},
|
||||
"inbounds users reset": {"args": lambda: _inbound_runtime_names("users")},
|
||||
"inbounds users extend": {"args": lambda: _inbound_runtime_names("users")},
|
||||
"inbounds users rotate-sub": {"args": lambda: _inbound_runtime_names("users")},
|
||||
"inbounds users listeners": {"args": lambda: {**_inbound_runtime_names("users"), **_inbound_runtime_names("listeners")}, "repeat": True},
|
||||
"inbounds users on": {"args": lambda: {**_inbound_runtime_names("listeners"), **_inbound_runtime_names("users")}, "repeat": True},
|
||||
"inbounds users add": {"flags": {"--order": "its serverSource number", "--listener": "a listener to put it on"}},
|
||||
@@ -2344,15 +2394,21 @@ class GroupWatch:
|
||||
return status == 200 and isinstance(body, dict) and "delay" in body
|
||||
|
||||
def record(self, tag, ok, hinted=False):
|
||||
# Logged: each miss of a member still up, and its going down and up. A hiccup that heals
|
||||
# before the member goes down leaves those misses, and nothing else, behind.
|
||||
h = self.health.setdefault(tag, {"up": True, "misses": 0, "passes": 0, "since": self.wall()})
|
||||
if ok:
|
||||
h["misses"], h["passes"] = 0, h["passes"] + 1
|
||||
if not h["up"] and h["passes"] >= GROUP_PASSES_UP:
|
||||
h["up"], h["since"] = True, self.wall()
|
||||
print(f"{tag}: up again", file=sys.stderr)
|
||||
else:
|
||||
h["passes"], h["misses"] = 0, h["misses"] + 1
|
||||
if h["up"]:
|
||||
print(f"{tag}: test failed ({h['misses']}/{1 if hinted else GROUP_MISSES_DOWN}{', after a hint' if hinted else ''})", file=sys.stderr)
|
||||
if h["up"] and (hinted or h["misses"] >= GROUP_MISSES_DOWN):
|
||||
h["up"], h["since"] = False, self.wall()
|
||||
print(f"{tag}: down", file=sys.stderr)
|
||||
|
||||
def up(self, tag):
|
||||
return self.health.get(tag, {}).get("up", True)
|
||||
@@ -4420,21 +4476,25 @@ def _replace_lines(path, keep, extra=()):
|
||||
"""Rewrites path with the lines keep() accepts, plus extra.
|
||||
|
||||
Via a temp file in the same directory, with the old file's owner and mode (a new one
|
||||
world-readable: unprivileged proxy-ctl reads these lists too). Locked against another
|
||||
proxy-ctl; what nfqws2 appended meanwhile, unlocked, is carried over before the rename.
|
||||
world-readable: unprivileged proxy-ctl reads these lists too), group-writable where the
|
||||
directory is: renamed in by a member, the file is theirs, and nfqws2 appends to it as one
|
||||
of the group. Locked against another proxy-ctl; what nfqws2 appended meanwhile,
|
||||
unlocked, is carried over before the rename.
|
||||
"""
|
||||
with _file_lock(path):
|
||||
try:
|
||||
old = os.lstat(path) if os.path.lexists(path) else None
|
||||
text = read_shared_text(path) if old else ""
|
||||
fd, tmp = tempfile.mkstemp(prefix=os.path.basename(path) + ".", dir=os.path.dirname(path) or ".")
|
||||
directory = os.path.dirname(path) or "."
|
||||
shared = os.stat(directory).st_mode & stat.S_IWGRP
|
||||
fd, tmp = tempfile.mkstemp(prefix=os.path.basename(path) + ".", dir=directory)
|
||||
except OSError:
|
||||
denied(path, "write")
|
||||
try:
|
||||
with os.fdopen(fd, "w", encoding="utf-8") as f:
|
||||
f.writelines(f"{line}\n" for line in [*filter(keep, lines(text)), *extra])
|
||||
# By fd, not path: tmp's name could be swapped for a symlink in between.
|
||||
os.fchmod(f.fileno(), stat.S_IMODE(old.st_mode) & 0o777 if old else 0o644)
|
||||
os.fchmod(f.fileno(), (stat.S_IMODE(old.st_mode) & 0o777 if old else 0o644) | shared)
|
||||
if old and os.geteuid() == 0:
|
||||
os.fchown(f.fileno(), old.st_uid, old.st_gid)
|
||||
# Newer than anything this edit means to drop: kept as they came.
|
||||
@@ -6088,11 +6148,17 @@ def _inbound_subscriptions(*args):
|
||||
user = arg
|
||||
path = env("INBOUNDS_SUBS_FILE", f"{runtime_dir()}/proxy-suite-inbounds/subscriptions.json")
|
||||
base = env("INBOUNDS_SUB_BASE_URL")
|
||||
if not os.path.isfile(path):
|
||||
if not os.path.isfile(path) and _manager_enabled():
|
||||
# Served by the manager only (no static files): its API knows the tokens.
|
||||
rows = [r for r in _manager("GET", "/users") if r.get("subscription")]
|
||||
subs = [{"user": r["name"], "token": r["subscription"]["token"]} for r in rows]
|
||||
path = ""
|
||||
elif not os.path.isfile(path):
|
||||
die("No subscriptions available. Is proxy-suite-inbounds running, and is inbounds.subscriptions enabled?")
|
||||
if not readable(path):
|
||||
elif not readable(path):
|
||||
denied(path)
|
||||
subs = read_json(path)
|
||||
else:
|
||||
subs = read_json(path)
|
||||
if not user:
|
||||
if qr:
|
||||
usage("inbounds sub <user> --qr")
|
||||
@@ -6109,7 +6175,8 @@ def _inbound_subscriptions(*args):
|
||||
else:
|
||||
if qr:
|
||||
die("A QR code needs inbounds.subscriptions.baseUrl.")
|
||||
print(f"{path.removesuffix('.json')}/{_s(token)}")
|
||||
# The manager's: the token, which its socket serves at any path ending in it.
|
||||
print(f"{path.removesuffix('.json')}/{_s(token)}" if path else _s(token))
|
||||
sys.stdout.flush()
|
||||
print("Set inbounds.subscriptions.baseUrl to get a URL instead of a path.", file=sys.stderr)
|
||||
|
||||
@@ -6204,7 +6271,311 @@ def _inbound_runtime_apply():
|
||||
print(f"warning: {line}", file=sys.stderr)
|
||||
|
||||
|
||||
# --- the inbound manager --------------------------------------------------------
|
||||
#
|
||||
# inbounds.manager: a daemon with an HTTP+JSON API on a Unix socket (scripts/inbound_manager.py),
|
||||
# which bots use too. `inbounds users show|set|unset|enable|disable|reset|extend`, bans, export
|
||||
# and import go to it; with it on, adding and removing users do as well, so a user's policy
|
||||
# comes and goes with them.
|
||||
|
||||
MANAGER_TIMEOUT = 120
|
||||
# The CLI's names for the policy's fields, as `users set` takes them and `users unset` names them.
|
||||
POLICY_FLAGS = {
|
||||
"--expires": "expiresAt",
|
||||
"--on-hold": "expiresAfter",
|
||||
"--traffic": "trafficLimit",
|
||||
"--period": "trafficPeriod",
|
||||
"--ips": "ipLimit",
|
||||
"--speed": "speedLimit",
|
||||
}
|
||||
POLICY_NAMES = {
|
||||
"expires": "expiresAt",
|
||||
"hold": "expiresAfter",
|
||||
"traffic": "trafficLimit",
|
||||
"period": "trafficPeriod",
|
||||
"ips": "ipLimit",
|
||||
"speed": "speedLimit",
|
||||
"meta": "meta",
|
||||
"enabled": "enabled",
|
||||
}
|
||||
|
||||
|
||||
def _manager_enabled():
|
||||
return bool(env("INBOUNDS_MANAGER_SOCKET"))
|
||||
|
||||
|
||||
def _manager(method, path, body=None):
|
||||
"""One call to the manager's API: its JSON, or its complaint as ours."""
|
||||
socket_path = env("INBOUNDS_MANAGER_SOCKET")
|
||||
if not socket_path:
|
||||
die("The inbound manager is not enabled in this configuration (inbounds.manager.enable).")
|
||||
conn = _UnixHTTPConnection(socket_path, MANAGER_TIMEOUT)
|
||||
try:
|
||||
conn.request(method, "/api/v1" + path, body=None if body is None else json.dumps(body),
|
||||
headers={"Content-Type": "application/json"})
|
||||
response = conn.getresponse()
|
||||
status, raw = response.status, response.read()
|
||||
except PermissionError:
|
||||
die(f"Cannot use the inbound manager ({socket_path}): permission denied - {ask_group()}.", 77)
|
||||
except (FileNotFoundError, ConnectionRefusedError):
|
||||
die("The inbound manager is not running - see: proxy-ctl logs proxy-suite-inbounds-manager")
|
||||
except (OSError, http.client.HTTPException) as e:
|
||||
die(f"Cannot reach the inbound manager: {e}")
|
||||
finally:
|
||||
conn.close()
|
||||
try:
|
||||
value = json.loads(raw) if raw else None
|
||||
except ValueError:
|
||||
value = None
|
||||
if status >= 400:
|
||||
error = value.get("error") if isinstance(value, dict) else None
|
||||
die(error or f"The inbound manager answered {status}.")
|
||||
return value
|
||||
|
||||
|
||||
def _when(ts):
|
||||
return datetime.datetime.fromtimestamp(ts).strftime("%Y-%m-%d %H:%M") if ts else "-"
|
||||
|
||||
|
||||
def _rate(bits):
|
||||
if not bits:
|
||||
return "-"
|
||||
for unit, size in (("Gbit/s", 1e9), ("Mbit/s", 1e6), ("kbit/s", 1e3)):
|
||||
if bits >= size:
|
||||
return f"{bits / size:g} {unit}"
|
||||
return f"{bits} bit/s"
|
||||
|
||||
|
||||
def _user_status(row):
|
||||
if not row.get("active"):
|
||||
return "off: " + ",".join(row.get("reasons") or [])
|
||||
return "on hold" if row.get("onHold") else "active"
|
||||
|
||||
|
||||
def _user_expiry(row):
|
||||
if row.get("onHold"):
|
||||
return f"+{_span((row.get('policy') or {}).get('expiresAfter'))} on 1st use"
|
||||
return _when(row.get("expiresAt"))
|
||||
|
||||
|
||||
def _span(seconds):
|
||||
for unit, size in (("w", 604800), ("d", 86400), ("h", 3600), ("m", 60)):
|
||||
if seconds and seconds % size == 0:
|
||||
return f"{seconds // size}{unit}"
|
||||
return f"{seconds}s"
|
||||
|
||||
|
||||
def _user_traffic(row):
|
||||
traffic = row.get("traffic") or {}
|
||||
used = _human_bytes(traffic.get("used") or 0)
|
||||
return f"{used} / {_human_bytes(traffic['limit'])}" if traffic.get("limit") else used
|
||||
|
||||
|
||||
def _manager_users_table(rows):
|
||||
line = " {:<20} {:<18} {:<24} {:<17} {}"
|
||||
print(line.format("USER", "STATUS", "TRAFFIC", "EXPIRES", "LISTENERS").rstrip())
|
||||
for row in rows:
|
||||
print(line.format(_s(row["name"]), _user_status(row), _user_traffic(row), _user_expiry(row),
|
||||
",".join(row.get("listeners") or []) or "-").rstrip())
|
||||
for problem in row.get("problems") or []:
|
||||
print(f" ! {problem}")
|
||||
|
||||
|
||||
def _manager_user_show(row):
|
||||
policy = row.get("policy") or {}
|
||||
traffic = row.get("traffic") or {}
|
||||
speed = policy.get("speedLimit") or {}
|
||||
out = [
|
||||
f"{row['name']} ({row.get('source')}): {_user_status(row)}",
|
||||
f" listeners {', '.join(row.get('listeners') or []) or '-'}",
|
||||
f" expires {_user_expiry(row)}",
|
||||
f" traffic {_user_traffic(row)} (down {_human_bytes(traffic.get('down') or 0)}, up {_human_bytes(traffic.get('up') or 0)})"
|
||||
+ (f", renews {policy['trafficPeriod']} at {_when(traffic.get('periodEnd'))}" if traffic.get("periodEnd") else ""),
|
||||
f" since {_when(traffic.get('periodStart'))}",
|
||||
f" addresses {policy.get('ipLimit') or 'any number'} at once; online: {', '.join(row['online']['ips']) or '-'}",
|
||||
f" speed down {_rate(speed.get('down'))}, up {_rate(speed.get('up'))}",
|
||||
]
|
||||
if row.get("subscription") and row["subscription"].get("url"):
|
||||
out.append(f" sub {row['subscription']['url']}")
|
||||
for key, value in sorted((policy.get("meta") or {}).items()):
|
||||
out.append(f" meta.{key} = {value}")
|
||||
overridden = sorted(set(row.get("stored") or {}) & set(row.get("declared") or {}))
|
||||
if overridden:
|
||||
out.append(f" (set at runtime over the config: {', '.join(overridden)})")
|
||||
for problem in row.get("problems") or []:
|
||||
out.append(f" ! {problem}")
|
||||
print("\n".join(out))
|
||||
|
||||
|
||||
def _policy_args(args):
|
||||
"""Policy fields from `users set`'s flags; the arguments that are none of them."""
|
||||
fields, rest, i = {}, [], 0
|
||||
args = list(args)
|
||||
while i < len(args):
|
||||
arg = args[i]
|
||||
flag, has_value, value = arg.partition("=")
|
||||
if flag in POLICY_FLAGS or flag == "--meta":
|
||||
if not has_value:
|
||||
if i + 1 >= len(args):
|
||||
usage(f"inbounds users set <name> {flag} <value>")
|
||||
value = args[i + 1]
|
||||
i += 1
|
||||
if flag == "--meta":
|
||||
key, sep, item = value.partition("=")
|
||||
if not sep:
|
||||
usage("inbounds users set <name> --meta <key>=<value>")
|
||||
fields.setdefault("meta", {})[key] = item
|
||||
else:
|
||||
fields[POLICY_FLAGS[flag]] = value
|
||||
elif arg in ("--enable", "--disable"):
|
||||
fields["enabled"] = arg == "--enable"
|
||||
else:
|
||||
rest.append(arg)
|
||||
i += 1
|
||||
return fields, rest
|
||||
|
||||
|
||||
def _manager_users(verb, args):
|
||||
"""`inbounds users ...` with the manager on. False: not one of its verbs."""
|
||||
as_json = "--json" in args
|
||||
args = [a for a in args if a != "--json"]
|
||||
|
||||
def show(row):
|
||||
print(_json_text(row)) if as_json else _manager_user_show(row)
|
||||
|
||||
if verb in ("list", "--json"):
|
||||
rows = _manager("GET", "/users")
|
||||
print(_json_text(rows)) if as_json or verb == "--json" else _manager_users_table(rows)
|
||||
elif verb == "show" and len(args) == 1:
|
||||
show(_manager("GET", f"/users/{urllib.parse.quote(args[0], safe='')}"))
|
||||
elif verb == "add" and args:
|
||||
fields, rest = _policy_args(args[1:])
|
||||
listeners, order, i = [], None, 0
|
||||
while i < len(rest):
|
||||
if rest[i] in ("--listener", "--order") and i + 1 < len(rest):
|
||||
if rest[i] == "--listener":
|
||||
listeners.append(rest[i + 1])
|
||||
else:
|
||||
order = int(rest[i + 1]) if rest[i + 1].isdigit() else die(f"Not an order: {rest[i + 1]}")
|
||||
i += 2
|
||||
else:
|
||||
usage("inbounds users add <name> [--order N] [--listener <tag>]... [policy flags: see users set]")
|
||||
body = {"name": args[0], "listeners": listeners, "policy": fields}
|
||||
if order is not None:
|
||||
body["order"] = order
|
||||
show(_manager("POST", "/users", body))
|
||||
elif verb == "rm" and len(args) == 1:
|
||||
print(_manager("DELETE", f"/users/{urllib.parse.quote(args[0], safe='')}").get("message", ""))
|
||||
elif verb == "set" and args:
|
||||
fields, rest = _policy_args(args[1:])
|
||||
if rest or not fields:
|
||||
usage("inbounds users set <name> [--expires T] [--traffic SIZE] [--period daily|weekly|monthly|none]"
|
||||
" [--ips N] [--speed RATE[/RATE]] [--enable|--disable] [--meta k=v]...")
|
||||
show(_manager("PATCH", f"/users/{urllib.parse.quote(args[0], safe='')}", fields))
|
||||
elif verb == "unset" and len(args) >= 2:
|
||||
unknown = [a for a in args[1:] if a not in POLICY_NAMES]
|
||||
if unknown:
|
||||
usage(f"inbounds users unset <name> <{'|'.join(POLICY_NAMES)}>...")
|
||||
show(_manager("PATCH", f"/users/{urllib.parse.quote(args[0], safe='')}", {"unset": [POLICY_NAMES[a] for a in args[1:]]}))
|
||||
elif verb in ("enable", "disable") and len(args) == 1:
|
||||
show(_manager("POST", f"/users/{urllib.parse.quote(args[0], safe='')}/{verb}"))
|
||||
elif verb == "reset" and len(args) == 1:
|
||||
show(_manager("POST", f"/users/{urllib.parse.quote(args[0], safe='')}/reset-traffic"))
|
||||
elif verb == "extend" and len([a for a in args if a != "--reset"]) in (2, 3):
|
||||
reset = "--reset" in args
|
||||
rest = [a for a in args if a != "--reset"]
|
||||
if len(rest) == 2:
|
||||
body = {"by": rest[1]}
|
||||
elif rest[1] == "--until":
|
||||
body = {"until": rest[2]}
|
||||
else:
|
||||
usage("inbounds users extend <name> <30d | --until <time>> [--reset]")
|
||||
if reset:
|
||||
body["resetTraffic"] = True
|
||||
show(_manager("POST", f"/users/{urllib.parse.quote(rest[0], safe='')}/extend", body))
|
||||
elif verb == "rotate-sub" and len(args) == 1:
|
||||
show(_manager("POST", f"/users/{urllib.parse.quote(args[0], safe='')}/rotate-subscription"))
|
||||
else:
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
def _inbound_bans(*args):
|
||||
as_json = "--json" in args
|
||||
args = [a for a in args if a != "--json"]
|
||||
if args[:1] == ["rm"] and len(args) == 2:
|
||||
result = _manager("DELETE", f"/bans/{urllib.parse.quote(args[1], safe='')}")
|
||||
print(f"{result['ip']}: {result['lifted']} ban(s) lifted")
|
||||
return
|
||||
if args:
|
||||
usage("inbounds bans [--json] | bans rm <address>")
|
||||
bans = _manager("GET", "/bans")
|
||||
if as_json:
|
||||
print(_json_text(bans))
|
||||
return
|
||||
if not bans:
|
||||
print("No address is banned.")
|
||||
return
|
||||
print(" {:<40} {:<6} {}".format("ADDRESS", "PORT", "LEFT"))
|
||||
for ban in bans:
|
||||
print(" {:<40} {:<6} {}".format(ban["ip"], ban["port"], f"{ban['expires']}s" if ban.get("expires") is not None else "-"))
|
||||
|
||||
|
||||
def _inbound_export(*args):
|
||||
"""The users, their policies, keys and traffic, as JSON: to a file (0600) or stdout."""
|
||||
rest = [a for a in args if a != "--no-stats"]
|
||||
if len(rest) > 1:
|
||||
usage("inbounds export [file] [--no-stats]")
|
||||
bundle = _manager("GET", "/export" + ("?stats=0" if "--no-stats" in args else ""))
|
||||
text = json.dumps(bundle, indent=2) + "\n"
|
||||
if not rest or rest[0] == "-":
|
||||
sys.stdout.write(text)
|
||||
return
|
||||
fd = os.open(rest[0], os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
|
||||
with os.fdopen(fd, "w", encoding="utf-8") as f:
|
||||
# A file that was there keeps its mode through O_CREAT: this one holds every secret.
|
||||
os.fchmod(f.fileno(), 0o600)
|
||||
f.write(text)
|
||||
users = len(((bundle.get("runtime") or {}).get("users") or {}))
|
||||
print(f"Exported {users} runtime user(s), {len(bundle.get('policies') or {})} policies to {rest[0]} - it holds their secrets.")
|
||||
|
||||
|
||||
def _inbound_import(*args):
|
||||
rest = [a for a in args if a != "--replace"]
|
||||
if len(rest) != 1:
|
||||
usage("inbounds import <file|-> [--replace]")
|
||||
try:
|
||||
text = sys.stdin.read() if rest[0] == "-" else open(rest[0], encoding="utf-8").read()
|
||||
bundle = json.loads(text)
|
||||
except (OSError, ValueError) as e:
|
||||
die(f"Cannot read {rest[0]}: {e}")
|
||||
report = _manager("POST", "/import", {"bundle": bundle, "replace": "--replace" in args})
|
||||
for key in ("users", "listeners", "policies", "amneziaWg", "salamander"):
|
||||
if report.get(key):
|
||||
print(f"{key}: {', '.join(report[key])}")
|
||||
if report.get("subscriptionKey"):
|
||||
print("subscriptionKey: taken; the subscription URLs are the exported server's")
|
||||
for line in report.get("skipped") or []:
|
||||
print(f"skipped: {line}")
|
||||
for line in report.get("applied") or []:
|
||||
print(f"applied: {line}")
|
||||
|
||||
|
||||
def _inbound_events(*args):
|
||||
limit = args[0] if args and args[0].isdigit() else "50"
|
||||
events = _manager("GET", f"/events?limit={limit}")
|
||||
if "--json" in args:
|
||||
print(_json_text(events))
|
||||
return
|
||||
for event in events:
|
||||
print(f"{_when(event['at'])} {event['event']:<15} {event.get('user') or '-':<20} {json.dumps(event.get('data') or {}, sort_keys=True)}")
|
||||
|
||||
|
||||
def _inbound_users(verb="list", *args):
|
||||
if _manager_enabled() and _manager_users(verb, list(args)):
|
||||
return
|
||||
if verb in ("show", "set", "unset", "enable", "disable", "reset", "extend", "rotate-sub"):
|
||||
die("Policies need the inbound manager (inbounds.manager.enable).")
|
||||
if verb in ("list", "--json"):
|
||||
sys.stdout.write(_inbound_runtime("users", *(["--json"] if "--json" in (verb, *args) else []), listing=True)[1])
|
||||
elif verb == "add" and args:
|
||||
@@ -6219,8 +6590,10 @@ def _inbound_users(verb="list", *args):
|
||||
_inbound_bindings_set(tag=args[0], wanted=args[1:])
|
||||
else:
|
||||
usage(
|
||||
"inbounds users [list] | add <name> [--order N] [--listener <tag>]... | rm <name> | order <name> <N>"
|
||||
" | listeners <name> [tag...] | on <tag> [user...]"
|
||||
"inbounds users [list] [--json] | show <name> | add <name> [--order N] [--listener <tag>]... | rm <name>"
|
||||
" | order <name> <N> | listeners <name> [tag...] | on <tag> [user...]"
|
||||
" | set <name> [policy flags] | unset <name> <field>... | enable|disable|reset <name>"
|
||||
" | extend <name> <30d>|--until <time> | rotate-sub <name>"
|
||||
)
|
||||
|
||||
|
||||
@@ -6285,8 +6658,19 @@ def cmd_inbounds(verb="list", *args):
|
||||
_inbound_online()
|
||||
elif verb == "sub":
|
||||
_inbound_subscriptions(*args)
|
||||
elif verb == "bans":
|
||||
_inbound_bans(*args)
|
||||
elif verb == "export":
|
||||
_inbound_export(*args)
|
||||
elif verb == "import":
|
||||
_inbound_import(*args)
|
||||
elif verb == "events":
|
||||
_inbound_events(*args)
|
||||
else:
|
||||
usage("inbounds [list] | link <tag> [user] [--qr] | sub [user] [--qr] | stats [days] [--by user|inbound|outbound] | online")
|
||||
usage(
|
||||
"inbounds [list] | link <tag> [user] [--qr] | sub [user] [--qr] | stats [days] [--by user|inbound|outbound]"
|
||||
" | online | users ... | bans | export [file] | import <file> | events"
|
||||
)
|
||||
|
||||
|
||||
# --- main ---------------------------------------------------------------------
|
||||
|
||||
@@ -1515,13 +1515,26 @@ class ProxySuiteGui(Adw.Application):
|
||||
if self.timer is None:
|
||||
self.timer = GLib.timeout_add_seconds(self.refresh, self.tick)
|
||||
self.reload()
|
||||
if not options.get("hidden"):
|
||||
# proxy-suite:// links, from xdg-open (the .desktop file's %u): shown even to --hidden.
|
||||
links = [a for a in command_line.get_arguments()[1:] if a.lower().startswith(model.DEEP_LINK_SCHEME + ":")]
|
||||
if not options.get("hidden") or links:
|
||||
# A launcher's token comes along when the running instance is asked to show itself.
|
||||
platform = command_line.get_platform_data()
|
||||
token = platform.lookup_value("activation-token", None) if platform else None
|
||||
self.present(options.get("tab"), token=token.get_string() if token else None)
|
||||
for link in links:
|
||||
self.open_link(link)
|
||||
return 0
|
||||
|
||||
def open_link(self, link):
|
||||
"""A proxy-suite:// link: what it adds, run once confirmed."""
|
||||
argv, why, stdin = model.deep_link_argv(link)
|
||||
if argv is None:
|
||||
self.window.toast(why)
|
||||
return
|
||||
# Asked first, as a paste is: any web page can open such a link.
|
||||
self.confirm(argv, lambda: self.run_argv("run", argv, self.window, stdin=stdin), self.window, stdin=stdin)
|
||||
|
||||
def do_activate(self):
|
||||
self.present()
|
||||
|
||||
|
||||
@@ -16,6 +16,7 @@ import signal
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
import urllib.parse
|
||||
import zlib
|
||||
from dataclasses import dataclass, field, replace
|
||||
from typing import Callable
|
||||
@@ -1360,6 +1361,28 @@ def paste_argv(tab_id, text):
|
||||
return None, "Not a share link, a subscription URL or a host.", None
|
||||
|
||||
|
||||
DEEP_LINK_SCHEME = "proxy-suite"
|
||||
|
||||
|
||||
def deep_link_argv(link):
|
||||
"""What a proxy-suite://install-config?url=<subscription>&name=... link runs, as paste_argv.
|
||||
|
||||
The subscription pages of inbounds.manager offer it on Linux, as clash:// for Clash. Any web
|
||||
page can open one, so the GUI asks first. Only a subscription: the URL on stdin, and
|
||||
proxy-ctl refuses plain http. name is a title, so it is made a tag as proxy-ctl makes one
|
||||
(-2, -3... when taken); without one left, proxy-ctl names it after its host.
|
||||
"""
|
||||
parts = urllib.parse.urlsplit((link or "").strip())
|
||||
if parts.scheme.lower() != DEEP_LINK_SCHEME or parts.netloc.lower() not in ("install-config", "installconfig"):
|
||||
return None, f"Not a {DEEP_LINK_SCHEME}://install-config link.", None
|
||||
query = urllib.parse.parse_qs(parts.query)
|
||||
url = (query.get("url") or [""])[0].strip()
|
||||
if url.split("://", 1)[0].lower() not in ("http", "https") or len(url.splitlines()) > 1:
|
||||
return None, "The link carries no subscription URL.", None
|
||||
tag = ctl._unique_runtime_tag("subscription", (query.get("name") or [""])[0], "")
|
||||
return ["proxy", "subs", "add", *([tag] if tag else []), "-"], "", url
|
||||
|
||||
|
||||
def _awg_paste(tab_id, text):
|
||||
"""An AmneziaWG config, on stdin: an outbound where outbounds are, else a global profile."""
|
||||
outbound = ctl.env("AWG_RUNTIME_OUTBOUNDS") == "1"
|
||||
|
||||
@@ -419,6 +419,25 @@ class GroupWatchTest(EnvTest):
|
||||
self.assertEqual(self.step(), [])
|
||||
self.assertEqual(self.step(), [("warp", "warp-1")])
|
||||
|
||||
def test_logs_misses_and_outages(self):
|
||||
def lines(fn, *args):
|
||||
return run(fn, *args)[2].splitlines()
|
||||
|
||||
self.step(0)
|
||||
self.working["warp-1"] = False
|
||||
# A hiccup that heals before the member goes down still leaves its miss behind.
|
||||
self.assertEqual(lines(self.step), ["warp-1: test failed (1/2)"])
|
||||
self.working["warp-1"] = True
|
||||
self.assertEqual(lines(self.step), [])
|
||||
self.working["warp-1"] = False
|
||||
self.assertEqual(lines(self.step), ["warp-1: test failed (1/2)"])
|
||||
self.assertEqual(lines(self.step), ["warp-1: test failed (2/2)", "warp-1: down", "warp: warp-1 -> warp-2"])
|
||||
# Down, its misses are not repeated every test.
|
||||
self.assertEqual(lines(self.step), [])
|
||||
self.working["warp-1"] = True
|
||||
self.step(), self.step()
|
||||
self.assertEqual(lines(self.step), ["warp-1: up again", "warp: warp-2 -> warp-1"])
|
||||
|
||||
def test_a_hint_moves_at_once(self):
|
||||
self.step(0)
|
||||
self.working["warp-1"] = False
|
||||
@@ -1683,6 +1702,20 @@ class ZapretAutoTest(EnvTest):
|
||||
ctl._replace_lines(path, lambda line: "b.example" not in line)
|
||||
self.assertEqual(ctl.read_text(path), "works\ta.example\ttcp\nworks\tc.example\ttcp\n")
|
||||
|
||||
def test_rewrite_stays_writable_for_the_group_nfqws2_appends_through(self):
|
||||
"""A member's rewrite makes the list theirs: group-writable where the directory is, for nfqws2."""
|
||||
path = self.write("verdicts.tsv", "works\ta.example\ttcp\n")
|
||||
os.chmod(path, 0o644)
|
||||
os.chmod(self.dir, 0o2775)
|
||||
ctl._replace_lines(path, lambda _: True)
|
||||
self.assertEqual(stat.S_IMODE(os.stat(path).st_mode), 0o664)
|
||||
os.chmod(self.dir, 0o755)
|
||||
ctl._replace_lines(path, lambda _: True)
|
||||
self.assertEqual(stat.S_IMODE(os.stat(path).st_mode), 0o664)
|
||||
os.chmod(path, 0o644)
|
||||
ctl._replace_lines(path, lambda _: True)
|
||||
self.assertEqual(stat.S_IMODE(os.stat(path).st_mode), 0o644)
|
||||
|
||||
def test_rewrites_take_the_lock(self):
|
||||
"""Another proxy-ctl mid-edit holds .<name>.lock: this one waits for it, then gives up."""
|
||||
path = self.write("zapret-hosts-auto.txt", "a.example\n")
|
||||
@@ -2175,6 +2208,141 @@ class OutboundTestTest(EnvTest):
|
||||
self.assertIn("proxy-suite group, or re-run with sudo", err)
|
||||
|
||||
|
||||
class InboundManagerTest(EnvTest):
|
||||
"""inbounds.manager through proxy-ctl: requests to its socket, its answers shown."""
|
||||
|
||||
ROW = {
|
||||
"name": "alice", "source": "runtime", "active": False, "reasons": ["traffic"], "listeners": ["vless-in"],
|
||||
"problems": [], "policy": {"trafficLimit": 1073741824, "trafficPeriod": "monthly", "expiresAt": None, "ipLimit": 2,
|
||||
"speedLimit": {"up": 5000000, "down": 20000000}, "meta": {"tg": "42"}, "enabled": True},
|
||||
"stored": {"ipLimit": 2}, "declared": {},
|
||||
"traffic": {"up": 1, "down": 1073741823, "used": 1073741824, "limit": 1073741824, "periodStart": 1700000000,
|
||||
"periodEnd": 1702592000},
|
||||
"expiresAt": None, "online": {"ips": ["198.51.100.7"], "lastSeen": None},
|
||||
"subscription": {"token": "a" * 32, "url": "https://vpn.example.com/sub/" + "a" * 32},
|
||||
}
|
||||
|
||||
def setUp(self):
|
||||
super().setUp()
|
||||
import http.server
|
||||
import socketserver
|
||||
|
||||
self.requests = []
|
||||
self.answers = {}
|
||||
test = self
|
||||
|
||||
class Handler(http.server.BaseHTTPRequestHandler):
|
||||
def log_message(self, *_):
|
||||
pass
|
||||
|
||||
def address_string(self):
|
||||
return "unix"
|
||||
|
||||
def handle_one(self):
|
||||
length = int(self.headers.get("Content-Length") or 0)
|
||||
body = json.loads(self.rfile.read(length)) if length else None
|
||||
test.requests.append((self.command, self.path, body))
|
||||
status, value = test.answers.get((self.command, self.path.split("?")[0]), (200, test.ROW))
|
||||
raw = json.dumps(value).encode()
|
||||
self.send_response(status)
|
||||
self.send_header("Content-Length", str(len(raw)))
|
||||
self.end_headers()
|
||||
self.wfile.write(raw)
|
||||
|
||||
do_GET = do_POST = do_PATCH = do_DELETE = handle_one
|
||||
|
||||
class Server(socketserver.ThreadingMixIn, socketserver.UnixStreamServer):
|
||||
daemon_threads = True
|
||||
|
||||
def get_request(self):
|
||||
request, _ = super().get_request()
|
||||
return request, ("unix", 0)
|
||||
|
||||
sock = self.path("api.sock")
|
||||
server = Server(sock, Handler)
|
||||
threading.Thread(target=server.serve_forever, daemon=True).start()
|
||||
self.addCleanup(server.server_close)
|
||||
self.addCleanup(server.shutdown)
|
||||
os.environ.update(INBOUNDS_ENABLED="1", INBOUNDS_MANAGER_SOCKET=sock)
|
||||
|
||||
def test_set_unset_and_the_rest(self):
|
||||
out = ok(ctl.cmd_inbounds, "users", "set", "alice", "--traffic", "1G", "--speed=20M/5M", "--meta", "tg=42", "--disable",
|
||||
"--expires", "+30d")
|
||||
self.assertEqual(self.requests[-1], ("PATCH", "/api/v1/users/alice", {
|
||||
"trafficLimit": "1G", "speedLimit": "20M/5M", "meta": {"tg": "42"}, "enabled": False, "expiresAt": "+30d"}))
|
||||
self.assertIn("alice (runtime): off: traffic", out)
|
||||
self.assertIn("down 20 Mbit/s, up 5 Mbit/s", out)
|
||||
self.assertIn("https://vpn.example.com/sub/", out)
|
||||
ok(ctl.cmd_inbounds, "users", "unset", "alice", "ips", "speed")
|
||||
self.assertEqual(self.requests[-1][2], {"unset": ["ipLimit", "speedLimit"]})
|
||||
ok(ctl.cmd_inbounds, "users", "extend", "alice", "30d")
|
||||
self.assertEqual(self.requests[-1], ("POST", "/api/v1/users/alice/extend", {"by": "30d"}))
|
||||
ok(ctl.cmd_inbounds, "users", "reset", "alice")
|
||||
self.assertEqual(self.requests[-1][:2], ("POST", "/api/v1/users/alice/reset-traffic"))
|
||||
ok(ctl.cmd_inbounds, "users", "add", "bob", "--listener", "vless-in", "--ips", "3", "--order", "7")
|
||||
self.assertEqual(self.requests[-1], ("POST", "/api/v1/users", {
|
||||
"name": "bob", "listeners": ["vless-in"], "policy": {"ipLimit": "3"}, "order": 7}))
|
||||
rows = json.loads(ok(ctl.cmd_inbounds, "users", "show", "alice", "--json"))
|
||||
self.assertEqual(rows["name"], "alice")
|
||||
|
||||
def test_on_hold_and_renewals(self):
|
||||
ok(ctl.cmd_inbounds, "users", "add", "bob", "--on-hold", "30d")
|
||||
self.assertEqual(self.requests[-1][2]["policy"], {"expiresAfter": "30d"})
|
||||
ok(ctl.cmd_inbounds, "users", "unset", "bob", "hold")
|
||||
self.assertEqual(self.requests[-1][2], {"unset": ["expiresAfter"]})
|
||||
ok(ctl.cmd_inbounds, "users", "extend", "alice", "30d", "--reset")
|
||||
self.assertEqual(self.requests[-1], ("POST", "/api/v1/users/alice/extend", {"by": "30d", "resetTraffic": True}))
|
||||
ok(ctl.cmd_inbounds, "users", "extend", "alice", "--until", "2027-01-31")
|
||||
self.assertEqual(self.requests[-1][2], {"until": "2027-01-31"})
|
||||
held = {**self.ROW, "active": True, "reasons": [], "onHold": True,
|
||||
"policy": {**self.ROW["policy"], "expiresAfter": 30 * 86400}}
|
||||
self.answers[("GET", "/api/v1/users")] = (200, [held])
|
||||
out = ok(ctl.cmd_inbounds, "users")
|
||||
self.assertIn("on hold", out)
|
||||
self.assertIn("+30d on 1st use", out)
|
||||
|
||||
def test_list_table(self):
|
||||
self.answers[("GET", "/api/v1/users")] = (200, [self.ROW])
|
||||
out = ok(ctl.cmd_inbounds, "users")
|
||||
self.assertIn("alice", out)
|
||||
self.assertIn("1.0 GiB / 1.0 GiB", out)
|
||||
self.assertIn("off: traffic", out)
|
||||
|
||||
def test_errors_and_absence(self):
|
||||
self.answers[("PATCH", "/api/v1/users/zed")] = (404, {"error": "no user 'zed'"})
|
||||
status, _, err = run(ctl.cmd_inbounds, "users", "set", "zed", "--ips", "1")
|
||||
self.assertEqual(status, 1)
|
||||
self.assertIn("no user 'zed'", err)
|
||||
os.environ["INBOUNDS_MANAGER_SOCKET"] = ""
|
||||
status, _, err = run(ctl.cmd_inbounds, "users", "set", "zed", "--ips", "1")
|
||||
self.assertIn("need the inbound manager", err)
|
||||
os.environ["INBOUNDS_MANAGER_SOCKET"] = self.path("nothing.sock")
|
||||
status, _, err = run(ctl.cmd_inbounds, "bans")
|
||||
self.assertIn("not running", err)
|
||||
|
||||
def test_subscription_urls_from_the_manager(self):
|
||||
os.environ.update(INBOUNDS_SUBS_FILE=self.path("absent.json"), INBOUNDS_SUB_BASE_URL="https://vpn.example.com/sub")
|
||||
self.answers[("GET", "/api/v1/users")] = (200, [self.ROW])
|
||||
self.assertEqual(ok(ctl.cmd_inbounds, "sub", "alice"), "https://vpn.example.com/sub/" + "a" * 32 + "\n")
|
||||
self.assertIn("alice", ok(ctl.cmd_inbounds, "sub"))
|
||||
|
||||
def test_bans_export_import(self):
|
||||
self.answers[("GET", "/api/v1/bans")] = (200, [{"ip": "203.0.113.9", "port": 443, "expires": 120}])
|
||||
self.assertIn("203.0.113.9", ok(ctl.cmd_inbounds, "bans"))
|
||||
self.answers[("DELETE", "/api/v1/bans/203.0.113.9")] = (200, {"ip": "203.0.113.9", "lifted": 1})
|
||||
self.assertIn("1 ban(s) lifted", ok(ctl.cmd_inbounds, "bans", "rm", "203.0.113.9"))
|
||||
bundle = {"format": "proxy-suite-inbounds", "version": 1, "runtime": {"users": {"a": {}}}, "policies": {}}
|
||||
self.answers[("GET", "/api/v1/export")] = (200, bundle)
|
||||
target = self.path("export.json")
|
||||
ok(ctl.cmd_inbounds, "export", target, "--no-stats")
|
||||
self.assertEqual(self.requests[-1][1], "/api/v1/export?stats=0")
|
||||
self.assertEqual(stat.S_IMODE(os.stat(target).st_mode), 0o600)
|
||||
self.answers[("POST", "/api/v1/import")] = (200, {"users": ["a"], "skipped": [], "applied": ["vless-in: +a"]})
|
||||
out = ok(ctl.cmd_inbounds, "import", target, "--replace")
|
||||
self.assertEqual(self.requests[-1][2], {"bundle": bundle, "replace": True})
|
||||
self.assertIn("users: a", out)
|
||||
|
||||
|
||||
class InboundRuntimeTest(EnvTest):
|
||||
"""inbounds.runtime through proxy-ctl: the tool does the work, proxy-ctl reloads after."""
|
||||
|
||||
|
||||
@@ -11,6 +11,7 @@ import subprocess
|
||||
import tempfile
|
||||
import time
|
||||
import unittest
|
||||
import urllib.parse
|
||||
import zlib
|
||||
from unittest import mock
|
||||
|
||||
@@ -406,6 +407,35 @@ class ModelTest(unittest.TestCase):
|
||||
self.assertEqual([i.id for i in model.tray_menu(None)], ["status", "open", "sep-0", "quit"])
|
||||
self.assertEqual(model.icon_name(ctl._overall_state(None)), "proxy-suite-disabled-unknown")
|
||||
|
||||
def test_deep_link_argv(self):
|
||||
link = model.deep_link_argv
|
||||
sub = "https://vpn.test/sub/" + "a" * 32 + "?format=links&x=1"
|
||||
quoted = urllib.parse.quote(sub, safe="")
|
||||
# The URL on stdin, as pasted; the name made a tag, one not taken yet.
|
||||
with mock.patch.object(ctl, "_runtime_tags", lambda kind: ["work"]), \
|
||||
mock.patch.object(ctl, "_sub_tags", lambda: ["home"]):
|
||||
self.assertEqual(link(f"proxy-suite://install-config?url={quoted}&name=VPN%20alice"),
|
||||
(["proxy", "subs", "add", "VPN-alice", "-"], "", sub))
|
||||
for name, tag in [("work", "work-2"), ("home", "home-2"), ("tor", "tor-2"), ("..%2F..%2Fx", "x"),
|
||||
("%F0%9F%87%A9%F0%9F%87%AA%20" + "y" * 40, "y" * 32)]:
|
||||
self.assertEqual(link(f"proxy-suite://install-config?url={quoted}&name={name}")[0][3], tag, name)
|
||||
# No name, or none left of it: proxy-ctl names it after its host.
|
||||
for name in ["", "&name=", "&name=%F0%9F%87%A9%F0%9F%87%AA"]:
|
||||
self.assertEqual(link(f"proxy-suite://install-config?url={quoted}{name}")[0], ["proxy", "subs", "add", "-"], name)
|
||||
self.assertEqual(link(f"PROXY-SUITE://installconfig?url={quoted}")[2], sub)
|
||||
for text in [
|
||||
"",
|
||||
f"clash://install-config?url={quoted}",
|
||||
f"proxy-suite://import?url={quoted}",
|
||||
"proxy-suite://install-config?name=x",
|
||||
"proxy-suite://install-config?url=vless%3A%2F%2Fu%40a.test%3A443",
|
||||
"proxy-suite://install-config?url=https%3A%2F%2Fa.test%2F%0Ahttps%3A%2F%2Fb.test%2F",
|
||||
]:
|
||||
argv, why, stdin = link(text)
|
||||
self.assertIsNone(argv, text)
|
||||
self.assertIsNone(stdin)
|
||||
self.assertTrue(why)
|
||||
|
||||
def test_paste_argv(self):
|
||||
paste = model.paste_argv
|
||||
# Links and JSON carry credentials: on stdin, never in argv (ps, pkexec's log).
|
||||
|
||||
@@ -5,8 +5,8 @@ let
|
||||
src = pkgs.fetchFromGitHub {
|
||||
owner = "Flowseal";
|
||||
repo = "tg-ws-proxy";
|
||||
rev = "v1.11.1";
|
||||
hash = "sha256-kn+OsMxgwbM+KsKj+E4Qq7JZXzB9Lco83W1/tgxRVwc=";
|
||||
rev = "v1.11.2";
|
||||
hash = "sha256-oX6fdrsqeLwcwGJsI+0bj/y+5JM2ap+d3HuqLmnViho=";
|
||||
};
|
||||
|
||||
pythonEnv = pkgs.python3.withPackages (
|
||||
|
||||
+30
-20
@@ -1,27 +1,37 @@
|
||||
# Xray-core ahead of nixpkgs, which still ships 26.3.27. From 26.9.8 its go.mod
|
||||
# asks for Go 1.27, so the builder is swapped along with the source. Steps
|
||||
# aside once nixpkgs has caught up.
|
||||
# aside once nixpkgs has caught up; the patch stays.
|
||||
#
|
||||
# The patch marks an outbound's sockets by the level of the inbound user they dial for
|
||||
# (inbounds.manager's speed limits); passthru.userLevelMark says it is in.
|
||||
{ pkgs }:
|
||||
|
||||
let
|
||||
inherit (pkgs) lib;
|
||||
version = "26.9.30";
|
||||
version = "26.10.21";
|
||||
base =
|
||||
if lib.versionAtLeast pkgs.xray.version version then
|
||||
pkgs.xray
|
||||
else
|
||||
(pkgs.xray.override (
|
||||
args: lib.optionalAttrs (args ? buildGo126Module) { buildGo126Module = pkgs.buildGo127Module; }
|
||||
)).overrideAttrs
|
||||
(
|
||||
finalAttrs: _: {
|
||||
inherit version;
|
||||
src = pkgs.fetchFromGitHub {
|
||||
owner = "XTLS";
|
||||
repo = "Xray-core";
|
||||
rev = "v${finalAttrs.version}";
|
||||
hash = "sha256-1FwcB/qZaH7W9b+GSe+CG/s+uStaDjz792OxDc3uAyg=";
|
||||
};
|
||||
vendorHash = "sha256-o4mKfCGgI4r5ZatnA4AsK4zR0/qOl2qpqCmoJmE2jBQ=";
|
||||
}
|
||||
);
|
||||
in
|
||||
if lib.versionAtLeast pkgs.xray.version version then
|
||||
pkgs.xray
|
||||
else
|
||||
(pkgs.xray.override (
|
||||
args: lib.optionalAttrs (args ? buildGo126Module) { buildGo126Module = pkgs.buildGo127Module; }
|
||||
)).overrideAttrs
|
||||
(
|
||||
finalAttrs: _: {
|
||||
inherit version;
|
||||
src = pkgs.fetchFromGitHub {
|
||||
owner = "XTLS";
|
||||
repo = "Xray-core";
|
||||
rev = "v${finalAttrs.version}";
|
||||
hash = "sha256-JOXpF8qRvI2PLrEyvNlPRY5BC+4T2MByBy2NQSUgr88=";
|
||||
};
|
||||
vendorHash = "sha256-NCTHE7WdczOUSr6HVu27LX9TCQ3iuRg4PtJKMxDwZ00=";
|
||||
}
|
||||
)
|
||||
base.overrideAttrs (old: {
|
||||
patches = (old.patches or [ ]) ++ [ ./patches/xray-user-level-mark.patch ];
|
||||
passthru = (old.passthru or { }) // {
|
||||
userLevelMark = true;
|
||||
};
|
||||
})
|
||||
@@ -0,0 +1,33 @@
|
||||
# z2k-detect, the 16 KB cutoff probe's Go side, at the z2k rev flake.lock holds. It is
|
||||
# built from its own checkout, not from the module's `z2k` input: a consumer that
|
||||
# supplies its own z2k (lon, npins, `follows`) would otherwise change go.sum under the
|
||||
# pinned vendorHash. It talks to the lists and Lua only through the TSV maps.
|
||||
#
|
||||
# The rev comes from flake.lock; scripts/update-pins.sh refreshes hash and vendorHash
|
||||
# after a z2k bump. The rev in the name keeps a store that still holds the previous
|
||||
# checkout from reusing it under a stale hash.
|
||||
{ pkgs }:
|
||||
|
||||
let
|
||||
locked = (pkgs.lib.importJSON ../flake.lock).nodes.z2k.locked;
|
||||
shortRev = builtins.substring 0 7 locked.rev;
|
||||
in
|
||||
pkgs.buildGoModule (finalAttrs: {
|
||||
pname = "z2k-detect";
|
||||
version = "0-unstable-${shortRev}";
|
||||
|
||||
src = pkgs.fetchFromGitHub {
|
||||
name = "z2k-detect-source-${shortRev}";
|
||||
inherit (locked) owner repo rev;
|
||||
sparseCheckout = [ "z2k-detect" ];
|
||||
hash = "sha256-eagnkmLgZfa4Qc2UkhBHO721iWTdKnqzPGHKLcphJtY=";
|
||||
};
|
||||
sourceRoot = "${finalAttrs.src.name}/z2k-detect";
|
||||
vendorHash = "sha256-9Qv6O6/8MP9N44GPSDULEV/NcrHdEC3YZmIQmpaa1nE=";
|
||||
|
||||
subPackages = [ "cmd/z2k-detect" ];
|
||||
# Its tests open raw sockets and dial out.
|
||||
doCheck = false;
|
||||
|
||||
meta.mainProgram = "z2k-detect";
|
||||
})
|
||||
@@ -240,6 +240,9 @@ def render_server_config(listener: dict, state: dict) -> str:
|
||||
awg = listener["amneziaWg"]
|
||||
peers = []
|
||||
for user in listener["users"]:
|
||||
# Switched off by the manager: no peer, but the keys and address stay in the state.
|
||||
if user.get("active") is False:
|
||||
continue
|
||||
entry = state["users"][user["name"]]
|
||||
peer: dict[str, Any] = {
|
||||
"publicKey": entry["publicKey"],
|
||||
|
||||
@@ -5,8 +5,7 @@ import argparse
|
||||
import json
|
||||
import sys
|
||||
|
||||
import inbound_runtime
|
||||
from proxy_inbound import build_inbounds
|
||||
from inbound_apply import render
|
||||
|
||||
|
||||
def main() -> None:
|
||||
@@ -42,14 +41,13 @@ def main() -> None:
|
||||
sys.exit(1)
|
||||
|
||||
try:
|
||||
spec, runtime, warnings = inbound_runtime.merge(spec, check_ports=True)
|
||||
for warning in warnings:
|
||||
print(f"proxy-suite: warning: {warning}", file=sys.stderr)
|
||||
result = build_inbounds(spec, server_address, args.onion_address)
|
||||
template = None
|
||||
if args.template and spec.get("runtime"):
|
||||
with open(args.template, encoding="utf-8") as handle:
|
||||
template = json.load(handle)
|
||||
result.update(inbound_runtime.routing(spec, runtime, template["routing"]["rules"]))
|
||||
result, warnings = render(spec, server_address, args.onion_address, template, check_ports=True)
|
||||
for warning in warnings:
|
||||
print(f"proxy-suite: warning: {warning}", file=sys.stderr)
|
||||
except (ValueError, OSError) as exc:
|
||||
print(f"error: {exc}", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
|
||||
@@ -0,0 +1,473 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Apply a change to the inbounds without restarting them, where XRay's API can.
|
||||
|
||||
The inbounds' start script keeps what it rendered (build-inbound.py's output) and with
|
||||
what, in its runtime directory. This renders the spec again the same way and compares:
|
||||
|
||||
- users who came, went or changed on a listener that is otherwise the same: removed and
|
||||
added through the API (rmu, adu), and the connections of those removed cut (ss -K for
|
||||
TCP, a short drop in proxy-suite's nftables table for UDP), since XRay keeps them;
|
||||
- the routing rules (runtime users' serverSource rules): replaced whole (adrules);
|
||||
- their serverSource outbounds and addresses: added and removed (ado, rmo, ip addr);
|
||||
- the share links and subscriptions: written again by the module's own writer;
|
||||
- AmneziaWG listeners whose peers changed: their interfaces synced (awg syncconf), which
|
||||
leaves the other peers' sessions alone.
|
||||
|
||||
Anything else (a listener added, removed or changed, a Shadowsocks listener going between
|
||||
one user and many, socks or http accounts) needs the restart it always needed, and so does
|
||||
an API call that fails. One apply at a time (a lock in the runtime directory).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import copy
|
||||
import fcntl
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
|
||||
import inbound_runtime
|
||||
from proxy_inbound import build_inbounds
|
||||
|
||||
# The inbound's user list, by XRay protocol; a Shadowsocks inbound has one only with more
|
||||
# than one user. The others (socks, http, a single-user Shadowsocks, AmneziaWG's) change
|
||||
# only with a restart.
|
||||
USER_LISTS = {"vless": "clients", "vmess": "clients", "trojan": "clients", "hysteria": "clients", "shadowsocks": "clients"}
|
||||
# Inbounds that speak UDP to their clients: a cut user's sessions there are dropped for a
|
||||
# while instead (QUIC has no socket to kill).
|
||||
UDP_CUT_SECONDS = 90
|
||||
|
||||
|
||||
def render(spec: dict, server_address: str, onion_address: str = "", template: dict | None = None,
|
||||
check_ports: bool | set = False, now: float | None = None) -> tuple[dict, list[str]]:
|
||||
"""What build-inbound.py prints: the inbounds, links and subscriptions, and with
|
||||
inbounds.runtime and the template its routing additions. check_ports: whether a runtime
|
||||
listener's port must be free, or the ports the running XRay holds, which count as free."""
|
||||
merged, runtime, warnings = inbound_runtime.merge(spec, check_ports=check_ports, now=now)
|
||||
result = build_inbounds(merged, server_address, onion_address)
|
||||
if template is not None and merged.get("runtime"):
|
||||
result.update(inbound_runtime.routing(merged, runtime, template["routing"]["rules"]))
|
||||
return result, warnings
|
||||
|
||||
|
||||
# --- the comparison -------------------------------------------------------------------
|
||||
|
||||
|
||||
def split_users(inbound: dict) -> tuple[dict, dict[str, dict]]:
|
||||
"""The inbound without its users, and its users by email. One whose users cannot be
|
||||
told apart from the rest comes whole, with none."""
|
||||
key = USER_LISTS.get(inbound.get("protocol", ""))
|
||||
settings = inbound.get("settings") or {}
|
||||
if key is None or not isinstance(settings.get(key), list):
|
||||
return inbound, {}
|
||||
shape = copy.deepcopy(inbound)
|
||||
users = {client.get("email"): client for client in shape["settings"].pop(key)}
|
||||
if None in users or len(users) != len(settings[key]):
|
||||
return inbound, {}
|
||||
return shape, users
|
||||
|
||||
|
||||
def plan(old: dict, new: dict) -> dict:
|
||||
"""What it takes to go from the old rendering to the new one: {"restart": [reasons],
|
||||
"users": {tag: {"remove": [emails], "add": [clients]}}, "rules": rules | None,
|
||||
"outbounds": {"remove": [tags], "add": [outbounds]}, "addresses": {"remove", "add"},
|
||||
"outputs": bool}. A non-empty "restart" means the rest does not apply."""
|
||||
result: dict = {"restart": [], "users": {}, "rules": None, "outbounds": {"remove": [], "add": []},
|
||||
"addresses": {"remove": [], "add": []}, "outputs": False}
|
||||
old_inbounds = {ib.get("tag"): ib for ib in old.get("inbounds") or []}
|
||||
new_inbounds = {ib.get("tag"): ib for ib in new.get("inbounds") or []}
|
||||
if set(old_inbounds) != set(new_inbounds):
|
||||
added = sorted(set(new_inbounds) - set(old_inbounds))
|
||||
gone = sorted(set(old_inbounds) - set(new_inbounds))
|
||||
result["restart"].append(
|
||||
"listeners " + ", ".join(filter(None, [added and f"added: {', '.join(added)}", gone and f"gone: {', '.join(gone)}"]))
|
||||
)
|
||||
return result
|
||||
for tag, inbound in new_inbounds.items():
|
||||
old_shape, old_users = split_users(old_inbounds[tag])
|
||||
new_shape, new_users = split_users(inbound)
|
||||
if old_shape != new_shape:
|
||||
result["restart"].append(f"listener '{tag}' changed")
|
||||
continue
|
||||
remove = sorted(e for e in old_users if e not in new_users or old_users[e] != new_users[e])
|
||||
add = [new_users[e] for e in sorted(new_users) if e not in old_users or old_users[e] != new_users[e]]
|
||||
if remove or add:
|
||||
result["users"][tag] = {"remove": remove, "add": add}
|
||||
if result["restart"]:
|
||||
return result
|
||||
if (old.get("rules") or []) != (new.get("rules") or []):
|
||||
result["rules"] = new.get("rules") or []
|
||||
old_outbounds = {ob["tag"]: ob for ob in old.get("selfOutbounds") or []}
|
||||
new_outbounds = {ob["tag"]: ob for ob in new.get("selfOutbounds") or []}
|
||||
result["outbounds"]["remove"] = sorted(t for t in old_outbounds if old_outbounds[t] != new_outbounds.get(t))
|
||||
result["outbounds"]["add"] = [new_outbounds[t] for t in sorted(new_outbounds) if new_outbounds[t] != old_outbounds.get(t)]
|
||||
|
||||
def addresses(rendering):
|
||||
return {(family, entry[key]) for entry in rendering.get("selfAddresses") or []
|
||||
for family, key in (("4", "ipv4"), ("6", "ipv6")) if entry.get(key)}
|
||||
|
||||
old_addresses, new_addresses = addresses(old), addresses(new)
|
||||
result["addresses"]["remove"] = sorted(old_addresses - new_addresses)
|
||||
result["addresses"]["add"] = sorted(new_addresses - old_addresses)
|
||||
result["outputs"] = (old.get("links"), old.get("subscriptions")) != (new.get("links"), new.get("subscriptions"))
|
||||
return result
|
||||
|
||||
|
||||
def is_noop(steps: dict) -> bool:
|
||||
return not (steps["restart"] or steps["users"] or steps["rules"] is not None or steps["outbounds"]["remove"]
|
||||
or steps["outbounds"]["add"] or steps["addresses"]["remove"] or steps["addresses"]["add"]
|
||||
or steps["outputs"])
|
||||
|
||||
|
||||
def udp_inbound(inbound: dict) -> bool:
|
||||
stream = inbound.get("streamSettings") or {}
|
||||
alpn = ((stream.get("tlsSettings") or {}).get("alpn")) or []
|
||||
return inbound.get("protocol") == "hysteria" or (stream.get("network") == "xhttp" and alpn == ["h3"])
|
||||
|
||||
|
||||
# --- doing it -------------------------------------------------------------------------
|
||||
|
||||
|
||||
class ApplyError(RuntimeError):
|
||||
pass
|
||||
|
||||
|
||||
class Tools:
|
||||
"""The binaries and names the module hands over (apply.json), and how to call them."""
|
||||
|
||||
def __init__(self, config: dict, dry_run: bool = False):
|
||||
self.config = config
|
||||
self.dry_run = dry_run
|
||||
self.log: list[str] = []
|
||||
|
||||
def run(self, argv: list[str], what: str, stdin: str | None = None, check: bool = True) -> str:
|
||||
self.log.append(" ".join(argv))
|
||||
if self.dry_run:
|
||||
return ""
|
||||
env = dict(os.environ)
|
||||
env.update(self.config.get("env") or {})
|
||||
try:
|
||||
done = subprocess.run(argv, input=stdin, capture_output=True, text=True, env=env, timeout=30)
|
||||
except (OSError, subprocess.TimeoutExpired) as exc:
|
||||
raise ApplyError(f"{what}: {exc}") from None
|
||||
if check and done.returncode != 0:
|
||||
raise ApplyError(f"{what}: {(done.stderr or done.stdout).strip() or f'exit {done.returncode}'}")
|
||||
return done.stdout
|
||||
|
||||
def xray_api(self, command: str, *args: str, what: str) -> str:
|
||||
# The server first: Go's flags end at the first argument that is none (rmu's emails).
|
||||
return self.run([self.config["xray"], "api", command, f"--server={self.config['api']}", *args], what)
|
||||
|
||||
def xray_api_file(self, command: str, value: dict, what: str) -> str:
|
||||
with tempfile.NamedTemporaryFile("w", suffix=".json", dir=self.config.get("tmpDir"), delete=True) as handle:
|
||||
json.dump(value, handle)
|
||||
handle.flush()
|
||||
return self.run([self.config["xray"], "api", command, f"--server={self.config['api']}", handle.name], what)
|
||||
|
||||
|
||||
def online_ips(tools: Tools, email: str) -> list[str]:
|
||||
"""Where a user is connected from now, as XRay counts it (loopback never is)."""
|
||||
try:
|
||||
out = tools.xray_api("statsonlineiplist", "-email", email, what=f"online addresses of {email}")
|
||||
return sorted((json.loads(out or "{}").get("ips") or {}).keys())
|
||||
except (ApplyError, ValueError):
|
||||
return []
|
||||
|
||||
|
||||
def cut(tools: Tools, ips: list[str], tcp_ports: set[int], udp_ports: set[int]) -> None:
|
||||
"""Close what these addresses hold open on these ports: TCP sockets killed, UDP dropped
|
||||
for a while. Other users behind the same address reconnect once."""
|
||||
ss = tools.config.get("ss")
|
||||
if ss:
|
||||
for ip in ips:
|
||||
# A prefix: a bare IPv6 address would read as address and port to ss.
|
||||
prefix = f"{ip}/128" if ":" in ip else f"{ip}/32"
|
||||
for port in sorted(tcp_ports):
|
||||
tools.run([ss, "-K", "-n", "-t", "state", "established", f"( sport = :{port} )", "dst", prefix],
|
||||
f"closing {ip}'s connections to {port}", check=False)
|
||||
nft, table = tools.config.get("nft"), tools.config.get("nftTable")
|
||||
if nft and table and udp_ports and ips:
|
||||
lines = []
|
||||
for ip in ips:
|
||||
family = "6" if ":" in ip else "4"
|
||||
for port in sorted(udp_ports):
|
||||
lines.append(f"add element inet {table} cut{family} {{ {ip} . {port} timeout {UDP_CUT_SECONDS}s }}")
|
||||
tools.run([nft, "-f", "-"], "dropping UDP of the users cut off", stdin="\n".join(lines) + "\n", check=False)
|
||||
|
||||
|
||||
def run_steps(tools: Tools, steps: dict, new: dict, template: dict | None) -> list[str]:
|
||||
"""Carry out a plan without "restart". What was done, line by line."""
|
||||
done = []
|
||||
by_tag = {ib["tag"]: ib for ib in new.get("inbounds") or []}
|
||||
# Where the users going away are connected from, before XRay forgets them.
|
||||
leaving: dict[str, list[str]] = {}
|
||||
for change in steps["users"].values():
|
||||
for email in change["remove"]:
|
||||
if email not in leaving:
|
||||
leaving[email] = online_ips(tools, email)
|
||||
tcp_ports: dict[str, set[int]] = {}
|
||||
udp_ports: dict[str, set[int]] = {}
|
||||
for tag, change in sorted(steps["users"].items()):
|
||||
inbound = by_tag[tag]
|
||||
if change["remove"]:
|
||||
tools.xray_api("rmu", f"-tag={tag}", *change["remove"], what=f"removing users from {tag}")
|
||||
ports = udp_ports if udp_inbound(inbound) else tcp_ports
|
||||
for email in change["remove"]:
|
||||
ports.setdefault(email, set()).add(int(inbound["port"]))
|
||||
done.append(f"{tag}: -{','.join(change['remove'])}")
|
||||
if change["add"]:
|
||||
key = USER_LISTS[inbound["protocol"]]
|
||||
partial = copy.deepcopy(inbound)
|
||||
partial["settings"][key] = change["add"]
|
||||
tools.xray_api_file("adu", {"inbounds": [partial]}, f"adding users to {tag}")
|
||||
done.append(f"{tag}: +{','.join(c['email'] for c in change['add'])}")
|
||||
# A user whose secret or level changed was removed and added: their old sessions go too.
|
||||
for email, ips in sorted(leaving.items()):
|
||||
if ips:
|
||||
cut(tools, ips, tcp_ports.get(email, set()), udp_ports.get(email, set()))
|
||||
done.append(f"cut {email} ({', '.join(ips)})")
|
||||
for tag in steps["outbounds"]["remove"]:
|
||||
tools.xray_api("rmo", tag, what=f"removing outbound {tag}")
|
||||
if steps["outbounds"]["add"]:
|
||||
tools.xray_api_file("ado", {"outbounds": steps["outbounds"]["add"]}, "adding serverSource outbounds")
|
||||
if steps["outbounds"]["remove"] or steps["outbounds"]["add"]:
|
||||
done.append("serverSource outbounds")
|
||||
if steps["rules"] is not None:
|
||||
routing = {key: value for key, value in ((template or {}).get("routing") or {}).items() if key != "rules"}
|
||||
routing["rules"] = steps["rules"]
|
||||
tools.xray_api_file("adrules", {"routing": routing}, "replacing the routing rules")
|
||||
done.append("routing rules")
|
||||
ip, interface = tools.config.get("ip"), tools.config.get("selfInterface")
|
||||
if ip and interface:
|
||||
for family, address in steps["addresses"]["remove"]:
|
||||
prefix = "32" if family == "4" else "128"
|
||||
tools.run([ip, f"-{family}", "addr", "del", f"{address}/{prefix}", "dev", interface],
|
||||
f"removing {address}", check=False)
|
||||
for family, address in steps["addresses"]["add"]:
|
||||
prefix = "32" if family == "4" else "128"
|
||||
extra = ["nodad"] if family == "6" else []
|
||||
tools.run([ip, f"-{family}", "addr", "add", f"{address}/{prefix}", "dev", interface, *extra],
|
||||
f"adding {address}")
|
||||
if steps["addresses"]["remove"] or steps["addresses"]["add"]:
|
||||
done.append("serverSource addresses")
|
||||
return done
|
||||
|
||||
|
||||
def sync_config(runtime_dir: str, steps: dict, new: dict) -> None:
|
||||
"""The running XRay's config.json, as it now runs: what proxy-ctl and people read. In
|
||||
place, so its owner, mode and ACLs stay."""
|
||||
path = os.path.join(runtime_dir, "config.json")
|
||||
config = load_json(path)
|
||||
if not isinstance(config, dict):
|
||||
return
|
||||
by_tag = {ib["tag"]: ib for ib in new.get("inbounds") or []}
|
||||
for inbound in config.get("inbounds") or []:
|
||||
tag = inbound.get("tag")
|
||||
if tag in steps["users"]:
|
||||
key = USER_LISTS[inbound["protocol"]]
|
||||
inbound.setdefault("settings", {})[key] = copy.deepcopy(by_tag[tag]["settings"][key])
|
||||
if steps["rules"] is not None:
|
||||
config.setdefault("routing", {})["rules"] = steps["rules"]
|
||||
gone = set(steps["outbounds"]["remove"])
|
||||
if gone or steps["outbounds"]["add"]:
|
||||
config["outbounds"] = [ob for ob in config.get("outbounds") or [] if ob.get("tag") not in gone]
|
||||
config["outbounds"] += copy.deepcopy(steps["outbounds"]["add"])
|
||||
fd = os.open(path, os.O_WRONLY | os.O_TRUNC | os.O_NOFOLLOW)
|
||||
with os.fdopen(fd, "w", encoding="utf-8") as handle:
|
||||
json.dump(config, handle)
|
||||
|
||||
|
||||
def write_outputs(tools: Tools, rendered_path: str) -> None:
|
||||
script = tools.config.get("outputsScript")
|
||||
if script:
|
||||
tools.run([script, rendered_path], "writing the share links and subscriptions")
|
||||
|
||||
|
||||
def save_rendering(runtime_dir: str, rendered: dict) -> str:
|
||||
path = os.path.join(runtime_dir, "rendered.json")
|
||||
tmp = path + ".tmp"
|
||||
fd = os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_TRUNC | os.O_NOFOLLOW, 0o600)
|
||||
with os.fdopen(fd, "w", encoding="utf-8") as handle:
|
||||
json.dump(rendered, handle)
|
||||
os.replace(tmp, path)
|
||||
return path
|
||||
|
||||
|
||||
def load_json(path: str):
|
||||
try:
|
||||
with open(path, encoding="utf-8") as handle:
|
||||
return json.load(handle)
|
||||
except (OSError, ValueError):
|
||||
return None
|
||||
|
||||
|
||||
def restart(tools: Tools, units: list[str], reason: str) -> list[str]:
|
||||
systemctl = tools.config["systemctl"]
|
||||
tools.run([systemctl, "try-restart", *units], f"restarting {', '.join(units)}")
|
||||
return [f"restarted {', '.join(units)}: {reason}"]
|
||||
|
||||
|
||||
def apply_xray(tools: Tools, spec: dict) -> list[str]:
|
||||
"""The XRay side; restarts the inbounds when the API cannot do it."""
|
||||
config = tools.config
|
||||
runtime_dir = config["runtimeDir"]
|
||||
unit = config["unit"]
|
||||
old = load_json(os.path.join(runtime_dir, "rendered.json"))
|
||||
args = load_json(os.path.join(runtime_dir, "render-args.json"))
|
||||
if not isinstance(old, dict) or not isinstance(args, dict):
|
||||
return restart(tools, [unit], "nothing rendered to compare with")
|
||||
template = load_json(config["template"]) if config.get("template") else None
|
||||
try:
|
||||
server_address = args.get("serverAddress") or spec.get("serverAddress") or ""
|
||||
# As the start script checks them, but the ports XRay holds now are its own.
|
||||
held = {int(ib["port"]) for ib in old.get("inbounds") or [] if isinstance(ib.get("port"), int)}
|
||||
new, warnings = render(spec, server_address, args.get("onionAddress", ""), template, check_ports=held or True)
|
||||
except (ValueError, OSError) as exc:
|
||||
return restart(tools, [unit], f"cannot render: {exc}")
|
||||
for warning in warnings:
|
||||
print(f"proxy-suite: warning: {warning}", file=sys.stderr)
|
||||
steps = plan(old, new)
|
||||
if steps["restart"]:
|
||||
return restart(tools, [unit], "; ".join(steps["restart"]))
|
||||
if is_noop(steps):
|
||||
return []
|
||||
try:
|
||||
done = run_steps(tools, steps, new, template)
|
||||
except ApplyError as exc:
|
||||
return restart(tools, [unit], f"the API failed: {exc}")
|
||||
path = save_rendering(runtime_dir, new)
|
||||
try:
|
||||
sync_config(runtime_dir, steps, new)
|
||||
except (OSError, ValueError, KeyError) as exc:
|
||||
print(f"proxy-suite: config.json not updated: {exc}", file=sys.stderr)
|
||||
if steps["outputs"]:
|
||||
try:
|
||||
write_outputs(tools, path)
|
||||
done.append("links and subscriptions")
|
||||
except ApplyError as exc:
|
||||
print(f"proxy-suite: {exc}", file=sys.stderr)
|
||||
return done
|
||||
|
||||
|
||||
# --- AmneziaWG ------------------------------------------------------------------------
|
||||
|
||||
|
||||
STRIPPED_INTERFACE_KEYS = {"address", "dns", "mtu", "table", "preup", "postup", "predown", "postdown", "saveconfig"}
|
||||
|
||||
|
||||
def strip_config(text: str) -> str:
|
||||
"""awg-quick strip: what `awg setconf` takes, without awg-quick's own keys."""
|
||||
lines, section = [], ""
|
||||
for line in text.splitlines():
|
||||
stripped = line.strip()
|
||||
if stripped.startswith("["):
|
||||
section = stripped.lower()
|
||||
elif section == "[interface]" and "=" in stripped:
|
||||
if stripped.split("=", 1)[0].strip().lower() in STRIPPED_INTERFACE_KEYS:
|
||||
continue
|
||||
lines.append(line)
|
||||
return "\n".join(lines) + "\n"
|
||||
|
||||
|
||||
def interface_part(text: str) -> str:
|
||||
out, section = [], ""
|
||||
for line in strip_config(text).splitlines():
|
||||
if line.strip().startswith("["):
|
||||
section = line.strip().lower()
|
||||
if section == "[interface]":
|
||||
out.append(line.strip())
|
||||
return "\n".join(out)
|
||||
|
||||
|
||||
def apply_awg(tools: Tools, spec: dict) -> list[str]:
|
||||
"""Write the AmneziaWG listeners' configs again and sync the interfaces whose peers
|
||||
changed. A change to an interface itself restarts their unit."""
|
||||
config = tools.config
|
||||
awg = config.get("awg")
|
||||
if not awg or not any(listener.get("type") == "amneziawg" for listener in spec["listeners"]):
|
||||
return []
|
||||
import awg_inbound
|
||||
|
||||
awg_dir = config["awgRuntimeDir"]
|
||||
if not os.path.isdir(awg_dir):
|
||||
return restart(tools, [config["awgUnit"]], "the AmneziaWG listeners are not running")
|
||||
before = {}
|
||||
for listener in spec["listeners"]:
|
||||
if listener.get("type") == "amneziawg":
|
||||
path = os.path.join(awg_dir, f"{listener['amneziaWg']['interfaceName']}.conf")
|
||||
try:
|
||||
with open(path, encoding="utf-8") as handle:
|
||||
before[listener["amneziaWg"]["interfaceName"]] = handle.read()
|
||||
except OSError:
|
||||
before[listener["amneziaWg"]["interfaceName"]] = None
|
||||
merged, _, _ = inbound_runtime.merge(spec)
|
||||
if tools.dry_run:
|
||||
return []
|
||||
prepared = awg_inbound.prepare(merged, awg, awg_dir)
|
||||
if {entry["interface"] for entry in prepared} != set(before):
|
||||
return restart(tools, [config["awgUnit"]], "AmneziaWG listeners added or removed")
|
||||
done = []
|
||||
for entry in prepared:
|
||||
with open(entry["config"], encoding="utf-8") as handle:
|
||||
text = handle.read()
|
||||
old = before.get(entry["interface"])
|
||||
if old == text:
|
||||
continue
|
||||
if old is None or interface_part(old) != interface_part(text):
|
||||
return done + restart(tools, [config["awgUnit"]], f"interface {entry['interface']} changed")
|
||||
stripped = entry["config"] + ".stripped"
|
||||
fd = os.open(stripped, os.O_WRONLY | os.O_CREAT | os.O_TRUNC | os.O_NOFOLLOW, 0o600)
|
||||
with os.fdopen(fd, "w", encoding="utf-8") as handle:
|
||||
handle.write(strip_config(text))
|
||||
try:
|
||||
tools.run([awg, "syncconf", entry["interface"], stripped], f"syncing {entry['interface']}")
|
||||
except ApplyError as exc:
|
||||
return done + restart(tools, [config["awgUnit"]], str(exc))
|
||||
finally:
|
||||
os.unlink(stripped)
|
||||
done.append(f"{entry['interface']}: peers synced")
|
||||
return done
|
||||
|
||||
|
||||
# --- entry ----------------------------------------------------------------------------
|
||||
|
||||
|
||||
def apply(config: dict, spec: dict, dry_run: bool = False) -> list[str]:
|
||||
"""Both sides, under the apply lock. With the inbounds stopped (no runtime directory)
|
||||
there is nothing to change in place: try-restart, which leaves them stopped."""
|
||||
tools = Tools(config, dry_run)
|
||||
if not os.path.isdir(config["runtimeDir"]):
|
||||
return apply_awg(tools, spec) + restart(tools, [config["unit"]], "the inbounds are not running")
|
||||
lock_path = os.path.join(config["runtimeDir"], "apply.lock")
|
||||
fd = os.open(lock_path, os.O_RDWR | os.O_CREAT | os.O_NOFOLLOW, 0o600)
|
||||
try:
|
||||
fcntl.flock(fd, fcntl.LOCK_EX)
|
||||
return apply_awg(tools, spec) + apply_xray(tools, spec)
|
||||
finally:
|
||||
os.close(fd)
|
||||
|
||||
|
||||
def main(argv: list[str] | None = None) -> int:
|
||||
parser = argparse.ArgumentParser(description=__doc__.split("\n", 1)[0])
|
||||
parser.add_argument("--config", required=True, help="apply.json, from the module")
|
||||
parser.add_argument("--spec", required=True)
|
||||
parser.add_argument("--dry-run", action="store_true")
|
||||
args = parser.parse_args(argv)
|
||||
with open(args.config, encoding="utf-8") as handle:
|
||||
config = json.load(handle)
|
||||
with open(args.spec, encoding="utf-8") as handle:
|
||||
spec = json.load(handle)
|
||||
try:
|
||||
for line in apply(config, spec, args.dry_run):
|
||||
print(line)
|
||||
except (ApplyError, OSError) as exc:
|
||||
print(f"error: {exc}", file=sys.stderr)
|
||||
return 1
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,194 @@
|
||||
#!/usr/bin/env python3
|
||||
"""The inbound manager's nftables table: banned addresses, cut-off UDP, and speed limits.
|
||||
|
||||
- ban4/ban6: an address on a port, for a while (an address past a user's ipLimit).
|
||||
- cut4/cut6: the same, for the UDP sessions of a user just switched off (inbound_apply.py).
|
||||
- up/down: speed limits of XRay users, by socket mark. The patched XRay marks the sockets
|
||||
its exits dial for a user of level N with MARK_BASE + N (pkgs/patches/
|
||||
xray-user-level-mark.patch); the mark goes to the connection, whose packets toward the
|
||||
site (original direction, leaving this host) are policed against the user's "up" limit
|
||||
and those back (reply direction, arriving) against "down". Through the local proxy the
|
||||
connection is on loopback, where both directions arrive and leave: each is policed once.
|
||||
- awg_up/awg_down: AmneziaWG peers, by interface and tunnel address.
|
||||
|
||||
Limits police (drop past the rate), which TCP and QUIC back off from. The table is
|
||||
replaced whole when it is missing (nftables flushed it); the limits are swapped in one
|
||||
transaction; the bans' sets are left alone.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import subprocess
|
||||
|
||||
TABLE = "proxy_suite_inbound_limits"
|
||||
MARK_BASE = 0x04000000
|
||||
MARK_MASK = 0xFFFF0000
|
||||
# What the exits' sockopt.mark carries: the patch's flag, and the base the levels are added to.
|
||||
LEVEL_MARK_FLAG = 0x40000000
|
||||
EXIT_MARK = LEVEL_MARK_FLAG | MARK_BASE
|
||||
MAX_SLOTS = 0xFFFF
|
||||
|
||||
|
||||
def ruleset(table: str = TABLE) -> str:
|
||||
"""The table from nothing: an existing one of that name goes first."""
|
||||
mark = f"ct mark & 0x{MARK_MASK:08x} == 0x{MARK_BASE:08x}"
|
||||
return f"""table inet {table}
|
||||
delete table inet {table}
|
||||
table inet {table} {{
|
||||
set ban4 {{ type ipv4_addr . inet_service; flags timeout; }}
|
||||
set ban6 {{ type ipv6_addr . inet_service; flags timeout; }}
|
||||
set cut4 {{ type ipv4_addr . inet_service; flags timeout; }}
|
||||
set cut6 {{ type ipv6_addr . inet_service; flags timeout; }}
|
||||
map up {{ type mark : limit; }}
|
||||
map down {{ type mark : limit; }}
|
||||
map awg_up4 {{ type ifname . ipv4_addr : limit; }}
|
||||
map awg_down4 {{ type ifname . ipv4_addr : limit; }}
|
||||
map awg_up6 {{ type ifname . ipv6_addr : limit; }}
|
||||
map awg_down6 {{ type ifname . ipv6_addr : limit; }}
|
||||
|
||||
chain input {{
|
||||
type filter hook input priority filter - 5; policy accept;
|
||||
ip saddr . th dport @ban4 drop
|
||||
ip6 saddr . th dport @ban6 drop
|
||||
meta l4proto udp ip saddr . th dport @cut4 drop
|
||||
meta l4proto udp ip6 saddr . th dport @cut6 drop
|
||||
ct direction reply {mark} limit name ct mark map @down drop
|
||||
}}
|
||||
chain output {{
|
||||
type filter hook output priority filter - 5; policy accept;
|
||||
ct state new meta mark & 0x{MARK_MASK:08x} == 0x{MARK_BASE:08x} ct mark set meta mark
|
||||
ct direction original {mark} limit name ct mark map @up drop
|
||||
}}
|
||||
chain awg_in {{
|
||||
type filter hook prerouting priority filter - 5; policy accept;
|
||||
limit name iifname . ip saddr map @awg_up4 drop
|
||||
limit name iifname . ip6 saddr map @awg_up6 drop
|
||||
}}
|
||||
chain awg_out {{
|
||||
type filter hook postrouting priority filter - 5; policy accept;
|
||||
limit name oifname . ip daddr map @awg_down4 drop
|
||||
limit name oifname . ip6 daddr map @awg_down6 drop
|
||||
}}
|
||||
}}
|
||||
"""
|
||||
|
||||
|
||||
def _limit(name: str, bits: int) -> str:
|
||||
rate = max(bits // 8, 1)
|
||||
# Room for a TCP window or two: a burst too small holds a fast link far below its rate.
|
||||
burst = max(rate // 4, 65536)
|
||||
return f"{name} {{ rate over {rate} bytes/second burst {burst} bytes }}"
|
||||
|
||||
|
||||
def limits_script(table: str, existing: list[str], users: dict[int, dict], peers: list[dict]) -> str:
|
||||
"""One transaction that empties the maps, drops the old limits and adds the new ones.
|
||||
|
||||
users: {slot: {"up": bit/s|None, "down": bit/s|None}}; peers: [{"interface", "address",
|
||||
"up", "down"}]."""
|
||||
lines = [f"flush map inet {table} {m}" for m in ("up", "down", "awg_up4", "awg_down4", "awg_up6", "awg_down6")]
|
||||
lines += [f"delete limit inet {table} {name}" for name in sorted(existing)]
|
||||
for slot, speed in sorted(users.items()):
|
||||
for direction in ("up", "down"):
|
||||
if speed.get(direction):
|
||||
name = f"u{slot}_{direction}"
|
||||
lines.append(f"add limit inet {table} {_limit(name, speed[direction])}")
|
||||
lines.append(f'add element inet {table} {direction} {{ 0x{MARK_BASE + slot:08x} : "{name}" }}')
|
||||
for index, peer in enumerate(peers):
|
||||
family = "6" if ":" in peer["address"] else "4"
|
||||
for direction in ("up", "down"):
|
||||
if peer.get(direction):
|
||||
name = f"p{index}_{direction}"
|
||||
lines.append(f"add limit inet {table} {_limit(name, peer[direction])}")
|
||||
lines.append(
|
||||
f'add element inet {table} awg_{direction}{family} {{ "{peer["interface"]}" . {peer["address"]} : "{name}" }}'
|
||||
)
|
||||
return "\n".join(lines) + "\n"
|
||||
|
||||
|
||||
class Netfilter:
|
||||
"""nft, for the manager. Off (nft None) on hosts it cannot run on: nothing happens."""
|
||||
|
||||
def __init__(self, nft: str | None, table: str = TABLE):
|
||||
self.nft = nft
|
||||
self.table = table
|
||||
self.installed: tuple | None = None
|
||||
|
||||
@property
|
||||
def enabled(self) -> bool:
|
||||
return bool(self.nft)
|
||||
|
||||
def _run(self, *args: str, stdin: str | None = None) -> str:
|
||||
done = subprocess.run([self.nft, *args], input=stdin, capture_output=True, text=True, timeout=30)
|
||||
if done.returncode != 0:
|
||||
raise RuntimeError(done.stderr.strip() or f"nft exited with {done.returncode}")
|
||||
return done.stdout
|
||||
|
||||
def present(self) -> bool:
|
||||
try:
|
||||
self._run("list", "table", "inet", self.table)
|
||||
return True
|
||||
except RuntimeError:
|
||||
return False
|
||||
|
||||
def ensure(self) -> bool:
|
||||
"""Make the table if it is gone. True when it was (the limits must go in again)."""
|
||||
if not self.enabled or self.present():
|
||||
return False
|
||||
self._run("-f", "-", stdin=ruleset(self.table))
|
||||
self.installed = None
|
||||
return True
|
||||
|
||||
def objects(self) -> list[str]:
|
||||
out = self._run("-j", "list", "table", "inet", self.table)
|
||||
names = []
|
||||
for item in json.loads(out).get("nftables", []):
|
||||
if "limit" in item and isinstance(item["limit"], dict) and "name" in item["limit"]:
|
||||
names.append(item["limit"]["name"])
|
||||
return names
|
||||
|
||||
def sync_limits(self, users: dict[int, dict], peers: list[dict]) -> bool:
|
||||
"""Install these limits unless they are what is in. True when it changed them."""
|
||||
if not self.enabled:
|
||||
return False
|
||||
wanted = (tuple(sorted((slot, s.get("up"), s.get("down")) for slot, s in users.items())),
|
||||
tuple(sorted((p["interface"], p["address"], p.get("up"), p.get("down")) for p in peers)))
|
||||
if wanted == self.installed and self.present():
|
||||
return False
|
||||
self.ensure()
|
||||
self._run("-f", "-", stdin=limits_script(self.table, self.objects(), users, peers))
|
||||
self.installed = wanted
|
||||
return True
|
||||
|
||||
def ban(self, ip: str, ports: list[int], seconds: int) -> None:
|
||||
if not self.enabled or not ports:
|
||||
return
|
||||
family = "6" if ":" in ip else "4"
|
||||
elements = ", ".join(f"{ip} . {port} timeout {int(seconds)}s" for port in sorted(set(ports)))
|
||||
self._run("add", "element", "inet", self.table, f"ban{family}", "{ " + elements + " }")
|
||||
|
||||
def bans(self) -> list[dict]:
|
||||
"""[{"ip", "port", "expires"}]: seconds left."""
|
||||
if not self.enabled or not self.present():
|
||||
return []
|
||||
result = []
|
||||
for family in ("4", "6"):
|
||||
out = self._run("-j", "list", "set", "inet", self.table, f"ban{family}")
|
||||
for item in json.loads(out).get("nftables", []):
|
||||
for element in (item.get("set") or {}).get("elem") or []:
|
||||
value = element.get("elem", element) if isinstance(element, dict) else element
|
||||
expires = value.get("expires") if isinstance(value, dict) else None
|
||||
concat = (value.get("val") if isinstance(value, dict) else value) or {}
|
||||
parts = concat.get("concat") if isinstance(concat, dict) else None
|
||||
if parts and len(parts) == 2:
|
||||
result.append({"ip": str(parts[0]), "port": int(parts[1]), "expires": expires})
|
||||
return result
|
||||
|
||||
def unban(self, ip: str) -> int:
|
||||
"""Lift every ban of this address; how many there were."""
|
||||
found = [ban for ban in self.bans() if ban["ip"] == ip]
|
||||
if found:
|
||||
family = "6" if ":" in ip else "4"
|
||||
elements = ", ".join(f"{ip} . {ban['port']}" for ban in found)
|
||||
self._run("delete", "element", "inet", self.table, f"ban{family}", "{ " + elements + " }")
|
||||
return len(found)
|
||||
@@ -0,0 +1,538 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Per-user policies of the inbound manager (services.proxy-suite.inbounds.manager).
|
||||
|
||||
A policy says whether a user may connect and how much: switched on or off by hand, an
|
||||
expiry time (or a term that starts with the first connection), a traffic allowance that may renew every day, week or month, how many
|
||||
addresses may use it at once, and a speed limit. Declared users take theirs from
|
||||
`inbounds.users.<name>.policy`; the manager's policy file overrides those field by field,
|
||||
and holds the runtime users' whole. Only the manager (root) writes that file.
|
||||
|
||||
The manager's state file keeps what the policies are measured against: when each user's
|
||||
traffic period began, and the speed slot (XRay user level) a limited user's sockets are
|
||||
marked with. Traffic comes from the collector's file (proxy-suite-inbound-stats), whose
|
||||
daily totals are summed from the period's first day, less what that day had carried before
|
||||
the period began.
|
||||
|
||||
Whoever renders the inbounds (build-inbound.py, awg_inbound.py) asks statuses() which users
|
||||
are active and at which level; this module never writes there.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import calendar
|
||||
import copy
|
||||
import datetime
|
||||
import fcntl
|
||||
import json
|
||||
import math
|
||||
import os
|
||||
import re
|
||||
import secrets
|
||||
import time
|
||||
|
||||
PERIODS = ("daily", "weekly", "monthly")
|
||||
DEFAULT_POLICY = {
|
||||
"enabled": True,
|
||||
"expiresAt": None,
|
||||
"expiresAfter": None,
|
||||
"trafficLimit": None,
|
||||
"trafficPeriod": None,
|
||||
"ipLimit": None,
|
||||
"speedLimit": None,
|
||||
"meta": {},
|
||||
}
|
||||
FIELDS = tuple(DEFAULT_POLICY)
|
||||
MAX_META_KEYS = 32
|
||||
MAX_META_VALUE = 1024
|
||||
STATE_VERSION = 1
|
||||
MAX_TIME = 253402214400 # 9999-12-31
|
||||
|
||||
|
||||
class PolicyError(ValueError):
|
||||
"""A policy value that cannot be used."""
|
||||
|
||||
|
||||
# --- parsing --------------------------------------------------------------------------
|
||||
|
||||
_SIZE = re.compile(r"\s*([0-9]+(?:\.[0-9]+)?)\s*([KMGTP]?)(?:I?B)?\s*", re.IGNORECASE)
|
||||
_RATE = re.compile(r"\s*([0-9]+(?:\.[0-9]+)?)\s*([KMG]?)(?:BIT|BPS|BIT/S|B/S)?\s*", re.IGNORECASE)
|
||||
_RELATIVE = re.compile(r"\s*\+\s*([0-9]+)\s*([mhdw])\s*", re.IGNORECASE)
|
||||
_DURATION = re.compile(r"\s*\+?\s*([0-9]+)\s*([mhdw])\s*", re.IGNORECASE)
|
||||
SIZE_UNITS = {"": 1, "K": 1024, "M": 1024**2, "G": 1024**3, "T": 1024**4, "P": 1024**5}
|
||||
RATE_UNITS = {"": 1, "K": 1000, "M": 1000**2, "G": 1000**3}
|
||||
RELATIVE_UNITS = {"m": 60, "h": 3600, "d": 86400, "w": 7 * 86400}
|
||||
|
||||
|
||||
def parse_size(value) -> int | None:
|
||||
"""Bytes, from an int or "50G", "1.5T", "512MiB": binary units, as clients show them.
|
||||
None, "", "none", "unlimited" and 0 mean no limit."""
|
||||
if value is None or value == 0:
|
||||
return None
|
||||
if type(value) is int:
|
||||
if value < 0:
|
||||
raise PolicyError(f"size {value} is negative")
|
||||
return value
|
||||
if not isinstance(value, str):
|
||||
raise PolicyError(f"size {json.dumps(value)} is neither a number nor a string")
|
||||
if value.strip().lower() in ("", "none", "unlimited", "0"):
|
||||
return None
|
||||
match = _SIZE.fullmatch(value)
|
||||
if not match:
|
||||
raise PolicyError(f"size {json.dumps(value)}: a number with K, M, G or T")
|
||||
return int(float(match.group(1)) * SIZE_UNITS[match.group(2).upper()])
|
||||
|
||||
|
||||
def parse_rate(value) -> int | None:
|
||||
"""Bits per second, from an int or "10M", "500k", "1G": decimal units, as ISPs sell them."""
|
||||
if value is None or value == 0:
|
||||
return None
|
||||
if type(value) is int:
|
||||
if value < 0:
|
||||
raise PolicyError(f"rate {value} is negative")
|
||||
return value
|
||||
if not isinstance(value, str):
|
||||
raise PolicyError(f"rate {json.dumps(value)} is neither a number nor a string")
|
||||
if value.strip().lower() in ("", "none", "unlimited", "0"):
|
||||
return None
|
||||
match = _RATE.fullmatch(value)
|
||||
if not match:
|
||||
raise PolicyError(f"rate {json.dumps(value)}: bits per second, a number with k, M or G")
|
||||
return int(float(match.group(1)) * RATE_UNITS[match.group(2).upper()])
|
||||
|
||||
|
||||
def parse_speed(value) -> dict | None:
|
||||
"""{"up": bit/s|None, "down": bit/s|None}, from one rate for both ("20M"), "down/up"
|
||||
("20M/5M"), or such an object. None: no limit."""
|
||||
if value is None:
|
||||
return None
|
||||
if isinstance(value, dict):
|
||||
unknown = set(value) - {"up", "down"}
|
||||
if unknown:
|
||||
raise PolicyError(f"speedLimit: unknown keys {sorted(unknown)}")
|
||||
speed = {"up": parse_rate(value.get("up")), "down": parse_rate(value.get("down"))}
|
||||
elif isinstance(value, str) and "/" in value:
|
||||
down, up = value.split("/", 1)
|
||||
speed = {"up": parse_rate(up), "down": parse_rate(down)}
|
||||
else:
|
||||
rate = parse_rate(value)
|
||||
speed = {"up": rate, "down": rate}
|
||||
return speed if speed["up"] or speed["down"] else None
|
||||
|
||||
|
||||
def parse_duration(value) -> int | None:
|
||||
"""Seconds, from an int or "30d", "+12h" (m, h, d, w). None, "", "none" and 0: none."""
|
||||
if value is None or value == 0:
|
||||
return None
|
||||
if type(value) is int:
|
||||
if value < 0:
|
||||
raise PolicyError(f"duration {value} is negative")
|
||||
return value
|
||||
if not isinstance(value, str):
|
||||
raise PolicyError(f"duration {json.dumps(value)} is neither a number nor a string")
|
||||
text = value.strip()
|
||||
if text.lower() in ("", "none", "0"):
|
||||
return None
|
||||
if text.isdigit():
|
||||
return int(text)
|
||||
match = _DURATION.fullmatch(text)
|
||||
if not match:
|
||||
raise PolicyError(f"duration {json.dumps(value)}: a number with m, h, d or w, such as 30d")
|
||||
return int(match.group(1)) * RELATIVE_UNITS[match.group(2).lower()] or None
|
||||
|
||||
|
||||
def _local_midnight(day: datetime.date) -> int:
|
||||
return int(time.mktime(day.timetuple()))
|
||||
|
||||
|
||||
def parse_time(value, now: float | None = None) -> int | None:
|
||||
"""A Unix time from an int, "2026-12-31" (the end of that day, local time),
|
||||
"2026-12-31T18:00" (local), an ISO time with its zone, or "+30d" from now (m, h, d, w).
|
||||
None, "", "never": no expiry."""
|
||||
if value is None:
|
||||
return None
|
||||
if type(value) is int:
|
||||
return value
|
||||
if not isinstance(value, str):
|
||||
raise PolicyError(f"time {json.dumps(value)} is neither a number nor a string")
|
||||
text = value.strip()
|
||||
if text.lower() in ("", "never", "none"):
|
||||
return None
|
||||
if text.isdigit():
|
||||
return int(text)
|
||||
relative = _RELATIVE.fullmatch(text)
|
||||
if relative:
|
||||
base = time.time() if now is None else now
|
||||
return int(base) + int(relative.group(1)) * RELATIVE_UNITS[relative.group(2).lower()]
|
||||
try:
|
||||
if re.fullmatch(r"[0-9]{4}-[0-9]{2}-[0-9]{2}", text):
|
||||
return _local_midnight(datetime.date.fromisoformat(text) + datetime.timedelta(days=1))
|
||||
moment = datetime.datetime.fromisoformat(text)
|
||||
except ValueError:
|
||||
raise PolicyError(f"time {json.dumps(value)}: a date, an ISO time, a Unix time or +<n>d") from None
|
||||
return int(moment.timestamp())
|
||||
|
||||
|
||||
# --- policies -------------------------------------------------------------------------
|
||||
|
||||
|
||||
def _check_meta(value) -> dict:
|
||||
if not isinstance(value, dict):
|
||||
raise PolicyError("meta must be an object of strings")
|
||||
if len(value) > MAX_META_KEYS:
|
||||
raise PolicyError(f"meta holds at most {MAX_META_KEYS} keys")
|
||||
for key, item in value.items():
|
||||
if not isinstance(key, str) or not re.fullmatch(r"[A-Za-z0-9_.-]{1,64}", key):
|
||||
raise PolicyError(f"meta key {json.dumps(key)}: letters, digits, dot, dash and underscore, up to 64")
|
||||
if not isinstance(item, str) or len(item) > MAX_META_VALUE:
|
||||
raise PolicyError(f"meta.{key} must be a string of at most {MAX_META_VALUE} characters")
|
||||
return dict(value)
|
||||
|
||||
|
||||
def normalize(fields: dict, now: float | None = None) -> dict:
|
||||
"""Policy fields as the file keeps them, from what a person or a bot gave: sizes,
|
||||
rates and times in any form parse_* takes. Only the fields given."""
|
||||
if not isinstance(fields, dict):
|
||||
raise PolicyError("a policy is an object")
|
||||
unknown = set(fields) - set(FIELDS)
|
||||
if unknown:
|
||||
raise PolicyError(f"unknown policy fields: {', '.join(sorted(unknown))}")
|
||||
out: dict = {}
|
||||
for key, value in fields.items():
|
||||
if key == "enabled":
|
||||
if type(value) is not bool:
|
||||
raise PolicyError("enabled must be true or false")
|
||||
out[key] = value
|
||||
elif key == "expiresAt":
|
||||
# 0 is no expiry, as 0 is no limit in the other fields: not 1970.
|
||||
out[key] = None if value in (0, "0") else parse_time(value, now)
|
||||
if out[key] is not None and not 0 < out[key] < MAX_TIME:
|
||||
raise PolicyError(f"time {json.dumps(value)} is out of range")
|
||||
elif key == "expiresAfter":
|
||||
out[key] = parse_duration(value)
|
||||
if out[key] is not None and out[key] >= MAX_TIME:
|
||||
raise PolicyError(f"duration {json.dumps(value)} is out of range")
|
||||
elif key == "trafficLimit":
|
||||
out[key] = parse_size(value)
|
||||
elif key == "trafficPeriod":
|
||||
if value in (None, "", "none", "never"):
|
||||
out[key] = None
|
||||
elif value in PERIODS:
|
||||
out[key] = value
|
||||
else:
|
||||
raise PolicyError(f"trafficPeriod must be one of {', '.join(PERIODS)} or none")
|
||||
elif key == "ipLimit":
|
||||
if value in (None, 0, ""):
|
||||
out[key] = None
|
||||
elif type(value) is int and value > 0:
|
||||
out[key] = value
|
||||
elif isinstance(value, str) and value.isdigit():
|
||||
out[key] = int(value) or None
|
||||
else:
|
||||
raise PolicyError("ipLimit must be a positive number, or 0 for none")
|
||||
elif key == "speedLimit":
|
||||
out[key] = parse_speed(value)
|
||||
elif key == "meta":
|
||||
out[key] = _check_meta(value)
|
||||
return out
|
||||
|
||||
|
||||
def check_stored(entry: dict) -> dict:
|
||||
"""A stored policy, already normalized: the same check, which must change nothing."""
|
||||
normalized = normalize(entry)
|
||||
if normalized != entry:
|
||||
raise PolicyError("not in its stored form")
|
||||
return entry
|
||||
|
||||
|
||||
def effective(declared: dict | None, stored: dict | None) -> dict:
|
||||
"""The defaults, then the declared policy, then the stored one, field by field."""
|
||||
policy = copy.deepcopy(DEFAULT_POLICY)
|
||||
for layer in (declared or {}, stored or {}):
|
||||
for key in FIELDS:
|
||||
if key in layer:
|
||||
policy[key] = copy.deepcopy(layer[key])
|
||||
return policy
|
||||
|
||||
|
||||
def declared_policies(spec: dict) -> dict[str, dict]:
|
||||
"""The declared users' `policy` options, normalized; a bad one is left out (the module's
|
||||
assertions catch it at build time)."""
|
||||
policies = {}
|
||||
for name, user in (spec.get("users") or {}).items():
|
||||
declared = {k: v for k, v in (user.get("policy") or {}).items() if v is not None}
|
||||
try:
|
||||
policies[name] = normalize(declared)
|
||||
except PolicyError:
|
||||
continue
|
||||
return policies
|
||||
|
||||
|
||||
# --- files ----------------------------------------------------------------------------
|
||||
|
||||
|
||||
def read_json(path: str, default):
|
||||
try:
|
||||
with open(path, encoding="utf-8") as handle:
|
||||
value = json.load(handle)
|
||||
except FileNotFoundError:
|
||||
return copy.deepcopy(default)
|
||||
except (OSError, ValueError):
|
||||
return copy.deepcopy(default)
|
||||
return value if isinstance(value, type(default)) else copy.deepcopy(default)
|
||||
|
||||
|
||||
def write_json(path: str, value, mode: int = 0o600) -> None:
|
||||
"""Atomically, through a new file of its own next to it."""
|
||||
directory = os.path.dirname(path) or "."
|
||||
os.makedirs(directory, mode=0o700, exist_ok=True)
|
||||
tmp = os.path.join(directory, f".{os.path.basename(path)}.{secrets.token_hex(6)}")
|
||||
fd = os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW, mode)
|
||||
try:
|
||||
with os.fdopen(fd, "w", encoding="utf-8") as handle:
|
||||
handle.write(json.dumps(value, indent=2, sort_keys=True) + "\n")
|
||||
handle.flush()
|
||||
os.fsync(handle.fileno())
|
||||
os.replace(tmp, path)
|
||||
except BaseException:
|
||||
try:
|
||||
os.unlink(tmp)
|
||||
except OSError:
|
||||
pass
|
||||
raise
|
||||
|
||||
|
||||
class Locked:
|
||||
"""flock on <path>.lock, for a read-modify-write of path."""
|
||||
|
||||
def __init__(self, path: str):
|
||||
self.path = path + ".lock"
|
||||
self.fd = -1
|
||||
|
||||
def __enter__(self):
|
||||
os.makedirs(os.path.dirname(self.path) or ".", mode=0o700, exist_ok=True)
|
||||
self.fd = os.open(self.path, os.O_RDWR | os.O_CREAT | os.O_NOFOLLOW, 0o600)
|
||||
fcntl.flock(self.fd, fcntl.LOCK_EX)
|
||||
return self
|
||||
|
||||
def __exit__(self, *_):
|
||||
os.close(self.fd)
|
||||
|
||||
|
||||
def load_policies(path: str) -> dict[str, dict]:
|
||||
"""The policy file: {name: stored fields}; entries that do not hold up are left out."""
|
||||
raw = read_json(path, {})
|
||||
policies = {}
|
||||
for name, entry in (raw.get("users") or {}).items() if isinstance(raw.get("users"), dict) else []:
|
||||
try:
|
||||
policies[name] = check_stored(entry)
|
||||
except PolicyError:
|
||||
continue
|
||||
return policies
|
||||
|
||||
|
||||
def _count(value) -> bool:
|
||||
return type(value) is int and value >= 0
|
||||
|
||||
|
||||
def check_user_state(entry) -> dict:
|
||||
"""A user's entry in the state file, as start_period() and roll_period() make it: the
|
||||
renderers read it at every start, so a bad one (an import, a hand edit) must not get in."""
|
||||
if not isinstance(entry, dict):
|
||||
raise PolicyError("a user's state is an object")
|
||||
for key in ("periodStart", "baselineUp", "baselineDown"):
|
||||
if key in entry and not _count(entry[key]):
|
||||
raise PolicyError(f"{key} must be a whole number")
|
||||
# A date the calendar functions still take (the year 9999).
|
||||
if entry.get("periodStart", 0) >= MAX_TIME:
|
||||
raise PolicyError("periodStart is too far ahead")
|
||||
if "anchorDay" in entry and not (type(entry["anchorDay"]) is int and 1 <= entry["anchorDay"] <= 31):
|
||||
raise PolicyError("anchorDay must be a day of the month")
|
||||
if "notified" in entry and not isinstance(entry["notified"], dict):
|
||||
raise PolicyError("notified must be an object")
|
||||
return entry
|
||||
|
||||
|
||||
def load_state(path: str) -> dict:
|
||||
"""The state file; entries that do not hold up are left out, as the policy file's are."""
|
||||
state = read_json(path, {})
|
||||
state.setdefault("version", STATE_VERSION)
|
||||
for key in ("users", "slots", "bans", "seen", "subscriptions"):
|
||||
if not isinstance(state.get(key), dict):
|
||||
state[key] = {}
|
||||
for name, entry in list(state["users"].items()):
|
||||
try:
|
||||
check_user_state(entry)
|
||||
except PolicyError:
|
||||
del state["users"][name]
|
||||
for name, slot in list(state["slots"].items()):
|
||||
if not (type(slot) is int and slot > 0):
|
||||
del state["slots"][name]
|
||||
for name, first in list(state["seen"].items()):
|
||||
if not isinstance(first, dict):
|
||||
del state["seen"][name]
|
||||
# Salts of the users whose subscription URL was moved on (proxy_inbound.subscription_token).
|
||||
for name, salt in list(state["subscriptions"].items()):
|
||||
if not is_subscription_salt(salt):
|
||||
del state["subscriptions"][name]
|
||||
return state
|
||||
|
||||
|
||||
def is_subscription_salt(value) -> bool:
|
||||
return isinstance(value, str) and re.fullmatch(r"[0-9a-f]{32}", value) is not None
|
||||
|
||||
|
||||
def read_stats(path: str) -> dict:
|
||||
return read_json(path, {})
|
||||
|
||||
|
||||
# --- traffic --------------------------------------------------------------------------
|
||||
|
||||
|
||||
def day_key(ts: float) -> str:
|
||||
"""The collector's day: its `date +%F`, in local time."""
|
||||
return time.strftime("%Y-%m-%d", time.localtime(ts))
|
||||
|
||||
|
||||
def _counters(entry) -> tuple[int, int]:
|
||||
"""(up, down) of one day's counters; nothing from a malformed entry, which must not stop
|
||||
the renderers that ask statuses()."""
|
||||
if not isinstance(entry, dict):
|
||||
return 0, 0
|
||||
|
||||
def number(value) -> int:
|
||||
# jq may write a large sum as a float.
|
||||
return int(value) if type(value) in (int, float) and math.isfinite(value) and value >= 0 else 0
|
||||
|
||||
return number(entry.get("up", 0)), number(entry.get("down", 0))
|
||||
|
||||
|
||||
def day_traffic(stats: dict, day: str, name: str) -> tuple[int, int]:
|
||||
buckets = (stats.get("days") or {}).get(day)
|
||||
users = buckets.get("user") if isinstance(buckets, dict) else None
|
||||
return _counters(users.get(name) if isinstance(users, dict) else None)
|
||||
|
||||
|
||||
def day_total(stats: dict, day: str, name: str) -> int:
|
||||
return sum(day_traffic(stats, day, name))
|
||||
|
||||
|
||||
def period_traffic(stats: dict, user_state: dict, name: str) -> tuple[int, int]:
|
||||
"""(up, down) since the period began: every day from its first, less what that day had
|
||||
before it (the baselines). A user the manager has not measured yet has used nothing:
|
||||
their count begins when it first sees them, not with whatever the file kept before."""
|
||||
start = user_state.get("periodStart")
|
||||
if not start:
|
||||
return 0, 0
|
||||
first = day_key(start)
|
||||
up = down = 0
|
||||
days = stats.get("days")
|
||||
for day, buckets in (days.items() if isinstance(days, dict) else []):
|
||||
if not isinstance(day, str) or day < first or not isinstance(buckets, dict):
|
||||
continue
|
||||
users = buckets.get("user")
|
||||
day_up, day_down = _counters(users.get(name) if isinstance(users, dict) else None)
|
||||
up += day_up
|
||||
down += day_down
|
||||
return (max(up - int(user_state.get("baselineUp", 0) or 0), 0),
|
||||
max(down - int(user_state.get("baselineDown", 0) or 0), 0))
|
||||
|
||||
|
||||
def used_bytes(stats: dict, user_state: dict, name: str) -> int:
|
||||
return sum(period_traffic(stats, user_state, name))
|
||||
|
||||
|
||||
def _add_period(day: datetime.date, period: str, anchor_day: int) -> datetime.date:
|
||||
if period == "daily":
|
||||
return day + datetime.timedelta(days=1)
|
||||
if period == "weekly":
|
||||
return day + datetime.timedelta(days=7)
|
||||
year, month = (day.year + 1, 1) if day.month == 12 else (day.year, day.month + 1)
|
||||
return datetime.date(year, month, min(anchor_day, calendar.monthrange(year, month)[1]))
|
||||
|
||||
|
||||
def period_end(policy: dict, user_state: dict) -> int | None:
|
||||
"""When the current period ends and the traffic starts over, or None."""
|
||||
period = policy.get("trafficPeriod")
|
||||
start = user_state.get("periodStart")
|
||||
if period not in PERIODS or not start:
|
||||
return None
|
||||
first = datetime.date.fromtimestamp(start)
|
||||
anchor = int(user_state.get("anchorDay") or first.day)
|
||||
return _local_midnight(_add_period(first, period, anchor))
|
||||
|
||||
|
||||
def start_period(stats: dict, name: str, now: float) -> dict:
|
||||
"""A period that begins now: the day so far is the baseline. A renewing period begins
|
||||
at midnight, so a monthly one renews on this day of the month."""
|
||||
up, down = day_traffic(stats, day_key(now), name)
|
||||
return {
|
||||
"periodStart": int(now),
|
||||
"baselineUp": up,
|
||||
"baselineDown": down,
|
||||
"anchorDay": datetime.date.fromtimestamp(now).day,
|
||||
}
|
||||
|
||||
|
||||
def roll_period(policy: dict, user_state: dict, now: float) -> bool:
|
||||
"""Move a renewing period on past now, from boundary to boundary (midnights, so nothing
|
||||
of the day before counts). True when it moved."""
|
||||
moved = False
|
||||
while True:
|
||||
end = period_end(policy, user_state)
|
||||
if end is None or end > now:
|
||||
return moved
|
||||
user_state["periodStart"] = end
|
||||
user_state["baselineUp"] = user_state["baselineDown"] = 0
|
||||
moved = True
|
||||
|
||||
|
||||
# --- status ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def on_hold(policy: dict) -> bool:
|
||||
"""A term that starts with the first connection, and has not: expiresAfter without
|
||||
expiresAt. An expiresAt set by hand wins over it."""
|
||||
return policy.get("expiresAt") is None and bool(policy.get("expiresAfter"))
|
||||
|
||||
|
||||
def status(policy: dict, used: int, now: float) -> dict:
|
||||
"""{"active", "reasons"}: why a user may not connect now, if they may not. A user on
|
||||
hold may: their term begins when they do."""
|
||||
reasons = []
|
||||
if not policy.get("enabled", True):
|
||||
reasons.append("disabled")
|
||||
expires = policy.get("expiresAt")
|
||||
if expires is not None and now >= expires:
|
||||
reasons.append("expired")
|
||||
limit = policy.get("trafficLimit")
|
||||
if limit is not None and used >= limit:
|
||||
reasons.append("traffic")
|
||||
return {"active": not reasons, "reasons": reasons}
|
||||
|
||||
|
||||
def user_names(spec: dict, runtime_users) -> list[str]:
|
||||
return sorted(set(spec.get("users") or {}) | set(runtime_users))
|
||||
|
||||
|
||||
def statuses(spec: dict, runtime_users, now: float | None = None) -> dict[str, dict]:
|
||||
"""Each user's {"active", "level", "reasons"}, for the renderers. Empty without the
|
||||
manager: everyone active, nobody limited, as before it."""
|
||||
manager = spec.get("manager")
|
||||
if not manager:
|
||||
return {}
|
||||
now = time.time() if now is None else now
|
||||
declared = declared_policies(spec)
|
||||
stored = load_policies(manager["policyFile"])
|
||||
state = load_state(manager["stateFile"])
|
||||
stats = read_stats(manager["statsFile"])
|
||||
result = {}
|
||||
for name in user_names(spec, runtime_users):
|
||||
policy = effective(declared.get(name), stored.get(name))
|
||||
user_state = copy.deepcopy(state["users"].get(name) or {})
|
||||
roll_period(policy, user_state, now)
|
||||
view = status(policy, used_bytes(stats, user_state, name), now)
|
||||
slot = state["slots"].get(name)
|
||||
limited = bool(policy.get("speedLimit")) and manager.get("speedLimits", False)
|
||||
view["level"] = int(slot) if limited and isinstance(slot, int) and slot > 0 else 0
|
||||
result[name] = view
|
||||
return result
|
||||
@@ -37,6 +37,8 @@ import time
|
||||
import urllib.parse
|
||||
import uuid
|
||||
|
||||
import inbound_policy
|
||||
|
||||
# User names and listener tags: they become file names, XRay emails and tags, and URL parts.
|
||||
NAME = re.compile(r"[A-Za-z0-9][A-Za-z0-9._-]{0,31}")
|
||||
MAX_ENTRY_BYTES = 65536
|
||||
@@ -841,17 +843,55 @@ def number_users(spec: dict, names: list[str], state_users: dict, warnings: list
|
||||
return numbered
|
||||
|
||||
|
||||
def merge_state(spec: dict, state: dict, check_ports: bool = False) -> tuple[dict, dict, list[str]]:
|
||||
# Listener types whose XRay inbound runs with no client at all, so a user switched off by
|
||||
# the manager leaves it in place, ready to take them back without a restart. A Shadowsocks
|
||||
# listener has a client list only with more than one user (render_xray_inbound).
|
||||
EMPTY_CLIENTS_TYPES = ("vless", "vmess", "trojan", "hysteria2")
|
||||
|
||||
|
||||
def _runs_without_clients(listener: dict) -> bool:
|
||||
if listener.get("type") in EMPTY_CLIENTS_TYPES:
|
||||
return True
|
||||
return listener.get("type") == "shadowsocks" and len(listener["users"]) > 1
|
||||
|
||||
|
||||
def apply_statuses(merged: dict, statuses: dict, warnings: list[str]) -> None:
|
||||
"""The manager's view of each user (inbound_policy.statuses): "active" and "level" on
|
||||
every listener's users. A listener whose users are all switched off stays when it runs
|
||||
without clients, and is left out otherwise, as one without users is."""
|
||||
kept = []
|
||||
for listener in merged["listeners"]:
|
||||
for user in listener["users"]:
|
||||
view = statuses.get(user["name"]) or {}
|
||||
user["active"] = view.get("active", True)
|
||||
user["level"] = view.get("level", 0)
|
||||
if (
|
||||
listener["users"]
|
||||
and listener.get("type") not in (None, "amneziawg")
|
||||
and not any(user["active"] for user in listener["users"])
|
||||
and not _runs_without_clients(listener)
|
||||
):
|
||||
warnings.append(f"listener '{listener['tag']}' has no active users; not started")
|
||||
continue
|
||||
kept.append(listener)
|
||||
merged["listeners"] = kept
|
||||
|
||||
|
||||
def merge_state(spec: dict, state: dict, check_ports: bool | set = False, statuses: dict | None = None) -> tuple[dict, dict, list[str]]:
|
||||
"""The spec with the runtime entries merged in, what was made of them, and warnings.
|
||||
|
||||
The result's "runtime" key holds {"listeners": [runtime tags kept], "users": [runtime
|
||||
names kept], "selfSources": [...], "problems": {("user"|"listener", name): [why]}}.
|
||||
statuses: the manager's, by user name (inbound_policy.statuses); None leaves everyone
|
||||
active, at level 0.
|
||||
"""
|
||||
runtime = spec.get("runtime")
|
||||
merged = copy.deepcopy(spec)
|
||||
result = {"listeners": [], "users": [], "selfSources": [], "problems": {}}
|
||||
if not runtime:
|
||||
return merged, result, []
|
||||
warnings: list[str] = []
|
||||
apply_statuses(merged, statuses or {}, warnings)
|
||||
return merged, result, warnings
|
||||
warnings: list[str] = []
|
||||
problems: dict = result["problems"]
|
||||
|
||||
@@ -948,7 +988,11 @@ def merge_state(spec: dict, state: dict, check_ports: bool = False) -> tuple[dic
|
||||
why = [f"cannot be checked: {exc}"]
|
||||
if listener["port"] in declared_ports or listener["port"] in used_ports:
|
||||
why.append(f"port {listener['port']} is taken by another listener")
|
||||
if not why and check_ports and not port_free(listener["listen"], listener["port"], _protocols(listener)):
|
||||
# check_ports may name the ports the running XRay holds already (inbound_apply.py):
|
||||
# those are its own, not taken.
|
||||
held = check_ports if isinstance(check_ports, (set, frozenset)) else set()
|
||||
if (not why and check_ports and listener["port"] not in held
|
||||
and not port_free(listener["listen"], listener["port"], _protocols(listener))):
|
||||
why.append(f"port {listener['port']} is in use on this host")
|
||||
if why:
|
||||
for message in why:
|
||||
@@ -1005,16 +1049,21 @@ def merge_state(spec: dict, state: dict, check_ports: bool = False) -> tuple[dic
|
||||
}
|
||||
result["users"] = sorted(users)
|
||||
result["selfSources"] = number_users(spec, sorted(on_xray), state["users"], warnings)
|
||||
apply_statuses(merged, statuses or {}, warnings)
|
||||
result["listeners"] = [tag for tag in result["listeners"] if any(l["tag"] == tag for l in merged["listeners"])]
|
||||
return merged, result, warnings
|
||||
|
||||
|
||||
def merge(spec: dict, check_ports: bool = False) -> tuple[dict, dict, list[str]]:
|
||||
"""merge_state() on the spool the spec names, as the services read it at start."""
|
||||
def merge(spec: dict, check_ports: bool | set = False, now: float | None = None) -> tuple[dict, dict, list[str]]:
|
||||
"""merge_state() on the spool the spec names, as the services read it at start, with
|
||||
the manager's statuses when it is on."""
|
||||
runtime = spec.get("runtime")
|
||||
if not runtime:
|
||||
return spec, {"listeners": [], "users": [], "selfSources": [], "problems": {}}, []
|
||||
state, warnings = load_spool(runtime["spool"])
|
||||
merged, result, more = merge_state(spec, state, check_ports)
|
||||
state, warnings = load_spool(runtime["spool"]) if runtime else ({"users": {}, "listeners": {}}, [])
|
||||
statuses = inbound_policy.statuses(spec, state["users"], now) if spec.get("manager") else None
|
||||
merged, result, more = merge_state(spec, state, check_ports, statuses)
|
||||
if spec.get("manager"):
|
||||
# Users whose subscription URL the manager moved on (proxy_inbound.subscription_token).
|
||||
merged["subscriptionSalts"] = inbound_policy.load_state(spec["manager"]["stateFile"])["subscriptions"]
|
||||
return merged, result, warnings + more
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,543 @@
|
||||
#!/usr/bin/env python3
|
||||
"""A user's subscription in the shape their client asks for (inbounds.manager).
|
||||
|
||||
The manager serves one URL per user. Most clients (v2rayN, v2rayNG, Happ, Hiddify,
|
||||
Streisand, Shadowrocket, NekoBox) read base64 of the share links, which stays the answer to
|
||||
anything not recognized. Clash and mihomo clients get a config of proxies and groups, the
|
||||
sing-box apps a sing-box config, and a browser a page with the subscription's state, a QR
|
||||
code and buttons that open it in an app. `?format=` picks one by hand.
|
||||
|
||||
Everything comes from rendered.json (proxy_inbound.build_inbounds): each link's client
|
||||
outbound is already parsed there, as sing-box JSON where sing-box can dial it and XRay's
|
||||
where only XRay can (XHTTP, ECH). The configs leave those out; the links keep them.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import datetime
|
||||
import hashlib
|
||||
import html
|
||||
import json
|
||||
import re
|
||||
import urllib.parse
|
||||
|
||||
FORMATS = ("base64", "links", "clash", "sing-box", "html")
|
||||
# The configs' own groups and exits, which no server may be named as.
|
||||
RESERVED = {"proxy", "auto", "direct", "block", "reject", "dns"}
|
||||
|
||||
# By the start of the User-Agent: Hiddify says "like ClashMeta v2ray sing-box" further on,
|
||||
# and reads the links best.
|
||||
_CLASH_AGENTS = re.compile(r"(clash|mihomo|stash|flclash|koala-clash)", re.IGNORECASE)
|
||||
_SING_BOX_AGENTS = re.compile(r"(SF[AIMT]/|sing-box)", re.IGNORECASE)
|
||||
|
||||
|
||||
def pick_format(query_format: str | None, user_agent: str, accept: str) -> str:
|
||||
"""The format to answer in: the query's, or one the client is known to read."""
|
||||
if query_format in FORMATS:
|
||||
return query_format
|
||||
if _CLASH_AGENTS.match(user_agent):
|
||||
return "clash"
|
||||
if _SING_BOX_AGENTS.match(user_agent):
|
||||
return "sing-box"
|
||||
if user_agent.startswith("Mozilla/") and "text/html" in accept:
|
||||
return "html"
|
||||
return "base64"
|
||||
|
||||
|
||||
def entries(rendered: dict, user: str) -> list[dict]:
|
||||
"""The user's links as subscriptions carry them: no AmneziaWG configs, which clients
|
||||
reading these do not speak. Each with a name of its own, the listener's tag and variant."""
|
||||
result = []
|
||||
seen: set[str] = set()
|
||||
for link in rendered.get("links") or []:
|
||||
if link.get("user") != user or link.get("config") is not None:
|
||||
continue
|
||||
name = link.get("tag", "proxy") + (f"-{link['variant']}" if link.get("variant") else "")
|
||||
base, index = name, 2
|
||||
if name.lower() in RESERVED:
|
||||
name = f"{base}-{index}"
|
||||
index += 1
|
||||
while name in seen:
|
||||
name, index = f"{base}-{index}", index + 1
|
||||
seen.add(name)
|
||||
result.append({**link, "name": name})
|
||||
return result
|
||||
|
||||
|
||||
# --- sing-box -------------------------------------------------------------------------
|
||||
|
||||
|
||||
def sing_box_outbounds(items: list[dict]) -> list[dict]:
|
||||
"""Outbounds sing-box dials, named for the config: XRay-only ones are left out."""
|
||||
outbounds = []
|
||||
for item in items:
|
||||
outbound = item.get("outbound")
|
||||
if isinstance(outbound, dict) and "type" in outbound:
|
||||
outbounds.append({**outbound, "tag": item["name"]})
|
||||
return outbounds
|
||||
|
||||
|
||||
def sing_box_config(items: list[dict]) -> dict:
|
||||
"""A whole client config for the sing-box apps (1.12 and later): TUN, the user's
|
||||
servers under a selector whose default picks the fastest, private networks direct."""
|
||||
outbounds = sing_box_outbounds(items)
|
||||
names = [o["tag"] for o in outbounds]
|
||||
groups = []
|
||||
if names:
|
||||
groups = [
|
||||
{"type": "selector", "tag": "proxy", "outbounds": ["auto", *names], "default": "auto"},
|
||||
{"type": "urltest", "tag": "auto", "outbounds": names, "interval": "10m"},
|
||||
]
|
||||
return {
|
||||
"log": {"level": "warn"},
|
||||
"dns": {
|
||||
"servers": [
|
||||
{"type": "https", "tag": "remote", "server": "1.1.1.1", "detour": "proxy" if names else "direct"},
|
||||
{"type": "local", "tag": "local"},
|
||||
],
|
||||
"final": "remote",
|
||||
},
|
||||
"inbounds": [
|
||||
{
|
||||
"type": "tun",
|
||||
"tag": "tun-in",
|
||||
"address": ["172.19.0.1/30", "fdfe:dcba:9876::1/126"],
|
||||
"auto_route": True,
|
||||
"strict_route": True,
|
||||
}
|
||||
],
|
||||
"outbounds": [*groups, *outbounds, {"type": "direct", "tag": "direct"}],
|
||||
"route": {
|
||||
"rules": [
|
||||
{"action": "sniff"},
|
||||
{"protocol": "dns", "action": "hijack-dns"},
|
||||
{"ip_is_private": True, "outbound": "direct"},
|
||||
],
|
||||
"final": "proxy" if names else "direct",
|
||||
"auto_detect_interface": True,
|
||||
"default_domain_resolver": "local",
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
# --- Clash and mihomo -----------------------------------------------------------------
|
||||
|
||||
|
||||
def _clash_tls(proxy: dict, tls: dict, sni_key: str) -> None:
|
||||
if not tls.get("enabled"):
|
||||
return
|
||||
proxy["tls"] = True
|
||||
if tls.get("server_name"):
|
||||
proxy[sni_key] = tls["server_name"]
|
||||
if tls.get("insecure"):
|
||||
proxy["skip-cert-verify"] = True
|
||||
if tls.get("alpn"):
|
||||
proxy["alpn"] = list(tls["alpn"])
|
||||
fingerprint = (tls.get("utls") or {}).get("fingerprint")
|
||||
if fingerprint:
|
||||
proxy["client-fingerprint"] = fingerprint
|
||||
reality = tls.get("reality") or {}
|
||||
if reality.get("enabled"):
|
||||
proxy["reality-opts"] = {"public-key": reality.get("public_key", ""), "short-id": reality.get("short_id", "")}
|
||||
proxy.setdefault("client-fingerprint", "chrome")
|
||||
|
||||
|
||||
def _clash_transport(proxy: dict, transport: dict | None) -> bool:
|
||||
"""mihomo's network and its options; False for a transport it lacks."""
|
||||
if not transport:
|
||||
proxy["network"] = "tcp"
|
||||
return True
|
||||
kind = transport.get("type")
|
||||
if kind in ("ws", "httpupgrade"):
|
||||
proxy["network"] = "ws"
|
||||
opts: dict = {"path": transport.get("path") or "/"}
|
||||
host = (transport.get("headers") or {}).get("Host") or transport.get("host")
|
||||
if host:
|
||||
opts["headers"] = {"Host": host}
|
||||
if kind == "httpupgrade":
|
||||
opts["v2ray-http-upgrade"] = True
|
||||
proxy["ws-opts"] = opts
|
||||
elif kind == "grpc":
|
||||
proxy["network"] = "grpc"
|
||||
proxy["grpc-opts"] = {"grpc-service-name": transport.get("service_name", "")}
|
||||
elif kind == "http":
|
||||
proxy["network"] = "h2"
|
||||
proxy["h2-opts"] = {"host": list(transport.get("host") or []), "path": transport.get("path") or "/"}
|
||||
else:
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
def clash_proxy(name: str, outbound: dict) -> dict | None:
|
||||
"""A mihomo proxy from a sing-box outbound; None for what it cannot dial the same way."""
|
||||
kind = outbound.get("type")
|
||||
proxy: dict = {"name": name, "server": outbound.get("server"), "port": outbound.get("server_port")}
|
||||
tls = outbound.get("tls") or {}
|
||||
if kind in ("vless", "vmess"):
|
||||
proxy.update(type=kind, uuid=outbound.get("uuid"), udp=True)
|
||||
if kind == "vless":
|
||||
if outbound.get("flow"):
|
||||
proxy["flow"] = outbound["flow"]
|
||||
if outbound.get("packet_encoding"):
|
||||
proxy["packet-encoding"] = outbound["packet_encoding"]
|
||||
else:
|
||||
proxy.update({"alterId": outbound.get("alter_id", 0), "cipher": outbound.get("security") or "auto"})
|
||||
_clash_tls(proxy, tls, "servername")
|
||||
elif kind == "trojan":
|
||||
proxy.update(type="trojan", password=outbound.get("password"), udp=True)
|
||||
_clash_tls(proxy, tls, "sni")
|
||||
elif kind == "shadowsocks":
|
||||
if outbound.get("plugin"):
|
||||
return None
|
||||
proxy.update(type="ss", cipher=outbound.get("method"), password=outbound.get("password"), udp=True)
|
||||
elif kind == "hysteria2":
|
||||
proxy.update(type="hysteria2", password=outbound.get("password"))
|
||||
if tls.get("server_name"):
|
||||
proxy["sni"] = tls["server_name"]
|
||||
if tls.get("insecure"):
|
||||
proxy["skip-cert-verify"] = True
|
||||
if tls.get("alpn"):
|
||||
proxy["alpn"] = list(tls["alpn"])
|
||||
obfs = outbound.get("obfs") or {}
|
||||
if obfs.get("type"):
|
||||
proxy.update({"obfs": obfs["type"], "obfs-password": obfs.get("password", "")})
|
||||
if outbound.get("server_ports"):
|
||||
proxy["ports"] = ",".join(p.replace(":", "-") for p in outbound["server_ports"])
|
||||
return proxy
|
||||
elif kind in ("socks", "http"):
|
||||
proxy["type"] = "socks5" if kind == "socks" else "http"
|
||||
for key in ("username", "password"):
|
||||
if outbound.get(key):
|
||||
proxy[key] = outbound[key]
|
||||
_clash_tls(proxy, tls, "sni")
|
||||
return proxy
|
||||
else:
|
||||
return None
|
||||
if kind in ("vless", "vmess", "trojan") and not _clash_transport(proxy, outbound.get("transport")):
|
||||
return None
|
||||
return proxy
|
||||
|
||||
|
||||
def clash_config(items: list[dict]) -> dict:
|
||||
"""A mihomo config: the user's servers, a group that picks the fastest and one to choose
|
||||
by hand, private networks direct."""
|
||||
proxies = []
|
||||
for item in items:
|
||||
outbound = item.get("outbound")
|
||||
if isinstance(outbound, dict) and "type" in outbound:
|
||||
proxy = clash_proxy(item["name"], outbound)
|
||||
if proxy is not None:
|
||||
proxies.append(proxy)
|
||||
names = [p["name"] for p in proxies]
|
||||
groups = [
|
||||
{"name": "PROXY", "type": "select", "proxies": ["auto", *names] if names else ["DIRECT"]},
|
||||
{"name": "auto", "type": "url-test", "proxies": names or ["DIRECT"],
|
||||
"url": "https://www.gstatic.com/generate_204", "interval": 600},
|
||||
]
|
||||
return {
|
||||
"mixed-port": 7890,
|
||||
"mode": "rule",
|
||||
"log-level": "warning",
|
||||
"proxies": proxies,
|
||||
"proxy-groups": groups,
|
||||
"rules": [
|
||||
"IP-CIDR,10.0.0.0/8,DIRECT,no-resolve",
|
||||
"IP-CIDR,172.16.0.0/12,DIRECT,no-resolve",
|
||||
"IP-CIDR,192.168.0.0/16,DIRECT,no-resolve",
|
||||
"IP-CIDR,127.0.0.0/8,DIRECT,no-resolve",
|
||||
"MATCH,PROXY",
|
||||
],
|
||||
}
|
||||
|
||||
|
||||
# --- the page -------------------------------------------------------------------------
|
||||
|
||||
TEXT = {
|
||||
"en": {
|
||||
"active": "Active", "hold": "Starts with the first connection", "off": "Switched off",
|
||||
"disabled": "switched off", "expired": "expired", "traffic": "out of traffic",
|
||||
"used": "Traffic", "of": "of", "unlimited": "unlimited", "renews": "renews",
|
||||
"expires": "Expires", "never": "never", "term": "for {} from the first connection",
|
||||
"sub": "Subscription", "copy": "Copy", "copied": "Copied", "open": "Add to an app",
|
||||
"more": "Other apps", "links": "Connections", "support": "Support", "user": "User",
|
||||
"hint": "Keep this page to yourself: its address is your access.",
|
||||
},
|
||||
"ru": {
|
||||
"active": "Активна", "hold": "Начнётся с первого подключения", "off": "Отключена",
|
||||
"disabled": "отключена", "expired": "срок истёк", "traffic": "трафик исчерпан",
|
||||
"used": "Трафик", "of": "из", "unlimited": "без лимита", "renews": "обновится",
|
||||
"expires": "Действует до", "never": "бессрочно", "term": "{} с первого подключения",
|
||||
"sub": "Подписка", "copy": "Копировать", "copied": "Скопировано", "open": "Добавить в приложение",
|
||||
"more": "Другие приложения", "links": "Подключения", "support": "Поддержка", "user": "Пользователь",
|
||||
"hint": "Не показывайте эту страницу никому: её адрес и есть ваш доступ.",
|
||||
},
|
||||
}
|
||||
|
||||
ANDROID, IOS, MACOS, WINDOWS, LINUX = "android", "ios", "macos", "windows", "linux"
|
||||
EVERYWHERE = frozenset({ANDROID, IOS, MACOS, WINDOWS, LINUX})
|
||||
|
||||
# Each opens the subscription in that app, on the systems the app takes the link on; {url} is
|
||||
# quoted, {raw} is not. clash:// is taken by Clash Meta, FlClash, Clash Verge Rev, Clash Party
|
||||
# and Stash; v2rayN and Throne take no link, only the URL pasted.
|
||||
APPS = [
|
||||
("Happ", "happ://add/{raw}", EVERYWHERE),
|
||||
("Hiddify", "hiddify://import/{raw}#{name}", EVERYWHERE),
|
||||
("v2rayNG", "v2rayng://install-config?url={url}#{name}", {ANDROID}),
|
||||
("Streisand", "streisand://import/{raw}#{name}", {IOS, MACOS}),
|
||||
("Karing", "karing://install-config?url={url}&name={name}", {ANDROID, IOS, MACOS, WINDOWS}),
|
||||
("sing-box", "sing-box://import-remote-profile?url={url}#{name}", {ANDROID, IOS, MACOS}),
|
||||
("Clash / mihomo", "clash://install-config?url={url}&name={name}", EVERYWHERE),
|
||||
# proxy-suite-gui (gui.enable): asks before it runs `proxy subs add`.
|
||||
("Proxy Suite", "proxy-suite://install-config?url={url}&name={name}", {LINUX}),
|
||||
]
|
||||
|
||||
# In this order: Android's User-Agent says Linux too, and a Chromebook runs Android apps.
|
||||
_PLATFORMS = [
|
||||
(ANDROID, re.compile(r"Android|CrOS")),
|
||||
(IOS, re.compile(r"iPhone|iPad|iPod")),
|
||||
(WINDOWS, re.compile(r"Windows")),
|
||||
(MACOS, re.compile(r"Macintosh|Mac OS X")),
|
||||
(LINUX, re.compile(r"Linux|X11")),
|
||||
]
|
||||
|
||||
|
||||
def platform(user_agent: str) -> str | None:
|
||||
"""The system a browser runs on, as APPS names them; None when it does not say."""
|
||||
return next((name for name, pattern in _PLATFORMS if pattern.search(user_agent or "")), None)
|
||||
|
||||
|
||||
def language(accept_language: str) -> str:
|
||||
for part in (accept_language or "").split(","):
|
||||
tag = part.split(";")[0].strip().lower()
|
||||
if tag.startswith("ru"):
|
||||
return "ru"
|
||||
if tag.startswith("en"):
|
||||
return "en"
|
||||
return "en"
|
||||
|
||||
|
||||
def human_bytes(value: int) -> str:
|
||||
size = float(value)
|
||||
for unit in ("B", "KiB", "MiB", "GiB", "TiB"):
|
||||
if size < 1024 or unit == "TiB":
|
||||
return f"{size:.0f} {unit}" if unit == "B" else f"{size:.1f} {unit}"
|
||||
size /= 1024
|
||||
return f"{value} B"
|
||||
|
||||
|
||||
def human_span(seconds: int) -> str:
|
||||
for unit, size in (("w", 604800), ("d", 86400), ("h", 3600), ("m", 60)):
|
||||
if seconds % size == 0:
|
||||
return f"{seconds // size}{unit}"
|
||||
return f"{seconds}s"
|
||||
|
||||
|
||||
_STYLE = """
|
||||
:root{--bg:#f6f7f9;--card:#fff;--fg:#1c1f24;--muted:#646b75;--line:#e1e4e8;--accent:#2563eb;--ok:#15803d;--warn:#b45309;--bad:#b91c1c}
|
||||
@media (prefers-color-scheme:dark){:root{--bg:#111316;--card:#1b1e23;--fg:#e8eaed;--muted:#9aa1ab;--line:#2c3036;--accent:#6ea0ff;--ok:#4ade80;--warn:#fbbf24;--bad:#f87171}}
|
||||
*{box-sizing:border-box}body{margin:0;background:var(--bg);color:var(--fg);font:16px/1.5 system-ui,-apple-system,"Segoe UI",Roboto,sans-serif}
|
||||
main{max-width:560px;margin:0 auto;padding:24px 16px 48px}h1{font-size:22px;margin:0 0 4px}
|
||||
.card{background:var(--card);border:1px solid var(--line);border-radius:12px;padding:16px;margin-top:16px}
|
||||
.status{font-weight:600}.ok{color:var(--ok)}.warn{color:var(--warn)}.bad{color:var(--bad)}
|
||||
.row{display:flex;justify-content:space-between;gap:12px;padding:6px 0;border-bottom:1px solid var(--line)}.row:last-child{border:0}
|
||||
.muted{color:var(--muted);font-size:14px}.bar{display:block;width:100%;height:6px;border-radius:3px;overflow:hidden;margin-top:6px}
|
||||
.bar .track{fill:var(--line)}.bar .fill{fill:var(--accent)}
|
||||
.qr{display:flex;justify-content:center;margin:8px 0}.qr svg{width:220px;height:220px;background:#fff;border-radius:8px}
|
||||
code{display:block;word-break:break-all;font-size:13px;background:var(--bg);border:1px solid var(--line);border-radius:8px;padding:8px;margin:8px 0}
|
||||
button,a.app{font:inherit;font-size:14px;border:1px solid var(--line);background:var(--bg);color:var(--fg);border-radius:8px;padding:6px 12px;cursor:pointer;text-decoration:none;display:inline-block;margin:4px 4px 0 0}
|
||||
button:hover,a.app:hover{border-color:var(--accent)}
|
||||
summary{cursor:pointer;color:var(--muted);font-size:14px;margin-top:12px}h2{font-size:16px;margin:0 0 8px}h2.next{margin-top:16px}
|
||||
"""
|
||||
|
||||
# The QR code is drawn by the browser: a request costs the server no encoder run, and the page
|
||||
# takes no image from elsewhere, for the people opening it may not reach much. qrMatrix(text):
|
||||
# the modules, rows of booleans, of the smallest QR code (byte mode, error correction M) that
|
||||
# holds text, mask chosen by the standard's penalty; null past version 40. A test decodes its
|
||||
# output with zbar.
|
||||
_QR_SCRIPT = """
|
||||
function qrMatrix(text){
|
||||
var ECC=[0,10,16,26,18,24,16,18,22,22,26,30,22,22,24,24,28,28,26,26,26,26,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28],
|
||||
BLK=[0,1,1,1,2,2,4,4,4,5,5,5,8,9,9,10,10,11,13,14,16,17,17,18,20,21,23,25,26,28,29,31,33,35,37,38,40,43,45,47,49];
|
||||
var bytes=new TextEncoder().encode(text),ver,size,raw,i,j,x,y;
|
||||
function rawModules(v){var r=(16*v+128)*v+64;if(v>=2){var n=Math.floor(v/7)+2;r-=(25*n-10)*n-55;if(v>=7)r-=36}return r}
|
||||
for(ver=1;;ver++){if(ver>40)return null;raw=Math.floor(rawModules(ver)/8);if(4+(ver<10?8:16)+8*bytes.length<=(raw-ECC[ver]*BLK[ver])*8)break}
|
||||
size=ver*4+17;var cap=raw-ECC[ver]*BLK[ver],bits=[];
|
||||
function put(v,n){for(var k=n-1;k>=0;k--)bits.push(v>>>k&1)}
|
||||
put(4,4);put(bytes.length,ver<10?8:16);for(i=0;i<bytes.length;i++)put(bytes[i],8);
|
||||
put(0,Math.min(4,cap*8-bits.length));put(0,(8-bits.length%8)%8);
|
||||
for(var pad=0xEC;bits.length<cap*8;pad^=0xEC^0x11)put(pad,8);
|
||||
var data=[];for(i=0;i<bits.length;i+=8){for(x=0,j=0;j<8;j++)x=x<<1|bits[i+j];data.push(x)}
|
||||
function mul(a,b){for(var z=0,k=7;k>=0;k--){z=(z<<1)^((z>>>7)*0x11D);z^=(b>>>k&1)*a}return z}
|
||||
var deg=ECC[ver],gen=[],root=1;for(i=0;i<deg;i++)gen.push(0);gen[deg-1]=1;
|
||||
for(i=0;i<deg;i++){for(j=0;j<deg;j++){gen[j]=mul(gen[j],root);if(j+1<deg)gen[j]^=gen[j+1]}root=mul(root,2)}
|
||||
var nb=BLK[ver],nshort=nb-raw%nb,slen=Math.floor(raw/nb),blocks=[],eccs=[],at=0;
|
||||
for(i=0;i<nb;i++){var d=data.slice(at,at+=slen-deg+(i<nshort?0:1)),rem=gen.map(function(){return 0});
|
||||
for(j=0;j<d.length;j++){var f=d[j]^rem.shift();rem.push(0);for(var k=0;k<deg;k++)rem[k]^=mul(gen[k],f)}
|
||||
blocks.push(d);eccs.push(rem)}
|
||||
var words=[];for(i=0;i<=slen-deg;i++)for(j=0;j<nb;j++)if(i<blocks[j].length)words.push(blocks[j][i]);
|
||||
for(i=0;i<deg;i++)for(j=0;j<nb;j++)words.push(eccs[j][i]);
|
||||
var m=[],fn=[];for(y=0;y<size;y++){m.push([]);fn.push([]);for(x=0;x<size;x++){m[y].push(false);fn[y].push(false)}}
|
||||
function set(x,y,dark){m[y][x]=dark;fn[y][x]=true}
|
||||
for(i=0;i<size;i++){set(6,i,i%2==0);set(i,6,i%2==0)}
|
||||
[[3,3],[size-4,3],[3,size-4]].forEach(function(c){for(var dy=-4;dy<=4;dy++)for(var dx=-4;dx<=4;dx++){
|
||||
var q=Math.max(Math.abs(dx),Math.abs(dy)),xx=c[0]+dx,yy=c[1]+dy;if(xx>=0&&xx<size&&yy>=0&&yy<size)set(xx,yy,q!=2&&q!=4)}});
|
||||
var pos=[];if(ver>1){var na=Math.floor(ver/7)+2,step=Math.floor((ver*8+na*3+5)/(na*4-4))*2;pos=[6];for(x=size-7;pos.length<na;x-=step)pos.splice(1,0,x)}
|
||||
for(i=0;i<pos.length;i++)for(j=0;j<pos.length;j++){if(i==0&&j==0||i==0&&j==pos.length-1||i==pos.length-1&&j==0)continue;
|
||||
for(var ay=-2;ay<=2;ay++)for(var ax=-2;ax<=2;ax++)set(pos[i]+ax,pos[j]+ay,Math.max(Math.abs(ax),Math.abs(ay))!=1)}
|
||||
function format(mask){var v=mask,r=v;for(var k=0;k<10;k++)r=(r<<1)^((r>>>9)*0x537);v=(v<<10|r)^0x5412;
|
||||
function b(k){return (v>>>k&1)==1}
|
||||
for(k=0;k<=5;k++)set(8,k,b(k));set(8,7,b(6));set(8,8,b(7));set(7,8,b(8));for(k=9;k<15;k++)set(14-k,8,b(k));
|
||||
for(k=0;k<8;k++)set(size-1-k,8,b(k));for(k=8;k<15;k++)set(8,size-15+k,b(k));set(8,size-8,true)}
|
||||
format(0);
|
||||
if(ver>=7){var r=ver;for(i=0;i<12;i++)r=(r<<1)^((r>>>11)*0x1F25);var vb=ver<<12|r;
|
||||
for(i=0;i<18;i++){var bit=(vb>>>i&1)==1,a=size-11+i%3,c=Math.floor(i/3);set(a,c,bit);set(c,a,bit)}}
|
||||
for(i=0,x=size-1;x>=1;x-=2){if(x==6)x=5;for(var v=0;v<size;v++)for(j=0;j<2;j++){
|
||||
var xx=x-j;y=(x+1&2)==0?size-1-v:v;if(!fn[y][xx]&&i<words.length*8){m[y][xx]=(words[i>>>3]>>>7-(i&7)&1)==1;i++}}}
|
||||
var masks=[function(x,y){return (x+y)%2==0},function(x,y){return y%2==0},function(x,y){return x%3==0},
|
||||
function(x,y){return (x+y)%3==0},function(x,y){return (Math.floor(x/3)+Math.floor(y/2))%2==0},
|
||||
function(x,y){return x*y%2+x*y%3==0},function(x,y){return (x*y%2+x*y%3)%2==0},function(x,y){return ((x+y)%2+x*y%3)%2==0}];
|
||||
function flip(k){for(var y=0;y<size;y++)for(var x=0;x<size;x++)if(!fn[y][x]&&masks[k](x,y))m[y][x]=!m[y][x]}
|
||||
function line(get){var p=0,dark=0,run=0,last=null,seq='';for(var k=0;k<size;k++){var d=get(k);dark+=d;seq+=d?'1':'0';
|
||||
if(d===last)run++;else{if(run>=5)p+=run-2;run=1;last=d}}if(run>=5)p+=run-2;
|
||||
for(k=seq.indexOf('1011101');k>=0;k=seq.indexOf('1011101',k+1))
|
||||
if(seq.substr(k-4,4)=='0000'||seq.substr(k+7,4)=='0000'||k<4||k+11>size)p+=40;return p}
|
||||
function score(){var p=0,dark=0;for(var a=0;a<size;a++){p+=line(function(k){return m[a][k]?1:0});p+=line(function(k){return m[k][a]?1:0})}
|
||||
for(var y=0;y<size;y++)for(var x=0;x<size;x++){dark+=m[y][x];if(x<size-1&&y<size-1&&m[y][x]==m[y][x+1]&&m[y][x]==m[y+1][x]&&m[y][x]==m[y+1][x+1])p+=3}
|
||||
return p+10*Math.max(0,Math.ceil(Math.abs(dark*20-size*size*10)/(size*size))-1)}
|
||||
var best=0,low=Infinity;for(k=0;k<8;k++){flip(k);format(k);var s=score();if(s<low){low=s;best=k}flip(k)}
|
||||
flip(best);format(best);return m}
|
||||
"""
|
||||
|
||||
_SCRIPT = _QR_SCRIPT + """
|
||||
document.querySelectorAll('[data-qr]').forEach(function(e){var m=qrMatrix(e.getAttribute('data-qr'));if(!m)return;
|
||||
var n=m.length+8,ns='http://www.w3.org/2000/svg',s=document.createElementNS(ns,'svg'),p=document.createElementNS(ns,'path'),d='';
|
||||
for(var y=0;y<m.length;y++)for(var x=0;x<m.length;x++)if(m[y][x])d+='M'+(x+4)+' '+(y+4)+'h1v1h-1z';
|
||||
s.setAttribute('viewBox','0 0 '+n+' '+n);s.setAttribute('shape-rendering','crispEdges');p.setAttribute('d',d);p.setAttribute('fill','#000');
|
||||
s.appendChild(p);e.appendChild(s)});
|
||||
document.querySelectorAll('button[data-copy]').forEach(function(b){b.addEventListener('click',function(){
|
||||
var t=b.getAttribute('data-copy'),l=b.textContent;function done(){b.textContent=b.getAttribute('data-done');setTimeout(function(){b.textContent=l},1500)}
|
||||
if(navigator.clipboard){navigator.clipboard.writeText(t).then(done)}else{var a=document.createElement('textarea');a.value=t;document.body.appendChild(a);a.select();document.execCommand('copy');a.remove();done()}})});
|
||||
"""
|
||||
|
||||
|
||||
def _csp_hash(source: str) -> str:
|
||||
return "'sha256-" + base64.b64encode(hashlib.sha256(source.encode("utf-8")).digest()).decode("ascii") + "'"
|
||||
|
||||
|
||||
# Every answer: the address is the secret, not to be sent on, indexed, sniffed into something
|
||||
# else or read by other sites' pages.
|
||||
HEADERS = {
|
||||
"Cache-Control": "no-store",
|
||||
"Referrer-Policy": "no-referrer",
|
||||
"X-Robots-Tag": "noindex, nofollow",
|
||||
"X-Content-Type-Options": "nosniff",
|
||||
"Cross-Origin-Resource-Policy": "same-origin",
|
||||
}
|
||||
# The page, besides: nothing runs or styles it but its own script and stylesheet, by their
|
||||
# hashes; no style attribute, no frame, no form, no other origin.
|
||||
PAGE_HEADERS = {
|
||||
"Content-Security-Policy": f"default-src 'none'; script-src {_csp_hash(_SCRIPT)}; style-src {_csp_hash(_STYLE)}; "
|
||||
"base-uri 'none'; form-action 'none'; frame-ancestors 'none'; "
|
||||
"require-trusted-types-for 'script'",
|
||||
"Cross-Origin-Opener-Policy": "same-origin",
|
||||
}
|
||||
|
||||
|
||||
def html_page(row: dict, items: list[dict], sub_url: str, title: str, settings: dict, lang: str,
|
||||
user_agent: str = "") -> str:
|
||||
"""The page a browser gets: the state of the subscription, its QR code and links. The apps
|
||||
for the browser's system come first, the rest folded away: the page may be open on a laptop
|
||||
to set up a phone."""
|
||||
t = TEXT[lang]
|
||||
esc = html.escape
|
||||
if not row.get("active"):
|
||||
state = f'<span class="status bad">{esc(t["off"])}</span>'
|
||||
reasons = ", ".join(t.get(r, r) for r in row.get("reasons") or [])
|
||||
if reasons:
|
||||
state += f' <span class="muted">({esc(reasons)})</span>'
|
||||
elif row.get("onHold"):
|
||||
state = f'<span class="status warn">{esc(t["hold"])}</span>'
|
||||
else:
|
||||
state = f'<span class="status ok">{esc(t["active"])}</span>'
|
||||
traffic = row.get("traffic") or {}
|
||||
used, limit = traffic.get("used") or 0, traffic.get("limit")
|
||||
usage = esc(human_bytes(used)) + (f' {esc(t["of"])} {esc(human_bytes(limit))}' if limit else f' <span class="muted">({esc(t["unlimited"])})</span>')
|
||||
if limit and traffic.get("periodEnd"):
|
||||
renew = datetime.datetime.fromtimestamp(traffic["periodEnd"]).strftime("%Y-%m-%d")
|
||||
usage += f' <span class="muted">· {esc(t["renews"])} {esc(renew)}</span>'
|
||||
# An SVG's width attribute, not a style one: the CSP lets no style attribute through.
|
||||
bar = (f'<svg class="bar" viewBox="0 0 100 1" preserveAspectRatio="none"><rect class="track" width="100" height="1"/>'
|
||||
f'<rect class="fill" width="{min(100, int(used * 100 / limit))}" height="1"/></svg>') if limit else ""
|
||||
if row.get("onHold"):
|
||||
expires = esc(t["term"].format(human_span((row.get("policy") or {}).get("expiresAfter") or 0)))
|
||||
elif row.get("expiresAt"):
|
||||
expires = esc(datetime.datetime.fromtimestamp(row["expiresAt"]).strftime("%Y-%m-%d %H:%M"))
|
||||
else:
|
||||
expires = esc(t["never"])
|
||||
name = urllib.parse.quote(title, safe="")
|
||||
system = platform(user_agent)
|
||||
buttons = {
|
||||
label: f'<a class="app" href="{esc(pattern.format(url=urllib.parse.quote(sub_url, safe=""), raw=sub_url, name=name))}">{esc(label)}</a>'
|
||||
for label, pattern, _ in APPS
|
||||
}
|
||||
mine = [label for label, _, systems in APPS if system in systems]
|
||||
others = [label for label, _, _ in APPS if label not in mine]
|
||||
if mine:
|
||||
apps = "".join(buttons[label] for label in mine)
|
||||
if others:
|
||||
apps += f'<details><summary>{esc(t["more"])}</summary>{"".join(buttons[label] for label in others)}</details>'
|
||||
else:
|
||||
apps = "".join(buttons.values())
|
||||
links = "".join(
|
||||
f'<div class="row"><span>{esc(item["name"])}</span>'
|
||||
f'<button data-copy="{esc(item["link"])}" data-done="{esc(t["copied"])}">{esc(t["copy"])}</button></div>'
|
||||
for item in items
|
||||
)
|
||||
# Whose it is, unless the title (profileTitle's {user}) says so already.
|
||||
user = ""
|
||||
if row.get("name") and row["name"] not in title:
|
||||
user = f'<div class="muted">{esc(t["user"])}: {esc(row["name"])}</div>'
|
||||
support = ""
|
||||
if settings.get("supportUrl"):
|
||||
support = f'<p class="muted"><a href="{esc(settings["supportUrl"])}">{esc(t["support"])}</a></p>'
|
||||
return f"""<!doctype html>
|
||||
<html lang="{lang}"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
|
||||
<meta name="robots" content="noindex,nofollow"><meta name="referrer" content="no-referrer">
|
||||
<title>{esc(title)}</title><style>{_STYLE}</style></head>
|
||||
<body><main>
|
||||
<h1>{esc(title)}</h1>{user}<div>{state}</div>
|
||||
<div class="card">
|
||||
<div class="row"><span>{esc(t["used"])}</span><span>{usage}</span></div>{bar}
|
||||
<div class="row"><span>{esc(t["expires"])}</span><span>{expires}</span></div>
|
||||
</div>
|
||||
<div class="card"><h2>{esc(t["sub"])}</h2>
|
||||
<div class="qr" data-qr="{esc(sub_url)}"></div>
|
||||
<code>{esc(sub_url)}</code>
|
||||
<button data-copy="{esc(sub_url)}" data-done="{esc(t["copied"])}">{esc(t["copy"])}</button>
|
||||
<h2 class="next">{esc(t["open"])}</h2>{apps}
|
||||
</div>
|
||||
{f'<div class="card"><h2>{esc(t["links"])}</h2>{links}</div>' if links else ''}
|
||||
<p class="muted">{esc(t["hint"])}</p>{support}
|
||||
</main><script>{_SCRIPT}</script></body></html>
|
||||
"""
|
||||
|
||||
|
||||
# --- the answer -----------------------------------------------------------------------
|
||||
|
||||
|
||||
def render(fmt: str, rendered: dict, user: str, body_b64: str, row: dict | None, sub_url: str, title: str,
|
||||
settings: dict, accept_language: str = "", user_agent: str = "") -> tuple[bytes, str]:
|
||||
"""(body, Content-Type) of a subscription in one format."""
|
||||
items = entries(rendered, user)
|
||||
if fmt == "links":
|
||||
return base64.b64decode(body_b64) + b"\n", "text/plain; charset=utf-8"
|
||||
if fmt == "sing-box":
|
||||
return (json.dumps(sing_box_config(items), indent=2) + "\n").encode("utf-8"), "application/json; charset=utf-8"
|
||||
if fmt == "clash":
|
||||
# JSON is YAML: no YAML library needed, and mihomo reads it as such.
|
||||
return (json.dumps(clash_config(items), indent=2, ensure_ascii=False) + "\n").encode("utf-8"), "text/yaml; charset=utf-8"
|
||||
if fmt == "html" and row is not None:
|
||||
page = html_page(row, items, sub_url, title, settings, language(accept_language), user_agent)
|
||||
return page.encode("utf-8"), "text/html; charset=utf-8"
|
||||
return body_b64.encode("ascii"), "text/plain; charset=utf-8"
|
||||
+48
-17
@@ -21,6 +21,8 @@ import sys
|
||||
import time
|
||||
|
||||
TIMEOUT = 4.0
|
||||
# A UDP query is sent again after this long without an answer (ask_udp).
|
||||
RESEND_AFTER = 1.5
|
||||
MAX_MESSAGE = 65535
|
||||
|
||||
# --log (debug.perAppDns): a line per lookup sent on, to the journal.
|
||||
@@ -48,7 +50,7 @@ def question(query: bytes) -> str:
|
||||
return f"{'.'.join(labels) or '.'} {QTYPES.get(qtype, qtype)}"
|
||||
|
||||
|
||||
def log_lookup(port: int, proto: str, query: bytes, reply: bytes | None, started: float):
|
||||
def log_lookup(port: int, proto: str, query: bytes, reply: bytes | None, started: float, asked: int = 1):
|
||||
if not LOG:
|
||||
return
|
||||
if reply is None:
|
||||
@@ -58,7 +60,8 @@ def log_lookup(port: int, proto: str, query: bytes, reply: bytes | None, started
|
||||
else:
|
||||
outcome = RCODES.get(reply[3] & 0x0F, f"rcode {reply[3] & 0x0F}")
|
||||
took = (time.monotonic() - started) * 1000
|
||||
print(f"per-app-dns: :{port} {proto} {question(query)}: {outcome} in {took:.0f} ms", flush=True)
|
||||
again = f", asked {asked} times" if asked > 1 else ""
|
||||
print(f"per-app-dns: :{port} {proto} {question(query)}: {outcome} in {took:.0f} ms{again}", flush=True)
|
||||
|
||||
|
||||
# The source address of the queries sent on (--bind): on a TProxy route's local route the
|
||||
@@ -80,23 +83,51 @@ def upstream_socket(server: str, kind: int, mark: int) -> socket.socket:
|
||||
return sock
|
||||
|
||||
|
||||
async def ask_udp(query: bytes, servers: list[str], mark: int) -> bytes | None:
|
||||
"""The first answer any server gives, in order; None when none does."""
|
||||
async def ask_udp_once(query: bytes, server: str, mark: int) -> bytes:
|
||||
loop = asyncio.get_running_loop()
|
||||
sock = upstream_socket(server, socket.SOCK_DGRAM, mark)
|
||||
try:
|
||||
await loop.sock_connect(sock, (server, 53))
|
||||
await loop.sock_sendall(sock, query)
|
||||
return await loop.sock_recv(sock, MAX_MESSAGE)
|
||||
finally:
|
||||
sock.close()
|
||||
|
||||
|
||||
async def ask_udp(query: bytes, servers: list[str], mark: int) -> tuple[bytes | None, int]:
|
||||
"""(the first answer any server gives, in order, or None; how many times it was asked).
|
||||
|
||||
Unanswered after RESEND_AFTER, a query goes again from a new socket, the first still
|
||||
waiting: through a proxy one is often lost (a tunnel that stalled, a session it was
|
||||
opening), and the app asks again only after its own timeout, glibc's 5 s. Silence, not
|
||||
SERVFAIL, when none answers: on SERVFAIL glibc gives up, on silence it retries.
|
||||
"""
|
||||
loop = asyncio.get_running_loop()
|
||||
asked = 0
|
||||
for server in servers:
|
||||
attempts = []
|
||||
deadline = loop.time() + TIMEOUT
|
||||
# Set as each attempt goes out; the first goes out at once.
|
||||
resend_at = loop.time()
|
||||
try:
|
||||
sock = upstream_socket(server, socket.SOCK_DGRAM, mark)
|
||||
except OSError:
|
||||
continue
|
||||
try:
|
||||
await loop.sock_connect(sock, (server, 53))
|
||||
await loop.sock_sendall(sock, query)
|
||||
return await asyncio.wait_for(loop.sock_recv(sock, MAX_MESSAGE), TIMEOUT)
|
||||
except (OSError, asyncio.TimeoutError):
|
||||
continue
|
||||
while loop.time() < deadline:
|
||||
pending = [a for a in attempts if not a.done()]
|
||||
if not pending and len(attempts) == 2:
|
||||
break
|
||||
if not pending or (len(attempts) == 1 and loop.time() >= resend_at):
|
||||
attempts.append(asyncio.ensure_future(ask_udp_once(query, server, mark)))
|
||||
asked += 1
|
||||
resend_at = loop.time() + RESEND_AFTER
|
||||
pending = [a for a in attempts if not a.done()]
|
||||
wake = min(deadline, resend_at) if len(attempts) == 1 else deadline
|
||||
done, _ = await asyncio.wait(pending, timeout=max(0, wake - loop.time()), return_when=asyncio.FIRST_COMPLETED)
|
||||
for attempt in done:
|
||||
if attempt.exception() is None:
|
||||
return attempt.result(), asked
|
||||
finally:
|
||||
sock.close()
|
||||
return None
|
||||
for attempt in attempts:
|
||||
attempt.cancel()
|
||||
return None, asked
|
||||
|
||||
|
||||
class UdpListener(asyncio.DatagramProtocol):
|
||||
@@ -114,8 +145,8 @@ class UdpListener(asyncio.DatagramProtocol):
|
||||
|
||||
async def answer(self, query, addr):
|
||||
started = time.monotonic()
|
||||
reply = await ask_udp(query, self.servers, self.mark)
|
||||
log_lookup(self.port, "udp", query, reply, started)
|
||||
reply, asked = await ask_udp(query, self.servers, self.mark)
|
||||
log_lookup(self.port, "udp", query, reply, started, asked)
|
||||
if reply is not None and self.transport is not None:
|
||||
self.transport.sendto(reply, addr)
|
||||
|
||||
|
||||
@@ -10,6 +10,7 @@ without changing the spec or the link generator.
|
||||
|
||||
import base64
|
||||
import hashlib
|
||||
import hmac
|
||||
import json
|
||||
import os
|
||||
import secrets
|
||||
@@ -73,7 +74,11 @@ def _salamander(listener: dict) -> str | None:
|
||||
return _resolve(
|
||||
salamander.get("password"), salamander.get("passwordFile"), "salamander password", listener["tag"]
|
||||
)
|
||||
path = listener["salamanderStateFile"]
|
||||
return _kept_secret(listener["salamanderStateFile"], lambda: secrets.token_urlsafe(24))
|
||||
|
||||
|
||||
def _kept_secret(path: str, generate) -> str:
|
||||
"""The secret kept in path, or one generated now and kept there for the next start."""
|
||||
try:
|
||||
stored = _read_secret(path)
|
||||
except FileNotFoundError:
|
||||
@@ -81,7 +86,7 @@ def _salamander(listener: dict) -> str | None:
|
||||
if stored:
|
||||
return stored
|
||||
os.makedirs(os.path.dirname(path), mode=0o700, exist_ok=True)
|
||||
generated = secrets.token_urlsafe(24)
|
||||
generated = generate()
|
||||
fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
|
||||
with os.fdopen(fd, "w", encoding="utf-8") as handle:
|
||||
handle.write(generated + "\n")
|
||||
@@ -100,8 +105,13 @@ def _share_port(listener: dict) -> int:
|
||||
|
||||
|
||||
def _clients(listener: dict, tag: str) -> list[dict]:
|
||||
"""The users XRay accepts: those the manager has switched off are left out (their links
|
||||
stay), and a speed-limited one carries its slot as its level, which the patched XRay
|
||||
marks its sockets with (pkgs/patches/xray-user-level-mark.patch)."""
|
||||
clients = []
|
||||
for index, user in enumerate(listener["users"]):
|
||||
if user.get("active") is False:
|
||||
continue
|
||||
secret = _user_secret(user, listener["type"], tag)
|
||||
email = user.get("name") or f"{tag}-{index}"
|
||||
if listener["type"] in UUID_TYPES:
|
||||
@@ -112,6 +122,8 @@ def _clients(listener: dict, tag: str) -> list[dict]:
|
||||
client = {"auth": secret, "email": email}
|
||||
else:
|
||||
client = {"password": secret, "email": email}
|
||||
if user.get("level"):
|
||||
client["level"] = user["level"]
|
||||
clients.append(client)
|
||||
return clients
|
||||
|
||||
@@ -119,6 +131,8 @@ def _clients(listener: dict, tag: str) -> list[dict]:
|
||||
def _accounts(listener: dict, tag: str) -> list[dict]:
|
||||
accounts = []
|
||||
for index, user in enumerate(listener["users"]):
|
||||
if user.get("active") is False:
|
||||
continue
|
||||
secret = _user_secret(user, listener["type"], tag)
|
||||
accounts.append({"user": user.get("name") or f"{tag}-{index}", "pass": secret})
|
||||
return accounts
|
||||
@@ -226,6 +240,8 @@ def render_xray_inbound(listener: dict) -> dict:
|
||||
if len(users) == 1:
|
||||
settings["password"] = _user_secret(users[0], listener_type, tag)
|
||||
settings["email"] = users[0].get("name") or f"{tag}-0"
|
||||
if users[0].get("level"):
|
||||
settings["level"] = users[0]["level"]
|
||||
keys = [(settings["email"], settings["password"])]
|
||||
else:
|
||||
# Multi-user is 2022-blake3-aes only: the server key, then one key per user.
|
||||
@@ -558,15 +574,33 @@ def client_outbound(link: str, tag: str) -> dict | None:
|
||||
return None
|
||||
|
||||
|
||||
def subscription_token(name: str, secrets: list[str]) -> str:
|
||||
def subscription_token(name: str, secrets: list[str], key: str | None = None, salt: str = "") -> str:
|
||||
"""Name of a user's subscription file, and so the secret part of its URL.
|
||||
|
||||
Derived from the user's own credentials rather than stored: there is no
|
||||
second secret to manage, it stays put for as long as they do, and rotating
|
||||
the user's uuid rotates the URL with it.
|
||||
Derived from the user's own credentials rather than stored: it stays put for
|
||||
as long as they do, and rotating the user's uuid rotates the URL with it.
|
||||
key (inbounds.subscriptions.keyFile, or the one generated) makes it an HMAC under
|
||||
a secret only this server holds: whoever learns one of a user's links cannot work
|
||||
the URL out from it. salt (the manager's, `proxy-ctl inbounds users rotate-sub`) moves one
|
||||
user's URL on without new credentials. Neither: the plain hash of before.
|
||||
"""
|
||||
material = "\n".join(["proxy-suite-subscription", name, *sorted(set(secrets))])
|
||||
return hashlib.sha256(material.encode("utf-8")).hexdigest()[:32]
|
||||
material = "\n".join(["proxy-suite-subscription", name, *sorted(set(secrets)), *([salt] if salt else [])])
|
||||
if key is None:
|
||||
return hashlib.sha256(material.encode("utf-8")).hexdigest()[:32]
|
||||
return hmac.new(key.encode("utf-8"), material.encode("utf-8"), hashlib.sha256).hexdigest()[:32]
|
||||
|
||||
|
||||
def _subscription_key(spec: dict) -> str | None:
|
||||
"""The config's key file; else the one generated on first start (subscriptions.keyFile
|
||||
null); else none (false)."""
|
||||
path = spec.get("subscriptionKeyFile")
|
||||
if not path:
|
||||
state = spec.get("subscriptionKeyStateFile")
|
||||
return _kept_secret(state, lambda: secrets.token_hex(32)) if state else None
|
||||
key = _read_secret(path)
|
||||
if not key:
|
||||
raise ValueError(f"subscription key file '{path}' is empty")
|
||||
return key
|
||||
|
||||
|
||||
def build_inbounds(spec: dict, server_address: str, onion_address: str = "") -> dict:
|
||||
@@ -628,10 +662,12 @@ def build_inbounds(spec: dict, server_address: str, onion_address: str = "") ->
|
||||
"outbound": None,
|
||||
}
|
||||
)
|
||||
key = _subscription_key(spec) if by_user else None
|
||||
salts = spec.get("subscriptionSalts") or {}
|
||||
subscriptions = [
|
||||
{
|
||||
"user": name,
|
||||
"token": subscription_token(name, entry["secrets"]),
|
||||
"token": subscription_token(name, entry["secrets"], key, salts.get(name, "")),
|
||||
"body": base64.b64encode("\n".join(entry["links"]).encode("utf-8")).decode("ascii"),
|
||||
}
|
||||
for name, entry in by_user.items()
|
||||
|
||||
@@ -707,6 +707,47 @@ class BuildInboundsTests(unittest.TestCase):
|
||||
self.assertNotEqual(token, next(s["token"] for s in rotated if s["user"] == "fufsob"))
|
||||
# No links, nothing to subscribe to.
|
||||
self.assertEqual(build_inbounds(spec(share=False), "vpn.example.com")["subscriptions"], [])
|
||||
# Under a key only the server holds, the credentials alone do not give the token away.
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
key_file = os.path.join(tmp, "key")
|
||||
with open(key_file, "w", encoding="utf-8") as handle:
|
||||
handle.write("k" * 64 + "\n")
|
||||
keyed = {s["user"]: s["token"] for s in build_inbounds({**spec(), "subscriptionKeyFile": key_file},
|
||||
"vpn.example.com")["subscriptions"]}
|
||||
self.assertRegex(keyed["fufsob"], "^[0-9a-f]{32}$")
|
||||
self.assertNotEqual(keyed["fufsob"], token)
|
||||
self.assertEqual(keyed["fufsob"], subscription_token("fufsob", ["uuid-fufsob"], "k" * 64))
|
||||
self.assertNotEqual(keyed["fufsob"], subscription_token("fufsob", ["uuid-fufsob"], "other"))
|
||||
# The manager's salt moves one user's on, the rest stay.
|
||||
salted = {s["user"]: s["token"] for s in build_inbounds(
|
||||
{**spec(), "subscriptionKeyFile": key_file, "subscriptionSalts": {"fufsob": "ab" * 16}},
|
||||
"vpn.example.com")["subscriptions"]}
|
||||
self.assertNotEqual(salted["fufsob"], keyed["fufsob"])
|
||||
self.assertEqual(salted["teri"], keyed["teri"])
|
||||
# Without a key too: a salt is a secret of the server's.
|
||||
self.assertNotEqual(subscription_token("fufsob", ["uuid-fufsob"], salt="ab" * 16), token)
|
||||
# No key file: one generated on first start, kept, and used from then on.
|
||||
state = os.path.join(tmp, "state", "subscription-key")
|
||||
generated = {s["user"]: s["token"] for s in build_inbounds(
|
||||
{**spec(), "subscriptionKeyStateFile": state}, "vpn.example.com")["subscriptions"]}
|
||||
with open(state, encoding="utf-8") as handle:
|
||||
kept = handle.read().strip()
|
||||
self.assertRegex(kept, "^[0-9a-f]{64}$")
|
||||
self.assertEqual(os.stat(state).st_mode & 0o777, 0o600)
|
||||
self.assertEqual(generated["fufsob"], subscription_token("fufsob", ["uuid-fufsob"], kept))
|
||||
self.assertEqual(generated, {s["user"]: s["token"] for s in build_inbounds(
|
||||
{**spec(), "subscriptionKeyStateFile": state}, "vpn.example.com")["subscriptions"]})
|
||||
# The config's key wins over it.
|
||||
self.assertEqual(keyed, {s["user"]: s["token"] for s in build_inbounds(
|
||||
{**spec(), "subscriptionKeyFile": key_file, "subscriptionKeyStateFile": state},
|
||||
"vpn.example.com")["subscriptions"]})
|
||||
# A key file that is empty or not there stops the rendering, as a secret's would.
|
||||
with open(key_file, "w", encoding="utf-8") as handle:
|
||||
handle.write("\n")
|
||||
with self.assertRaises(ValueError):
|
||||
build_inbounds({**spec(), "subscriptionKeyFile": key_file}, "vpn.example.com")
|
||||
with self.assertRaises(OSError):
|
||||
build_inbounds({**spec(), "subscriptionKeyFile": os.path.join(tmp, "none")}, "vpn.example.com")
|
||||
|
||||
def test_share_port_overrides_the_bound_port(self):
|
||||
spec = {
|
||||
|
||||
@@ -0,0 +1,223 @@
|
||||
#!/usr/bin/env python3
|
||||
|
||||
import copy
|
||||
import json
|
||||
import os
|
||||
import secrets
|
||||
import subprocess
|
||||
import tempfile
|
||||
import time
|
||||
import unittest
|
||||
|
||||
import inbound_apply as ap
|
||||
|
||||
UUID_A = "b831381d-6324-4d53-ad4f-8cda48b30811"
|
||||
UUID_B = "11111111-2222-3333-4444-555555555555"
|
||||
|
||||
|
||||
def vless(tag, clients, port=443, **extra):
|
||||
inbound = {"tag": tag, "listen": "::", "port": port, "protocol": "vless",
|
||||
"settings": {"clients": clients, "decryption": "none"},
|
||||
"streamSettings": {"network": "raw", "security": "none"}}
|
||||
inbound.update(extra)
|
||||
return inbound
|
||||
|
||||
|
||||
def client(email, uuid=UUID_A, **extra):
|
||||
return {"id": uuid, "email": email, **extra}
|
||||
|
||||
|
||||
def rendering(*inbounds, **extra):
|
||||
return {"inbounds": list(inbounds), "links": [], "subscriptions": [], **extra}
|
||||
|
||||
|
||||
class Plan(unittest.TestCase):
|
||||
def test_nothing_changed(self):
|
||||
old = rendering(vless("a", [client("u")]))
|
||||
steps = ap.plan(old, copy.deepcopy(old))
|
||||
self.assertTrue(ap.is_noop(steps))
|
||||
|
||||
def test_users_come_and_go(self):
|
||||
old = rendering(vless("a", [client("u"), client("v", UUID_B)]))
|
||||
new = rendering(vless("a", [client("v", UUID_B, level=3), client("w")]))
|
||||
steps = ap.plan(old, new)
|
||||
self.assertEqual(steps["restart"], [])
|
||||
self.assertEqual(steps["users"]["a"]["remove"], ["u", "v"])
|
||||
self.assertEqual([c["email"] for c in steps["users"]["a"]["add"]], ["v", "w"])
|
||||
|
||||
def test_a_changed_listener_restarts(self):
|
||||
old = rendering(vless("a", [client("u")]))
|
||||
new = rendering(vless("a", [client("u")], port=8443))
|
||||
self.assertEqual(ap.plan(old, new)["restart"], ["listener 'a' changed"])
|
||||
|
||||
def test_listeners_added_or_gone_restart(self):
|
||||
old = rendering(vless("a", [client("u")]))
|
||||
new = rendering(vless("a", [client("u")]), vless("b", [client("u")], port=8443))
|
||||
self.assertEqual(ap.plan(old, new)["restart"], ["listeners added: b"])
|
||||
self.assertEqual(ap.plan(new, old)["restart"], ["listeners gone: b"])
|
||||
|
||||
def test_accounts_and_single_user_shadowsocks_restart(self):
|
||||
socks = {"tag": "s", "protocol": "socks", "port": 1080, "settings": {"accounts": [{"user": "u", "pass": "1"}]}}
|
||||
changed = copy.deepcopy(socks)
|
||||
changed["settings"]["accounts"].append({"user": "v", "pass": "2"})
|
||||
self.assertTrue(ap.plan(rendering(socks), rendering(changed))["restart"])
|
||||
single = {"tag": "ss", "protocol": "shadowsocks", "port": 8388,
|
||||
"settings": {"method": "aes-128-gcm", "password": "x", "email": "u"}}
|
||||
other = copy.deepcopy(single)
|
||||
other["settings"]["level"] = 2
|
||||
self.assertTrue(ap.plan(rendering(single), rendering(other))["restart"])
|
||||
|
||||
def test_routing_outbounds_addresses_and_outputs(self):
|
||||
old = rendering(vless("a", []), rules=[{"ruleTag": "x"}],
|
||||
selfOutbounds=[{"tag": "direct-self4-1", "sendThrough": "10.0.0.1"}],
|
||||
selfAddresses=[{"ipv4": "10.0.0.1", "ipv6": None}])
|
||||
new = rendering(vless("a", []), rules=[{"ruleTag": "x"}, {"ruleTag": "y"}],
|
||||
selfOutbounds=[{"tag": "direct-self4-2", "sendThrough": "10.0.0.2"}],
|
||||
selfAddresses=[{"ipv4": "10.0.0.2", "ipv6": "fd00::2"}])
|
||||
new["links"] = [{"link": "vless://..."}]
|
||||
steps = ap.plan(old, new)
|
||||
self.assertEqual(steps["rules"], [{"ruleTag": "x"}, {"ruleTag": "y"}])
|
||||
self.assertEqual(steps["outbounds"]["remove"], ["direct-self4-1"])
|
||||
self.assertEqual([o["tag"] for o in steps["outbounds"]["add"]], ["direct-self4-2"])
|
||||
self.assertEqual(steps["addresses"]["remove"], [("4", "10.0.0.1")])
|
||||
self.assertEqual(steps["addresses"]["add"], [("4", "10.0.0.2"), ("6", "fd00::2")])
|
||||
self.assertTrue(steps["outputs"])
|
||||
|
||||
def test_udp_inbounds(self):
|
||||
self.assertTrue(ap.udp_inbound({"protocol": "hysteria"}))
|
||||
self.assertTrue(ap.udp_inbound({"protocol": "vless", "streamSettings": {"network": "xhttp", "tlsSettings": {"alpn": ["h3"]}}}))
|
||||
self.assertFalse(ap.udp_inbound(vless("a", [])))
|
||||
|
||||
|
||||
class Steps(unittest.TestCase):
|
||||
def test_the_commands(self):
|
||||
config = {"xray": "xray", "api": "unix:///run/api.sock", "ss": "ss", "nft": "nft", "nftTable": "t",
|
||||
"ip": "ip", "selfInterface": "ps-self"}
|
||||
tools = ap.Tools(config, dry_run=True)
|
||||
new = rendering(vless("a", [client("w")]), {"tag": "h", "protocol": "hysteria", "port": 443, "settings": {"clients": []}})
|
||||
steps = {"restart": [], "users": {"a": {"remove": ["u"], "add": [client("w")]}, "h": {"remove": ["u"], "add": []}},
|
||||
"rules": None, "outbounds": {"remove": [], "add": []},
|
||||
"addresses": {"remove": [("4", "10.0.0.1")], "add": [("6", "fd00::2")]}, "outputs": False}
|
||||
done = ap.run_steps(tools, steps, new, None)
|
||||
self.assertIn("a: -u", done)
|
||||
self.assertIn("a: +w", done)
|
||||
log = "\n".join(tools.log)
|
||||
self.assertIn("xray api statsonlineiplist --server=unix:///run/api.sock -email u", log)
|
||||
self.assertIn("xray api rmu --server=unix:///run/api.sock -tag=a u", log)
|
||||
self.assertIn("xray api adu --server=unix:///run/api.sock", log)
|
||||
self.assertIn("ip -4 addr del 10.0.0.1/32 dev ps-self", log)
|
||||
self.assertIn("ip -6 addr add fd00::2/128 dev ps-self nodad", log)
|
||||
|
||||
|
||||
class SyncConfig(unittest.TestCase):
|
||||
def test_config_json_follows_in_place(self):
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
path = os.path.join(directory, "config.json")
|
||||
running = {"inbounds": [vless("a", [client("u")]), vless("b", [client("u")], port=8443)],
|
||||
"routing": {"rules": [{"ruleTag": "x"}]},
|
||||
"outbounds": [{"tag": "direct"}, {"tag": "direct-self4-1"}]}
|
||||
with open(path, "w", encoding="utf-8") as handle:
|
||||
json.dump(running, handle)
|
||||
os.chmod(path, 0o440 | 0o200)
|
||||
inode = os.stat(path).st_ino
|
||||
new = rendering(vless("a", [client("w")]), vless("b", [client("u")], port=8443))
|
||||
steps = {"users": {"a": {"remove": ["u"], "add": [client("w")]}}, "rules": [{"ruleTag": "y"}],
|
||||
"outbounds": {"remove": ["direct-self4-1"], "add": [{"tag": "direct-self4-2"}]}}
|
||||
ap.sync_config(directory, steps, new)
|
||||
with open(path, encoding="utf-8") as handle:
|
||||
synced = json.load(handle)
|
||||
self.assertEqual(os.stat(path).st_ino, inode)
|
||||
self.assertEqual([c["email"] for c in synced["inbounds"][0]["settings"]["clients"]], ["w"])
|
||||
self.assertEqual([c["email"] for c in synced["inbounds"][1]["settings"]["clients"]], ["u"])
|
||||
self.assertEqual(synced["routing"]["rules"], [{"ruleTag": "y"}])
|
||||
self.assertEqual([o["tag"] for o in synced["outbounds"]], ["direct", "direct-self4-2"])
|
||||
|
||||
|
||||
class Stopped(unittest.TestCase):
|
||||
def test_stopped_inbounds_are_left_to_try_restart(self):
|
||||
config = {"runtimeDir": "/nonexistent/proxy-suite-inbounds", "unit": "proxy-suite-inbounds.service",
|
||||
"systemctl": "systemctl"}
|
||||
done = ap.apply(config, {"listeners": []}, dry_run=True)
|
||||
self.assertEqual(done, ["restarted proxy-suite-inbounds.service: the inbounds are not running"])
|
||||
|
||||
|
||||
class AmneziaWG(unittest.TestCase):
|
||||
CONFIG = "[Interface]\nPrivateKey = k\nAddress = 10.66.0.1/24\nListenPort = 51820\nMTU = 1380\nTable = off\nJc = 4\n\n[Peer]\nPublicKey = p\nAllowedIPs = 10.66.0.2/32\n"
|
||||
|
||||
def test_strip(self):
|
||||
stripped = ap.strip_config(self.CONFIG)
|
||||
self.assertNotIn("Address", stripped)
|
||||
self.assertNotIn("MTU", stripped)
|
||||
self.assertIn("Jc = 4", stripped)
|
||||
self.assertIn("AllowedIPs = 10.66.0.2/32", stripped)
|
||||
|
||||
def test_interface_part_ignores_peers(self):
|
||||
other = self.CONFIG.replace("10.66.0.2/32", "10.66.0.3/32")
|
||||
self.assertEqual(ap.interface_part(self.CONFIG), ap.interface_part(other))
|
||||
self.assertNotEqual(ap.interface_part(self.CONFIG), ap.interface_part(self.CONFIG.replace("Jc = 4", "Jc = 5")))
|
||||
|
||||
|
||||
@unittest.skipUnless(os.environ.get("XRAY"), "XRAY is not set: no live XRay to talk to")
|
||||
class LiveXray(unittest.TestCase):
|
||||
"""The API steps against a running XRay: users added and removed, rules replaced."""
|
||||
|
||||
def setUp(self):
|
||||
self.dir = tempfile.TemporaryDirectory()
|
||||
self.socket = f"@proxy-suite-test-{secrets.token_hex(4)}"
|
||||
self.api = f"unix-abstract:{self.socket[1:]}"
|
||||
template = {"routing": {"domainStrategy": "AsIs", "rules": [{"ruleTag": "inbound-stats-api", "inboundTag": ["api-in"], "outboundTag": "api"}]}}
|
||||
config = {
|
||||
"log": {"loglevel": "warning"},
|
||||
"api": {"tag": "api", "services": ["StatsService", "HandlerService", "RoutingService"]},
|
||||
"stats": {},
|
||||
"inbounds": [
|
||||
{"tag": "api-in", "protocol": "dokodemo-door", "listen": self.socket,
|
||||
"settings": {"address": "127.0.0.1", "network": "unix"}},
|
||||
vless("a", [client("u")], port=0, listen="127.0.0.1"),
|
||||
],
|
||||
"outbounds": [{"tag": "direct", "protocol": "freedom"}, {"tag": "api", "protocol": "freedom"}],
|
||||
"routing": template["routing"],
|
||||
}
|
||||
self.template = template
|
||||
# Port 0 is no port to XRay: take a free one.
|
||||
import socket
|
||||
with socket.socket() as probe:
|
||||
probe.bind(("127.0.0.1", 0))
|
||||
config["inbounds"][1]["port"] = probe.getsockname()[1]
|
||||
self.inbound = config["inbounds"][1]
|
||||
path = os.path.join(self.dir.name, "config.json")
|
||||
with open(path, "w", encoding="utf-8") as handle:
|
||||
json.dump(config, handle)
|
||||
self.xray = subprocess.Popen([os.environ["XRAY"], "run", "-c", path], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
|
||||
self.tools = ap.Tools({"xray": os.environ["XRAY"], "api": self.api, "tmpDir": self.dir.name})
|
||||
for _ in range(50):
|
||||
try:
|
||||
self.tools.xray_api("lsi", what="waiting")
|
||||
break
|
||||
except ap.ApplyError:
|
||||
time.sleep(0.1)
|
||||
|
||||
def tearDown(self):
|
||||
self.xray.terminate()
|
||||
self.xray.wait()
|
||||
self.dir.cleanup()
|
||||
|
||||
def users(self):
|
||||
out = self.tools.xray_api("inbounduser", "-tag=a", what="listing")
|
||||
return sorted(u["email"] for u in json.loads(out or "{}").get("users") or [])
|
||||
|
||||
def test_users_and_rules(self):
|
||||
old = rendering(self.inbound)
|
||||
new_inbound = copy.deepcopy(self.inbound)
|
||||
new_inbound["settings"]["clients"] = [client("v", UUID_B, level=4)]
|
||||
new = rendering(new_inbound, rules=self.template["routing"]["rules"] + [{"ruleTag": "extra", "user": ["v"], "outboundTag": "direct"}])
|
||||
steps = ap.plan(old, new)
|
||||
self.assertEqual(steps["restart"], [])
|
||||
ap.run_steps(self.tools, steps, new, self.template)
|
||||
self.assertEqual(self.users(), ["v"])
|
||||
rules = json.loads(self.tools.xray_api("lsrules", what="rules"))["rules"]
|
||||
self.assertEqual([r["ruleTag"] for r in rules], ["inbound-stats-api", "extra"])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,628 @@
|
||||
#!/usr/bin/env python3
|
||||
|
||||
import base64
|
||||
import copy
|
||||
import http.client
|
||||
import importlib.util
|
||||
import json
|
||||
import os
|
||||
import socket
|
||||
import tempfile
|
||||
import threading
|
||||
import time
|
||||
import unittest
|
||||
import uuid
|
||||
from unittest import mock
|
||||
|
||||
import inbound_apply
|
||||
import inbound_manager as im
|
||||
import inbound_subscription
|
||||
import inbound_policy as policy
|
||||
import inbound_runtime as rt
|
||||
|
||||
# The runtime tests' spec, spool and all.
|
||||
_spec = importlib.util.spec_from_file_location("runtime_tests", os.path.join(os.path.dirname(__file__), "test-inbound-runtime.py"))
|
||||
runtime_tests = importlib.util.module_from_spec(_spec)
|
||||
_spec.loader.exec_module(runtime_tests)
|
||||
|
||||
|
||||
class FakeNetfilter:
|
||||
enabled = True
|
||||
|
||||
def __init__(self):
|
||||
self.banned = []
|
||||
self.limits = None
|
||||
|
||||
def ensure(self):
|
||||
return False
|
||||
|
||||
def ban(self, ip, ports, seconds):
|
||||
self.banned.append((ip, sorted(ports), seconds))
|
||||
|
||||
def bans(self):
|
||||
return [{"ip": ip, "port": port, "expires": seconds} for ip, ports, seconds in self.banned for port in ports]
|
||||
|
||||
def unban(self, ip):
|
||||
found = [b for b in self.banned if b[0] == ip]
|
||||
self.banned = [b for b in self.banned if b[0] != ip]
|
||||
return len(found)
|
||||
|
||||
def sync_limits(self, users, peers):
|
||||
self.limits = (users, peers)
|
||||
return True
|
||||
|
||||
|
||||
class Clock:
|
||||
def __init__(self, now):
|
||||
self.now = now
|
||||
|
||||
def __call__(self):
|
||||
return self.now
|
||||
|
||||
|
||||
class ManagerTest(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.tmp = tempfile.TemporaryDirectory()
|
||||
base = self.tmp.name
|
||||
self.spool = os.path.join(base, "spool")
|
||||
os.makedirs(self.spool)
|
||||
self.runtime_dir = os.path.join(base, "run")
|
||||
os.makedirs(self.runtime_dir)
|
||||
self.spec = runtime_tests.make_spec(self.spool)
|
||||
self.config = {
|
||||
"policyFile": os.path.join(base, "policy.json"),
|
||||
"stateFile": os.path.join(base, "state.json"),
|
||||
"statsFile": os.path.join(base, "stats.json"),
|
||||
"speedLimits": True,
|
||||
"slots": 4,
|
||||
"apply": {"runtimeDir": self.runtime_dir},
|
||||
"subscriptions": {"baseUrl": "https://vpn.example.com/sub", "profileTitle": "VPN {user}", "updateInterval": 12},
|
||||
"ipLimit": {"banSeconds": 300},
|
||||
}
|
||||
self.spec["manager"] = {k: self.config[k] for k in ("policyFile", "stateFile", "statsFile", "speedLimits")}
|
||||
self.clock = Clock(time.time())
|
||||
self.netfilter = FakeNetfilter()
|
||||
self.webhooks = im.Webhooks([])
|
||||
self.applies = []
|
||||
patcher = mock.patch.object(inbound_apply, "apply", side_effect=lambda config, spec: self.applies.append(spec) or [])
|
||||
patcher.start()
|
||||
self.addCleanup(patcher.stop)
|
||||
self.cut = mock.patch.object(inbound_apply, "cut").start()
|
||||
self.addCleanup(mock.patch.stopall)
|
||||
self.manager = im.Manager(self.config, self.spec, clock=self.clock, netfilter=self.netfilter, webhooks=self.webhooks)
|
||||
|
||||
def tearDown(self):
|
||||
self.tmp.cleanup()
|
||||
|
||||
def events(self, kind=None):
|
||||
return [(e["event"], e["user"]) for e in self.webhooks.sent if kind is None or e["event"] == kind]
|
||||
|
||||
def write_stats(self, stats):
|
||||
policy.write_json(self.config["statsFile"], stats)
|
||||
|
||||
def write_rendered(self, rendered):
|
||||
with open(os.path.join(self.runtime_dir, "rendered.json"), "w", encoding="utf-8") as handle:
|
||||
json.dump(rendered, handle)
|
||||
|
||||
# --- users and policies -----------------------------------------------------------
|
||||
|
||||
def test_create_a_user_with_a_policy(self):
|
||||
row = self.manager.create_user({"name": "alice", "listeners": ["vless-in"],
|
||||
"policy": {"trafficLimit": "10G", "expiresAt": "+30d", "speedLimit": "20M/5M"}})
|
||||
self.assertEqual(row["source"], "runtime")
|
||||
self.assertEqual(row["listeners"], ["vless-in"])
|
||||
self.assertEqual(row["policy"]["trafficLimit"], 10 * 1024**3)
|
||||
self.assertEqual(row["expiresAt"], int(self.clock.now) + 30 * 86400)
|
||||
self.assertEqual(row["level"], 1)
|
||||
self.assertTrue(row["active"])
|
||||
self.assertEqual(len(self.applies), 1)
|
||||
self.assertIn(("user.created", "alice"), self.events())
|
||||
with self.assertRaises(im.ApiError) as raised:
|
||||
self.manager.create_user({"name": "alice"})
|
||||
self.assertEqual(raised.exception.status, 409)
|
||||
|
||||
def test_bad_policy_is_refused_before_anything_is_written(self):
|
||||
with self.assertRaises(im.ApiError) as raised:
|
||||
self.manager.create_user({"name": "zed", "policy": {"trafficLimit": "lots"}})
|
||||
self.assertEqual(raised.exception.status, 400)
|
||||
self.assertNotIn("zed", rt.load_spool(self.spool)[0]["users"])
|
||||
|
||||
def test_declared_users_get_policies_too(self):
|
||||
row = self.manager.set_policy("bob", {"enabled": False})
|
||||
self.assertFalse(row["active"])
|
||||
self.assertEqual(row["reasons"], ["disabled"])
|
||||
self.assertEqual(row["stored"], {"enabled": False})
|
||||
row = self.manager.set_policy("bob", {}, unset=["enabled"])
|
||||
self.assertTrue(row["active"])
|
||||
self.assertEqual(policy.load_policies(self.config["policyFile"]), {})
|
||||
|
||||
def test_disabling_reaches_the_renderers(self):
|
||||
self.manager.set_policy("bob", {"enabled": False})
|
||||
merged, _, _ = rt.merge(self.spec)
|
||||
vless = next(l for l in merged["listeners"] if l["tag"] == "vless-in")
|
||||
bob = next(u for u in vless["users"] if u["name"] == "bob")
|
||||
self.assertFalse(bob["active"])
|
||||
|
||||
def test_extend_from_the_later_of_now_and_the_expiry(self):
|
||||
now = int(self.clock.now)
|
||||
self.manager.set_policy("bob", {"expiresAt": now + 86400})
|
||||
row = self.manager.extend("bob", by="30d")
|
||||
self.assertEqual(row["expiresAt"], now + 31 * 86400)
|
||||
self.manager.set_policy("bob", {"expiresAt": now - 86400})
|
||||
self.assertEqual(self.manager.extend("bob", by="1d")["expiresAt"], now + 86400)
|
||||
with self.assertRaises(im.ApiError):
|
||||
self.manager.extend("bob")
|
||||
|
||||
def test_extend_with_a_reset_starts_the_traffic_over(self):
|
||||
today = policy.day_key(self.clock.now)
|
||||
self.manager.create_user({"name": "alice", "policy": {"trafficLimit": 100}})
|
||||
self.manager.tick()
|
||||
self.write_stats({"days": {today: {"user": {"alice": {"up": 60, "down": 60}}}}})
|
||||
self.manager.tick()
|
||||
self.assertEqual(self.manager.overview("alice")[0]["reasons"], ["traffic"])
|
||||
row = self.manager.extend("alice", by="30d", reset=True)
|
||||
self.assertTrue(row["active"])
|
||||
self.assertEqual(row["traffic"]["used"], 0)
|
||||
self.assertEqual(row["expiresAt"], int(self.clock.now) + 30 * 86400)
|
||||
self.assertIn(("user.reset", "alice"), self.events())
|
||||
|
||||
def test_on_hold_starts_with_the_first_connection(self):
|
||||
today = policy.day_key(self.clock.now)
|
||||
row = self.manager.create_user({"name": "alice", "policy": {"expiresAfter": "30d"}})
|
||||
self.assertTrue(row["active"])
|
||||
self.assertTrue(row["onHold"])
|
||||
self.assertIsNone(row["expiresAt"])
|
||||
# Extended while on hold: the term grows, nothing starts.
|
||||
row = self.manager.extend("alice", by="5d")
|
||||
self.assertEqual(row["policy"]["expiresAfter"], 35 * 86400)
|
||||
self.assertTrue(row["onHold"])
|
||||
self.manager.tick()
|
||||
self.clock.now += 3 * 86400
|
||||
self.manager.tick()
|
||||
self.assertTrue(self.manager.overview("alice")[0]["onHold"])
|
||||
self.assertEqual(self.events("user.activated"), [])
|
||||
self.write_stats({"days": {today: {"user": {"alice": {"up": 1, "down": 2}}}}})
|
||||
self.manager.tick()
|
||||
row = self.manager.overview("alice")[0]
|
||||
self.assertFalse(row["onHold"])
|
||||
self.assertEqual(row["expiresAt"], int(self.clock.now) + 35 * 86400)
|
||||
self.assertEqual(self.events("user.activated"), [("user.activated", "alice")])
|
||||
self.manager.tick()
|
||||
self.assertEqual(len(self.events("user.activated")), 1)
|
||||
|
||||
def test_on_hold_starts_when_seen_online(self):
|
||||
self.manager.create_user({"name": "alice", "policy": {"expiresAfter": "1d", "trafficLimit": "1G"}})
|
||||
self.manager.create_user({"name": "zed", "policy": {"expiresAfter": policy.MAX_TIME - 1, "trafficLimit": "1G"}})
|
||||
self.write_stats({"online": [{"email": name, "ips": [{"ip": "198.51.100.1"}]} for name in ("alice", "zed")]})
|
||||
self.manager.tick()
|
||||
self.assertEqual(self.manager.overview("alice")[0]["expiresAt"], int(self.clock.now) + 86400)
|
||||
# A term past the year 9999 ends just before it: the rest of the policy stays.
|
||||
zed = self.manager.overview("zed")[0]
|
||||
self.assertEqual(zed["expiresAt"], policy.MAX_TIME - 1)
|
||||
self.assertEqual(zed["policy"]["trafficLimit"], 1024**3)
|
||||
|
||||
def test_expired_runtime_users_are_deleted_after_a_while(self):
|
||||
self.config["deleteExpiredAfter"] = "7d"
|
||||
now = int(self.clock.now)
|
||||
self.manager.create_user({"name": "alice", "policy": {"expiresAt": now + 86400}})
|
||||
self.manager.create_user({"name": "carol"})
|
||||
self.manager.set_policy("bob", {"expiresAt": now + 86400})
|
||||
self.clock.now += 7 * 86400
|
||||
self.manager.tick()
|
||||
self.assertIn("alice", self.manager.names())
|
||||
self.clock.now += 86400 + 1
|
||||
self.manager.tick()
|
||||
names = self.manager.names()
|
||||
self.assertNotIn("alice", names)
|
||||
# Declared in the config: kept. Never expires: kept.
|
||||
self.assertIn("bob", names)
|
||||
self.assertIn("carol", names)
|
||||
deleted = [e for e in self.webhooks.sent if e["event"] == "user.deleted"]
|
||||
self.assertEqual([(e["user"], e["data"]) for e in deleted], [("alice", {"reason": "expired"})])
|
||||
|
||||
def test_delete_forgets_the_policy(self):
|
||||
self.manager.create_user({"name": "alice", "policy": {"ipLimit": 2}})
|
||||
self.manager.delete_user("alice")
|
||||
self.assertNotIn("alice", policy.load_policies(self.config["policyFile"]))
|
||||
with self.assertRaises(im.ApiError) as raised:
|
||||
self.manager.delete_user("bob")
|
||||
self.assertEqual(raised.exception.status, 409)
|
||||
|
||||
def test_set_listeners(self):
|
||||
self.manager.create_user({"name": "alice", "listeners": ["vless-in"]})
|
||||
self.assertEqual(self.manager.set_listeners("alice", [])["listeners"], [])
|
||||
self.assertEqual(self.manager.set_listeners("alice", ["vless-in"])["listeners"], ["vless-in"])
|
||||
# A single-user shadowsocks listener takes no second user.
|
||||
with self.assertRaises(im.ApiError) as raised:
|
||||
self.manager.set_listeners("alice", ["ss-in"])
|
||||
self.assertEqual(raised.exception.status, 409)
|
||||
|
||||
def test_slots_run_out(self):
|
||||
for name in ("a1", "a2", "a3", "a4"):
|
||||
self.manager.create_user({"name": name, "policy": {"speedLimit": "1M"}})
|
||||
with self.assertRaises(im.ApiError):
|
||||
self.manager.create_user({"name": "a5", "policy": {"speedLimit": "1M"}})
|
||||
# Refused whole: no user without the slot their policy needs.
|
||||
self.assertNotIn("a5", rt.load_spool(self.spool)[0]["users"])
|
||||
self.manager.create_user({"name": "a5"})
|
||||
with self.assertRaises(im.ApiError):
|
||||
self.manager.set_policy("a5", {"speedLimit": "1M"})
|
||||
self.assertNotIn("a5", self.manager.stored_policies())
|
||||
# A slot comes back when its user's limit goes.
|
||||
self.manager.set_policy("a1", {"speedLimit": None})
|
||||
self.manager.tick()
|
||||
self.assertNotIn("a1", self.manager.state()["slots"])
|
||||
self.manager.set_policy("a5", {"speedLimit": "1M"})
|
||||
self.assertIn("a5", self.manager.state()["slots"])
|
||||
|
||||
# --- the tick ---------------------------------------------------------------------
|
||||
|
||||
def test_traffic_runs_out_and_comes_back_with_the_period(self):
|
||||
today = policy.day_key(self.clock.now)
|
||||
self.manager.create_user({"name": "alice", "policy": {"trafficLimit": 1000, "trafficPeriod": "daily"}})
|
||||
self.manager.tick()
|
||||
self.write_stats({"days": {today: {"user": {"alice": {"up": 300, "down": 600}}}}})
|
||||
self.manager.tick()
|
||||
self.assertIn(("user.traffic", "alice"), self.events())
|
||||
self.assertTrue(self.manager.overview("alice")[0]["active"])
|
||||
self.write_stats({"days": {today: {"user": {"alice": {"up": 400, "down": 700}}}}})
|
||||
applies = len(self.applies)
|
||||
self.manager.tick()
|
||||
row = self.manager.overview("alice")[0]
|
||||
self.assertFalse(row["active"])
|
||||
self.assertEqual(row["reasons"], ["traffic"])
|
||||
self.assertEqual(len(self.applies), applies + 1)
|
||||
self.assertIn(("user.disabled", "alice"), self.events())
|
||||
self.assertEqual([e for e in self.events("user.traffic")], [("user.traffic", "alice")] * 2)
|
||||
# The next day: a new period.
|
||||
self.clock.now += 86400
|
||||
self.manager.tick()
|
||||
self.assertTrue(self.manager.overview("alice")[0]["active"])
|
||||
self.assertIn(("user.enabled", "alice"), self.events())
|
||||
|
||||
def test_expiry_warnings_and_expiry(self):
|
||||
self.manager.create_user({"name": "alice", "policy": {"expiresAt": int(self.clock.now) + 2 * 86400}})
|
||||
self.manager.tick()
|
||||
self.assertEqual(self.events("user.expiring"), [("user.expiring", "alice")])
|
||||
self.manager.tick()
|
||||
self.assertEqual(len(self.events("user.expiring")), 1)
|
||||
self.clock.now += 2 * 86400 + 1
|
||||
self.manager.tick()
|
||||
self.assertEqual(self.manager.overview("alice")[0]["reasons"], ["expired"])
|
||||
self.assertIn(("user.disabled", "alice"), self.events())
|
||||
|
||||
def test_ip_limit_bans_the_newest(self):
|
||||
self.manager.create_user({"name": "alice", "listeners": ["vless-in"], "policy": {"ipLimit": 1}})
|
||||
self.write_rendered({"inbounds": [
|
||||
{"tag": "vless-in", "listen": "::", "port": 443, "protocol": "vless", "settings": {"clients": [{"email": "alice"}]}},
|
||||
{"tag": "behind", "listen": "127.0.0.1", "port": 9000, "protocol": "vless", "settings": {"clients": [{"email": "alice"}]}},
|
||||
]})
|
||||
self.write_stats({"online": [{"email": "alice", "ips": [{"ip": "198.51.100.1"}]}]})
|
||||
self.manager.tick()
|
||||
self.assertEqual(self.netfilter.banned, [])
|
||||
self.clock.now += 10
|
||||
self.write_stats({"online": [{"email": "alice", "ips": [{"ip": "198.51.100.1"}, {"ip": "203.0.113.9"}]}]})
|
||||
self.manager.tick()
|
||||
self.assertEqual(self.netfilter.banned, [("203.0.113.9", [443], 300)])
|
||||
self.assertTrue(self.cut.called)
|
||||
self.assertEqual(self.events("user.ip-limit"), [("user.ip-limit", "alice")])
|
||||
|
||||
def test_speed_limits_follow_activity(self):
|
||||
self.manager.create_user({"name": "alice", "policy": {"speedLimit": "8M/2M"}})
|
||||
users, _ = self.netfilter.limits
|
||||
self.assertEqual(users, {1: {"up": 2_000_000, "down": 8_000_000}})
|
||||
self.manager.set_policy("alice", {"enabled": False})
|
||||
self.assertEqual(self.netfilter.limits[0], {})
|
||||
|
||||
# --- subscriptions ----------------------------------------------------------------
|
||||
|
||||
def test_subscription_headers(self):
|
||||
today = policy.day_key(self.clock.now)
|
||||
self.manager.create_user({"name": "alice", "policy": {"trafficLimit": 5000, "expiresAt": 2_000_000_000}})
|
||||
self.manager.tick()
|
||||
self.write_stats({"days": {today: {"user": {"alice": {"up": 10, "down": 20}}}}})
|
||||
self.write_rendered({"subscriptions": [{"user": "alice", "token": "a" * 32, "body": "Ym9keQ=="}]})
|
||||
body, headers = self.manager.subscription("a" * 32)
|
||||
self.assertEqual(body, b"Ym9keQ==")
|
||||
self.assertEqual(headers["subscription-userinfo"], "upload=10; download=20; total=5000; expire=2000000000")
|
||||
self.assertEqual(base64.b64decode(headers["profile-title"][len("base64:"):]).decode(), "VPN alice")
|
||||
self.assertEqual(headers["Content-Type"], "text/plain; charset=utf-8")
|
||||
self.assertEqual(headers["profile-update-interval"], "12")
|
||||
self.assertIsNone(self.manager.subscription("b" * 32))
|
||||
self.assertEqual(self.manager.overview("alice")[0]["subscription"]["url"], "https://vpn.example.com/sub/" + "a" * 32)
|
||||
|
||||
def test_subscription_formats(self):
|
||||
self.manager.create_user({"name": "alice", "policy": {"expiresAfter": "30d"}})
|
||||
link = "trojan://pass@vpn.example.com:8443?security=tls&sni=vpn.example.com#tr"
|
||||
self.write_rendered({
|
||||
"subscriptions": [{"user": "alice", "token": "a" * 32, "body": base64.b64encode(link.encode()).decode()}],
|
||||
"links": [{"tag": "tr", "user": "alice", "link": link,
|
||||
"outbound": {"type": "trojan", "tag": "tr", "server": "vpn.example.com", "server_port": 8443,
|
||||
"password": "pass", "tls": {"enabled": True, "server_name": "vpn.example.com"}}}],
|
||||
})
|
||||
body, headers = self.manager.subscription("a" * 32, user_agent="ClashMetaForAndroid/2.11")
|
||||
self.assertEqual(json.loads(body)["proxies"][0]["name"], "tr")
|
||||
self.assertIn("subscription-userinfo", headers)
|
||||
body, headers = self.manager.subscription("a" * 32, user_agent="Mozilla/5.0", accept="text/html",
|
||||
accept_language="ru")
|
||||
self.assertEqual(headers["Content-Type"], "text/html; charset=utf-8")
|
||||
self.assertEqual(headers["Referrer-Policy"], "no-referrer")
|
||||
self.assertEqual(headers["Content-Security-Policy"], inbound_subscription.PAGE_HEADERS["Content-Security-Policy"])
|
||||
self.assertNotIn("content-disposition", headers)
|
||||
page = body.decode()
|
||||
self.assertIn("Начнётся с первого подключения", page)
|
||||
# baseUrl wins over the address asked at: it is what clients are given.
|
||||
self.assertIn("https://vpn.example.com/sub/" + "a" * 32, page)
|
||||
body, headers = self.manager.subscription("a" * 32, fmt="links")
|
||||
self.assertEqual(body.decode().strip(), link)
|
||||
# Every format: not cached, sniffed, sent on or indexed; the page's CSP on the page only.
|
||||
self.assertEqual({k: headers[k] for k in inbound_subscription.HEADERS}, inbound_subscription.HEADERS)
|
||||
self.assertNotIn("Content-Security-Policy", headers)
|
||||
|
||||
def test_rotate_subscription(self):
|
||||
self.manager.create_user({"name": "alice", "listeners": ["vless-in"]})
|
||||
merged, _, _ = rt.merge(self.spec)
|
||||
self.assertEqual(merged["subscriptionSalts"], {})
|
||||
status, _ = im.handle_api(self.manager, "POST", "/api/v1/users/alice/rotate-subscription", {}, None)
|
||||
self.assertEqual(status, 200)
|
||||
salt = policy.load_state(self.config["stateFile"])["subscriptions"]["alice"]
|
||||
self.assertTrue(policy.is_subscription_salt(salt))
|
||||
# The renderers take it (proxy_inbound.subscription_token), on the apply it asked for.
|
||||
self.assertEqual(rt.merge(self.spec)[0]["subscriptionSalts"], {"alice": salt})
|
||||
self.assertEqual(self.applies[-1], self.spec)
|
||||
self.assertEqual(self.webhooks.sent[-1]["data"], {"subscription": "rotated"})
|
||||
self.manager.rotate_subscription("alice")
|
||||
self.assertNotEqual(policy.load_state(self.config["stateFile"])["subscriptions"]["alice"], salt)
|
||||
with self.assertRaises(im.ApiError) as raised:
|
||||
self.manager.rotate_subscription("nobody")
|
||||
self.assertEqual(raised.exception.status, 404)
|
||||
# It travels with an export; a deleted user's goes with them.
|
||||
bundle = self.manager.export()
|
||||
self.assertIn("alice", bundle["state"]["subscriptions"])
|
||||
self.manager.delete_user("alice")
|
||||
self.assertNotIn("alice", policy.load_state(self.config["stateFile"])["subscriptions"])
|
||||
self.manager.import_bundle(bundle)
|
||||
self.assertEqual(policy.load_state(self.config["stateFile"])["subscriptions"]["alice"],
|
||||
bundle["state"]["subscriptions"]["alice"])
|
||||
with self.assertRaises(im.ApiError):
|
||||
self.manager.import_bundle({**bundle, "state": {"subscriptions": {"alice": "../x"}}})
|
||||
# A salt that does not hold up is left out.
|
||||
state = policy.load_state(self.config["stateFile"])
|
||||
state["subscriptions"]["bob"] = "short"
|
||||
policy.write_json(self.config["stateFile"], state)
|
||||
self.assertNotIn("bob", policy.load_state(self.config["stateFile"])["subscriptions"])
|
||||
|
||||
def test_misses_are_logged_sparingly(self):
|
||||
clock = Clock(1000.0)
|
||||
misses = im.Misses(every=60, clock=clock)
|
||||
with mock.patch.object(im, "_log") as log:
|
||||
for _ in range(5):
|
||||
misses.note("203.0.113.7")
|
||||
misses.note("198.51.100.1")
|
||||
clock.now += 61
|
||||
misses.note("203.0.113.7")
|
||||
self.assertEqual([c.args[0] for c in log.call_args_list], [
|
||||
"subscription: unknown token from 203.0.113.7",
|
||||
"subscription: unknown token from 198.51.100.1",
|
||||
"subscription: unknown token from 203.0.113.7 (4 more since the last line)",
|
||||
])
|
||||
|
||||
# --- export and import ------------------------------------------------------------
|
||||
|
||||
def test_export_and_import_into_an_empty_server(self):
|
||||
self.manager.create_user({"name": "alice", "listeners": ["vless-in"], "policy": {"trafficLimit": "1G"}})
|
||||
self.write_stats({"days": {"2026-10-01": {"user": {"alice": {"up": 1, "down": 2}}}}})
|
||||
awg_state = os.path.join(self.tmp.name, "awg.json")
|
||||
self.spec["listeners"][2]["amneziaWg"] = {"stateFile": awg_state, "interfaceName": "awgi-awg", "subnet": "10.66.0.0/24"}
|
||||
server_key = base64.b64encode(b"S" * 32).decode()
|
||||
policy.write_json(awg_state, {"version": 1, "server": {"publicKey": server_key}, "users": {"bob": {"offset": 2}}})
|
||||
bundle = json.loads(json.dumps(self.manager.export()))
|
||||
self.assertEqual(sorted(bundle["runtime"]["users"]), ["alice"])
|
||||
self.assertEqual(bundle["amneziaWg"]["awg"]["server"]["publicKey"], server_key)
|
||||
|
||||
other = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(other.cleanup)
|
||||
spool = os.path.join(other.name, "spool")
|
||||
os.makedirs(spool)
|
||||
spec = runtime_tests.make_spec(spool)
|
||||
spec["listeners"][2]["amneziaWg"] = {"stateFile": os.path.join(other.name, "awg.json"), "interfaceName": "awgi-awg", "subnet": "10.66.0.0/24"}
|
||||
config = copy.deepcopy(self.config)
|
||||
for key in ("policyFile", "stateFile", "statsFile"):
|
||||
config[key] = os.path.join(other.name, os.path.basename(config[key]))
|
||||
spec["manager"] = {k: config[k] for k in ("policyFile", "stateFile", "statsFile", "speedLimits")}
|
||||
target = im.Manager(config, spec, clock=self.clock, netfilter=FakeNetfilter(), webhooks=im.Webhooks([]))
|
||||
report = target.import_bundle(bundle)
|
||||
self.assertEqual(report["users"], ["alice"])
|
||||
self.assertEqual(report["amneziaWg"], ["awg"])
|
||||
row = target.overview("alice")[0]
|
||||
self.assertEqual(row["policy"]["trafficLimit"], 1024**3)
|
||||
self.assertEqual(rt.load_spool(spool)[0]["users"]["alice"]["uuid"], rt.load_spool(self.spool)[0]["users"]["alice"]["uuid"])
|
||||
self.assertEqual(policy.read_stats(config["statsFile"])["days"]["2026-10-01"]["user"]["alice"], {"up": 1, "down": 2})
|
||||
with self.assertRaises(im.ApiError) as raised:
|
||||
target.import_bundle(bundle)
|
||||
self.assertEqual(raised.exception.status, 409)
|
||||
self.assertEqual(target.import_bundle(bundle, replace=True)["users"], ["alice"])
|
||||
|
||||
def test_the_generated_subscription_key_travels(self):
|
||||
key_path = os.path.join(self.tmp.name, "inbounds", "subscription-key")
|
||||
self.spec["subscriptionKeyStateFile"] = key_path
|
||||
self.assertIsNone(self.manager.export()["subscriptionKey"])
|
||||
os.makedirs(os.path.dirname(key_path))
|
||||
with open(key_path, "w", encoding="utf-8") as handle:
|
||||
handle.write("e" * 64 + "\n")
|
||||
bundle = self.manager.export()
|
||||
self.assertEqual(bundle["subscriptionKey"], "e" * 64)
|
||||
# A key the config names is the config's: not exported.
|
||||
named = im.Manager(self.config, {**self.spec, "subscriptionKeyFile": "/run/secrets/k"}, netfilter=FakeNetfilter())
|
||||
self.assertIsNone(named.export()["subscriptionKey"])
|
||||
|
||||
other = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(other.cleanup)
|
||||
target_path = os.path.join(other.name, "inbounds", "subscription-key")
|
||||
target = im.Manager(self.config, {**self.spec, "subscriptionKeyStateFile": target_path},
|
||||
clock=self.clock, netfilter=FakeNetfilter(), webhooks=im.Webhooks([]))
|
||||
report = {"skipped": []}
|
||||
target._import_subscription_key(bundle["subscriptionKey"], False, report)
|
||||
self.assertTrue(report["subscriptionKey"])
|
||||
with open(target_path, encoding="utf-8") as handle:
|
||||
self.assertEqual(handle.read().strip(), "e" * 64)
|
||||
self.assertEqual(os.stat(target_path).st_mode & 0o777, 0o600)
|
||||
# One of its own already: kept, unless replace.
|
||||
report = {"skipped": []}
|
||||
target._import_subscription_key("f" * 64, False, report)
|
||||
self.assertIn("kept this server's", report["skipped"][0])
|
||||
target._import_subscription_key("f" * 64, True, report)
|
||||
with open(target_path, encoding="utf-8") as handle:
|
||||
self.assertEqual(handle.read().strip(), "f" * 64)
|
||||
# None to keep it in: said so.
|
||||
report = {"skipped": []}
|
||||
im.Manager(self.config, {**self.spec, "subscriptionKeyStateFile": None},
|
||||
netfilter=FakeNetfilter())._import_subscription_key("f" * 64, False, report)
|
||||
self.assertIn("keyFile is false", report["skipped"][0])
|
||||
with self.assertRaises(im.ApiError):
|
||||
self.manager.import_bundle({**bundle, "subscriptionKey": "short\nline"})
|
||||
|
||||
def test_import_refuses_garbage(self):
|
||||
for bad in (None, {}, {"format": "x"}, {"format": im.BUNDLE_FORMAT, "version": 99}):
|
||||
with self.assertRaises(im.ApiError):
|
||||
self.manager.import_bundle(bad)
|
||||
bundle = self.manager.export()
|
||||
bundle["runtime"]["users"]["evil"] = {"order": 1, "uuid": "nope", "password": "x"}
|
||||
with self.assertRaises(im.ApiError) as raised:
|
||||
self.manager.import_bundle(bundle)
|
||||
self.assertEqual(raised.exception.status, 400)
|
||||
|
||||
def test_import_refuses_what_would_escape_or_break_its_files(self):
|
||||
clean = self.manager.export()
|
||||
awg_state = os.path.join(self.tmp.name, "awg.json")
|
||||
self.spec["listeners"][2]["amneziaWg"] = {"stateFile": awg_state, "interfaceName": "awgi-awg", "subnet": "10.66.0.0/24"}
|
||||
key = base64.b64encode(b"k" * 32).decode()
|
||||
bad_parts = [
|
||||
# A tag is a directory under the Salamander state: not a way out of it.
|
||||
("salamander", {"../../escape": "password"}),
|
||||
("salamander", {"hy2": "two\nlines"}),
|
||||
# A key with a line break would add a line (PostUp = ...) to what awg-quick runs.
|
||||
("amneziaWg", {"awg": {"version": 1, "server": {"privateKey": key + "\nPostUp = touch /x"}, "users": {}}}),
|
||||
("amneziaWg", {"awg": {"version": 1, "server": {}, "users": {"bob": {"offset": 2, "presharedKey": "short"}}}}),
|
||||
# A state of another version: its keys would be made anew.
|
||||
("amneziaWg", {"awg": {"server": {"privateKey": key}, "users": {}}}),
|
||||
# The renderers and the collector read these at every start and run.
|
||||
("state", {"users": {"alice": {"periodStart": "yesterday"}}, "slots": {}}),
|
||||
("stats", {"days": {"2026-10-01": {"user": {"alice": {"up": "lots"}}}}}),
|
||||
]
|
||||
for section, value in bad_parts:
|
||||
bundle = copy.deepcopy(clean)
|
||||
bundle[section] = value
|
||||
with self.subTest(section=section, value=value), self.assertRaises(im.ApiError) as raised:
|
||||
self.manager.import_bundle(bundle)
|
||||
self.assertEqual(raised.exception.status, 400)
|
||||
self.assertFalse(os.path.exists(os.path.join(self.tmp.name, "escape")))
|
||||
self.assertFalse(os.path.exists(awg_state))
|
||||
|
||||
def test_import_takes_declared_names_outside_the_runtime_pattern(self):
|
||||
# Declared tags and user names are any string; only a path made of one is checked.
|
||||
awg_state = os.path.join(self.tmp.name, "awg.json")
|
||||
salamander_file = os.path.join(self.tmp.name, "declared-salamander")
|
||||
self.spec["listeners"][2]["amneziaWg"] = {"stateFile": awg_state, "interfaceName": "awgi-awg", "subnet": "10.66.0.0/24"}
|
||||
self.spec["listeners"][0]["salamanderStateFile"] = salamander_file
|
||||
tag = self.spec["listeners"][0]["tag"]
|
||||
bundle = self.manager.export()
|
||||
bundle["amneziaWg"] = {"awg": {"version": 1, "server": {}, "users": {"bob smith": {"offset": 3}}}}
|
||||
bundle["salamander"] = {tag: "secret-password"}
|
||||
report = self.manager.import_bundle(bundle)
|
||||
self.assertEqual(report["amneziaWg"], ["awg"])
|
||||
self.assertEqual(report["salamander"], [tag])
|
||||
with open(salamander_file, encoding="utf-8") as handle:
|
||||
self.assertEqual(handle.read(), "secret-password\n")
|
||||
|
||||
def test_import_refuses_a_runtime_user_named_as_a_declared_one(self):
|
||||
bundle = self.manager.export()
|
||||
declared = sorted(self.spec["users"])[0]
|
||||
bundle["runtime"]["users"][declared] = {"order": 900, "uuid": str(uuid.uuid4()), "password": "x" * 16}
|
||||
with self.assertRaises(im.ApiError) as raised:
|
||||
self.manager.import_bundle(bundle)
|
||||
self.assertEqual(raised.exception.status, 409)
|
||||
self.assertNotIn(declared, rt.load_spool(self.spool)[0]["users"])
|
||||
|
||||
def test_a_malformed_state_entry_is_left_out(self):
|
||||
policy.write_json(self.config["stateFile"], {"users": {"alice": {"periodStart": "x"}, "bob": {"periodStart": 5}},
|
||||
"slots": {"alice": "1", "bob": 2}})
|
||||
state = policy.load_state(self.config["stateFile"])
|
||||
self.assertEqual(state["users"], {"bob": {"periodStart": 5}})
|
||||
self.assertEqual(state["slots"], {"bob": 2})
|
||||
|
||||
|
||||
class Api(ManagerTest):
|
||||
def test_routes(self):
|
||||
status, value = im.handle_api(self.manager, "POST", "/api/v1/users", {}, {"name": "alice", "policy": {"ipLimit": 2}})
|
||||
self.assertEqual(status, 201)
|
||||
self.assertEqual(value["policy"]["ipLimit"], 2)
|
||||
status, value = im.handle_api(self.manager, "PATCH", "/api/v1/users/alice", {}, {"trafficLimit": "1G", "unset": ["ipLimit"]})
|
||||
self.assertIsNone(value["policy"]["ipLimit"])
|
||||
status, value = im.handle_api(self.manager, "POST", "/api/v1/users/alice/disable", {}, None)
|
||||
self.assertFalse(value["active"])
|
||||
with self.assertRaises(im.ApiError) as raised:
|
||||
im.handle_api(self.manager, "PUT", "/api/v1/users/alice", {}, {})
|
||||
self.assertEqual(raised.exception.status, 405)
|
||||
with self.assertRaises(im.ApiError) as raised:
|
||||
im.handle_api(self.manager, "GET", "/api/v1/users/nobody", {}, None)
|
||||
self.assertEqual(raised.exception.status, 404)
|
||||
|
||||
def request(self, path, method="GET", body=None, headers=None, sock=None):
|
||||
connection = http.client.HTTPConnection("localhost")
|
||||
connection.sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
|
||||
connection.sock.connect(sock)
|
||||
payload = body if isinstance(body, bytes) or body is None else json.dumps(body).encode()
|
||||
connection.request(method, path, body=payload, headers=headers or {})
|
||||
response = connection.getresponse()
|
||||
return response.status, dict(response.getheaders()), response.read()
|
||||
|
||||
def test_over_the_sockets(self):
|
||||
api_socket = os.path.join(self.tmp.name, "api.sock")
|
||||
sub_socket = os.path.join(self.tmp.name, "sub.sock")
|
||||
misses = mock.Mock()
|
||||
servers = [im.unix_server(api_socket, im._handler(self.manager, "api", []), None, 0o600),
|
||||
im.unix_server(sub_socket, im._handler(self.manager, "sub", [], misses), None, 0o600)]
|
||||
for server in servers:
|
||||
threading.Thread(target=server.serve_forever, daemon=True).start()
|
||||
self.addCleanup(server.shutdown)
|
||||
status, _, body = self.request("/api/v1/users", "POST", {"name": "alice"}, sock=api_socket)
|
||||
self.assertEqual(status, 201, body)
|
||||
status, _, body = self.request("/api/v1/users/alice", sock=api_socket)
|
||||
self.assertEqual(json.loads(body)["name"], "alice")
|
||||
status, _, body = self.request("/api/v1/users", "POST", b"x", sock=api_socket)
|
||||
self.assertEqual(status, 400)
|
||||
# The subscription socket answers subscriptions only.
|
||||
self.write_rendered({"subscriptions": [{"user": "alice", "token": "c" * 32, "body": "eA=="}]})
|
||||
status, headers, body = self.request("/sub/" + "c" * 32, sock=sub_socket)
|
||||
self.assertEqual((status, body), (200, b"eA=="))
|
||||
self.assertIn("subscription-userinfo", {k.lower() for k in headers})
|
||||
status, headers, _ = self.request("/api/v1/users", sock=sub_socket)
|
||||
self.assertEqual(status, 404)
|
||||
self.assertEqual(headers.get("X-Content-Type-Options"), "nosniff")
|
||||
# A miss is noted by the address the web server says it came from, when that is one.
|
||||
self.request("/sub/" + "d" * 32, sock=sub_socket, headers={"X-Real-IP": "203.0.113.7"})
|
||||
self.request("/sub/" + "d" * 32, sock=sub_socket, headers={"X-Forwarded-For": "10.0.0.1, 198.51.100.1"})
|
||||
self.request("/sub/" + "d" * 32, sock=sub_socket, headers={"X-Real-IP": "forged words"})
|
||||
self.assertEqual([c.args[0] for c in misses.note.call_args_list][-3:], ["203.0.113.7", "198.51.100.1", "unix"])
|
||||
# The format from the query or the client; a page that names the address it was asked at.
|
||||
status, headers, body = self.request("/sub/" + "c" * 32 + "?format=sing-box", sock=sub_socket)
|
||||
self.assertEqual(json.loads(body)["route"]["final"], "direct")
|
||||
del self.config["subscriptions"]["baseUrl"]
|
||||
status, headers, body = self.request("/sub/" + "c" * 32, sock=sub_socket, headers={
|
||||
"User-Agent": "Mozilla/5.0", "Accept": "text/html", "Host": "vpn.example.org", "X-Forwarded-Proto": "https"})
|
||||
self.assertEqual(status, 200)
|
||||
self.assertIn("https://vpn.example.org/sub/" + "c" * 32, body.decode())
|
||||
status, headers, body = self.request("/sub/" + "c" * 32, sock=sub_socket, headers={
|
||||
"User-Agent": "Mozilla/5.0", "Accept": "text/html", "Host": "evil\"><script>"})
|
||||
self.assertNotIn("evil", body.decode())
|
||||
|
||||
def test_tokens(self):
|
||||
path = os.path.join(self.tmp.name, "tokens")
|
||||
with open(path, "w", encoding="utf-8") as handle:
|
||||
handle.write("# bots\nbot:s3cret\nplain\n")
|
||||
self.assertEqual(im.read_tokens(path), [b"s3cret", b"plain"])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,244 @@
|
||||
#!/usr/bin/env python3
|
||||
|
||||
import datetime
|
||||
import json
|
||||
import os
|
||||
import tempfile
|
||||
import time
|
||||
import unittest
|
||||
|
||||
import inbound_policy as policy
|
||||
import inbound_runtime as rt
|
||||
from proxy_inbound import render_xray_inbound
|
||||
|
||||
|
||||
def midnight(year, month, day):
|
||||
return int(time.mktime(datetime.date(year, month, day).timetuple()))
|
||||
|
||||
|
||||
class Parsing(unittest.TestCase):
|
||||
def test_sizes_are_binary(self):
|
||||
self.assertEqual(policy.parse_size("50G"), 50 * 1024**3)
|
||||
self.assertEqual(policy.parse_size("1.5T"), int(1.5 * 1024**4))
|
||||
self.assertEqual(policy.parse_size("512MiB"), 512 * 1024**2)
|
||||
self.assertEqual(policy.parse_size(1000), 1000)
|
||||
for none in (None, 0, "", "none", "unlimited", "0"):
|
||||
self.assertIsNone(policy.parse_size(none))
|
||||
for bad in ("lots", "-5G", -1, 1.5, "5X"):
|
||||
with self.assertRaises(policy.PolicyError):
|
||||
policy.parse_size(bad)
|
||||
|
||||
def test_rates_are_decimal_bits(self):
|
||||
self.assertEqual(policy.parse_rate("10M"), 10_000_000)
|
||||
self.assertEqual(policy.parse_rate("500k"), 500_000)
|
||||
self.assertEqual(policy.parse_rate("1Gbit"), 1_000_000_000)
|
||||
self.assertIsNone(policy.parse_rate("0"))
|
||||
|
||||
def test_speed_forms(self):
|
||||
self.assertEqual(policy.parse_speed("20M"), {"up": 20_000_000, "down": 20_000_000})
|
||||
self.assertEqual(policy.parse_speed("20M/5M"), {"up": 5_000_000, "down": 20_000_000})
|
||||
self.assertEqual(policy.parse_speed({"down": "8M"}), {"up": None, "down": 8_000_000})
|
||||
self.assertIsNone(policy.parse_speed("0/0"))
|
||||
with self.assertRaises(policy.PolicyError):
|
||||
policy.parse_speed({"sideways": "1M"})
|
||||
|
||||
def test_times(self):
|
||||
now = 1_800_000_000
|
||||
self.assertEqual(policy.parse_time("+30d", now), now + 30 * 86400)
|
||||
self.assertEqual(policy.parse_time("+2h", now), now + 7200)
|
||||
# A date is the end of that day.
|
||||
self.assertEqual(policy.parse_time("2026-12-31"), midnight(2027, 1, 1))
|
||||
self.assertEqual(policy.parse_time("2026-12-31T00:00:00+00:00"), 1798675200)
|
||||
self.assertEqual(policy.parse_time(str(now)), now)
|
||||
self.assertIsNone(policy.parse_time("never"))
|
||||
with self.assertRaises(policy.PolicyError):
|
||||
policy.parse_time("next tuesday")
|
||||
|
||||
|
||||
class Policies(unittest.TestCase):
|
||||
def test_normalize_and_store_round_trip(self):
|
||||
fields = policy.normalize(
|
||||
{"trafficLimit": "10G", "speedLimit": "10M/2M", "ipLimit": "2", "trafficPeriod": "monthly",
|
||||
"meta": {"telegram": "42"}, "enabled": False, "expiresAt": "+1d"},
|
||||
now=1_800_000_000,
|
||||
)
|
||||
self.assertEqual(fields["trafficLimit"], 10 * 1024**3)
|
||||
self.assertEqual(fields["ipLimit"], 2)
|
||||
self.assertEqual(fields["expiresAt"], 1_800_086_400)
|
||||
self.assertEqual(policy.check_stored(fields), fields)
|
||||
self.assertIsNone(policy.normalize({"expiresAt": 0})["expiresAt"])
|
||||
|
||||
def test_unknown_and_bad_fields(self):
|
||||
for bad in ({"colour": "red"}, {"enabled": "yes"}, {"trafficPeriod": "yearly"}, {"ipLimit": -1},
|
||||
{"meta": {"a b": "x"}}, {"meta": {"k": 5}}):
|
||||
with self.assertRaises(policy.PolicyError, msg=bad):
|
||||
policy.normalize(bad)
|
||||
|
||||
def test_stored_overrides_declared_field_by_field(self):
|
||||
declared = {"trafficLimit": 100, "ipLimit": 3}
|
||||
stored = {"ipLimit": None, "enabled": False}
|
||||
merged = policy.effective(declared, stored)
|
||||
self.assertEqual(merged["trafficLimit"], 100)
|
||||
self.assertIsNone(merged["ipLimit"])
|
||||
self.assertFalse(merged["enabled"])
|
||||
|
||||
def test_declared_nulls_do_not_override(self):
|
||||
spec = {"users": {"phone": {"policy": {"trafficLimit": None, "ipLimit": 2, "expiresAt": None}}}}
|
||||
self.assertEqual(policy.declared_policies(spec), {"phone": {"ipLimit": 2}})
|
||||
|
||||
|
||||
class Traffic(unittest.TestCase):
|
||||
STATS = {
|
||||
"days": {
|
||||
"2026-10-01": {"user": {"a": {"up": 10, "down": 90}, "b": {"up": 1, "down": 1}}},
|
||||
"2026-10-02": {"user": {"a": {"up": 5, "down": 5}}},
|
||||
}
|
||||
}
|
||||
|
||||
def test_usage_from_period_start_less_baseline(self):
|
||||
start = midnight(2026, 10, 1) + 3600
|
||||
self.assertEqual(policy.used_bytes(self.STATS, {"periodStart": start, "baselineUp": 10, "baselineDown": 30}, "a"), 70)
|
||||
self.assertEqual(policy.period_traffic(self.STATS, {"periodStart": start, "baselineDown": 30}, "a"), (15, 65))
|
||||
self.assertEqual(policy.used_bytes(self.STATS, {"periodStart": midnight(2026, 10, 2)}, "a"), 10)
|
||||
# Not measured yet: the history before the manager saw the user does not count.
|
||||
self.assertEqual(policy.used_bytes(self.STATS, {}, "a"), 0)
|
||||
self.assertEqual(policy.used_bytes(self.STATS, {"periodStart": 1, "baselineUp": 500, "baselineDown": 500}, "a"), 0)
|
||||
|
||||
def test_start_period_takes_the_day_so_far(self):
|
||||
now = midnight(2026, 10, 1) + 7200
|
||||
state = policy.start_period(self.STATS, "a", now)
|
||||
self.assertEqual((state["baselineUp"], state["baselineDown"]), (10, 90))
|
||||
self.assertEqual(policy.used_bytes(self.STATS, state, "a"), 10)
|
||||
|
||||
def test_monthly_periods_renew_at_midnight_on_the_anchor_day(self):
|
||||
state = {"periodStart": midnight(2026, 1, 31) + 5000, "baselineUp": 7, "anchorDay": 31}
|
||||
pol = {"trafficPeriod": "monthly"}
|
||||
self.assertEqual(policy.period_end(pol, state), midnight(2026, 2, 28))
|
||||
self.assertTrue(policy.roll_period(pol, state, midnight(2026, 3, 5)))
|
||||
# Feb 28, then Mar 31 is still ahead: the anchor day survives the short month.
|
||||
self.assertEqual(state["periodStart"], midnight(2026, 2, 28))
|
||||
self.assertEqual(state["baselineUp"], 0)
|
||||
self.assertEqual(policy.period_end(pol, state), midnight(2026, 3, 31))
|
||||
self.assertFalse(policy.roll_period(pol, state, midnight(2026, 3, 6)))
|
||||
|
||||
def test_no_period_never_rolls(self):
|
||||
state = {"periodStart": 1, "baselineUp": 3}
|
||||
self.assertFalse(policy.roll_period({"trafficPeriod": None}, state, time.time()))
|
||||
self.assertEqual(state["baselineUp"], 3)
|
||||
|
||||
def test_durations(self):
|
||||
self.assertEqual(policy.parse_duration("30d"), 30 * 86400)
|
||||
self.assertEqual(policy.parse_duration("+12h"), 12 * 3600)
|
||||
self.assertEqual(policy.parse_duration(90), 90)
|
||||
for none in (None, 0, "", "none", "0d"):
|
||||
self.assertIsNone(policy.parse_duration(none))
|
||||
for bad in ("30 days", "-1d", -5, 1.5):
|
||||
with self.assertRaises(policy.PolicyError):
|
||||
policy.parse_duration(bad)
|
||||
self.assertEqual(policy.normalize({"expiresAfter": "1w"}), {"expiresAfter": 7 * 86400})
|
||||
policy.check_stored({"expiresAfter": 604800})
|
||||
|
||||
def test_on_hold_until_an_expiry_is_set(self):
|
||||
self.assertTrue(policy.on_hold(policy.effective({"expiresAfter": 86400}, None)))
|
||||
# A term started, or an expiry given by hand: no longer on hold.
|
||||
self.assertFalse(policy.on_hold(policy.effective({"expiresAfter": 86400}, {"expiresAt": 2_000_000_000})))
|
||||
self.assertFalse(policy.on_hold(policy.effective(None, None)))
|
||||
self.assertTrue(policy.status(policy.effective({"expiresAfter": 86400}, None), 0, 2_000_000_000)["active"])
|
||||
|
||||
def test_status_reasons(self):
|
||||
now = 2_000_000_000
|
||||
self.assertEqual(policy.status(policy.effective(None, None), 10**12, now), {"active": True, "reasons": []})
|
||||
pol = policy.effective({"trafficLimit": 100, "expiresAt": now - 1}, {"enabled": False})
|
||||
self.assertEqual(policy.status(pol, 100, now)["reasons"], ["disabled", "expired", "traffic"])
|
||||
self.assertTrue(policy.status(policy.effective({"trafficLimit": 100}, None), 99, now)["active"])
|
||||
|
||||
|
||||
class Statuses(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.dir = tempfile.TemporaryDirectory()
|
||||
base = self.dir.name
|
||||
self.manager = {
|
||||
"policyFile": os.path.join(base, "policy.json"),
|
||||
"stateFile": os.path.join(base, "state.json"),
|
||||
"statsFile": os.path.join(base, "stats.json"),
|
||||
"speedLimits": True,
|
||||
}
|
||||
|
||||
def tearDown(self):
|
||||
self.dir.cleanup()
|
||||
|
||||
def write(self, key, value):
|
||||
with open(self.manager[key], "w", encoding="utf-8") as handle:
|
||||
json.dump(value, handle)
|
||||
|
||||
def test_without_the_manager_nothing_changes(self):
|
||||
self.assertEqual(policy.statuses({"users": {"a": {}}}, []), {})
|
||||
|
||||
def test_statuses_from_the_files(self):
|
||||
now = time.time()
|
||||
today = policy.day_key(now)
|
||||
self.write("policyFile", {"users": {"rt": {"trafficLimit": 50}, "phone": {"speedLimit": {"up": 1000, "down": 1000}}}})
|
||||
self.write("stateFile", {"users": {"rt": {"periodStart": int(now) - 60}}, "slots": {"phone": 3, "rt": 4}})
|
||||
self.write("statsFile", {"days": {today: {"user": {"rt": {"up": 30, "down": 30}}}}})
|
||||
spec = {"manager": self.manager, "users": {"phone": {"policy": {"expiresAt": None}}}}
|
||||
views = policy.statuses(spec, ["rt"], now)
|
||||
self.assertEqual(views["rt"], {"active": False, "reasons": ["traffic"], "level": 0})
|
||||
self.assertEqual(views["phone"], {"active": True, "reasons": [], "level": 3})
|
||||
|
||||
def test_a_broken_policy_file_is_no_policy(self):
|
||||
with open(self.manager["policyFile"], "w", encoding="utf-8") as handle:
|
||||
handle.write("{nope")
|
||||
spec = {"manager": self.manager, "users": {"a": {}}}
|
||||
self.assertTrue(policy.statuses(spec, [])["a"]["active"])
|
||||
|
||||
|
||||
def listener(tag, kind, users, **extra):
|
||||
base = {"tag": tag, "type": kind, "port": 443, "listen": "::", "via": "direct", "users": users,
|
||||
"flow": None, "fallbacks": [], "transport": {"type": "raw", "path": "/"},
|
||||
"tls": {"enable": False}, "reality": {"enable": False}, "hysteria": {}}
|
||||
base.update(extra)
|
||||
return base
|
||||
|
||||
|
||||
def user(name, **fields):
|
||||
return {"name": name, "uuid": "b831381d-6324-4d53-ad4f-8cda48b30811", "password": "pw-" + name, **fields}
|
||||
|
||||
|
||||
class MergeWithStatuses(unittest.TestCase):
|
||||
def spec(self):
|
||||
return {
|
||||
"runtime": None,
|
||||
"users": {},
|
||||
"listeners": [
|
||||
listener("vl", "vless", [user("a"), user("b")]),
|
||||
listener("sk", "socks", [user("a")]),
|
||||
listener("ss", "shadowsocks", [user("b")], method="aes-128-gcm"),
|
||||
],
|
||||
}
|
||||
|
||||
def test_inactive_users_leave_xray_but_listeners_that_can_stay_do(self):
|
||||
statuses = {"a": {"active": False, "level": 0}, "b": {"active": True, "level": 7}}
|
||||
merged, _, warnings = rt.merge_state(self.spec(), {"users": {}, "listeners": {}}, statuses=statuses)
|
||||
tags = [l["tag"] for l in merged["listeners"]]
|
||||
self.assertEqual(tags, ["vl", "ss"])
|
||||
self.assertIn("listener 'sk' has no active users; not started", warnings)
|
||||
inbound = render_xray_inbound(merged["listeners"][0])
|
||||
self.assertEqual([(c["email"], c.get("level")) for c in inbound["settings"]["clients"]], [("b", 7)])
|
||||
ss = render_xray_inbound(merged["listeners"][1])
|
||||
self.assertEqual(ss["settings"]["level"], 7)
|
||||
|
||||
def test_a_vless_listener_with_everyone_off_runs_empty(self):
|
||||
statuses = {"a": {"active": False}, "b": {"active": False}}
|
||||
merged, _, _ = rt.merge_state(self.spec(), {"users": {}, "listeners": {}}, statuses=statuses)
|
||||
vl = next(l for l in merged["listeners"] if l["tag"] == "vl")
|
||||
self.assertEqual(render_xray_inbound(vl)["settings"]["clients"], [])
|
||||
|
||||
def test_no_statuses_keeps_everyone(self):
|
||||
merged, _, warnings = rt.merge_state(self.spec(), {"users": {}, "listeners": {}})
|
||||
self.assertEqual(len(merged["listeners"]), 3)
|
||||
self.assertEqual(warnings, [])
|
||||
self.assertTrue(all(u["active"] for l in merged["listeners"] for u in l["users"]))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,272 @@
|
||||
#!/usr/bin/env python3
|
||||
|
||||
import base64
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
import inbound_subscription as sub
|
||||
import proxy_inbound
|
||||
|
||||
UUID = "11111111-2222-3333-4444-555555555555"
|
||||
LINKS = {
|
||||
"reality": f"vless://{UUID}@vpn.example.com:443?type=tcp&security=reality&sni=www.microsoft.com&fp=chrome"
|
||||
"&pbk=jNXHt1yRo0vDuchQlIP6Z0ZvjT3KtzVI-T4E7RoLJS0&sid=0123abcd&flow=xtls-rprx-vision#reality",
|
||||
"ws": f"vless://{UUID}@vpn.example.com:443?type=ws&security=tls&sni=vpn.example.com&path=%2Fws"
|
||||
"&host=vpn.example.com&fp=chrome&alpn=h2%2Chttp%2F1.1#ws",
|
||||
"grpc": f"vless://{UUID}@vpn.example.com:443?type=grpc&security=tls&sni=vpn.example.com&serviceName=gs#grpc",
|
||||
"xhttp": f"vless://{UUID}@vpn.example.com:443?type=xhttp&security=tls&sni=vpn.example.com&path=%2Fx#xh",
|
||||
"trojan": "trojan://pass@vpn.example.com:8443?security=tls&sni=vpn.example.com&type=httpupgrade&path=%2Fhu#tr",
|
||||
"hy2": "hysteria2://pw@vpn.example.com:443?sni=vpn.example.com&obfs=salamander&obfs-password=xx&mport=20000-20010#hy2",
|
||||
}
|
||||
|
||||
|
||||
def rendered_for(user="alice"):
|
||||
links = [{"tag": tag, "user": user, "link": link, "outbound": proxy_inbound.client_outbound(link, tag)}
|
||||
for tag, link in LINKS.items()]
|
||||
links.append({"tag": "reality", "user": user, "link": LINKS["reality"], "variant": "onion",
|
||||
"outbound": proxy_inbound.client_outbound(LINKS["reality"], "reality")})
|
||||
links.append({"tag": "awg", "user": user, "link": "vpn://x", "config": "[Interface]", "outbound": None})
|
||||
links.append({"tag": "ws", "user": "bob", "link": LINKS["ws"], "outbound": None})
|
||||
body = base64.b64encode("\n".join(LINKS.values()).encode()).decode()
|
||||
return {"links": links, "subscriptions": [{"user": user, "token": "a" * 32, "body": body}]}
|
||||
|
||||
|
||||
ROW = {"name": "alice", "active": True, "reasons": [], "onHold": False, "expiresAt": 2_000_000_000,
|
||||
"policy": {"expiresAfter": None},
|
||||
"traffic": {"up": 1, "down": 1023, "used": 1024, "limit": 4096, "periodEnd": 1_900_000_000}}
|
||||
|
||||
|
||||
class Formats(unittest.TestCase):
|
||||
def test_pick_by_client(self):
|
||||
cases = {
|
||||
"ClashMetaForAndroid/2.11.2.Meta": "clash",
|
||||
"clash-verge/v2.0.0": "clash",
|
||||
"FlClash/v0.8": "clash",
|
||||
"mihomo/1.19": "clash",
|
||||
"Stash/2.4.6 Clash/1.9.0": "clash",
|
||||
"SFA/1.11.4 (Android 14; sing-box 1.11.4)": "sing-box",
|
||||
"SFI/1.12.0": "sing-box",
|
||||
"sing-box 1.12.0": "sing-box",
|
||||
# Hiddify names Clash and sing-box after "like": the links serve it best.
|
||||
"HiddifyNext/2.5.7 (android) like ClashMeta v2ray sing-box": "base64",
|
||||
"v2rayNG/1.9.1": "base64",
|
||||
"Happ/1.0": "base64",
|
||||
"": "base64",
|
||||
}
|
||||
for agent, expected in cases.items():
|
||||
self.assertEqual(sub.pick_format(None, agent, "*/*"), expected, agent)
|
||||
browser = "Mozilla/5.0 (X11; Linux x86_64) Firefox/131.0"
|
||||
self.assertEqual(sub.pick_format(None, browser, "text/html,application/xhtml+xml"), "html")
|
||||
# A client that says Mozilla but wants no page.
|
||||
self.assertEqual(sub.pick_format(None, browser, "*/*"), "base64")
|
||||
self.assertEqual(sub.pick_format("clash", "v2rayNG/1.9", ""), "clash")
|
||||
self.assertEqual(sub.pick_format("nonsense", "v2rayNG/1.9", ""), "base64")
|
||||
|
||||
def test_entries_are_the_users_links_named_apart(self):
|
||||
names = [e["name"] for e in sub.entries(rendered_for(), "alice")]
|
||||
self.assertEqual(names, ["reality", "ws", "grpc", "xhttp", "trojan", "hy2", "reality-onion"])
|
||||
|
||||
def test_names_stay_clear_of_the_groups(self):
|
||||
rendered = {"links": [{"tag": tag, "user": "u", "link": LINKS["ws"], "outbound": None}
|
||||
for tag in ("proxy", "AUTO", "direct", "proxy")]}
|
||||
self.assertEqual([e["name"] for e in sub.entries(rendered, "u")], ["proxy-2", "AUTO-2", "direct-2", "proxy-3"])
|
||||
|
||||
def test_sing_box_config(self):
|
||||
config = sub.sing_box_config(sub.entries(rendered_for(), "alice"))
|
||||
tags = [o["tag"] for o in config["outbounds"]]
|
||||
# XHTTP only XRay dials: left out of the config.
|
||||
self.assertNotIn("xhttp", tags)
|
||||
self.assertEqual(tags[:2], ["proxy", "auto"])
|
||||
self.assertEqual(config["outbounds"][0]["outbounds"][0], "auto")
|
||||
self.assertIn("reality-onion", config["outbounds"][1]["outbounds"])
|
||||
self.assertEqual(config["route"]["final"], "proxy")
|
||||
empty = sub.sing_box_config([])
|
||||
self.assertEqual(empty["route"]["final"], "direct")
|
||||
self.assertEqual([o["tag"] for o in empty["outbounds"]], ["direct"])
|
||||
sing_box = os.environ.get("SING_BOX")
|
||||
if sing_box:
|
||||
for value in (config, empty):
|
||||
with tempfile.NamedTemporaryFile("w", suffix=".json") as handle:
|
||||
json.dump(value, handle)
|
||||
handle.flush()
|
||||
done = subprocess.run([sing_box, "check", "-c", handle.name], capture_output=True, text=True)
|
||||
self.assertEqual(done.returncode, 0, done.stderr)
|
||||
|
||||
def test_clash_proxies(self):
|
||||
config = sub.clash_config(sub.entries(rendered_for(), "alice"))
|
||||
proxies = {p["name"]: p for p in config["proxies"]}
|
||||
self.assertNotIn("xhttp", proxies)
|
||||
reality = proxies["reality"]
|
||||
self.assertEqual((reality["type"], reality["server"], reality["port"], reality["uuid"]),
|
||||
("vless", "vpn.example.com", 443, UUID))
|
||||
self.assertEqual(reality["flow"], "xtls-rprx-vision")
|
||||
self.assertEqual(reality["servername"], "www.microsoft.com")
|
||||
self.assertEqual(reality["reality-opts"], {"public-key": "jNXHt1yRo0vDuchQlIP6Z0ZvjT3KtzVI-T4E7RoLJS0",
|
||||
"short-id": "0123abcd"})
|
||||
self.assertEqual(reality["client-fingerprint"], "chrome")
|
||||
self.assertEqual(reality["network"], "tcp")
|
||||
self.assertEqual(proxies["ws"]["ws-opts"], {"path": "/ws", "headers": {"Host": "vpn.example.com"}})
|
||||
self.assertEqual(proxies["ws"]["alpn"], ["h2", "http/1.1"])
|
||||
self.assertEqual(proxies["grpc"]["grpc-opts"], {"grpc-service-name": "gs"})
|
||||
trojan = proxies["trojan"]
|
||||
self.assertEqual((trojan["type"], trojan["sni"], trojan["network"]), ("trojan", "vpn.example.com", "ws"))
|
||||
self.assertTrue(trojan["ws-opts"]["v2ray-http-upgrade"])
|
||||
hy2 = proxies["hy2"]
|
||||
self.assertEqual((hy2["type"], hy2["obfs"], hy2["obfs-password"], hy2["ports"]),
|
||||
("hysteria2", "salamander", "xx", "20000-20010"))
|
||||
groups = {g["name"]: g for g in config["proxy-groups"]}
|
||||
self.assertEqual(groups["PROXY"]["proxies"][0], "auto")
|
||||
self.assertEqual(config["rules"][-1], "MATCH,PROXY")
|
||||
self.assertEqual(sub.clash_proxy("x", {"type": "shadowsocks", "method": "aes-128-gcm", "password": "p",
|
||||
"server": "h", "server_port": 1, "plugin": "obfs-local"}), None)
|
||||
self.assertEqual(sub.clash_proxy("x", {"type": "shadowsocks", "method": "aes-128-gcm", "password": "p",
|
||||
"server": "h", "server_port": 1})["cipher"], "aes-128-gcm")
|
||||
|
||||
def test_render(self):
|
||||
rendered = rendered_for()
|
||||
body_b64 = rendered["subscriptions"][0]["body"]
|
||||
args = (rendered, "alice", body_b64, ROW, "https://vpn.example.com/sub/" + "a" * 32, "VPN alice", {})
|
||||
body, kind = sub.render("base64", *args)
|
||||
self.assertEqual((body, kind), (body_b64.encode(), "text/plain; charset=utf-8"))
|
||||
body, _ = sub.render("links", *args)
|
||||
self.assertEqual(body.decode().split("\n")[0], LINKS["reality"])
|
||||
body, kind = sub.render("clash", *args)
|
||||
self.assertEqual(kind, "text/yaml; charset=utf-8")
|
||||
self.assertIn("proxies", json.loads(body))
|
||||
body, kind = sub.render("sing-box", *args)
|
||||
self.assertEqual(json.loads(body)["route"]["final"], "proxy")
|
||||
|
||||
def test_page(self):
|
||||
rendered = rendered_for()
|
||||
url = "https://vpn.example.com/sub/" + "a" * 32
|
||||
row = {**ROW, "name": "<b>alice</b>"}
|
||||
page = sub.html_page(row, sub.entries(rendered, "alice"), url, "VPN <b>", {"supportUrl": "https://t.me/x"}, "en")
|
||||
self.assertIn("VPN <b>", page)
|
||||
self.assertNotIn("<b>", page)
|
||||
self.assertIn("User: <b>alice</b>", page)
|
||||
# Named in the title already: not again.
|
||||
self.assertNotIn("Пользователь", sub.html_page(ROW, [], url, "VPN alice", {}, "ru"))
|
||||
self.assertIn("Пользователь: alice", sub.html_page(ROW, [], url, "Stage", {}, "ru"))
|
||||
self.assertIn("Active", page)
|
||||
self.assertIn("1.0 KiB of 4.0 KiB", page)
|
||||
self.assertIn('<rect class="fill" width="25"', page)
|
||||
self.assertIn(f'data-qr="{url}"', page)
|
||||
self.assertIn("happ://add/" + url, page)
|
||||
self.assertIn("v2rayng://install-config?url=https%3A%2F%2Fvpn.example.com", page)
|
||||
self.assertIn("https://t.me/x", page)
|
||||
# Share links are attributes, escaped: & stays &.
|
||||
self.assertIn("type=tcp&security=reality", page)
|
||||
held = sub.html_page({**ROW, "onHold": True, "expiresAt": None, "policy": {"expiresAfter": 30 * 86400}},
|
||||
[], url, "VPN", {}, "ru")
|
||||
self.assertIn("Начнётся с первого подключения", held)
|
||||
self.assertIn("30d с первого подключения", held)
|
||||
off = sub.html_page({**ROW, "active": False, "reasons": ["expired", "traffic"]}, [], url, "VPN", {}, "en")
|
||||
self.assertIn("expired, out of traffic", off)
|
||||
self.assertEqual(sub.language("ru-RU,ru;q=0.9,en;q=0.8"), "ru")
|
||||
self.assertEqual(sub.language("de-DE,en;q=0.5"), "en")
|
||||
self.assertEqual(sub.language(""), "en")
|
||||
|
||||
def test_apps_for_the_system(self):
|
||||
url = "https://vpn.example.com/sub/" + "a" * 32
|
||||
agents = {
|
||||
"android": "Mozilla/5.0 (Linux; Android 14; Pixel 8) AppleWebKit/537.36 Chrome/130.0 Mobile Safari/537.36",
|
||||
"ios": "Mozilla/5.0 (iPhone; CPU iPhone OS 18_0 like Mac OS X) AppleWebKit/605.1.15 Mobile/15E148",
|
||||
"macos": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 Version/18.0 Safari/605.1.15",
|
||||
"windows": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 Chrome/130.0 Safari/537.36",
|
||||
"linux": "Mozilla/5.0 (X11; Linux x86_64; rv:131.0) Gecko/20100101 Firefox/131.0",
|
||||
}
|
||||
for system, agent in agents.items():
|
||||
self.assertEqual(sub.platform(agent), system)
|
||||
self.assertEqual(sub.platform("Mozilla/5.0 (X11; CrOS x86_64 15917.0.0) Chrome/130.0"), "android")
|
||||
self.assertIsNone(sub.platform(""))
|
||||
|
||||
def shown(agent):
|
||||
"""(labels up front, labels folded away) on the page for this browser."""
|
||||
page = sub.html_page(ROW, [], url, "VPN", {}, "en", user_agent=agent)
|
||||
apps = page.split("Add to an app</h2>", 1)[1].split("</div>", 1)[0]
|
||||
first, _, folded = apps.partition("<details>")
|
||||
label = lambda part: re.findall(r'<a class="app" href="[^"]*">([^<]*)</a>', part)
|
||||
return label(first), label(folded)
|
||||
|
||||
first, folded = shown(agents["android"])
|
||||
self.assertIn("v2rayNG", first)
|
||||
self.assertIn("Streisand", folded)
|
||||
self.assertNotIn("Proxy Suite", first)
|
||||
first, folded = shown(agents["linux"])
|
||||
self.assertEqual(first, ["Happ", "Hiddify", "Clash / mihomo", "Proxy Suite"])
|
||||
self.assertIn("v2rayNG", folded)
|
||||
# Nothing said: every app, none folded away.
|
||||
first, folded = shown("")
|
||||
self.assertEqual((len(first), folded), (len(sub.APPS), []))
|
||||
self.assertIn('proxy-suite://install-config?url=https%3A%2F%2Fvpn.example.com%2Fsub%2F' + "a" * 32 + "&name=VPN",
|
||||
sub.html_page(ROW, [], url, "VPN", {}, "ru", user_agent=agents["linux"]))
|
||||
self.assertIn("Другие приложения", sub.html_page(ROW, [], url, "VPN", {}, "ru", user_agent=agents["linux"]))
|
||||
|
||||
def test_page_policy(self):
|
||||
"""The CSP lets the page's own script and stylesheet run, by their hashes, and nothing
|
||||
else: no style attribute, no other script or stylesheet."""
|
||||
page = sub.html_page({**ROW, "active": False, "reasons": ["expired"]},
|
||||
sub.entries(rendered_for(), "alice"), "https://vpn.example.com/sub/x", "VPN", {}, "en")
|
||||
csp = dict(part.strip().split(" ", 1) for part in sub.PAGE_HEADERS["Content-Security-Policy"].split(";"))
|
||||
scripts = re.findall(r"<script>(.*?)</script>", page, re.S)
|
||||
styles = re.findall(r"<style>(.*?)</style>", page, re.S)
|
||||
self.assertEqual((len(scripts), len(styles)), (1, 1))
|
||||
self.assertEqual(csp["script-src"], sub._csp_hash(scripts[0]))
|
||||
self.assertEqual(csp["style-src"], sub._csp_hash(styles[0]))
|
||||
self.assertEqual(csp["default-src"], "'none'")
|
||||
self.assertNotIn("unsafe", sub.PAGE_HEADERS["Content-Security-Policy"])
|
||||
self.assertNotIn(" style=", page)
|
||||
self.assertEqual(page.count("<script"), 1)
|
||||
|
||||
def test_qr_code(self):
|
||||
"""The browser's QR encoder, run by node, read back by zbar: each length up to version
|
||||
40, multibyte text, and every mask."""
|
||||
node, zbarimg = os.environ.get("NODE"), os.environ.get("ZBARIMG")
|
||||
if not (node and zbarimg):
|
||||
self.skipTest("needs NODE and ZBARIMG")
|
||||
driver = """
|
||||
const fs = require('fs');
|
||||
const [source, text, mask, out] = process.argv.slice(2);
|
||||
let code = fs.readFileSync(source, 'utf8');
|
||||
if (mask !== '') code = code.replace('flip(best);format(best);return m', `flip(${mask});format(${mask});return m`);
|
||||
const qrMatrix = new Function(code + ';return qrMatrix')();
|
||||
const m = qrMatrix(text), quiet = 4, scale = 3, n = (m.length + 2 * quiet) * scale;
|
||||
const rows = [];
|
||||
for (let y = 0; y < n; y++) {
|
||||
const row = [];
|
||||
for (let x = 0; x < n; x++) {
|
||||
const my = Math.floor(y / scale) - quiet, mx = Math.floor(x / scale) - quiet;
|
||||
row.push(my >= 0 && mx >= 0 && my < m.length && mx < m.length && m[my][mx] ? 1 : 0);
|
||||
}
|
||||
rows.push(row.join(' '));
|
||||
}
|
||||
fs.writeFileSync(out, `P1\\n${n} ${n}\\n${rows.join('\\n')}\\n`);
|
||||
console.log(m.length);
|
||||
"""
|
||||
self.assertIn("flip(best);format(best);return m", sub._QR_SCRIPT)
|
||||
cases = [("https://vpn.example.com/sub/" + "0123456789abcdef" * 2, ""), ("https://vpn.example.com/sub/привет", "")]
|
||||
cases += [("".join(chr(0x21 + (i * 7 + n) % 90) for i in range(n)), "") for n in (1, 14, 15, 84, 154, 213, 400, 1000, 2331)]
|
||||
cases += [("https://vpn.example.com/sub/" + "a" * 32, str(mask)) for mask in range(8)]
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
source, script, image = (os.path.join(tmp, name) for name in ("qr.js", "driver.js", "qr.pbm"))
|
||||
with open(source, "w", encoding="utf-8") as handle:
|
||||
handle.write(sub._QR_SCRIPT)
|
||||
with open(script, "w", encoding="utf-8") as handle:
|
||||
handle.write(driver)
|
||||
sizes = set()
|
||||
for text, mask in cases:
|
||||
with self.subTest(length=len(text), mask=mask):
|
||||
drawn = subprocess.run([node, script, source, text, mask, image], capture_output=True, text=True, check=True)
|
||||
sizes.add(int(drawn.stdout))
|
||||
read = subprocess.run([zbarimg, "-q", "--raw", image], capture_output=True)
|
||||
self.assertEqual(read.stdout.decode("utf-8").rstrip("\n"), text)
|
||||
# Versions 1 and 40, and some between.
|
||||
self.assertTrue({21, 177} <= sizes and len(sizes) >= 8, sizes)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,78 @@
|
||||
#!/usr/bin/env python3
|
||||
"""per_app_dns.py: the question in a log line, and a lost UDP query asked again."""
|
||||
|
||||
import asyncio
|
||||
import struct
|
||||
import unittest
|
||||
from unittest import mock
|
||||
|
||||
import per_app_dns as dns
|
||||
|
||||
|
||||
def query(name: str, qtype: int = 1) -> bytes:
|
||||
labels = b"".join(bytes([len(p)]) + p.encode() for p in name.split("."))
|
||||
return struct.pack("!HHHHHH", 7, 0x100, 1, 0, 0, 0) + labels + b"\0" + struct.pack("!HH", qtype, 1)
|
||||
|
||||
|
||||
class QuestionTest(unittest.TestCase):
|
||||
def test_question(self):
|
||||
self.assertEqual(dns.question(query("pbs.twimg.com", 65)), "pbs.twimg.com HTTPS")
|
||||
self.assertEqual(dns.question(query("x.com", 999)), "x.com 999")
|
||||
# The app's name, shown safely; garbage is "?".
|
||||
self.assertEqual(dns.question(query("a\x1bb.com")), "a?b.com A")
|
||||
self.assertEqual(dns.question(b"\0" * 5), "?")
|
||||
self.assertEqual(dns.question(query("x.com")[:-3]), "?")
|
||||
|
||||
|
||||
class AskUdpTest(unittest.TestCase):
|
||||
def ask(self, behaviours, servers=("192.0.2.53",)):
|
||||
"""ask_udp with each attempt, in order, answering after its delay (None: never, an
|
||||
exception: failing)."""
|
||||
behaviours = iter(behaviours)
|
||||
|
||||
async def once(q, server, mark):
|
||||
delay, result = next(behaviours)
|
||||
await asyncio.sleep(delay)
|
||||
if isinstance(result, Exception):
|
||||
raise result
|
||||
if result is None:
|
||||
await asyncio.sleep(3600)
|
||||
return result
|
||||
|
||||
async def run():
|
||||
loop = asyncio.get_running_loop()
|
||||
started = loop.time()
|
||||
reply = await dns.ask_udp(b"q", list(servers), 0)
|
||||
return reply, loop.time() - started
|
||||
|
||||
with mock.patch.object(dns, "ask_udp_once", once), mock.patch.multiple(dns, TIMEOUT=0.4, RESEND_AFTER=0.15):
|
||||
return asyncio.run(run())
|
||||
|
||||
def check(self, behaviours, reply, asked, took, **kw):
|
||||
result, elapsed = self.ask(behaviours, **kw)
|
||||
self.assertEqual(result, (reply, asked))
|
||||
# A busy builder runs late, never early.
|
||||
self.assertGreaterEqual(elapsed, took - 0.01)
|
||||
self.assertLess(elapsed, took + 0.1)
|
||||
|
||||
def test_answered_at_once(self):
|
||||
self.check([(0, b"a")], b"a", 1, 0)
|
||||
|
||||
def test_lost_query_is_asked_again(self):
|
||||
# The first never answers; the second, sent at 0.15, answers 0.05 later.
|
||||
self.check([(0, None), (0.05, b"b")], b"b", 2, 0.2)
|
||||
|
||||
def test_the_first_may_still_answer(self):
|
||||
self.check([(0.3, b"late"), (1, b"never")], b"late", 2, 0.3)
|
||||
|
||||
def test_failing_socket_is_asked_again_at_once(self):
|
||||
self.check([(0, OSError()), (0, b"b")], b"b", 2, 0)
|
||||
|
||||
def test_silence(self):
|
||||
# Asked twice at most per server, then the next server.
|
||||
self.check([(0, None), (0, None)], None, 2, 0.4)
|
||||
self.check([(0, None), (0, None), (0, b"c")], b"c", 3, 0.4, servers=("192.0.2.53", "192.0.2.54"))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
+113
-18
@@ -8,8 +8,14 @@
|
||||
# that must stay in lockstep.
|
||||
# flake-attr package built to recompute vendorHash; "-" when there is none.
|
||||
#
|
||||
# LOCKED_PINS are sources whose rev comes from a flake.lock input, so `nix flake update`
|
||||
# moves them: their hash and vendorHash are refreshed when the source no longer matches.
|
||||
# Table columns: nix-file|flake-input|flake-attr.
|
||||
#
|
||||
# Prints one "updated <repo>: <old> -> <new>" line per change on stdout; progress
|
||||
# and errors go to stderr. `--attrs` lists the flake attrs instead.
|
||||
# and errors go to stderr. A pin whose update fails (no tarball, no vendorHash to read
|
||||
# from the build) is put back as it was and printed as a "skipped <name>: <reason>"
|
||||
# line instead; the others still go through. `--attrs` lists the flake attrs instead.
|
||||
set -euo pipefail
|
||||
|
||||
PINS=(
|
||||
@@ -17,15 +23,26 @@ PINS=(
|
||||
"pkgs/zapret2.nix|bol-van|zapret2|version|zapret2"
|
||||
"pkgs/xray.nix|XTLS|Xray-core|version|xray"
|
||||
"pkgs/whitelist-bypass.nix|kulikov0|whitelist-bypass|version|whitelist-bypass"
|
||||
"pkgs/wireproxy-awg.nix|artem-russkikh|wireproxy-awg|version|wireproxy-awg"
|
||||
)
|
||||
|
||||
LOCKED_PINS=(
|
||||
"pkgs/z2k-detect.nix|z2k|z2k-detect"
|
||||
)
|
||||
|
||||
FAKE_HASH="sha256-AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA="
|
||||
|
||||
if [[ "${1:-}" == "--attrs" ]]; then
|
||||
for pin in "${PINS[@]}"; do
|
||||
IFS='|' read -r _ _ _ _ attr <<<"$pin"
|
||||
[[ "$attr" == "-" ]] || printf '.#%s\n' "$attr"
|
||||
done | sort -u
|
||||
{
|
||||
for pin in "${PINS[@]}"; do
|
||||
IFS='|' read -r _ _ _ _ attr <<<"$pin"
|
||||
[[ "$attr" == "-" ]] || printf '.#%s\n' "$attr"
|
||||
done
|
||||
for pin in "${LOCKED_PINS[@]}"; do
|
||||
IFS='|' read -r _ _ attr <<<"$pin"
|
||||
printf '.#%s\n' "$attr"
|
||||
done
|
||||
} | sort -u
|
||||
exit 0
|
||||
fi
|
||||
|
||||
@@ -109,7 +126,7 @@ refresh_vendor_hash() {
|
||||
return 1
|
||||
fi
|
||||
set_attr "$file" "$repo" vendorHash "$got"
|
||||
echo "updated ${repo} vendorHash: ${got}"
|
||||
echo "updated ${repo:-$attr} vendorHash: ${got}"
|
||||
}
|
||||
|
||||
|
||||
@@ -155,47 +172,125 @@ fi
|
||||
|
||||
declare -A BUMPED=()
|
||||
|
||||
for pin in "${PINS[@]}"; do
|
||||
IFS='|' read -r file owner repo key attr <<<"$pin"
|
||||
[[ -f "$file" ]] || { echo "missing ${file}" >&2; exit 1; }
|
||||
# One tag pin, in this shell so BUMPED sticks. Lines for stdout collect in PIN_OUT and
|
||||
# are printed only once the whole pin went through; a failure sets SKIP_REASON and
|
||||
# returns 1, and the caller puts the file back.
|
||||
update_pin() {
|
||||
local file=$1 owner=$2 repo=$3 key=$4 attr=$5 current new tag tag_ref hash commit vendor
|
||||
PIN_OUT="" SKIP_REASON=""
|
||||
|
||||
if [[ "$key" == =* ]]; then
|
||||
# Lockstep source: refetch only when the key it follows actually moved.
|
||||
key=${key#=}
|
||||
[[ -n "${BUMPED[$key]:-}" ]] || { echo "${repo}: follows ${key}, unchanged" >&2; continue; }
|
||||
[[ -n "${BUMPED[$key]:-}" ]] || { echo "${repo}: follows ${key}, unchanged" >&2; return 0; }
|
||||
new=$(get_key "$file" "$key")
|
||||
current=$new
|
||||
else
|
||||
current=$(get_key "$file" "$key")
|
||||
[[ -n "$current" ]] || { echo "could not read ${key} from ${file}" >&2; exit 1; }
|
||||
tag=$(latest_tag "$owner" "$repo")
|
||||
tag=$(latest_tag "$owner" "$repo") || { SKIP_REASON="could not list its tags"; return 1; }
|
||||
# Keep whatever "v" convention the file already uses.
|
||||
if [[ "$current" == v* ]]; then new=$tag; else new=${tag#v}; fi
|
||||
if [[ "$current" == "$new" ]]; then
|
||||
echo "${repo}: already at ${current}" >&2
|
||||
continue
|
||||
return 0
|
||||
fi
|
||||
# These pins exist because they are ahead of nixpkgs; never walk one back.
|
||||
if [[ "$(newest "$current" "$new")" != "$new" ]]; then
|
||||
echo "${repo}: pinned ${current} is newer than upstream ${new}, keeping it" >&2
|
||||
continue
|
||||
return 0
|
||||
fi
|
||||
fi
|
||||
|
||||
tag_ref=$new
|
||||
[[ "$tag_ref" == v* ]] || tag_ref="v${tag_ref}"
|
||||
hash=$(nix store prefetch-file --json --unpack \
|
||||
"https://github.com/${owner}/${repo}/archive/refs/tags/${tag_ref}.tar.gz" | jq -r '.hash')
|
||||
[[ -n "$hash" && "$hash" != "null" ]] || { echo "could not hash ${repo} ${tag_ref}" >&2; exit 1; }
|
||||
"https://github.com/${owner}/${repo}/archive/refs/tags/${tag_ref}.tar.gz" | jq -r '.hash') || hash=""
|
||||
[[ -n "$hash" && "$hash" != "null" ]] || { SKIP_REASON="could not fetch ${tag_ref}, kept ${current}"; return 1; }
|
||||
|
||||
if [[ "$current" != "$new" ]]; then
|
||||
set_attr "$file" "" "$key" "$new" || { echo "could not write ${key} in ${file}" >&2; exit 1; }
|
||||
BUMPED[$key]=1
|
||||
# The commit the tag names now, for the review: a moved tag shows up as a commit that
|
||||
# is not on the project's history.
|
||||
commit=$(gh_api "https://api.github.com/repos/${owner}/${repo}/commits/${tag_ref}" | jq -r '.sha // empty') || true
|
||||
echo "updated ${repo}: ${current} -> ${new} (commit ${commit:-unknown})"
|
||||
PIN_OUT+="updated ${repo}: ${current} -> ${new} (commit ${commit:-unknown})"$'\n'
|
||||
fi
|
||||
set_attr "$file" "$repo" hash "$hash" || { echo "could not write hash for ${repo}" >&2; exit 1; }
|
||||
refresh_vendor_hash "$file" "$repo" "$attr"
|
||||
vendor=$(refresh_vendor_hash "$file" "$repo" "$attr") ||
|
||||
{ SKIP_REASON="${new} does not build far enough to give its vendorHash, kept ${current}"; return 1; }
|
||||
[[ -z "$vendor" ]] || PIN_OUT+="${vendor}"$'\n'
|
||||
[[ "$current" == "$new" ]] || BUMPED[$key]=1
|
||||
}
|
||||
|
||||
# Locked sources: the fetch is named after the rev, so a moved input always refetches
|
||||
# and a stale hash shows up as a mismatch here instead of reusing the old checkout.
|
||||
update_locked_pin() {
|
||||
local file=$1 input=$2 attr=$3 rev log got vendor
|
||||
PIN_OUT="" SKIP_REASON=""
|
||||
rev=$(jq -r --arg input "$input" '.nodes[$input].locked.rev // empty' flake.lock)
|
||||
[[ -n "$rev" ]] || { echo "no locked rev for ${input} in flake.lock" >&2; exit 1; }
|
||||
if log=$(nix build --no-link ".#${attr}.src" 2>&1); then
|
||||
echo "${attr}: source matches ${input} ${rev:0:7}" >&2
|
||||
return 0
|
||||
fi
|
||||
got=$(grep -oE 'got: +sha256-[A-Za-z0-9+/]{43}=' <<<"$log" | grep -oE 'sha256-.*' | tail -n1)
|
||||
if [[ -z "$got" ]]; then
|
||||
echo "could not fetch the source of ${attr}:" >&2
|
||||
tail -n 30 <<<"$log" >&2
|
||||
SKIP_REASON="could not fetch ${input} ${rev:0:7}"
|
||||
return 1
|
||||
fi
|
||||
set_attr "$file" "" hash "$got" || { echo "could not write hash in ${file}" >&2; exit 1; }
|
||||
PIN_OUT+="updated ${attr}: source to ${input} ${rev:0:7}"$'\n'
|
||||
vendor=$(refresh_vendor_hash "$file" "" "$attr") ||
|
||||
{ SKIP_REASON="${input} ${rev:0:7} does not build far enough to give its vendorHash"; return 1; }
|
||||
[[ -z "$vendor" ]] || PIN_OUT+="${vendor}"$'\n'
|
||||
}
|
||||
|
||||
# Put a locked input back at the committed rev, so the source and its hashes stay a
|
||||
# matching pair. Only a node with no inputs of its own (a `flake = false` source) can be
|
||||
# swapped alone; any other is left moved, and its package build fails in the open.
|
||||
restore_locked_input() {
|
||||
local input=$1 old tmp
|
||||
old=$(git show HEAD:flake.lock 2>/dev/null | jq -c --arg input "$input" '.nodes[$input] // empty') || old=""
|
||||
if [[ -z "$old" ]] || jq -e --arg input "$input" '.nodes[$input].inputs' flake.lock >/dev/null; then
|
||||
return 1
|
||||
fi
|
||||
tmp=$(mktemp)
|
||||
jq --arg input "$input" --argjson old "$old" '.nodes[$input] = $old' flake.lock >"$tmp"
|
||||
mv "$tmp" flake.lock
|
||||
}
|
||||
|
||||
snapshot=$(mktemp)
|
||||
trap 'rm -f "$snapshot"' EXIT
|
||||
|
||||
for pin in "${PINS[@]}"; do
|
||||
IFS='|' read -r file owner repo key attr <<<"$pin"
|
||||
[[ -f "$file" ]] || { echo "missing ${file}" >&2; exit 1; }
|
||||
cp "$file" "$snapshot"
|
||||
if update_pin "$file" "$owner" "$repo" "$key" "$attr"; then
|
||||
printf '%s' "$PIN_OUT"
|
||||
else
|
||||
cp "$snapshot" "$file"
|
||||
echo "${repo}: ${SKIP_REASON}" >&2
|
||||
echo "skipped ${repo}: ${SKIP_REASON}"
|
||||
fi
|
||||
done
|
||||
|
||||
for pin in "${LOCKED_PINS[@]}"; do
|
||||
IFS='|' read -r file input attr <<<"$pin"
|
||||
[[ -f "$file" ]] || { echo "missing ${file}" >&2; exit 1; }
|
||||
cp "$file" "$snapshot"
|
||||
if update_locked_pin "$file" "$input" "$attr"; then
|
||||
printf '%s' "$PIN_OUT"
|
||||
else
|
||||
cp "$snapshot" "$file"
|
||||
if restore_locked_input "$input"; then
|
||||
SKIP_REASON+=", kept ${input} at the committed rev"
|
||||
else
|
||||
SKIP_REASON+=", ${input} stays moved with stale hashes"
|
||||
fi
|
||||
echo "${attr}: ${SKIP_REASON}" >&2
|
||||
echo "skipped ${attr}: ${SKIP_REASON}"
|
||||
fi
|
||||
done
|
||||
@@ -0,0 +1,15 @@
|
||||
# The Windows programs carry their C runtime: vcruntime140.dll is not on every Windows (the
|
||||
# Visual C++ Redistributable brings it), and nothing else should have to be installed first.
|
||||
# (LNK4099: the static runtime's objects name Microsoft's own PDBs, which are not shipped; it
|
||||
# is about their debug info only.)
|
||||
[target.x86_64-pc-windows-msvc]
|
||||
rustflags = ["-C", "target-feature=+crt-static", "-C", "link-arg=/ignore:4099"]
|
||||
|
||||
# GPUI's build compiles its manifest with embed-resource, which would take the dev shell's RC
|
||||
# (MinGW's windres, for the C cross-compiler) and make a COFF object of it; with llvm-rc it makes
|
||||
# a .res, which the linker merges with the app's icon (crates/ps-gui/build.rs). Two resource
|
||||
# objects it refuses. (A target/ from before this keeps GPUI's object: cargo clean -p gpui-pre.)
|
||||
# Building on Windows without llvm-rc: set RC_x86_64_pc_windows_msvc=rc.exe in the environment,
|
||||
# which this does not override.
|
||||
[env]
|
||||
RC_x86_64_pc_windows_msvc = "llvm-rc"
|
||||
@@ -0,0 +1,4 @@
|
||||
target/
|
||||
dist/
|
||||
# The app logs tools/gui-shot.sh writes beside each shot.
|
||||
docs/screenshots/*.log
|
||||
Generated
+9104
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,47 @@
|
||||
[workspace]
|
||||
resolver = "2"
|
||||
members = ["crates/ps-core", "crates/ps-ipc", "crates/ps-service", "crates/ps-client", "crates/ps-ctl", "crates/ps-gui"]
|
||||
# The app (GPUI) builds only when asked for: `-p ps-gui` or `--workspace`.
|
||||
default-members = ["crates/ps-core", "crates/ps-ipc", "crates/ps-service", "crates/ps-client", "crates/ps-ctl"]
|
||||
|
||||
[workspace.package]
|
||||
version = "0.3.0-pre.1"
|
||||
edition = "2024"
|
||||
license = "MIT"
|
||||
repository = "https://git.faumaray.com/faumaray/proxy-suite-flake"
|
||||
|
||||
[workspace.dependencies]
|
||||
anyhow = "1"
|
||||
base64 = "0.22"
|
||||
serde = { version = "1", features = ["derive"] }
|
||||
serde_json = { version = "1", features = ["preserve_order"] }
|
||||
regex = "1"
|
||||
thiserror = "2"
|
||||
percent-encoding = "2"
|
||||
ipnet = "2"
|
||||
indexmap = { version = "2", features = ["serde"] }
|
||||
tokio = { version = "1.54", features = ["rt-multi-thread", "macros", "net", "io-util", "process", "time", "sync", "fs", "signal"] }
|
||||
clap = { version = "4.6", features = ["derive"] }
|
||||
rpassword = "7"
|
||||
reqwest = { version = "0.13", default-features = false, features = ["rustls-no-provider", "socks", "json", "stream", "http2", "query"] }
|
||||
rustls = { version = "0.23", default-features = false, features = ["ring", "std", "tls12"] }
|
||||
windows-service = "0.8"
|
||||
windows-sys = "0.61"
|
||||
tracing = "0.1"
|
||||
tracing-subscriber = { version = "0.3", features = ["env-filter"] }
|
||||
rand = "0.9"
|
||||
sha2 = "0.10"
|
||||
zip = { version = "2", default-features = false, features = ["deflate"] }
|
||||
ps-core = { path = "crates/ps-core" }
|
||||
ps-ipc = { path = "crates/ps-ipc" }
|
||||
ps-client = { path = "crates/ps-client" }
|
||||
|
||||
[profile.release]
|
||||
lto = "thin"
|
||||
strip = true
|
||||
codegen-units = 4
|
||||
|
||||
# GPUI's Windows backend, its shader build patched to work when cross-compiling
|
||||
# (vendor/gpui-pre-windows/PATCHED.md, tools/vendor-gpui-windows.py).
|
||||
[patch.crates-io]
|
||||
gpui-pre-windows = { path = "vendor/gpui-pre-windows" }
|
||||
@@ -0,0 +1,88 @@
|
||||
# Proxy Suite for Windows: design
|
||||
|
||||
The Linux tree (`modules/`, `pkgs/`, `scripts/`) stays as upstream has it, so `main` keeps
|
||||
merging from FUFSoB/proxy-suite-flake. Everything Windows-specific lives under `windows/`.
|
||||
|
||||
## Why a rewrite and not a port
|
||||
|
||||
Upstream's logic sits in Nix: the module evaluates `services.proxy-suite` into bash + jq start
|
||||
scripts, systemd units, nftables rules and polkit rules. None of that runs on Windows, and Nix
|
||||
does not either. What carries over is the *behaviour* (option semantics, link parsing, config
|
||||
shape, routing order, group/detour resolution, CLI verbs, GUI tabs), not the code. The Python
|
||||
pieces (`scripts/proxy_url_parsers.py`, `proxy_parsing.py`, …) are the reference
|
||||
implementation: the Rust port is tested against them differentially.
|
||||
|
||||
## Shape
|
||||
|
||||
One Rust workspace, four binaries, one library:
|
||||
|
||||
| Crate | Binary | Role |
|
||||
|---|---|---|
|
||||
| `ps-core` | — | Config model (the `services.proxy-suite` tree as serde types, same names), validation, link and subscription parsing, sing-box / XRay config rendering, zapret strategy rendering, AmneziaWG/WARP config handling, share links. Pure: no I/O beyond what callers hand it. |
|
||||
| `ps-ipc` | — | The service API: request/response types and the framed-JSON transport (named pipe on Windows, Unix socket elsewhere, so the stack runs on Linux for development). |
|
||||
| `ps-service` | `proxy-suite-service.exe` | Runs as a Windows service (LocalSystem). Owns the config and state, renders backend configs, supervises the backend processes (a Job Object kills them with it), runs the timers (subscriptions, rule sets, autoProxy), talks to sing-box's Clash API, applies the kill switch, serves the API. `--console` runs it in the foreground. |
|
||||
| `ps-ctl` | `proxy-ctl.exe` | Upstream's CLI verbs over the API. |
|
||||
| `ps-gui` | `proxy-suite.exe` | GPUI window and tray icon. Every setting is editable here; it never writes files itself, it sends edits to the service, which validates them. |
|
||||
|
||||
### Config and state
|
||||
|
||||
- `%ProgramData%\ProxySuite\config.json`: the whole option tree, **with upstream's exact
|
||||
camelCase names** (`proxy.listener.port`, `zapret.zapret2.autoHostlist.failThreshold` …), so
|
||||
`docs/options/*.md` stays the reference and differential tests compare like with like. Written only by the service,
|
||||
after validation, atomically. The GUI and `proxy-ctl config get/set/edit` go through the API.
|
||||
Upstream's split between *declared* (Nix) and *runtime* additions disappears: everything is
|
||||
runtime-editable. Secrets (`urlFile`, `passwordFile` …) become plain fields kept in a
|
||||
separate `secrets.json` readable only by SYSTEM and Administrators (and the API returns them
|
||||
only to callers with the `secrets` scope).
|
||||
- `%ProgramData%\ProxySuite\state\`: pins, disabled outbounds, route-mode override, subscription
|
||||
caches, rule-set downloads, autoProxy results, AWG/WARP registrations, inbound users' traffic.
|
||||
- `%ProgramData%\ProxySuite\bin\<component>\<version>\`: backend binaries, fetched by the
|
||||
component manager from pinned release URLs with pinned SHA-256s (see below).
|
||||
- `%ProgramData%\ProxySuite\logs\`: one rotating log per unit, also tailed over the API.
|
||||
|
||||
### Units
|
||||
|
||||
The service keeps upstream's unit names so `proxy-ctl status`/`logs` read the same:
|
||||
|
||||
| Unit | Windows process | Notes |
|
||||
|---|---|---|
|
||||
| `proxy-suite-socks` | `sing-box.exe` (or `xray.exe`) | mixed inbound on `listener`; Clash API on loopback |
|
||||
| `proxy-suite-tun` | `sing-box.exe` | TUN through wintun, `auto_route`, `strict_route` |
|
||||
| `proxy-suite-xray-sidecar` | `xray.exe` | hybrid backend's XRay-only outbounds |
|
||||
| `proxy-suite-zapret` | `winws.exe` / `winws2.exe` | a child with the exact arguments Flowseal's / bol-van's Windows strategies use; never their `service.bat`, which would register a competing `zapret` service. zapret v1 and zapret2 are mutually exclusive, and other WinDivert users (GoodbyeDPI) conflict: validation says so |
|
||||
| `proxy-suite-awg-<p>` | AmneziaWG tunnel | global VPN profile; amneziawg-windows installs each tunnel as its own Windows service, so this unit kind is a *managed service*, not a child (decided once the AWG research is in) |
|
||||
| `proxy-suite-awg-ob-<p>` | `wireproxy-awg.exe` | AWG as a SOCKS outbound |
|
||||
| `proxy-suite-tor` | `tor.exe` (+ lyrebird/snowflake) | outbound tagged `tor` |
|
||||
| `proxy-suite-ssh-proxy` | `ssh.exe -D` (Windows OpenSSH) | outbound tagged `ssh-proxy` |
|
||||
| `proxy-suite-tg-ws-proxy` | `tg-ws-proxy.exe` | |
|
||||
| `proxy-suite-wl-<name>` | whitelist-bypass | creators/joiners |
|
||||
| `proxy-suite-inbounds` | `xray.exe` | server listeners |
|
||||
| `proxy-suite-killswitch` | in-service | sing-box `strict_route` first if it holds on Windows; WFP filters as the follow-up |
|
||||
|
||||
TProxy, cgroup/netns per-app routing and proxychains have no Windows counterpart. Per-app
|
||||
routing becomes sing-box `process_name` / `process_path` rules on the TUN, plus a
|
||||
`proxy-ctl apps run` that sets `HTTP(S)_PROXY`/`ALL_PROXY` for programs that honour them.
|
||||
The system proxy (WinINet, per user) is set by the GUI for its user, not by the service.
|
||||
|
||||
### Who may change things
|
||||
|
||||
"Everything editable in the app" means no UAC prompt per edit: the API pipe grants SYSTEM and
|
||||
Administrators full access and, by default, the interactive user (`S-1-5-4`). `userControl`
|
||||
maps onto this: `userControl.enable = false` keeps the pipe to Administrators, and
|
||||
`userControl.scopes` limit what non-admin callers may do, as upstream's do.
|
||||
|
||||
### Component manager
|
||||
|
||||
Binaries are not vendored into git. `ps-core::components` holds a manifest: name, version,
|
||||
URL, SHA-256, archive layout, files to keep. The service downloads into `bin\`, verifies, and
|
||||
switches atomically; the GUI's Components page shows versions and offers updates. Each manifest
|
||||
entry follows its project's own Windows release (zapret's WinDivert driver and files exactly
|
||||
as Flowseal / bol-van ship them).
|
||||
|
||||
### Testing on the Linux dev box
|
||||
|
||||
- `ps-core` unit tests, plus differential tests against upstream's Python parsers.
|
||||
- Rendered configs are checked with `sing-box check` and `xray run -test` (from nixpkgs).
|
||||
- `ps-service --console` runs on Linux against Linux sing-box/xray, so the API, supervisor,
|
||||
timers and CLI are exercised end to end without Windows.
|
||||
- Windows binaries are cross-compiled (see `README.md` for the toolchain).
|
||||
@@ -0,0 +1,260 @@
|
||||
# Proxy Suite for Windows
|
||||
|
||||
A native Windows port of [proxy-suite-flake](https://github.com/FUFSoB/proxy-suite-flake): the
|
||||
same configuration (upstream's `services.proxy-suite` options, same names and defaults), run
|
||||
by a Windows service instead of NixOS and systemd, controlled from its desktop app (window and
|
||||
tray icon) or with `proxy-ctl`, as upstream's is.
|
||||
|
||||
> [!WARNING]
|
||||
> **Pre-release.** Built and tested on Linux and under Wine; on real Windows so far only the
|
||||
> setup program, zapret, zapret2 and tg-ws-proxy have been tried (they work). Read
|
||||
> [what has been verified](#what-has-been-verified) before relying on it, and please report
|
||||
> what happens on yours.
|
||||
|
||||
> [!IMPORTANT]
|
||||
> For study and research only, as upstream: learning how proxies, tunnels and traffic
|
||||
> routing work. No warranty.
|
||||
|
||||
## What it does (this release)
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| Local proxy | SOCKS5/HTTP on `127.0.0.1:1080` through sing-box (or the hybrid sing-box + XRay backend, or XRay alone: `proxy.backend = "xray"`, without the TUN, groups, rule sets, autoProxy, latency tests, per-app and program rules, which need sing-box) |
|
||||
| Outbounds | links (vless/REALITY/TLS, vmess, trojan, shadowsocks, hysteria2, tuic, anytls, naive, socks, http), raw JSON, subscriptions, groups (failover, urltest, selector), chains, pins, route modes, routing rules by site, address, geodata, rule set or **program** |
|
||||
| zapret | Flowseal's [zapret-discord-youtube](https://github.com/Flowseal/zapret-discord-youtube) release: `winws.exe` with any of its `general*.bat` presets, your lists, the game filter, and `hostlistRules` (a strategy of its own for a group of sites, copied from a preset or given) |
|
||||
| zapret2 | `winws2.exe` from bol-van's [zapret-win-bundle](https://github.com/bol-van/zapret-win-bundle) with [nfqws2-keenetic](https://github.com/nfqws/nfqws2-keenetic)'s strategies or [z2k](https://github.com/necronicle/z2k)'s (made by z2k's own generator, per category: YouTube, Discord, QUIC, the RKN list), and upstream's Lua around them: each site's working strategy kept across restarts, strategies keyed by site (the public suffix list), and the extended detector, which also learns sites blocked only some of the time and requests that never get an answer. The server's TLS replies reach the detectors through a WinDivert filter part; a download stalling mid-way (the 16 KB cutoff) is not seen on Windows, as WinDivert cannot hand over a flow's first packets alone. By its detector's verdicts the proxy routes too: what zapret2 cannot fix goes through the proxy (`proxyFallback`), what it fixes goes direct so it sees it (`directSync`). The **16 KB cutoff probe** (`zapret2.cutoff`, on by default): some lines cut TLS to certain hosting networks after about 16 KB, which no strategy fixes; z2k's probe (`z2k-detect`, built from its source) finds them daily or when the line's network changes, and with z2k's strategies a name that gets through for each, which z2k puts into a fake hello; the networks no name fixes go through the proxy, by address. Its connections leave from ports winws2 is told to leave alone. `proxy-ctl zapret cutoff [probe]`, or the DPI bypass page |
|
||||
| tg-ws-proxy | Flowseal's [tg-ws-proxy](https://github.com/Flowseal/tg-ws-proxy), the headless proxy, on a bundled Python |
|
||||
| Tor | `tor`: the Tor Project's own Windows build (the Expert Bundle, signed, pinned), with bridges (obfs4, webtunnel, snowflake, meek, conjure) and, with `asOutbound`, an outbound of the proxy |
|
||||
| AmneziaWG | `amneziaWg` profiles, from a `.conf`, an AmneziaVPN `vpn://` link or settings. Without `asOutbound`, a **system-wide VPN**: amneziawg-windows's tunnel (amneziawg-go on Wintun, built from its source) as a Windows service of its own, with its routes, DNS and, for one peer that takes everything, its firewall blocking what leaves outside the tunnel; on and off in the app or `proxy-ctl awg on|off`. As outbounds: `"userspace"` (wireproxy-awg, built from upstream's source, AmneziaWG's obfuscation kept, no driver) or `"singBox"` (plain WireGuard). WARP devices take either kind too |
|
||||
| WARP | `warp` with `asOutbound = "singBox"` or `"userspace"`: each device registered with Cloudflare as wgcf registers (through the local proxy first, then directly, then `generatorUrl`), or a profile given; a sing-box WireGuard endpoint, several grouped as `warp` |
|
||||
| autoProxy | `proxy.autoProxy`: the sites apps reach directly are probed through each exit in turn (direct first); one blocked directly but reached through an exit is routed through it, as upstream's prober decides (block pages, one exit per network first, strikes against exits that refuse). Blocks zapret can fix stay direct. A site that crawls directly (`slowBelowKiBps`) moves to the first exit that carries it as well as direct does. Its page in the app, or `proxy-ctl proxy auto`, shows, probes, learns and forgets |
|
||||
| whitelist-bypass | `whitelistBypass`: [whitelist-bypass](https://github.com/kulikov0/whitelist-bypass)'s headless creators and joiners (WB Stream, Telemost, DION, Bitrix; VK creators), built from upstream's source: a joiner is an outbound of the proxy tunnelled through a video call, a creator the call's free end. `proxy-ctl wl` gives the links and logins |
|
||||
| SSH tunnel | `sshProxy`: Windows' own OpenSSH as a SOCKS listener (`ssh -D`) for other programs, and, with `asOutbound`, an outbound of the proxy (sing-box's SSH client) |
|
||||
| TUN | sing-box's TUN (wintun), `proxy-ctl proxy tun on`, alongside zapret too — **see the caveats** |
|
||||
| Kill switch | `killSwitch`: while the TUN or a system-wide AmneziaWG profile is on, what would leave past it is blocked (Windows Filtering Platform filters, in the service's session); LAN, DHCP, NTP and the tunnel's own programs stay open. `proxy-ctl killswitch [on\|off]`, or the Overview |
|
||||
| The app | **Proxy Suite** in the Start Menu, and a tray icon from sign-in: the proxy, DPI bypass and Telegram proxy at a glance and a click; outbounds, subscriptions and the routing mode; zapret's presets and sites; tg-ws-proxy's links; whitelist-bypass's joiners and creators (links, logins); autoProxy's routes, probes and exits; the logs; **every option** in its JSON editor, checked by the service before it takes it; the system proxy; in English or Russian (as Windows is set, or chosen); a light and a dark theme (or as Windows is set); a newer release installed from its Overview |
|
||||
|
||||
Not ported: server inbounds (this PC serving other devices) and Tor's onion service, which
|
||||
serves them. Their options are accepted (they are upstream's), but the
|
||||
service says, in its status and in the app, that it does not run them yet.
|
||||
|
||||
Needs 64-bit Windows 10 (1903 or later) or 11.
|
||||
|
||||
## Screenshots
|
||||
|
||||
Taken on Linux against the service with a demo configuration (`tools/screenshots.sh`), so the
|
||||
DPI bypass, which runs on Windows only, shows as inactive.
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
|  |  |
|
||||
|  |  |
|
||||
|  |  |
|
||||
|  |  |
|
||||
|  |  |
|
||||
|  |  |
|
||||
|
||||
## What has been verified
|
||||
|
||||
| Part | How |
|
||||
|---|---|
|
||||
| **On real Windows** (0.2.0-pre.1) | the setup program installs it; zapret, zapret2 and tg-ws-proxy work |
|
||||
| Share-link and subscription parsing | upstream's tests, ported; ~750 links through upstream's Python and this, identical results |
|
||||
| sing-box and XRay configs | rendered for many setups and accepted by `sing-box check` and `xray run -test` |
|
||||
| The XRay-only backend | its config (listener login, DNS order and pinned server names, route modes, urltest balancer and pin, chains, helper hops, zapret's direct lists) accepted by `xray run -test` and asserted as upstream's filter vectors are; end to end on Linux: the service running xray with the release's own `geoip.dat`/`geosite.dat`, a page fetched through its listener and a Shadowsocks outbound (urltest, then pinned), a wrong password refused, the latency test refused as upstream refuses it |
|
||||
| The kill switch | its plan (what stays open: local networks, the tunnels' addresses, their programs, NTP; when it holds and when it is lifted) by unit tests; the Windows Filtering Platform filters built and compiled for Windows. Not run: Wine has no Windows Filtering Platform, so whether the filters block and let through as meant needs real Windows |
|
||||
| zapret beside the TUN | the filter part that leaves the TUN's packets out (IPv4 and IPv6), alone, with the cutoff probe's and around Flowseal's own filter as `--wf-raw` takes it, compiled by WinDivert's own `WinDivertHelperCompileFilter` (under Wine); zapret2's arguments with it checked by `winws2 --dry-run`. Traffic through both needs real Windows |
|
||||
| Service, API, `proxy-ctl` | end to end on Linux: a real sing-box Shadowsocks server, the service, `proxy-ctl` adding the outbound, a page fetched through the local proxy |
|
||||
| Windows build: service, named pipe, its ACL, caller identification, component hashes, supervisor | under Wine (`tools/wine-e2e.sh`) |
|
||||
| zapret arguments | **every** preset of the release, both game filters, checked by the release's own `winws.exe --dry-run` under Wine (`tools/winws-dry-run.sh`) |
|
||||
| zapret2 arguments | checked by `winws2.exe --dry-run` under Wine, the cutoff probe's filter part included |
|
||||
| 16 KB cutoff probe | on this test machine's line, which does cut TLS at 16 KB to some networks: the service ran z2k-detect (its Linux build, the same patched source), which found 25 networks cut off and a name for each; its connections left from the probe's ports only; 157 distinct local ports of the probe's range were seen in use during its run; the maps, the line's network and the rule-set written, shown by `proxy-ctl zapret cutoff` and the app. The Windows build runs under Wine (it found the same networks, from the range's ports); winws2 leaving its connections alone needs real Windows (its filter, with the exclusion, saved by `winws2 --wf-save`) |
|
||||
| Updates from the app | on Linux against a local stand-in for the releases API: a newer release found (and none for a pre-release's user beyond its channel, by unit tests), its setup program fetched and matched to its SHA-256, a wrong checksum refused, the app's states (found, fetching, installing) shown. Not verified: the setup run as SYSTEM by the service, and the app started again in the user's session afterwards, which need real Windows (the first chance is the update from 0.3.0-pre.1 to the release after it) |
|
||||
| tg-ws-proxy | runs and listens under Wine |
|
||||
| SSH tunnel | end to end on Linux: an sshd of the test's own, a page through the `ssh -D` listener and through sing-box's SSH outbound, each logging in with the service's copy of the key (`an_ssh_tunnel`) |
|
||||
| Tor | its Windows `tor.exe` (under Wine) accepts the torrc the service writes, bridges and transports included; on Linux the service runs Tor with it and Tor starts bootstrapping (where Tor's relays are blocked, it needs bridges) |
|
||||
| AmneziaWG | profiles from `.conf`, `vpn://` links and settings converted exactly as upstream's script converts them (its own encoder's links as test vectors); end to end on Linux: sing-box as a WireGuard server, the service running wireproxy-awg, a page through its listener and through the proxy's outbound (`an_amneziawg_tunnel`) |
|
||||
| autoProxy | its judgement (upstream's verdicts, walk, exit order, strikes, state) by unit tests; the config with its probe listeners and learned rule-sets accepted by `sing-box check`; on Linux with a local exit: probes through direct and the exit, a learn request, a site an app reached directly queued from the Clash API and probed at the next run, the state and the rule-set files written; a download held to 40 KiB/s seen crawling and moved to the exit. A site blocked here and reached through an exit needs a remote exit, so none was routed that way |
|
||||
| whitelist-bypass | its Windows programs built from upstream's tag with upstream's patches (links and passwords from the environment, never the command line); on Linux the service runs a joiner and a creator with their flags, the link and the login reaching them (`proxy-ctl wl join`, `wl auth`, `wl new`, `wl link`); a real call needs an account on a platform, so none was made |
|
||||
| AmneziaWG system-wide | under Wine's service manager (`tools/wine-setup-test.sh`): a profile added registers its tunnel service (program, configuration, dependencies), `proxy-ctl awg on` starts it, and the tunnel runs as a service up to creating the Wintun adapter, which Wine cannot; its log is read back; the service goes with its profile. Traffic through it needs real Windows |
|
||||
| WARP | a device registered live with Cloudflare by the service, its profile rendered as a sing-box endpoint and accepted; traffic through it not (this test machine blocks outgoing UDP) |
|
||||
| zapret's hostlist rules | every preset with sample rules, checked by `winws.exe --dry-run` (a preset without the profile a rule copies is refused, as upstream refuses it) |
|
||||
| The app | every page against the service running on Linux, in a window on a virtual display (Xvfb, Mesa's software Vulkan), clicked and typed into by a script, screenshots looked at, and the service's configuration checked after each change (`tools/gui-shot.sh`) |
|
||||
| The setup program | under Wine (`tools/wine-setup-test.sh`): a silent install puts every file of the release into Program Files and the entry into Settings → Apps, the service runs and answers; the same setup again over the running install upgrades it; the entry's uninstall removes the service, the files and the entry. Its pages (and the Russian ones) not looked at |
|
||||
| The app's Windows build | built by the release workflow; its shaders by Microsoft's own `fxc.exe` (under Wine) with GPUI's own arguments; its icon and manifest in its resources, no C runtime DLL among its imports; under Wine it starts and gets as far as drawing text |
|
||||
|
||||
**Not verified yet: the rest of what needs real Windows.** Traffic through sing-box on Windows
|
||||
(Wine lacks an API it needs), the TUN adapter, AmneziaWG's system-wide tunnels, autoProxy,
|
||||
whitelist-bypass, the SSH tunnel, Tor and WARP there, uninstalling, and the app's pages beyond
|
||||
what the zapret and Telegram ones need, its tray icon, the system proxy and the Start Menu entry.
|
||||
|
||||
## Install
|
||||
|
||||
1. Download `ProxySuite-<version>-windows-x64-setup.exe` and run it. It asks for
|
||||
administrator rights; SmartScreen may warn of an unknown publisher (the programs are not
|
||||
signed yet): **More info** → **Run anyway**.
|
||||
2. It installs everything into `C:\Program Files\ProxySuite`, registers the **ProxySuite**
|
||||
service (starts at boot), adds `proxy-ctl` to PATH, starts it, and opens the app; the app
|
||||
starts at every sign-in, in the tray (its shield is green while things work, amber when one
|
||||
failed, grey when all is off). One option, unchecked: Windows' **OpenSSH Client**, for the
|
||||
SSH tunnel only, where it was removed from Windows (Windows 10 1809 and later have it).
|
||||
3. Open **Proxy Suite** from the Start Menu or the tray, or in a **new** terminal:
|
||||
`proxy-ctl status`.
|
||||
|
||||
Nothing has to be installed first: the C runtime is linked into the programs, and WinDivert,
|
||||
wintun, Python, Tor and the rest come with it, as components. For a silent install:
|
||||
`ProxySuite-<version>-windows-x64-setup.exe /S`.
|
||||
|
||||
To upgrade, run the new setup, or install it from the app: its Overview says when a newer
|
||||
release is out (it looks when it starts, and daily; Settings → This app turns that off), and
|
||||
**Install** has the service fetch the setup program from this project's releases, check its
|
||||
SHA-256 against the one published beside it, and run it silently: the service and the app close
|
||||
for a moment and start again, new. `proxy-ctl update` and `proxy-ctl update install` do the
|
||||
same. A pre-release is offered newer pre-releases and releases; a release only releases. The
|
||||
settings stay either way. To remove: **Settings → Apps → Proxy Suite →
|
||||
Uninstall** (it runs `uninstall.cmd` in that folder); the configuration and state stay in
|
||||
`%ProgramData%\ProxySuite` until you delete it.
|
||||
|
||||
Without the setup program: unzip `ProxySuite-<version>-windows-x64.zip` anywhere and run
|
||||
`install.cmd` (it asks for administrator rights): the same install, from the same files.
|
||||
|
||||
Windows Defender and other antivirus software may flag WinDivert (zapret's driver): it is a
|
||||
packet-filtering driver, which is what it is for. Remove other DPI-bypass tools first:
|
||||
Flowseal's own `zapret` service (its `service.bat` → Remove Services) or GoodbyeDPI — the
|
||||
service refuses to start zapret while one runs, and says which.
|
||||
|
||||
## First run
|
||||
|
||||
In the app: **Outbounds** → paste a link → **Add**, then switch the local proxy on in the
|
||||
**Overview** (and, if wanted, *Use it as the system proxy*). **DPI bypass** switches zapret on
|
||||
and picks its preset; **Telegram proxy** gives the link to open in Telegram. Or from a terminal:
|
||||
|
||||
```powershell
|
||||
# A proxy:
|
||||
proxy-ctl proxy outbounds add "vless://...#My Server"
|
||||
proxy-ctl proxy on
|
||||
proxy-ctl status
|
||||
# Then point apps (or Windows: Settings → Network → Proxy) at 127.0.0.1:1080.
|
||||
|
||||
# Or a subscription:
|
||||
proxy-ctl proxy subs add https://provider.example/sub/token
|
||||
|
||||
# zapret, Flowseal's presets:
|
||||
proxy-ctl zapret on
|
||||
proxy-ctl zapret preset "general (ALT9)"
|
||||
proxy-ctl zapret game-filter all
|
||||
|
||||
# zapret2 instead:
|
||||
proxy-ctl config get > config.json # set "zapret": { "enable": true, "engine": "zapret2" }
|
||||
proxy-ctl config set config.json
|
||||
proxy-ctl zapret cutoff # the networks this line cuts off after 16 KB (probe: now)
|
||||
|
||||
# Telegram's WebSocket proxy:
|
||||
proxy-ctl config get > config.json # set "tgWsProxy": { "enable": true }
|
||||
proxy-ctl config set config.json
|
||||
proxy-ctl logs proxy-suite-tg-ws-proxy # its tg:// link and secret
|
||||
|
||||
# whitelist-bypass: a joiner here (set "whitelistBypass": { "enable": true,
|
||||
# "joiners": { "wl": { "platform": "wbstream" } } }), its creator's link from the other end:
|
||||
proxy-ctl wl join wl "https://..."
|
||||
proxy-ctl proxy pin wl
|
||||
# A creator: its login (a cookies export; DION and Bitrix ask for an email and password), its call:
|
||||
proxy-ctl wl auth laptop cookies.json
|
||||
proxy-ctl wl link laptop
|
||||
|
||||
# AmneziaWG as a system-wide VPN (a profile without asOutbound):
|
||||
proxy-ctl awg # profiles and their state
|
||||
proxy-ctl awg on home # start it; off stops it
|
||||
proxy-ctl awg log home # its tunnel's log
|
||||
|
||||
# autoProxy (set "proxy": { "autoProxy": { "enable": true } }):
|
||||
proxy-ctl proxy auto # what it routed, and where
|
||||
proxy-ctl proxy auto probe example.com # how a site answers through each exit
|
||||
proxy-ctl proxy auto learn example.com # probe it now, route it if it needs it
|
||||
|
||||
proxy-ctl logs -f # everything, following
|
||||
proxy-ctl --help
|
||||
```
|
||||
|
||||
## The configuration
|
||||
|
||||
The app's **Settings** page edits it whole, and checks it with the service before saving.
|
||||
`proxy-ctl config get` prints it, `proxy-ctl config set <file>` replaces it (checked first; a
|
||||
bad one changes nothing), `proxy-ctl config validate <file>` only checks. It is upstream's
|
||||
option tree as JSON, so [upstream's option reference](../docs/options/index.md) describes it:
|
||||
`services.proxy-suite.proxy.listener.port` is `{"proxy": {"listener": {"port": …}}}`.
|
||||
Options that only mean something on Linux (TProxy, fwmarks, routing tables, packages) are not
|
||||
there; the Windows-only ones are documented in `crates/ps-core/src/config/`:
|
||||
|
||||
- `proxy.singBox.testPort`; `proxy.systemProxy` (applied by the app, for the signed-in user)
|
||||
- `proxy.routing.rules.*.processNames` / `processPaths` (and `name`, `priority`, `disabled`)
|
||||
- `perAppRouting.profiles.*`: programs held to an outbound, by name or path
|
||||
- `zapret.tcpTimestamps`, `geodata` as download locations, `tor.controlPort`
|
||||
- inline `config` text where upstream only takes a file (AmneziaWG, WARP)
|
||||
|
||||
## Who may change what
|
||||
|
||||
The service runs as LocalSystem. Its settings are meant to be edited by whoever uses the
|
||||
machine, so — **unlike upstream, where changes need root** — `userControl` defaults to on
|
||||
for the signed-in user, with every scope. On a shared computer, set
|
||||
`userControl.scopes` (or turn `userControl.enable` off) as an administrator.
|
||||
|
||||
Whatever the scopes, these always need an administrator: anything that makes the service run
|
||||
a program, pass arguments to one, or read or write a file of the caller's choosing — every
|
||||
`*File` option, raw `singBoxJson`/`xrayJson`, `sshProxy.extraArgs`, `tor.extraConfig`,
|
||||
`nfqwsArgs`, zapret2's `profiles` and `blobs`, `allowConfigHooks`, and `userControl` itself —
|
||||
and installing components. Installing an update takes the `services` scope only: it runs no
|
||||
program but this project's own setup, from its own releases, checked, and only a newer one. Secrets (links, passwords) are hidden from callers without the
|
||||
`secrets` scope, and survive a round trip through `config get`/`config set` unchanged.
|
||||
|
||||
## Caveats
|
||||
|
||||
- **TUN and zapret together**: zapret (winws or winws2) leaves the TUN's own packets alone,
|
||||
by its address in WinDivert's filter, and handles the connections sing-box makes on the way
|
||||
out of the real adapter, direct ones included. Checked by WinDivert's own filter compiler;
|
||||
traffic through both needs real Windows.
|
||||
- The global TUN restarts the local proxy when it is turned on or off (one sing-box does both).
|
||||
- The system proxy is set by the app, for the user it runs as, while it runs: quitting the app
|
||||
puts the user's own setting back.
|
||||
|
||||
## Components
|
||||
|
||||
The release carries every program it runs, each pinned by version and hash
|
||||
([`components.json`](components.json)), and the service checks each against the hashes
|
||||
recorded at install before running it. `proxy-ctl components` lists them;
|
||||
`proxy-ctl components install [name…]` fetches and verifies them again (administrator).
|
||||
See [`THIRD-PARTY.md`](THIRD-PARTY.md) for their licenses and sources.
|
||||
|
||||
## Building
|
||||
|
||||
On Linux with Nix: `nix develop` here (this directory has its own `flake.nix`), then
|
||||
|
||||
```sh
|
||||
cargo test # everything but the app; sing-box and xray from the shell
|
||||
python3 -I tools/parity/links.py # link parsing against upstream's Python
|
||||
tools/package.sh # the setup program and the zip, in dist/
|
||||
nix shell nixpkgs#wineWow64Packages.stable -c tools/winws-dry-run.sh dist/ProxySuite-*/components
|
||||
nix shell nixpkgs#wineWow64Packages.stable -c tools/wine-setup-test.sh dist/ProxySuite-*-setup.exe dist/ProxySuite-*-x64
|
||||
```
|
||||
|
||||
The app on Linux, against the service on Linux:
|
||||
|
||||
```sh
|
||||
tools/dev-service.sh # the service, a demo outbound; leave it running
|
||||
cargo run -p ps-gui -- --socket "$XDG_RUNTIME_DIR/proxy-suite-dev.sock"
|
||||
tools/gui-shot.sh shot.png 8 -- --socket "$XDG_RUNTIME_DIR/proxy-suite-dev.sock" # headless
|
||||
```
|
||||
|
||||
Its Windows build compiles GPUI's shaders with Microsoft's `fxc.exe` under Wine
|
||||
(`tools/fxc-wine.sh`, fetched from the Windows SDK and pinned by hash; it stays on the build
|
||||
machine), through a small patch to GPUI's Windows backend (`vendor/gpui-pre-windows`).
|
||||
|
||||
The Windows programs are cross-compiled with `cargo xwin` (MSVC target, the C runtime linked
|
||||
in: `.cargo/config.toml`), with the toolchain in `rust-toolchain.toml`. The setup program is
|
||||
NSIS's (`tools/installer.nsi`, `makensis` from the shell): it unpacks the release and runs its
|
||||
`proxy-suite-service.exe install`, as `install.cmd` does. Design notes: [`DESIGN.md`](DESIGN.md).
|
||||
|
||||
Releases are built by Gitea Actions (`.gitea/workflows/windows-release.yml`): bump `version`
|
||||
in `Cargo.toml`, add `release-notes/<version>.md`, push a tag `windows-v<version>`. The
|
||||
workflow tests, packages and publishes the setup program and the zip, each with its `.sha256`, with the `RELEASE_TOKEN`
|
||||
secret (a token with `write:repository`). Run by hand, it only builds.
|
||||
@@ -0,0 +1,151 @@
|
||||
{
|
||||
"components": {
|
||||
"sing-box": {
|
||||
"version": "1.14.4",
|
||||
"license": "GPL-3.0-or-later",
|
||||
"homepage": "https://github.com/SagerNet/sing-box",
|
||||
"sources": [
|
||||
{
|
||||
"url": "https://github.com/SagerNet/sing-box/releases/download/v1.14.4/sing-box-1.14.4-windows-amd64.zip",
|
||||
"sha256": "99185d75d314a07dbba4a130c8ad986cbeb629a07927975636b341ca61f991df",
|
||||
"strip": "sing-box-1.14.4-windows-amd64/"
|
||||
}
|
||||
]
|
||||
},
|
||||
"xray": {
|
||||
"version": "26.10.21",
|
||||
"license": "MPL-2.0",
|
||||
"homepage": "https://github.com/XTLS/Xray-core",
|
||||
"sources": [
|
||||
{
|
||||
"url": "https://github.com/XTLS/Xray-core/releases/download/v26.10.21/Xray-windows-64.zip",
|
||||
"sha256": "fc58c39ee2f2717b4c54d28d374362389e5319b20ae44aea76ea45a5243ec827",
|
||||
"strip": "",
|
||||
"include": [
|
||||
"xray.exe",
|
||||
"geoip.dat",
|
||||
"geosite.dat",
|
||||
"LICENSE"
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
"zapret": {
|
||||
"version": "1.10.4",
|
||||
"license": "MIT",
|
||||
"homepage": "https://github.com/Flowseal/zapret-discord-youtube",
|
||||
"sources": [
|
||||
{
|
||||
"url": "https://github.com/Flowseal/zapret-discord-youtube/releases/download/1.10.4/zapret-discord-youtube-1.10.4.zip",
|
||||
"sha256": "291af673bd0238506f9548e0e94ca0abf244000f4c9a06960544fb01c5f97b34",
|
||||
"strip": "zapret-discord-youtube-1.10.4/",
|
||||
"exclude": [
|
||||
"service.bat",
|
||||
"utils/"
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
"zapret2": {
|
||||
"version": "2026.10.21+de9795d",
|
||||
"license": "MIT",
|
||||
"homepage": "https://github.com/bol-van/zapret-win-bundle",
|
||||
"sources": [
|
||||
{
|
||||
"url": "https://codeload.github.com/bol-van/zapret-win-bundle/zip/de9795d71287fdb21cf8c20b8af1a09d0eb10ab2",
|
||||
"strip": "zapret-win-bundle-de9795d71287fdb21cf8c20b8af1a09d0eb10ab2/zapret-winws/",
|
||||
"files": {
|
||||
"WinDivert.dll": "16abd6a029e65557c6a309bea7b13bf81fff4e193567582e1cddbf6719f323e0",
|
||||
"WinDivert64.sys": "8da085332782708d8767bcace5327a6ec7283c17cfb85e40b03cd2323a90ddc2",
|
||||
"cygwin1.dll": "103104a52e5293ce418944725df19e2bf81ad9269b9a120d71d39028e821499b",
|
||||
"files/list-youtube.txt": "47ea8a9ca11eb9ad833e5f22d12e8857400880e8f555f45687230ce8ba57d299",
|
||||
"files/quic_initial_www_google_com.bin": "f4589c57749f956bb30538197a521d7005f8b0a8723b4707e72405e51ddac50a",
|
||||
"lua/zapret-antidpi.lua": "6d1fa9168e5de1682fef91fd174f68b58c50f6739ef00f42ca7db2b940b6246d",
|
||||
"lua/zapret-auto.lua": "23a9b99a776d868d92f4cc0ee5110f5c1f12fe746620d9c0337022dbc2f52df0",
|
||||
"lua/zapret-lib.lua": "6bf528fef1f0fc3c65e189216fc8a06bb873f6e25d1c29d2bfa4695a09b73440",
|
||||
"lua/zapret-obfs.lua": "e2d75840a9f1e3bfb74fa7463886932e03eb02ab33c6146d6392d6a231d1cfd5",
|
||||
"lua/zapret-pcap.lua": "6866c37c92fbc62075accf94228da48af618c7f416edc682eba99b2196e05f45",
|
||||
"lua/zapret-tests.lua": "82664cb50a751a531b63dce094ac03de5045b16b489e726ff32a9a1034811459",
|
||||
"windivert.filter/README.txt": "be9ad4622296c463f1cf278c4f97be0c7eabaff9e79ad36262a8255fafd2b216",
|
||||
"windivert.filter/windivert_part.dht.txt": "0e0d071239995332c2e45e60c59c5bb3d70233426e430a7babb24b18b75e90c0",
|
||||
"windivert.filter/windivert_part.discord_media.txt": "2f2deaf49ed68eb684258497134181753188f2b475161deb244488a53872b7c5",
|
||||
"windivert.filter/windivert_part.quic_initial_ietf.txt": "f243ddc22758b9e04838211a3815e43fb3abe615e6be29e6a812ae4c72b392e0",
|
||||
"windivert.filter/windivert_part.stun.txt": "2a14f470b00cd9704003e0cade500086398f9222c858d9ae944bdeb89f520595",
|
||||
"windivert.filter/windivert_part.wireguard.txt": "da68586267462b29e3e370203ce0369ae2baa25a07aa2deab5fb44d69fef27be",
|
||||
"winws2.exe": "ba4ceccdea3576da0a0991a50d7893ea911de197281338132dbec02a5b2fcf58"
|
||||
}
|
||||
},
|
||||
{
|
||||
"url": "https://codeload.github.com/nfqws/nfqws2-keenetic/zip/fa22c177b340e73d8b8a94b295af20e0228c4c22",
|
||||
"strip": "nfqws2-keenetic-fa22c177b340e73d8b8a94b295af20e0228c4c22/etc/nfqws2/",
|
||||
"dest": "keenetic/",
|
||||
"files": {
|
||||
"blobs/quic_initial.bin": "f4589c57749f956bb30538197a521d7005f8b0a8723b4707e72405e51ddac50a",
|
||||
"blobs/tls_clienthello.bin": "936c2bee4cfb80aa3c426b2dcbcc834b3fbcd1adb17172959dc569c73a14275c",
|
||||
"lists/auto.list": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
|
||||
"lists/exclude.list": "e7f87f890ad7916da8e30ceb101e8340955bdbba1e16cd6e6439469cc847f796",
|
||||
"lists/ipset.list": "88cfdebe5531fd14d3a1ff16e303ae28307563c2ecd0820090918bf92da90b88",
|
||||
"lists/ipset_exclude.list": "0a332890f577839bcce0651d3cf287d3d820c1bf4495b3f568276856d6e85073",
|
||||
"lists/user.list": "974016ffc0b0cef05fbb05718f12b721104a72b3fa7261a814d596974dc339cc",
|
||||
"nfqws2.conf": "b5c6598d5ba03762393a877514e005d2a241e0eb51c4e03142cade544e1e5b30"
|
||||
}
|
||||
}
|
||||
]
|
||||
},
|
||||
"tg-ws-proxy": {
|
||||
"version": "1.11.2+py3.12.10",
|
||||
"license": "MIT",
|
||||
"homepage": "https://github.com/Flowseal/tg-ws-proxy",
|
||||
"bundled": true,
|
||||
"sources": []
|
||||
},
|
||||
"tor": {
|
||||
"version": "15.0.26",
|
||||
"license": "BSD-3-Clause",
|
||||
"homepage": "https://www.torproject.org",
|
||||
"sources": [
|
||||
{
|
||||
"url": "https://dist.torproject.org/torbrowser/15.0.26/tor-expert-bundle-windows-x86_64-15.0.26.tar.gz",
|
||||
"sha256": "c1988c701de2f24f7d098d1d6d7f507b58f27740d097f29c246e0524d639b252",
|
||||
"include": [
|
||||
"tor/",
|
||||
"data/geoip",
|
||||
"data/geoip6",
|
||||
"docs/"
|
||||
],
|
||||
"exclude": [
|
||||
"tor/tor-gencert.exe"
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
"wireproxy-awg": {
|
||||
"version": "1.0.18",
|
||||
"license": "ISC",
|
||||
"homepage": "https://github.com/artem-russkikh/wireproxy-awg",
|
||||
"bundled": true,
|
||||
"sources": []
|
||||
},
|
||||
"zapret2-extras": {
|
||||
"version": "2026.10.28+z2k.7beb975",
|
||||
"license": "MIT (z2k, proxy-suite's Lua); MPL-2.0 (the public suffix list)",
|
||||
"homepage": "https://github.com/necronicle/z2k",
|
||||
"bundled": true,
|
||||
"sources": []
|
||||
},
|
||||
"amneziawg": {
|
||||
"version": "0-unstable-2026-08-14+e90531d",
|
||||
"license": "MIT",
|
||||
"homepage": "https://github.com/amnezia-vpn/amneziawg-windows",
|
||||
"bundled": true,
|
||||
"sources": []
|
||||
},
|
||||
"whitelist-bypass": {
|
||||
"version": "0.4.4",
|
||||
"license": "MIT",
|
||||
"homepage": "https://github.com/kulikov0/whitelist-bypass",
|
||||
"bundled": true,
|
||||
"sources": []
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
[package]
|
||||
name = "ps-client"
|
||||
description = "Proxy Suite for Windows: the service's client side, for proxy-ctl and the app"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
|
||||
[dependencies]
|
||||
ps-core.workspace = true
|
||||
ps-ipc.workspace = true
|
||||
anyhow.workspace = true
|
||||
serde_json.workspace = true
|
||||
|
||||
[dev-dependencies]
|
||||
tokio.workspace = true
|
||||
@@ -0,0 +1,419 @@
|
||||
//! The configuration edits proxy-ctl and the app make, on the configuration as JSON (what
|
||||
//! `config-get` returns). Each can be made again on a newer configuration, which
|
||||
//! [`Client::edit`](crate::Client::edit) does when another change came first.
|
||||
|
||||
use anyhow::{Result, anyhow, bail};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
/// The list at `path`, made (with the objects above it) when missing.
|
||||
pub fn arr<'a>(v: &'a mut Value, path: &[&str]) -> &'a mut Vec<Value> {
|
||||
let mut cur = v;
|
||||
for p in path {
|
||||
if cur.get(*p).is_none_or(Value::is_null) {
|
||||
cur[*p] = if *p == path[path.len() - 1] { json!([]) } else { json!({}) };
|
||||
}
|
||||
cur = cur.get_mut(*p).unwrap();
|
||||
}
|
||||
cur.as_array_mut().expect("a list")
|
||||
}
|
||||
|
||||
/// A tag for a link without one: its remark, else its host.
|
||||
pub fn link_tag(link: &str) -> String {
|
||||
if let Some((_, remark)) = link.split_once('#') {
|
||||
let t = ps_core::links::subscription::slugify_tag(&ps_core::links::py::unquote(remark));
|
||||
if t != "proxy" {
|
||||
return t;
|
||||
}
|
||||
}
|
||||
let host = link.split("://").nth(1).unwrap_or("").split(['@']).next_back().unwrap_or("").split([':', '/', '?', '#']).next().unwrap_or("");
|
||||
let t = ps_core::links::subscription::slugify_tag(host);
|
||||
if t.is_empty() { "outbound".into() } else { t }
|
||||
}
|
||||
|
||||
/// A tag for a subscription without one: its host.
|
||||
pub fn subscription_tag(url: &str) -> String {
|
||||
let host = ps_core::links::subscription::url_parts::split(url).ok().and_then(|u| u.hostname).unwrap_or_else(|| "sub".into());
|
||||
ps_core::links::subscription::slugify_tag(&host)
|
||||
}
|
||||
|
||||
/// What an outbound is made from: a share link, or a backend's own JSON for one.
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub enum OutboundSource {
|
||||
Link(String),
|
||||
SingBoxJson(Value),
|
||||
XrayJson(Value),
|
||||
}
|
||||
|
||||
impl OutboundSource {
|
||||
/// A link, or JSON (XRay's has a `protocol`, sing-box's a `type`). A link is checked
|
||||
/// here: the service would only say it left the outbound out.
|
||||
pub fn parse(text: &str) -> Result<Self> {
|
||||
let text = text.trim();
|
||||
if text.starts_with('{') {
|
||||
let json: Value = serde_json::from_str(text).map_err(|e| anyhow!("not JSON: {e}"))?;
|
||||
return Ok(if json.get("protocol").is_some() { Self::XrayJson(json) } else { Self::SingBoxJson(json) });
|
||||
}
|
||||
ps_core::links::build_outbound(text, "check", ps_core::links::LinkBackend::SingBox)
|
||||
.or_else(|_| ps_core::links::build_outbound(text, "check", ps_core::links::LinkBackend::Xray))
|
||||
.map_err(|e| anyhow!("{e}"))?;
|
||||
Ok(Self::Link(text.to_owned()))
|
||||
}
|
||||
}
|
||||
|
||||
pub fn add_outbound(c: &mut Value, tag: &str, source: &OutboundSource, detour: Option<&str>) -> Result<()> {
|
||||
let list = arr(c, &["proxy", "outbounds"]);
|
||||
if list.iter().any(|o| o["tag"] == tag) {
|
||||
bail!("an outbound '{tag}' exists");
|
||||
}
|
||||
let mut ob = match source {
|
||||
OutboundSource::Link(link) => json!({ "tag": tag, "url": link }),
|
||||
OutboundSource::SingBoxJson(j) => json!({ "tag": tag, "singBoxJson": j }),
|
||||
OutboundSource::XrayJson(j) => json!({ "tag": tag, "xrayJson": j }),
|
||||
};
|
||||
if let Some(d) = detour {
|
||||
ob["detour"] = d.into();
|
||||
}
|
||||
list.push(ob);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn remove_outbound(c: &mut Value, tag: &str) -> Result<()> {
|
||||
let list = arr(c, &["proxy", "outbounds"]);
|
||||
let before = list.len();
|
||||
list.retain(|o| o["tag"] != tag);
|
||||
if list.len() == before {
|
||||
bail!("no outbound '{tag}' in the configuration");
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn add_subscription(c: &mut Value, tag: &str, url: &str) -> Result<()> {
|
||||
let list = arr(c, &["proxy", "subscriptions"]);
|
||||
if list.iter().any(|s| s["tag"] == tag) {
|
||||
bail!("a subscription '{tag}' exists");
|
||||
}
|
||||
list.push(json!({ "tag": tag, "url": url }));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn remove_subscription(c: &mut Value, tag: &str) -> Result<()> {
|
||||
let list = arr(c, &["proxy", "subscriptions"]);
|
||||
let before = list.len();
|
||||
list.retain(|s| s["tag"] != tag);
|
||||
if list.len() == before {
|
||||
bail!("no subscription '{tag}'");
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// A rule's matches, sorted into their kinds: domains, addresses, `geosite:`, `geoip:`,
|
||||
/// `ruleset:` and `process:` ones.
|
||||
pub fn sort_matches(matches: &[String]) -> Value {
|
||||
let mut m = json!({ "domains": [], "ips": [], "geosites": [], "geoips": [], "ruleSets": [], "processNames": [] });
|
||||
for x in matches {
|
||||
let (key, value) = if let Some(v) = x.strip_prefix("geosite:") {
|
||||
("geosites", v.to_owned())
|
||||
} else if let Some(v) = x.strip_prefix("geoip:") {
|
||||
("geoips", v.to_owned())
|
||||
} else if let Some(v) = x.strip_prefix("ruleset:") {
|
||||
("ruleSets", v.to_owned())
|
||||
} else if let Some(v) = x.strip_prefix("process:") {
|
||||
("processNames", v.to_owned())
|
||||
} else if x.parse::<std::net::IpAddr>().is_ok() || x.split_once('/').is_some_and(|(a, _)| a.parse::<std::net::IpAddr>().is_ok()) {
|
||||
("ips", x.clone())
|
||||
} else {
|
||||
("domains", x.trim_start_matches('.').to_lowercase())
|
||||
};
|
||||
m[key].as_array_mut().unwrap().push(value.into());
|
||||
}
|
||||
m
|
||||
}
|
||||
|
||||
/// Sends `matches` to `target`: into the rule called `name` (the target's name without
|
||||
/// one), extended if it exists, made with priority 50 if not.
|
||||
pub fn add_rule(c: &mut Value, target: &str, matches: &[String], name: Option<&str>, priority: Option<i64>) -> Result<()> {
|
||||
if matches.is_empty() {
|
||||
bail!("a rule needs something to match");
|
||||
}
|
||||
let m = sort_matches(matches);
|
||||
let name = name.unwrap_or(target);
|
||||
let list = arr(c, &["proxy", "routing", "rules"]);
|
||||
if let Some(rule) = list.iter_mut().find(|r| r["name"] == name) {
|
||||
for (k, v) in m.as_object().unwrap() {
|
||||
let mut merged = rule[k.as_str()].as_array().cloned().unwrap_or_default();
|
||||
for x in v.as_array().unwrap() {
|
||||
if !merged.contains(x) {
|
||||
merged.push(x.clone());
|
||||
}
|
||||
}
|
||||
rule[k.as_str()] = Value::Array(merged);
|
||||
}
|
||||
rule["outbound"] = target.into();
|
||||
if let Some(p) = priority {
|
||||
rule["priority"] = p.into();
|
||||
}
|
||||
} else {
|
||||
let mut rule = m;
|
||||
rule["name"] = name.into();
|
||||
rule["outbound"] = target.into();
|
||||
rule["priority"] = priority.unwrap_or(50).into();
|
||||
list.push(rule);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn remove_rule(c: &mut Value, name: &str) -> Result<()> {
|
||||
let list = arr(c, &["proxy", "routing", "rules"]);
|
||||
let before = list.len();
|
||||
list.retain(|r| r["name"] != name);
|
||||
if list.len() == before {
|
||||
bail!("no rule named '{name}'");
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn set_rule_disabled(c: &mut Value, name: &str, disabled: bool) -> Result<()> {
|
||||
if name.is_empty() {
|
||||
bail!("a rule name");
|
||||
}
|
||||
let list = arr(c, &["proxy", "routing", "rules"]);
|
||||
let rule = list.iter_mut().find(|r| r["name"] == name).ok_or_else(|| anyhow!("no rule named '{name}'"))?;
|
||||
rule["disabled"] = disabled.into();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn set_proxy_enabled(c: &mut Value, on: bool) {
|
||||
c["proxy"]["enable"] = on.into();
|
||||
}
|
||||
|
||||
pub fn set_tun_enabled(c: &mut Value, on: bool) {
|
||||
c["proxy"]["tun"]["enable"] = on.into();
|
||||
}
|
||||
|
||||
pub fn set_zapret_enabled(c: &mut Value, on: bool) {
|
||||
c["zapret"]["enable"] = on.into();
|
||||
}
|
||||
|
||||
/// The DPI bypass's engine, by upstream's names: `zapret-discord-youtube` (Flowseal's
|
||||
/// presets) or `zapret2`.
|
||||
pub fn set_zapret_engine(c: &mut Value, engine: &str) -> Result<()> {
|
||||
if !matches!(engine, "zapret-discord-youtube" | "zapret2") {
|
||||
bail!("the engine is zapret-discord-youtube or zapret2");
|
||||
}
|
||||
c["zapret"]["engine"] = engine.into();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The zapret-discord-youtube preset, e.g. "general (ALT9)".
|
||||
pub fn set_zapret_preset(c: &mut Value, name: &str) {
|
||||
c["zapret"]["zapret-discord-youtube"]["configName"] = name.into();
|
||||
}
|
||||
|
||||
/// Which game traffic zapret handles: all, tcp, udp or null.
|
||||
pub fn set_game_filter(c: &mut Value, filter: &str) -> Result<()> {
|
||||
if !matches!(filter, "all" | "tcp" | "udp" | "null") {
|
||||
bail!("the game filter is all, tcp, udp or null");
|
||||
}
|
||||
c["zapret"]["zapret-discord-youtube"]["gameFilter"] = filter.into();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn set_tg_ws_proxy_enabled(c: &mut Value, on: bool) {
|
||||
c["tgWsProxy"]["enable"] = on.into();
|
||||
}
|
||||
|
||||
/// Any option by its path, e.g. `["zapret", "zapret2", "ipv6"]`; the objects above it are
|
||||
/// made when missing.
|
||||
pub fn set_path(c: &mut Value, path: &[&str], value: Value) {
|
||||
let mut cur = c;
|
||||
for p in path {
|
||||
if !cur.is_object() {
|
||||
*cur = json!({});
|
||||
}
|
||||
cur = &mut cur[*p];
|
||||
}
|
||||
*cur = value;
|
||||
}
|
||||
|
||||
/// whitelist-bypass's platforms, as its options name them.
|
||||
pub const WL_PLATFORMS: [&str; 5] = ["wbstream", "telemost", "dion", "bitrix", "vk"];
|
||||
|
||||
/// A whitelist-bypass joiner or creator (`role`: "joiners" or "creators") on `platform`. A name
|
||||
/// is one of either: `proxy-ctl wl` takes them by name alone.
|
||||
pub fn add_wl(c: &mut Value, role: &str, name: &str, platform: &str) -> Result<()> {
|
||||
if !matches!(role, "joiners" | "creators") {
|
||||
bail!("a whitelist-bypass role is joiners or creators");
|
||||
}
|
||||
if !ps_core::config::path_name_ok(name) {
|
||||
bail!("a name takes letters, digits, '.', '_' and '-', and no leading dot");
|
||||
}
|
||||
if !WL_PLATFORMS.contains(&platform) {
|
||||
bail!("no platform '{platform}': {}", WL_PLATFORMS.join(", "));
|
||||
}
|
||||
if role == "joiners" && platform == "vk" {
|
||||
bail!("VK has no joiner, only creators");
|
||||
}
|
||||
let wl = &c["whitelistBypass"];
|
||||
if wl["joiners"].get(name).is_some() || wl["creators"].get(name).is_some() {
|
||||
bail!("'{name}' is taken");
|
||||
}
|
||||
set_path(c, &["whitelistBypass", role, name], json!({ "platform": platform }));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn remove_wl(c: &mut Value, role: &str, name: &str) -> Result<()> {
|
||||
match c.get_mut("whitelistBypass").and_then(|w| w.get_mut(role)).and_then(Value::as_object_mut).and_then(|o| o.remove(name)) {
|
||||
Some(_) => Ok(()),
|
||||
None => bail!("no whitelist-bypass {} '{name}'", role.trim_end_matches('s')),
|
||||
}
|
||||
}
|
||||
|
||||
/// An AmneziaWG profile from an AmneziaVPN `vpn://` link or a `.conf`'s text: `kind` "vpn"
|
||||
/// (system-wide), "userspace" or "singBox" (an outbound of the proxy).
|
||||
pub fn add_awg_profile(c: &mut Value, name: &str, text: &str, kind: &str) -> Result<()> {
|
||||
if !ps_core::config::path_name_ok(name) || name.len() > 32 {
|
||||
bail!("a profile name takes up to 32 letters, digits, '.', '_' and '-', and no leading dot");
|
||||
}
|
||||
let text = text.trim();
|
||||
let mut profile = if text.starts_with("vpn://") {
|
||||
json!({ "vpn": text })
|
||||
} else if text.contains("[Interface]") {
|
||||
json!({ "config": text })
|
||||
} else {
|
||||
bail!("paste an AmneziaVPN vpn:// link or a .conf (with its [Interface])");
|
||||
};
|
||||
match kind {
|
||||
"vpn" => {}
|
||||
"userspace" | "singBox" => profile["asOutbound"] = kind.into(),
|
||||
_ => bail!("a profile is a system-wide VPN or an outbound (userspace, singBox)"),
|
||||
}
|
||||
if c["amneziaWg"]["profiles"].get(name).is_some() {
|
||||
bail!("there is a profile '{name}' already");
|
||||
}
|
||||
set_path(c, &["amneziaWg", "profiles", name], profile);
|
||||
set_path(c, &["amneziaWg", "enable"], true.into());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn remove_awg_profile(c: &mut Value, name: &str) -> Result<()> {
|
||||
match c.get_mut("amneziaWg").and_then(|w| w.get_mut("profiles")).and_then(Value::as_object_mut).and_then(|o| o.remove(name)) {
|
||||
Some(_) => Ok(()),
|
||||
None => bail!("no AmneziaWG profile '{name}'"),
|
||||
}
|
||||
}
|
||||
|
||||
/// The sites an engine also handles and those it leaves alone: for `zapret-discord-youtube`
|
||||
/// beside its release's lists, for `zapret2` beside its strategies' own.
|
||||
pub fn set_zapret_sites(c: &mut Value, engine: &str, domains: &[String], exclude: &[String]) -> Result<()> {
|
||||
if !matches!(engine, "zapret-discord-youtube" | "zapret2") {
|
||||
bail!("the engine is zapret-discord-youtube or zapret2");
|
||||
}
|
||||
let clean = |list: &[String]| -> Vec<Value> {
|
||||
let mut out: Vec<Value> = Vec::new();
|
||||
for d in list.iter().map(|d| d.trim().trim_start_matches('.').to_lowercase()).filter(|d| !d.is_empty()) {
|
||||
if !out.contains(&Value::from(d.as_str())) {
|
||||
out.push(d.into());
|
||||
}
|
||||
}
|
||||
out
|
||||
};
|
||||
c["zapret"][engine]["domains"] = Value::Array(clean(domains));
|
||||
c["zapret"][engine]["excludeDomains"] = Value::Array(clean(exclude));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn amneziawg_profiles_come_from_links_or_confs() {
|
||||
let mut c = json!({});
|
||||
add_awg_profile(&mut c, "home", "vpn://AAAA", "vpn").unwrap();
|
||||
add_awg_profile(&mut c, "exit", "[Interface]\nPrivateKey = x\n", "userspace").unwrap();
|
||||
assert_eq!(c["amneziaWg"]["profiles"]["home"], json!({ "vpn": "vpn://AAAA" }));
|
||||
assert_eq!(c["amneziaWg"]["profiles"]["exit"]["asOutbound"], "userspace");
|
||||
assert_eq!(c["amneziaWg"]["enable"], true);
|
||||
assert!(add_awg_profile(&mut c, "home", "vpn://B", "vpn").is_err());
|
||||
assert!(add_awg_profile(&mut c, "x", "hello", "vpn").is_err());
|
||||
assert!(add_awg_profile(&mut c, "a/b", "vpn://B", "vpn").is_err());
|
||||
remove_awg_profile(&mut c, "home").unwrap();
|
||||
assert!(remove_awg_profile(&mut c, "home").is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn whitelist_bypass_entries_are_added_once_and_removed() {
|
||||
let mut c = json!({});
|
||||
add_wl(&mut c, "joiners", "wl", "wbstream").unwrap();
|
||||
add_wl(&mut c, "creators", "laptop", "vk").unwrap();
|
||||
assert_eq!(c["whitelistBypass"]["joiners"]["wl"], json!({ "platform": "wbstream" }));
|
||||
assert!(add_wl(&mut c, "creators", "wl", "dion").is_err(), "a name is one of either");
|
||||
assert!(add_wl(&mut c, "joiners", "phone", "vk").is_err(), "VK has no joiner");
|
||||
assert!(add_wl(&mut c, "joiners", "phone", "zoom").is_err());
|
||||
assert!(add_wl(&mut c, "joiners", "../x", "wbstream").is_err());
|
||||
assert!(add_wl(&mut c, "joiners", "CON", "wbstream").is_err());
|
||||
remove_wl(&mut c, "joiners", "wl").unwrap();
|
||||
assert!(remove_wl(&mut c, "joiners", "wl").is_err());
|
||||
assert_eq!(c["whitelistBypass"]["creators"]["laptop"]["platform"], "vk");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn outbounds_are_added_once_and_removed() {
|
||||
let mut c = json!({});
|
||||
let src = OutboundSource::parse("ss://YWVzLTEyOC1nY206cGFzcw@1.2.3.4:8388#My%20Server").unwrap();
|
||||
add_outbound(&mut c, "nl", &src, Some("hop")).unwrap();
|
||||
assert_eq!(c["proxy"]["outbounds"][0]["detour"], "hop");
|
||||
assert!(add_outbound(&mut c, "nl", &src, None).is_err());
|
||||
remove_outbound(&mut c, "nl").unwrap();
|
||||
assert!(remove_outbound(&mut c, "nl").is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sources_are_links_or_either_json() {
|
||||
assert!(matches!(OutboundSource::parse(r#"{"protocol":"vless"}"#).unwrap(), OutboundSource::XrayJson(_)));
|
||||
assert!(matches!(OutboundSource::parse(r#" {"type":"vless"}"#).unwrap(), OutboundSource::SingBoxJson(_)));
|
||||
assert!(OutboundSource::parse("not a link").is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tags_come_from_the_remark_or_the_host() {
|
||||
assert_eq!(link_tag("ss://x@1.2.3.4:8388#My%20Server"), "My-Server");
|
||||
assert_eq!(link_tag("vless://id@example.com:443?security=tls"), "example-com");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rules_are_extended_by_name() {
|
||||
let mut c = json!({});
|
||||
add_rule(&mut c, "direct", &["Example.com".into(), "10.0.0.0/8".into(), "process:steam.exe".into()], None, None).unwrap();
|
||||
add_rule(&mut c, "direct", &["example.com".into(), "geosite:cn".into()], None, Some(10)).unwrap();
|
||||
let r = &c["proxy"]["routing"]["rules"][0];
|
||||
assert_eq!(r["domains"], json!(["example.com"]));
|
||||
assert_eq!(r["ips"], json!(["10.0.0.0/8"]));
|
||||
assert_eq!(r["processNames"], json!(["steam.exe"]));
|
||||
assert_eq!(r["geosites"], json!(["cn"]));
|
||||
assert_eq!(r["priority"], 10);
|
||||
set_rule_disabled(&mut c, "direct", true).unwrap();
|
||||
assert_eq!(c["proxy"]["routing"]["rules"][0]["disabled"], true);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn paths_and_site_lists() {
|
||||
let mut c = json!({ "zapret": null });
|
||||
set_path(&mut c, &["zapret", "zapret2", "ipv6"], true.into());
|
||||
assert_eq!(c["zapret"]["zapret2"]["ipv6"], true);
|
||||
set_zapret_sites(&mut c, "zapret2", &[" .Example.com".into(), "".into(), "example.com".into()], &["bank.example".into()]).unwrap();
|
||||
assert_eq!(c["zapret"]["zapret2"]["domains"], json!(["example.com"]));
|
||||
assert_eq!(c["zapret"]["zapret2"]["excludeDomains"], json!(["bank.example"]));
|
||||
assert!(set_zapret_sites(&mut c, "goodbyedpi", &[], &[]).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn zapret_settings_are_checked() {
|
||||
let mut c = json!({});
|
||||
assert!(set_game_filter(&mut c, "everything").is_err());
|
||||
set_game_filter(&mut c, "udp").unwrap();
|
||||
assert!(set_zapret_engine(&mut c, "goodbyedpi").is_err());
|
||||
set_zapret_engine(&mut c, "zapret2").unwrap();
|
||||
assert_eq!(c["zapret"], json!({ "engine": "zapret2", "zapret-discord-youtube": { "gameFilter": "udp" } }));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,155 @@
|
||||
//! The service's client side, shared by proxy-ctl and the app: requests, configuration
|
||||
//! edits made against the revision they read, and the edits both make ([`edits`]).
|
||||
|
||||
pub mod edits;
|
||||
|
||||
use anyhow::{Result, bail};
|
||||
use ps_ipc::transport::{self, Address};
|
||||
use ps_ipc::{Request, Response};
|
||||
use serde_json::Value;
|
||||
|
||||
/// What a configuration edit got back: the new revision, the validator's notes, and the
|
||||
/// error applying it, when it was saved but did not apply.
|
||||
#[derive(Debug, Clone, Default)]
|
||||
pub struct Saved {
|
||||
pub revision: Option<u64>,
|
||||
pub issues: Vec<Issue>,
|
||||
pub apply_error: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct Issue {
|
||||
pub severity: String,
|
||||
pub path: String,
|
||||
pub message: String,
|
||||
}
|
||||
|
||||
impl std::fmt::Display for Issue {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
write!(f, "{}: {}: {}", self.severity, self.path, self.message)
|
||||
}
|
||||
}
|
||||
|
||||
/// The validator's notes in a response's data.
|
||||
pub fn issues(data: &Value) -> Vec<Issue> {
|
||||
data["issues"]
|
||||
.as_array()
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.map(|i| Issue {
|
||||
severity: i["severity"].as_str().unwrap_or("").to_owned(),
|
||||
path: i["path"].as_str().unwrap_or("").to_owned(),
|
||||
message: i["message"].as_str().unwrap_or("").to_owned(),
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Client {
|
||||
pub addr: Address,
|
||||
}
|
||||
|
||||
impl Client {
|
||||
pub fn new(addr: Address) -> Self {
|
||||
Self { addr }
|
||||
}
|
||||
|
||||
/// One request; a refusal is an error carrying the service's words and its notes.
|
||||
pub async fn call(&self, req: Request) -> Result<Value> {
|
||||
let resp: Response = transport::call(&self.addr, &req).await?;
|
||||
if !resp.ok {
|
||||
let mut msg = resp.error.unwrap_or_else(|| "failed".into());
|
||||
for i in issues(&resp.data) {
|
||||
msg.push_str(&format!("\n {i}"));
|
||||
}
|
||||
bail!(msg);
|
||||
}
|
||||
Ok(resp.data)
|
||||
}
|
||||
|
||||
/// Reads the configuration, lets `edit` change it, and writes it back against the
|
||||
/// revision read; a concurrent change is read again and `edit` made again.
|
||||
pub async fn edit(&self, edit: impl Fn(&mut Value) -> Result<()>) -> Result<Saved> {
|
||||
for _ in 0..3 {
|
||||
let got = self.call(Request::ConfigGet).await?;
|
||||
let mut config = got["config"].clone();
|
||||
edit(&mut config)?;
|
||||
match self.call(Request::ConfigSet { config, base: got["revision"].as_u64() }).await {
|
||||
Err(e) if e.to_string().contains("changed since revision") => continue,
|
||||
other => {
|
||||
let r = other?;
|
||||
return Ok(Saved {
|
||||
revision: r["revision"].as_u64(),
|
||||
issues: issues(&r),
|
||||
apply_error: r["error"].as_str().map(str::to_owned),
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
bail!("the configuration kept changing; try again")
|
||||
}
|
||||
|
||||
/// Log lines (every unit's without `unit`) as `(unit, line)`, the last `lines` and, with
|
||||
/// `follow`, each new one, until `each` says stop.
|
||||
pub async fn logs(&self, unit: Option<String>, lines: usize, follow: bool, mut each: impl FnMut(&str, &str) -> bool) -> Result<()> {
|
||||
let mut take = |r: Response| {
|
||||
let one = |l: &Value| (l["unit"].as_str().unwrap_or("").to_owned(), l["line"].as_str().unwrap_or("").to_owned());
|
||||
match &r.data {
|
||||
Value::Array(ls) => ls.iter().map(one).all(|(u, l)| each(&u, &l)),
|
||||
d if d.is_object() => {
|
||||
let (u, l) = one(d);
|
||||
each(&u, &l)
|
||||
}
|
||||
_ => true,
|
||||
}
|
||||
};
|
||||
let req = Request::Logs { unit, lines, follow };
|
||||
if follow {
|
||||
let mut refused = None;
|
||||
transport::stream(&self.addr, &req, |r| {
|
||||
if !r.ok {
|
||||
refused = Some(r.error.unwrap_or_else(|| "failed".into()));
|
||||
return false;
|
||||
}
|
||||
take(r)
|
||||
})
|
||||
.await?;
|
||||
if let Some(e) = refused {
|
||||
bail!(e);
|
||||
}
|
||||
} else {
|
||||
let r = transport::call(&self.addr, &req).await?;
|
||||
if !r.ok {
|
||||
bail!(r.error.unwrap_or_else(|| "failed".into()));
|
||||
}
|
||||
take(r);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// A Unix time as `YYYY-MM-DD HH:MM UTC`.
|
||||
pub fn utc(ts: u64) -> String {
|
||||
let (days, secs) = ((ts / 86400) as i64, ts % 86400);
|
||||
// Howard Hinnant's civil_from_days.
|
||||
let z = days + 719_468;
|
||||
let era = z.div_euclid(146_097);
|
||||
let doe = z - era * 146_097;
|
||||
let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146_096) / 365;
|
||||
let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
|
||||
let mp = (5 * doy + 2) / 153;
|
||||
let d = doy - (153 * mp + 2) / 5 + 1;
|
||||
let m = if mp < 10 { mp + 3 } else { mp - 9 };
|
||||
let y = yoe + era * 400 + i64::from(m <= 2);
|
||||
format!("{y:04}-{m:02}-{d:02} {:02}:{:02} UTC", secs / 3600, secs % 3600 / 60)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod time_tests {
|
||||
#[test]
|
||||
fn unix_times_read_as_dates() {
|
||||
assert_eq!(super::utc(0), "1970-01-01 00:00 UTC");
|
||||
assert_eq!(super::utc(951_782_400), "2000-02-29 00:00 UTC");
|
||||
assert_eq!(super::utc(1_793_190_240), "2026-10-28 12:24 UTC");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
[package]
|
||||
name = "ps-core"
|
||||
description = "Proxy Suite for Windows: config model, link parsing and backend config rendering"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
|
||||
[dependencies]
|
||||
base64.workspace = true
|
||||
flate2 = "1"
|
||||
serde.workspace = true
|
||||
serde_json.workspace = true
|
||||
regex.workspace = true
|
||||
thiserror.workspace = true
|
||||
percent-encoding.workspace = true
|
||||
ipnet.workspace = true
|
||||
indexmap.workspace = true
|
||||
psl = "2"
|
||||
|
||||
[dev-dependencies]
|
||||
@@ -0,0 +1,22 @@
|
||||
//! For the parity check against upstream (tools/parity/links.py): JSON lines in,
|
||||
//! `{"url", "tag", "backend"}`, JSON lines out, `{"ok": outbound}` or `{"error": message}`.
|
||||
|
||||
use std::io::{BufRead, Write};
|
||||
|
||||
use ps_core::links::{LinkBackend, build_outbound};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
fn main() {
|
||||
let stdout = std::io::stdout();
|
||||
let mut out = stdout.lock();
|
||||
for line in std::io::stdin().lock().lines() {
|
||||
let line = line.expect("stdin");
|
||||
let req: Value = serde_json::from_str(&line).expect("a JSON request");
|
||||
let backend = if req["backend"] == "xray" { LinkBackend::Xray } else { LinkBackend::SingBox };
|
||||
let result = match build_outbound(req["url"].as_str().unwrap(), req["tag"].as_str().unwrap(), backend) {
|
||||
Ok(ob) => json!({ "ok": ob }),
|
||||
Err(e) => json!({ "error": e.to_string() }),
|
||||
};
|
||||
writeln!(out, "{result}").unwrap();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
//! For tools/winws-dry-run.sh: winws2's arguments as the service builds them, one per line.
|
||||
//! `zapret2_args <component dir> <component dir as Windows sees it> <state dir as Windows sees it>
|
||||
//! [<extras dir> <extras dir as Windows sees it> <extras dir as Cygwin sees it> keenetic|z2k]`
|
||||
|
||||
use ps_core::config::{StrategySource, Zapret2};
|
||||
use ps_core::zapret2::{Extras, Paths, args, keenetic, z2k};
|
||||
|
||||
fn main() {
|
||||
let a: Vec<String> = std::env::args().collect();
|
||||
let conf = std::fs::read_to_string(std::path::Path::new(&a[1]).join("keenetic").join("nfqws2.conf")).unwrap();
|
||||
let (comp, state) = (&a[2], &a[3]);
|
||||
let mut z = Zapret2 { domains: vec!["rutracker.org".into()], ..Default::default() };
|
||||
let mut source = keenetic(&conf, &format!("{comp}keenetic\\")).unwrap();
|
||||
let mut extras = None;
|
||||
if let [_, _, _, _, dir, win, cyg, kind] = &a[..] {
|
||||
let read = |f: &str| std::fs::read_to_string(std::path::Path::new(dir).join("z2k").join(f)).unwrap();
|
||||
if kind == "z2k" {
|
||||
z.strategy_source = StrategySource::Z2k;
|
||||
source = z2k(
|
||||
&read("profiles.plain"),
|
||||
&read("profiles.learn"),
|
||||
&read("blobs"),
|
||||
&read("ports"),
|
||||
&format!("{cyg}z2k"),
|
||||
&format!("{cyg}z2k/root"),
|
||||
&format!("{cyg}z2k/files/lua/"),
|
||||
)
|
||||
.unwrap();
|
||||
}
|
||||
let state_cyg = format!("/cygdrive/{}", state.replace(':', "").replace('\\', "/").to_lowercase());
|
||||
extras = Some(Extras {
|
||||
lua: format!("{win}lua\\"),
|
||||
z2k_lua: format!("{win}z2k\\files\\lua\\"),
|
||||
auto_lua: format!("{state_cyg}learned/zapret-hosts-auto.txt"),
|
||||
exclude_lua: vec![format!("{state_cyg}zapret-hosts-user-exclude.txt")],
|
||||
});
|
||||
}
|
||||
let paths = Paths {
|
||||
lua: format!("{comp}lua\\"),
|
||||
user: format!("{state}zapret-hosts-user.txt"),
|
||||
exclude: format!("{state}zapret-hosts-user-exclude.txt"),
|
||||
auto: format!("{state}learned\\zapret-hosts-auto.txt"),
|
||||
extras,
|
||||
// Beside sing-box's TUN, as its defaults are: checked by winws2 with the rest.
|
||||
keep_off: ps_core::zapret::tun_exclusion("172.19.0.1/30", Some("fd66:19::1/64")),
|
||||
};
|
||||
for arg in args(&z, &source, &paths, false).unwrap() {
|
||||
println!("{arg}");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
//! For tools/winws-dry-run.sh: a preset's winws arguments as the service builds them, one
|
||||
//! per line. `zapret_args <release dir> <release dir as Windows sees it> <lists dir as Windows
|
||||
//! sees it> <preset> <game filter> [<hostlistRules JSON> <lists dir>]`, Windows paths with a
|
||||
//! trailing separator. With rules, their lists are written into the lists dir.
|
||||
|
||||
use ps_core::config::{GameFilter, HostlistRule};
|
||||
use ps_core::zapret::{ReleaseLists, expand, find_preset, preset_args, rule, rule_lists, with_rules};
|
||||
|
||||
fn main() {
|
||||
let a: Vec<String> = std::env::args().collect();
|
||||
let (release, win_root, win_lists, preset, game) = (&a[1], &a[2], &a[3], &a[4], &a[5]);
|
||||
let release = std::path::Path::new(release);
|
||||
let files: Vec<String> = std::fs::read_dir(release).unwrap().filter_map(|e| e.ok()?.file_name().into_string().ok()).collect();
|
||||
let game: GameFilter = serde_json::from_value(serde_json::json!(game)).unwrap();
|
||||
let bin = format!("{win_root}bin\\");
|
||||
let ex = |args: &[String]| expand(args, &bin, win_lists, win_root, game);
|
||||
let args_of = |name: &str| -> Result<Vec<String>, String> {
|
||||
let file = find_preset(&files, name)?;
|
||||
Ok(ex(&preset_args(&std::fs::read_to_string(release.join(file)).unwrap())?))
|
||||
};
|
||||
let mut args = args_of(preset).unwrap();
|
||||
if let (Some(json), Some(lists)) = (a.get(6), a.get(7)) {
|
||||
let read = |f: &str| std::fs::read_to_string(release.join("lists").join(f)).unwrap_or_default();
|
||||
let (general, google, ipset_all) = (read("list-general.txt"), read("list-google.txt"), read("ipset-all.txt"));
|
||||
let release_lists = ReleaseLists { general: &general, google: &google, ipset_all: &ipset_all };
|
||||
let raw: Vec<HostlistRule> = serde_json::from_str(&std::fs::read_to_string(json).unwrap()).unwrap();
|
||||
let rules: Vec<_> = raw.iter().map(|r| rule(r, &release_lists).unwrap()).collect();
|
||||
for r in &rules {
|
||||
let (list, ipset) = rule_lists(r);
|
||||
for (file, entries) in [(list, &r.domains), (ipset, &r.ips)] {
|
||||
if !entries.is_empty() {
|
||||
std::fs::write(std::path::Path::new(lists).join(file), format!("{}\n", entries.join("\n"))).unwrap();
|
||||
}
|
||||
}
|
||||
}
|
||||
args = match with_rules(args, &rules, win_lists, &args_of, &ex) {
|
||||
Ok(a) => a,
|
||||
Err(e) => {
|
||||
eprintln!("{e}");
|
||||
std::process::exit(2);
|
||||
}
|
||||
};
|
||||
}
|
||||
for arg in args {
|
||||
println!("{arg}");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,865 @@
|
||||
//! autoProxy's judgement, as upstream decides it: what one fetch through an exit says
|
||||
//! (proxy_ctl.py's `proxy auto probe`), the walk over the exits for a destination, the order
|
||||
//! they are walked in (autoproxy-rounds.jq), the strikes against exits a destination refused
|
||||
//! (autoproxy-strike.jq), what is remembered (autoproxy-run.template.sh, autoproxy-edit.jq)
|
||||
//! and the rule-sets sing-box takes it from (autoproxy-render.template.sh).
|
||||
//!
|
||||
//! The fetches themselves are the service's; this is the deciding, so it is tested here.
|
||||
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
use std::sync::LazyLock;
|
||||
|
||||
use regex::Regex;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use crate::links::subscription::{nearness, url_parts};
|
||||
|
||||
/// The exit that is this host: always the first.
|
||||
pub const DIRECT: &str = "direct";
|
||||
|
||||
/// The paths a destination is probed at: the page, then robots.txt, which some sites serve
|
||||
/// where their front page refuses a client that is not a browser.
|
||||
pub const PATHS: [&str; 2] = ["/", "/robots.txt"];
|
||||
|
||||
/// One fetch through one exit, at the first hop that is not a same-site redirect.
|
||||
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct Fetch {
|
||||
/// The answer's status; none when no answer came (TLS or the connection failed first).
|
||||
pub status: Option<u16>,
|
||||
/// The PROBE_BLOCK_PAGES name a refusal's page matched, "" for none.
|
||||
#[serde(default)]
|
||||
pub block: String,
|
||||
/// A redirect's Location.
|
||||
#[serde(default)]
|
||||
pub location: String,
|
||||
/// Bytes read of the body (at most what was read to judge it).
|
||||
#[serde(default)]
|
||||
pub bytes: u64,
|
||||
/// Why no answer came.
|
||||
#[serde(default)]
|
||||
pub error: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub enum Judgement {
|
||||
/// Content.
|
||||
Ok,
|
||||
/// Failed before the origin spoke: the censor's doing, zapret's job.
|
||||
Dead,
|
||||
/// The site's security layer refused this address: an exit past it helps.
|
||||
Wall,
|
||||
/// The origin answered and refused: another exit can fix it.
|
||||
Blocked,
|
||||
}
|
||||
|
||||
/// Block pages, by name: (kind, pattern over a refusal's headers and the first 8 KiB of its
|
||||
/// body). "address": the address itself was refused, so an exit that gets past it reaches the
|
||||
/// site; "geo": its country was, which is an ordinary refusal.
|
||||
static BLOCK_PAGES: LazyLock<Vec<(&str, &str, Regex)>> = LazyLock::new(|| {
|
||||
[
|
||||
("aws-waf", "address", r"(?ims)^server: cloudfront\b.*Request blocked\."),
|
||||
("cloudfront-geo", "geo", r"(?i)configured to block access from your country"),
|
||||
("cloudflare", "address", r#"(?im)^cf-mitigated: challenge|cf-error-code">10(06|07|08|20)<|error code: 10(06|07|08|20)\b"#),
|
||||
("cloudflare-geo", "geo", r#"(?i)cf-error-code">1009<|error code: 1009\b"#),
|
||||
("akamai", "address", r"(?ims)^server: AkamaiGHost\b.*Access Denied"),
|
||||
("imperva", "address", r"(?i)Incapsula incident ID"),
|
||||
("datadome", "address", r"(?im)^x-datadome:"),
|
||||
]
|
||||
.into_iter()
|
||||
.map(|(name, kind, re)| (name, kind, Regex::new(re).expect("a valid pattern")))
|
||||
.collect()
|
||||
});
|
||||
|
||||
static BLOCK_REDIRECT: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"(?i)unavailable|not-available|blocked|geo|region|restricted").unwrap());
|
||||
static HOST: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"^[a-zA-Z0-9._-]+\.[a-zA-Z]{2,}$").unwrap());
|
||||
|
||||
/// A host name autoProxy probes or routes: letters, digits, dots, '_' and '-', with a TLD.
|
||||
pub fn host_ok(host: &str) -> bool {
|
||||
host.len() <= 253 && HOST.is_match(host)
|
||||
}
|
||||
|
||||
/// The name of the block page a refusal (`status` 4xx or 5xx) shows, "" for none. `head` is
|
||||
/// its headers as received, `body` its first bytes.
|
||||
pub fn block_page(status: u16, head: &str, body: &[u8]) -> String {
|
||||
if !(400..600).contains(&status) {
|
||||
return String::new();
|
||||
}
|
||||
let body: String = body.iter().take(8192).map(|&b| b as char).collect();
|
||||
let text = format!("{head}\n\n{body}\n\n");
|
||||
BLOCK_PAGES.iter().find(|(_, _, re)| re.is_match(&text)).map(|(name, _, _)| (*name).to_owned()).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// The last two labels: a redirect is followed only within them.
|
||||
pub fn site(url: &str) -> String {
|
||||
let host = url_parts::split(url).ok().and_then(|u| u.hostname).unwrap_or_default();
|
||||
let labels: Vec<&str> = host.split('.').collect();
|
||||
labels[labels.len().saturating_sub(2)..].join(".")
|
||||
}
|
||||
|
||||
/// Whether a Location names this host or its LAN (localhost, or an address literal in any of
|
||||
/// the forms curl takes): never followed.
|
||||
pub fn local_target(url: &str) -> bool {
|
||||
match url_parts::split(url) {
|
||||
Ok(u) => nearness(u.hostname.as_deref()) > 0,
|
||||
Err(_) => true,
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether a redirect's target says the content is refused (a "not available" page).
|
||||
pub fn redirect_is_block(location: &str) -> bool {
|
||||
BLOCK_REDIRECT.is_match(location)
|
||||
}
|
||||
|
||||
fn http_ok(f: &Fetch) -> bool {
|
||||
match f.status {
|
||||
Some(s) if (200..300).contains(&s) || s == 401 || s == 404 => true,
|
||||
Some(s) if (300..400).contains(&s) => !redirect_is_block(&f.location),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn judge(f: &Fetch) -> Judgement {
|
||||
if f.status.is_none() {
|
||||
return Judgement::Dead;
|
||||
}
|
||||
if http_ok(f) {
|
||||
return Judgement::Ok;
|
||||
}
|
||||
let address = BLOCK_PAGES.iter().any(|(name, kind, _)| *name == f.block && *kind == "address");
|
||||
if address { Judgement::Wall } else { Judgement::Blocked }
|
||||
}
|
||||
|
||||
/// Content; or, where direct hit a wall, any answer from the origin past it.
|
||||
pub fn reaches(direct: Judgement, j: Judgement) -> bool {
|
||||
j == Judgement::Ok || (direct == Judgement::Wall && j == Judgement::Blocked)
|
||||
}
|
||||
|
||||
/// "ok": direct gets it. "destination": an exit reaches what direct does not, past a refusal:
|
||||
/// route through it. "censor": direct dies on the way while an exit reaches it, which zapret
|
||||
/// is for: it stays direct. "both-fail" and "unreachable": no exit helps.
|
||||
pub fn verdict(direct: &Fetch, via: &Fetch) -> &'static str {
|
||||
let d = judge(direct);
|
||||
if d == Judgement::Ok {
|
||||
return "ok";
|
||||
}
|
||||
if reaches(d, judge(via)) {
|
||||
return if d == Judgement::Dead { "censor" } else { "destination" };
|
||||
}
|
||||
if d == Judgement::Dead { "unreachable" } else { "both-fail" }
|
||||
}
|
||||
|
||||
pub fn verdict_text(verdict: &str, exit: Option<&str>) -> String {
|
||||
match verdict {
|
||||
"ok" => "reachable directly - nothing to do".into(),
|
||||
"destination" => format!("destination-side block - route via {}", exit.unwrap_or("proxy")),
|
||||
"censor" => "censor-side block - zapret's territory, not proxied".into(),
|
||||
"both-fail" => "fails through every egress - not an egress problem".into(),
|
||||
"unreachable" => "no egress reaches it at all".into(),
|
||||
_ => "inconclusive".into(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn describe(f: &Fetch) -> String {
|
||||
let Some(status) = f.status else {
|
||||
return if f.error.is_empty() { "no answer".into() } else { format!("no answer ({})", f.error) };
|
||||
};
|
||||
let mut text = format!("{status}, {} bytes", f.bytes);
|
||||
if !f.block.is_empty() {
|
||||
text.push_str(&format!(", {} page", f.block));
|
||||
}
|
||||
if !f.location.is_empty() {
|
||||
text.push_str(&format!(" -> {}", f.location));
|
||||
}
|
||||
text
|
||||
}
|
||||
|
||||
/// One request of a walk.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct Row {
|
||||
pub tag: String,
|
||||
pub path: String,
|
||||
pub fetch: Fetch,
|
||||
pub judgement: Judgement,
|
||||
}
|
||||
|
||||
/// What a probe found: the verdict, the exit that reached it (none for "ok" and the failures),
|
||||
/// the path it was judged on, and every request made.
|
||||
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct Probe {
|
||||
pub domain: String,
|
||||
pub verdict: String,
|
||||
pub exit: Option<String>,
|
||||
pub path: String,
|
||||
pub rows: Vec<Row>,
|
||||
}
|
||||
|
||||
/// Walks the exits (`exits[0]` is direct) and stops at the first that reaches `domain`: gets
|
||||
/// content, or gets past a wall direct hit. `keep_going` still tries the rest, keeping that
|
||||
/// first one. `fetch(tag, path)` is one request through one exit.
|
||||
pub async fn walk<F, Fut>(domain: &str, exits: &[String], paths: &[&str], keep_going: bool, mut fetch: F) -> Probe
|
||||
where
|
||||
F: FnMut(String, String) -> Fut,
|
||||
Fut: Future<Output = Fetch>,
|
||||
{
|
||||
let mut p = Probe { domain: domain.to_owned(), ..Default::default() };
|
||||
let Some((direct_tag, others)) = exits.split_first() else {
|
||||
p.verdict = "error".into();
|
||||
return p;
|
||||
};
|
||||
let mut first_direct: Option<Fetch> = None;
|
||||
for path in paths {
|
||||
let direct = fetch(direct_tag.clone(), (*path).to_owned()).await;
|
||||
let dj = judge(&direct);
|
||||
p.rows.push(Row { tag: direct_tag.clone(), path: (*path).to_owned(), fetch: direct.clone(), judgement: dj });
|
||||
first_direct.get_or_insert_with(|| direct.clone());
|
||||
if dj == Judgement::Ok && p.verdict.is_empty() {
|
||||
p.verdict = "ok".into();
|
||||
p.path = (*path).to_owned();
|
||||
if !keep_going {
|
||||
return p;
|
||||
}
|
||||
}
|
||||
for tag in others {
|
||||
let via = fetch(tag.clone(), (*path).to_owned()).await;
|
||||
let j = judge(&via);
|
||||
p.rows.push(Row { tag: tag.clone(), path: (*path).to_owned(), fetch: via.clone(), judgement: j });
|
||||
if reaches(dj, j) && p.verdict.is_empty() {
|
||||
p.verdict = verdict(&direct, &via).into();
|
||||
p.exit = Some(tag.clone());
|
||||
p.path = (*path).to_owned();
|
||||
if !keep_going {
|
||||
return p;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if p.verdict.is_empty() {
|
||||
let dead = first_direct.as_ref().is_none_or(|f| judge(f) == Judgement::Dead);
|
||||
p.verdict = if dead { "unreachable" } else { "both-fail" }.into();
|
||||
p.path = paths.first().map(|s| (*s).to_owned()).unwrap_or_default();
|
||||
}
|
||||
p
|
||||
}
|
||||
|
||||
/// `--via`: can `via` carry what direct reaches? It must get content on some path and fail on
|
||||
/// none where direct succeeds. Verdict "ok" or "blocked".
|
||||
pub async fn stand_in<F, Fut>(domain: &str, via: &str, paths: &[&str], mut fetch: F) -> Probe
|
||||
where
|
||||
F: FnMut(String, String) -> Fut,
|
||||
Fut: Future<Output = Fetch>,
|
||||
{
|
||||
let mut p = Probe {
|
||||
domain: domain.to_owned(),
|
||||
verdict: "ok".into(),
|
||||
exit: Some(via.to_owned()),
|
||||
path: paths.first().map(|s| (*s).to_owned()).unwrap_or_default(),
|
||||
rows: Vec::new(),
|
||||
};
|
||||
let mut got = false;
|
||||
for path in paths {
|
||||
let direct = fetch(DIRECT.to_owned(), (*path).to_owned()).await;
|
||||
let through = fetch(via.to_owned(), (*path).to_owned()).await;
|
||||
let (dj, vj) = (judge(&direct), judge(&through));
|
||||
p.rows.push(Row { tag: DIRECT.into(), path: (*path).to_owned(), fetch: direct, judgement: dj });
|
||||
p.rows.push(Row { tag: via.to_owned(), path: (*path).to_owned(), fetch: through, judgement: vj });
|
||||
got |= vj == Judgement::Ok;
|
||||
if dj == Judgement::Ok && vj != Judgement::Ok {
|
||||
p.verdict = "blocked".into();
|
||||
}
|
||||
}
|
||||
if !got {
|
||||
p.verdict = "blocked".into();
|
||||
}
|
||||
p
|
||||
}
|
||||
|
||||
/// The registrable domain of `host` (its site: example.co.uk, foo.workers.dev), by the public
|
||||
/// suffix list with its private section; none for a public suffix itself, or a bare label.
|
||||
pub fn registrable(host: &str) -> Option<String> {
|
||||
let host = host.trim_end_matches('.').to_ascii_lowercase();
|
||||
if !host.contains('.') {
|
||||
return None;
|
||||
}
|
||||
let domain = psl::domain_str(&host)?;
|
||||
Some(domain.to_owned())
|
||||
}
|
||||
|
||||
// --- the state -----------------------------------------------------------------------------
|
||||
|
||||
/// A destination routed through an exit: probed blocked directly ("destination"), or
|
||||
/// crawling directly ("slow").
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct Route {
|
||||
pub verdict: String,
|
||||
pub exit: String,
|
||||
pub host: String,
|
||||
#[serde(default)]
|
||||
pub path: String,
|
||||
pub at: u64,
|
||||
/// "slow": times it crawled on its exit since it last did not; two move it on.
|
||||
#[serde(default, skip_serializing_if = "is_zero")]
|
||||
pub bad: u32,
|
||||
/// "slow": the exits tried, in order.
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub tried: Vec<String>,
|
||||
}
|
||||
|
||||
fn is_zero(n: &u32) -> bool {
|
||||
*n == 0
|
||||
}
|
||||
|
||||
/// What the transfer sampler saw: a host's best connection through an exit, crawling
|
||||
/// (`slow`) or not, and its fastest second.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct Observation {
|
||||
pub domain: String,
|
||||
pub host: String,
|
||||
pub exit: String,
|
||||
pub slow: bool,
|
||||
pub peak: u64,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct SlowHits {
|
||||
pub n: u32,
|
||||
pub first: u64,
|
||||
}
|
||||
|
||||
/// A site owed an exit for crawling directly, and the exits tried for it.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct SlowWant {
|
||||
pub host: String,
|
||||
#[serde(default)]
|
||||
pub tried: Vec<String>,
|
||||
}
|
||||
|
||||
/// What the last probe of a host found.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct HostVerdict {
|
||||
pub domain: String,
|
||||
pub verdict: String,
|
||||
#[serde(default)]
|
||||
pub exit: Option<String>,
|
||||
pub at: u64,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct Strike {
|
||||
pub why: String,
|
||||
pub at: u64,
|
||||
}
|
||||
|
||||
/// An exit: where it leaves from (its network, by AS), and the destinations that refused it.
|
||||
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase", default)]
|
||||
pub struct ExitInfo {
|
||||
pub ip: Option<String>,
|
||||
pub asn: Option<String>,
|
||||
pub at: u64,
|
||||
pub strikes: BTreeMap<String, Strike>,
|
||||
pub bad: bool,
|
||||
pub bad_by: Vec<String>,
|
||||
}
|
||||
|
||||
/// A host dialled directly, not yet probed: how often, and since when.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct Queued {
|
||||
pub domain: String,
|
||||
pub hits: u64,
|
||||
pub first: u64,
|
||||
}
|
||||
|
||||
/// state.json.
|
||||
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase", default)]
|
||||
pub struct State {
|
||||
/// This host's public address the verdicts are about.
|
||||
pub egress: Option<String>,
|
||||
/// Registrable domain -> the exit it is routed through.
|
||||
pub domains: BTreeMap<String, Route>,
|
||||
pub hosts: BTreeMap<String, HostVerdict>,
|
||||
pub exits: BTreeMap<String, ExitInfo>,
|
||||
pub backlog: BTreeMap<String, Queued>,
|
||||
pub last_run: u64,
|
||||
/// Hosts seen crawling directly, within a day.
|
||||
pub slow_hits: BTreeMap<String, SlowHits>,
|
||||
/// Sites owed an exit for crawling, by registrable domain.
|
||||
pub slow_want: BTreeMap<String, SlowWant>,
|
||||
/// Sites no exit carried better, left direct until then.
|
||||
pub slow_skip: BTreeMap<String, u64>,
|
||||
}
|
||||
|
||||
/// Most entries the backlog keeps: every distinct name dialled is one.
|
||||
const BACKLOG_MAX: usize = 5000;
|
||||
|
||||
impl State {
|
||||
/// `domain` refused `tags` at `now` (`why`: "wall:<page>", "refused" or "slow"), and every
|
||||
/// strike older than `ttl` goes. A domain counts once per exit; two make an exit bad.
|
||||
pub fn strike(&mut self, tags: &[String], domain: &str, why: &str, now: u64, ttl: u64) {
|
||||
for t in tags {
|
||||
self.exits.entry(t.clone()).or_default().strikes.insert(domain.to_owned(), Strike { why: why.to_owned(), at: now });
|
||||
}
|
||||
for e in self.exits.values_mut() {
|
||||
e.strikes.retain(|_, s| s.at + ttl > now);
|
||||
rebad(e);
|
||||
}
|
||||
}
|
||||
|
||||
/// `domain` back to direct, every verdict and strike about it gone.
|
||||
pub fn forget(&mut self, domain: &str) {
|
||||
self.domains.remove(domain);
|
||||
self.hosts.retain(|_, h| h.domain != domain);
|
||||
self.backlog.retain(|_, q| q.domain != domain);
|
||||
self.slow_want.remove(domain);
|
||||
self.slow_skip.remove(domain);
|
||||
for e in self.exits.values_mut() {
|
||||
if e.strikes.remove(domain).is_some() {
|
||||
rebad(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Everything learned forgotten; what each exit is, the backlog and the egress stay.
|
||||
pub fn clear(&mut self) {
|
||||
self.domains.clear();
|
||||
self.hosts.clear();
|
||||
self.slow_want.clear();
|
||||
self.slow_skip.clear();
|
||||
for e in self.exits.values_mut() {
|
||||
e.strikes.clear();
|
||||
rebad(e);
|
||||
}
|
||||
}
|
||||
|
||||
/// A new public address: every verdict was about the old one.
|
||||
pub fn new_egress(&mut self, egress: &str) {
|
||||
*self = State { egress: Some(egress.to_owned()), backlog: std::mem::take(&mut self.backlog), last_run: self.last_run, ..Default::default() };
|
||||
}
|
||||
|
||||
/// What probing `host` (of `domain`) found. A route applies to the whole domain (blocks
|
||||
/// are drawn around sites); a verdict to the host. Exits refused on the path the winner
|
||||
/// reached are struck: by a block page, or by the origin where the winner got content.
|
||||
pub fn record(&mut self, domain: &str, host: &str, p: &Probe, now: u64, ttl: u64) {
|
||||
if p.verdict == "destination"
|
||||
&& let Some(exit) = &p.exit
|
||||
{
|
||||
self.domains.insert(
|
||||
domain.to_owned(),
|
||||
Route { verdict: p.verdict.clone(), exit: exit.clone(), host: host.to_owned(), path: p.path.clone(), at: now, bad: 0, tried: Vec::new() },
|
||||
);
|
||||
}
|
||||
let exit = if p.verdict == "destination" { p.exit.clone() } else { None };
|
||||
self.hosts.insert(host.to_owned(), HostVerdict { domain: domain.to_owned(), verdict: p.verdict.clone(), exit, at: now });
|
||||
self.backlog.remove(host);
|
||||
let Some(winner) = &p.exit else { return };
|
||||
let won = p.rows.iter().find(|r| &r.tag == winner && r.path == p.path).map(|r| r.judgement);
|
||||
let mut struck: BTreeMap<String, String> = BTreeMap::new();
|
||||
for r in p.rows.iter().filter(|r| r.path == p.path && r.tag != DIRECT && &r.tag != winner) {
|
||||
let why = match r.judgement {
|
||||
Judgement::Wall => format!("wall:{}", r.fetch.block),
|
||||
Judgement::Blocked if won == Some(Judgement::Ok) => "refused".into(),
|
||||
_ => continue,
|
||||
};
|
||||
struck.entry(r.tag.clone()).or_insert(why);
|
||||
}
|
||||
for (tag, why) in struck {
|
||||
self.strike(&[tag], domain, &why, now, ttl);
|
||||
}
|
||||
}
|
||||
|
||||
/// Hosts dialled directly since the last run (`counts`: host -> (domain, hits)) into the
|
||||
/// backlog, skipping those a route covers or a verdict within the TTL judged; entries past
|
||||
/// the TTL, or covered since, go; the most dialled 5000 stay.
|
||||
pub fn queue(&mut self, counts: &BTreeMap<String, (String, u64)>, now: u64, ttl: u64) {
|
||||
self.last_run = now;
|
||||
self.hosts.retain(|_, h| h.at + ttl > now);
|
||||
for (host, (domain, hits)) in counts {
|
||||
if self.domains.contains_key(domain) || self.hosts.get(host).is_some_and(|h| h.at + ttl > now) {
|
||||
continue;
|
||||
}
|
||||
let q = self.backlog.entry(host.clone()).or_insert(Queued { domain: domain.clone(), hits: 0, first: now });
|
||||
q.hits += hits;
|
||||
}
|
||||
let domains = &self.domains;
|
||||
self.backlog.retain(|_, q| q.first + ttl > now && !domains.contains_key(&q.domain));
|
||||
if self.backlog.len() > BACKLOG_MAX {
|
||||
let mut v: Vec<(String, Queued)> = std::mem::take(&mut self.backlog).into_iter().collect();
|
||||
v.sort_by_key(|a| std::cmp::Reverse(a.1.hits));
|
||||
v.truncate(BACKLOG_MAX);
|
||||
self.backlog = v.into_iter().collect();
|
||||
}
|
||||
}
|
||||
|
||||
/// The backlog to probe, most dialled first: (domain, host).
|
||||
pub fn backlog_order(&self, now: u64, ttl: u64) -> Vec<(String, String)> {
|
||||
let mut v: Vec<(&String, &Queued)> = self
|
||||
.backlog
|
||||
.iter()
|
||||
.filter(|(h, q)| !self.domains.contains_key(&q.domain) && self.hosts.get(*h).is_none_or(|v| v.at + ttl <= now))
|
||||
.collect();
|
||||
v.sort_by(|a, b| b.1.hits.cmp(&a.1.hits).then_with(|| a.0.cmp(b.0)));
|
||||
v.into_iter().map(|(h, q)| (q.domain.clone(), h.clone())).collect()
|
||||
}
|
||||
|
||||
/// Routes to probe again, once per TTL: (domain, host, exit).
|
||||
pub fn due(&self, now: u64, ttl: u64) -> Vec<(String, String, String)> {
|
||||
self.domains
|
||||
.iter()
|
||||
.filter(|(_, r)| r.verdict == "destination" && now.saturating_sub(r.at) >= ttl)
|
||||
.map(|(d, r)| (d.clone(), r.host.clone(), r.exit.clone()))
|
||||
.collect()
|
||||
}
|
||||
}
|
||||
|
||||
impl State {
|
||||
/// What the sampler saw, folded in (autoproxy-slow-judge.jq). `hits` crawls on direct
|
||||
/// within a day make a site owed an exit (`slow_want`); once routed it is judged on that
|
||||
/// exit alone: a fast transfer keeps it, two slow ones move it to the next. Never moved:
|
||||
/// censor verdicts (zapret's) and sites skipped for a while.
|
||||
pub fn judge_slow(&mut self, obs: &[Observation], now: u64, hits: u32) {
|
||||
self.slow_hits.retain(|_, h| h.first + 86400 > now);
|
||||
for x in obs {
|
||||
if let Some(r) = self.domains.get_mut(&x.domain)
|
||||
&& r.verdict == "slow"
|
||||
{
|
||||
if x.exit != r.exit {
|
||||
} else if x.slow {
|
||||
r.bad += 1;
|
||||
} else {
|
||||
r.bad = 0;
|
||||
r.at = now;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
let skip = self.domains.contains_key(&x.domain)
|
||||
|| x.exit != DIRECT
|
||||
|| !x.slow
|
||||
|| self.slow_want.contains_key(&x.domain)
|
||||
|| self.slow_skip.get(&x.domain).is_some_and(|u| *u > now)
|
||||
|| self.hosts.get(&x.host).is_some_and(|h| h.verdict == "censor");
|
||||
if skip {
|
||||
continue;
|
||||
}
|
||||
let h = self.slow_hits.entry(x.host.clone()).or_insert(SlowHits { n: 0, first: now });
|
||||
h.n += 1;
|
||||
if h.n >= hits {
|
||||
self.slow_hits.remove(&x.host);
|
||||
self.slow_want.insert(x.domain.clone(), SlowWant { host: x.host.clone(), tried: Vec::new() });
|
||||
}
|
||||
}
|
||||
let moved: Vec<(String, Route)> =
|
||||
self.domains.iter().filter(|(_, r)| r.verdict == "slow" && r.bad >= 2).map(|(d, r)| (d.clone(), r.clone())).collect();
|
||||
for (d, r) in moved {
|
||||
self.domains.remove(&d);
|
||||
let tried = if r.tried.is_empty() { vec![r.exit.clone()] } else { r.tried.clone() };
|
||||
self.slow_want.insert(d, SlowWant { host: r.host, tried });
|
||||
}
|
||||
self.slow_skip.retain(|_, until| *until > now);
|
||||
if self.slow_hits.len() > 5000 {
|
||||
let mut v: Vec<(String, SlowHits)> = std::mem::take(&mut self.slow_hits).into_iter().collect();
|
||||
v.sort_by_key(|(_, h)| std::cmp::Reverse(h.n));
|
||||
v.truncate(5000);
|
||||
self.slow_hits = v.into_iter().collect();
|
||||
}
|
||||
while self.slow_want.len() > 500 {
|
||||
let last = self.slow_want.keys().next_back().cloned().unwrap();
|
||||
self.slow_want.remove(&last);
|
||||
}
|
||||
}
|
||||
|
||||
/// A crawling site's next exit found: routed through it.
|
||||
pub fn route_slow(&mut self, domain: &str, host: &str, exit: &str, tried: Vec<String>, now: u64) {
|
||||
self.domains.insert(
|
||||
domain.to_owned(),
|
||||
Route { verdict: "slow".into(), exit: exit.to_owned(), host: host.to_owned(), path: String::new(), at: now, bad: 0, tried },
|
||||
);
|
||||
self.slow_want.remove(domain);
|
||||
}
|
||||
|
||||
/// No exit carries a crawling site better: left direct for `ttl`.
|
||||
pub fn skip_slow(&mut self, domain: &str, now: u64, ttl: u64) {
|
||||
self.slow_skip.insert(domain.to_owned(), now + ttl);
|
||||
self.slow_want.remove(domain);
|
||||
}
|
||||
}
|
||||
|
||||
/// From Clash API `/connections` snapshots a second apart: per host and exit that moved at
|
||||
/// least `min` bytes, its best connection's fastest second, and whether it never beat `below`
|
||||
/// in any second (paced streams burst, so they read fast). Probe and test listeners skipped;
|
||||
/// `chains[0]` is the exit that carried it. (autoproxy-slow-sample.jq)
|
||||
pub fn sample_transfers(snapshots: &[Value], min: u64, below: u64) -> Vec<(String, String, bool, u64)> {
|
||||
// id -> (host, exit, [download per snapshot])
|
||||
let mut seen: BTreeMap<String, (String, String, Vec<Option<u64>>)> = BTreeMap::new();
|
||||
for (i, snap) in snapshots.iter().enumerate() {
|
||||
for c in snap["connections"].as_array().into_iter().flatten() {
|
||||
let kind = c["metadata"]["type"].as_str().unwrap_or("");
|
||||
if kind.contains("/probe-in-") || kind.ends_with("/proxy-suite-test-in") {
|
||||
continue;
|
||||
}
|
||||
let Some(id) = c["id"].as_str() else { continue };
|
||||
let host = c["metadata"]["host"].as_str().unwrap_or("").to_owned();
|
||||
let exit = c["chains"][0].as_str().unwrap_or("").to_owned();
|
||||
let e = seen.entry(id.to_owned()).or_insert_with(|| (host, exit, vec![None; snapshots.len()]));
|
||||
e.2[i] = c["download"].as_u64();
|
||||
}
|
||||
}
|
||||
let mut best: BTreeMap<(String, String), (u64, u64)> = BTreeMap::new();
|
||||
for (host, exit, d) in seen.into_values() {
|
||||
let deltas: Vec<u64> = d.windows(2).filter_map(|w| Some(w[1]?.saturating_sub(w[0]?))).collect();
|
||||
let (total, peak) = (deltas.iter().sum::<u64>(), deltas.iter().copied().max().unwrap_or(0));
|
||||
if host.is_empty() || exit.is_empty() || deltas.is_empty() || total < min {
|
||||
continue;
|
||||
}
|
||||
let b = best.entry((host, exit)).or_insert((0, 0));
|
||||
if peak >= b.0 {
|
||||
*b = (peak, total);
|
||||
}
|
||||
}
|
||||
best.into_iter().map(|((host, exit), (peak, _))| (host, exit, peak < below, peak)).collect()
|
||||
}
|
||||
|
||||
fn rebad(e: &mut ExitInfo) {
|
||||
e.bad = e.strikes.len() >= 2;
|
||||
let mut s: Vec<(&String, &Strike)> = e.strikes.iter().collect();
|
||||
s.sort_by_key(|(_, v)| v.at);
|
||||
e.bad_by = s.into_iter().map(|(d, v)| format!("{d} {}", v.why)).collect();
|
||||
}
|
||||
|
||||
/// The probe order of the exits after direct: round 1, one exit per network (AS); round 2,
|
||||
/// walked only when round 1 all refused, the rest; bad exits never take a network's round-1
|
||||
/// place and go last. Also the whole order.
|
||||
pub fn rounds(exits: &[String], state: &State) -> (Vec<String>, Vec<String>, Vec<String>) {
|
||||
let info = |t: &str| state.exits.get(t);
|
||||
let bad = |t: &str| info(t).is_some_and(|e| e.bad);
|
||||
let mut ordered: Vec<String> = exits.iter().filter(|t| t.as_str() != DIRECT && !bad(t)).cloned().collect();
|
||||
ordered.extend(exits.iter().filter(|t| t.as_str() != DIRECT && bad(t)).cloned());
|
||||
let (mut r1, mut r2) = (Vec::new(), Vec::new());
|
||||
let mut seen = BTreeSet::new();
|
||||
for t in &ordered {
|
||||
let asn = info(t).and_then(|e| e.asn.clone()).unwrap_or_default();
|
||||
if bad(t) {
|
||||
r2.push(t.clone());
|
||||
} else if asn.is_empty() || seen.insert(asn) {
|
||||
r1.push(t.clone());
|
||||
} else {
|
||||
r2.push(t.clone());
|
||||
}
|
||||
}
|
||||
(r1, r2, ordered)
|
||||
}
|
||||
|
||||
/// The sing-box rule-set (source format) of the domains routed through `exit`.
|
||||
pub fn rule_set(state: &State, exit: &str) -> Value {
|
||||
let domains: Vec<&String> = state.domains.iter().filter(|(_, r)| r.exit == exit).map(|(d, _)| d).collect();
|
||||
if domains.is_empty() {
|
||||
json!({ "version": 1, "rules": [] })
|
||||
} else {
|
||||
json!({ "version": 1, "rules": [{ "domain_suffix": domains }] })
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn ok() -> Fetch {
|
||||
Fetch { status: Some(200), bytes: 1000, ..Default::default() }
|
||||
}
|
||||
fn dead() -> Fetch {
|
||||
Fetch { status: None, error: "reset".into(), ..Default::default() }
|
||||
}
|
||||
fn refused() -> Fetch {
|
||||
Fetch { status: Some(403), ..Default::default() }
|
||||
}
|
||||
fn wall() -> Fetch {
|
||||
Fetch { status: Some(403), block: "cloudflare".into(), ..Default::default() }
|
||||
}
|
||||
|
||||
/// Runs a future that never waits (the fetches here answer at once).
|
||||
fn now<F: Future>(f: F) -> F::Output {
|
||||
let mut f = std::pin::pin!(f);
|
||||
let mut cx = std::task::Context::from_waker(std::task::Waker::noop());
|
||||
match f.as_mut().poll(&mut cx) {
|
||||
std::task::Poll::Ready(v) => v,
|
||||
std::task::Poll::Pending => panic!("a test fetch waited"),
|
||||
}
|
||||
}
|
||||
|
||||
fn exits(tags: &[&str]) -> Vec<String> {
|
||||
tags.iter().map(|s| (*s).to_owned()).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn judgements_follow_upstream() {
|
||||
assert_eq!(judge(&ok()), Judgement::Ok);
|
||||
assert_eq!(judge(&Fetch { status: Some(404), ..Default::default() }), Judgement::Ok);
|
||||
assert_eq!(judge(&Fetch { status: Some(302), location: "https://x.example/why-not-available".into(), ..Default::default() }), Judgement::Blocked);
|
||||
assert_eq!(judge(&Fetch { status: Some(301), location: "https://www.x.example/".into(), ..Default::default() }), Judgement::Ok);
|
||||
assert_eq!(judge(&dead()), Judgement::Dead);
|
||||
assert_eq!(judge(&wall()), Judgement::Wall);
|
||||
assert_eq!(judge(&Fetch { status: Some(403), block: "cloudflare-geo".into(), ..Default::default() }), Judgement::Blocked);
|
||||
assert_eq!(verdict(&refused(), &ok()), "destination");
|
||||
assert_eq!(verdict(&dead(), &ok()), "censor");
|
||||
assert_eq!(verdict(&wall(), &refused()), "destination");
|
||||
assert_eq!(verdict(&dead(), &dead()), "unreachable");
|
||||
assert_eq!(verdict(&refused(), &refused()), "both-fail");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn block_pages_are_recognised() {
|
||||
assert_eq!(block_page(403, "HTTP/1.1 403\r\nserver: cloudflare\r\ncf-mitigated: challenge\r\n", b""), "cloudflare");
|
||||
assert_eq!(block_page(403, "", b"<span class=\"cf-error-code\">1009</span>"), "cloudflare-geo");
|
||||
assert_eq!(block_page(403, "Server: CloudFront\r\n", b"<h1>Request blocked.</h1>"), "aws-waf");
|
||||
assert_eq!(block_page(200, "x-datadome: 1\r\n", b""), "");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_walk_stops_at_the_first_exit_that_reaches() {
|
||||
let answers = |tag: &str, _path: &str| match tag {
|
||||
"direct" => refused(),
|
||||
"a" => refused(),
|
||||
_ => ok(),
|
||||
};
|
||||
let p = now(walk("x.example", &exits(&["direct", "a", "b", "c"]), &PATHS, false, |t: String, p: String| std::future::ready(answers(&t, &p))));
|
||||
assert_eq!(p.verdict, "destination");
|
||||
assert_eq!(p.exit.as_deref(), Some("b"));
|
||||
assert_eq!(p.rows.len(), 3, "c is never asked");
|
||||
let p = now(walk("x.example", &exits(&["direct", "a"]), &PATHS, false, |_: String, _: String| std::future::ready(ok())));
|
||||
assert_eq!((p.verdict.as_str(), p.rows.len()), ("ok", 1));
|
||||
let p = now(walk("x.example", &exits(&["direct", "a"]), &PATHS, false, |_: String, _: String| std::future::ready(dead())));
|
||||
assert_eq!((p.verdict.as_str(), p.rows.len()), ("unreachable", 4));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn robots_txt_can_decide_what_the_page_did_not() {
|
||||
let p = now(walk("x.example", &exits(&["direct", "a"]), &PATHS, false, |t: String, path: String| std::future::ready(match (t.as_str(), path.as_str()) {
|
||||
("direct", _) => refused(),
|
||||
("a", "/") => refused(),
|
||||
_ => ok(),
|
||||
})));
|
||||
assert_eq!((p.verdict.as_str(), p.exit.as_deref(), p.path.as_str()), ("destination", Some("a"), "/robots.txt"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_stand_in_must_carry_everything_direct_gets() {
|
||||
let p = now(stand_in("x.example", "a", &PATHS, |t: String, path: String| std::future::ready(if t == "a" && path == "/robots.txt" { refused() } else { ok() })));
|
||||
assert_eq!(p.verdict, "blocked");
|
||||
let p = now(stand_in("x.example", "a", &PATHS, |_: String, _: String| std::future::ready(ok())));
|
||||
assert_eq!(p.verdict, "ok");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn recording_routes_the_domain_and_strikes_who_refused() {
|
||||
let mut s = State::default();
|
||||
let p = now(walk("www.x.example", &exits(&["direct", "a", "b"]), &PATHS, false, |t: String, _: String| std::future::ready(match t.as_str() {
|
||||
"a" => wall(),
|
||||
"b" => ok(),
|
||||
_ => refused(),
|
||||
})));
|
||||
s.record("x.example", "www.x.example", &p, 100, 1000);
|
||||
assert_eq!(s.domains["x.example"].exit, "b");
|
||||
assert_eq!(s.exits["a"].strikes["x.example"].why, "wall:cloudflare");
|
||||
assert!(!s.exits["a"].bad);
|
||||
s.strike(&exits(&["a"]), "y.example", "refused", 200, 1000);
|
||||
assert!(s.exits["a"].bad, "two domains make an exit bad");
|
||||
assert_eq!(s.exits["a"].bad_by, ["x.example wall:cloudflare", "y.example refused"]);
|
||||
s.strike(&[], "", "", 1150, 1000);
|
||||
assert!(!s.exits["a"].bad, "a strike past the TTL stops counting");
|
||||
s.forget("x.example");
|
||||
assert!(s.domains.is_empty() && s.hosts.is_empty());
|
||||
assert_eq!(rule_set(&s, "b"), json!({ "version": 1, "rules": [] }));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rounds_take_one_exit_per_network_first_and_bad_ones_last() {
|
||||
let mut s = State::default();
|
||||
for (t, asn) in [("a", "AS1"), ("b", "AS1"), ("c", "AS2")] {
|
||||
s.exits.insert(t.into(), ExitInfo { asn: Some(asn.into()), ..Default::default() });
|
||||
}
|
||||
s.exits.insert("d".into(), ExitInfo { bad: true, ..Default::default() });
|
||||
let (r1, r2, ordered) = rounds(&exits(&["direct", "d", "a", "b", "c", "e"]), &s);
|
||||
assert_eq!(r1, ["a", "c", "e"]);
|
||||
assert_eq!(r2, ["b", "d"]);
|
||||
assert_eq!(ordered, ["a", "b", "c", "e", "d"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_backlog_skips_what_is_known_and_keeps_counting() {
|
||||
let mut s = State::default();
|
||||
s.domains.insert("routed.example".into(), Route { verdict: "destination".into(), exit: "a".into(), host: "routed.example".into(), path: "/".into(), at: 0, bad: 0, tried: Vec::new() });
|
||||
let counts: BTreeMap<String, (String, u64)> = [
|
||||
("www.routed.example".to_owned(), ("routed.example".to_owned(), 5)),
|
||||
("cdn.new.example".to_owned(), ("new.example".to_owned(), 2)),
|
||||
("api.other.example".to_owned(), ("other.example".to_owned(), 7)),
|
||||
]
|
||||
.into();
|
||||
s.queue(&counts, 10, 1000);
|
||||
s.queue(&counts, 20, 1000);
|
||||
assert_eq!(s.backlog.len(), 2);
|
||||
assert_eq!(s.backlog["cdn.new.example"].hits, 4);
|
||||
assert_eq!(s.backlog_order(20, 1000)[0], ("other.example".to_owned(), "api.other.example".to_owned()));
|
||||
s.new_egress("203.0.113.9");
|
||||
assert!(s.domains.is_empty());
|
||||
assert_eq!(s.backlog.len(), 2, "the backlog is about the clients, not the address");
|
||||
}
|
||||
|
||||
fn obs(d: &str, exit: &str, slow: bool) -> Observation {
|
||||
Observation { domain: d.into(), host: format!("www.{d}"), exit: exit.into(), slow, peak: 1 }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn crawling_three_times_owes_a_site_an_exit_and_two_more_move_it_on() {
|
||||
let mut s = State::default();
|
||||
s.judge_slow(&[obs("slow.example", "direct", true), obs("fast.example", "direct", false)], 10, 3);
|
||||
s.judge_slow(&[obs("slow.example", "direct", true)], 20, 3);
|
||||
assert!(s.slow_want.is_empty());
|
||||
s.judge_slow(&[obs("slow.example", "direct", true)], 30, 3);
|
||||
assert_eq!(s.slow_want["slow.example"].host, "www.slow.example");
|
||||
s.route_slow("slow.example", "www.slow.example", "nl", vec!["nl".into()], 40);
|
||||
assert!(s.slow_want.is_empty());
|
||||
s.judge_slow(&[obs("slow.example", "nl", true)], 50, 3);
|
||||
s.judge_slow(&[obs("slow.example", "nl", false)], 60, 3);
|
||||
assert_eq!(s.domains["slow.example"].bad, 0, "a fast transfer keeps it");
|
||||
s.judge_slow(&[obs("slow.example", "nl", true)], 70, 3);
|
||||
s.judge_slow(&[obs("slow.example", "nl", true)], 80, 3);
|
||||
assert!(!s.domains.contains_key("slow.example"));
|
||||
assert_eq!(s.slow_want["slow.example"].tried, ["nl"]);
|
||||
s.skip_slow("slow.example", 90, 1000);
|
||||
s.judge_slow(&[obs("slow.example", "direct", true)], 100, 1);
|
||||
assert!(s.slow_want.is_empty(), "skipped for a while");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn transfers_are_judged_by_their_fastest_second() {
|
||||
let snap = |down: &[(&str, &str, &str, u64)]| {
|
||||
json!({ "connections": down.iter().map(|(id, host, exit, d)| json!({
|
||||
"id": id, "download": d, "chains": [exit], "metadata": { "host": host, "type": "mixed/mixed-in" },
|
||||
})).collect::<Vec<_>>() })
|
||||
};
|
||||
let snaps = [
|
||||
snap(&[("1", "a.example", "direct", 0), ("2", "b.example", "direct", 0)]),
|
||||
snap(&[("1", "a.example", "direct", 100_000), ("2", "b.example", "direct", 400_000)]),
|
||||
snap(&[("1", "a.example", "direct", 200_000), ("2", "b.example", "direct", 400_100)]),
|
||||
snap(&[("1", "a.example", "direct", 300_000), ("2", "b.example", "direct", 400_200)]),
|
||||
];
|
||||
let out = sample_transfers(&snaps, 250_000, 150 * 1024);
|
||||
assert_eq!(out, [("a.example".to_owned(), "direct".to_owned(), true, 100_000), ("b.example".to_owned(), "direct".to_owned(), false, 400_000)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sites_and_local_targets() {
|
||||
assert_eq!(registrable("www.example.co.uk").as_deref(), Some("example.co.uk"));
|
||||
assert_eq!(registrable("foo.workers.dev").as_deref(), Some("foo.workers.dev"));
|
||||
assert_eq!(registrable("co.uk"), None);
|
||||
assert_eq!(site("https://accounts.spotify.com/why"), "spotify.com");
|
||||
assert!(local_target("http://127.1/"));
|
||||
assert!(local_target("https://192.168.0.1/admin"));
|
||||
assert!(local_target("http://localhost:8080/"));
|
||||
assert!(!local_target("https://example.com/"));
|
||||
assert!(host_ok("www.example.com") && !host_ok("127.0.0.1") && !host_ok("example") && !host_ok("a b.com"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,635 @@
|
||||
//! AmneziaWG profiles as upstream's scripts/amneziawg_config.py prepares them: from a `.conf`,
|
||||
//! a `vpn://` link (AmneziaVPN's export) or declarative settings, to the `.conf` a tunnel runs
|
||||
//! (`prepare`); and that `.conf` for wireproxy-awg, a SOCKS listener in front of the tunnel
|
||||
//! (`as_wireproxy`).
|
||||
|
||||
use std::collections::BTreeSet;
|
||||
use std::io::Read;
|
||||
|
||||
use base64::Engine;
|
||||
use serde_json::{Map, Value};
|
||||
|
||||
use crate::config::{AwgObfuscation, AwgProfile, AwgSettings};
|
||||
use crate::wg::conf_sections;
|
||||
|
||||
const MAX_INPUT_BYTES: usize = 8 * 1024 * 1024;
|
||||
const AWG3_SAFE_DEFAULT_MTU: &str = "1280";
|
||||
const FORBIDDEN_WG_QUICK_KEYS: [&str; 5] = ["preup", "postup", "predown", "postdown", "saveconfig"];
|
||||
const AWG_PROTOCOL_KEYS: [&str; 4] = ["awg", "amnezia-awg", "amnezia-awg2", "amnezia-awg3"];
|
||||
const AWG3_INTERFACE_KEYS: [&str; 9] = [
|
||||
"headerprotectionkey",
|
||||
"contentpaddingaddition",
|
||||
"rekeyaftertime",
|
||||
"rekeytimeout",
|
||||
"rejectaftertime",
|
||||
"keepalivetimeout",
|
||||
"maxhandshakeattempts",
|
||||
"randomtrailers",
|
||||
"disablecookies",
|
||||
];
|
||||
/// The obfuscation's keys, normalized (lowercase, letters and digits) and as written.
|
||||
const VPN_INTERFACE_FIELDS: [(&str, &str); 25] = [
|
||||
("jc", "Jc"),
|
||||
("jmin", "Jmin"),
|
||||
("jmax", "Jmax"),
|
||||
("s1", "S1"),
|
||||
("s2", "S2"),
|
||||
("s3", "S3"),
|
||||
("s4", "S4"),
|
||||
("h1", "H1"),
|
||||
("h2", "H2"),
|
||||
("h3", "H3"),
|
||||
("h4", "H4"),
|
||||
("i1", "I1"),
|
||||
("i2", "I2"),
|
||||
("i3", "I3"),
|
||||
("i4", "I4"),
|
||||
("i5", "I5"),
|
||||
("headerprotectionkey", "HeaderProtectionKey"),
|
||||
("contentpaddingaddition", "ContentPaddingAddition"),
|
||||
("rekeyaftertime", "RekeyAfterTime"),
|
||||
("rekeytimeout", "RekeyTimeout"),
|
||||
("rejectaftertime", "RejectAfterTime"),
|
||||
("keepalivetimeout", "KeepaliveTimeout"),
|
||||
("maxhandshakeattempts", "MaxHandshakeAttempts"),
|
||||
("randomtrailers", "RandomTrailers"),
|
||||
("disablecookies", "DisableCookies"),
|
||||
];
|
||||
|
||||
type Res<T> = Result<T, String>;
|
||||
|
||||
fn normalize(key: &str) -> String {
|
||||
key.to_lowercase().chars().filter(|c| c.is_ascii_alphanumeric()).collect()
|
||||
}
|
||||
|
||||
/// A `vpn://` link's data: URL-safe base64 of Qt's qCompress (a 4-byte length, then zlib) of
|
||||
/// JSON, or of the `.conf` itself (AmneziaVPN's compact form, shaped like the JSON here).
|
||||
pub fn decode_vpn_link(link: &str) -> Res<Value> {
|
||||
let encoded = link.trim().strip_prefix("vpn://").ok_or("expected a self-contained vpn:// link")?;
|
||||
let body = encoded.trim_end_matches('=');
|
||||
if body.is_empty() || !body.chars().all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_') || encoded.len() - body.len() > 2 {
|
||||
return Err("unsupported vpn:// link; API-backed text keys are not supported".into());
|
||||
}
|
||||
let raw = base64::engine::general_purpose::URL_SAFE_NO_PAD
|
||||
.decode(body)
|
||||
.map_err(|_| "unsupported vpn:// link; expected embedded base64 data, not an API-backed text key")?;
|
||||
if raw.len() > MAX_INPUT_BYTES {
|
||||
return Err("vpn:// payload is too large".into());
|
||||
}
|
||||
let mut decoded = raw.clone();
|
||||
if raw.len() >= 5 {
|
||||
let expected = u32::from_be_bytes([raw[0], raw[1], raw[2], raw[3]]) as usize;
|
||||
let mut out = Vec::new();
|
||||
let mut z = flate2::read::ZlibDecoder::new(&raw[4..]).take(MAX_INPUT_BYTES as u64 + 1);
|
||||
if z.read_to_end(&mut out).is_ok() {
|
||||
if out.len() > MAX_INPUT_BYTES {
|
||||
return Err("decompressed vpn:// payload is too large".into());
|
||||
}
|
||||
if out.len() != expected {
|
||||
return Err("vpn:// qCompress length header does not match payload".into());
|
||||
}
|
||||
decoded = out;
|
||||
}
|
||||
}
|
||||
let text = String::from_utf8(decoded).map_err(|_| "unsupported vpn:// link; expected embedded qCompress/base64 JSON, not an API-backed key")?;
|
||||
if text.trim_start().starts_with("[Interface]") && text.contains("[Peer]") {
|
||||
return Ok(serde_json::json!({
|
||||
"defaultContainer": "amnezia-awg",
|
||||
"containers": [{ "container": "amnezia-awg", "config": text }],
|
||||
}));
|
||||
}
|
||||
match serde_json::from_str::<Value>(&text) {
|
||||
Ok(v) if v.is_object() => Ok(v),
|
||||
Ok(_) => Err("invalid vpn:// configuration: expected a JSON object".into()),
|
||||
Err(_) => Err("unsupported vpn:// link; expected embedded qCompress/base64 JSON, not an API-backed key".into()),
|
||||
}
|
||||
}
|
||||
|
||||
fn json_object(value: &Value, label: &str) -> Res<Map<String, Value>> {
|
||||
let v = match value {
|
||||
Value::String(s) => serde_json::from_str::<Value>(s).map_err(|e| format!("invalid {label} JSON: {e}"))?,
|
||||
other => other.clone(),
|
||||
};
|
||||
match v {
|
||||
Value::Object(m) => Ok(m),
|
||||
_ => Err(format!("invalid {label}: expected an object")),
|
||||
}
|
||||
}
|
||||
|
||||
/// A container's payload: its last configuration and the `.conf` in it.
|
||||
fn candidate_payload(value: &Value, key: &str) -> Res<(Map<String, Value>, String)> {
|
||||
let payload = json_object(value, &format!("{key} protocol"))?;
|
||||
let last = json_object(payload.get("last_config").unwrap_or(&Value::Object(payload.clone())), &format!("{key}.last_config"))?;
|
||||
match last.get("config").and_then(Value::as_str) {
|
||||
Some(c) if c.contains("[Interface]") && c.contains("[Peer]") => Ok((last.clone(), c.to_owned())),
|
||||
_ => Err(format!("{key} candidate does not contain an AmneziaWG config")),
|
||||
}
|
||||
}
|
||||
|
||||
/// The AmneziaWG `.conf` of a `vpn://` export: its default container's (or `container`'s),
|
||||
/// DNS placeholders filled, the obfuscation and MTU its last configuration records applied.
|
||||
pub fn extract_vpn_config(data: &Value, container: Option<&str>) -> Res<String> {
|
||||
let containers = data["containers"].as_array().ok_or("vpn:// configuration has no containers list")?;
|
||||
struct Candidate {
|
||||
id: String,
|
||||
key: String,
|
||||
last: Map<String, Value>,
|
||||
config: String,
|
||||
}
|
||||
let mut candidates = Vec::new();
|
||||
for item in containers {
|
||||
let Some(obj) = item.as_object() else { continue };
|
||||
let id = obj.get("container").and_then(Value::as_str).unwrap_or("").to_owned();
|
||||
let mut protocols: Vec<(String, Value)> = obj.iter().filter(|(k, _)| AWG_PROTOCOL_KEYS.contains(&k.to_lowercase().as_str())).map(|(k, v)| (k.clone(), v.clone())).collect();
|
||||
if AWG_PROTOCOL_KEYS.contains(&id.to_lowercase().as_str()) && protocols.is_empty() && (obj.contains_key("last_config") || obj.contains_key("config")) {
|
||||
protocols = vec![(id.clone(), item.clone())];
|
||||
}
|
||||
for (key, value) in protocols {
|
||||
if let Ok((last, config)) = candidate_payload(&value, &key) {
|
||||
candidates.push(Candidate { id: if id.is_empty() { key.clone() } else { id.clone() }, key, last, config });
|
||||
}
|
||||
}
|
||||
}
|
||||
if candidates.is_empty() {
|
||||
return Err("vpn:// configuration contains no AmneziaWG client config".into());
|
||||
}
|
||||
let named = |c: &Candidate, name: &str| [c.id.to_lowercase(), c.key.to_lowercase()].contains(&name.to_lowercase());
|
||||
let chosen: Vec<&Candidate> = match container {
|
||||
Some(want) => {
|
||||
let found: Vec<&Candidate> = candidates.iter().filter(|c| named(c, want)).collect();
|
||||
if found.len() != 1 {
|
||||
return Err(format!("vpnContainer '{want}' matched {} AmneziaWG configs", found.len()));
|
||||
}
|
||||
found
|
||||
}
|
||||
None => {
|
||||
let default: Vec<&Candidate> = data["defaultContainer"].as_str().map(|d| candidates.iter().filter(|c| named(c, d)).collect()).unwrap_or_default();
|
||||
if default.len() == 1 {
|
||||
default
|
||||
} else if candidates.len() == 1 {
|
||||
vec![&candidates[0]]
|
||||
} else {
|
||||
let ids: Vec<&str> = candidates.iter().map(|c| c.id.as_str()).collect();
|
||||
return Err(format!("vpn:// configuration contains multiple AmneziaWG configs ({}); set vpnContainer", ids.join(", ")));
|
||||
}
|
||||
}
|
||||
};
|
||||
let c = chosen[0];
|
||||
let mut config = c.config.clone();
|
||||
if let Some(d) = data["dns1"].as_str().filter(|d| !d.is_empty()) {
|
||||
config = config.replace("$PRIMARY_DNS", d);
|
||||
}
|
||||
if let Some(d) = data["dns2"].as_str().filter(|d| !d.is_empty()) {
|
||||
config = config.replace("$SECONDARY_DNS", d);
|
||||
}
|
||||
if config.contains("$PRIMARY_DNS") || config.contains("$SECONDARY_DNS") {
|
||||
return Err("vpn:// configuration contains unresolved DNS placeholders".into());
|
||||
}
|
||||
let last: Vec<(String, &Value)> = c.last.iter().map(|(k, v)| (normalize(k), v)).collect();
|
||||
for (norm, key) in VPN_INTERFACE_FIELDS {
|
||||
let Some((_, value)) = last.iter().find(|(k, _)| k == norm) else { continue };
|
||||
let text = match value {
|
||||
Value::Null => continue,
|
||||
Value::String(s) if s.is_empty() => continue,
|
||||
Value::Bool(b) if matches!(norm, "randomtrailers" | "disablecookies") => if *b { "on".into() } else { "off".into() },
|
||||
Value::String(s) => s.clone(),
|
||||
other => other.to_string(),
|
||||
};
|
||||
config = set_interface_value(&config, key, &text)?;
|
||||
}
|
||||
for (field, key) in [("mtu", "MTU"), ("port", "ListenPort")] {
|
||||
let text = match c.last.get(field) {
|
||||
None | Some(Value::Null) => continue,
|
||||
Some(Value::String(s)) if s.is_empty() => continue,
|
||||
Some(Value::String(s)) => s.clone(),
|
||||
Some(other) => other.to_string(),
|
||||
};
|
||||
config = set_interface_value(&config, key, &text)?;
|
||||
}
|
||||
apply_awg3_mtu_default(&config)
|
||||
}
|
||||
|
||||
/// Python's `str.splitlines()` and `"\n".join(...) + "\n"`, which upstream's rewrites use.
|
||||
fn lines(config: &str) -> Vec<String> {
|
||||
crate::links::py::splitlines(config).into_iter().map(str::to_owned).collect()
|
||||
}
|
||||
|
||||
fn joined(lines: &[String]) -> String {
|
||||
let mut s = lines.join("\n");
|
||||
s.push('\n');
|
||||
s
|
||||
}
|
||||
|
||||
fn key_line(line: &str, key: &str) -> bool {
|
||||
let t = line.trim_start();
|
||||
t.len() >= key.len() && t[..key.len()].eq_ignore_ascii_case(key) && t[key.len()..].trim_start().starts_with('=')
|
||||
}
|
||||
|
||||
/// `key = value` in `[Interface]`: the first such line replaced, or one added at its end.
|
||||
fn set_interface_value(config: &str, key: &str, value: &str) -> Res<String> {
|
||||
let mut ls = lines(config);
|
||||
let start = ls.iter().position(|l| l.trim().eq_ignore_ascii_case("[interface]")).ok_or("configuration has no [Interface] section")?;
|
||||
let end = (start + 1..ls.len()).find(|i| ls[*i].trim().starts_with('[')).unwrap_or(ls.len());
|
||||
match (start + 1..end).find(|i| key_line(&ls[*i], key)) {
|
||||
Some(i) => ls[i] = format!("{key} = {value}"),
|
||||
None => ls.insert(end, format!("{key} = {value}")),
|
||||
}
|
||||
Ok(joined(&ls))
|
||||
}
|
||||
|
||||
fn interface_keys(config: &str) -> BTreeSet<String> {
|
||||
conf_sections(config).into_iter().filter(|(n, _)| n == "interface").flat_map(|(_, pairs)| pairs.into_iter().map(|(k, _)| normalize(&k))).collect()
|
||||
}
|
||||
|
||||
/// AWG 3's per-packet padding with awg-quick's 1420 black-holes larger packets: without an
|
||||
/// MTU of its own, such a profile gets the official clients' 1280.
|
||||
fn apply_awg3_mtu_default(config: &str) -> Res<String> {
|
||||
let keys = interface_keys(config);
|
||||
if keys.contains("mtu") || !AWG3_INTERFACE_KEYS.iter().any(|k| keys.contains(*k)) {
|
||||
return Ok(config.to_owned());
|
||||
}
|
||||
set_interface_value(config, "MTU", AWG3_SAFE_DEFAULT_MTU)
|
||||
}
|
||||
|
||||
/// Section headers as awg-quick reads them ("[Peer] # home" opens a Peer section).
|
||||
fn normalize_headers(config: &str) -> String {
|
||||
config
|
||||
.split('\n')
|
||||
.map(|line| match line.split('#').next().unwrap_or("").trim().to_lowercase().as_str() {
|
||||
"[interface]" => "[Interface]".to_owned(),
|
||||
"[peer]" => "[Peer]".to_owned(),
|
||||
_ => line.to_owned(),
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
.join("\n")
|
||||
}
|
||||
|
||||
/// A secret given inline or in a file: exactly one, one line.
|
||||
fn secret(inline: Option<&str>, file: Option<&str>, label: &str, read: &dyn Fn(&str) -> Res<String>) -> Res<String> {
|
||||
let value = match (inline, file) {
|
||||
(Some(v), None) => v.to_owned(),
|
||||
(None, Some(f)) => read(f)?.trim().to_owned(),
|
||||
_ => return Err(format!("set exactly one of {label} or {label}File")),
|
||||
};
|
||||
if value.is_empty() || value.contains(['\n', '\r']) {
|
||||
return Err(format!("{label} must be one non-empty line"));
|
||||
}
|
||||
Ok(value)
|
||||
}
|
||||
|
||||
fn range_text(v: &Value) -> String {
|
||||
match v {
|
||||
Value::String(s) => s.clone(),
|
||||
other => other.to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The obfuscation given inline, with `obfuscationFile`'s secret fields merged in (a field
|
||||
/// given both ways is refused, as upstream refuses it).
|
||||
fn obfuscation_values(o: &AwgObfuscation, file: Option<&str>, read: &dyn Fn(&str) -> Res<String>) -> Res<Vec<(String, String)>> {
|
||||
let mut values: Vec<(String, String)> = Vec::new();
|
||||
let mut put = |name: &str, v: Option<String>| {
|
||||
if let Some(v) = v {
|
||||
values.push((name.to_owned(), v));
|
||||
}
|
||||
};
|
||||
put("jc", o.jc.map(|v| v.to_string()));
|
||||
put("jmin", o.jmin.map(|v| v.to_string()));
|
||||
put("jmax", o.jmax.map(|v| v.to_string()));
|
||||
put("s1", o.s1.map(|v| v.to_string()));
|
||||
put("s2", o.s2.map(|v| v.to_string()));
|
||||
put("s3", o.s3.map(|v| v.to_string()));
|
||||
put("s4", o.s4.map(|v| v.to_string()));
|
||||
put("h1", o.h1.as_ref().map(range_text));
|
||||
put("h2", o.h2.as_ref().map(range_text));
|
||||
put("h3", o.h3.as_ref().map(range_text));
|
||||
put("h4", o.h4.as_ref().map(range_text));
|
||||
put("i1", o.i1.clone());
|
||||
put("i2", o.i2.clone());
|
||||
put("i3", o.i3.clone());
|
||||
put("i4", o.i4.clone());
|
||||
put("i5", o.i5.clone());
|
||||
put("contentpaddingaddition", o.content_padding_addition.as_ref().map(range_text));
|
||||
put("rekeyaftertime", o.rekey_after_time.as_ref().map(range_text));
|
||||
put("rekeytimeout", o.rekey_timeout.as_ref().map(range_text));
|
||||
put("rejectaftertime", o.reject_after_time.as_ref().map(range_text));
|
||||
put("keepalivetimeout", o.keepalive_timeout.as_ref().map(range_text));
|
||||
put("maxhandshakeattempts", o.max_handshake_attempts.as_ref().map(range_text));
|
||||
put("randomtrailers", o.random_trailers.map(|b| if b { "on".into() } else { "off".into() }));
|
||||
put("disablecookies", o.disable_cookies.map(|b| if b { "on".into() } else { "off".into() }));
|
||||
if let Some(f) = file {
|
||||
let text = read(f)?;
|
||||
let secret: Map<String, Value> = match serde_json::from_str::<Value>(&text) {
|
||||
Ok(Value::Object(m)) => m,
|
||||
Ok(_) => return Err("obfuscationFile must contain a JSON object".into()),
|
||||
Err(_) => return Err("cannot read or decode obfuscationFile".into()),
|
||||
};
|
||||
for (key, value) in secret {
|
||||
let norm = normalize(&key);
|
||||
if !VPN_INTERFACE_FIELDS.iter().any(|(n, _)| *n == norm) {
|
||||
return Err("obfuscationFile contains an unsupported field".into());
|
||||
}
|
||||
if value.is_null() {
|
||||
continue;
|
||||
}
|
||||
if values.iter().any(|(n, _)| *n == norm) || (norm == "headerprotectionkey" && (o.header_protection_key.is_some() || o.header_protection_key_file.is_some())) {
|
||||
return Err(format!("obfuscationFile field '{key}' has multiple sources"));
|
||||
}
|
||||
let unsigned = value.as_u64().is_some();
|
||||
let text = match norm.as_str() {
|
||||
"jc" | "jmin" | "jmax" | "s1" | "s2" | "s3" | "s4" if unsigned => value.to_string(),
|
||||
"randomtrailers" | "disablecookies" => match value.as_bool() {
|
||||
Some(b) => (if b { "on" } else { "off" }).to_owned(),
|
||||
None => return Err(format!("obfuscationFile field '{key}' has an invalid value")),
|
||||
},
|
||||
"i1" | "i2" | "i3" | "i4" | "i5" | "headerprotectionkey" => match value.as_str() {
|
||||
Some(s) if !s.trim().is_empty() && !s.contains(['\n', '\r', '\0']) => s.to_owned(),
|
||||
_ => return Err(format!("obfuscationFile field '{key}' has an invalid value")),
|
||||
},
|
||||
"h1" | "h2" | "h3" | "h4" | "contentpaddingaddition" | "rekeyaftertime" | "rekeytimeout" | "rejectaftertime" | "keepalivetimeout" | "maxhandshakeattempts" => {
|
||||
match &value {
|
||||
Value::Number(_) if unsigned => value.to_string(),
|
||||
Value::String(s) if s.split_once('-').map_or(s.chars().all(|c| c.is_ascii_digit()) && !s.is_empty(), |(a, b)| !a.is_empty() && !b.is_empty() && (a.to_owned() + b).chars().all(|c| c.is_ascii_digit())) || s == "(off)" => s.clone(),
|
||||
_ => return Err(format!("obfuscationFile field '{key}' has an invalid value")),
|
||||
}
|
||||
}
|
||||
_ => return Err(format!("obfuscationFile field '{key}' has an invalid value")),
|
||||
};
|
||||
values.push((norm, text));
|
||||
}
|
||||
}
|
||||
Ok(values)
|
||||
}
|
||||
|
||||
/// A `.conf` from declarative settings.
|
||||
pub fn render_settings(s: &AwgSettings, read: &dyn Fn(&str) -> Res<String>) -> Res<String> {
|
||||
if s.addresses.is_empty() {
|
||||
return Err("declarative settings require at least one address".into());
|
||||
}
|
||||
if s.peers.is_empty() {
|
||||
return Err("declarative settings require at least one peer".into());
|
||||
}
|
||||
let mut out = vec!["[Interface]".to_owned()];
|
||||
out.push(format!("PrivateKey = {}", secret(s.private_key.as_deref(), s.private_key_file.as_deref(), "privateKey", read)?));
|
||||
for a in &s.addresses {
|
||||
out.push(format!("Address = {a}"));
|
||||
}
|
||||
if !s.dns.is_empty() {
|
||||
out.push(format!("DNS = {}", s.dns.join(",")));
|
||||
}
|
||||
if let Some(p) = s.listen_port {
|
||||
out.push(format!("ListenPort = {p}"));
|
||||
}
|
||||
if let Some(m) = s.mtu {
|
||||
out.push(format!("MTU = {m}"));
|
||||
}
|
||||
let values = obfuscation_values(&s.obfuscation, s.obfuscation_file.as_deref(), read)?;
|
||||
for (norm, key) in VPN_INTERFACE_FIELDS {
|
||||
if norm == "headerprotectionkey" {
|
||||
continue;
|
||||
}
|
||||
if let Some((_, v)) = values.iter().find(|(n, _)| n == norm) {
|
||||
out.push(format!("{key} = {v}"));
|
||||
}
|
||||
}
|
||||
let from_file = values.iter().find(|(n, _)| n == "headerprotectionkey").map(|(_, v)| v.clone());
|
||||
let o = &s.obfuscation;
|
||||
if o.header_protection_key.is_some() || o.header_protection_key_file.is_some() {
|
||||
out.push(format!("HeaderProtectionKey = {}", secret(o.header_protection_key.as_deref(), o.header_protection_key_file.as_deref(), "headerProtectionKey", read)?));
|
||||
} else if let Some(v) = from_file {
|
||||
out.push(format!("HeaderProtectionKey = {v}"));
|
||||
}
|
||||
for peer in &s.peers {
|
||||
if peer.public_key.is_empty() || peer.allowed_ips.is_empty() {
|
||||
return Err("each peer requires publicKey and allowedIPs".into());
|
||||
}
|
||||
out.extend([String::new(), "[Peer]".into(), format!("PublicKey = {}", peer.public_key)]);
|
||||
if peer.preshared_key.is_some() || peer.preshared_key_file.is_some() {
|
||||
out.push(format!("PresharedKey = {}", secret(peer.preshared_key.as_deref(), peer.preshared_key_file.as_deref(), "presharedKey", read)?));
|
||||
}
|
||||
out.push(format!("AllowedIPs = {}", peer.allowed_ips.join(",")));
|
||||
if let Some(e) = &peer.endpoint {
|
||||
out.push(format!("Endpoint = {e}"));
|
||||
}
|
||||
if let Some(k) = &peer.persistent_keepalive {
|
||||
out.push(format!("PersistentKeepalive = {}", range_text(k)));
|
||||
}
|
||||
if let Some(a) = peer.advanced_security {
|
||||
out.push(format!("AdvancedSecurity = {}", if a { "on" } else { "off" }));
|
||||
}
|
||||
}
|
||||
Ok(joined(&out))
|
||||
}
|
||||
|
||||
/// The first peer's `Endpoint` replaced by `endpoint` (host:port, IPv6 in brackets).
|
||||
pub fn override_endpoint(config: &str, endpoint: &str) -> Res<String> {
|
||||
let mut done = false;
|
||||
let out: Vec<String> = config
|
||||
.split('\n')
|
||||
.map(|line| {
|
||||
if !done && key_line(line, "Endpoint") {
|
||||
let value = line.split_once('=').map(|(_, v)| v.trim()).unwrap_or("");
|
||||
if value.rsplit_once(':').is_some_and(|(h, p)| !h.is_empty() && !p.is_empty() && p.chars().all(|c| c.is_ascii_digit()) && !value.contains(char::is_whitespace)) {
|
||||
done = true;
|
||||
let prefix = &line[..line.find('=').unwrap() + 1];
|
||||
return format!("{prefix} {endpoint}");
|
||||
}
|
||||
}
|
||||
line.to_owned()
|
||||
})
|
||||
.collect();
|
||||
if !done {
|
||||
return Err("configuration has no Endpoint to override".into());
|
||||
}
|
||||
Ok(out.join("\n"))
|
||||
}
|
||||
|
||||
/// Upstream's checks: no control characters a reader could take for a line end, sections
|
||||
/// [Interface] (exactly one) and [Peer] only, alone on their lines, and no wg-quick hooks
|
||||
/// unless allowed.
|
||||
pub fn validate(config: &str, allow_hooks: bool) -> Res<()> {
|
||||
let bytes: Vec<char> = config.chars().collect();
|
||||
for (i, c) in bytes.iter().enumerate() {
|
||||
let lone_cr = *c == '\r' && bytes.get(i + 1) != Some(&'\n');
|
||||
let bad = matches!(*c as u32, 0x00..=0x08 | 0x0b | 0x0c | 0x0e..=0x1f | 0x7f | 0x85 | 0x2028 | 0x2029);
|
||||
if bad || lone_cr {
|
||||
return Err("configuration contains control characters".into());
|
||||
}
|
||||
}
|
||||
let lowered = config.to_lowercase();
|
||||
if !lowered.contains("[interface]") || !lowered.contains("[peer]") {
|
||||
return Err("configuration requires [Interface] and [Peer] sections".into());
|
||||
}
|
||||
let mut interfaces = 0;
|
||||
for line in config.split('\n') {
|
||||
let stripped = line.trim();
|
||||
if !stripped.split('#').next().unwrap_or("").trim().starts_with('[') {
|
||||
continue;
|
||||
}
|
||||
let lower = stripped.to_lowercase();
|
||||
if lower != "[interface]" && lower != "[peer]" {
|
||||
return Err(format!("unexpected section header {:?}: only [Interface] and [Peer], alone on their line", stripped.chars().take(40).collect::<String>()));
|
||||
}
|
||||
interfaces += usize::from(lower == "[interface]");
|
||||
}
|
||||
if interfaces != 1 {
|
||||
return Err("configuration needs exactly one [Interface] section".into());
|
||||
}
|
||||
if !allow_hooks {
|
||||
for line in config.split('\n') {
|
||||
let key = line.split('#').next().unwrap_or("").split('=').next().unwrap_or("").trim().to_lowercase();
|
||||
if !key.is_ascii() {
|
||||
return Err("configuration has a key with non-ASCII characters".into());
|
||||
}
|
||||
if FORBIDDEN_WG_QUICK_KEYS.contains(&key.as_str()) {
|
||||
return Err(format!("configuration contains privileged wg-quick directive '{key}'; set allowConfigHooks = true only for trusted input"));
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// A profile's `.conf`, from whichever source it has, as upstream's `prepare` makes it.
|
||||
pub fn prepare(p: &AwgProfile, read: &dyn Fn(&str) -> Res<String>) -> Res<String> {
|
||||
let config = match (&p.config, &p.config_file, &p.vpn, &p.vpn_file, &p.settings) {
|
||||
(Some(text), None, None, None, None) => text.clone(),
|
||||
(None, Some(f), None, None, None) => read(f)?,
|
||||
(None, None, Some(link), None, None) => extract_vpn_config(&decode_vpn_link(link)?, p.vpn_container.as_deref())?,
|
||||
(None, None, None, Some(f), None) => extract_vpn_config(&decode_vpn_link(&read(f)?)?, p.vpn_container.as_deref())?,
|
||||
(None, None, None, None, Some(s)) => render_settings(s, read)?,
|
||||
_ => return Err("a profile needs exactly one of config, configFile, vpn, vpnFile and settings".into()),
|
||||
};
|
||||
if config.len() > MAX_INPUT_BYTES {
|
||||
return Err("the configuration is too large".into());
|
||||
}
|
||||
let mut config = apply_awg3_mtu_default(&normalize_headers(&config))?;
|
||||
if let Some(e) = &p.endpoint {
|
||||
config = override_endpoint(&config, e)?;
|
||||
}
|
||||
validate(&config, p.allow_config_hooks)?;
|
||||
Ok(config)
|
||||
}
|
||||
|
||||
/// A wireproxy-awg configuration: the profile served as a SOCKS5 listener on `socks_address`,
|
||||
/// with `login`. Only [Interface] and [Peer] are kept, wg-quick's keys dropped.
|
||||
pub fn as_wireproxy(config: &str, socks_address: &str, login: Option<(&str, &str)>) -> Res<String> {
|
||||
const LISTS: [&str; 3] = ["address", "dns", "allowedips"];
|
||||
const DROPPED: [&str; 7] = ["preup", "postup", "predown", "postdown", "saveconfig", "table", "fwmark"];
|
||||
let mut out: Vec<String> = Vec::new();
|
||||
for (name, pairs) in conf_sections(config) {
|
||||
if name != "interface" && name != "peer" {
|
||||
continue;
|
||||
}
|
||||
if !out.is_empty() {
|
||||
out.push(String::new());
|
||||
}
|
||||
out.push(if name == "interface" { "[Interface]".into() } else { "[Peer]".into() });
|
||||
let mut lists: Vec<(String, Vec<String>)> = Vec::new();
|
||||
let mut section: Vec<String> = Vec::new();
|
||||
for (key, value) in pairs {
|
||||
if DROPPED.contains(&key.as_str()) {
|
||||
continue;
|
||||
}
|
||||
if LISTS.contains(&key.as_str()) {
|
||||
let items = value.split(',').map(str::trim).filter(|s| !s.is_empty()).map(str::to_owned);
|
||||
match lists.iter_mut().find(|(k, _)| *k == key) {
|
||||
Some((_, l)) => l.extend(items),
|
||||
None => {
|
||||
lists.push((key.clone(), items.collect()));
|
||||
section.push(key);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
section.push(format!("{key} = {value}"));
|
||||
}
|
||||
}
|
||||
for line in section {
|
||||
match lists.iter().find(|(k, _)| *k == line) {
|
||||
Some((k, l)) => out.push(format!("{k} = {}", l.join(","))),
|
||||
None => out.push(line),
|
||||
}
|
||||
}
|
||||
}
|
||||
out.extend([String::new(), "[Socks5]".into(), format!("BindAddress = {socks_address}")]);
|
||||
if let Some((user, password)) = login {
|
||||
let ok = |s: &str| !s.is_empty() && s.chars().all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '-'));
|
||||
if !ok(user) || !ok(password) {
|
||||
return Err("the SOCKS login must be letters, digits, dot, dash and underscore".into());
|
||||
}
|
||||
out.extend([format!("Username = {user}"), format!("Password = {password}")]);
|
||||
}
|
||||
Ok(joined(&out))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
// Made by upstream's encode_vpn_link (scripts/amneziawg_config.py), and a JSON export with
|
||||
// DNS placeholders and a last configuration, as AmneziaVPN shares one.
|
||||
const LINK: &str = "vpn://AAAEX3jalVNdb-IwEPwryM9cwPmQqkh9qNpTA72iSJwQB0HIJOZqNTiRbSgp4r93dxO43sPpVCVKZmbXa3vsPbG80k4oLY1l8fL0h7KYiZ2W70p8E2-_WZ_hNz6xcQ6REPh4pzRAPiQsjoAjxFMOiIDfgQQVjgAVH0EAIEAQdtVKYd0aJt8qmIWdMtbijMUZW460k2YrcrnKMp0adRBOPsmmd9sTjzO7ebxx__s_P9zdwti7ojDSWhjIh96Nxz1_EPigP0ymqHn0AB_nQEMEsEnKJiyOgCPEUw6IgN-BBBUcm6CCRZMAQIAg7KrBu0ylNLSN_aZUebuL3J81xW7W_JhPylwvylzx98V87C_mI_d37BftoiyrN1mMUtzI0KNnMOz34niAK_mui7pS2uEyhgEEOQ-8KI74jY_hFI5aWSe1e5KyFqU6SMyMcH2sn7GXyrqJ2Emy_lBrTx7Fri4lBevKOAhQLaB5qaDOWtWUfPGUMrtQDae1fpUNJXzptLCIleYgzbreb641vuQVLdm-XgeTIFr7YNUWxGXGrhZSmFxkKxx5dQoKyHpNXlEdcAtTxzmxsCVwVTobOi6OxKOWTzmxjvifSNJGeEvaSGtiEhAJWhJeZjtDw-BJYMvhSQB1RmiLGjheuQoi-6IGXdmfL8oUqTCuue_ay5m9PJ9XfVbIrdiX7v6fPV9ImxtVO1Vhqz83vVk6AflyRUD7dEEwX1vq9baR2PkDyhJUgw";
|
||||
const LINK2: &str = "vpn://AAACXnichVLvb4IwEP1XSLOPDinIpiR-MGoUnY5oYvyBMRXq0gSKgapTwv--O2BZ9mVLafreu-v1Lo-cBIlUTEieZsTRdvkPB0pYLPlDsGd2-yANoHA4Wk4ilqkDJJ4EcpL7pCI-MJ_sXKl4emIB3_u-9FJxZYpP-V3ramy0yo6jtvrvnA16XbjbC8OUZxlcpIbe1qluNi0T9MF8CdqTt3BnvcXmALShPS2H_ff5oOaQNAkgp4UgFrIsUWL2CdhGvKSASmDWYIwKRYAKvjS2AFgIWnU1-HYe52k52-UYiaAaLTBX9zBe3d_W8yiQ2ygQ9LFdT8zt2lW_Y5tytChKbjx0PZzO0MvVNBqa4zSxk6EMz4mQCtswLAhSaum2Y9O2iWEP7BKZ4lJNOT-zSFw5ZtrYHxjlk1hdKjOo9fpSSZOgUmyfFGjmOUkVulfWJEWxBy3kJ3aJVP-PfyCUGUW5o5erlkyUaKsDfZrfmxRfDVi3BA";
|
||||
|
||||
const EXTRACTED: &str = "[Interface]\nPrivateKey = aGVsbG8taGVsbG8taGVsbG8taGVsbG8taGVsbG8tMDA=\nAddress = 10.8.1.2/32\nDNS = 1.1.1.1\nJc = 4\nJmin = 10\nJmax = 50\nS1 = 0\nS2 = 0\nH1 = 1\nH2 = 2\nH3 = 3\nH4 = 4\n\nListenPort = 51820\n[Peer]\nPublicKey = c2VydmVyLXNlcnZlci1zZXJ2ZXItc2VydmVyLXNlcnY=\nAllowedIPs = 0.0.0.0/0, ::/0\nEndpoint = 203.0.113.5:51820\nPersistentKeepalive = 25\n";
|
||||
|
||||
#[test]
|
||||
fn vpn_links_extract_as_upstreams_do() {
|
||||
assert_eq!(extract_vpn_config(&decode_vpn_link(LINK).unwrap(), None).unwrap(), EXTRACTED);
|
||||
let two = extract_vpn_config(&decode_vpn_link(LINK2).unwrap(), None).unwrap();
|
||||
assert!(two.contains("DNS = 9.9.9.9, 149.112.112.112\n"), "{two}");
|
||||
assert!(two.contains("Jc = 5\n") && two.contains("MTU = 1376\n"), "{two}");
|
||||
assert!(decode_vpn_link("vpn://short.key").is_err());
|
||||
assert!(decode_vpn_link("https://x").is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn wireproxy_as_upstreams() {
|
||||
let w = as_wireproxy(EXTRACTED, "127.0.0.1:18700", Some(("hop", "pw-123"))).unwrap();
|
||||
assert_eq!(
|
||||
w,
|
||||
"[Interface]\nprivatekey = aGVsbG8taGVsbG8taGVsbG8taGVsbG8taGVsbG8tMDA=\naddress = 10.8.1.2/32\ndns = 1.1.1.1\njc = 4\njmin = 10\njmax = 50\n\
|
||||
s1 = 0\ns2 = 0\nh1 = 1\nh2 = 2\nh3 = 3\nh4 = 4\nlistenport = 51820\n\n[Peer]\npublickey = c2VydmVyLXNlcnZlci1zZXJ2ZXItc2VydmVyLXNlcnY=\n\
|
||||
allowedips = 0.0.0.0/0,::/0\nendpoint = 203.0.113.5:51820\npersistentkeepalive = 25\n\n[Socks5]\nBindAddress = 127.0.0.1:18700\nUsername = hop\nPassword = pw-123\n"
|
||||
);
|
||||
assert!(as_wireproxy(EXTRACTED, "127.0.0.1:1", Some(("hop", "a b"))).is_err());
|
||||
}
|
||||
|
||||
fn read(_: &str) -> Res<String> {
|
||||
Err("no files here".into())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn prepare_checks_and_overrides() {
|
||||
let mut p = AwgProfile { config: Some(EXTRACTED.into()), endpoint: Some("198.51.100.9:443".into()), ..Default::default() };
|
||||
let c = prepare(&p, &read).unwrap();
|
||||
assert!(c.contains("Endpoint = 198.51.100.9:443"), "{c}");
|
||||
p.config = Some(format!("{EXTRACTED}PostUp = calc.exe\n"));
|
||||
p.endpoint = None;
|
||||
assert!(prepare(&p, &read).unwrap_err().contains("wg-quick directive"));
|
||||
p.config = Some(EXTRACTED.replace("[Peer]", "[Peer]\r[Interface]"));
|
||||
assert!(prepare(&p, &read).unwrap_err().contains("control"));
|
||||
p.config = None;
|
||||
p.vpn = Some(LINK.into());
|
||||
assert_eq!(prepare(&p, &read).unwrap(), EXTRACTED);
|
||||
// AWG 3 keys without an MTU: 1280.
|
||||
p.vpn = None;
|
||||
p.config = Some(EXTRACTED.replace("H4 = 4", "H4 = 4\nRandomTrailers = on"));
|
||||
assert!(prepare(&p, &read).unwrap().contains("MTU = 1280"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn settings_render() {
|
||||
let s: AwgSettings = serde_json::from_value(serde_json::json!({
|
||||
"addresses": ["10.9.0.2/32"],
|
||||
"privateKey": "PRIV",
|
||||
"obfuscation": { "jc": 3, "h1": "100-200", "randomTrailers": true },
|
||||
"peers": [{ "publicKey": "PUB", "allowedIPs": ["0.0.0.0/0"], "endpoint": "198.51.100.1:51820", "persistentKeepalive": 25 }],
|
||||
}))
|
||||
.unwrap();
|
||||
let c = render_settings(&s, &read).unwrap();
|
||||
assert_eq!(
|
||||
c,
|
||||
"[Interface]\nPrivateKey = PRIV\nAddress = 10.9.0.2/32\nJc = 3\nH1 = 100-200\nRandomTrailers = on\n\n[Peer]\nPublicKey = PUB\nAllowedIPs = 0.0.0.0/0\nEndpoint = 198.51.100.1:51820\nPersistentKeepalive = 25\n"
|
||||
);
|
||||
}
|
||||
}
|
||||
Loaded 100 of 252 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user