Merge branch 'master' into codex/hn-custom-theme

# Conflicts:
#	docs/maintenance/STATUS.md
This commit is contained in:
hellcat committed 2026-10-27 18:29:48 +08:00
commit 2e5cec6a05
39 files changed
+4329 -275

No files matched your search

@@ -2,4 +2,5 @@
Description=Renew only the two gateway administration host certificates
[Service]
Type=oneshot
TimeoutStartSec=15min
ExecStart=/bin/sh /opt/gateway-admin-proxy/provision/renew-gateway-admin.sh
@@ -32,7 +32,7 @@ def api(method, suffix, payload=None):
if not re.fullmatch(r'[a-f0-9]{32}', zone) or cfg['target'] != TARGET:
raise RuntimeError('Unapproved DNS configuration')
token = TOKEN.read_text().strip()
if not re.fullmatch(r'[A-Za-z0-9_-]{40}', token):
if not re.fullmatch(r'[A-Za-z0-9_-]{20,128}', token):
raise RuntimeError('Invalid token format')
with tempfile.TemporaryDirectory(prefix='acme-api-', dir=STATE) as folder:
body = pathlib.Path(folder) / 'request.json'
+23 -5
View File
@@ -9,6 +9,20 @@ import re
CA = '/etc/ssl/certs/ca-certificates.crt'
ACME = '/var/lib/gateway-admin-proxy/acme'
CF_TRUST = '/etc/nginx/white-proxy-cloudflare-realip.conf'
HEALTH_MAP = '''log_format gateway_admin_proxy_health '$time_iso8601 host=$host status=$status upstream_status=$upstream_status duration=$request_time';
map $status $gateway_admin_proxy_log_failure {
~^[45] 1;
default 0;
}
'''
def private_logs():
# Nginx error lines include the entire request URI, including subscription tokens.
# Keep critical diagnostics plus status-only failure records for these new vhosts.
return ''' access_log /var/log/nginx/gateway-admin-proxy.health.log gateway_admin_proxy_health if=$gateway_admin_proxy_log_failure;
error_log /var/log/nginx/gateway-admin-proxy.error.log crit;
'''
def proxy_lines(upstream, tls_name, host, alias=None):
@@ -48,7 +62,7 @@ def http_server(names, redirect=True):
listen 80;
listen [::]:80;
server_name {names};
access_log off;
{private_logs()}
location ^~ /.well-known/acme-challenge/ {{
root {ACME};
try_files $uri =404;
@@ -95,15 +109,14 @@ def https_server(names, certificate, content, cloudflare=False, white_ip=None, k
ssl_certificate_key {certificate}/{key_name};
ssl_protocols TLSv1.2 TLSv1.3;
client_max_body_size 20m;
access_log off;
error_log /var/log/nginx/gateway-admin-proxy.error.log warn;
{private_logs()}
{trusted}{content}
}}
'''
def render_gateway(stage, legacy_path, white_ip):
files = {'00-gateway-admin-proxy-maps.conf': '''map $http_upgrade $gateway_admin_proxy_connection {
files = {'00-gateway-admin-proxy-maps.conf': HEALTH_MAP + '''map $http_upgrade $gateway_admin_proxy_connection {
default upgrade;
'' close;
}
@@ -133,7 +146,7 @@ def render_gateway(stage, legacy_path, white_ip):
def render_white(stage, legacy_certificate, skip_legacy=False):
files = {}
maps = '''map $http_upgrade $gateway_admin_proxy_connection {
maps = HEALTH_MAP + '''map $http_upgrade $gateway_admin_proxy_connection {
default upgrade;
'' close;
}
@@ -142,6 +155,7 @@ map $host $gateway_admin_origin_host {
~^(?<gnew>[a-z0-9-]+)\\.tomshell\\.online$ $gnew.gemcook.net;
tomshell.com.de diaodu.us;
~^(?<gold>[a-z0-9-]+)\\.tomshell\\.com\\.de$ $gold.diaodu.us;
weiwei.tomtojapan.online hw.lshan.eu.org;
dpl.tomtojapan.online dp-link.net;
fuc.tomtojapan.online xn--9kqy16h.com;
default '';
@@ -161,6 +175,8 @@ map "$host|$http_referer" $gateway_admin_referer {
'gemcook.net', 'tomshell.online', True),
('old', 'tomshell.com.de *.tomshell.com.de', legacy_certificate,
'diaodu.us', 'tomshell.com.de', False),
('weiwei', 'weiwei.tomtojapan.online', '/etc/white-proxy-origin/tomtojapan.online',
'hw.lshan.eu.org', 'weiwei.tomtojapan.online', True),
('dpl-site', 'dpl.tomtojapan.online', '/etc/white-proxy-origin/tomtojapan.online',
'dp-link.net', 'dpl.tomtojapan.online', True),
('fuc-site', 'fuc.tomtojapan.online', '/etc/white-proxy-origin/tomtojapan.online',
@@ -186,6 +202,8 @@ map "$host|$http_referer" $gateway_admin_referer {
{body_rewrites(source, alias, key)}
}}
'''
if key == 'weiwei':
location += ' add_header Cache-Control "private, no-store" always;\n'
data += https_server(names, cert, location, cloudflare=cf,
key_name='privatekey.pem' if cf else 'privkey.pem')
files[f'white-{key}-proxy.conf'] = data
@@ -1,7 +1,7 @@
#!/bin/sh
set -eu
umask 077
exec certbot renew --quiet \
exec certbot renew --quiet --no-random-sleep-on-renew \
--config-dir /etc/gateway-admin-letsencrypt \
--work-dir /var/lib/gateway-admin-proxy/certbot \
--logs-dir /var/log/gateway-admin-certbot \
@@ -1,7 +1,7 @@
#!/bin/sh
set -eu
umask 077
exec certbot renew --quiet \
exec certbot renew --quiet --no-random-sleep-on-renew \
--config-dir /etc/white-proxy-letsencrypt \
--work-dir /var/lib/white-proxy-certbot \
--logs-dir /var/log/white-proxy-certbot \
@@ -23,6 +23,7 @@ with tempfile.TemporaryDirectory(prefix='gateway-proxy-maps-') as folder:
port = sock.getsockname()[1]
maps = render.render_white('https', '/unused')['00-gateway-admin-proxy-maps.conf']
bodies = [
('weiwei', 'weiwei.tomtojapan.online', 'hw.lshan.eu.org', 'weiwei.tomtojapan.online', 'weiwei', '海外转发'),
('dpl', 'dpl.tomtojapan.online', 'dp-link.net', 'dpl.tomtojapan.online', 'dpl-site', 'DP-LINK.NET'),
('fuc', 'fuc.tomtojapan.online', 'xn--9kqy16h.com', 'fuc.tomtojapan.online', 'fuc-site', '福云.com'),
('new', 'getway-dpl.tomshell.online', 'gemcook.net', 'tomshell.online', 'new', 'GEMCOOK.NET'),
@@ -2,4 +2,5 @@
Description=Renew isolated public wildcard certificate for legacy white proxy
[Service]
Type=oneshot
TimeoutStartSec=30min
ExecStart=/bin/sh /opt/gateway-admin-proxy/provision/renew-white-legacy.sh
+134
View File
@@ -0,0 +1,134 @@
"""Token-free dynamic evidence validation shared by the reusable site adapter."""
import hashlib
import ipaddress
import re
import json
import time
def digest(value):
return hashlib.sha256(json.dumps(value, sort_keys=True, ensure_ascii=False, separators=(',', ':')).encode()).hexdigest()
def snapshot(nodes):
if not isinstance(nodes, list) or not nodes:
raise ValueError('Empty authorized node set')
fields = ('id', 'type', 'tag', 'relay', 'relay_port', 'sni', 'expected_exit', 'country')
result = []
for node in nodes:
if node.get('type') != 'anytls' or any(node.get(k) in (None, '') for k in fields):
raise ValueError('Unsupported protocol or incomplete independently registered expectations')
if type(node['id']) is not int or node['id']<1 or type(node['relay_port']) is not int or not 1<=node['relay_port']<=65535 or not isinstance(node['country'],str) or not re.fullmatch('[A-Z]{2}',node['country']):
raise ValueError('Invalid authorized node identity or expectation')
address=ipaddress.ip_address(node['expected_exit'])
if getattr(address,'scope_id',None):raise ValueError('Scoped exit expectation unsupported')
result.append({k: node[k] for k in fields})
for key in ('id', 'tag'):
if len({n[key] for n in result}) != len(result):
raise ValueError('Duplicate authorized node identity')
if len({(n['relay'], n['relay_port'], n['sni']) for n in result}) != len(result):
raise ValueError('Ambiguous authorized endpoint')
return sorted(result, key=lambda n: n['id'])
def candidate_eligibility(total_memory_bytes, xrayr_installed):
"""Use physical MemTotal, excluding swap and currently free memory. 1 GB = 10**9 bytes."""
if type(total_memory_bytes) is not int or total_memory_bytes <= 0 or type(xrayr_installed) is not bool:
raise ValueError('Unknown candidate memory or XrayR installation')
return not (total_memory_bytes < 1_000_000_000 and xrayr_installed)
def validate_impact(impact):
if impact is None:
return
if not isinstance(impact, dict) or set(impact) != {'shared_changes', 'affected_snis', 'review'}:
raise ValueError('Explicit reviewed impact required')
if not isinstance(impact['review'], str) or not impact['review'].strip():
raise ValueError('Impact review reference required')
for key in ('shared_changes', 'affected_snis'):
if not isinstance(impact[key], list) or any(not isinstance(x, str) or not x.strip() for x in impact[key]) or len(set(impact[key])) != len(impact[key]):
raise ValueError('Invalid impact inventory')
def verification_scope(nodes, impact=None):
"""Unknown/shared impact keeps full tests; reviewed append uses light TLS probes."""
nodes = snapshot(nodes)
if impact is None:
return {n['tag']: 'full' for n in nodes}
validate_impact(impact)
if not set(impact['affected_snis']).issubset({n['sni'] for n in nodes}):
raise ValueError('Affected node absent from current authorization set')
return {n['tag']: 'full' if impact['shared_changes'] or n['sni'] in impact['affected_snis'] else 'tls' for n in nodes}
def audit(before, after, report_bytes, qa_bytes, binding, plan_sha, expected_qas, now=None, ttl=900, scope=None):
now = time.time() if now is None else now
before, after = snapshot(before), snapshot(after)
if before != after or binding.get('snapshot_sha256') != digest(before):
raise ValueError('Authorized node set changed; regenerate and verify the complete set')
if binding.get('plan_sha256') != plan_sha:
raise ValueError('Wrong plan binding')
for label, raw in [('report', report_bytes), ('qa_rejections', qa_bytes)]:
if binding.get(label + '_sha256') != hashlib.sha256(raw).hexdigest():
raise ValueError('Evidence bytes changed')
report, qas = json.loads(report_bytes), json.loads(qa_bytes)
for stamp in (binding.get('verified_at'), report.get('verified_at'), qas.get('captured_at')):
if type(stamp) not in (int, float) or not 0 <= now-stamp <= ttl:
raise ValueError('Evidence expired or future dated')
modes = {n['tag']: 'full' for n in before} if scope is None else scope
if set(modes) != {n['tag'] for n in before} or any(v not in ('full', 'tls') for v in modes.values()):
raise ValueError('Incomplete verification scope')
if scope is not None and binding.get('scope_sha256') != digest(modes):
raise ValueError('Verification scope binding changed')
if report.get('state') != 'live_verified' or len(report.get('results', [])) != len(before):
raise ValueError('Incomplete live verification')
actual = {}
for result in report['results']:
tag = result.get('tag')
if tag in actual or tag not in modes:
raise ValueError('Unexpected or duplicate verification result')
actual[tag] = result
for node in before:
result = actual.get(node['tag'], {})
if result.get('live') is not True or result.get('strict_tls') is not True or result.get('verification', 'full') != modes[node['tag']]:
raise ValueError('Required verification mode or strict TLS missing')
if any(result.get(k) != node[k] for k in ('relay', 'relay_port', 'sni')):
raise ValueError('Node endpoint mismatch')
if modes[node['tag']] == 'full' and (result.get('exit_ip') != node['expected_exit'] or result.get('country') != node['country']):
raise ValueError('Node exit/country mismatch')
if qas.get('plan_sha256') != plan_sha or set(qas.get('users', {})) != set(expected_qas):
raise ValueError('QA evidence identity mismatch')
for key, identity in expected_qas.items():
q = qas['users'][key]
if q.get('id') != identity or q.get('http_status') != 403 or q.get('banned') is not True or q.get('excluded') is not True:
raise ValueError('QA account not fully revoked')
return {'nodes': len(before), 'snapshot_sha256': digest(before), 'verified_at': now}
def service_change(before, current):
"""Process movement is investigatory; never silently accept/rebase it."""
required = ('unit_sha256', 'binary_sha256', 'config_sha256', 'listeners')
if any(not before.get(k) or not current.get(k) for k in required):
return 'unknown'
if any(before[k] != current[k] for k in required) or current.get('active') is not True:
return 'conflict'
if any(before.get(k) != current.get(k) for k in ('pid', 'started', 'restarts')):
return 'investigate_restart'
return 'ready'
def provider_state(observed, node, now=None):
"""Canonical observations from the registered provider UI/API, never HTML substrings."""
now=time.time() if now is None else now
stamp=observed.get('captured_at')
if type(stamp) not in (int,float) or not 0<=now-stamp<=900:
raise ValueError('Provider observation expired')
if not isinstance(observed.get('dns'),list) or not isinstance(observed.get('relays'),list):
raise ValueError('Canonical DNS and relay observations required')
dns=[d for d in observed['dns'] if d.get('name')==node['tls_domain']]
relays=[r for r in observed['relays'] if r.get('host')==node['relay_host'] and r.get('port')==node['relay_port']]
if dns and (len(dns)!=1 or dns[0].get('type')!='A' or dns[0].get('address')!=node['node_address'] or dns[0].get('proxy') is not False):
raise ValueError('DNS provider resource conflict')
if relays and (len(relays)!=1 or relays[0].get('target')!=node['node_address'] or relays[0].get('listen_port')!=node['listen_port'] or relays[0].get('name')!='dpl-'+node['key']+'-anytls' or relays[0].get('proxy_protocol_in') is not False or relays[0].get('proxy_protocol_out') is not False):
raise ValueError('Relay provider resource conflict')
return {'dns':dns,'relays':relays}
+461
View File
@@ -0,0 +1,461 @@
#!/usr/bin/env python3
"""DPL append-only batch coordinator. Adapters must probe before and after writes."""
import argparse
import concurrent.futures
import contextlib
import fcntl
import hashlib
import ipaddress
import importlib.util
import json
import os
from pathlib import Path
import re
import signal
import sqlite3
import subprocess
import sys
import threading
import time
PHASES = ('stage', 'dns', 'provision', 'relay', 'verify', 'publish', 'audit')
SHARED = {'stage': 'panel', 'dns': 'dns', 'relay': 'relay', 'publish': 'panel'}
STOP = threading.Event()
EVENTS = False
def digest(value):
return hashlib.sha256(json.dumps(value, sort_keys=True, ensure_ascii=False,
separators=(',', ':')).encode()).hexdigest()
def read_json(path):
return json.loads(Path(path).read_text())
def atomic_json(path, value):
path = Path(path)
tmp = path.with_name(path.name + '.tmp-' + str(os.getpid()) + '-' + str(threading.get_ident()))
with tmp.open('x') as f:
os.chmod(tmp, 0o600)
json.dump(value, f, ensure_ascii=False, sort_keys=True)
f.flush()
os.fsync(f.fileno())
os.replace(tmp, path)
def validate(plan):
if plan.get('version') != 1 or plan.get('mode') != 'append':
raise ValueError('Only version=1, mode=append is supported')
if not re.fullmatch(r'[a-z0-9-]{1,64}', plan.get('batch_id', '')):
raise ValueError('Invalid batch_id')
context = plan.get('context', {})
required = ('panel_vps', 'gateway_vps', 'jump_vps', 'app_root', 'panel_url',
'subscription_url', 'provision_commit', 'bundle', 'client_binary')
if any(not context.get(k) for k in required):
raise ValueError('Missing explicit context fields')
if not re.fullmatch(r'[0-9a-f]{40}', context['provision_commit']):
raise ValueError('A full reviewed, pushed Git commit is required')
for k in ('panel_url', 'subscription_url'):
if not re.fullmatch(r'https://[a-z0-9.-]+', context[k]):
raise ValueError('HTTPS origin without token/path required: ' + k)
adapter = plan.get('adapter')
if not isinstance(adapter, list) or not adapter or not all(isinstance(x, str) for x in adapter):
raise ValueError('adapter must be an argv array, never a shell string')
if not plan.get('nodes') or not isinstance(plan['nodes'], list):
raise ValueError('A nonempty node list is required')
seen = {k: set() for k in ('key', 'name', 'vps_id', 'node_address', 'tls_domain', 'relay', 'socks_port', 'number')}
for n in plan['nodes']:
if any(k not in n for k in ('key', 'country', 'sequence', 'flag', 'country_name', 'name',
'vps_id', 'node_address', 'listen_port', 'relay_host',
'relay_port', 'tls_domain', 'formal_group_id',
'expected_exit', 'socks_port')):
raise ValueError('Incomplete node specification')
if not re.fullmatch(r'[a-z0-9-]{1,48}', n['key']):
raise ValueError('Invalid deployment key')
if not re.fullmatch(r'[A-Z]{2}', n['country']):
raise ValueError('Country must be a two-letter code')
if type(n['sequence']) is not int or not 1 <= n['sequence'] <= 99:
raise ValueError('Display sequence must be 01..99')
expected = f"{n['flag']} {n['country_name']} {n['country']} - {n['sequence']:02d}"
flag = ''.join(chr(0x1F1E6 + ord(x) - ord('A')) for x in n['country'])
if n['name'] != expected or n['flag'] != flag:
raise ValueError('Display name/flag does not match country and sequence')
for k in ('listen_port', 'relay_port', 'socks_port'):
if type(n[k]) is not int or not 1024 <= n[k] <= 65535:
raise ValueError('Invalid port: ' + k)
if type(n['formal_group_id']) is not int or n['formal_group_id'] < 1:
raise ValueError('An existing formal group is required')
ipaddress.ip_address(n['node_address'])
exit_address=ipaddress.ip_address(n['expected_exit'])
if getattr(exit_address,'scope_id',None):raise ValueError('Scoped/link-local exit addresses are not supported')
for k in ('relay_host', 'tls_domain'):
if not re.fullmatch(r'[a-z0-9](?:[a-z0-9.-]*[a-z0-9])?\.[a-z]{2,}', n[k]):
raise ValueError('Invalid DNS name: ' + k)
for k in ('vps_id',):
if not re.fullmatch(r'VPS-[0-9]{3}', n[k]):
raise ValueError('Use the exact CoDocs VPS ID')
identities = {k: n[k] for k in ('key', 'name', 'vps_id', 'node_address', 'tls_domain', 'socks_port')}
identities.update(relay=(n['relay_host'], n['relay_port']), number=(n['country'], n['sequence']))
for k, value in identities.items():
if value in seen[k]:
raise ValueError('Duplicate batch identity: ' + k)
seen[k].add(value)
# The plan carries references, never secret values. Adapters load credentials themselves.
def check(value):
if isinstance(value, dict):
for k, v in value.items():
if re.search(r'password|secret|token|private_key', k, re.I):
raise ValueError('Secret fields are not allowed in a batch plan')
check(v)
elif isinstance(value, list):
for v in value:
check(v)
check(plan)
return plan
@contextlib.contextmanager
def lock(root, name):
path = root / ('lock-' + hashlib.sha256(name.encode()).hexdigest())
with path.open('a+') as f:
os.chmod(path, 0o600)
while True:
try:
fcntl.flock(f, fcntl.LOCK_EX | fcntl.LOCK_NB)
break
except BlockingIOError:
if STOP.wait(.1):
raise RuntimeError('Stopped while waiting for resource lock')
try:
yield
finally:
fcntl.flock(f, fcntl.LOCK_UN)
class Ledger:
def __init__(self, root):
self.root = Path(root).resolve()
if self.root == Path('/'):
raise ValueError('Invalid state root')
self.root.mkdir(parents=True, mode=0o700, exist_ok=True)
os.chmod(self.root, 0o700)
self.path = self.root / 'registry.sqlite3'
with self.db() as c:
c.executescript('''
CREATE TABLE IF NOT EXISTS batches(id TEXT PRIMARY KEY, digest TEXT NOT NULL);
CREATE TABLE IF NOT EXISTS claims(namespace TEXT, kind TEXT, value TEXT,
owner TEXT NOT NULL, PRIMARY KEY(namespace,kind,value));
CREATE TABLE IF NOT EXISTS evidence(batch TEXT,node TEXT,phase TEXT,
dependency TEXT,expires REAL,request TEXT,PRIMARY KEY(batch,node,phase));
CREATE TABLE IF NOT EXISTS phases(batch TEXT, node TEXT, phase TEXT,
status TEXT NOT NULL, attempts INTEGER NOT NULL DEFAULT 0,
updated REAL NOT NULL, PRIMARY KEY(batch,node,phase));
''')
os.chmod(self.path, 0o600)
@contextlib.contextmanager
def db(self):
c = sqlite3.connect(self.path, timeout=30)
try:
c.execute('PRAGMA synchronous=FULL')
with c: yield c
finally: c.close()
def reserve(self, plan):
namespace = plan['context']['panel_vps'] + ':' + plan['context']['app_root']
with self.db() as c:
c.execute('BEGIN IMMEDIATE')
prior = c.execute('SELECT digest FROM batches WHERE id=?', (plan['batch_id'],)).fetchone()
if prior and prior[0] != digest(plan):
raise ValueError('Batch plan changed; resume requires the original exact plan')
for n in plan['nodes']:
owner = digest({'context': plan['context'], 'node': n})
claims = {k: n[k] for k in ('key', 'name', 'vps_id', 'node_address', 'tls_domain')}
claims['relay'] = [n['relay_host'], n['relay_port']]
claims['number'] = [n['country'], n['sequence']]
for kind, value in claims.items():
scope = namespace
if kind == 'relay':
scope = 'relay:' + n['relay_host']
elif kind in ('vps_id', 'node_address', 'tls_domain'):
scope = 'infrastructure'
encoded = json.dumps(value, ensure_ascii=False, sort_keys=True)
existing = c.execute('SELECT owner FROM claims WHERE namespace=? AND kind=? AND value=?',
(scope, kind, encoded)).fetchone()
if existing and existing[0] != owner:
raise ValueError('Another batch reserved identity: ' + kind)
c.execute('INSERT OR IGNORE INTO claims VALUES(?,?,?,?)', (scope, kind, encoded, owner))
# SOCKS listeners are shared by all batches using this gateway.
scope, value = 'gateway:' + plan['context']['gateway_vps'], str(n['socks_port'])
old = c.execute('SELECT owner FROM claims WHERE namespace=? AND kind=? AND value=?',
(scope, 'socks_port', value)).fetchone()
if old and old[0] != owner:
raise ValueError('Another batch reserved the gateway SOCKS port')
c.execute('INSERT OR IGNORE INTO claims VALUES(?,?,?,?)', (scope, 'socks_port', value, owner))
formal_port=plan['context'].get('formal_socks_port')
if formal_port is not None:
if type(formal_port) is not int or not 1024<=formal_port<=65535 or any(n['socks_port']==formal_port for n in plan['nodes']):
raise ValueError('A distinct formal SOCKS port is required')
scope,value='gateway:'+plan['context']['gateway_vps'],str(formal_port)
owner=digest({'context':plan['context'],'formal_port':formal_port})
old=c.execute('SELECT owner FROM claims WHERE namespace=? AND kind=? AND value=?',(scope,'socks_port',value)).fetchone()
if old and old[0]!=owner:raise ValueError('Formal SOCKS port already reserved')
c.execute('INSERT OR IGNORE INTO claims VALUES(?,?,?,?)',(scope,'socks_port',value,owner))
c.execute('INSERT OR IGNORE INTO batches VALUES(?,?)', (plan['batch_id'], digest(plan)))
def state(self, batch, key, phase):
with self.db() as c:
row = c.execute('SELECT status FROM phases WHERE batch=? AND node=? AND phase=?',
(batch, key, phase)).fetchone()
return row[0] if row else 'pending'
def reusable(self, batch, key, phase, dependency, request):
if not dependency or self.state(batch, key, phase) != 'done':
return False
with self.db() as c:
row = c.execute('SELECT dependency,expires,request FROM evidence WHERE batch=? AND node=? AND phase=?', (batch,key,phase)).fetchone()
return bool(row and row[0] == dependency and time.time() <= row[1] <= time.time()+900 and row[2] == request)
def proof(self, batch, key, phase, dependency, expires, request):
with self.db() as c:
c.execute('INSERT OR REPLACE INTO evidence VALUES(?,?,?,?,?,?)',(batch,key,phase,dependency,expires,request))
def mark(self, batch, key, phase, status, attempt=False):
previous=self.state(batch,key,phase)
with self.db() as c:
c.execute('''INSERT INTO phases VALUES(?,?,?,?,?,?) ON CONFLICT(batch,node,phase)
DO UPDATE SET status=excluded.status,attempts=phases.attempts+?,updated=excluded.updated''',
(batch, key, phase, status, int(attempt), time.time(), int(attempt)))
if previous!=status or attempt:
fd=os.open(self.root/'events.jsonl',os.O_CREAT|os.O_WRONLY|os.O_APPEND,0o600)
try:
os.fchmod(fd,0o600)
event=json.dumps({'batch':batch,'node':key,'phase':phase,'status':status,'time':time.time()})+'\n'
os.write(fd,event.encode())
if EVENTS:sys.stdout.write(event);sys.stdout.flush()
finally:os.close(fd)
class Coordinator:
def __init__(self, plan, root, jobs=4, timeout=900):
self.plan = validate(plan)
self.ledger = Ledger(root)
self.jobs = jobs
self.timeout = timeout
self.dependencies = {}
self.runtime = None
self.ledger.reserve(plan)
self.dir = self.ledger.root / plan['batch_id']
self.dir.mkdir(mode=0o700, exist_ok=True)
self.plan_file = self.dir / 'plan.json'
atomic_json(self.plan_file, plan)
if plan.get('runtime'):
self.check_runtime()
directory = str(Path(__file__).resolve().parent)
if directory not in sys.path: sys.path.insert(0, directory)
from site_adapter import SiteAdapter
self.runtime = SiteAdapter(plan, self.dir, atomic_writer=atomic_json, resource_lock=lock)
def check_runtime(self):
runtime = self.plan['runtime']
if runtime.get('kind') != 'ssh-site-v1': raise ValueError('Unknown runtime')
if runtime.get('python') != str(Path(sys.executable).resolve()):raise ValueError('Use the frozen runtime interpreter')
import paramiko
if paramiko.__version__ != runtime.get('paramiko_version'):raise ValueError('Runtime dependency version changed')
base = Path(__file__).resolve().parent
required = [base/n for n in ('batch.py','site_adapter.py','ssh_pool.py','acceptance.py')]
required += [Path(self.plan['context'][k]) for k in ('ssh_config','exit_registry')]
files = runtime.get('files', {})
if any(str(f) not in files for f in required): raise ValueError('Runtime source pin missing')
for f, sha in files.items():
if not Path(f).is_absolute() or hashlib.sha256(Path(f).read_bytes()).hexdigest() != sha:
raise ValueError('Runtime code/config changed')
def call(self, n, phase, action):
fingerprint = digest({'context': self.plan['context'], 'node': n})
path = self.dir / (n['key'] + '.json')
atomic_json(path, dict(n, request_sha256=fingerprint))
argv = self.plan['adapter'] + ['--plan', str(self.plan_file), '--node', str(path),
'--phase', phase, '--action', action, '--state-dir', str(self.dir)]
if self.runtime:
self.check_runtime()
r = self.runtime.call(dict(n, request_sha256=fingerprint), phase, action)
if (r.get('key'),r.get('phase'),r.get('request_sha256')) != (n['key'],phase,fingerprint):
raise RuntimeError('Runtime identity mismatch')
if r.get('status') not in ('ready','absent','waiting','unknown','conflict'):
raise RuntimeError('Runtime status invalid')
return r
with subprocess.Popen(argv, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL,
start_new_session=True) as p:
deadline = time.monotonic() + self.timeout
while True:
try:
output, _ = p.communicate(timeout=.2)
break
except subprocess.TimeoutExpired:
if STOP.is_set() or time.monotonic() >= deadline:
os.killpg(p.pid, signal.SIGTERM)
try:
p.communicate(timeout=5)
except subprocess.TimeoutExpired:
os.killpg(p.pid, signal.SIGKILL)
p.communicate()
raise RuntimeError('Adapter interrupted; remote outcome must be probed')
if p.returncode or len(output) > 65536:
raise RuntimeError('Adapter failed; no stdout/stderr persisted')
r = json.loads(output)
if (r.get('key'), r.get('phase'), r.get('request_sha256')) != (n['key'], phase, fingerprint):
raise RuntimeError('Adapter receipt identity mismatch')
if r.get('status') not in ('ready', 'absent', 'waiting', 'unknown', 'conflict'):
raise RuntimeError('Invalid adapter status')
return r
def phase(self, n, phase):
try:
return self._phase(n, phase)
except Exception:
self.ledger.mark(self.plan['batch_id'], n['key'], phase, 'unknown')
return False
def _phase(self, n, phase):
batch, key = self.plan['batch_id'], n['key']
resource = SHARED.get(phase, n['vps_id'])
# Common panel/dns/relay lock names across batches and processes.
namespace = self.plan['context']['panel_vps']
if resource in ('dns', 'relay'):
namespace = 'dpl-external'
with lock(self.ledger.root, namespace + ':' + resource):
dependency = self.dependencies.get(key, {}).get(phase)
request = digest({'plan': self.plan, 'node': n})
# Publish/audit/preflight are always live; unknown or running phases cannot use a cache.
if phase in ('stage','dns','provision','relay','verify') and self.ledger.reusable(batch,key,phase,dependency,request):
if self.runtime: self.check_runtime()
return True
r = self.call(n, phase, 'probe')
if phase == 'preflight' and r['status'] == 'ready':
deps = r.get('resume_dependencies', {})
clean = {k:v for k,v in deps.items() if k in PHASES and isinstance(v,str) and re.fullmatch('[0-9a-f]{64}',v)}
self.dependencies[key] = {k:digest({p:clean.get(p) for p in PHASES[:PHASES.index(k)+1]}) for k in clean}
if r['status'] == 'ready':
if dependency and type(r.get('valid_until')) in (int,float) and time.time() < r['valid_until'] <= time.time()+900:
self.ledger.proof(batch,key,phase,dependency,r['valid_until'],request)
self.ledger.mark(batch, key, phase, 'done')
return True
if r['status'] == 'conflict':
STOP.set()
if phase in ('preflight', 'verify', 'audit') or r['status'] != 'absent' or r.get('retry_safe') is not True:
self.ledger.mark(batch, key, phase, r['status'])
return False
if STOP.is_set():
return False
# Persist intent before a write; never infer success from the command exit code.
self.ledger.mark(batch, key, phase, 'running', attempt=True)
applied = self.call(n, phase, 'apply')
if applied['status'] == 'conflict':
self.ledger.mark(batch, key, phase, 'conflict')
STOP.set()
return False
r = self.call(n, phase, 'probe')
self.ledger.mark(batch, key, phase, 'done' if r['status'] == 'ready' else r['status'])
if r['status'] == 'ready' and dependency and type(r.get('valid_until')) in (int,float) and time.time()<r['valid_until']<=time.time()+900:
self.ledger.proof(batch,key,phase,dependency,r['valid_until'],request)
if r['status'] == 'conflict':
STOP.set()
return r['status'] == 'ready'
def worker(self, n):
try:
with lock(self.ledger.root, 'node:' + self.plan['context']['panel_vps'] + ':' + n['key']):
self.ledger.mark(self.plan['batch_id'], n['key'], 'coordinator', 'running')
# Already finished batches are re-audited; disabled QA need not be re-enabled.
if self.ledger.state(self.plan['batch_id'], n['key'], 'audit') == 'done':
success = self.phase(n, 'audit')
else:
success = True
for phase in PHASES:
if STOP.is_set() or not self.phase(n, phase):
success = False
break
self.ledger.mark(self.plan['batch_id'], n['key'], 'coordinator', 'done' if success else 'waiting')
return success
except Exception:
# Never print adapter payloads, commands, credentials or exception contents.
self.ledger.mark(self.plan['batch_id'], n['key'], 'coordinator', 'unknown')
return False
def run(self):
# Whole-batch barrier: no staging until every candidate passed current preflight.
with concurrent.futures.ThreadPoolExecutor(max_workers=self.jobs) as pool:
def check(n):
try:
return self.phase(n, 'preflight')
except Exception:
self.ledger.mark(self.plan['batch_id'], n['key'], 'preflight', 'unknown')
return False
checks = list(pool.map(check, self.plan['nodes']))
if not all(checks):
return False
return all(list(pool.map(self.worker, self.plan['nodes'])))
def main():
p = argparse.ArgumentParser(description=__doc__)
p.add_argument('command', choices=('plan', 'run', 'status'))
p.add_argument('--plan', required=True)
p.add_argument('--state-root', required=True)
p.add_argument('--jobs', type=int, default=4)
p.add_argument('--timeout', type=int, default=900)
p.add_argument('--events', action='store_true', help='Emit token-free phase transition JSON lines; final result is last line')
p.add_argument('--execute', action='store_true', help='Required for a run that may write remotely')
a = p.parse_args()
global EVENTS
EVENTS = a.events
os.umask(0o077)
if not 1 <= a.jobs <= 16 or not 1 <= a.timeout <= 3600:
p.error('jobs must be 1..16; timeout 1..3600')
try:
plan = validate(read_json(a.plan))
if a.command == 'plan':
print(json.dumps({'batch_id': plan['batch_id'], 'nodes': len(plan['nodes']),
'plan_sha256': digest(plan), 'writes': False}))
return 0
if a.command == 'run' and not a.execute:
p.error('run requires --execute; plan does not perform remote requests')
if a.command == 'status':
path = Path(a.state_root).resolve() / 'registry.sqlite3'
rows = {}
if path.exists():
with sqlite3.connect(path.as_uri() + '?mode=ro', uri=True) as c:
prior = c.execute('SELECT digest FROM batches WHERE id=?', (plan['batch_id'],)).fetchone()
if prior and prior[0] != digest(plan):
raise ValueError('Batch plan differs from its reserved plan')
rows = {(key, phase): status for key, phase, status in c.execute(
'SELECT node,phase,status FROM phases WHERE batch=?', (plan['batch_id'],))}
print(json.dumps({n['key']: {phase: rows.get((n['key'], phase), 'pending')
for phase in ('preflight',) + PHASES + ('coordinator',)}
for n in plan['nodes']}))
return 0
runner = Coordinator(plan, a.state_root, a.jobs, a.timeout)
for sig in (signal.SIGINT, signal.SIGTERM):
signal.signal(sig, lambda *_: STOP.set())
try:
success = runner.run()
finally:
if runner.runtime:
try:runner.runtime.close()
except Exception:
for node in plan['nodes']:runner.ledger.mark(plan['batch_id'],node['key'],'coordinator','unknown')
raise
print(json.dumps({'batch_id': plan['batch_id'], 'complete': success,
'next': None if success else 'Inspect status, resolve waiting/conflict, rerun the exact plan'}))
return 0 if success else 2
except Exception as exc:
# Validation errors have no adapter/credential material.
print(json.dumps({'error': str(exc) if isinstance(exc, ValueError) else 'Coordinator failed; inspect protected state'}))
return 2
if __name__ == '__main__':
sys.exit(main())
+60
View File
@@ -0,0 +1,60 @@
#!/usr/bin/env python3
"""Build a versioned flat operations bundle from committed files, without touching the worktree/index."""
import argparse
import hashlib
import json
import os
from pathlib import Path
import re
import subprocess
import tempfile
FILES=('stage.php','promote.php','operations.php','rollback.php','readiness.php',
'verify-node.py','panel-acceptance.php','install-node.sh','renew-node.sh','dpl-node.service')
def build(repo,source,base,branch,bundle,advance=False):
if not all(re.fullmatch('[0-9a-f]{40}',r) for r in (source,base)) or not re.fullmatch('codex/[A-Za-z0-9_/-]+',branch) or '..' in branch:
raise ValueError('Explicit full commits and a new codex branch required')
destination=Path(bundle)
if not destination.is_absolute() or destination.exists() or destination.is_symlink():raise ValueError('New absolute bundle path required')
def git(*args,input=None,env=None):
r=subprocess.run(['git','-C',str(repo),*args],input=input,stdout=subprocess.PIPE,stderr=subprocess.DEVNULL,env=env)
if r.returncode:raise ValueError('Git source/base/ref check failed')
return r.stdout
git('cat-file','-e',source+'^{commit}');git('cat-file','-e',base+'^{commit}');git('check-ref-format','refs/heads/'+branch)
exists=subprocess.run(['git','-C',str(repo),'show-ref','--verify','--quiet','refs/heads/'+branch]).returncode
expected_old='0'*40
if exists==0 and advance:
expected_old=git('rev-parse','refs/heads/'+branch).decode().strip()
if expected_old!=base:raise ValueError('Advance requires the exact current branch head as reviewed base')
elif exists!=1:raise ValueError('Branch exists or outcome unknown; inspect it, do not overwrite')
with tempfile.TemporaryDirectory(prefix='dpl-ops-index-',dir=destination.parent) as temp:
env=dict(os.environ,GIT_INDEX_FILE=str(Path(temp)/'index'))
git('read-tree',base,env=env)
for name in FILES:
entry=git('ls-tree',source,'--','scripts/node-onboarding/'+name).decode().strip()
if not entry:raise ValueError('Required committed operations file missing')
mode,kind,rest=entry.split(' ',2);sha,_=rest.split('\t',1)
if kind!='blob' or mode not in ('100644','100755'):raise ValueError('Regular committed operations file required')
git('update-index','--add','--cacheinfo',mode+','+sha+','+name,env=env)
tree=git('write-tree',env=env).decode().strip()
commit=git('commit-tree',tree,'-p',base,input=('DPL operations snapshot\n\nSource commit: '+source+'\n').encode()).decode().strip()
git('update-ref','refs/heads/'+branch,commit,expected_old)
git('bundle','create',str(destination),'refs/heads/'+branch)
destination.chmod(0o600)
return {'commit':commit,'source_commit':source,'branch':branch,'bundle_sha256':hashlib.sha256(destination.read_bytes()).hexdigest(),'files':len(FILES),'network':False}
def main():
p=argparse.ArgumentParser(description=__doc__)
p.add_argument('--repo',default=str(Path(__file__).resolve().parents[2]))
for k in ('source','base','branch','bundle'):p.add_argument('--'+k,required=True)
p.add_argument('--advance',action='store_true',help='Explicit fast-forward only from the exact --base current branch head')
a=p.parse_args()
try:
print(json.dumps(build(a.repo,a.source,a.base,a.branch,a.bundle,a.advance)));return 0
except Exception:
print(json.dumps({'state':'blocked','reason':'Inspect source/base, branch and bundle outcome before retry; no network performed'}));return 2
if __name__=='__main__':raise SystemExit(main())
@@ -0,0 +1,66 @@
#!/usr/bin/env python3
"""Run reviewed, pinned site-specific commands for batch.py without a shell.
Missing integration is a waiting gate, never an assumed successful operation.
Handlers receive paths to the frozen request, not passwords on the command line.
"""
import argparse
import hashlib
import json
from pathlib import Path
import subprocess
import sys
def main():
p = argparse.ArgumentParser(description=__doc__)
for field in ('plan', 'node', 'phase', 'action', 'state-dir'):
p.add_argument('--' + field, required=True)
a = p.parse_args()
node = json.loads(Path(a.node).read_text())
plan = json.loads(Path(a.plan).read_text())
identity = {'key': node['key'], 'phase': a.phase, 'request_sha256': node['request_sha256']}
try:
profile = plan['command_profile']
# Every runnable local script/config must be pinned; pinning the interpreter
# alone does not pin scripts, remote code or the commands' dependencies.
files = profile['files']
if not files:
raise ValueError('No pinned handler files')
for filename, expected in files.items():
if not Path(filename).is_absolute():
raise ValueError('Absolute handler paths required')
if hashlib.sha256(Path(filename).read_bytes()).hexdigest() != expected:
raise ValueError('Handler changed')
command = profile['phases'].get(a.phase, {}).get(a.action)
if command is None:
result = dict(identity, status='waiting', reason='handler_not_configured')
else:
if not isinstance(command, list) or not command or not all(isinstance(x, str) for x in command):
raise ValueError('Command must be argv')
values = dict(plan=a.plan, node=a.node, state_dir=a.state_dir,
key=node['key'], phase=a.phase, action=a.action)
argv = [x.format_map(values) for x in command]
if not Path(argv[0]).is_absolute():
raise ValueError('Absolute executable required')
completed = subprocess.run(argv, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL)
if completed.returncode or len(completed.stdout) > 65536:
raise ValueError('Handler failed')
result = json.loads(completed.stdout)
if any(result.get(k) != v for k, v in identity.items()):
raise ValueError('Wrong handler receipt')
if result.get('status') not in ('ready', 'absent', 'waiting', 'unknown', 'conflict'):
raise ValueError('Wrong handler status')
# Only structured nonsecret receipt fields are allowed through to the runner.
safe = {**identity, 'status': result['status']}
if result.get('retry_safe') is True:
safe['retry_safe'] = True
print(json.dumps(safe))
return 0
except Exception:
print(json.dumps(dict(identity, status='unknown')))
return 2
if __name__ == '__main__':
sys.exit(main())
+46
View File
@@ -0,0 +1,46 @@
#!/usr/bin/env python3
"""Freeze a reusable SSH-site plan locally. No network, credentials or ledger writes."""
import argparse
import hashlib
import json
import importlib
import sys
from pathlib import Path
from batch import validate,atomic_json
from site_adapter import SiteAdapter
def configure(plan,site):
allowed={'ops_root','node_root','batch_backup_root','node_backup_root','qa_root','provider_snapshot','exit_registry','ssh_config','preserved_service','preserved_service_overrides','formal_socks_port','gateway_containers','client_sha256','acceptance_impact'}
if set(site)-allowed:raise ValueError('Unexpected site configuration fields')
library=importlib.import_module('paramiko')
if library.__version__!='5.0.0':raise ValueError('Use the reviewed Paramiko 5.0.0 environment')
plan=dict(plan,context={**plan['context'],**site})
validate(plan)
adapter=SiteAdapter(plan,Path('/private/tmp/dpl-validation-only')) # Creates no directory or connections.
adapter.pool.close()
base=Path(__file__).resolve().parent
plan.pop('command_profile',None)
plan['adapter']=[str(Path(sys.executable).resolve()),str(base/'command-adapter.py')]
paths=[base/x for x in ('batch.py','site_adapter.py','ssh_pool.py','acceptance.py')]+[Path(site[k]) for k in ('ssh_config','exit_registry')]
if any(h.get('credential_format')=='gemdocs-resource' for h in adapter.pool.config['hosts'].values()):
paths += [Path('/Users/hellcat/Documents/GemDocs/AI版/tools')/name for name in ('credentials.py','resources.py')]
plan['runtime']={'kind':'ssh-site-v1','python':str(Path(sys.executable).resolve()),'paramiko_version':library.__version__,'files':{str(p):hashlib.sha256(p.read_bytes()).hexdigest() for p in paths}}
return plan
def main():
p=argparse.ArgumentParser(description=__doc__)
for k in ('plan','site','output'):p.add_argument('--'+k,required=True)
a=p.parse_args()
try:
output=Path(a.output)
if not output.is_absolute() or output.exists() or output.is_symlink():raise ValueError('New absolute output file required; never mutate a frozen plan')
plan=configure(json.loads(Path(a.plan).read_text()),json.loads(Path(a.site).read_text()))
atomic_json(output,plan)
print(json.dumps({'state':'configured','nodes':len(plan['nodes']),'network':False,'ledger_writes':False}))
return 0
except Exception:
print(json.dumps({'state':'blocked','reason':'Inspect explicit site paths, registry and plan; no network performed'}));return 2
if __name__=='__main__':raise SystemExit(main())
@@ -0,0 +1,7 @@
[Unit]
Requires=dpl-certbot-apparmor.service
After=dpl-certbot-apparmor.service
[Service]
# Recheck generated profiles after a snap refresh, before the existing renewal command.
ExecStartPre=/bin/bash /opt/dpl-certbot-security/provision/load-certbot-apparmor.sh --load
@@ -0,0 +1,14 @@
[Unit]
Description=Load existing Certbot AppArmor profiles for DPL certificate operations
After=local-fs.target
RequiresMountsFor=/snap/core/current /snap/certbot/current /var/lib/snapd/apparmor/profiles
Before=snap.certbot.renew.service
ConditionPathExists=/var/lib/snapd/apparmor/profiles/snap.certbot.certbot
[Service]
Type=oneshot
ExecStart=/bin/bash /opt/dpl-certbot-security/provision/load-certbot-apparmor.sh --load
RemainAfterExit=yes
[Install]
WantedBy=multi-user.target
@@ -0,0 +1,30 @@
#!/bin/bash
set -euo pipefail
# Restore only profiles already generated by the installed Certbot/core snaps.
# This does not enable the global AppArmor service or change profile modes.
[[ $(id -u) == 0 ]] || exit 1
mode=${1:---load}
[[ $# -le 1 && ( $mode == --load || $mode == --check ) ]] || exit 2
[[ $(cat /sys/module/apparmor/parameters/enabled) == Y ]] || exit 3
directory=/var/lib/snapd/apparmor/profiles
[[ -d $directory && ! -L $directory && $(stat -c %u "$directory") == 0 ]] || exit 4
[[ -z $(find "$directory" -maxdepth 0 -perm /022 -print) ]] || exit 4
[[ -f $directory/snap.certbot.certbot && -f $directory/snap.certbot.renew ]] || exit 5
shopt -s nullglob
core=$(readlink -f /snap/core/current)
[[ $core =~ ^/(var/lib/snapd/)?snap/core/([0-9]+)$ ]] || exit 5
revision=${BASH_REMATCH[2]}
profiles=("$directory"/snap.certbot.* "$directory"/snap-update-ns.certbot "$directory/snap-confine.core.$revision")
(( ${#profiles[@]} >= 4 )) || exit 5
# Validate every input before loading any profile. Never use complain/disable flags.
for profile in "${profiles[@]}"; do
[[ -f $profile && ! -L $profile && $(stat -c %u "$profile") == 0 ]] || exit 6
[[ -z $(find "$profile" -maxdepth 0 -perm /022 -print) ]] || exit 6
/usr/sbin/apparmor_parser --skip-kernel-load --skip-cache "$profile"
done
if [[ $mode == --load ]]; then
for profile in "${profiles[@]}"; do
/usr/sbin/apparmor_parser --replace --skip-cache "$profile"
done
fi
printf 'Certbot/core profiles checked: %s; mode: %s\n' "${#profiles[@]}" "$mode"
+332
View File
@@ -0,0 +1,332 @@
<?php
/** Shared CLI helpers; loading this file does not bootstrap Laravel or open a connection. */
namespace DplOnboarding;
use App\Models\{Server, ServerGroup, User, Plan, Setting};
use Illuminate\Support\Facades\{DB, Cache};
use RuntimeException;
function ids(string $value): array
{
if (!preg_match('/^[1-9][0-9]*(,[1-9][0-9]*)*$/D', $value)) {
throw new RuntimeException('Expected explicit comma-separated positive IDs');
}
$ids = array_map('intval', explode(',', $value));
if (count($ids) !== count(array_unique($ids))) throw new RuntimeException('Duplicate IDs');
return $ids;
}
function readJson(string $path): array
{
if (!is_file($path) || is_link($path)) throw new RuntimeException('Required regular journal/manifest missing');
$data = json_decode(file_get_contents($path), true, flags: JSON_THROW_ON_ERROR);
if (!is_array($data)) throw new RuntimeException('Invalid JSON document');
return $data;
}
function writeJson(string $path, array $data): void
{
if (is_link($path)) throw new RuntimeException('Refusing journal symlink');
$tmp = tempnam(dirname($path), '.onboarding-');
if ($tmp === false) throw new RuntimeException('Cannot create journal');
try {
chmod($tmp, 0600);
$body = json_encode($data, JSON_THROW_ON_ERROR | JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE) . "\n";
if (file_put_contents($tmp, $body) !== strlen($body) || !rename($tmp, $path)) {
throw new RuntimeException('Cannot persist journal');
}
} finally {
if (is_file($tmp)) unlink($tmp);
}
}
function manifest(string $dir): array
{
$m = readJson($dir . '/manifest.json');
foreach (['node_id','machine_id','group_id','test_user_id'] as $field) {
if (!isset($m[$field]) || !preg_match('/^[1-9][0-9]*$/D', (string)$m[$field])) {
throw new RuntimeException('Manifest missing positive object ID');
}
$m[$field] = (int)$m[$field];
}
if (!isset($m['key']) || !preg_match('/^[a-z0-9-]+$/D', $m['key'])) throw new RuntimeException('Invalid manifest key');
return $m;
}
function locked(string $dir, callable $fn): mixed
{
if (!is_dir($dir) || is_link($dir) || (fileperms($dir)&0077)!==0) throw new RuntimeException('Existing private backup directory required');
$path = $dir . '/operation.lock';
if (is_link($path)) throw new RuntimeException('Refusing lock symlink');
$h = fopen($path, 'c');
if ($h === false) throw new RuntimeException('Cannot open operation lock');
chmod($path, 0600);
try {
if (!flock($h, LOCK_EX | LOCK_NB)) throw new RuntimeException('Another operation is active');
return $fn();
} finally { flock($h, LOCK_UN); fclose($h); }
}
function boot(): void
{
require getcwd() . '/vendor/autoload.php';
$app = require getcwd() . '/bootstrap/app.php';
$app->make(\Illuminate\Contracts\Console\Kernel::class)->bootstrap();
}
final class PanelChange
{
private const MODELS = ['node'=>Server::class,'qa'=>User::class,'user'=>User::class,
'plan'=>Plan::class,'group'=>ServerGroup::class,'setting'=>Setting::class];
private const FIELDS = ['node'=>['group_ids'],'qa'=>['banned'],'user'=>['group_id'],
'plan'=>['group_id'],'group'=>['name'],'setting'=>['value']];
private static function normalize(string $field, mixed $value): mixed
{
return match ($field) {
'group_ids' => array_map('strval', $value ?? []),
'group_id' => $value === null ? null : (int)$value,
'banned','enabled','show' => (bool)$value,
default => $value,
};
}
private static function object(string $kind, int|string $id): mixed
{
$class = self::MODELS[$kind] ?? throw new RuntimeException('Unsupported journal object');
return $class::where($kind === 'setting' ? 'name' : 'id', $id)->lockForUpdate()->first();
}
private static function value(mixed $model, string $field): mixed
{
return $model === null ? null : self::normalize($field, $model->getAttribute($field));
}
private static function operation(string $kind, mixed $model, string $field, mixed $after, int|string|null $id = null): ?array
{
if (!in_array($field, self::FIELDS[$kind] ?? [], true)) throw new RuntimeException('Unsupported journal field');
$before = self::value($model, $field);
$after = self::normalize($field, $after);
if ($model !== null && $before === $after) return null;
return ['kind'=>$kind,'id'=>$id ?? $model->getKey(),'field'=>$field,
'before_exists'=>$model !== null,'before'=>$before,'after'=>$after];
}
private static function context(array $m): array
{
$node = self::object('node', $m['node_id']) ?? throw new RuntimeException('Manifest node missing');
$qa = self::object('qa', $m['test_user_id']) ?? throw new RuntimeException('Manifest QA missing');
if ((int)$node->machine_id !== $m['machine_id'] || $node->type !== 'anytls') {
throw new RuntimeException('Manifest node/machine mismatch');
}
if ($qa->is_admin || (int)$qa->group_id !== $m['group_id'] ||
!str_starts_with($qa->email, 'node-qa-' . $m['key'] . '-') ||
!str_ends_with($qa->email, '@example.invalid')) {
throw new RuntimeException('Manifest does not identify an isolated QA user');
}
return [$node, $qa];
}
private static function checkJournal(array $j, array $m): void
{
if (($j['version'] ?? null) !== 1 || ($j['manifest'] ?? null) !== $m || !is_array($j['operations'] ?? null)) {
throw new RuntimeException('Journal/manifest mismatch or unsupported version');
}
foreach ($j['operations'] as $op) {
if (!in_array($op['field'], self::FIELDS[$op['kind']] ?? [], true)) throw new RuntimeException('Invalid journal operation');
if ($op['kind']==='node' && $op['id']!==$m['node_id']) throw new RuntimeException('Wrong node in journal');
if ($op['kind']==='qa' && $op['id']!==$m['test_user_id']) throw new RuntimeException('Wrong QA in journal');
if ($op['kind']==='setting' && $op['id']!=='subscribe_url') throw new RuntimeException('Wrong setting in journal');
if ($j['request']['mode']==='append' && !in_array($op['kind'], ['node','qa'], true)) {
throw new RuntimeException('Append journal contains shared-resource writes');
}
}
}
private static function current(array $op): array
{
$model = self::object($op['kind'], $op['id']);
return [$model, $model !== null, self::value($model, $op['field'])];
}
private static function applyOperation(array $op): void
{
[$model, $exists, $value] = self::current($op);
if ($exists !== $op['before_exists'] || $value !== $op['before']) throw new RuntimeException('Object changed before application');
if (!$exists) {
if ($op['kind'] !== 'setting') throw new RuntimeException('Missing target');
$model = new Setting(['name'=>$op['id']]);
}
$model->setAttribute($op['field'], $op['after']);
// Keep model observers for node full-sync notifications; QA does not send notifications.
$op['kind'] === 'qa' ? $model->saveQuietly() : $model->save();
}
private static function flushSettings(array $ops): void
{
if (array_filter($ops, fn($op) => $op['kind']==='setting')) {
// Called after commit; clearing request-local state also makes retry recovery safe.
Cache::store('redis')->forget(\App\Support\Setting::CACHE_KEY);
app()->forgetInstance(\App\Support\Setting::class);
}
}
private static function notifyCommitted(array $m): void
{
// Explicitly repeat idempotent invalidations after commit. If an observer's
// after-commit callback failed, prepared+after recovery must still notify.
\App\Services\NodeSyncService::notifyFullSync($m['node_id']);
\App\Services\NodeSyncService::notifyMachineNodesChanged($m['machine_id']);
}
private static function verifyEvidence(array $request, array $m, mixed $node): void
{
$report = readJson($request['verification'] ?? throw new RuntimeException('Missing --verification live QA report'));
$at = $report['verified_at'] ?? 0;
if (($report['state'] ?? '') !== 'live_verified' || ($report['qa_user_id'] ?? null) !== $m['test_user_id'] ||
!is_int($at) || $at > time() || time()-$at > 900) {
throw new RuntimeException('Recent live verification for this manifest QA required');
}
$sni = $node->protocol_settings['tls']['server_name'] ?? null;
$targets = array_filter($report['results'] ?? [], fn($row) =>
($row['live'] ?? false) === true && ($row['strict_tls'] ?? false) === true &&
($row['relay'] ?? null) === $node->host && (int)($row['relay_port'] ?? 0) === (int)$node->port &&
($row['sni'] ?? null) === $sni);
if (count($targets)!==1) throw new RuntimeException('Live evidence endpoint/SNI mismatch');
}
public static function promote(string $dir, array $request, bool $apply): array
{
$mode = $request['mode'] ?? '';
if (!in_array($mode, ['append','initialize'], true)) throw new RuntimeException('Explicit append/initialize mode required');
$request['group'] = isset($request['group']) ? (int)$request['group'] : null;
if ($mode==='append' && (!$request['group'] || isset($request['plans']) || isset($request['subscribe-url']) || isset($request['group-name']))) {
throw new RuntimeException('Append requires group and forbids plans, subscribe-url and group-name');
}
if ($mode==='initialize') {
$request['plan_ids'] = ids($request['plans'] ?? '');
$url = $request['subscribe-url'] ?? '';
$parts = parse_url($url);
if (!is_array($parts) || ($parts['scheme'] ?? '')!=='https' || empty($parts['host']) || isset($parts['user']) || isset($parts['pass']) || isset($parts['query']) || isset($parts['fragment'])) {
throw new RuntimeException('Initialize requires an explicit HTTPS subscribe-url without credentials/query');
}
}
ksort($request);
$m = manifest($dir); $path = $dir . '/promotion-journal.json';
$result = DB::transaction(function () use ($dir,$request,$mode,$m,$path,$apply) {
[$node,$qa] = self::context($m);
if (is_file($path)) {
$j = readJson($path); self::checkJournal($j,$m);
if ($j['request'] !== $request) throw new RuntimeException('Existing operation has different parameters');
if (is_file($dir.'/rollback-journal.json')) throw new RuntimeException('Rollback started; use a new reviewed task');
$before = $after = true;
foreach ($j['operations'] as $op) {
[, $exists,$value] = self::current($op);
$before = $before && $exists===$op['before_exists'] && $value===$op['before'];
$after = $after && $exists && $value===$op['after'];
}
if (!$after && (!$before || $j['state']!=='prepared')) throw new RuntimeException('Journal conflict; inspect before retrying');
if (!$apply) return ['state'=>$after?'already_applied':'preview','journal'=>$j];
if (!$after) {
self::verifyEvidence($request,$m,$node);
if (!$node->is_online || (int)$qa->u+(int)$qa->d<=0 || $qa->banned) throw new RuntimeException('QA evidence no longer ready');
foreach ($j['operations'] as $op) self::applyOperation($op);
}
return ['state'=>'applied','journal'=>$j];
}
if (is_file($dir.'/promoted.json')) throw new RuntimeException('Legacy promotion exists without new journal; do not adopt automatically');
if (!$node->enabled || !$node->show || !$node->is_online || (int)$qa->u + (int)$qa->d <= 0 || $qa->banned) throw new RuntimeException('Fresh online/active QA traffic evidence missing');
if (self::value($node,'group_ids') !== [(string)$m['group_id']]) throw new RuntimeException('Node no longer in its isolated stage group');
$groupId = $request['group'] ?? $m['group_id'];
$group = self::object('group',$groupId) ?? throw new RuntimeException('Target group missing');
if ($mode==='append' && $groupId===$m['group_id']) throw new RuntimeException('Append requires an existing formal group');
$ops = [self::operation('node',$node,'group_ids',[(string)$groupId]), self::operation('qa',$qa,'banned',true)];
if ($mode==='initialize') {
$plans = Plan::whereIn('id',$request['plan_ids'])->orderBy('id')->lockForUpdate()->get();
if ($plans->count()!==count($request['plan_ids'])) throw new RuntimeException('Plan IDs do not all exist');
foreach ($plans as $plan) {
if ($plan->group_id !== null && (int)$plan->group_id!==$groupId) throw new RuntimeException('Plan belongs to another group');
$ops[] = self::operation('plan',$plan,'group_id',$groupId);
}
// Only the explicitly selected plans' unassigned users can change in initialize mode.
foreach (User::whereIn('plan_id',$request['plan_ids'])->whereNull('group_id')->orderBy('id')->lockForUpdate()->get() as $user) {
$ops[] = self::operation('user',$user,'group_id',$groupId);
}
if (isset($request['group-name'])) $ops[] = self::operation('group',$group,'name',$request['group-name']);
$setting = self::object('setting','subscribe_url');
$ops[] = self::operation('setting',$setting,'value',$request['subscribe-url'],'subscribe_url');
}
if ($apply) self::verifyEvidence($request,$m,$node);
$j = ['version'=>1,'state'=>'prepared','manifest'=>$m,'request'=>$request,
'operations'=>array_values(array_filter($ops)),
'node_guard'=>['enabled'=>(bool)$node->enabled,'show'=>(bool)$node->show]];
if (!$apply) return ['state'=>'preview','journal'=>$j];
writeJson($path,$j); // Durable intent before any DB write; recover prepared+after on retry.
foreach ($j['operations'] as $op) self::applyOperation($op);
return ['state'=>'applied','journal'=>$j];
},1);
if ($apply) {
self::flushSettings($result['journal']['operations']);
self::notifyCommitted($m);
$result['journal']['state']='applied'; writeJson($path,$result['journal']);
}
return $result;
}
public static function rollback(string $dir, bool $apply): array
{
$m = manifest($dir); $j = readJson($dir.'/promotion-journal.json'); self::checkJournal($j,$m);
$rollbackPath=$dir.'/rollback-journal.json';
$result=DB::transaction(function () use ($m,$j,$apply,$rollbackPath) {
[$node,$qa]=self::context($m);
if (!$qa->banned) throw new RuntimeException('QA must remain disabled during rollback');
if (is_file($rollbackPath)) {
$r=readJson($rollbackPath);
if (($r['promotion']??null)!==$j) throw new RuntimeException('Rollback journal mismatch');
} else {
// Rollback itself has a durable before/after journal, including node containment.
$undo=[];
foreach (array_reverse($j['operations']) as $op) {
if ($op['kind']==='qa') continue; // Never reactivate test users.
[$model,$exists,$value]=self::current($op);
if (!$exists || $value!==$op['after']) throw new RuntimeException('Rollback conflict: current value differs from recorded after');
$undo[]=['kind'=>$op['kind'],'id'=>$op['id'],'field'=>$op['field'],
'before_exists'=>true,'before'=>$op['after'],'after'=>$op['before'],
'delete'=>!$op['before_exists']];
}
foreach (['enabled','show'] as $field) {
if ((bool)$node->$field!==$j['node_guard'][$field]) throw new RuntimeException('Node containment field changed after promotion');
if ($node->$field) $undo[]=['kind'=>'node','id'=>$m['node_id'],'field'=>$field,
'before_exists'=>true,'before'=>true,'after'=>false,'delete'=>false];
}
if (!$qa->banned) throw new RuntimeException('QA reactivated after promotion; resolve conflict before rollback');
$r=['version'=>1,'state'=>'prepared','promotion'=>$j,'operations'=>$undo];
}
$before=$after=true;
foreach ($r['operations'] as $op) {
// Only rollback containment adds these two node fields.
if (!in_array($op['field'],self::FIELDS[$op['kind']]??[],true) && !($op['kind']==='node' && $op['id']===$m['node_id'] && in_array($op['field'],['enabled','show'],true))) {
throw new RuntimeException('Invalid rollback field');
}
[, $exists,$value]=self::current($op);
$before=$before && $exists && $value===$op['before'];
$after=$after && ($op['delete'] ? !$exists : ($exists && $value===$op['after']));
}
if (!$after && (!$before || $r['state']!=='prepared')) throw new RuntimeException('Rollback conflicts; no objects restored');
if (!$apply) return ['state'=>$after?'already_rolled_back':'preview','journal'=>$r];
if (!is_file($rollbackPath)) writeJson($rollbackPath,$r);
if (!$after) foreach ($r['operations'] as $op) {
[$model]=self::current($op);
if ($op['delete']) $model->delete();
else { $model->setAttribute($op['field'],$op['after']); $model->save(); }
}
return ['state'=>'rolled_back','journal'=>$r];
},1);
if ($apply) {
self::flushSettings($j['operations']);
self::notifyCommitted($m);
$result['journal']['state']='rolled_back';writeJson($rollbackPath,$result['journal']);
}
return $result;
}
}
@@ -0,0 +1,100 @@
<?php
/** On-demand batch acceptance lease. No bootstrap occurs when included by tests. */
namespace DplOnboarding;
require_once __DIR__.'/operations.php';
use App\Models\{User,Server,ServerGroup};
use App\Services\ServerService;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use RuntimeException;
final class Acceptance {
public static function eligible(User $u,int $group): bool {
return !$u->banned && (int)$u->group_id===$group && (int)$u->u+(int)$u->d<(int)$u->transfer_enable && ($u->expired_at===null || (int)$u->expired_at>=time());
}
public static function prepare(string $dir,int $group,bool $apply): array {
return locked($dir,function()use($dir,$group,$apply){
if(!ServerGroup::find($group))throw new RuntimeException('Formal group missing');
$path=$dir.'/acceptance-user.json';
if(is_file($path) && readJson($path)['state']==='closed' && $apply){
$old=readJson($path);$prior=isset($old['id'])?User::find($old['id']):null;
if($old['owned'] && $prior && (!$prior->banned || $prior->email!==$old['email'] || $prior->uuid!==$old['uuid'] || $prior->token!==$old['token'] || $prior->is_admin || (int)$prior->group_id!==$old['group']))throw new RuntimeException('Prior lease not revoked');
writeJson($dir.'/acceptance-closed-'.($old['id']??'absent').'.json',$old);unlink($path);
}
if(is_file($path)){
$j=readJson($path);
if($j['group']!==$group || $j['state']==='closed')throw new RuntimeException('Lease closed or parameters changed; never reactivate');
$u=User::where('email',$j['email'])->first();
if(!$u && $j['owned'] && $j['state']==='prepared' && $apply){
$u=DB::transaction(fn()=>self::create($j),1);
}
if(!$u || $u->uuid!==$j['uuid'] || $u->token!==$j['token'] || !self::eligible($u,$group) || ($j['owned'] && $u->is_admin))throw new RuntimeException('Acceptance lease drifted');
if($j['owned'])self::limits($u,$j);
$j['id']=$u->id;$j['state']='active';if($apply)writeJson($path,$j);
return ['state'=>'ready','id'=>$u->id,'owned'=>$j['owned']];
}
$u=null;
$candidates=User::where('group_id',$group)->where('banned',0)->whereRaw('u+d<transfer_enable')->where(fn($q)=>$q->whereNull('expired_at')->orWhere('expired_at','>=',time()))->where('email','not like','node-qa-%')->where('email','not like','batch-acceptance-%')->orderByDesc('is_admin')->orderBy('id')->limit(20)->get();
foreach($candidates as $candidate){
$effective=true;
foreach(ServerService::getAvailableServers($candidate) as $s)if(!ServerService::getAvailableUsers(Server::findOrFail($s['id']))->contains('id',$candidate->id)){$effective=false;break;}
if($effective){$u=$candidate;break;}
}
if(!$apply)return ['state'=>$u?'existing':'would_create'];
$j=['group'=>$group,'state'=>'prepared','owned'=>!$u,'email'=>$u?->email??'batch-acceptance-'.substr(hash('sha256',$dir),0,12).'-'.Str::lower(Str::random(8)).'@example.invalid','uuid'=>$u?->uuid??(string)Str::uuid(),'token'=>$u?->token??Str::random(32),'quota'=>104857600,'expires_at'=>time()+3600];
// Persist identity before commit. A lost response resumes the same row, never another user.
if(!$u && User::where('email',$j['email'])->exists())throw new RuntimeException('Unowned acceptance email conflict');
writeJson($path,$j);
if(!$u)$u=DB::transaction(fn()=>self::create($j),1);
$j['id']=$u->id;$j['state']='active';writeJson($path,$j);
return ['state'=>'ready','id'=>$u->id,'owned'=>$j['owned']];
});
}
private static function limits(User $u,array $j):void {
if((int)$u->transfer_enable!==$j['quota'] || (int)$u->expired_at!==$j['expires_at'] || (int)$u->device_limit!==1)throw new RuntimeException('Owned lease limits changed; inspect before mutation');
}
private static function create(array $j): User {
$u=new User(['email'=>$j['email'],'uuid'=>$j['uuid'],'token'=>$j['token'],'password'=>password_hash(Str::random(40),PASSWORD_BCRYPT),'group_id'=>$j['group'],'transfer_enable'=>$j['quota'],'expired_at'=>$j['expires_at'],'banned'=>0,'is_admin'=>0,'remind_expire'=>0,'remind_traffic'=>0,'device_limit'=>1]);$u->saveQuietly();return $u;
}
public static function source(string $dir,int $group,bool $inspect=false): array {
$j=readJson($dir.'/acceptance-user.json');$u=User::findOrFail($j['id']);
if($j['group']!==$group || (!$inspect && $j['state']!=='active') || $u->uuid!==$j['uuid'] || $u->token!==$j['token'] || (!$inspect && !self::eligible($u,$group)) || ($inspect && !$j['owned'] && !self::eligible($u,$group)) || (int)$u->group_id!==$group)throw new RuntimeException('Acceptance user unavailable');
if($j['owned'])self::limits($u,$j);
$nodes=[];
foreach(ServerService::getAvailableServers($u) as $s){
if(isset($s['ports']))throw new RuntimeException('Port-range nodes require an explicit verifier');
$model=Server::findOrFail($s['id']);
if(!$inspect && !ServerService::getAvailableUsers($model)->contains('id',$u->id))throw new RuntimeException('User excluded by effective node filter');
$nodes[]=['id'=>$s['id'],'type'=>$s['type'],'tag'=>$s['name'],'relay'=>$s['host'],'relay_port'=>(int)$s['port'],'sni'=>$s['protocol_settings']['tls']['server_name']??null,'uuid'=>$s['password']];
}
if($inspect){foreach($nodes as &$n)unset($n['uuid']);unset($n);return ['nodes'=>$nodes];}
return ['user_id'=>$u->id,'owned'=>$j['owned'],'token'=>$u->token,'nodes'=>$nodes];
}
public static function cleanup(string $dir,bool $apply): array {
return locked($dir,function()use($dir,$apply){
$p=$dir.'/acceptance-user.json';if(!is_file($p))return ['state'=>'absent'];$j=readJson($p);
$u=isset($j['id'])?User::find($j['id']):User::where('email',$j['email'])->first();
if($j['owned'] && $u){
if($u->email!==$j['email'] || $u->uuid!==$j['uuid'] || $u->token!==$j['token'] || $u->is_admin || (int)$u->group_id!==$j['group'])throw new RuntimeException('Cleanup ownership mismatch');
self::limits($u,$j);
if($apply){$u->banned=true;$u->saveQuietly();}
if($apply && !$u->fresh()->banned)throw new RuntimeException('Cleanup failed');
}
if($apply){$j['state']='closed';$j['id']=$u?->id;writeJson($p,$j);}
return ['state'=>$apply?'closed':'preview','owned'=>$j['owned'],'id'=>$u?->id];
});
}
}
if(realpath($_SERVER['SCRIPT_FILENAME']??'')===__FILE__){
$o=getopt('',['action:','dir:','group:','apply','help']);
if(isset($o['help'])){echo "--action=prepare|source|snapshot|cleanup --dir=PRIVATE_DIR --group=EXISTING_ID [--apply]\n";exit;}
try{
$dir=$o['dir']??'';$group=(int)($o['group']??0);
if(!preg_match('~^/[A-Za-z0-9_./-]+$~D',$dir)||str_contains($dir,'..')||$group<1)throw new RuntimeException('Explicit private directory and group required');
umask(0077);if(!is_dir($dir))mkdir($dir,0700,true);
if(is_link($dir)||(fileperms($dir)&0077))throw new RuntimeException('Private directory required');
boot();$apply=isset($o['apply']);
$r=match($o['action']??''){'prepare'=>Acceptance::prepare($dir,$group,$apply),'source'=>Acceptance::source($dir,$group),'snapshot'=>Acceptance::source($dir,$group,true),'cleanup'=>Acceptance::cleanup($dir,$apply),default=>throw new RuntimeException('Unknown action')};
echo json_encode($r,JSON_THROW_ON_ERROR).PHP_EOL;
}catch(\Throwable $e){fwrite(STDERR,json_encode(['state'=>'blocked','reason'=>'Inspect protected lease and effective authorization; no automatic overwrite']).PHP_EOL);exit(2);}
}
+24 -42
View File
@@ -1,43 +1,25 @@
<?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;
// Default is preview. Apply only in a separately authorized target environment.
require __DIR__ . '/operations.php';
use DplOnboarding\PanelChange;
$opts = getopt('', ['backup:', 'mode:', 'plans:', 'group:', 'subscribe-url:', 'group-name:', 'verification:', 'apply', 'help']);
if (isset($opts['help'])) {
echo "--backup=DIR --mode=append --group=ID [--verification=QA_REPORT --apply]\n";
echo "--backup=DIR --mode=initialize --plans=IDS --subscribe-url=HTTPS_URL [--group=ID] [--group-name=NAME] [--verification=QA_REPORT --apply]\n";
exit;
}
try {
$dir = $opts['backup'] ?? throw new RuntimeException('Missing --backup');
$apply = array_key_exists('apply', $opts);
unset($opts['backup'], $opts['apply']);
if (!isset($opts['mode']) || !in_array($opts['mode'], ['append','initialize'], true)) throw new RuntimeException('Explicit --mode required');
if (isset($opts['group'])) { DplOnboarding\ids($opts['group']); if (str_contains($opts['group'],',')) throw new RuntimeException('One group required'); }
DplOnboarding\boot();
$result = DplOnboarding\locked($dir, fn() => PanelChange::promote($dir, $opts, $apply));
// Journal is field-scoped and contains no passwords/UUIDs/tokens.
echo json_encode($result, JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE) . PHP_EOL;
} catch (Throwable $e) {
$reason=get_class($e)===RuntimeException::class ? $e->getMessage() : "Inspect protected journal/current state";
fwrite(STDERR, "Promotion stopped: " . $reason . "\n");
exit(1);
}
+31 -15
View File
@@ -1,16 +1,32 @@
<?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;
require __DIR__ . '/operations.php';
$opts=getopt('', ['backup:', 'plans:', 'group:', 'help']);
if (isset($opts['help'])) { echo "--backup=DIR [--plans=ID,ID] [--group=ID]; no implicit plan IDs\n"; exit; }
try {
$dir=$opts['backup'] ?? throw new RuntimeException('Missing --backup');
$ids=isset($opts['plans']) ? DplOnboarding\ids($opts['plans']) : [];
$group=null;
if (isset($opts['group'])) {
$groups=DplOnboarding\ids($opts['group']);
if (count($groups)!==1) throw new RuntimeException('One group required');
$group=$groups[0];
}
$m=DplOnboarding\manifest($dir);
DplOnboarding\boot();
$node=App\Models\Server::findOrFail($m['node_id']);
$qa=App\Models\User::findOrFail($m['test_user_id']);
if ((int)$node->machine_id!==$m['machine_id']) throw new RuntimeException('Manifest machine mismatch');
$plans=App\Models\Plan::whereIn('id',$ids)->orderBy('id')->get(['id','group_id']);
if ($plans->count()!==count($ids)) throw new RuntimeException('Some selected plans missing');
if ($group!==null) App\Models\ServerGroup::findOrFail($group);
$result=[
'node_id'=>$node->id, 'name'=>$node->name, 'is_online'=>(bool)$node->is_online,
'last_check_at'=>$node->last_check_at, 'last_push_at'=>$node->last_push_at,
'group_ids'=>$node->group_ids, 'qa_upload'=>(int)$qa->u, 'qa_download'=>(int)$qa->d,
'qa_banned'=>(bool)$qa->banned, 'selected_plan_ids'=>$ids, 'plans'=>$plans->toArray(),
'existing_users_with_selected_plan_and_null_group'=>$ids ? App\Models\User::whereIn('plan_id',$ids)->whereNull('group_id')->count() : null,
'selected_plans_in_other_group'=>$group===null ? null : $plans->filter(fn($p) => $p->group_id!==null && (int)$p->group_id!==$group)->pluck('id')->all(),
'scope'=>'Read-only snapshot; not subscription/traffic/GUI acceptance',
];
echo json_encode($result,JSON_THROW_ON_ERROR|JSON_UNESCAPED_UNICODE).PHP_EOL;
} catch (Throwable $e) { fwrite(STDERR,"Readiness failed; verify parameters and manifest.\n"); exit(1); }
+1
View File
@@ -0,0 +1 @@
paramiko==5.0.0
+16
View File
@@ -0,0 +1,16 @@
<?php
// Field-scoped compare-before-restore. Preview unless explicitly --apply.
require __DIR__ . '/operations.php';
use DplOnboarding\PanelChange;
$opts=getopt('', ['backup:', 'apply', 'help']);
if (isset($opts['help'])) { echo "--backup=DIR [--apply]; restores new-format promotion journal only\n"; exit; }
try {
$dir=$opts['backup'] ?? throw new RuntimeException('Missing --backup');
DplOnboarding\boot();
$result=DplOnboarding\locked($dir, fn() => PanelChange::rollback($dir, array_key_exists('apply',$opts)));
echo json_encode($result, JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE) . PHP_EOL;
} catch (Throwable $e) {
$reason=get_class($e)===RuntimeException::class ? $e->getMessage() : "Inspect journal/conflicts";
fwrite(STDERR, "Rollback stopped: " . $reason . "\n");
exit(1);
}
+496
View File
@@ -0,0 +1,496 @@
"""Reusable AnyTLS site adapter; invoked in-process by batch.py, never a daemon."""
import base64,hashlib,json,os,shlex,threading,time
from pathlib import Path
from types import SimpleNamespace
from ssh_pool import Pool,private_json
from acceptance import audit,digest,snapshot,service_change,provider_state,verification_scope,validate_impact,candidate_eligibility
class SiteAdapter:
def __init__(self,plan,directory,pool=None,atomic_writer=None,resource_lock=None):
if atomic_writer is None or resource_lock is None:
from batch import atomic_json,lock
atomic_writer,resource_lock=atomic_writer or atomic_json,resource_lock or lock
self.atomic_json,self.resource_lock=atomic_writer,resource_lock
self.plan,self.directory=plan,Path(directory)
self.ctx=plan['context'];self.lock=threading.RLock();self.leases={};self.formal_done={}
self.validate_service_overrides(self.ctx,plan['nodes'])
for field in ('ops_root','node_root','batch_backup_root','node_backup_root','qa_root','provider_snapshot','exit_registry','ssh_config','client_binary'):
value=self.ctx.get(field,'')
if not isinstance(value,str) or not value.startswith('/') or '..' in value.split('/') or any(c not in 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_./-' for c in value):
raise ValueError('Explicit safe absolute site path required: '+field)
validate_impact(self.ctx.get('acceptance_impact'))
config=private_json(self.ctx['ssh_config'])
for candidate in plan['nodes']:
if config['hosts'].get(candidate['vps_id'],{}).get('host')!=candidate['node_address']:raise ValueError('SSH target differs from frozen candidate address')
for role in ('jump_vps','panel_vps','gateway_vps'):
if self.ctx[role] not in config['hosts']:raise ValueError('Missing registered SSH role')
self.pool=pool or Pool(config,self.ctx['jump_vps'])
if not __import__('re').fullmatch('[0-9a-f]{64}',self.ctx.get('client_sha256','')):raise ValueError('Reviewed official client SHA256 required')
self.exit_registry=private_json(self.ctx['exit_registry'])
for candidate in plan['nodes']:
if self.exit_registry.get(candidate['tls_domain'])!={'expected_exit':candidate['expected_exit'],'country':candidate['country']}:raise ValueError('Candidate exit registry missing or changed')
if any(n['vps_id'] in [self.ctx['jump_vps'],self.ctx['panel_vps'],self.ctx['gateway_vps']] for n in plan['nodes']):raise ValueError('Dedicated node host required')
for key in ('app_root',):
if not __import__('re').fullmatch('/[A-Za-z0-9_./-]+',self.ctx[key]) or '..' in self.ctx[key].split('/'):raise ValueError('Unsafe application root')
if type(self.ctx.get('formal_socks_port')) is not int or not 1024<=self.ctx['formal_socks_port']<=65535 or self.ctx['formal_socks_port'] in [n['socks_port'] for n in plan['nodes']]:raise ValueError('Reserve a distinct formal SOCKS port')
if not self.ctx.get('gateway_containers') or any(not __import__('re').fullmatch('[A-Za-z0-9_.-]+',v) for v in self.ctx['gateway_containers']):raise ValueError('Explicit gateway container inventory required')
def close(self):
# On waiting, failure and success, close owned formal leases before closing SSH.
failed=False
for group in list(self.leases):
try:self.account_command(group,'cleanup',True)
except Exception:failed=True
self.pool.close()
if failed:
self.atomic_json(self.directory/'cleanup-error.json',{'groups':list(self.leases),'reason':'cleanup_outcome_unknown','needs_probe':True})
raise RuntimeError('Acceptance cleanup incomplete; inspect protected leases before retry')
def account_command(self,group,action,apply=False,client=None):
panel=client or self.pool.get(self.ctx['panel_vps'])
directory=self.ctx['batch_backup_root']+'/acceptance-group-'+str(group)
cmd='cd '+self.ctx['app_root']+' && php '+self.ctx['ops_root']+'/panel-acceptance.php --action='+action+' --dir='+directory+' --group='+str(group)+(' --apply' if apply else '')
_,out,err=panel.exec_command(cmd,timeout=90);data=out.read();err.read()
if out.channel.recv_exit_status():raise RuntimeError('acceptance_account_blocked')
try:return json.loads(data)
except ValueError:raise RuntimeError('acceptance_account_response_not_json') from None
def prepare_account(self,n,panel,execute):
with self.lock:
group=n['formal_group_id']
for spec in self.plan['nodes']:
registered=self.exit_registry.get(spec['tls_domain'],{})
if registered != {'expected_exit':spec['expected_exit'],'country':spec['country']}:
raise ValueError('Exit registry must independently cover the candidate plan')
if group not in self.leases:
# Register cleanup obligation before any possibly successful remote create.
self.leases[group]=True
self.account_command(group,'prepare',True,panel)
source=self.account_command(group,'source',client=panel)
for spec in source['nodes']:
if spec['sni'] not in self.exit_registry:raise ValueError('Missing old-node exit expectation')
def capacity_gate(self,node,execute):
script=r"""from pathlib import Path
import json,shutil,subprocess,re
text=Path('/proc/meminfo').read_text()
match=re.search(r'^MemTotal:\s+(\d+) kB$',text,re.M)
if not match:raise RuntimeError('memory_unknown')
units=[]
for unit in ['XrayR','xrayr']:
data=subprocess.check_output(['systemctl','show',unit,'-p','LoadState'],text=True).strip()
if data not in ['LoadState=loaded','LoadState=not-found','LoadState=masked','LoadState=bad-setting','LoadState=error','LoadState=merged']:raise RuntimeError('xrayr_installation_unknown')
if data!='LoadState=not-found':units.append(unit)
paths=[p for p in ['/usr/local/XrayR/XrayR','/usr/local/bin/XrayR','/usr/bin/XrayR','/etc/XrayR/config.yml'] if Path(p).exists()]
installed=bool(units or paths or shutil.which('XrayR') or shutil.which('xrayr'))
print(json.dumps({'total_memory_bytes':int(match.group(1))*1024,'xrayr_installed':installed}))
"""
observation=json.loads(execute(node,"python3 - <<'DPLCAPACITY'\n"+script+"\nDPLCAPACITY"))
if not candidate_eligibility(observation.get('total_memory_bytes'),observation.get('xrayr_installed')):
raise RuntimeError('candidate_low_memory_with_xrayr')
return observation
def certificate_gate(self,n,node,read,execute):
owner=read(node,'/etc/dpl-node/batch-owner.json')
owned=bool(owner and json.loads(owner).get('request_sha256')==n['request_sha256'])
script=r"""from pathlib import Path
import re
def hook_options(path):
for line in path.read_text().splitlines():
match=re.match(r'^\s*([A-Za-z0-9_-]+)\s*=(.*)$',line)
if match:
key=match.group(1).lower().replace('-','_')
if key.endswith('_hook'):yield key,match.group(2).strip()
for name in ['/etc/letsencrypt/cli.ini','/root/.config/letsencrypt/cli.ini']:
p=Path(name)
if p.exists() and any(value for key,value in hook_options(p)):raise SystemExit(2)
# Both normal and Snap directory hooks need an explicit independent review.
for name in ['/etc/letsencrypt/renewal-hooks','/var/snap/certbot/common/letsencrypt/renewal-hooks']:
p=Path(name)
if p.is_symlink() or (p.exists() and any(x.is_file() or x.is_symlink() for x in p.rglob('*'))):raise SystemExit(6)
domain=DOMAIN
paths=[Path('/etc/letsencrypt')/kind/domain for kind in ['live','archive']]+[Path('/etc/letsencrypt/renewal')/(domain+'.conf')]
if not OWNED and any(p.exists() or p.is_symlink() for p in paths):raise SystemExit(3)
p=paths[-1]
if p.exists():
seen_hook=False
for key,value in hook_options(p):
if key in ('deploy_hook','renew_hook'):
if seen_hook:raise SystemExit(5)
seen_hook=True
if value!=HOOK:raise SystemExit(5)
elif value:raise SystemExit(4)
"""
prefix='DOMAIN='+repr(n['tls_domain'])+';OWNED='+repr(owned)+';HOOK='+repr('/bin/sh '+self.ctx['node_root']+'/renew-node.sh')+'\n'
execute(node,"python3 - <<'DPLCERTGATE'\n"+prefix+script+"\nDPLCERTGATE")
execute(node,'command -v git >/dev/null && command -v curl >/dev/null && command -v certbot >/dev/null && command -v ss >/dev/null && command -v sha256sum >/dev/null && command -v openssl >/dev/null')
@staticmethod
def validate_service_overrides(context,nodes):
overrides=context.get('preserved_service_overrides',{})
if not isinstance(overrides,dict):raise ValueError('Invalid preserved service overrides')
hosts={n['vps_id'] for n in nodes}
for host,value in overrides.items():
if host not in hosts or not isinstance(value,dict) or set(value) not in ({'config'},{'unit','binary','config','port'}):
raise ValueError('Unknown preserved service override host or fields')
for field in ('binary','config'):
if field not in value:continue
path=value[field]
if not isinstance(path,str) or not __import__('re').fullmatch('/[A-Za-z0-9_./-]+',path) or any(part in ('','.','..') for part in path.split('/')[1:]):
raise ValueError('Unsafe preserved service override path')
if 'unit' in value and (not isinstance(value['unit'],str) or not __import__('re').fullmatch('[[email protected]]+',value['unit'])):
raise ValueError('Unsafe preserved service override unit')
if 'port' in value and (type(value['port']) is not int or not 1<=value['port']<=65535):
raise ValueError('Unsafe preserved service override port')
def guard_service(self,node,backup,read,write,execute):
spec={**self.ctx['preserved_service'],**self.ctx.get('preserved_service_overrides',{}).get(getattr(node,'rid',None),{})}
for field in ('unit','binary','config','port'):
if field not in spec:raise ValueError('Explicit preserved service specification required')
if not all(isinstance(spec[k],str) and __import__('re').fullmatch('[A-Za-z0-9_./@-]+',spec[k]) for k in ('unit','binary','config')) or type(spec['port']) is not int:
raise ValueError('Unsafe preserved service specification')
script="""import hashlib,json,pathlib,subprocess
s=SPEC
v=dict(x.split('=',1) for x in subprocess.check_output(['systemctl','show',s['unit'],'-p','MainPID','-p','ActiveEnterTimestamp','-p','NRestarts','-p','ActiveState','-p','FragmentPath'],text=True).splitlines())
def h(p):return hashlib.sha256(pathlib.Path(p).read_bytes()).hexdigest()
listeners=subprocess.check_output(['ss','-lntH','( sport = :'+str(s['port'])+' )'],text=True)
print(json.dumps({'unit_sha256':h(v['FragmentPath']),'binary_sha256':h(s['binary']),'config_sha256':h(s['config']),'listeners':sorted(x.split()[3] for x in listeners.splitlines()),'pid':v['MainPID'],'started':v['ActiveEnterTimestamp'],'restarts':v['NRestarts'],'active':v['ActiveState']=='active'}))
""".replace('SPEC',repr(spec))
current=json.loads(execute(node,"python3 - <<'DPLSERVICE'\n"+script+"\nDPLSERVICE"))
if not current['active'] or not current['listeners']:raise RuntimeError('preserved_service_unavailable')
execute(node,'install -d -m 700 '+backup)
p=backup+'/preserved-service-original.json';raw=read(node,p)
if raw is None:write(node,p,json.dumps(current));return current
before=json.loads(raw);status=service_change(before,current)
if status=='investigate_restart':
write(node,backup+'/preserved-service-observed.json',json.dumps(current))
review=read(node,backup+'/preserved-service-review.json')
review=json.loads(review) if review else {}
if review.get('before_sha256')!=digest(before) or review.get('after_sha256')!=digest(current) or not review.get('reason') or not review.get('evidence_sha256'):
raise RuntimeError('investigate_preserved_service_restart')
elif status!='ready':raise RuntimeError('preserved_service_'+status)
return current
def dependencies(self,n,panel,gateway,node,stage_probe,read,execute,gateway_py):
"""Current dependency reads; a missing observation cannot authorize a skip."""
state=stage_probe(panel);deps={'stage':digest(state)}
ui=provider_state(private_json(self.ctx['provider_snapshot']),n)
try:
dns=json.loads(gateway_py(gateway,'import socket,json\nprint(json.dumps(sorted(set(x[4][0] for x in socket.getaddrinfo('+repr(n['tls_domain'])+',443,socket.AF_INET)))))'))
if dns==[n['node_address']]:deps['dns']=digest(dns)
except Exception:pass
try:
live=execute(node,'systemctl is-active dpl-node; git -C '+self.ctx['node_root']+' rev-parse HEAD; sha256sum /etc/dpl-node/config.yml /etc/dpl-node/secret.env /etc/systemd/system/dpl-node.service /etc/letsencrypt/live/'+n['tls_domain']+'/fullchain.pem')
deps['provision']=digest(live)
# End-to-end strict TLS at preflight is necessary to reuse a relay observation.
tls=gateway_py(gateway,'import ssl,socket\nc=ssl.create_default_context()\nwith socket.create_connection(('+repr(n['relay_host'])+','+str(n['relay_port'])+'),10) as s:\n with c.wrap_socket(s,server_hostname='+repr(n['tls_domain'])+') as t:print(t.version())')
rows=ui['relays']
deps['relay']=digest([rows,tls])
report=read(panel,self.ctx['node_backup_root']+'/'+n['key']+'/qa-report.json')
if report:deps['verify']=digest([state,live,hashlib.sha256(report).hexdigest()])
except Exception:pass
return deps
def formal(self,n,panel,gateway,php,execute,read,write):
group=n['formal_group_id'];ctx=self.ctx
with self.lock, self.resource_lock(self.directory.parent, ctx['gateway_vps']+':formal:'+str(ctx['formal_socks_port'])):
source=self.account_command(group,'snapshot' if group in self.formal_done else 'source',client=panel)
def public(source):
values=[]
for item in source['nodes']:
if item['sni'] not in self.exit_registry:raise ValueError('Unregistered current node exit')
values.append(dict(item,**self.exit_registry[item['sni']]))
return snapshot(values)
before=public(source)
owned=self.formal_done.get(group,{}).get('owned',source.get('owned',False))
scope=verification_scope(before,None if owned else ctx.get('acceptance_impact'))
# Do not run final verification while any candidate in this group is still isolated.
cohort=[x for x in self.plan['nodes'] if x['formal_group_id']==group]
wanted={(x['relay_host'],x['relay_port'],x['tls_domain']) for x in cohort}
if not wanted.issubset({(x['relay'],x['relay_port'],x['sni']) for x in before}):raise RuntimeError('formal_group_not_ready')
if group in self.formal_done:
prior=self.formal_done[group]
return audit(prior['before'],before,prior['report'],prior['qas'],prior['binding'],digest(self.plan),prior['expected_qas'],scope=scope)
root=ctx['qa_root']+'/formal-group-'+str(group)
execute(gateway,'install -d -m 700 '+root)
expectations=[]
for node in before:
original=next(x for x in source['nodes'] if x['id']==node['id'])
expectations.append({'tag':node['tag'],'host':node['relay'],'port':node['relay_port'],'sni':node['sni'],'uuid':original['uuid'],'expected_exit':node['expected_exit'],'expected_country':node['country'],'verification':scope[node['tag']]})
# Tokens/UUIDs never leave memory except the gateway's private task files.
write(gateway,root+'/source-private.json',json.dumps({'token':source['token'],'expectations':expectations,'owned':source['owned']}))
script="""import gzip,json,urllib.request,subprocess,os,time
from pathlib import Path
os.umask(0o077);root=Path(ROOT);source=json.loads((root/'source-private.json').read_text())
r=urllib.request.Request(SUB+'/api/v1/client/subscribe?token='+source['token'],headers={'User-Agent':'sing-box/1.14.3'})
with urllib.request.urlopen(r,timeout=30) as response:
data=response.read();headers={k.lower():v for k,v in response.headers.items()}
if headers.get('content-encoding','').lower()=='gzip':data=gzip.decompress(data)
assert headers.get('cf-cache-status','').upper() not in ['HIT','STALE','UPDATING'] and not headers.get('age') and not headers.get('cf-mitigated') and 'no-store' in headers.get('cache-control','').lower()
(root/'subscription.json').write_bytes(data);(root/'expectations.json').write_text(json.dumps(source['expectations']))
deadline=time.monotonic()+900
for attempt in range(3 if source['owned'] else 1):
with (root/'verify.stdout').open('wb') as out,(root/'verify.stderr').open('wb') as err:
result=subprocess.run(['python3',OPS+'/verify-node.py','--subscription',str(root/'subscription.json'),'--expectations',str(root/'expectations.json'),'--binary',BINARY,'--port',str(PORT),'--report',str(root/'report.json'),'--run'],timeout=max(1,deadline-time.monotonic()),stdout=out,stderr=err)
if result.returncode==0:break
try:reason=json.loads((root/'verify.stderr').read_text()).get('reason')
except Exception:reason=None
if not source['owned'] or attempt==2 or reason!='Verification failed; inspect protected diagnostics' or deadline-time.monotonic()<15:raise RuntimeError('Formal verification failed')
# A just-created user's UUID may need one node pull interval to propagate.
# Retry only diagnostic reads, keep the same lease; never replay production writes.
time.sleep(15)
"""
prefix='ROOT='+repr(root)+';SUB='+repr(ctx['subscription_url'])+';OPS='+repr(ctx['ops_root'])+';BINARY='+repr(ctx['client_binary'])+';PORT='+repr(ctx['formal_socks_port'])+'\n'
try:
execute(gateway,"python3 - <<'DPLFORMAL'\n"+prefix+script+"\nDPLFORMAL",1000)
after=public(self.account_command(group,'source',client=panel))
report=read(gateway,root+'/report.json')
finally:
# Never leave an owned formal test user active, including failed client runs.
self.account_command(group,'cleanup',True,panel)
identities={};tokens={}
for candidate in cohort:
b=ctx['node_backup_root']+'/'+candidate['key']
result=php(panel,'$m=json_decode(file_get_contents('+self.php_value(b+'/manifest.json')+'),true);$s=App\\Models\\Server::findOrFail($m["node_id"]);$u=App\\Models\\User::findOrFail($m["test_user_id"]);echo json_encode(["id"=>$u->id,"token"=>$u->token,"banned"=>(bool)$u->banned,"excluded"=>!App\\Services\\ServerService::getAvailableUsers($s)->contains("id",$u->id)]);')
identities[candidate['key']]=result['id'];tokens[candidate['key']]=result
# Include every owned formal lease from earlier resumptions, not just the current user.
lease_dir=ctx['batch_backup_root']+'/acceptance-group-'+str(group)
leases=php(panel,'$out=[];foreach(glob('+self.php_value(lease_dir+'/acceptance-*.json')+') as $f){$j=json_decode(file_get_contents($f),true);if(!($j["owned"]??false)||empty($j["id"]))continue;$u=App\\Models\\User::findOrFail($j["id"]);$excluded=true;foreach(App\\Models\\Server::all() as $s)if(App\\Services\\ServerService::getAvailableUsers($s)->contains("id",$u->id))$excluded=false;$out[(string)$u->id]=["id"=>$u->id,"token"=>$u->token,"banned"=>(bool)$u->banned,"excluded"=>$excluded];}echo json_encode($out);')
for ident,value in (leases.items() if isinstance(leases,dict) else []):
key='formal-'+str(ident);identities[key]=value['id'];tokens[key]=value
users={}
for key,value in tokens.items():
# Only the gateway accesses the subscription source; local HTTP never bypasses its registered route.
script='import urllib.request,urllib.error\nr=urllib.request.Request('+repr(ctx['subscription_url']+'/api/v1/client/subscribe?token='+value['token'])+',headers={"User-Agent":"sing-box/1.14.3"})\ntry:\n response=urllib.request.urlopen(r,timeout=30);print(response.status);response.close()\nexcept urllib.error.HTTPError as e:print(e.code)'
# Keep tokens out of argv: exec_command carries a private stdin script, not an OS argv.
si,o,e=gateway.exec_command('python3 -',timeout=60);si.write(script);si.channel.shutdown_write();out=o.read();e.read()
if o.channel.recv_exit_status():raise RuntimeError('qa_rejection_probe_failed')
users[key]={'id':value['id'],'banned':value['banned'],'excluded':value['excluded'],'http_status':int(out.strip())}
qas=json.dumps({'users':users,'captured_at':int(time.time()),'plan_sha256':digest(self.plan)},sort_keys=True).encode()
binding={'plan_sha256':digest(self.plan),'snapshot_sha256':digest(before),'report_sha256':hashlib.sha256(report).hexdigest(),'qa_rejections_sha256':hashlib.sha256(qas).hexdigest(),'verified_at':int(time.time()),'scope_sha256':digest(scope)}
audit(before,after,report,qas,binding,digest(self.plan),identities,scope=scope)
write(gateway,root+'/qa-rejections.json',qas);write(gateway,root+'/binding.json',json.dumps(binding));write(gateway,root+'/snapshot.json',json.dumps(before))
self.formal_done[group]={'before':before,'report':report,'qas':qas,'binding':binding,'expected_qas':identities,'owned':owned}
# Persist only nonsecret, byte-bound results for coordinator/operator review.
self.atomic_json(self.directory/('formal-group-'+str(group)+'.json'),{'snapshot':before,'verification_scope':scope,'report':json.loads(report),'qas':json.loads(qas),'binding':binding})
def qa_evidence(self,n,raw,state):
# Bind the exact remote bytes, not a re-serialized nested report. Persist the latest
# online/traffic state so independent review never needs a separate task collector.
report=json.loads(raw)
self.atomic_json(self.directory/(n['key']+'-evidence.json'),{
'key':n['key'],'request_sha256':n['request_sha256'],
'report_sha256':hashlib.sha256(raw).hexdigest(),'report':report,
'panel':state,'collected_at':int(time.time())})
@staticmethod
def php_value(value):
return "json_decode(base64_decode('"+base64.b64encode(json.dumps(value).encode()).decode()+"'),true)"
def call(self,n,phase,action):
plan=self.plan;ctx=self.ctx;key=n['key'];sha=n['request_sha256']
a=SimpleNamespace(phase=phase,action=action,state_dir=str(self.directory))
B=ctx['node_backup_root']+'/'+key;Q=ctx['qa_root']+'/'+key
OPS=ctx['ops_root'];NP=ctx['node_root'];APP=ctx['app_root']
def execute(c,cmd,timeout=120):
si,o,e=c.exec_command(cmd,timeout=timeout);out=o.read();err=e.read();code=o.channel.recv_exit_status()
if code: raise RuntimeError('remote_exit_'+str(code))
return out.decode()
def php(c,body):
si,o,e=c.exec_command('cd '+shlex.quote(APP)+' && php',timeout=90)
si.write("<?php require 'vendor/autoload.php';$app=require 'bootstrap/app.php';$app->make(Illuminate\\Contracts\\Console\\Kernel::class)->bootstrap();"+body)
si.channel.shutdown_write();out=o.read();err=e.read()
if o.channel.recv_exit_status():raise RuntimeError('panel_php_failed')
try:return json.loads(out)
except ValueError:raise RuntimeError('panel_response_not_json') from None
def payload(value):return "json_decode(base64_decode('"+base64.b64encode(json.dumps(value,ensure_ascii=False).encode()).decode()+"'),true)"
def read(c,path):
with c.open_sftp() as s:
try:
with s.open(path,'rb') as f:return f.read()
except FileNotFoundError:return None
except OSError as e:
if e.errno==2:return None
raise
def write(c,path,data):
if isinstance(data,str):data=data.encode()
with c.open_sftp() as s:
tmp=path+'.tmp-'+str(os.getpid())+'-'+str(threading.get_ident())
with s.open(tmp,'w') as f:s.chmod(tmp,0o600);f.write(data)
s.posix_rename(tmp,path)
def parameters():return dict(sorted({'key':key,'name':n['name'],'relay-host':n['relay_host'],'relay-port':n['relay_port'],'listen-port':n['listen_port'],'tls-domain':n['tls_domain'],'panel-url':ctx['panel_url']}.items()))
def canonical(value):return hashlib.sha256(json.dumps(value,sort_keys=True,ensure_ascii=False,separators=(',',':')).encode()).hexdigest()
def containers(gateway):
data=json.loads(execute(gateway,'docker inspect '+ ' '.join(ctx['gateway_containers'])))
return {v['Name']:{'id':v['Id'],'started':v['State']['StartedAt'],'restarts':v['RestartCount']} for v in data}
def receipt(status,retry=False):return {'key':key,'phase':a.phase,'request_sha256':sha,'status':status,'valid_until':time.time()+300,**({'retry_safe':True} if retry else {})}
def stage_probe(panel):
p=parameters()
code='$b='+payload(B)+';$p='+payload(p)+r''';$f=$b.'/manifest.json';if(!is_file($f)){$conf=App\Models\ServerMachine::where('name','dpl-'.$p['key'])->exists()||App\Models\Server::where('name',$p['name'])->exists()||App\Models\Server::where('host',$p['relay-host'])->where('port',(string)$p['relay-port'])->exists();echo json_encode(['status'=>$conf?'conflict':'absent','retry_safe'=>!$conf]);return;}$m=json_decode(file_get_contents($f),true);$s=App\Models\Server::find($m['node_id']);$mch=App\Models\ServerMachine::find($m['machine_id']);$ok=($m['parameters']??null)===$p && $s && $mch && $s->machine_id===$mch->id && $mch->name==='dpl-'.$p['key'] && $s->type==='anytls' && ($s->protocol_settings['tls']['allow_insecure']??null)===false && $s->name===$p['name'] && $s->host===$p['relay-host'] && (int)$s->port===$p['relay-port'] && (int)$s->server_port===$p['listen-port'] && ($s->protocol_settings['tls']['server_name']??null)===$p['tls-domain'];$u=App\Models\User::find($m['test_user_id']);$g=App\Models\ServerGroup::find($m['group_id']);$ok=$ok && $u && $g && !$u->is_admin && (int)$u->group_id===$m['group_id'] && str_starts_with($u->email,'node-qa-'.$p['key'].'-') && $g->name==='dpl 接入验收 '.$p['key'];if(!is_file($b.'/promotion-journal.json'))$ok=$ok && $s->group_ids===[(string)$m['group_id']] && !$u->banned;echo json_encode(['status'=>$ok?'ready':'conflict','manifest'=>$m]);'''
return php(panel,code)
def state(panel):
return php(panel,'$b='+payload(B)+r''';$m=json_decode(file_get_contents($b.'/manifest.json'),true);$s=App\Models\Server::findOrFail($m['node_id']);$u=App\Models\User::findOrFail($m['test_user_id']);echo json_encode(['manifest'=>$m,'node_online'=>(bool)$s->is_online,'groups'=>$s->group_ids,'qa_banned'=>(bool)$u->banned,'u'=>(int)$u->u,'d'=>(int)$u->d]);''')
def baseline(panel,gateway):
directory=ctx['batch_backup_root'];f=directory+'/baseline.json'
version=json.loads(execute(panel,"python3 - <<'DPLVERSION'\nimport subprocess,hashlib,json\np="+repr(APP)+"\nh=subprocess.check_output(['git','-C',p,'rev-parse','HEAD']).decode().strip()\nd=subprocess.check_output(['git','-C',p,'diff','HEAD'])+subprocess.check_output(['git','-C',p,'status','--porcelain'])\nprint(json.dumps({'head':h,'worktree_sha256':hashlib.sha256(d).hexdigest()}))\nDPLVERSION"))
previous=read(panel,directory+'/application-version.json')
if previous is None:write(panel,directory+'/application-version.json',json.dumps(version))
elif json.loads(previous)!=version:raise RuntimeError('application_version_changed')
# Read/write a protected snapshot only once, before any new stage.
return php(panel,'$p='+payload(f)+r''';if(is_file($p)){echo json_encode(['exists'=>true]);return;} $v=['nodes'=>App\Models\Server::orderBy('id')->get()->toArray(),'plans'=>App\Models\Plan::orderBy('id')->get()->toArray(),'users'=>App\Models\User::orderBy('id')->get(['id','group_id','plan_id'])->toArray(),'subscribe_url'=>admin_setting('subscribe_url')];file_put_contents($p,json_encode($v,JSON_THROW_ON_ERROR));chmod($p,0600);echo json_encode(['exists'=>true]);''')
def gateway_py(gateway,script,timeout=120):
return execute(gateway,"python3 - <<'DPLPY'\n"+script+"\nDPLPY",timeout)
def assert_old(node):
self.guard_service(node,B,read,write,execute)
def transfer(panel,gateway,node):
execute(node,'install -d -m 700 /etc/dpl-node')
execute(gateway,'install -d -m 700 '+Q)
for source,dest,target in [('node-config.yml',node,'/etc/dpl-node/config.yml'),('node-secret.env',node,'/etc/dpl-node/secret.env'),('qa-private.json',gateway,Q+'/qa.json')]:
data=read(panel,B+'/'+source);prior=read(dest,target)
if prior is not None and prior!=data:raise RuntimeError('private_config_conflict')
if prior is None:write(dest,target,data)
def fetch_qa(gateway):
script='''import json,urllib.request
from pathlib import Path
q=json.loads(Path(Q+'/qa.json').read_text())
req=urllib.request.Request(SUB+'/api/v1/client/subscribe?token='+q['subscribe_token'],headers={'User-Agent':'sing-box/1.14.3'})
with urllib.request.urlopen(req,timeout=30) as r:
data=r.read(); code=r.status; headers={k.lower():v for k,v in r.headers.items()}
import gzip
if headers.get('content-encoding','').lower()=='gzip':data=gzip.decompress(data)
v=json.loads(data);Path(Q+'/subscription.json').write_bytes(data);Path(Q+'/subscription.json').chmod(0o600)
print(json.dumps({'status':code,'cache':headers.get('cf-cache-status'),'control':headers.get('cache-control'),'age':headers.get('age')}))
'''
return gateway_py(gateway,'Q='+repr(Q)+';SUB='+repr(ctx['subscription_url'])+'\n'+script)
def phase_impl(panel,gateway,node):
if a.phase=='preflight':
capacity=self.capacity_gate(node,execute)
self.atomic_json(self.directory/(key+'-capacity.json'),dict(capacity,request_sha256=sha,checked_at=int(time.time())))
with self.lock, self.resource_lock(self.directory.parent,ctx['panel_vps']+':panel'):
execute(panel,'install -d -m 700 '+ctx['batch_backup_root'])
execute(panel,'test "$(git -C '+OPS+' rev-parse HEAD)" = '+ctx['provision_commit']+' && test -z "$(git -C '+OPS+' status --porcelain)"')
baseline(panel,gateway)
base_path=ctx['batch_backup_root']+'/gateway-baseline.json'
current_containers=containers(gateway)
prior_gateway=read(panel,base_path)
if prior_gateway is None:write(panel,base_path,json.dumps(current_containers,sort_keys=True))
elif json.loads(prior_gateway)!=current_containers:return receipt('conflict')
ui=Path(ctx['provider_snapshot'])
if not ui.exists():return receipt('waiting')
snap=private_json(ui)
if type(snap.get('captured_at')) not in (int,float) or not 0<=time.time()-snap['captured_at']<=900:return receipt('waiting')
try:provider_state(snap,n)
except ValueError:return receipt('conflict')
gateway_py(gateway,'import socket\ns=socket.socket();s.bind(("127.0.0.1",'+str(n['socks_port'])+'));s.close()')
s=stage_probe(panel)
if s['status']=='conflict':return receipt('conflict')
assert_old(node)
self.certificate_gate(n,node,read,execute)
execute(node,'test "$(git -C '+NP+' rev-parse HEAD)" = '+ctx['provision_commit']+' && test -z "$(git -C '+NP+' status --porcelain)" && command -v git >/dev/null')
execute(gateway,"echo '"+ctx['client_sha256']+" "+ctx['client_binary']+"' | sha256sum -c --status && test -x "+shlex.quote(ctx['client_binary'])+' && test "$(git -C '+OPS+' rev-parse HEAD)" = '+ctx['provision_commit']+' && test -z "$(git -C '+OPS+' status --porcelain)"')
if s['status']=='absent':execute(node,"test ! -e /etc/dpl-node/config.yml && test ! -e /etc/systemd/system/dpl-node.service && test ! -e /etc/dpl-node/batch-owner.json && ! ss -lntH '( sport = :"+str(n['listen_port'])+" )' | grep -q .")
if not php(panel,'echo json_encode(App\\Models\\ServerGroup::where("id",'+str(n['formal_group_id'])+')->exists());'):return receipt('conflict')
self.prepare_account(n,panel,execute)
r=receipt('ready');r['resume_dependencies']=self.dependencies(n,panel,gateway,node,stage_probe,read,execute,gateway_py);return r
if a.phase=='stage':
if a.action=='probe':
r=stage_probe(panel);return receipt(r['status'],r.get('retry_safe',False))
command='cd '+APP+' && php '+OPS+'/stage.php '+ ' '.join('--'+k+'='+shlex.quote(str(v)) for k,v in {**parameters(),'backup':B}.items())
execute(panel,command);return receipt('ready')
if a.phase=='dns':
try:
result=gateway_py(gateway,'import socket,json\nprint(json.dumps(sorted(set(x[4][0] for x in socket.getaddrinfo('+repr(n['tls_domain'])+',443,socket.AF_INET)))))')
return receipt('ready' if json.loads(result)==[n['node_address']] else 'conflict')
except Exception:return receipt('waiting')
if a.phase=='provision':
owner='/etc/dpl-node/batch-owner.json';prior=read(node,owner)
if prior is not None and json.loads(prior).get('request_sha256')!=sha:return receipt('conflict')
if prior is None and read(node,'/etc/systemd/system/dpl-node.service') is not None:return receipt('conflict')
done=read(node,B+'/provision-ok.json')
if a.action=='probe':
if done and json.loads(done).get('request_sha256')==sha:
for file,target in [('node-config.yml','/etc/dpl-node/config.yml'),('node-secret.env','/etc/dpl-node/secret.env')]:
if read(panel,B+'/'+file)!=read(node,target):return receipt('conflict')
execute(node,"echo '55bf71fa9d9f2048d3255ae7c0af929a41897ca7743f6ead34132a6ca4c79043 /opt/dpl-node/xboard-node' | sha256sum -c >/dev/null")
assert_old(node);execute(node,'systemctl is-active --quiet dpl-node && openssl x509 -checkend 86400 -noout -in /etc/letsencrypt/live/'+n['tls_domain']+'/fullchain.pem')
return receipt('ready')
return receipt('absent',True)
if prior is None:
execute(node,'install -d -m 700 /etc/dpl-node');write(node,owner,json.dumps({'request_sha256':sha,'key':key}))
transfer(panel,gateway,node)
if read(node,'/etc/systemd/system/dpl-node.service') is None:
execute(node,'bash '+NP+'/install-node.sh --listen-port='+str(n['listen_port'])+' --tls-domain='+n['tls_domain']+' > '+B+'/install-node.log 2>&1',300)
execute(node,"echo '55bf71fa9d9f2048d3255ae7c0af929a41897ca7743f6ead34132a6ca4c79043 /opt/dpl-node/xboard-node' | sha256sum -c >/dev/null")
domain=n['tls_domain']
if read(node,'/etc/letsencrypt/live/'+domain+'/fullchain.pem') is None:
execute(node,"certbot certonly --standalone --non-interactive --agree-tos --no-directory-hooks --cert-name "+domain+' -d '+domain+" --deploy-hook '/bin/sh "+NP+"/renew-node.sh' > "+B+'/certbot.log 2>&1',300)
execute(node,'systemctl enable --now dpl-node > '+B+'/enable.log 2>&1 && systemctl is-active --quiet dpl-node',60)
execute(node,'certbot renew --cert-name '+domain+' --dry-run --no-random-sleep-on-renew --run-deploy-hooks --no-directory-hooks > '+B+'/renew-dry-run.log 2>&1',600)
assert_old(node)
write(node,B+'/provision-ok.json',json.dumps({'request_sha256':sha,'verified_at':int(time.time())}))
return receipt('ready')
if a.phase=='relay':
try:
result=gateway_py(gateway,'import ssl,socket,json\nc=ssl.create_default_context()\nwith socket.create_connection(('+repr(n['relay_host'])+','+str(n['relay_port'])+'),10) as s:\n with c.wrap_socket(s,server_hostname='+repr(n['tls_domain'])+') as t: print(json.dumps({"tls":t.version()}))')
return receipt('ready' if json.loads(result).get('tls') else 'waiting')
except Exception:return receipt('waiting')
if a.phase=='verify':
s=state(panel)
if s['qa_banned'] and s['groups']==[str(n['formal_group_id'])]:
return receipt('ready' if read(panel,B+'/qa-report.json') else 'unknown')
existing=read(panel,B+'/qa-report.json')
if existing:
report=json.loads(existing)
if report.get('state')=='live_verified' and report.get('qa_user_id')==s['manifest']['test_user_id'] and 0<=time.time()-report.get('verified_at',0)<=900 and s['node_online'] and s['u']>0 and s['d']>0:
self.qa_evidence(n,existing,s)
r=receipt('ready');r['valid_until']=min(r['valid_until'],report['verified_at']+900);return r
transfer(panel,gateway,node);fetch_qa(gateway)
execute(gateway,'python3 '+OPS+'/verify-node.py --qa '+Q+'/qa.json --subscription '+Q+'/subscription.json --binary '+ctx['client_binary']+' --port '+str(n['socks_port'])+' --expected-exit '+shlex.quote(n['expected_exit'])+' --expected-country '+n['country']+' --report '+Q+'/qa-report.json --run > '+Q+'/verify.stdout 2> '+Q+'/verify.stderr',300)
data=read(gateway,Q+'/qa-report.json');report=json.loads(data)
write(panel,B+'/qa-report.json',data)
for _ in range(24):
s=state(panel)
if s['node_online'] and s['u']>0 and s['d']>0:
self.qa_evidence(n,data,s)
r=receipt('ready');r['valid_until']=min(r['valid_until'],report['verified_at']+900);return r
time.sleep(5)
self.qa_evidence(n,data,s)
return receipt('waiting')
if a.phase=='publish':
s=state(panel)
report_data=read(panel,B+'/qa-report.json')
review_path=Path(a.state_dir)/(key+'-reviewed.json')
if not report_data or not review_path.exists():return receipt('waiting')
report=json.loads(report_data);review=json.loads(review_path.read_text())
valid=review.get('request_sha256')==sha and review.get('report_sha256')==hashlib.sha256(report_data).hexdigest() and review.get('qa_user_id')==s['manifest']['test_user_id'] and review.get('verified_at')==report.get('verified_at')
if not valid:return receipt('waiting')
if s['qa_banned'] and s['groups']==[str(n['formal_group_id'])]:
journal=read(panel,B+'/promotion-journal.json')
if not journal:return receipt('conflict')
j=json.loads(journal)
return receipt('ready' if j.get('manifest')==s['manifest'] and j.get('request',{}).get('mode')=='append' and j.get('request',{}).get('group')==n['formal_group_id'] and j.get('state')=='applied' else 'conflict')
if not s['node_online'] or s['u']<=0 or s['d']<=0:return receipt('waiting')
if a.action=='probe':return receipt('absent',True)
cmd='cd '+APP+' && php '+OPS+'/promote.php --backup='+B+' --mode=append --group='+str(n['formal_group_id'])+' --verification='+B+'/qa-report.json'
execute(panel,cmd);execute(panel,cmd+' --apply');return receipt('ready')
if a.phase=='audit':
s=state(panel);assert_old(node)
if not s['qa_banned'] or s['groups']!=[str(n['formal_group_id'])] or not s['node_online']:return receipt('conflict')
ok=php(panel,'$b='+payload(B)+r''';$m=json_decode(file_get_contents($b.'/manifest.json'),true);$n=App\Models\Server::findOrFail($m['node_id']);$base=json_decode(file_get_contents('''+payload(ctx['batch_backup_root']+'/baseline.json')+r'''),true);$ok=$base['plans']===App\Models\Plan::orderBy('id')->get()->toArray() && $base['users']===App\Models\User::whereIn('id',array_column($base['users'],'id'))->orderBy('id')->get(['id','group_id','plan_id'])->toArray() && $base['subscribe_url']===admin_setting('subscribe_url');foreach($base['nodes'] as $old){$cur=App\Models\Server::find($old['id'])->toArray();foreach(['name','host','port','server_port','protocol_settings','group_ids','machine_id','enabled','show','cert_config'] as $k)if(($cur[$k]??null)!==($old[$k]??null))$ok=false;}$ids=App\Services\ServerService::getAvailableUsers($n)->pluck('id')->all();$ok=$ok&&!in_array($m['test_user_id'],$ids);echo json_encode($ok);''')
if not ok:return receipt('conflict')
self.formal(n,panel,gateway,php,execute,read,write)
original_gateway=read(panel,ctx['batch_backup_root']+'/gateway-baseline.json')
if not original_gateway or containers(gateway)!=json.loads(original_gateway):return receipt('conflict')
return receipt('ready')
return receipt('unknown')
panel=Lazy(self.pool,ctx['panel_vps']);gateway=Lazy(self.pool,ctx['gateway_vps']);node=Lazy(self.pool,n['vps_id'])
try:return phase_impl(panel,gateway,node)
except Exception as exc:
# Never print underlying library/server errors or credentials.
safe = str(exc) if type(exc) is RuntimeError and __import__('re').fullmatch('[a-z_0-9]+',str(exc)) else 'inspect_protected_state'
self.atomic_json(self.directory/(key+'-'+phase+'-error.json'),{'reason':safe})
return receipt('waiting' if safe in ('investigate_preserved_service_restart','formal_group_not_ready') else 'unknown')
class Lazy:
def __init__(self,pool,rid):self.pool,self.rid=pool,rid
def __getattr__(self,name):return getattr(self.pool.get(self.rid),name)
+108
View File
@@ -0,0 +1,108 @@
"""Thread-local SSH sessions, mandatory explicit jump, strict known-host keys."""
import json
import hashlib
import base64
import re
import threading
from pathlib import Path
def private_text(path):
p = Path(path)
if not p.is_absolute() or p.is_symlink() or not p.is_file() or p.stat().st_mode & 0o077:
raise ValueError('Private regular absolute credential/config reference required')
return p.read_text()
def private_json(path):
return json.loads(private_text(path))
def credentials(spec):
if spec.get('credential_format') == 'gemdocs-resource':
import importlib.util,sys
root=Path('/Users/hellcat/Documents/GemDocs/AI版')
resource=spec.get('credential_resource','')
if not re.fullmatch(r'VPS-[0-9]{3}',resource):raise ValueError('Exact GemDocs VPS resource required')
if str(root/'tools') not in sys.path:sys.path.insert(0,str(root/'tools'))
module_spec=importlib.util.spec_from_file_location('gemdocs_credentials',root/'tools/credentials.py')
module=importlib.util.module_from_spec(module_spec);module_spec.loader.exec_module(module)
return {'password':module.get_field(root,resource,'password')}
if not spec.get('credential_ref'):return {}
if spec.get('credential_format','json')=='json':return private_json(spec['credential_ref'])
if spec['credential_format']=='codocs-password':
matches=re.findall(r'(?m)^[ \t]*(?:[-*][ \t]+)?密码[::][ \t]*([^\r\n]+)$',private_text(spec['credential_ref']))
if len(matches)!=1:raise ValueError('Unambiguous existing CoDocs password field required')
return {'password':matches[0].strip()}
raise ValueError('Unsupported credential reference format')
class Pool:
def __init__(self, config, jump_id, client_factory=None):
self.config, self.jump_id = config, jump_id
if jump_id not in config['hosts'] or config['hosts'][jump_id].get('role') != 'white_jump':
raise ValueError('Explicit registered white jump required')
if client_factory is None:
known=Path(config['known_hosts'])
if not known.is_absolute() or known.is_symlink() or not known.is_file() or known.stat().st_mode & 0o022:raise ValueError('Explicit trusted known-hosts file required')
if any(not re.fullmatch('SHA256:[A-Za-z0-9+/]{43}=?',s.get('host_key_sha256','')) for s in config['hosts'].values()):raise ValueError('Approved explicit host fingerprints required')
self.factory = client_factory
self.local = threading.local()
self.clients = []
self.lock = threading.Lock()
def get(self, rid):
sessions = getattr(self.local, 'sessions', None)
if sessions is None:
sessions = self.local.sessions = {}
if rid in sessions:
c = sessions[rid]
if c.get_transport() and c.get_transport().is_active():
return c
# Do not transparently retry operations after a lost connection.
raise RuntimeError('SSH session lost; probe remote outcome on next run')
spec = self.config['hosts'][rid]
jump = self.get(self.jump_id) if rid != self.jump_id else None
if self.factory:
client = self.factory(rid, spec, jump)
else:
import paramiko
client = paramiko.SSHClient()
known=Path(self.config['known_hosts'])
if not known.is_absolute() or known.is_symlink() or not known.is_file() or known.stat().st_mode & 0o022:raise ValueError('Trusted non-writable known-hosts reference required')
entries=paramiko.HostKeys(str(known))
hostname=spec['host'] if spec.get('port',22)==22 else '['+spec['host']+']:'+str(spec['port'])
approved=[]
for key in (entries.lookup(hostname) or {}).values():
actual='SHA256:'+base64.b64encode(hashlib.sha256(key.asbytes()).digest()).decode().rstrip('=')
if actual==spec['host_key_sha256'].rstrip('='):approved.append(key)
if not approved:raise ValueError('Approved known-host key absent; no credentials transmitted')
for key in approved:client.get_host_keys().add(hostname,key.get_name(),key)
client.set_missing_host_key_policy(paramiko.RejectPolicy())
auth = credentials(spec)
if set(auth) - {'username', 'password', 'key_filename', 'passphrase'}:
raise ValueError('Unexpected SSH credential fields')
if auth.get('username',spec['username'])!=spec['username']:raise ValueError('Credential username differs from registered host')
if auth.get('key_filename'):
key=Path(auth['key_filename'])
if not key.is_absolute() or not key.is_file() or key.stat().st_mode & 0o077:raise ValueError('Private absolute SSH key required')
sock = jump.get_transport().open_channel('direct-tcpip', (spec['host'], spec.get('port', 22)), ('127.0.0.1', 0)) if jump else None
try:
client.connect(spec['host'], port=spec.get('port', 22), username=spec['username'],
password=auth.get('password'), key_filename=auth.get('key_filename'),
passphrase=auth.get('passphrase'), sock=sock, allow_agent=False,
look_for_keys=False, timeout=20, banner_timeout=20, auth_timeout=20)
except Exception:
client.close()
raise RuntimeError('SSH connect failed; inspect registered route/host key/credential reference') from None
finally:
auth.clear()
sessions[rid] = client
with self.lock:
self.clients.append(client)
return client
def close(self):
for client in reversed(self.clients):
client.close()
self.clients.clear()
+103 -76
View File
@@ -1,82 +1,109 @@
<?php
// Run from the production application root. All credential output is private.
require getcwd() . '/vendor/autoload.php';
$app = require getcwd() . '/bootstrap/app.php';
$app->make(Illuminate\Contracts\Console\Kernel::class)->bootstrap();
use App\Models\Server;
use App\Models\ServerGroup;
use App\Models\ServerMachine;
use App\Models\User;
// Run only in an authorized target environment. --help never boots the app.
require __DIR__ . '/operations.php';
use App\Models\{Server,ServerGroup,ServerMachine,User};
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
$opts = getopt('', ['key:', 'name:', 'relay-host:', 'relay-port:', 'listen-port:', 'tls-domain:', 'backup:']);
foreach (['key', 'name', 'relay-host', 'relay-port', 'listen-port', 'tls-domain', 'backup'] as $key) {
if (empty($opts[$key])) throw new RuntimeException("Missing --$key");
}
if (!preg_match('/^[a-z0-9-]+$/', $opts['key'])) throw new RuntimeException('Invalid key');
foreach (['relay-port', 'listen-port'] as $key) {
if (!ctype_digit((string)$opts[$key]) || $opts[$key] < 1024 || $opts[$key] > 65535) throw new RuntimeException('Invalid port');
}
$dir = rtrim($opts['backup'], '/');
umask(0077);
if (!is_dir($dir) && !mkdir($dir, 0700, true)) throw new RuntimeException('Backup creation failed');
if (is_file("$dir/manifest.json")) {
$manifest = json_decode(file_get_contents("$dir/manifest.json"), true, flags: JSON_THROW_ON_ERROR);
if ($manifest['key'] !== $opts['key']) throw new RuntimeException('Backup belongs to another node');
echo json_encode(['already_staged' => true, 'node_id' => $manifest['node_id']]) . PHP_EOL;
$opts=getopt('', ['key:', 'name:', 'relay-host:', 'relay-port:', 'listen-port:', 'tls-domain:', 'panel-url:', 'backup:', 'help']);
if (isset($opts['help'])) {
echo "--key=KEY --name=NAME --relay-host=HOST --relay-port=PORT --listen-port=PORT --tls-domain=DOMAIN --panel-url=HTTPS_URL --backup=DIR\n";
exit;
}
if (ServerMachine::where('name', 'dpl-' . $opts['key'])->exists() || Server::where('name', $opts['name'])->exists()) {
throw new RuntimeException('Existing resources found without this backup manifest');
try {
foreach (['key','name','relay-host','relay-port','listen-port','tls-domain','panel-url','backup'] as $key) {
if (!isset($opts[$key]) || !is_string($opts[$key]) || $opts[$key]==='') throw new RuntimeException('Missing required stage option');
}
if (!preg_match('/^[a-z0-9-]+$/D',$opts['key'])) throw new RuntimeException('Invalid deployment key');
foreach (['relay-port','listen-port'] as $key) {
if (!ctype_digit($opts[$key]) || (int)$opts[$key]<1024 || (int)$opts[$key]>65535) throw new RuntimeException('Invalid port');
$opts[$key]=(int)$opts[$key];
}
foreach (['relay-host','tls-domain'] as $key) {
if (!preg_match('/^[a-z0-9][a-z0-9.-]*\.[a-z]{2,}$/Di',$opts[$key])) throw new RuntimeException('Explicit hostname required');
}
$url=parse_url($opts['panel-url']);
if (!is_array($url) || ($url['scheme']??'')!=='https' || empty($url['host']) || isset($url['user']) || isset($url['pass']) || isset($url['query']) || isset($url['fragment'])) {
throw new RuntimeException('Explicit HTTPS panel URL without credentials/query required');
}
$dir=rtrim($opts['backup'],'/');
if (!str_starts_with($dir,'/') || is_link($dir)) throw new RuntimeException('Absolute private backup directory required');
umask(0077);
if (!is_dir($dir) && !mkdir($dir,0700,true)) throw new RuntimeException('Cannot create backup directory');
if ((fileperms($dir)&0077)!==0) throw new RuntimeException('Backup directory must be private');
$parameters=$opts;unset($parameters['backup']);ksort($parameters);
DplOnboarding\boot();
$m=DplOnboarding\locked($dir,function () use ($dir,$parameters) {
$path=$dir.'/manifest.json';
if (is_file($path)) {
$m=DplOnboarding\manifest($dir);
if (($m['parameters']??null)!==$parameters) throw new RuntimeException('Existing manifest has different/legacy parameters; no automatic adoption');
$node=Server::findOrFail($m['node_id']);$qa=User::findOrFail($m['test_user_id']);
$machine=ServerMachine::findOrFail($m['machine_id']);
if ((int)$node->machine_id!==$machine->id || $machine->name!=='dpl-'.$parameters['key'] ||
$node->host!==$parameters['relay-host'] || (int)$node->port!==$parameters['relay-port'] ||
(int)$node->server_port!==$parameters['listen-port'] || $node->type!=='anytls' ||
($node->protocol_settings['tls']['server_name']??null)!==$parameters['tls-domain'] ||
(int)$qa->group_id!==$m['group_id']) throw new RuntimeException('Staged resources drifted');
if (is_file($dir.'/promotion-journal.json') || is_file($dir.'/promoted.json')) throw new RuntimeException('Node already promoted; staging cannot regenerate credentials');
return $m;
}
return DB::transaction(function () use ($parameters,$path,$dir) {
if (ServerMachine::where('name','dpl-'.$parameters['key'])->exists() || Server::where('name',$parameters['name'])->exists() ||
Server::where('host',$parameters['relay-host'])->where('port',(string)$parameters['relay-port'])->exists() ||
ServerGroup::where('name','dpl 接入验收 '.$parameters['key'])->exists()) {
throw new RuntimeException('Existing resource/relay tuple without matching manifest; refusing takeover');
}
DplOnboarding\writeJson($dir.'/before.json',[
'server_ids'=>Server::orderBy('id')->pluck('id')->all(),
'machine_ids'=>ServerMachine::orderBy('id')->pluck('id')->all(),
'group_ids'=>ServerGroup::orderBy('id')->pluck('id')->all(),
]);
$group=new ServerGroup();$group->name='dpl 接入验收 '.$parameters['key'];$group->save();
$machine=ServerMachine::create(['name'=>'dpl-'.$parameters['key'],
'notes'=>'Independent AnyTLS service; existing XrayR preserved','is_active'=>true,'token'=>ServerMachine::generateToken()]);
$node=Server::create([
'name'=>$parameters['name'],'type'=>'anytls','host'=>$parameters['relay-host'],
'port'=>(string)$parameters['relay-port'],'server_port'=>(string)$parameters['listen-port'],
'group_ids'=>[(string)$group->id],'route_ids'=>[],'tags'=>[],
'rate'=>1,'show'=>true,'enabled'=>true,'machine_id'=>$machine->id,'sort'=>1,
'protocol_settings'=>['tls'=>['server_name'=>$parameters['tls-domain'],'allow_insecure'=>false]],
'cert_config'=>['cert_mode'=>'file','domain'=>$parameters['tls-domain'],
'cert_file'=>'/etc/letsencrypt/live/'.$parameters['tls-domain'].'/fullchain.pem',
'key_file'=>'/etc/letsencrypt/live/'.$parameters['tls-domain'].'/privkey.pem'],
]);
$qa=new User([
'email'=>'node-qa-'.$parameters['key'].'-'.Str::lower(Str::random(8)).'@example.invalid',
'password'=>password_hash(Str::random(40),PASSWORD_BCRYPT),'uuid'=>(string)Str::uuid(),'token'=>Str::random(32),
'group_id'=>$group->id,'transfer_enable'=>104857600,'expired_at'=>time()+86400,'banned'=>0,'is_admin'=>0,
'remind_expire'=>0,'remind_traffic'=>0,'device_limit'=>2,
]);$qa->saveQuietly();
$m=['key'=>$parameters['key'],'node_id'=>$node->id,'machine_id'=>$machine->id,'group_id'=>$group->id,
'test_user_id'=>$qa->id,'parameters'=>$parameters];
// Save identities before commit. A failed/unknown commit must be inspected,
// never repeated into new resources merely because a response was lost.
DplOnboarding\writeJson($path,$m);
return $m;
},1);
});
// Recovery can regenerate missing transport files from the same staged objects.
$machine=ServerMachine::findOrFail($m['machine_id']);$qa=User::findOrFail($m['test_user_id']);
$panel=json_encode($parameters['panel-url'],JSON_THROW_ON_ERROR|JSON_UNESCAPED_SLASHES);
$config="panel:\n url: $panel\nmachine:\n machine_id: {$machine->id}\n token_env: DPL_MACHINE_TOKEN\nkernel:\n type: singbox\n config_dir: /var/lib/dpl-node/kernel\nlog:\n level: info\nruntime:\n gomemlimit: 384MiB\n gogc: 75\nnode:\n push_interval: 30\n pull_interval: 30\n";
foreach (['node-config.yml'=>$config,'node-secret.env'=>'DPL_MACHINE_TOKEN='.$machine->token."\n"] as $file=>$body) {
$path=$dir.'/'.$file;
if (is_link($path)) throw new RuntimeException('Refusing private transport symlink');
$tmp=tempnam($dir,'.private-');if ($tmp===false) throw new RuntimeException('Private file failed');
chmod($tmp,0600);
if (file_put_contents($tmp,$body)!==strlen($body) || !rename($tmp,$path)) {
if (is_file($tmp)) unlink($tmp);
throw new RuntimeException('Private file failed');
}
}
DplOnboarding\writeJson($dir.'/qa-private.json',['user_id'=>$qa->id,'uuid'=>$qa->uuid,'subscribe_token'=>$qa->token,
'host'=>$parameters['relay-host'],'port'=>$parameters['relay-port'],'sni'=>$parameters['tls-domain']]);
echo json_encode(['key'=>$m['key'],'node_id'=>$m['node_id'],'machine_id'=>$m['machine_id'],
'group_id'=>$m['group_id'],'test_user_id'=>$m['test_user_id']],JSON_THROW_ON_ERROR).PHP_EOL;
} catch (Throwable $e) {
$reason=get_class($e)===RuntimeException::class ? $e->getMessage() : 'Inspect manifest/DB state before retrying';
fwrite(STDERR,'Staging stopped: '.$reason.PHP_EOL);exit(1);
}
file_put_contents("$dir/before.json", json_encode([
'servers' => DB::table('v2_server')->get(),
'groups' => DB::table('v2_server_group')->get(),
'machines' => DB::table('v2_server_machine')->get(),
], JSON_THROW_ON_ERROR));
$manifest = DB::transaction(function () use ($opts) {
$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(),
]);
$node = Server::create([
'name' => $opts['name'], 'type' => 'anytls', 'host' => $opts['relay-host'],
'port' => (string)$opts['relay-port'], 'server_port' => (string)$opts['listen-port'],
'group_ids' => [(string)$group->id], 'route_ids' => [], 'tags' => [],
'rate' => 1, 'show' => true, 'enabled' => true, 'machine_id' => $machine->id, 'sort' => 1,
'protocol_settings' => ['tls' => ['server_name' => $opts['tls-domain'], 'allow_insecure' => false]],
'cert_config' => [
'cert_mode' => 'file', 'domain' => $opts['tls-domain'],
'cert_file' => '/etc/letsencrypt/live/' . $opts['tls-domain'] . '/fullchain.pem',
'key_file' => '/etc/letsencrypt/live/' . $opts['tls-domain'] . '/privkey.pem',
],
]);
$user = new User([
'email' => 'node-qa-' . $opts['key'] . '-' . Str::lower(Str::random(8)) . '@example.invalid',
'password' => password_hash(Str::random(40), PASSWORD_BCRYPT),
'uuid' => (string)Str::uuid(), 'token' => Str::random(32),
'group_id' => $group->id, 'transfer_enable' => 104857600,
'expired_at' => time() + 86400, 'banned' => 0, 'is_admin' => 0,
'remind_expire' => 0, 'remind_traffic' => 0, 'device_limit' => 2,
]);
$user->saveQuietly();
return ['key' => $opts['key'], 'node_id' => $node->id, 'machine_id' => $machine->id,
'group_id' => $group->id, 'test_user_id' => $user->id];
});
file_put_contents("$dir/manifest.json", json_encode($manifest, JSON_THROW_ON_ERROR));
$machine = ServerMachine::findOrFail($manifest['machine_id']);
$user = User::findOrFail($manifest['test_user_id']);
$config = "panel:\n url: \"https://dp-link.net\"\nmachine:\n machine_id: {$machine->id}\n token_env: DPL_MACHINE_TOKEN\nkernel:\n type: singbox\n config_dir: /var/lib/dpl-node/kernel\nlog:\n level: info\nruntime:\n gomemlimit: 384MiB\n gogc: 75\nnode:\n push_interval: 30\n pull_interval: 30\n";
file_put_contents("$dir/node-config.yml", $config);
file_put_contents("$dir/node-secret.env", 'DPL_MACHINE_TOKEN=' . $machine->token . "\n");
file_put_contents("$dir/qa-private.json", json_encode([
'user_id' => $user->id, 'uuid' => $user->uuid, 'subscribe_token' => $user->token,
'host' => $opts['relay-host'], 'port' => (int)$opts['relay-port'], 'sni' => $opts['tls-domain'],
], JSON_THROW_ON_ERROR));
echo json_encode($manifest, JSON_UNESCAPED_UNICODE) . PHP_EOL;
+245 -58
View File
@@ -1,72 +1,259 @@
#!/usr/bin/env python3
"""Run an isolated SOCKS client with strict TLS; never print QA credentials."""
"""Validate private subscriptions; network execution requires explicit --run.
For a formal multi-node subscription use a private --expectations JSON array:
[{"tag": "exact outbound tag", "host": "relay.example", "port": 12345,
"sni": "node.example", "uuid": "private password", "expected_exit": "192.0.2.1",
"expected_country": "JP"}]. Never print credentials or the subscription.
"""
import argparse
import copy
import ipaddress
import json
import os
import pathlib
from pathlib import Path
import shutil
import socket
import ssl
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)
class VerificationError(Exception):
pass
def require(condition, message):
if not condition:
raise VerificationError(message)
def read_private(path):
p = Path(path)
require(p.is_file() and not p.is_symlink(), 'Private input must be a regular file')
require(p.stat().st_mode & 0o077 == 0, 'Private input must have no group/other permissions')
return json.loads(p.read_text())
def validate(config, expectations, exact=True):
require(isinstance(config, dict) and isinstance(config.get('outbounds'), list), 'Missing outbounds')
all_tags = [o.get('tag') for o in config['outbounds'] if isinstance(o, dict)]
require(len(all_tags) == len(config['outbounds']) and all(isinstance(t, str) and t for t in all_tags), 'Each outbound needs a tag')
require(len(set(all_tags)) == len(all_tags), 'Duplicate outbound tags')
nodes = {o['tag']: o for o in config['outbounds'] if o.get('type') == 'anytls'}
require(isinstance(expectations, list) and expectations, 'Nonempty expectations required')
selected = []
for spec in expectations:
require(isinstance(spec, dict), 'Invalid expectation')
for key in ['tag', 'host', 'sni', 'uuid', 'expected_exit', 'expected_country']:
require(isinstance(spec.get(key), str) and bool(spec[key]), 'Expectation missing required field')
require(isinstance(spec.get('port'), int) and not isinstance(spec['port'], bool) and 1 <= spec['port'] <= 65535, 'Invalid relay port')
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))
ipaddress.ip_address(spec['expected_exit'])
except ValueError as exc:
raise VerificationError('Invalid expected exit IP') from exc
require(len(spec['expected_country']) == 2 and spec['expected_country'].isalpha() and spec['expected_country'].isupper(), 'Expected country must be two uppercase letters')
require(spec.get('verification', 'full') in ('full', 'tls'), 'Unsupported verification mode')
tag = spec['tag']
require(tag in nodes and tag not in selected, 'Missing/duplicate selected node')
node = nodes[tag]
tls = node.get('tls') or {}
require(tls.get('enabled') is True and tls.get('insecure') is False, 'Strict TLS must be explicit')
require(node.get('server') == spec['host'] and node.get('server_port') == spec['port'], 'Relay endpoint mismatch')
require(tls.get('server_name') == spec['sni'], 'SNI mismatch')
require(node.get('password') == spec['uuid'], 'Subscription password mismatch')
selected.append(tag)
if exact:
require(set(selected) == set(nodes), 'Expectations must cover every AnyTLS node exactly')
return selected
def probe_config(config, spec, port):
result = copy.deepcopy(config)
result['inbounds'] = [{'type': 'mixed', 'listen': '127.0.0.1', 'listen_port': port}]
result['log'] = {'level': 'error'}
# Preserve DNS, remote rulesets and all original outbounds. Only the two
# diagnostic destinations are pinned; ordinary subscription routing remains.
route = result.setdefault('route', {})
rules = route.setdefault('rules', [])
require(isinstance(rules, list), 'Invalid route rules')
rules.insert(0, {'domain': ['api.ipify.org', 'www.cloudflare.com'],
'action': 'route', 'outbound': spec['tag']})
return result
def stop(proc):
if proc is None or proc.poll() is not None:
return
proc.terminate()
try:
proc.wait(timeout=5)
except subprocess.TimeoutExpired:
proc.kill()
proc.wait(timeout=5)
def run_node(config, spec, binary, port, diagnostic_dir):
require(1024 <= port <= 65535, 'Invalid local SOCKS port')
with socket.socket() as free:
try:
free.bind(('127.0.0.1', port))
except OSError as exc:
raise VerificationError('Local SOCKS port is occupied') from exc
with tempfile.TemporaryDirectory(prefix='dpl-client-', dir=diagnostic_dir) as tmp:
temporary = Path(tmp)
path = temporary / 'client.json'
path.write_text(json.dumps(probe_config(config, spec, port)))
path.chmod(0o600)
env = dict(os.environ, GOMEMLIMIT='64MiB', GOGC='75')
proc = None
log_path = temporary / 'client.log'
try:
with log_path.open('wb') as log:
subprocess.run([binary, 'check', '-c', str(path)], env=env,
cwd=tmp, stdout=log, stderr=log, check=True, timeout=30)
proc = subprocess.Popen([binary, 'run', '-c', str(path)], env=env,
cwd=tmp, stdout=log, stderr=log)
ready = False
for _ in range(100):
require(proc.poll() is None, 'Client exited during startup')
try:
with socket.create_connection(('127.0.0.1', port), 0.1):
ready = True
break
except OSError:
time.sleep(0.1)
require(ready, 'Client startup timed out')
command = ['curl', '-q', '--fail', '--silent', '--show-error', '--max-time', '30',
'--socks5-hostname', f'127.0.0.1:{port}', '--noproxy', '']
ip = subprocess.run(command + ['https://api.ipify.org'], capture_output=True,
text=True, check=True, timeout=35).stdout.strip()
require(ipaddress.ip_address(ip) == ipaddress.ip_address(spec['expected_exit']), 'Unexpected exit IP')
response = subprocess.run(command + ['https://www.cloudflare.com/cdn-cgi/trace'],
capture_output=True, text=True, check=True, timeout=35)
trace = dict(line.split('=', 1) for line in response.stdout.splitlines() if '=' in line)
require(trace.get('ip') == ip, 'Second exit check mismatch')
require(trace.get('loc') == spec['expected_country'], 'Exit country mismatch')
require(trace.get('tls', '').startswith('TLSv'), 'Target HTTPS TLS not observed')
return {'tag': spec['tag'], 'strict_tls': True, 'exit_ip': ip,
'country': trace['loc'], 'https_tls': trace['tls'], 'live': True,
'relay': spec['host'], 'relay_port': spec['port'], 'sni': spec['sni']}
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}')
# Logs may contain private config context; retain only in private task directory.
stop(proc)
if log_path.exists():
fd, name = tempfile.mkstemp(prefix='client-failure-', suffix='.log', dir=diagnostic_dir)
os.close(fd)
failure = Path(name)
shutil.copyfile(log_path, failure)
failure.chmod(0o600)
raise
finally:
proc.terminate()
try:
proc.wait(timeout=5)
except subprocess.TimeoutExpired:
proc.kill()
proc.wait()
stop(proc)
def run_tls(spec):
"""Reach the relay and validate the node certificate; no exit/traffic claim."""
context = ssl.create_default_context()
with socket.create_connection((spec['host'], spec['port']), timeout=10) as stream:
with context.wrap_socket(stream, server_hostname=spec['sni']) as secure:
protocol = secure.version()
require(protocol in ('TLSv1.2', 'TLSv1.3'), 'Unexpected TLS protocol')
return {'tag': spec['tag'], 'strict_tls': True, 'live': True,
'relay': spec['host'], 'relay_port': spec['port'], 'sni': spec['sni'],
'verification': 'tls', 'node_tls': protocol}
def run_specs(config, specs, binary, port, folder):
return [run_tls(spec) if spec.get('verification', 'full') == 'tls'
else run_node(config, spec, binary, port, folder) for spec in specs]
def write_report(path, report):
destination = Path(path)
require(destination.parent.is_dir() and destination.parent.stat().st_mode & 0o077 == 0,
'Report directory must be private')
require(not destination.is_symlink(), 'Refusing report symlink')
with tempfile.NamedTemporaryFile(mode='w', dir=destination.parent, delete=False) as stream:
temporary = Path(stream.name)
try:
os.chmod(temporary, 0o600)
json.dump(report, stream, ensure_ascii=False)
stream.flush()
os.fsync(stream.fileno())
os.replace(temporary, destination)
finally:
if temporary.exists():
temporary.unlink()
def main():
parser = argparse.ArgumentParser(description=__doc__)
sources = parser.add_mutually_exclusive_group(required=True)
sources.add_argument('--qa')
sources.add_argument('--expectations')
parser.add_argument('--subscription', required=True)
parser.add_argument('--binary')
parser.add_argument('--expected-exit')
parser.add_argument('--expected-country')
parser.add_argument('--target-tag')
parser.add_argument('--report', help='Private JSON result file; required for --run')
parser.add_argument('--port', type=int, default=19080)
execution = parser.add_mutually_exclusive_group()
execution.add_argument('--run', action='store_true')
execution.add_argument('--validate-only', action='store_true')
args = parser.parse_args()
os.umask(0o077)
try:
require(not args.run or args.report, '--run requires a private --report destination')
if args.report:
destination = Path(args.report)
inputs = [args.subscription, args.qa, args.expectations]
require(all(destination.resolve() != Path(item).resolve() for item in inputs if item), 'Report must not overwrite a private input')
require(destination.parent.is_dir() and destination.parent.stat().st_mode & 0o077 == 0 and not destination.is_symlink(), 'Private regular report destination required')
if args.report:
write_report(args.report, {'state': 'verification_pending', 'verified_at': None})
config = read_private(args.subscription)
qa_user_id = None
source = args.expectations or args.qa
if args.expectations:
require(not any([args.expected_exit, args.expected_country, args.target_tag]), 'Put each node expectation in the private expectations file')
specs = read_private(args.expectations)
else:
qa = read_private(args.qa)
qa_user_id = qa.get('user_id')
require(args.expected_exit and args.expected_country, 'QA requires explicit expected-exit and expected-country')
candidates = [n for n in config.get('outbounds', []) if n.get('type') == 'anytls'
and n.get('server') == qa.get('host') and n.get('server_port') == qa.get('port')
and (not args.target_tag or n.get('tag') == args.target_tag)]
require(len(candidates) == 1, 'QA target ambiguous/missing; supply exact target-tag')
specs = [{'tag': candidates[0]['tag'], 'host': qa.get('host'), 'port': qa.get('port'),
'sni': qa.get('sni'), 'uuid': qa.get('uuid'), 'expected_exit': args.expected_exit,
'expected_country': args.expected_country}]
require(bool(args.expectations) or all(s.get('verification', 'full') == 'full' for s in specs), 'Isolated QA requires full verification')
tags = validate(config, specs, exact=bool(args.expectations))
results = []
if args.run:
require(args.binary and Path(args.binary).is_file(), 'Explicit existing client binary required')
binary = str(Path(args.binary).resolve())
folder = Path(source).resolve().parent
require(folder.stat().st_mode & 0o077 == 0, 'Live diagnostics directory must be private')
results = run_specs(config, specs, binary, args.port, str(folder))
report = {'state': 'live_verified' if args.run else 'structure_validated',
'verified_at': int(time.time()) if args.run else None,
'qa_user_id': qa_user_id, 'selected_nodes': tags, 'results': results,
'scope': 'Full subscription retained; only diagnostic destination routes pinned. No traffic/account/GUI acceptance implied.'}
if args.report:
write_report(args.report, report)
print(json.dumps(report, ensure_ascii=False))
return 0
except (Exception, KeyboardInterrupt) as exc:
# No traceback or subprocess stderr: either can contain credentials.
message = str(exc) if isinstance(exc, VerificationError) else 'Verification failed; inspect protected diagnostics'
print(json.dumps({'state': 'failed', 'reason': message}), file=__import__('sys').stderr)
return 1
if __name__ == '__main__':
raise SystemExit(main())