Compare commits
8
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b05c321550 | ||
|
|
0ba8f8072c | ||
|
|
dbe730cdc4 | ||
|
|
c6febc2c02 | ||
|
|
6fa2241c98 | ||
|
|
ed792ca542 | ||
|
|
6259018062 | ||
|
|
08c9fac50b |
No files matched your search
@@ -0,0 +1,22 @@
|
||||
<?php
|
||||
require getcwd() . '/vendor/autoload.php';
|
||||
$app = require getcwd() . '/bootstrap/app.php';
|
||||
$app->make(Illuminate\Contracts\Console\Kernel::class)->bootstrap();
|
||||
$opts = getopt('', ['backup:', 'expected-current-sha256:']);
|
||||
$dir = $opts['backup'] ?? throw new RuntimeException('Missing backup');
|
||||
umask(0077);
|
||||
$old = App\Models\SubscribeTemplate::where('name', 'singbox')->firstOrFail();
|
||||
$default = json_decode(file_get_contents('resources/rules/default.sing-box.json'), true, flags: JSON_THROW_ON_ERROR);
|
||||
$replacement = file_get_contents(__DIR__ . '/sing-box-template.json');
|
||||
$new = json_decode($replacement, true, flags: JSON_THROW_ON_ERROR);
|
||||
$current = json_decode($old->content, true, flags: JSON_THROW_ON_ERROR);
|
||||
if ($current === $new) { echo "Template already updated\n"; exit; }
|
||||
$expected = $opts['expected-current-sha256'] ?? '';
|
||||
$knownRevision = preg_match('/^[a-f0-9]{64}$/', $expected) && hash_equals($expected, hash('sha256', $old->content));
|
||||
if ($current !== $default && !$knownRevision) throw new RuntimeException('Custom or unexpected template detected; inspect instead of overwriting');
|
||||
if (!is_dir($dir)) throw new RuntimeException('Backup directory missing');
|
||||
$path = "$dir/singbox-template-before-" . hash('sha256', $old->content) . '.json';
|
||||
if (is_file($path)) throw new RuntimeException('Existing backup; inspect before retry');
|
||||
file_put_contents($path, json_encode($old->getAttributes(), JSON_THROW_ON_ERROR));
|
||||
App\Models\SubscribeTemplate::setContent('singbox', $replacement);
|
||||
echo "DPL default subscription template updated; custom templates and other airports untouched\n";
|
||||
@@ -0,0 +1,5 @@
|
||||
[Unit]
|
||||
Description=Synchronize both subscription gateways' trusted Cloudflare ranges
|
||||
[Service]
|
||||
Type=oneshot
|
||||
ExecStart=/usr/bin/python3 /opt/dpl-gateway/provision/update-cloudflare-ips.py
|
||||
@@ -0,0 +1,8 @@
|
||||
[Unit]
|
||||
Description=Daily DPL Cloudflare IP range synchronization
|
||||
[Timer]
|
||||
OnCalendar=*-*-* 02:00:00
|
||||
RandomizedDelaySec=900
|
||||
Persistent=true
|
||||
[Install]
|
||||
WantedBy=timers.target
|
||||
@@ -0,0 +1,5 @@
|
||||
[Unit]
|
||||
Description=Renew isolated DPL subscription gateway certificate
|
||||
[Service]
|
||||
Type=oneshot
|
||||
ExecStart=/usr/bin/certbot renew --config-dir /etc/dpl-letsencrypt --work-dir /var/lib/dpl-sgw/certbot --logs-dir /var/log/dpl-certbot --no-directory-hooks --quiet --deploy-hook /opt/dpl-gateway/provision/renew-gateway.sh
|
||||
@@ -0,0 +1,8 @@
|
||||
[Unit]
|
||||
Description=Daily isolated DPL gateway certificate renewal
|
||||
[Timer]
|
||||
OnCalendar=*-*-* 03:00:00
|
||||
RandomizedDelaySec=3600
|
||||
Persistent=true
|
||||
[Install]
|
||||
WantedBy=timers.target
|
||||
@@ -0,0 +1,28 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Authorized extension: add dynamic CF trust only to the original gateway vhosts."""
|
||||
import pathlib
|
||||
import re
|
||||
import subprocess
|
||||
|
||||
p = pathlib.Path('/etc/nginx/conf.d/g1.gembox-sub.com.conf')
|
||||
include = 'include /etc/nginx/dpl-cloudflare-realip.conf;'
|
||||
assert pathlib.Path('/etc/nginx/dpl-cloudflare-realip.conf').is_file()
|
||||
old = p.read_text()
|
||||
if include in old:
|
||||
print('Original gateway already uses dynamic Cloudflare ranges')
|
||||
raise SystemExit
|
||||
pattern = r'(?m)^(\s*server_name\s+fu101\.gembox-sub\.com\s*;)$'
|
||||
new, count = re.subn(pattern, lambda m: m.group(0) + '\n ' + include, old)
|
||||
assert 1 <= count <= 2, 'Unexpected vhost structure; inspect manually'
|
||||
backup = pathlib.Path('/root/codex-backups/dpl-gateway-20261011/original-before-ip-sync.conf')
|
||||
assert not backup.exists(), 'Backup exists; inspect previous attempt'
|
||||
backup.write_text(old)
|
||||
backup.chmod(0o600)
|
||||
p.write_text(new)
|
||||
try:
|
||||
subprocess.run(['nginx', '-t'], check=True)
|
||||
subprocess.run(['systemctl', 'reload', 'nginx'], check=True)
|
||||
except Exception:
|
||||
p.write_text(old)
|
||||
raise
|
||||
print(f'Original gateway Cloudflare trust synchronized in {count} vhosts; no containers restarted')
|
||||
@@ -0,0 +1,29 @@
|
||||
user nginx;
|
||||
worker_processes 1;
|
||||
pid /var/run/nginx.pid;
|
||||
events { worker_connections 256; }
|
||||
http {
|
||||
include /etc/nginx/mime.types;
|
||||
default_type application/octet-stream;
|
||||
server_tokens off;
|
||||
server {
|
||||
listen 64444 ssl;
|
||||
ssl_certificate /etc/dpl-letsencrypt/live/c2.deeplink-subscribe.com/fullchain.pem;
|
||||
ssl_certificate_key /etc/dpl-letsencrypt/live/c2.deeplink-subscribe.com/privkey.pem;
|
||||
root /var/www/html;
|
||||
index index.php;
|
||||
location / { try_files $uri /index.php$is_args$args; }
|
||||
location ~ ^/api/[a-z_]+\.php$ {
|
||||
include fastcgi_params;
|
||||
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
|
||||
fastcgi_pass 127.0.0.1:9000;
|
||||
}
|
||||
location ~ \.php$ {
|
||||
try_files $uri /index.php$is_args$args;
|
||||
include fastcgi_params;
|
||||
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
|
||||
fastcgi_pass 127.0.0.1:9000;
|
||||
}
|
||||
location ~ /\. { deny all; }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
server {
|
||||
listen 80;
|
||||
server_name c2.deeplink-subscribe.com;
|
||||
location ^~ /.well-known/acme-challenge/ { root /var/lib/dpl-sgw/acme; }
|
||||
location / { return 404; }
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
user nginx;
|
||||
worker_processes 1;
|
||||
error_log /var/log/nginx/error.log warn;
|
||||
pid /var/run/nginx.pid;
|
||||
events { worker_connections 1024; }
|
||||
http {
|
||||
include /etc/nginx/mime.types;
|
||||
default_type application/octet-stream;
|
||||
include /etc/nginx/subscribe/real_ip.conf;
|
||||
# Do not record subscription credentials in access logs.
|
||||
log_format main '$remote_addr [$time_local] "$request_method $uri $server_protocol" $status $body_bytes_sent "$http_user_agent"';
|
||||
access_log /var/log/subscribe/access.log main;
|
||||
error_log /var/log/subscribe/error.log crit;
|
||||
sendfile on;
|
||||
keepalive_timeout 65;
|
||||
server_tokens off;
|
||||
resolver 1.1.1.1 valid=60s ipv6=off;
|
||||
resolver_timeout 5s;
|
||||
map $http_upgrade $connection_upgrade { default upgrade; '' close; }
|
||||
include /etc/nginx/subscribe/cloud_geo.conf;
|
||||
include /etc/nginx/subscribe/whitelist.conf;
|
||||
include /etc/nginx/subscribe/ua_custom.conf;
|
||||
include /etc/nginx/subscribe/ua_whitelist.conf;
|
||||
server { listen 80 default_server; return 444; }
|
||||
server {
|
||||
listen 443 ssl;
|
||||
ssl_certificate /etc/nginx/ssl/cert.pem;
|
||||
ssl_certificate_key /etc/nginx/ssl/key.pem;
|
||||
ssl_protocols TLSv1.2 TLSv1.3;
|
||||
proxy_ssl_verify on;
|
||||
proxy_ssl_verify_depth 3;
|
||||
proxy_ssl_trusted_certificate /etc/ssl/certs/ca-certificates.crt;
|
||||
include /etc/nginx/subscribe/blacklist.conf;
|
||||
include /etc/nginx/subscribe/protect.conf;
|
||||
location / { return 404; }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
location ^~ /api/v1/client/subscribe {
|
||||
if ($is_cloud_ip = 1) { set $block_reason "cloud"; }
|
||||
if ($bad_subscribe_ua = 1) { set $block_reason "ua"; }
|
||||
if ($is_custom_bad_ua = 1) { set $block_reason "ua"; }
|
||||
if ($is_ua_whitelisted = 1) { set $block_reason ""; }
|
||||
if ($whitelist_ip = 1) { set $block_reason ""; }
|
||||
if ($block_reason = "cloud") { return 403 "Forbidden: Cloud IP"; }
|
||||
if ($block_reason = "ua") { return 403 "Forbidden: Invalid Client"; }
|
||||
limit_req zone=subscribe_limit burst=5 nodelay;
|
||||
limit_req_status 429;
|
||||
set $upstream_backend ${V2B_BACKEND};
|
||||
proxy_pass $upstream_backend;
|
||||
proxy_set_header Host ${V2B_HOST};
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $remote_addr;
|
||||
proxy_set_header X-Forwarded-Proto https;
|
||||
proxy_ssl_server_name on;
|
||||
proxy_ssl_name ${V2B_HOST};
|
||||
proxy_ssl_verify on;
|
||||
proxy_ssl_verify_depth 3;
|
||||
proxy_ssl_trusted_certificate /etc/ssl/certs/ca-certificates.crt;
|
||||
proxy_http_version 1.1;
|
||||
proxy_connect_timeout 10s;
|
||||
proxy_read_timeout 60s;
|
||||
add_header Cache-Control "private, no-store" always;
|
||||
add_header X-Subscribe-Filter "active" always;
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
proxy_set_header Host c2.deeplink-subscribe.com;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $remote_addr;
|
||||
proxy_set_header X-Forwarded-Proto https;
|
||||
proxy_http_version 1.1;
|
||||
proxy_ssl_server_name on;
|
||||
proxy_ssl_name c2.deeplink-subscribe.com;
|
||||
proxy_ssl_verify on;
|
||||
proxy_ssl_verify_depth 3;
|
||||
proxy_ssl_trusted_certificate /etc/ssl/certs/ca-certificates.crt;
|
||||
proxy_connect_timeout 10s;
|
||||
proxy_read_timeout 60s;
|
||||
proxy_hide_header Cache-Control;
|
||||
add_header Cache-Control "private, no-store" always;
|
||||
proxy_no_cache 1;
|
||||
proxy_cache_bypass 1;
|
||||
@@ -0,0 +1,28 @@
|
||||
server {
|
||||
listen 80;
|
||||
server_name c2.deeplink-subscribe.com;
|
||||
include /etc/nginx/dpl-cloudflare-realip.conf;
|
||||
location ^~ /.well-known/acme-challenge/ { root /var/lib/dpl-sgw/acme; }
|
||||
location / { return 301 https://$host$request_uri; }
|
||||
}
|
||||
server {
|
||||
listen 443 ssl;
|
||||
server_name c2.deeplink-subscribe.com;
|
||||
include /etc/nginx/dpl-cloudflare-realip.conf;
|
||||
ssl_certificate /etc/dpl-letsencrypt/live/c2.deeplink-subscribe.com/fullchain.pem;
|
||||
ssl_certificate_key /etc/dpl-letsencrypt/live/c2.deeplink-subscribe.com/privkey.pem;
|
||||
ssl_protocols TLSv1.2 TLSv1.3;
|
||||
# Public gateway serves subscriptions only; administration stays on loopback.
|
||||
access_log off;
|
||||
error_log /var/log/nginx/dpl-subscribe-error.log crit;
|
||||
location ~ ^/s/([^/]+)/?$ {
|
||||
rewrite ^/s/([^/]+)/?$ /api/v1/client/subscribe?token=$1 break;
|
||||
proxy_pass https://127.0.0.1:18443;
|
||||
include /etc/nginx/dpl-subscribe-proxy.conf;
|
||||
}
|
||||
location = /api/v1/client/subscribe {
|
||||
proxy_pass https://127.0.0.1:18443;
|
||||
include /etc/nginx/dpl-subscribe-proxy.conf;
|
||||
}
|
||||
location / { return 404; }
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
name: dpl-sgw
|
||||
services:
|
||||
gateway:
|
||||
image: sha256:d8807a5b2442bc25ce4fbc1312354b9dcbb0f538d75181ef735f4ea980760e70
|
||||
pull_policy: never
|
||||
container_name: dpl-subscribe-gateway
|
||||
restart: unless-stopped
|
||||
mem_limit: 160m
|
||||
cpus: 0.5
|
||||
ports:
|
||||
- "127.0.0.1:18080:80"
|
||||
- "127.0.0.1:18443:443"
|
||||
environment:
|
||||
V2B_BACKEND: https://dp-link.net
|
||||
V2B_HOST: dp-link.net
|
||||
REAL_IP_HEADER: X-Real-IP
|
||||
AXISNOW_TRUSTED_IPS: 172.28.31.1
|
||||
volumes:
|
||||
- config:/etc/nginx/subscribe
|
||||
- logs:/var/log/subscribe
|
||||
- /etc/dpl-letsencrypt:/etc/dpl-letsencrypt:ro
|
||||
- /var/lib/dpl-sgw/ssl:/etc/nginx/ssl:ro
|
||||
- ./gateway-nginx.conf:/etc/nginx/templates-src/nginx.conf:ro
|
||||
- ./gateway-protect.conf:/etc/nginx/templates-src/subscribe_protect.conf.template:ro
|
||||
networks: [dpl]
|
||||
logging: {driver: json-file, options: {max-size: "5m", max-file: "2"}}
|
||||
admin:
|
||||
image: sha256:31ff8ea3e8f958a835edbd1579709017da75b742ff3a5984ea59d12ea0775577
|
||||
pull_policy: never
|
||||
container_name: dpl-subscribe-admin
|
||||
restart: unless-stopped
|
||||
mem_limit: 128m
|
||||
cpus: 0.5
|
||||
ports:
|
||||
- "127.0.0.1:16444:64444"
|
||||
env_file: /var/lib/dpl-sgw/admin.env
|
||||
volumes:
|
||||
- config:/etc/nginx/subscribe
|
||||
- logs:/var/log/subscribe
|
||||
- /etc/dpl-letsencrypt:/etc/dpl-letsencrypt:ro
|
||||
- ./gateway-admin.conf:/etc/nginx/nginx.conf:ro
|
||||
networks: [dpl]
|
||||
logging: {driver: json-file, options: {max-size: "5m", max-file: "2"}}
|
||||
volumes:
|
||||
config: {name: dpl_sgw_config}
|
||||
logs: {name: dpl_sgw_logs}
|
||||
networks:
|
||||
dpl:
|
||||
name: dpl_sgw_net
|
||||
ipam:
|
||||
config: [{subnet: 172.28.31.0/24}]
|
||||
@@ -0,0 +1,31 @@
|
||||
#!/bin/bash
|
||||
set -euo pipefail
|
||||
[[ $(id -u) == 0 ]] || exit 1
|
||||
cd "$(dirname "$0")"
|
||||
test -s /etc/dpl-letsencrypt/live/c2.deeplink-subscribe.com/fullchain.pem
|
||||
docker image inspect sha256:d8807a5b2442bc25ce4fbc1312354b9dcbb0f538d75181ef735f4ea980760e70 >/dev/null
|
||||
docker image inspect sha256:31ff8ea3e8f958a835edbd1579709017da75b742ff3a5984ea59d12ea0775577 >/dev/null
|
||||
install -d -m 755 /var/lib/dpl-sgw
|
||||
install -d -m 755 /var/lib/dpl-sgw/acme /var/lib/dpl-sgw/ssl
|
||||
ln -sfn /etc/dpl-letsencrypt/live/c2.deeplink-subscribe.com/fullchain.pem /var/lib/dpl-sgw/ssl/cert.pem
|
||||
ln -sfn /etc/dpl-letsencrypt/live/c2.deeplink-subscribe.com/privkey.pem /var/lib/dpl-sgw/ssl/key.pem
|
||||
if [[ ! -e /var/lib/dpl-sgw/admin.env ]]; then
|
||||
umask 077
|
||||
printf 'ADMIN_USER=dpl-admin\nADMIN_PASS=%s\nV2B_BACKEND=https://dp-link.net\nV2B_HOST=dp-link.net\n' "$(openssl rand -hex 24)" > /var/lib/dpl-sgw/admin.env
|
||||
fi
|
||||
docker volume create dpl_sgw_config >/dev/null
|
||||
config_dir=$(docker volume inspect -f '{{.Mountpoint}}' dpl_sgw_config)
|
||||
# Only the new volume. Allow the documented jump host for acceptance checks.
|
||||
if [[ ! -f "$config_dir/whitelist_ips.txt" ]]; then
|
||||
printf '104.168.30.40\n' > "$config_dir/whitelist_ips.txt"
|
||||
fi
|
||||
chmod 755 renew-gateway.sh
|
||||
docker compose -f gateway.compose.yml config --quiet
|
||||
docker compose -f gateway.compose.yml up -d
|
||||
install -m 644 dpl-gateway-cert.service dpl-gateway-cert.timer /etc/systemd/system/
|
||||
install -m 644 dpl-cloudflare-ips.service dpl-cloudflare-ips.timer /etc/systemd/system/
|
||||
python3 update-cloudflare-ips.py
|
||||
systemctl daemon-reload
|
||||
systemctl enable --now dpl-gateway-cert.timer
|
||||
systemctl enable --now dpl-cloudflare-ips.timer
|
||||
echo 'New gateway started; verify initialization before enabling the HTTPS host site.'
|
||||
+19
-3
@@ -2,11 +2,27 @@
|
||||
set -euo pipefail
|
||||
# Credential files are installed separately with mode 0600.
|
||||
[[ $(id -u) == 0 ]] || exit 1
|
||||
listen_port=''
|
||||
tls_domain=''
|
||||
for arg in "$@"; do
|
||||
case "$arg" in
|
||||
--listen-port=*) listen_port=${arg#*=} ;;
|
||||
--tls-domain=*) tls_domain=${arg#*=} ;;
|
||||
*) echo 'Usage: install-node.sh --listen-port=24443 --tls-domain=us01.example.com'; exit 1 ;;
|
||||
esac
|
||||
done
|
||||
[[ $listen_port =~ ^[0-9]+$ && ${#listen_port} -le 5 ]] && (( 10#$listen_port >= 1024 && 10#$listen_port <= 65535 )) || { echo 'Explicit valid listen port required'; exit 1; }
|
||||
[[ $tls_domain =~ ^[a-z0-9][a-z0-9.-]*\.[a-z]{2,}$ ]] || { echo 'Explicit TLS domain required'; exit 1; }
|
||||
[[ -s /etc/dpl-node/config.yml && -s /etc/dpl-node/secret.env ]] || { echo 'Private node configuration missing'; exit 1; }
|
||||
if ss -lntH '( sport = :24443 )' | grep -q .; then
|
||||
echo 'Port 24443 already in use; inspect before deployment'; exit 1
|
||||
[[ ! -e /etc/systemd/system/dpl-node.service && ! -e /opt/dpl-node/xboard-node ]] || { echo 'DPL backend already installed; use a separately reviewed Git update'; exit 1; }
|
||||
if ss -lntH "( sport = :$listen_port )" | grep -q .; then
|
||||
echo "Port $listen_port already in use; inspect before deployment"; exit 1
|
||||
fi
|
||||
systemctl is-active --quiet XrayR
|
||||
if systemctl list-unit-files XrayR.service --no-legend | grep -q '^XrayR.service'; then
|
||||
systemctl is-active --quiet XrayR || { echo 'Existing XrayR is not active; investigate before installation'; exit 1; }
|
||||
fi
|
||||
printf '%s\n' "$tls_domain" > /etc/dpl-node/certificate-domain
|
||||
chmod 644 /etc/dpl-node/certificate-domain
|
||||
install -d -m 755 /opt/dpl-node
|
||||
install -d -m 700 /var/lib/dpl-node /var/lib/dpl-node/kernel
|
||||
curl --fail --location --silent --show-error \
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Move only the newly issued DPL certificate out of the old global renewal hooks."""
|
||||
import pathlib
|
||||
import shutil
|
||||
|
||||
domain = "c2.deeplink-subscribe.com"
|
||||
old = pathlib.Path("/etc/letsencrypt")
|
||||
new = pathlib.Path("/etc/dpl-letsencrypt")
|
||||
renewal = old / "renewal" / (domain + ".conf")
|
||||
if not renewal.exists():
|
||||
assert (new / "renewal" / (domain + ".conf")).exists(), "No DPL renewal registration"
|
||||
print("DPL certificate already isolated")
|
||||
raise SystemExit
|
||||
text = renewal.read_text()
|
||||
assert "authenticator = webroot" in text
|
||||
assert "https://acme-v02.api.letsencrypt.org/directory" in text
|
||||
account = next(line.split("=", 1)[1].strip() for line in text.splitlines() if line.startswith("account ="))
|
||||
assert account.isalnum()
|
||||
new.mkdir(mode=0o700, exist_ok=True)
|
||||
for folder in ("live", "archive", "renewal", "accounts"):
|
||||
(new / folder).mkdir(mode=0o700, exist_ok=True)
|
||||
for folder in ("live", "archive"):
|
||||
assert (old / folder / domain).is_dir()
|
||||
assert not (new / folder / domain).exists(), "Partial migration; inspect before retry"
|
||||
account_relative = pathlib.Path("accounts/acme-v02.api.letsencrypt.org/directory") / account
|
||||
shutil.copytree(old / account_relative, new / account_relative, dirs_exist_ok=True)
|
||||
backup = pathlib.Path("/root/codex-backups/dpl-gateway-20261011/certificate-before-isolation")
|
||||
backup.mkdir(mode=0o700, exist_ok=True)
|
||||
shutil.copy2(renewal, backup / renewal.name)
|
||||
for folder in ("live", "archive"):
|
||||
shutil.move(str(old / folder / domain), str(new / folder / domain))
|
||||
(new / "renewal" / renewal.name).write_text(text.replace("/etc/letsencrypt/", "/etc/dpl-letsencrypt/"))
|
||||
(new / "renewal" / renewal.name).chmod(0o600)
|
||||
renewal.unlink() # Only the new DPL registration; old certificates and hooks stay intact.
|
||||
assert (new / "live" / domain / "fullchain.pem").is_file()
|
||||
print("DPL certificate isolated from original gateway renewal hooks")
|
||||
+43
@@ -0,0 +1,43 @@
|
||||
<?php
|
||||
// Run only after real relay, subscription, certificate and traffic checks pass.
|
||||
require getcwd() . '/vendor/autoload.php';
|
||||
$app = require getcwd() . '/bootstrap/app.php';
|
||||
$app->make(Illuminate\Contracts\Console\Kernel::class)->bootstrap();
|
||||
use App\Models\Plan;
|
||||
use App\Models\Server;
|
||||
use App\Models\ServerGroup;
|
||||
use App\Models\User;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
$opts = getopt('', ['backup:', 'plans:', 'group:']);
|
||||
$dir = $opts['backup'] ?? throw new RuntimeException('Missing backup');
|
||||
$ids = array_map('intval', explode(',', $opts['plans'] ?? ''));
|
||||
if (!$ids || in_array(0, $ids, true)) throw new RuntimeException('Explicit plan IDs required');
|
||||
$m = json_decode(file_get_contents("$dir/manifest.json"), true, flags: JSON_THROW_ON_ERROR);
|
||||
$groupId = (int)($opts['group'] ?? $m['group_id']);
|
||||
$node = Server::findOrFail($m['node_id']);
|
||||
$qa = User::findOrFail($m['test_user_id']);
|
||||
if (!$node->is_online || $qa->u + $qa->d <= 0) throw new RuntimeException('Online and traffic evidence missing');
|
||||
if (is_file("$dir/promoted.json")) { echo "Already promoted; verify current state separately\n"; exit; }
|
||||
$plans = Plan::whereIn('id', $ids)->get();
|
||||
if ($plans->count() !== count($ids)) throw new RuntimeException('Plan list mismatch');
|
||||
foreach ($plans as $p) if ($p->group_id !== null && $p->group_id !== $groupId) throw new RuntimeException('Plan already assigned elsewhere');
|
||||
$users = User::whereIn('plan_id', $ids)->whereNull('group_id')->get(['id','group_id','updated_at']);
|
||||
umask(0077);
|
||||
file_put_contents("$dir/before-promotion.json", json_encode([
|
||||
'plans' => $plans->map->getAttributes(), 'user_groups' => $users,
|
||||
'node_groups' => $node->group_ids, 'group' => ServerGroup::findOrFail($groupId)->getAttributes(),
|
||||
'subscribe_url' => admin_setting('subscribe_url'), 'qa_banned' => $qa->banned,
|
||||
], JSON_THROW_ON_ERROR));
|
||||
DB::transaction(function () use ($ids, $users, $node, $qa, $groupId) {
|
||||
$group = ServerGroup::findOrFail($groupId);
|
||||
if (str_starts_with($group->name, 'dpl 接入验收 ')) { $group->name = '基础节点'; $group->save(); }
|
||||
Plan::whereIn('id', $ids)->whereNull('group_id')->update(['group_id' => $groupId]);
|
||||
User::whereIn('id', $users->pluck('id'))->whereNull('group_id')->update(['group_id' => $groupId]);
|
||||
$node->group_ids = [(string)$groupId]; $node->save();
|
||||
$qa->banned = 1; $qa->saveQuietly();
|
||||
admin_setting(['subscribe_url' => 'https://c2.deeplink-subscribe.com']);
|
||||
});
|
||||
$result = ['node_id' => $node->id, 'group_id' => $groupId, 'plan_ids' => $ids,
|
||||
'existing_users_assigned' => $users->count(), 'qa_disabled' => true];
|
||||
file_put_contents("$dir/promoted.json", json_encode($result, JSON_THROW_ON_ERROR));
|
||||
echo json_encode($result) . PHP_EOL;
|
||||
@@ -0,0 +1,16 @@
|
||||
<?php
|
||||
require getcwd() . '/vendor/autoload.php';
|
||||
$app = require getcwd() . '/bootstrap/app.php';
|
||||
$app->make(Illuminate\Contracts\Console\Kernel::class)->bootstrap();
|
||||
$opts = getopt('', ['backup:']);
|
||||
$dir = $opts['backup'] ?? throw new RuntimeException('Missing backup');
|
||||
$m = json_decode(file_get_contents("$dir/manifest.json"), true, flags: JSON_THROW_ON_ERROR);
|
||||
$node = App\Models\Server::findOrFail($m['node_id']);
|
||||
$qa = App\Models\User::findOrFail($m['test_user_id']);
|
||||
echo json_encode([
|
||||
'node_id' => $node->id, 'name' => $node->name, 'is_online' => $node->is_online,
|
||||
'last_check_at' => $node->last_check_at, 'last_push_at' => $node->last_push_at,
|
||||
'qa_upload' => $qa->u, 'qa_download' => $qa->d, 'qa_banned' => $qa->banned,
|
||||
'plans' => App\Models\Plan::orderBy('id')->get(['id', 'group_id']),
|
||||
'existing_users_with_selected_plan_and_null_group' => App\Models\User::whereIn('plan_id', [1,6,7,8])->whereNull('group_id')->count(),
|
||||
], JSON_UNESCAPED_UNICODE) . PHP_EOL;
|
||||
@@ -0,0 +1,9 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
[ "${RENEWED_LINEAGE:-}" = /etc/dpl-letsencrypt/live/c2.deeplink-subscribe.com ] || exit 0
|
||||
nginx -t
|
||||
for container in dpl-subscribe-gateway dpl-subscribe-admin; do
|
||||
docker exec "$container" nginx -t
|
||||
docker exec "$container" nginx -s reload
|
||||
done
|
||||
systemctl reload nginx
|
||||
@@ -0,0 +1,7 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
# Copy under renewal-hooks/deploy only after auditing all existing hooks.
|
||||
[ -s /etc/dpl-node/certificate-domain ] || exit 0
|
||||
domain=$(cat /etc/dpl-node/certificate-domain)
|
||||
[ "${RENEWED_LINEAGE:-}" = "/etc/letsencrypt/live/$domain" ] || exit 0
|
||||
systemctl try-restart dpl-node
|
||||
@@ -0,0 +1,140 @@
|
||||
{
|
||||
"dns": {
|
||||
"rules": [
|
||||
{
|
||||
"clash_mode": "global",
|
||||
"server": "remote"
|
||||
},
|
||||
{
|
||||
"clash_mode": "direct",
|
||||
"server": "local"
|
||||
},
|
||||
{
|
||||
"rule_set": [
|
||||
"geosite-cn"
|
||||
],
|
||||
"server": "local"
|
||||
}
|
||||
],
|
||||
"servers": [
|
||||
{
|
||||
"type": "https",
|
||||
"server": "1.1.1.1",
|
||||
"detour": "节点选择",
|
||||
"tag": "remote"
|
||||
},
|
||||
{
|
||||
"type": "https",
|
||||
"server": "223.5.5.5",
|
||||
"tag": "local"
|
||||
}
|
||||
],
|
||||
"strategy": "prefer_ipv4"
|
||||
},
|
||||
"experimental": {
|
||||
"cache_file": {
|
||||
"enabled": true,
|
||||
"path": "cache.db",
|
||||
"cache_id": "cache_db",
|
||||
"store_fakeip": true
|
||||
}
|
||||
},
|
||||
"inbounds": [
|
||||
{
|
||||
"auto_route": true,
|
||||
"address": [
|
||||
"172.19.0.1/30",
|
||||
"2001:0470:f9da:fdfa::1/64"
|
||||
],
|
||||
"mtu": 9000,
|
||||
"stack": "system",
|
||||
"strict_route": true,
|
||||
"type": "tun"
|
||||
},
|
||||
{
|
||||
"listen": "127.0.0.1",
|
||||
"listen_port": 2333,
|
||||
"tag": "socks-in",
|
||||
"type": "socks",
|
||||
"users": []
|
||||
},
|
||||
{
|
||||
"listen": "127.0.0.1",
|
||||
"listen_port": 2334,
|
||||
"tag": "mixed-in",
|
||||
"type": "mixed",
|
||||
"users": []
|
||||
}
|
||||
],
|
||||
"outbounds": [
|
||||
{
|
||||
"tag": "节点选择",
|
||||
"type": "selector",
|
||||
"default": "自动选择",
|
||||
"outbounds": [
|
||||
"自动选择"
|
||||
]
|
||||
},
|
||||
{
|
||||
"tag": "direct",
|
||||
"type": "direct"
|
||||
},
|
||||
{
|
||||
"tag": "自动选择",
|
||||
"type": "urltest",
|
||||
"outbounds": []
|
||||
}
|
||||
],
|
||||
"route": {
|
||||
"auto_detect_interface": true,
|
||||
"rules": [
|
||||
{
|
||||
"action": "resolve",
|
||||
"strategy": "prefer_ipv4"
|
||||
},
|
||||
{
|
||||
"action": "sniff"
|
||||
},
|
||||
{
|
||||
"protocol": "dns",
|
||||
"action": "hijack-dns"
|
||||
},
|
||||
{
|
||||
"clash_mode": "direct",
|
||||
"outbound": "direct"
|
||||
},
|
||||
{
|
||||
"clash_mode": "global",
|
||||
"outbound": "节点选择"
|
||||
},
|
||||
{
|
||||
"ip_is_private": true,
|
||||
"outbound": "direct"
|
||||
},
|
||||
{
|
||||
"rule_set": [
|
||||
"geosite-cn",
|
||||
"geoip-cn"
|
||||
],
|
||||
"outbound": "direct"
|
||||
}
|
||||
],
|
||||
"rule_set": [
|
||||
{
|
||||
"tag": "geosite-cn",
|
||||
"type": "remote",
|
||||
"format": "binary",
|
||||
"url": "https://raw.githubusercontent.com/SagerNet/sing-geosite/rule-set/geosite-cn.srs",
|
||||
"download_detour": "自动选择"
|
||||
},
|
||||
{
|
||||
"tag": "geoip-cn",
|
||||
"type": "remote",
|
||||
"format": "binary",
|
||||
"url": "https://raw.githubusercontent.com/SagerNet/sing-geoip/rule-set/geoip-cn.srs",
|
||||
"download_detour": "自动选择"
|
||||
}
|
||||
],
|
||||
"default_domain_resolver": "local"
|
||||
}
|
||||
}
|
||||
@@ -38,7 +38,9 @@ file_put_contents("$dir/before.json", json_encode([
|
||||
], JSON_THROW_ON_ERROR));
|
||||
|
||||
$manifest = DB::transaction(function () use ($opts) {
|
||||
$group = ServerGroup::create(['name' => 'dpl 接入验收 ' . $opts['key']]);
|
||||
$group = new ServerGroup();
|
||||
$group->name = 'dpl 接入验收 ' . $opts['key'];
|
||||
$group->save();
|
||||
$machine = ServerMachine::create([
|
||||
'name' => 'dpl-' . $opts['key'], 'notes' => 'Independent AnyTLS service; existing XrayR preserved',
|
||||
'is_active' => true, 'token' => ServerMachine::generateToken(),
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Update the gateway vhosts' trusted ranges, retaining the last valid configuration on failure."""
|
||||
import ipaddress
|
||||
import os
|
||||
import pathlib
|
||||
import subprocess
|
||||
|
||||
target = pathlib.Path("/etc/nginx/dpl-cloudflare-realip.conf")
|
||||
ranges = []
|
||||
for version in (4, 6):
|
||||
result = subprocess.run(["curl", "-4", "--fail", "--silent", "--show-error", "--max-time", "30",
|
||||
f"https://www.cloudflare.com/ips-v{version}"], check=True, capture_output=True, text=True)
|
||||
nets = [ipaddress.ip_network(line.strip(), strict=True) for line in result.stdout.splitlines() if line.strip()]
|
||||
assert 5 <= len(nets) <= 100 if version == 4 else 2 <= len(nets) <= 100, "Unexpected range count"
|
||||
assert all(n.version == version and n.prefixlen >= (8 if version == 4 else 16) for n in nets), "Invalid trust range"
|
||||
ranges.extend(str(n) for n in nets)
|
||||
assert len(ranges) == len(set(ranges)), "Duplicate ranges"
|
||||
data = ("# Subscription vhosts: synchronized from Cloudflare official lists.\n" +
|
||||
"".join(f"set_real_ip_from {n};\n" for n in ranges) +
|
||||
"real_ip_header CF-Connecting-IP;\nreal_ip_recursive off;\n").encode()
|
||||
old = target.read_bytes() if target.exists() else None
|
||||
if old == data:
|
||||
print("Cloudflare trust ranges unchanged")
|
||||
raise SystemExit
|
||||
temporary = target.with_suffix(".conf.new")
|
||||
temporary.write_bytes(data)
|
||||
temporary.chmod(0o644)
|
||||
os.replace(temporary, target)
|
||||
try:
|
||||
subprocess.run(["nginx", "-t"], check=True)
|
||||
subprocess.run(["systemctl", "reload", "nginx"], check=True)
|
||||
except Exception:
|
||||
if old is None:
|
||||
target.unlink()
|
||||
else:
|
||||
temporary.write_bytes(old)
|
||||
temporary.chmod(0o644)
|
||||
os.replace(temporary, target)
|
||||
raise
|
||||
print(f"DPL Cloudflare trust ranges updated: {len(ranges)} ranges")
|
||||
@@ -0,0 +1,72 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Run an isolated SOCKS client with strict TLS; never print QA credentials."""
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import pathlib
|
||||
import shutil
|
||||
import socket
|
||||
import subprocess
|
||||
import tempfile
|
||||
import time
|
||||
|
||||
p = argparse.ArgumentParser()
|
||||
p.add_argument('--qa', required=True)
|
||||
p.add_argument('--binary', required=True)
|
||||
p.add_argument('--expected-exit', required=True)
|
||||
p.add_argument('--port', type=int, default=19080)
|
||||
p.add_argument('--subscription')
|
||||
a = p.parse_args()
|
||||
q = json.loads(pathlib.Path(a.qa).read_text())
|
||||
c = {'log': {'level': 'error'}, 'dns': {'servers': [{'type': 'local', 'tag': 'local'}]},
|
||||
'inbounds': [{'type': 'mixed', 'listen': '127.0.0.1', 'listen_port': a.port}],
|
||||
'outbounds': [{'type': 'anytls', 'tag': 'qa', 'server': q['host'], 'server_port': q['port'],
|
||||
'password': q['uuid'], 'tls': {'enabled': True, 'server_name': q['sni'], 'insecure': False}}],
|
||||
'route': {'default_domain_resolver': 'local', 'final': 'qa'}}
|
||||
if a.subscription:
|
||||
c = json.loads(pathlib.Path(a.subscription).read_text())
|
||||
nodes = [x for x in c['outbounds'] if x.get('type') == 'anytls']
|
||||
assert len(nodes) == 1 and nodes[0]['tls'].get('insecure') is False
|
||||
assert nodes[0]['server'] == q['host'] and nodes[0]['server_port'] == q['port']
|
||||
assert nodes[0]['password'] == q['uuid']
|
||||
c['inbounds'] = [{'type': 'mixed', 'listen': '127.0.0.1', 'listen_port': a.port}]
|
||||
c['log'] = {'level': 'error'}
|
||||
os.umask(0o077)
|
||||
with tempfile.TemporaryDirectory(prefix='dpl-client-') as d:
|
||||
config = pathlib.Path(d) / 'client.json'
|
||||
config.write_text(json.dumps(c))
|
||||
env = dict(os.environ, GOMEMLIMIT='64MiB', GOGC='75')
|
||||
with (pathlib.Path(d) / 'client.log').open('wb') as log:
|
||||
proc = subprocess.Popen([a.binary, 'run', '-c', str(config)], cwd=d, env=env, stdout=log, stderr=log)
|
||||
try:
|
||||
for _ in range(50):
|
||||
assert proc.poll() is None, 'Client exited during startup'
|
||||
try:
|
||||
with socket.create_connection(('127.0.0.1', a.port), 0.1):
|
||||
break
|
||||
except OSError:
|
||||
time.sleep(0.1)
|
||||
command = ['curl', '-q', '--fail', '--silent', '--show-error', '--max-time', '30',
|
||||
'--socks5-hostname', f'127.0.0.1:{a.port}']
|
||||
result = subprocess.run(command + ['https://api.ipify.org'], capture_output=True, text=True, check=True)
|
||||
ip = result.stdout.strip()
|
||||
assert ip == a.expected_exit, 'Unexpected exit IP'
|
||||
result = subprocess.run(command + ['https://www.cloudflare.com/cdn-cgi/trace'], capture_output=True, text=True, check=True)
|
||||
trace = dict(line.split('=', 1) for line in result.stdout.splitlines() if '=' in line)
|
||||
assert trace.get('ip') == a.expected_exit, 'Second exit check mismatch'
|
||||
print(json.dumps({'anytls': True, 'relay': q['host'], 'port': q['port'], 'strict_tls': True,
|
||||
'exit_ip': ip, 'country': trace.get('loc'), 'https_tls': trace.get('tls')}, ensure_ascii=False))
|
||||
except Exception:
|
||||
log.flush()
|
||||
failure = pathlib.Path(a.qa).parent / 'client-failure.log'
|
||||
shutil.copyfile(pathlib.Path(d) / 'client.log', failure)
|
||||
failure.chmod(0o600)
|
||||
print(f'Client failed; protected diagnostic log: {failure}')
|
||||
raise
|
||||
finally:
|
||||
proc.terminate()
|
||||
try:
|
||||
proc.wait(timeout=5)
|
||||
except subprocess.TimeoutExpired:
|
||||
proc.kill()
|
||||
proc.wait()
|
||||
Reference in new issue
Block a user