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, 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 = """ 登录 · IPv6 / 组网 / NPS 域名路由

\U0001f512 \u9700\u8981 TOKEN \u624d\u80fd\u8bbf\u95ee

IPv6 / \u7ec4\u7f51 / NPS \u57df\u540d\u8def\u7531\u81ea\u52a8\u68c0\u6d4b

TOKEN 固定不变,见 data/config.json 的 access_token;支持 ?token= 快捷登录。
""" 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']}", 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 不支持") 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") _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[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)