init: IPv6/组网/NPS域名路由自动检测(多域名+固定TOKEN+日志落盘24h保留)

This commit is contained in:
3970260761 committed 2026-11-07 14:16:53 +08:00
commit 3063a52826
8 files changed
+850

No files matched your search

+8
View File
@@ -0,0 +1,8 @@
# 敏感数据(密钥明文, 绝不提交)
data/
*.log
# Python
__pycache__/
*.py[cod]
.venv/
+8
View File
@@ -0,0 +1,8 @@
FROM python:3.11-slim
WORKDIR /app
COPY requirements.txt .
RUN apt-get update && apt-get install -y --no-install-recommends iputils-ping iproute2 && rm -rf /var/lib/apt/lists/* && pip install --no-cache-dir -r requirements.txt
COPY app.py index.html ./
ENV CONFIG_PATH=/data/config.json
EXPOSE 8025
CMD ["uvicorn", "app:app", "--host", "0.0.0.0", "--port", "8025"]
+41
View File
@@ -0,0 +1,41 @@
# IPv6 / 组网 / NPS 域名路由自动检测
Docker 化单页面应用:自动判断本机 IPv6 是否可用,可用则把域名解析到 IPv6;
否则判断组网(EasyTier)地址能否连通,能连通则解析到组网地址;再不行则走 NPS 内网穿透。
页面横排三栏(配置 | 状态+已连通 | 日志),自适应全屏、无滚动条。
## 功能
- 检测优先级:IPv6 → 组网(ping,无端口)→ NPS(reachable)
- 多域名支持:多个域名共用同一套服务商凭据
- DNS 服务商:Cloudflare / 腾讯云 DNSPod / 阿里云 / 华为云 / 自定义 Webhook
- TOKEN 访问鉴权:固定值,存于 `data/config.json` 的 `access_token`,永不轮换
- 日志落盘:`data/logs.jsonl`,只保留最近 24 小时,超期自动删除
- 检测间隔可配置(秒),检测全部线路
## 部署
```bash
cp config.example.json data/config.json
# 编辑 data/config.json 填入域名与服务商密钥
docker compose up -d --build
```
访问 http://服务器IP:8025/,输入 TOKEN(见 `data/config.json` 的 `access_token`,
或容器启动日志)登录;也支持 `?token=` 快捷登录。
## 文件说明
| 文件 | 说明 |
| ---- | ---- |
| app.py | 后端(检测 / DNS 更新 / 鉴权 / 日志) |
| index.html | 前端单页面 |
| Dockerfile / docker-compose.yml | 容器化 |
| config.example.json | 配置模板(无密钥,可照抄) |
| data/ | 运行数据(config.json、logs.jsonl,**含密钥,不提交**) |
## 安全说明
- `data/` 目录(含 `config.json` 明文密钥与日志)已加入 `.gitignore`,绝不提交到仓库
- `/api/config` 接口不回传 `access_token`
+532
View File
@@ -0,0 +1,532 @@
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
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, dedup=0):
with lock:
now = time.time()
if dedup:
for e in reversed(STATUS["log"][-100:]):
if e["msg"] == msg:
if now - e.get("ts", 0) < dedup:
return
break
STATUS["log"].append({"t": time.strftime("%Y-%m-%d %H:%M:%S"), "ts": now, "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()
# 去掉可能残留的 :port
if h.count(":") == 1 and not h.startswith("["):
h = h.split(":")[0]
import subprocess
r = subprocess.run(["ping", "-c", "1", "-W", str(timeout), h],
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, timeout=timeout + 2)
return r.returncode == 0
except Exception:
return False
def check_tcp(host, port, timeout=5):
try:
with socket.create_connection((host, port), timeout=timeout):
return True
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']}", 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']}", 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']}", dedup=300)
return False
return True
except Exception as e:
log(f"Tencent DNS error: {e}", 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}", 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", 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", 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}", 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", 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", 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 不支持")
elif not domains:
s.append(f"✓ IPv6 {ip6} (未配置域名)")
else:
done, bad = [], []
for d in domains:
(done if update_dns(cfg, d, ip6) else bad).append(d)
line = f"✓ IPv6 {ip6} → {', '.join(done)}" if done else f"✗ IPv6 {ip6} DNS更新失败"
if bad:
line += f" (失败: {', '.join(bad)})"
s.append(line)
if done:
connected.append({"type": "ipv6", "target": ip6, "domain": ", ".join(done)})
# 2. EasyTier / group network (ping 检测,无需端口)
et_host = (cfg.get("easytier_host") or "").strip()
if not et_host:
s.append("- 组网 未配置")
else:
ok = ping_ok(et_host)
STATUS["easytier"] = {"ok": ok, "host": et_host}
if not ok:
s.append(f"✗ 组网 {et_host} 不可达")
elif not domains:
connected.append({"type": "easytier", "target": et_host, "domain": None})
s.append(f"✓ 组网 {et_host} 可达")
else:
done, bad = [], []
for d in domains:
(done if update_dns(cfg, d, et_host) else bad).append(d)
line = f"✓ 组网 {et_host} → {', '.join(done)}" if done else f"✗ 组网 {et_host} DNS更新失败"
if bad:
line += f" (失败: {', '.join(bad)})"
s.append(line)
if done:
connected.append({"type": "easytier", "target": et_host, "domain": ", ".join(done)})
# 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:
STATUS["connected"] = connected
STATUS["last_run"] = time.strftime("%Y-%m-%d %H:%M:%S")
log(" | ".join(s)) # 每轮检测只写这一条日志
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[str] = 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)
+18
View File
@@ -0,0 +1,18 @@
{
"interval": 60,
"dns_provider": "tencent",
"tencent_secret_id": "",
"tencent_secret_key": "",
"cf_token": "",
"cf_zone": "",
"aliyun_access_key_id": "",
"aliyun_access_key_secret": "",
"huawei_ak": "",
"huawei_sk": "",
"webhook_url": "",
"easytier_host": "",
"easytier_port": null,
"nps_server": "",
"nps_vkey": "",
"domains": ["example.com"]
}
+15
View File
@@ -0,0 +1,15 @@
services:
ipv6-router:
build: .
container_name: ipv6-domain-router
restart: always
pid: host
command: ["uvicorn", "app:app", "--host", "0.0.0.0", "--port", "8025"]
ports:
- "8025:8025"
volumes:
- ./data:/data
- /proc:/host/proc:ro
environment:
- TZ=Asia/Shanghai
- CONFIG_PATH=/data/config.json
+223
View File
@@ -0,0 +1,223 @@
<!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>
:root{--blue:#1a73e8;--bg:#f0f4f9;--card:#fff;--txt:#202124;--muted:#5f6368;--ok:#e6f4ea;--ok-t:#137333;--bad:#fce8e6;--bad-t:#c5221f}
*{box-sizing:border-box}
html,body{height:100%}
body{font-family:system-ui,-apple-system,"PingFang SC","Microsoft YaHei",sans-serif;margin:0;padding:12px 16px;background:var(--bg);color:var(--txt);height:100vh;overflow:hidden;display:flex;flex-direction:column}
.wrap{flex:1;min-height:0;display:flex;flex-direction:column}
.layout{display:flex;flex-wrap:wrap;gap:14px;align-items:stretch;flex:1;min-height:0;overflow-y:auto;overflow-x:hidden}
.layout>.card{flex:1 1 300px;min-width:0;min-height:0;overflow:auto}
@media(min-width:1000px){.layout>.card{max-height:100%}}
h1{color:var(--blue);font-size:20px;margin:2px 0 4px}
.subtitle{color:var(--muted);font-size:13px;line-height:1.6;margin:0 0 10px;background:#fff;border-left:4px solid var(--blue);border-radius:0 8px 8px 0;padding:8px 12px;box-shadow:0 1px 4px rgba(0,0,0,.06)}
.subtitle b{color:var(--blue)}
h2{font-size:17px;margin:4px 0 12px}
h3{font-size:15px;margin:18px 0 8px;color:#333}
.card{background:var(--card);border-radius:12px;padding:16px;margin:0;box-shadow:0 1px 4px rgba(0,0,0,.08);min-width:0}
label{display:block;margin:10px 0 5px;font-weight:600;font-size:14px}
.hint{font-weight:400;color:var(--muted);font-size:12px;margin-left:6px}
input{width:100%;padding:10px 12px;border:1px solid #dadce0;border-radius:8px;font-size:14px;outline:none;transition:border .15s,box-shadow .15s}
input:focus{border-color:var(--blue);box-shadow:0 0 0 3px rgba(26,115,232,.15)}
button{background:var(--blue);color:#fff;border:none;padding:10px 20px;border-radius:8px;cursor:pointer;margin:14px 8px 0 0;font-size:14px}
button:hover{filter:brightness(.94)}
button.secondary{background:#5f6368}
.row{display:grid;grid-template-columns:1fr 1fr;gap:12px}
@media(max-width:640px){.row{grid-template-columns:1fr}}
.status{padding:10px 12px;border-radius:8px;margin:8px 0;font-size:14px}
.ok{background:var(--ok);color:var(--ok-t)}
.bad{background:var(--bad);color:var(--bad-t)}
table{width:100%;border-collapse:collapse;font-size:14px}
th,td{padding:9px 8px;border-bottom:1px solid #eee;text-align:left}
.log{font-family:Consolas,monospace;font-size:12px;max-height:60vh;overflow:auto;background:#111;color:#0f0;padding:10px;border-radius:8px;white-space:pre-wrap;word-break:break-all}
.prov-grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(120px,1fr));gap:10px;margin-top:6px}
.prov{border:2px solid #e0e3e7;border-radius:10px;padding:12px 10px;text-align:center;cursor:pointer;transition:all .15s;background:#fafbfc;user-select:none}
.prov:hover{border-color:#b6d0f5;background:#f4f8ff}
.prov.active{border-color:var(--blue);background:#e8f0fe;box-shadow:0 0 0 3px rgba(26,115,232,.12)}
.prov .logo{font-size:26px;line-height:1.2}
.prov .name{font-weight:700;font-size:14px;margin-top:6px}
.prov .sub{font-size:12px;color:var(--muted);margin-top:2px}
.prov-fields{margin-top:6px;padding:12px;background:#f8fafd;border-radius:8px;border:1px dashed #d2dbe7}
.sec-block{padding:14px;background:#f8fafd;border:1px solid #e8edf3;border-radius:10px;margin-top:10px}
.sec-block h3{margin:0 0 4px}
.sec-block h3 .tag{font-weight:400;font-size:12px;color:var(--muted);margin-left:6px}
.sec-nps{margin-top:16px}
.pw-wrap{position:relative}
.pw-wrap input{padding-right:42px}
.pw-eye{position:absolute;right:6px;top:50%;transform:translateY(-50%);border:none;background:none;cursor:pointer;font-size:16px;padding:4px 6px;margin:0;color:#5f6368;line-height:1}
.pw-eye:hover{color:var(--blue)}
.dom-list{display:flex;flex-direction:column;gap:8px}
.dom-row{display:flex;gap:8px;align-items:center}
.dom-row input{flex:1;min-width:0}
.dom-del{background:#fce8e6;color:#c5221f;padding:10px 14px;margin:0;border-radius:8px;font-size:14px;flex:0 0 auto}
.dom-del:hover{filter:brightness(.94)}
.dom-add{background:#e8f0fe;color:var(--blue);margin:10px 0 0;padding:8px 16px;font-weight:600}
.dom-add:hover{filter:brightness(.96)}
</style>
</head>
<body>
<div class="wrap">
<h1>🌐 IPv6 / 组网 / NPS 域名路由自动检测</h1>
<p class="subtitle">🔄 自动检测本机 IPv6、组网(EasyTier) 与 NPS 穿透的连通性,按 <b>IPv6 → 组网 → NPS</b> 优先级自动把域名解析到当前可用的地址;检测间隔可配置,连通的线路会在下方「已连通」中显示。</p>
<div class="layout">
<div class="card">
<h2>域名与 DNS 服务商</h2>
<label>域名 <span class="hint">可添加多个,线路连通时全部域名一起解析</span></label>
<div id="domain_list" class="dom-list"></div>
<button type="button" class="dom-add" onclick="addDomain()">+ 添加域名</button>
<label>DNS 服务商 <span class="hint">点击下方卡片选择</span></label>
<div class="prov-grid" id="prov_grid">
<div class="prov" data-p="cloudflare" onclick="selectProvider('cloudflare')">
<div class="logo">☁️</div><div class="name">Cloudflare</div><div class="sub">国外首选</div>
</div>
<div class="prov" data-p="tencent" onclick="selectProvider('tencent')">
<div class="logo">🐧</div><div class="name">腾讯云</div><div class="sub">DNSPod</div>
</div>
<div class="prov" data-p="aliyun" onclick="selectProvider('aliyun')">
<div class="logo">🟧</div><div class="name">阿里云</div><div class="sub">万网 DNS</div>
</div>
<div class="prov" data-p="huawei" onclick="selectProvider('huawei')">
<div class="logo">🌸</div><div class="name">华为云</div><div class="sub">DNS 解析</div>
</div>
<div class="prov" data-p="webhook" onclick="selectProvider('webhook')">
<div class="logo">🔗</div><div class="name">自定义</div><div class="sub">Webhook 转发</div>
</div>
</div>
<input type="hidden" id="dns_provider" value="cloudflare">
<div id="cf_fields" class="prov-fields">
<label>SecretId <span class="hint">即 Cloudflare Zone ID</span></label><input id="cf_zone" placeholder="Zone ID">
<label>SecretKey <span class="hint">即 Cloudflare API Token</span></label><div class="pw-wrap"><input id="cf_token" type="password" placeholder="API Token"><button type="button" class="pw-eye" onclick="togglePw('cf_token',this)" title="显示/隐藏">👁️</button></div>
</div>
<div id="tencent_fields" class="prov-fields" style="display:none">
<label>SecretId</label><input id="tencent_secret_id" placeholder="腾讯云 SecretId">
<label>SecretKey</label><div class="pw-wrap"><input id="tencent_secret_key" type="password" placeholder="腾讯云 SecretKey"><button type="button" class="pw-eye" onclick="togglePw('tencent_secret_key',this)" title="显示/隐藏">👁️</button></div>
</div>
<div id="aliyun_fields" class="prov-fields" style="display:none">
<label>SecretId <span class="hint">即 AccessKeyId</span></label><input id="aliyun_access_key_id" placeholder="AccessKeyId">
<label>SecretKey <span class="hint">即 AccessKeySecret</span></label><div class="pw-wrap"><input id="aliyun_access_key_secret" type="password" placeholder="AccessKeySecret"><button type="button" class="pw-eye" onclick="togglePw('aliyun_access_key_secret',this)" title="显示/隐藏">👁️</button></div>
</div>
<div id="huawei_fields" class="prov-fields" style="display:none">
<label>SecretId <span class="hint">即 AK</span></label><input id="huawei_ak" placeholder="Access Key">
<label>SecretKey <span class="hint">即 SK</span></label><div class="pw-wrap"><input id="huawei_sk" type="password" placeholder="Secret Key"><button type="button" class="pw-eye" onclick="togglePw('huawei_sk',this)" title="显示/隐藏">👁️</button></div>
</div>
<div id="webhook_fields" class="prov-fields" style="display:none">
<label>Webhook URL</label><input id="webhook_url" placeholder="https://...">
</div>
<div class="sec-block">
<h3>🔗 组网 (EasyTier) <span class="tag">备用线路 ① · ping 连通即解析 A 记录</span></h3>
<label>组网地址 <span class="hint">填组网 IP,ping 能通即视为连通,无需端口</span></label><input id="easytier_host" placeholder="1.1.1.19">
</div>
<div class="sec-block sec-nps">
<h3>🚇 NPS 内网穿透 <span class="tag">备用线路 ② · 最后兜底</span></h3>
<div class="row">
<div><label>NPS 服务器 (host:port)</label><input id="nps_server" placeholder="x.x.x.x:8024"></div>
<div><label>VKey</label><div class="pw-wrap"><input id="nps_vkey" type="password" placeholder="NPS 客户端密钥"><button type="button" class="pw-eye" onclick="togglePw('nps_vkey',this)" title="显示/隐藏">👁️</button></div></div>
</div>
</div><!-- /sec-nps -->
<div style="margin-top:14px;padding-top:12px;border-top:1px solid #eee">
<label>检测间隔(秒) <span class="hint">对 IPv6 / 组网 / NPS 全部检测生效</span></label><input id="interval" type="number" value="60" style="max-width:200px">
</div>
<button onclick="save()">保存配置</button>
<button class="secondary" onclick="checkNow()">立即检测</button>
</div><!-- /card 配置 -->
<div class="card">
<h2>状态</h2>
<div id="st"></div>
<h3>已连通</h3>
<table><thead><tr><th>类型</th><th>目标</th><th>域名</th></tr></thead><tbody id="conn"></tbody></table>
</div>
<div class="card">
<h2>日志 <span class="hint">仅保留最近 24 小时,超期自动删除</span></h2>
<div class="log" id="log"></div>
</div>
</div><!-- /layout -->
</div><!-- /wrap -->
<script>
function togglePw(id,btn){
const el=document.getElementById(id);if(!el)return;
const show=el.type==='password';
el.type=show?'text':'password';
if(btn)btn.textContent=show?'🙈':'👁️';
}
function selectProvider(p){
document.getElementById('dns_provider').value=p;
document.querySelectorAll('.prov').forEach(el=>el.classList.toggle('active',el.dataset.p===p));
toggleProvider();
}
function toggleProvider(){
const p=document.getElementById('dns_provider').value||'cloudflare';
document.querySelectorAll('.prov').forEach(el=>el.classList.toggle('active',el.dataset.p===p));
for(const k of ['cf','tencent','aliyun','huawei','webhook'])
document.getElementById(k+'_fields').style.display=(k===p||(k==='cf'&&p==='cloudflare'))?'block':'none';
}
const _fetch=window.fetch.bind(window);
window.fetch=function(){return _fetch.apply(null,arguments).then(function(r){if(r.status===401){location.reload();throw new Error('401');}return r;});};
function addDomain(v){
const wrap=document.getElementById('domain_list');
const row=document.createElement('div');row.className='dom-row';
row.innerHTML='<input class="dom-in" placeholder="example.com"><button type="button" class="dom-del" onclick="this.parentNode.remove()" title="删除该域名">✕</button>';
if(v)row.querySelector('input').value=v;
wrap.appendChild(row);
}
function getDomains(){
const out=[];
document.querySelectorAll('#domain_list .dom-in').forEach(el=>{const v=el.value.trim();if(v&&!out.includes(v))out.push(v);});
return out;
}
async function load(){
try{
const r=await fetch('/api/config');const c=await r.json();
for(const k in c){const el=document.getElementById(k);if(el)el.value=c[k]??'';}
const list=document.getElementById('domain_list');list.innerHTML='';
const doms=Array.isArray(c.domains)?c.domains:(c.domain?[c.domain]:[]);
doms.forEach(d=>addDomain(d));
if(!doms.length)addDomain('');
toggleProvider();
}catch(e){}
}
async function save(){
const body={};
const ids=['dns_provider','interval','cf_zone','cf_token','tencent_secret_id','tencent_secret_key','aliyun_access_key_id','aliyun_access_key_secret','huawei_ak','huawei_sk','webhook_url','easytier_host','nps_server','nps_vkey'];
for(const id of ids){
const el=document.getElementById(id);if(!el)continue;
const v=el.value;
if(v!=='') body[id]=(id==='interval')?Number(v):v;
}
body.domains=getDomains(); // 多域名列表
await fetch('/api/config',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(body)});
alert('已保存');
poll();
}
async function checkNow(){await fetch('/api/check',{method:'POST'});setTimeout(poll,1000);}
async function poll(){
try{
const r=await fetch('/api/status');const s=await r.json();
let html='';
function row(name,o){return `<div class="status ${o&&o.ok?'ok':'bad'}">${name}: ${o?(o.ok?'✅ '+JSON.stringify(o):'❌ '+JSON.stringify(o)):'未配置'}</div>`;}
html+=row('IPv6',s.ipv6);
html+=row('EasyTier',s.easytier);
html+=row('NPS',s.nps);
html+=`<div>上次检测: ${s.last_run||'-'}</div>`;
document.getElementById('st').innerHTML=html;
const tb=document.getElementById('conn');tb.innerHTML='';
(s.connected||[]).forEach(c=>{const tr=document.createElement('tr');tr.innerHTML=`<td>${c.type}</td><td>${c.target||''}</td><td>${c.domain||''}</td>`;tb.appendChild(tr);});
const logArr=s.log||[];
const logKey=logArr.length+':'+(logArr.length?logArr[logArr.length-1].ts:'');
if(logKey!==window._logKey){window._logKey=logKey;document.getElementById('log').innerHTML=logArr.map(l=>`[${l.t}] ${l.msg}`).join('<br>');}
}catch(e){}
}
load();poll();setInterval(poll,5000);
</script>
</body>
</html>
+5
View File
@@ -0,0 +1,5 @@
fastapi==0.115.0
uvicorn[standard]==0.30.6
httpx==0.27.2
apscheduler==3.10.4
python-multipart==0.0.9