Files

565 lines
24 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import json, os, socket, subprocess, threading, time, httpx, hashlib, hmac, base64, urllib.parse, secrets
from fastapi import FastAPI, HTTPException
from fastapi.responses import HTMLResponse, FileResponse, JSONResponse, RedirectResponse
from pydantic import BaseModel
from typing import Optional, List, Any
CONFIG_PATH = os.environ.get("CONFIG_PATH", "/data/config.json")
LOG_PATH = os.environ.get("LOG_PATH", "/data/logs.jsonl")
LOG_RETENTION = 24 * 3600 # 日志只保留最近24小时, 超过自动删除
STATUS = {"ipv6": None, "easytier": None, "nps": None, "last_run": None, "connected": [], "log": []}
lock = threading.Lock()
def _save_log_locked():
"""(须持锁) 日志落盘: 只写最近24小时, 超期条目随写入自动删除"""
cutoff = time.time() - LOG_RETENTION
STATUS["log"] = [e for e in STATUS["log"] if e.get("ts", 0) >= cutoff]
try:
os.makedirs(os.path.dirname(LOG_PATH), exist_ok=True)
tmp = LOG_PATH + ".tmp"
with open(tmp, "w", encoding="utf-8") as f:
for e in STATUS["log"]:
f.write(json.dumps(e, ensure_ascii=False) + "\n")
os.replace(tmp, LOG_PATH)
except Exception:
pass
def load_log_from_disk():
"""启动时恢复最近24小时日志; 更早的直接从磁盘删除"""
with lock:
try:
with open(LOG_PATH, encoding="utf-8") as f:
for line in f:
line = line.strip()
if not line:
continue
try:
e = json.loads(line)
except Exception:
continue
if e.get("msg") and e.get("ts"):
STATUS["log"].append(e)
except FileNotFoundError:
pass
_save_log_locked()
def log(msg, level="info", dedup=0):
if level not in ("info", "warn", "error"):
level = "info"
with lock:
now = time.time()
if dedup:
for e in reversed(STATUS["log"][-100:]):
if e["msg"] == msg and e.get("level", "info") == level:
if now - e.get("ts", 0) < dedup:
return
break
STATUS["log"].append({"t": time.strftime("%Y-%m-%d %H:%M:%S"), "ts": now, "level": level, "msg": msg})
_save_log_locked() # 保留最近24小时, 超期自动删除(内存+磁盘)
def load_config():
try:
with open(CONFIG_PATH) as f:
return json.load(f)
except Exception:
return {}
def save_config(cfg):
os.makedirs(os.path.dirname(CONFIG_PATH), exist_ok=True)
with open(CONFIG_PATH, "w") as f:
json.dump(cfg, f, indent=2, ensure_ascii=False)
def get_domains(cfg):
"""返回去重去空的域名列表; 兼容旧版单域名 domain 字段自动迁移"""
ds = cfg.get("domains")
if not ds and cfg.get("domain"):
ds = [cfg["domain"]]
out = []
for d in (ds or []):
d = str(d).strip().rstrip(".")
if d and d not in out:
out.append(d)
return out
LOGIN_HTML = """<!doctype html><html lang="zh-cn"><head><meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>登录 · IPv6 / 组网 / NPS 域名路由</title>
<style>
*{box-sizing:border-box}body{margin:0;min-height:100vh;display:flex;align-items:center;justify-content:center;background:#f0f4f9;font-family:-apple-system,"Segoe UI","Microsoft YaHei",sans-serif;color:#202124}
.card{width:min(380px,92vw);background:#fff;border-radius:16px;padding:32px 28px;box-shadow:0 4px 24px rgba(0,0,0,.08)}
h1{font-size:18px;margin:0 0 6px;text-align:center}
p.sub{color:#5f6368;font-size:13px;text-align:center;margin:0 0 18px}
input{width:100%;padding:11px 14px;font-size:14px;border:1px solid #dadce0;border-radius:8px;outline:none;letter-spacing:1px}
input:focus{border-color:#1a73e8;box-shadow:0 0 0 2px rgba(26,115,232,.15)}
.row{display:flex;gap:8px;margin-top:12px}
button.eye{flex:0 0 46px;background:#f1f3f4;border:1px solid #dadce0;border-radius:8px;cursor:pointer;font-size:15px}
button.go{flex:1;background:#1a73e8;color:#fff;border:0;border-radius:8px;padding:11px;font-size:14px;font-weight:600;cursor:pointer}
button.go:hover{background:#1765cc}
.err{color:#c5221f;font-size:12.5px;margin-top:10px;text-align:center;min-height:16px}
.hint{color:#5f6368;font-size:11.5px;margin-top:14px;line-height:1.7;background:#f8f9fa;border-radius:8px;padding:9px 11px}
kbd{background:#e8eaed;border-radius:4px;padding:1px 5px;font-size:10.5px}
</style></head><body>
<div class="card">
<h1>\U0001f512 \u9700\u8981 TOKEN \u624d\u80fd\u8bbf\u95ee</h1>
<p class="sub">IPv6 / \u7ec4\u7f51 / NPS \u57df\u540d\u8def\u7531\u81ea\u52a8\u68c0\u6d4b</p>
<input id="t" type="password" placeholder="\u8bf7\u8f93\u5165\u8bbf\u95ee TOKEN" autofocus autocomplete="off">
<div class="row">
<button class="eye" onclick="tg()" title="\u663e\u793a/\u9690\u85cf">\U0001f441\ufe0f</button>
<button class="go" onclick="go()">\u767b \u5f55</button>
</div>
<div class="err" id="e"></div>
<div class="hint">TOKEN 固定不变,见 <kbd>data/config.json</kbd> 的 <kbd>access_token</kbd>;支持 <kbd>?token=</kbd> 快捷登录。</div>
</div>
<script>
var pv=false;
function tg(){var i=document.getElementById('t');pv=!pv;i.type=pv?'text':'password';}
async function go(){
var v=document.getElementById('t').value.trim();
if(!v){document.getElementById('e').textContent='\u8bf7\u8f93\u5165 TOKEN';return;}
var r=await fetch('/api/login',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({token:v})});
if(r.ok){location.href='/';}
else{var d=await r.json().catch(function(){return{};});document.getElementById('e').textContent=d.error||'TOKEN 无效';}
}
document.getElementById('t').addEventListener('keydown',function(e){if(e.key==='Enter')go();});
</script></body></html>"""
def ensure_token():
"""无 access_token 则生成一次; TOKEN 固定不变, 永不轮换/过期"""
cfg = load_config()
if not cfg.get("access_token"):
cfg["access_token"] = secrets.token_urlsafe(24)
save_config(cfg)
print(f"[auth] TOKEN 已生成(固定不变): {cfg['access_token']}", flush=True)
log("TOKEN 已生成(固定不变), 见 data/config.json")
if "token_expires_at" in cfg:
cfg.pop("token_expires_at", None) # 清理旧版30天有效期字段
save_config(cfg)
return cfg["access_token"]
def _read_host_if_inet6():
for p in ("/host/proc/1/net/if_inet6", "/host/proc/net/if_inet6",
"/proc/1/net/if_inet6", "/proc/net/if_inet6"):
try:
if os.path.exists(p):
with open(p) as f:
return f.read()
except Exception:
continue
return ""
def detect_ipv6():
# returns (ok, address)
# 桥接模式优先读宿主 if_inet6,保证与 host 模式一致
try:
txt = _read_host_if_inet6()
for line in (txt or "").splitlines():
parts = line.split()
if len(parts) >= 6:
raw, scope = parts[0], parts[3]
if scope == "00" and not raw.startswith("fe80") and raw != "00000000000000000000000000000001":
addr = ":".join(raw[i:i+4] for i in range(0, 32, 4))
return True, addr
except Exception:
pass
try:
out = subprocess.check_output(["ip", "-6", "addr", "show", "scope", "global"], text=True, stderr=subprocess.DEVNULL)
for line in out.splitlines():
line = line.strip()
if line.startswith("inet6"):
addr = line.split()[1].split("/")[0]
# skip link-local / unique local? keep global
if not addr.startswith("fe80") and not addr.startswith("fc") and not addr.startswith("fd"):
return True, addr
except Exception:
pass
# fallback: socket
try:
s = socket.socket(socket.AF_INET6, socket.SOCK_DGRAM)
s.connect(("2001:4860:4860::8888", 80))
addr = s.getsockname()[0]
s.close()
if addr and ":" in addr:
return True, addr
except Exception:
pass
return False, None
def ping_ok(host, timeout=2):
try:
h = (host or "").strip()
if h.count(":") == 1 and not h.startswith("["):
h = h.split(":")[0]
import subprocess, socket
# ping (ICMP)
r = subprocess.run(["ping", "-c", "1", "-W", str(timeout), h],
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, timeout=timeout + 2)
if r.returncode == 0:
return True
# fallback: TCP connect on common ports
for port in (80, 443, 53, 22):
try:
with socket.create_connection((h, port), timeout=timeout):
return True
except Exception:
pass
# fallback: ARP cache (local subnet hosts may block ICMP)
try:
out = subprocess.check_output(["ip", "neigh", "show", h], text=True, timeout=2, stderr=subprocess.DEVNULL)
if h in out and ("REACHABLE" in out or "STALE" in out or "DELAY" in out or "PERMANENT" in out):
return True
except Exception:
pass
return False
except Exception:
return False
def check_tcp(host, port, timeout=5):
try:
import socket
infos = socket.getaddrinfo(host, port, type=socket.SOCK_STREAM)
for fam, typ, proto, canon, sockaddr in infos:
try:
with socket.create_connection(sockaddr, timeout=timeout):
return True
except Exception:
continue
return False
except Exception:
return False
def split_domain(full):
"""拆 subdomain + 主域名: www.example.com -> (www, example.com); example.com -> (@, example.com)"""
parts = (full or "").strip().strip(".").split(".")
if len(parts) <= 2:
return "@", ".".join(parts)
return ".".join(parts[:-2]), ".".join(parts[-2:])
def tc3_request(action, payload, secret_id, secret_key, host="dnspod.tencentcloudapi.com", service="dnspod", version="2021-03-23"):
"""腾讯云 TC3-HMAC-SHA256 签名请求"""
import datetime
body = json.dumps(payload, ensure_ascii=False, separators=(",", ":"))
ts = int(time.time())
dt = datetime.datetime.utcfromtimestamp(ts).strftime("%Y-%m-%d")
scope = f"{dt}/{service}/tc3_request"
payload_hash = hashlib.sha256(body.encode("utf-8")).hexdigest()
canonical_headers = f"content-type:application/json\nhost:{host}\n"
signed_headers = "content-type;host"
canonical_req = f"POST\n/\n\n{canonical_headers}\n{signed_headers}\n{payload_hash}"
str_to_sign = f"TC3-HMAC-SHA256\n{ts}\n{scope}\n{hashlib.sha256(canonical_req.encode('utf-8')).hexdigest()}"
def _hmac(key, msg):
return hmac.new(key, msg.encode("utf-8"), hashlib.sha256).digest()
k_date = _hmac(("TC3" + secret_key).encode("utf-8"), dt)
k_service = hmac.new(k_date, service.encode("utf-8"), hashlib.sha256).digest()
k_sign = hmac.new(k_service, b"tc3_request", hashlib.sha256).digest()
sig = hmac.new(k_sign, str_to_sign.encode("utf-8"), hashlib.sha256).hexdigest()
headers = {
"Authorization": f"TC3-HMAC-SHA256 Credential={secret_id}/{scope}, SignedHeaders={signed_headers}, Signature={sig}",
"Content-Type": "application/json",
"Host": host,
"X-TC-Action": action,
"X-TC-Version": version,
"X-TC-Timestamp": str(ts),
}
r = httpx.post(f"https://{host}/", headers=headers, content=body.encode("utf-8"), timeout=15)
return r.json()
def update_dns_tencent(domain_full, ip, secret_id, secret_key, rtype="A"):
try:
sub, main = split_domain(domain_full)
data = tc3_request("DescribeRecordList", {"Domain": main, "Subdomain": sub, "RecordType": rtype}, secret_id, secret_key)
resp = data.get("Response", {})
if "Error" in resp:
if resp["Error"].get("Code") == "ResourceNotFound.NoDataOfRecord":
recs = [] # 该类型记录尚不存在,走创建流程
else:
log(f"Tencent Describe error: {resp['Error']}", level="error", dedup=300)
return False
else:
recs = resp.get("RecordList", []) or []
hit = next((x for x in recs if x.get("Name") == sub and x.get("Type") == rtype), recs[0] if recs else None)
if hit and hit.get("Value") == ip:
return True # 已是最新,无需更新
if hit:
m = tc3_request("ModifyRecord", {
"Domain": main, "SubDomain": sub, "RecordType": rtype,
"RecordLine": "默认", "Value": ip, "RecordId": hit["RecordId"], "TTL": 600,
}, secret_id, secret_key)
if "Error" in m.get("Response", {}):
log(f"Tencent Modify error: {m['Response']['Error']}", level="error", dedup=300)
return False
return True
c = tc3_request("CreateRecord", {
"Domain": main, "SubDomain": sub, "RecordType": rtype,
"RecordLine": "默认", "Value": ip, "TTL": 600,
}, secret_id, secret_key)
if "Error" in c.get("Response", {}):
log(f"Tencent Create error: {c['Response']['Error']}", level="error", dedup=300)
return False
return True
except Exception as e:
log(f"Tencent DNS error: {e}", level="error", dedup=300)
return False
def update_dns_cf(domain, token, zone_id, ip, record_type="AAAA"):
headers = {"Authorization": f"Bearer {token}", "Content-Type": "application/json"}
# find record
try:
r = httpx.get(f"https://api.cloudflare.com/client/v4/zones/{zone_id}/dns_records",
headers=headers, params={"type": record_type, "name": domain}, timeout=15)
data = r.json()
recs = data.get("result", [])
if recs:
rid = recs[0]["id"]
r2 = httpx.put(f"https://api.cloudflare.com/client/v4/zones/{zone_id}/dns_records/{rid}",
headers=headers, json={"type": record_type, "name": domain, "content": ip, "ttl": 120, "proxied": False}, timeout=15)
return r2.json().get("success", False)
else:
r2 = httpx.post(f"https://api.cloudflare.com/client/v4/zones/{zone_id}/dns_records",
headers=headers, json={"type": record_type, "name": domain, "content": ip, "ttl": 120, "proxied": False}, timeout=15)
return r2.json().get("success", False)
except Exception as e:
log(f"DNS update error: {e}", level="error", dedup=300)
return False
def update_dns(cfg, domain, ip, rtype=None):
rtype = "AAAA" if ":" in ip else "A" # 按 IP 族定记录类型(webhook 也用它)
provider = cfg.get("dns_provider") or "cloudflare"
if provider == "cloudflare":
token = cfg.get("cf_token"); zone = cfg.get("cf_zone")
if not (token and zone):
log("Cloudflare creds missing", level="warn", dedup=300); return False
return update_dns_cf(domain, token, zone, ip, "AAAA" if ":" in ip else "A")
if provider == "webhook":
url = cfg.get("webhook_url")
if not url:
log("webhook url missing", level="warn", dedup=300); return False
try:
r = httpx.post(url, json={"domain": domain, "ip": ip, "type": rtype}, timeout=15)
return r.status_code < 300
except Exception as e:
log(f"webhook error: {e}", level="error", dedup=300); return False
if provider == "tencent":
sid = cfg.get("tencent_secret_id"); skey = cfg.get("tencent_secret_key")
if not (sid and skey):
log("Tencent creds missing", level="warn", dedup=300); return False
return update_dns_tencent(domain, ip, sid, skey, "AAAA" if ":" in ip else "A")
# aliyun / huawei: store creds; auto-update not fully implemented -> fallback log
log(f"DNS provider {provider}: auto-update not implemented, please use webhook, cloudflare or tencent", level="warn", dedup=300)
return False
def run_check():
cfg = load_config()
connected = []
domains = get_domains(cfg) # 支持多个域名, 每轮逐个解析
interval = cfg.get("interval", 60)
s = [] # 本轮汇总, 末尾只写一条日志
# 1. IPv6
ok6, ip6 = detect_ipv6()
STATUS["ipv6"] = {"ok": ok6, "ip": ip6}
if not ok6:
s.append("✗ IPv6 不支持")
else:
if not domains:
s.append(f"✓ IPv6 {ip6} (未配置域名)")
else:
s.append(f"✓ IPv6 {ip6}")
for d in domains:
if update_dns(cfg, d, ip6):
connected.append({"type": "ipv6", "target": ip6, "domain": d})
# 2. EasyTier / group network (ping 检测,无需端口) — 支持多个地址,任一可达即用
raw_et = cfg.get("easytier_host") or cfg.get("easytier_hosts") or ""
if isinstance(raw_et, list):
et_hosts = [str(x).strip() for x in raw_et if str(x).strip()]
else:
et_hosts = [x.strip() for x in str(raw_et).replace("\\n", ",").split(",") if x.strip()]
if not et_hosts:
s.append("- 组网 未配置")
else:
reachable = [h for h in et_hosts if ping_ok(h)]
unreachable = [h for h in et_hosts if h not in reachable]
STATUS["easytier"] = {"ok": bool(reachable), "hosts": et_hosts, "reachable": reachable, "unreachable": unreachable}
if not reachable:
s.append(f"✗ 组网 {', '.join(et_hosts)} 均不可达")
else:
et_host = reachable[0]
warn_suffix = (f" ✗ 不可达: {', '.join(unreachable)}" if unreachable else "")
s.append(f"✓ 组网 {et_host} 可达" + (f" (共{len(reachable)}/{len(et_hosts)}可达)" if len(et_hosts) > 1 else "") + warn_suffix)
connected.append({"type": "easytier", "target": et_host, "domain": None})
for d in domains:
if update_dns(cfg, d, et_host):
connected.append({"type": "easytier", "target": et_host, "domain": d})
# 3. NPS
nps_server = cfg.get("nps_server")
nps_vkey = cfg.get("nps_vkey")
if not nps_server:
s.append("- NPS 未配置")
else:
ok = check_tcp(nps_server.split(":")[0], int(nps_server.split(":")[1]) if ":" in nps_server else 8024)
STATUS["nps"] = {"ok": ok, "server": nps_server}
if ok:
connected.append({"type": "nps", "target": nps_server, "domain": None})
s.append(f"✓ NPS {nps_server}")
else:
s.append(f"✗ NPS {nps_server} 不可达")
with lock:
# 当前生效: 每个域名最后被更新到的目标 (即远程用户实际使用的地址)
_active = {}
for c in connected:
if c.get("domain"):
for d in str(c["domain"]).split(", "):
d = d.strip()
if d:
_active[d] = {"target": c.get("target"), "type": c.get("type")}
STATUS["connected"] = connected
STATUS["active"] = [{"domain": d, "target": v["target"], "type": v["type"]} for d, v in _active.items()]
STATUS["last_run"] = time.strftime("%Y-%m-%d %H:%M:%S")
_det_msg = " | ".join(s)
_det_level = "warn" if "✗" in _det_msg else "info"
log(_det_msg, level=_det_level) # 每轮检测只写这一条日志
class ConfigModel(BaseModel):
domains: Optional[List[str]] = None # 多个域名, 共用下方服务商凭据
interval: Optional[int] = 60
dns_provider: Optional[str] = None
# cloudflare
cf_token: Optional[str] = None
cf_zone: Optional[str] = None
# aliyun
aliyun_access_key_id: Optional[str] = None
aliyun_access_key_secret: Optional[str] = None
# tencent
tencent_secret_id: Optional[str] = None
tencent_secret_key: Optional[str] = None
# huawei
huawei_ak: Optional[str] = None
huawei_sk: Optional[str] = None
# custom webhook
webhook_url: Optional[str] = None
easytier_host: Optional[Any] = None
easytier_port: Optional[int] = None
nps_server: Optional[str] = None
nps_vkey: Optional[str] = None
app = FastAPI(title="IPv6 Domain Router")
def _auth_state(request):
"""True=已登录 / 'cookie'=需种cookie / False=未授权"""
cfg = load_config()
tok = cfg.get("access_token") or ""
if not tok:
return False
c = request.cookies.get("auth_token")
if c and hmac.compare_digest(c, tok):
return True
if request.method == "GET" and request.url.path == "/":
q = request.query_params.get("token")
if q and hmac.compare_digest(q, tok):
return "cookie"
return False
@app.middleware("http")
async def auth_gate(request, call_next):
if request.url.path == "/api/login":
return await call_next(request)
state = _auth_state(request)
if state == "cookie":
cfg = load_config()
resp = RedirectResponse(url="/", status_code=303)
resp.set_cookie("auth_token", cfg["access_token"],
max_age=365 * 86400, # 固定TOKEN, Cookie长期有效
httponly=True, samesite="lax", path="/")
return resp
if state is True:
return await call_next(request)
if request.url.path.startswith("/api/"):
return JSONResponse({"error": "\u672a\u6388\u6743\uff1a\u8bf7\u5148\u8f93\u5165 TOKEN \u767b\u5f55"}, status_code=401)
return HTMLResponse(LOGIN_HTML)
class LoginModel(BaseModel):
token: str = ""
@app.post("/api/login")
def login(m: LoginModel):
tok = ensure_token() # TOKEN 固定不变, 永不过期
if not m.token or not hmac.compare_digest(m.token, tok):
return JSONResponse({"error": "TOKEN 无效(TOKEN 固定不变,见 data/config.json)"}, status_code=401)
resp = JSONResponse({"ok": True})
resp.set_cookie("auth_token", tok, max_age=365 * 86400,
httponly=True, samesite="lax", path="/")
return resp
@app.post("/api/logout")
def logout():
resp = JSONResponse({"ok": True})
resp.delete_cookie("auth_token", path="/")
return resp
@app.get("/", response_class=HTMLResponse)
def index():
with open("/app/index.html") as f:
return f.read()
@app.get("/api/config")
def get_config():
c = load_config()
c.pop("access_token", None)
c.pop("token_expires_at", None)
return c
@app.post("/api/config")
def set_config(cfg: ConfigModel):
data = {k: v for k, v in cfg.dict().items() if v is not None}
# merge
cur = load_config()
cur.update(data)
if data.get("domains") is not None:
cur.pop("domain", None) # 旧版单域名字段,迁移到 domains 后移除
save_config(cur)
# restart scheduler
start_scheduler(cur.get("interval", 60))
return {"ok": True}
@app.get("/api/status")
def get_status():
return STATUS
@app.post("/api/check")
def check_now():
threading.Thread(target=run_check, daemon=True).start()
return {"ok": True}
scheduler_thread = None
stop_event = threading.Event()
def scheduler_loop(interval, ev):
while not ev.is_set():
run_check()
ev.wait(interval)
def start_scheduler(interval):
global scheduler_thread, stop_event
stop_event.set()
if scheduler_thread and scheduler_thread.is_alive():
scheduler_thread.join(timeout=5)
stop_event = threading.Event()
scheduler_thread = threading.Thread(target=scheduler_loop, args=(interval, stop_event), daemon=True)
scheduler_thread.start()
@app.on_event("startup")
def startup():
cfg = load_config()
load_log_from_disk() # 恢复最近24小时日志, 超期条目自动删除
ensure_token() # 无 token 则生成一次(固定不变)
start_scheduler(cfg.get("interval", 60))
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=8000)