commit f229d848fe413ab64b9b7e801743196aeb9ca709
Author: danieldyx87 <danieldyx87@qq.com>
Date:   Mon Oct 12 05:09:25 2026 +0000

    2026-10-12 13:09 退款验证与备份演练完善：作废语义隔离验证、恢复演练覆盖 s2a_ops 定义
    
    - backup-restore-check.sh：s2a_ops 索引/约束定义逐条比对、refund_requests 行数、请求结果与台账一致性；支持 BACKUP_FILE 本地备份
    - 新增 ops/refund_e2e_check.py：复制生产库到临时库，经真实 HTTP 验证并发、结果未知、作废、删除/恢复与一致性，结果留档 ops/refund_e2e_check.log
    - key_query.py：S2A_DB/S2A_PORT/S2A_REDIS_PORT 环境变量（默认不变），供隔离验证使用
    - refund.html：订单列表操作文案改为「查看」
    - handoff_record.md：记录 round10/11 与 auto_proxy 误停事故

diff --git a/handoff_record.md b/handoff_record.md
index 7a9484e..6e60cb4 100644
--- a/handoff_record.md
+++ b/handoff_record.md
@@ -382,3 +382,5 @@ Nexus 页面右下角「API 文档」列出 9 个接口，逐一实测结果：
 - **审计整改 round8（2026-10-12 00:35）**：结果未确认的退款登记改为持久化核对：页面把未确认登记（订单、¥、原因、request_id、时间）存 localStorage `s2a_refund_pending`（按订单），关窗/刷新不丢；未核对前该订单只能按原金额和原因用原 request_id 重试，改金额/原因被拦截。重新打开订单时调新接口 `GET /api/relay/refund/request?id=<request_id>` 核对：已写入 → 提示成功并清除；查不到且超过 60 秒（后端写库最长约 10 秒）→ 确认未写入并清除；60 秒内 → 表单预填原值供重试。仍不防跨浏览器/跨设备的重复（需要线下退款凭证号唯一约束才能做到）。撤销/恢复复核：15 项回滚式测试（两轮删除/恢复、重复删除/恢复被拒、剩余额度不足恢复被拒且数据不变、余额不足恢复扣到 0 后再删按实扣退回、Redis 不可用恢复成功并留待补清、request_id 核对）全部通过，数据前后一致。日报口径保持：恢复后按原 created_at 计入（视为更正历史登记，不是恢复当日新现金流）。备份 `/root/backup/audit_fix_round8_20261011162131/`。
 - **审计整改 round9（2026-10-12 11:10）**：①**结果未确认的登记改由服务器原子作废**，不再用「60 秒查不到即未写入」的本机时间推断：新表 `s2a_ops.refund_requests(request_id 主键, state done/abandoned)`；登记写库语句同事务插入 done，新接口 `POST /api/relay/refund/abandon {request_id}` 插入 abandoned（on conflict do nothing 后读状态）——在途的同 ID 写入会先持有主键，作废等它结束再判定；作废后同 ID 写入撞主键整条失败。页面重新打开订单时直接调作废接口：已写入则提示结果并刷新详情，否则提示「未写入，已在服务器作废」。`relay_refund` 授予该表 SELECT/INSERT；已有带 request_id 的台账已回填 done。②**备份恢复演练覆盖 s2a_ops**：`backup-restore-check.sh` 新增 s2a_ops 表数与唯一索引数一致、manual_refunds/refund_users/route_keys/group_meta/nexus_tags 行数（>0，台账与退款账号 ≤ 生产）、台账→订单与子 Key→Key 关联缺失为 0；已确认 R2 定时备份本身包含 s2a_ops，并实跑演练通过（8 表/10 唯一索引一致，关联缺失 0）。新表在下次 02:00 备份后纳入表数比对。验证：作废语义 10 项（含两会话并发等待）与 round7/8 回归测试全部通过，均回滚，数据前后一致。备份 `/root/backup/audit_fix_round9_20261012025843/`（3 个文件、迁移前 s2a_ops 导出、迁移 SQL）。
 - **Git 仓库（2026-10-12 11:35）**：`/opt/sub2api` 已纳入 Git（分支 main），远程 `github` = git@github.com:DanielDu87/api_sub2api.git、`gitee` = git@gitee.com:danieldyx87/api_sub2api.git（均私有）。服务器上不存放 Git 凭据：从 Mac 用 `ssh -A ssa` 进入后 `git push github main && git push gitee main`（借用本机密钥）。凭据（config.yaml、relay/server/*.env）、官方二进制 `sub2api`、`data/`、`relay/node_modules`、`relay/dist`、ops 日志与状态文件由 `.gitignore` 排除。每次推送后在 Mac 的 `/Users/dyx/Code/api_sub2api` 执行 `git pull` 同步。
+- **审计整改 round10（2026-10-12 11:50，未提交，等用户通知）**：①`backup-restore-check.sh`：s2a_ops 索引/约束定义逐条比对（不只比数量）、`refund_requests` 行数、请求结果与台账一致性；支持 `BACKUP_FILE=/path.sql.gz` 用本地备份验证。`refund_requests` 的 CHECK 约束改写为 pg_dump 往返后的标准写法（原写法恢复后反解形式不同，比对误报，并因此发出 2 封「恢复演练失败」误报邮件）。用当前库导出实跑通过（9 表、84 条定义差异 0、不一致 0）；R2 真实备份含新表的验证待 10-13 02:00 备份、03:00 定时演练。②新增 `ops/refund_e2e_check.py`（root 运行）：复制生产库到临时库 s2a_e2e_check，启动指向临时库的 key_query 实例（127.0.0.1:18093；`key_query.py` 新增环境变量 S2A_DB/S2A_PORT，默认 sub2api/8092 不变），经真实 HTTP 验证同一编号并发、响应丢失查询/重试、先作废后提交、在途提交时作废、写入未提交时作废等待、删除/恢复、余额/订单/请求一致性，14 项全部通过，结束后删临时库。③**事故**：首次运行时测试端口误用 8093（生产 auto_proxy 统一路由），排查残留时误杀了生产 auto_proxy，看门狗约 3 秒内拉起（健康正常，15 分组）；期间统一路由请求可能失败。已改为 18093，启动前检查端口占用、实例未启动则中止。生产退款数据核对未变。备份 `/root/backup/audit_fix_round9_20261012025843/`（含约束修正 SQL fix_check.sql）。
+- **审计整改 round11（2026-10-12 12:45，未提交）**：`refund_e2e_check.py` 每次运行把时间、被测文件指纹、各场景结果和退出码追加到 `ops/refund_e2e_check.log`（异常中止也记录）；临时库改为 `s2a_e2e_check_<pid>`；测试实例设 `S2A_REDIS_PORT=1`，不再删除生产余额缓存（`key_query.py` 新增该环境变量，默认 6379）。12:37 运行 14 项全部通过。另做浏览器层验证（Chrome + 临时库 + SSH 隧道）：响应丢失后刷新自动核对为成功、发送前断网后刷新作废且同编号不可再写、改金额被拦截、同一订单再次登记正常，结果已记入同一日志；临时库、进程、隧道、测试账号均已清理，生产数据未变。
diff --git a/ops/backup-restore-check.sh b/ops/backup-restore-check.sh
index 43bc415..9e89e4b 100755
--- a/ops/backup-restore-check.sh
+++ b/ops/backup-restore-check.sh
@@ -6,6 +6,7 @@
 #      唯一索引、关键表行数与关联完整性，结果写日志
 #   4. 删除临时库与下载文件
 # 用法: backup-restore-check.sh [--expect-scheduled]   日志: /opt/sub2api/ops/backup_restore_check.log
+#       BACKUP_FILE=/path/x.sql.gz backup-restore-check.sh   用本地备份文件代替 R2 最新备份（验证脚本或新表结构时用）
 set -uo pipefail
 LOG=/opt/sub2api/ops/backup_restore_check.log
 exec >>"$LOG" 2>&1
@@ -19,7 +20,7 @@ WORK=$(mktemp -d /root/sub2api_restore_check.XXXX)
 cleanup() {
 	local rc=$?
 	$BIN/dropdb -h localhost -U postgres --if-exists "$DB"
-	rm -f -- "$WORK/backup.sql.gz" "$WORK/restore.log" && rmdir -- "$WORK"
+	rm -f -- "$WORK/backup.sql.gz" "$WORK/restore.log" "$WORK/defs.diff" && rmdir -- "$WORK"
 	if [ $rc -ne 0 ]; then # 失败时发表格邮件（成功不发，避免每日打扰）
 		python3 -I /opt/sub2api/ops/mail_report.py restore "$LOG" | python3 -I /opt/sub2api/ops/notify.py json ||
 			echo "失败通知邮件发送失败"
@@ -27,33 +28,42 @@ cleanup() {
 }
 trap cleanup EXIT
 
-read -r ID TRIGGER STARTED KEY < <(Q "select value from settings where key='backup_records'" | python3 -c "
+if [ -n "${BACKUP_FILE:-}" ]; then
+	echo "使用本地备份文件 $BACKUP_FILE"
+	cp -- "$BACKUP_FILE" "$WORK/backup.sql.gz" || exit 1
+	gzip -t "$WORK/backup.sql.gz" || {
+		echo "失败：gzip 损坏"
+		exit 1
+	}
+else
+	read -r ID TRIGGER STARTED KEY < <(Q "select value from settings where key='backup_records'" | python3 -c "
 import json, sys
 from datetime import datetime
 rows = [r for r in json.load(sys.stdin) if r['status'] == 'completed']
 rows.sort(key=lambda r: datetime.fromisoformat(r['started_at']))
 r = rows[-1]
 print(r['id'], r.get('triggered_by'), r['started_at'], r['s3_key'])")
-echo "最新备份 $ID 触发=$TRIGGER 开始=$STARTED"
-if [ "${1:-}" = "--expect-scheduled" ]; then
-	today=$(TZ=Asia/Shanghai date +%F)
-	if [ "$TRIGGER" = manual ] || [ "${STARTED:0:10}" != "$today" ]; then
-		echo "失败：未发现今天（$today）的定时备份"
-		exit 1
+	echo "最新备份 $ID 触发=$TRIGGER 开始=$STARTED"
+	if [ "${1:-}" = "--expect-scheduled" ]; then
+		today=$(TZ=Asia/Shanghai date +%F)
+		if [ "$TRIGGER" = manual ] || [ "${STARTED:0:10}" != "$today" ]; then
+			echo "失败：未发现今天（$today）的定时备份"
+			exit 1
+		fi
 	fi
-fi
 
-curl -sS -m 300 --aws-sigv4 "aws:amz:auto:s3" \
-	-K <(printf 'user = "%s:%s"\n' "$R2_ACCESS_KEY_ID" "$R2_SECRET_ACCESS_KEY") \
-	-o "$WORK/backup.sql.gz" "${R2_ENDPOINT}/${R2_BUCKET}/$KEY" || {
-	echo "失败：下载 $KEY"
-	exit 1
-}
-gzip -t "$WORK/backup.sql.gz" || {
-	echo "失败：gzip 损坏"
-	exit 1
-}
-echo "下载完成 $(stat -c %s "$WORK/backup.sql.gz") 字节"
+	curl -sS -m 300 --aws-sigv4 "aws:amz:auto:s3" \
+		-K <(printf 'user = "%s:%s"\n' "$R2_ACCESS_KEY_ID" "$R2_SECRET_ACCESS_KEY") \
+		-o "$WORK/backup.sql.gz" "${R2_ENDPOINT}/${R2_BUCKET}/$KEY" || {
+		echo "失败：下载 $KEY"
+		exit 1
+	}
+	gzip -t "$WORK/backup.sql.gz" || {
+		echo "失败：gzip 损坏"
+		exit 1
+	}
+fi
+echo "备份文件 $(stat -c %s "$WORK/backup.sql.gz") 字节"
 
 $BIN/dropdb -h localhost -U postgres --if-exists "$DB"
 $BIN/createdb -h localhost -U postgres "$DB"
@@ -81,6 +91,21 @@ sb=$(R "select count(*) from information_schema.tables where $S2A") sp=$(Q "sele
 ib=$(R "select count(*) from pg_indexes where $UIX") ip=$(Q "select count(*) from pg_indexes where $UIX")
 echo "s2a_ops 表数 备份=$sb 生产=$sp，唯一索引 备份=$ib 生产=$ip"
 { [ "${sb:-0}" -gt 0 ] && [ "$sb" = "$sp" ] && [ "$ib" = "$ip" ]; } || ok=0
+# 结构定义逐条比对（不只比数量）：索引定义与约束定义
+DEFS="select 'I ' || indexdef from pg_indexes where schemaname = 's2a_ops'
+      union all select 'C ' || conrelid::regclass || ' ' || pg_get_constraintdef(oid) from pg_constraint
+      where connamespace = 's2a_ops'::regnamespace order by 1"
+diff <(R "$DEFS") <(Q "$DEFS") >"$WORK/defs.diff"
+nd=$(grep -c '^[<>]' "$WORK/defs.diff")
+echo "  s2a_ops 索引/约束定义差异 $nd 条（$(Q "select count(*) from ($DEFS) d") 条定义）"
+[ "$nd" = 0 ] || {
+	ok=0
+	head -6 "$WORK/defs.diff"
+}
+# 退款请求结果表：可以为空，备份不应多于生产
+b=$(R "select count(*) from s2a_ops.refund_requests") p=$(Q "select count(*) from s2a_ops.refund_requests")
+echo "  s2a_ops.refund_requests 备份=${b:-缺失} 生产=$p"
+{ [ -n "$b" ] && [ "$b" -le "$p" ]; } || ok=0
 for t in manual_refunds refund_users route_keys group_meta nexus_tags; do
 	b=$(R "select count(*) from s2a_ops.$t") p=$(Q "select count(*) from s2a_ops.$t")
 	echo "  s2a_ops.$t 备份=$b 生产=$p"
@@ -93,6 +118,13 @@ orph=$(R "select (select count(*) from s2a_ops.manual_refunds m where not exists
                                                         or not exists (select 1 from api_keys k where k.id = r.parent_id))")
 echo "  s2a_ops 关联缺失（台账→订单、子 Key→Key）=$orph"
 [ "$orph" = 0 ] || ok=0
+# 请求结果与台账一致：带 request_id 的台账必有 done，done 必有台账
+incon=$(R "select (select count(*) from s2a_ops.manual_refunds m where m.request_id is not null and not exists
+                     (select 1 from s2a_ops.refund_requests q where q.request_id = m.request_id and q.state = 'done'))
+             + (select count(*) from s2a_ops.refund_requests q where q.state = 'done' and not exists
+                     (select 1 from s2a_ops.manual_refunds m where m.request_id = q.request_id))")
+echo "  s2a_ops 请求结果与台账不一致=$incon"
+[ "$incon" = 0 ] || ok=0
 [ "$errors" -eq 0 ] || ok=0
 [ $ok = 1 ] && echo "结果：通过" || echo "结果：失败"
 [ $ok = 1 ]
diff --git a/ops/refund_e2e_check.py b/ops/refund_e2e_check.py
new file mode 100755
index 0000000..6b7c842
--- /dev/null
+++ b/ops/refund_e2e_check.py
@@ -0,0 +1,377 @@
+"""退款登记端到端隔离验证（以 root 运行：python3 -I ops/refund_e2e_check.py）。
+
+把生产库完整复制到临时库 s2a_e2e_check，另起一个 key_query 实例（127.0.0.1:18093，S2A_PORT/S2A_DB 指向临时库），
+通过真实 HTTP 接口验证并发与结果未知场景（数据真实提交，但只在临时库），结束后停实例、删临时库。
+生产库只被 pg_dump 读取；测试实例的 Redis 指向不存在的端口（S2A_REDIS_PORT），不碰生产余额缓存。
+每次运行把时间、被测文件指纹、各场景结果与退出状态追加到 ops/refund_e2e_check.log。
+"""
+
+import hashlib
+import json
+import os
+import secrets
+import socket
+import subprocess
+import sys
+import threading
+import time
+import urllib.error
+import urllib.request
+import uuid
+
+BIN = "/www/server/pgsql/bin"
+DB = f"s2a_e2e_check_{os.getpid()}"  # 每次运行独立临时库，避免与并行或残留运行冲突
+PORT = (
+    18093  # 8091/8092/8093 是生产服务（路由鉴权/查询退款/统一路由），测试实例必须避开
+)
+KQ = "/opt/sub2api/relay/server/key_query.py"
+BASE = f"http://127.0.0.1:{PORT}/api/relay/refund"
+ok = True
+
+
+LOG = "/opt/sub2api/ops/refund_e2e_check.log"
+results = []
+
+
+def check(name, cond):
+    global ok
+    ok &= bool(cond)
+    line = ("PASS " if cond else "FAIL ") + name
+    results.append(line)
+    print(line, flush=True)
+
+
+def write_log(status):
+    fp = {
+        f: hashlib.sha256(open(f"/opt/sub2api/{f}", "rb").read()).hexdigest()
+        for f in (
+            "relay/server/key_query.py",
+            "relay/dist/refund.html",
+            "ops/refund_e2e_check.py",
+        )
+    }
+    with open(LOG, "a") as fh:
+        fh.write(f"==== 北京时间 {START} 开始，{bj_now()} 结束，临时库 {DB}\n")
+        fh.writelines(f"  {k} {v}\n" for k, v in fp.items())
+        fh.writelines(f"  {r}\n" for r in results)
+        fh.write(f"结果：{status}\n")
+
+
+def q(sql, db=DB):
+    return subprocess.run(
+        [
+            f"{BIN}/psql",
+            "-h",
+            "localhost",
+            "-U",
+            "postgres",
+            "-d",
+            db,
+            "-qAt",
+            "-F",
+            "\t",
+            "-v",
+            "ON_ERROR_STOP=1",
+        ],
+        input=sql,
+        capture_output=True,
+        text=True,
+        check=True,
+    ).stdout.strip()
+
+
+class Session:
+    """独立 psql 会话（postgres），用于持锁或手工事务。"""
+
+    def __init__(self):
+        self.p = subprocess.Popen(
+            [f"{BIN}/psql", "-h", "localhost", "-U", "postgres", "-d", DB, "-qAt"],
+            stdin=subprocess.PIPE,
+            stdout=subprocess.PIPE,
+            stderr=subprocess.STDOUT,
+            text=True,
+            bufsize=1,
+        )
+
+    def run(self, sql):
+        self.p.stdin.write(sql + "\n\\echo __END__\n")
+        self.p.stdin.flush()
+        out = []
+        while (line := self.p.stdout.readline().rstrip("\n")) != "__END__":
+            out.append(line)
+        errs = [x for x in out if "ERROR" in x]
+        if errs:
+            raise RuntimeError(errs)
+        return out
+
+    def close(self):
+        self.p.stdin.close()
+        self.p.wait()
+
+
+cookie = ""
+
+
+def api(method, path, body=None):
+    req = urllib.request.Request(
+        BASE + path,
+        method=method,
+        data=json.dumps(body).encode() if body is not None else None,
+        headers={
+            "X-Requested-With": "s2a-refund",
+            "Content-Type": "application/json",
+            "Cookie": cookie,
+        },
+    )
+    try:
+        with urllib.request.urlopen(req, timeout=30) as r:
+            return r.status, json.load(r), r.headers
+    except urllib.error.HTTPError as e:
+        return e.code, json.load(e), e.headers
+
+
+def refund(oid, cny, rid, reason="e2e"):
+    return api(
+        "POST",
+        "/refund",
+        {
+            "order_id": oid,
+            "cny": cny,
+            "reason": reason,
+            "request_id": rid,
+            "confirm": True,
+        },
+    )
+
+
+def ledger(rid):
+    return q(f"select count(*) from s2a_ops.manual_refunds where request_id = '{rid}'")
+
+
+def bj_now():
+    return time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime(time.time() + 8 * 3600))
+
+
+START = bj_now()
+
+
+def main():
+    global cookie
+    sys.path.insert(0, os.path.dirname(KQ))
+    q(f"drop database if exists {DB}", db="postgres")
+    q(f"create database {DB}", db="postgres")
+    subprocess.run(
+        f"{BIN}/pg_dump -h localhost -U postgres -d sub2api | {BIN}/psql -h localhost -U postgres -d {DB} -q -v ON_ERROR_STOP=1",
+        shell=True,
+        check=True,
+        capture_output=True,
+    )
+    # 测试账号（只在临时库）
+    pw = secrets.token_urlsafe(16)
+    salt = os.urandom(16)
+    dk = hashlib.scrypt(pw.encode(), salt=salt, n=2**14, r=8, p=1, dklen=32)
+    q(
+        "insert into s2a_ops.refund_users(username, pw_hash, must_change, enabled) "
+        f"values ('ze2e', 'scrypt$16384$8$1${salt.hex()}${dk.hex()}', false, true)"
+    )
+    oid, uid = map(
+        int,
+        q(
+            "select id, user_id from payment_orders where order_type = 'balance' and status in "
+            "('COMPLETED','PARTIALLY_REFUNDED') and pay_amount > 0.5 and refund_amount < amount - 0.5 order by id limit 1"
+        ).split("\t"),
+    )
+    ra0, bal0 = map(
+        float,
+        q(
+            f"select o.refund_amount, u.balance from payment_orders o join users u on u.id = o.user_id where o.id = {oid}"
+        ).split("\t"),
+    )
+    with socket.socket() as sk:
+        if sk.connect_ex(("127.0.0.1", PORT)) == 0:
+            sys.exit(f"端口 {PORT} 已被占用，未启动测试实例")
+    srv = subprocess.Popen(
+        [
+            "sudo",
+            "-u",
+            "sub2api",
+            "env",
+            f"S2A_DB={DB}",
+            f"S2A_PORT={PORT}",
+            "S2A_REDIS_PORT=1",
+            "python3",
+            "-I",
+            KQ,
+        ],
+        stdout=subprocess.PIPE,
+        stderr=subprocess.STDOUT,
+        text=True,
+    )
+    try:
+        for _ in range(50):
+            try:
+                urllib.request.urlopen(f"http://127.0.0.1:{PORT}/health", timeout=1)
+                break
+            except OSError:
+                time.sleep(0.2)
+        if srv.poll() is not None:  # 实例没起来就不能继续，避免请求打到别的服务
+            sys.exit("测试实例启动失败：\n" + srv.stdout.read())
+        st, body, hdr = api("POST", "/login", {"username": "ze2e", "password": pw})
+        cookie = hdr.get("Set-Cookie", "").split(";")[0]
+        check(f"测试实例登录（订单 #{oid}）", st == 200 and cookie)
+
+        # 1. 同一编号并发提交两次：只登记一笔，两次返回同一台账
+        rid, res = str(uuid.uuid4()), []
+        ts = [
+            threading.Thread(target=lambda: res.append(refund(oid, 0.1, rid)))
+            for _ in range(2)
+        ]
+        [t.start() for t in ts]
+        [t.join() for t in ts]
+        ids = {r[1]["data"]["ledger_id"] for r in res if r[0] == 200}
+        check(
+            "同一编号并发提交：两次都成功且同一台账",
+            len(res) == 2 and all(r[0] == 200 for r in res) and len(ids) == 1,
+        )
+        check("同一编号并发提交：只写入一笔", ledger(rid) == "1")
+
+        # 2. 响应丢失：查询与作废都返回已写入结果，作废不生效
+        rid2 = str(uuid.uuid4())
+        st, b, _ = refund(oid, 0.1, rid2)
+        st_q, bq, _ = api("GET", f"/request?id={rid2}")
+        st_a, ba, _ = api("POST", "/abandon", {"request_id": rid2})
+        check(
+            "响应丢失后查询/作废：返回首次结果、不作废",
+            st == 200
+            and bq["data"]["found"]
+            and ba["data"]["found"]
+            and not ba["data"]["abandoned"],
+        )
+        st, b, _ = refund(oid, 0.1, rid2)
+        check(
+            "响应丢失后原编号重试：返回原结果不重复扣",
+            st == 200 and b["data"].get("duplicate") and ledger(rid2) == "1",
+        )
+
+        # 3. 先作废、后提交：拒绝且不写入
+        rid3 = str(uuid.uuid4())
+        st_a, ba, _ = api("POST", "/abandon", {"request_id": rid3})
+        st, b, _ = refund(oid, 0.1, rid3)
+        check(
+            "先作废后提交：作废成功，提交被拒且未写入",
+            ba["data"]["abandoned"] and st == 400 and ledger(rid3) == "0",
+        )
+
+        # 4. 提交在途（订单行被锁住）时作废：作废先完成，在途提交随后撞主键失败、不扣款
+        rid4 = str(uuid.uuid4())
+        lock = Session()
+        lock.run(f"begin; select id from payment_orders where id = {oid} for update;")
+        out = {}
+        t = threading.Thread(target=lambda: out.update(r=refund(oid, 0.1, rid4)))
+        t.start()
+        time.sleep(1.5)
+        st_a, ba, _ = api("POST", "/abandon", {"request_id": rid4})
+        check(
+            "在途提交期间作废：立即作废成功",
+            st_a == 200 and ba["data"]["abandoned"] and t.is_alive(),
+        )
+        lock.run("commit;")
+        t.join(20)
+        st = out["r"][0]
+        check(
+            "在途提交随后失败且未写入（不会作废后再扣款）",
+            st == 400 and ledger(rid4) == "0",
+        )
+        lock.close()
+
+        # 5. 登记已占用编号（事务未提交）时作废：作废等待，提交后返回已写入
+        rid5 = str(uuid.uuid4())
+        a = Session()
+        a.run(
+            "begin; insert into s2a_ops.manual_refunds(order_id, user_id, cny, usd, deducted, balance_before, "
+            f"status_before, status_after, reason, operator, request_id, cache_cleared_at) values ({oid}, {uid}, 0.01, 0.01, 0, 0, "
+            f"'COMPLETED', 'COMPLETED', 'e2e', 'e2e-s5', '{rid5}', now());"
+            f"insert into s2a_ops.refund_requests(request_id, state) values ('{rid5}', 'done');"
+        )
+        out = {}
+        t0 = time.time()
+        t = threading.Thread(
+            target=lambda: out.update(r=api("POST", "/abandon", {"request_id": rid5}))
+        )
+        t.start()
+        time.sleep(2)
+        waiting = t.is_alive()
+        a.run("commit;")
+        t.join(20)
+        d = out["r"][1].get("data") or out["r"][1]
+        print(f"  场景5 作废返回 {out['r'][0]} {d}，等待中={waiting}", flush=True)
+        check(
+            f"写入未提交时作废：等待 {time.time() - t0:.1f}s 后返回已写入",
+            waiting and d["found"] and not d["abandoned"],
+        )
+        a.close()
+
+        # 6. 删除 / 恢复往返（真实提交）
+        lid = res[0][1]["data"]["ledger_id"]
+        st1, _, _ = api(
+            "POST", "/revoke", {"ledger_id": lid, "reason": "e2e", "confirm": True}
+        )
+        st2, _, _ = api("POST", "/restore", {"ledger_id": lid, "confirm": True})
+        st3, _, _ = api("POST", "/restore", {"ledger_id": lid, "confirm": True})
+        check("删除后恢复成功，重复恢复被拒", st1 == 200 and st2 == 200 and st3 == 400)
+
+        # 7. 最终一致性
+        ra1, bal1 = map(
+            float,
+            q(
+                f"select o.refund_amount, u.balance from payment_orders o join users u on u.id = o.user_id where o.id = {oid}"
+            ).split("\t"),
+        )
+        usd, ded = map(
+            float,
+            q(
+                "select coalesce(sum(usd),0), coalesce(sum(deducted),0) from s2a_ops.manual_refunds "
+                f"where order_id = {oid} and deleted_at is null and operator like 'relay:ze2e'"
+            ).split("\t"),
+        )
+        check(
+            f"订单已退 = 原值 + 测试台账合计（{ra1:.2f} = {ra0:.2f} + {usd:.2f}）",
+            abs(ra1 - ra0 - usd) < 0.005,
+        )
+        check(
+            f"客户余额 = 原值 - 实际扣回合计（{bal1:.8f} = {bal0:.8f} - {ded:.8f}）",
+            abs(bal0 - ded - bal1) < 1e-8,
+        )
+        bad = q(
+            "select (select count(*) from s2a_ops.refund_requests q where q.state = 'done' and not exists "
+            "(select 1 from s2a_ops.manual_refunds m where m.request_id = q.request_id)) + "
+            "(select count(*) from s2a_ops.refund_requests q where q.state = 'abandoned' and exists "
+            "(select 1 from s2a_ops.manual_refunds m where m.request_id = q.request_id)) + "
+            "(select count(*) from s2a_ops.manual_refunds m where m.request_id is not null and not exists "
+            "(select 1 from s2a_ops.refund_requests q where q.request_id = m.request_id and q.state = 'done'))"
+        )
+        check("请求结果与台账一致（done 必有台账、作废必无台账）", bad == "0")
+    finally:
+        srv.terminate()
+        subprocess.run(
+            ["pkill", "-u", "sub2api", "-f", f"S2A_PORT={PORT}"], check=False
+        )
+        try:
+            srv.wait(5)
+        except subprocess.TimeoutExpired:
+            srv.kill()
+        time.sleep(0.5)
+        q(f"drop database if exists {DB} with (force)", db="postgres")
+    status = "ALL PASS（退出码 0）" if ok else "SOME FAILED（退出码 1）"
+    print(status)
+    write_log(status)
+    sys.exit(0 if ok else 1)
+
+
+if __name__ == "__main__":
+    try:
+        main()
+    except Exception as e:  # 中途异常也留档，避免「没有执行记录」
+        results.append(f"ERROR {type(e).__name__}: {e}")
+        write_log("异常中止（退出码 1）")
+        raise
diff --git a/relay/server/key_query.py b/relay/server/key_query.py
index fab2b62..3fc9deb 100644
--- a/relay/server/key_query.py
+++ b/relay/server/key_query.py
@@ -52,7 +52,11 @@ PLAT_PROTOCOLS = {
 }
 QUERY_LIMIT_PER_MIN = 20
 REFUND_DB_ENV = "/opt/sub2api/relay/server/.refund_db.env"
-REDIS_ADDR = ("127.0.0.1", 6379)  # 无密码，与 /opt/sub2api/config.yaml 一致
+# 隔离验证（ops/refund_e2e_check.py）用环境变量把实例指向临时库/端口；生产不设置，保持默认
+DB_NAME = os.environ.get("S2A_DB", "sub2api")
+PORT = int(os.environ.get("S2A_PORT", "8092"))
+# 无密码，与 /opt/sub2api/config.yaml 一致；隔离验证时用 S2A_REDIS_PORT 指向不存在的端口，避免删生产缓存
+REDIS_ADDR = ("127.0.0.1", int(os.environ.get("S2A_REDIS_PORT", "6379")))
 REFUNDABLE = ("COMPLETED", "PARTIALLY_REFUNDED", "REFUND_REQUESTED", "REFUND_FAILED")
 
 
@@ -86,7 +90,7 @@ def sql(query, _env=None, **params):
             "-h",
             "localhost",
             "-d",
-            "sub2api",
+            DB_NAME,
             "-qAt",
             "-F",
             "\t",
@@ -1398,8 +1402,10 @@ class Handler(BaseHTTPRequestHandler):
 
 
 if __name__ == "__main__":
-    srv = ThreadingHTTPServer(("127.0.0.1", 8092), Handler)
+    srv = ThreadingHTTPServer(("127.0.0.1", PORT), Handler)
     srv.daemon_threads = True
     threading.Thread(target=cache_retry_loop, daemon=True).start()
-    print("sub2api-key-query 服务已启动在 127.0.0.1:8092", flush=True)
+    print(
+        f"sub2api-key-query 服务已启动在 127.0.0.1:{PORT}（库 {DB_NAME}）", flush=True
+    )
     srv.serve_forever()
diff --git a/relay/src/refund.html b/relay/src/refund.html
index affc423..7e8d639 100644
--- a/relay/src/refund.html
+++ b/relay/src/refund.html
@@ -762,7 +762,7 @@
             <td class="px-3 py-2.5 text-right font-mono">${usd(o.amount)}</td>
             <td class="px-3 py-2.5"><span class="px-2 py-0.5 rounded-md ${STATUS_CLASS[o.status] || "bg-slate-500/10 text-slate-500 dark:text-slate-400"}">${esc(STATUS[o.status] || o.status)}</span></td>
             <td class="px-3 py-2.5 text-right font-mono">${o.refunded_cny ? yuan(o.refunded_cny) + (o.refund_count > 1 ? `（${o.refund_count} 次）` : "") : "—"}</td>
-            <td class="px-3 py-2.5 text-right"><span class="text-indigo-600 dark:text-indigo-400 font-medium">详情 / 退款</span></td>
+            <td class="px-3 py-2.5 text-right"><span class="text-indigo-600 dark:text-indigo-400 font-medium">查看</span></td>
           </tr>`,
               )
               .join("")

commit 62409e033802a302f24bf4f9bde6255a660e0152
Author: danieldyx87 <danieldyx87@qq.com>
Date:   Mon Oct 12 03:34:08 2026 +0000

    2026-10-12 11:34 交接记录：补充 Git 仓库与推送方式说明

diff --git a/handoff_record.md b/handoff_record.md
index aaf2cc8..7a9484e 100644
--- a/handoff_record.md
+++ b/handoff_record.md
@@ -381,3 +381,4 @@ Nexus 页面右下角「API 文档」列出 9 个接口，逐一实测结果：
 - **退款页 v4（2026-10-12 00:05，基于 round7 版本修改）**：订单详情「支付」拆为「支付方式」「支付时间」；「交易号」「商户单号」点击复制。**已删除的退款可恢复**：`POST /api/relay/refund/restore {ledger_id, confirm}`，单条语句原子完成：按当次 $ 重新扣回余额（最多到 0）、订单已退金额加回并重算状态、清除删除标记、记 restored_at/restored_by、更新台账 deducted/balance_before（之后再删按新扣回额退回）、cache_cleared_at 置空走 round7 的缓存补清；订单剩余可退不足或状态不允许时拒绝。审计 action 改为带微秒时间戳后缀（`MANUAL_REFUND_<id>_REVOKED_<ts>` / `_RESTORED_<ts>`），避免同一台账多次删除/恢复撞 (order_id, action) 唯一索引。`relay_refund` 增加 UPDATE(deducted, balance_before, restored_at, restored_by)。验证：拒绝路径 + 单事务「恢复 → 再删除」演练（扣回 $2.01、部分退款、恢复人记录、再删不冲突，ROLLBACK 后不变）全部通过。台账 #1（订单 #4 ¥1）**仍为已删除**，如需恢复在页面订单 #4 点「恢复」。备份 `/root/backup/relay-refund4-20261011160137/`。
 - **审计整改 round8（2026-10-12 00:35）**：结果未确认的退款登记改为持久化核对：页面把未确认登记（订单、¥、原因、request_id、时间）存 localStorage `s2a_refund_pending`（按订单），关窗/刷新不丢；未核对前该订单只能按原金额和原因用原 request_id 重试，改金额/原因被拦截。重新打开订单时调新接口 `GET /api/relay/refund/request?id=<request_id>` 核对：已写入 → 提示成功并清除；查不到且超过 60 秒（后端写库最长约 10 秒）→ 确认未写入并清除；60 秒内 → 表单预填原值供重试。仍不防跨浏览器/跨设备的重复（需要线下退款凭证号唯一约束才能做到）。撤销/恢复复核：15 项回滚式测试（两轮删除/恢复、重复删除/恢复被拒、剩余额度不足恢复被拒且数据不变、余额不足恢复扣到 0 后再删按实扣退回、Redis 不可用恢复成功并留待补清、request_id 核对）全部通过，数据前后一致。日报口径保持：恢复后按原 created_at 计入（视为更正历史登记，不是恢复当日新现金流）。备份 `/root/backup/audit_fix_round8_20261011162131/`。
 - **审计整改 round9（2026-10-12 11:10）**：①**结果未确认的登记改由服务器原子作废**，不再用「60 秒查不到即未写入」的本机时间推断：新表 `s2a_ops.refund_requests(request_id 主键, state done/abandoned)`；登记写库语句同事务插入 done，新接口 `POST /api/relay/refund/abandon {request_id}` 插入 abandoned（on conflict do nothing 后读状态）——在途的同 ID 写入会先持有主键，作废等它结束再判定；作废后同 ID 写入撞主键整条失败。页面重新打开订单时直接调作废接口：已写入则提示结果并刷新详情，否则提示「未写入，已在服务器作废」。`relay_refund` 授予该表 SELECT/INSERT；已有带 request_id 的台账已回填 done。②**备份恢复演练覆盖 s2a_ops**：`backup-restore-check.sh` 新增 s2a_ops 表数与唯一索引数一致、manual_refunds/refund_users/route_keys/group_meta/nexus_tags 行数（>0，台账与退款账号 ≤ 生产）、台账→订单与子 Key→Key 关联缺失为 0；已确认 R2 定时备份本身包含 s2a_ops，并实跑演练通过（8 表/10 唯一索引一致，关联缺失 0）。新表在下次 02:00 备份后纳入表数比对。验证：作废语义 10 项（含两会话并发等待）与 round7/8 回归测试全部通过，均回滚，数据前后一致。备份 `/root/backup/audit_fix_round9_20261012025843/`（3 个文件、迁移前 s2a_ops 导出、迁移 SQL）。
+- **Git 仓库（2026-10-12 11:35）**：`/opt/sub2api` 已纳入 Git（分支 main），远程 `github` = git@github.com:DanielDu87/api_sub2api.git、`gitee` = git@gitee.com:danieldyx87/api_sub2api.git（均私有）。服务器上不存放 Git 凭据：从 Mac 用 `ssh -A ssa` 进入后 `git push github main && git push gitee main`（借用本机密钥）。凭据（config.yaml、relay/server/*.env）、官方二进制 `sub2api`、`data/`、`relay/node_modules`、`relay/dist`、ops 日志与状态文件由 `.gitignore` 排除。每次推送后在 Mac 的 `/Users/dyx/Code/api_sub2api` 执行 `git pull` 同步。

commit 48709cdc95a8c73bc5b8497dc6a82d54106d7fde
Author: danieldyx87 <danieldyx87@qq.com>
Date:   Mon Oct 12 03:33:12 2026 +0000

    2026-10-12 11:33 初始提交：sub2api 部署配置、运维脚本（ops）、Relay 查询与退款登记页
    
    不含凭据（config.yaml、relay/server/*.env）、官方二进制、运行时数据与日志，见 .gitignore。

diff --git a/.dockerignore b/.dockerignore
new file mode 100644
index 0000000..f5217c5
--- /dev/null
+++ b/.dockerignore
@@ -0,0 +1,14 @@
+# 与 .gitignore 一致：构建上下文不带凭据、二进制、运行时数据与依赖
+.git
+config.yaml
+.installed
+relay/server/.db.env
+relay/server/.refund_db.env
+*.env
+data/
+relay/node_modules/
+relay/dist/
+ops/*.log
+ops/auto_sync.state*
+__pycache__/
+handoff_record.md
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..0c016fa
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,31 @@
+# ---- 密钥与本机配置（真实凭据只在服务器上）----
+config.yaml
+.installed
+relay/server/.db.env
+relay/server/.refund_db.env
+*.env
+!*.env.example
+
+# ---- sub2api 官方二进制（118 MB，超出 GitHub 100 MB 限制；版本见 handoff_record.md，从官方 release 获取）----
+/sub2api
+
+# ---- 运行时数据（程序自动下载/生成）----
+/data/
+
+# ---- relay 前端依赖与构建产物（./relay/run build 生成）----
+relay/node_modules/
+relay/dist/
+
+# ---- ops 运行日志与状态（脚本运行时写入）----
+ops/*.log
+ops/auto_sync.state*
+ops/auto_route_index.json
+ops/policy_managed_history.json
+
+# ---- Python / 系统 / 编辑器 ----
+__pycache__/
+*.py[cod]
+.DS_Store
+*.swp
+*.bak
+*.tmp
diff --git a/APPLE_CONTAINER.md b/APPLE_CONTAINER.md
new file mode 100644
index 0000000..f0b86b3
--- /dev/null
+++ b/APPLE_CONTAINER.md
@@ -0,0 +1,245 @@
+# Apple container Deployment
+
+Sub2API can run as a native three-service stack with Apple's `container` CLI. This workflow runs the published Sub2API, PostgreSQL, and Redis OCI images without Docker Desktop or a Docker-compatible daemon.
+
+## Support Level
+
+Apple `container` support is intended for local development and operator-managed deployments on a Mac. Docker Compose remains the recommended production deployment path.
+
+Apple `container` 1.1 does not provide restart policies, automatic startup, workload health scheduling, a Docker API socket, or full Compose orchestration. `apple-container.sh` supplies ordered startup and readiness checks when you invoke it. Inside the application container, a small supervisor relaunches the Sub2API process after the Web UI requests a restart; it does not restart stopped containers or the stack itself.
+
+## Requirements
+
+- A Mac with Apple silicon
+- macOS 26 or newer
+- Apple `container` 1.1.0 or newer
+- `openssl` for generating initial secrets
+- Local Network access for `container-runtime-linux` when macOS prompts during the first published-container startup
+
+Install Apple `container` from its [official releases](https://github.com/apple/container/releases), then verify it:
+
+```bash
+container --version
+```
+
+## Quick Start
+
+```bash
+git clone https://github.com/Wei-Shaw/sub2api.git
+cd sub2api/deploy
+
+# Creates .env with random PostgreSQL, JWT, and TOTP secrets.
+./apple-container.sh init
+
+# Review optional settings before startup.
+nano .env
+
+# Creates volumes/network/containers, waits for dependencies, and starts Sub2API.
+./apple-container.sh up
+
+# Verifies PostgreSQL, Redis, and the application endpoint.
+./apple-container.sh status
+```
+
+Open `http://localhost:8080`. If `ADMIN_EMAIL` / `ADMIN_PASSWORD` are empty, retrieve the generated admin email (login username) and password with:
+
+```bash
+./apple-container.sh logs app
+```
+
+The env file uses literal `KEY=value` syntax. Do not use Compose expressions such as `${VALUE:-default}`, and do not quote values unless the quote characters are part of the intended value. `BIND_HOST` must be an IPv4 address, and `SERVER_PORT` must be between 1025 and 65535.
+
+## Commands
+
+```bash
+# Start dependencies and recreate the lightweight app container with current IPs.
+./apple-container.sh up
+
+# Also recreate PostgreSQL and Redis containers, preserving their volumes.
+./apple-container.sh up --recreate
+
+# Stop containers while preserving all resources and data.
+./apple-container.sh down
+
+# Restart PostgreSQL, Redis, and Sub2API in dependency order.
+./apple-container.sh restart
+
+# Show resource state and run live health probes.
+./apple-container.sh status
+
+# Follow one service's logs.
+./apple-container.sh logs app -f
+./apple-container.sh logs postgres -f
+./apple-container.sh logs redis -f
+
+# Pull all configured images for linux/arm64, then recreate containers.
+./apple-container.sh pull
+./apple-container.sh up --recreate
+
+# Delete containers and the network, preserving named volumes.
+./apple-container.sh destroy --yes
+
+# Permanently delete the stack and all application/database/cache data.
+./apple-container.sh destroy --volumes --yes
+```
+
+`destroy --volumes` does not remove `.env`, backup files, or pulled images. Delete credentials and backups separately when decommissioning a deployment. Use `container image delete <image>` only after confirming no other Apple containers use that image.
+
+After a host reboot or `container system stop`, run `./apple-container.sh up` again. Apple `container` does not automatically restart persisted containers.
+
+## Configuration
+
+The script uses `deploy/.env`, the same source file used by Docker Compose. Export `SUB2API_ENV_FILE` to use another file for every command in the current shell:
+
+```bash
+export SUB2API_ENV_FILE=/absolute/path/to/sub2api.env
+./apple-container.sh init
+./apple-container.sh up
+```
+
+Apple-specific image overrides are available:
+
+```dotenv
+APPLE_CONTAINER_SUB2API_IMAGE=weishaw/sub2api:latest
+APPLE_CONTAINER_POSTGRES_IMAGE=postgres:18-alpine
+APPLE_CONTAINER_REDIS_IMAGE=redis:8-alpine
+```
+
+By default, Apple `container` selects the private IPv4 subnet for the managed
+network. Set `APPLE_CONTAINER_NETWORK_SUBNET` only when host-side tooling needs
+a stable network gateway:
+
+```dotenv
+APPLE_CONTAINER_NETWORK_SUBNET=
+```
+
+Leave the setting empty to keep automatic subnet allocation. When setting it,
+choose a CIDR that does not overlap the host LAN or VPN. The script applies the
+setting only when it creates `sub2api-apple`. If the existing managed network
+uses a different subnet, it stops without deleting any resources. To migrate
+intentionally, run `./apple-container.sh destroy --yes` to remove the managed
+containers and network while preserving named volumes, then run
+`./apple-container.sh up`.
+
+The normal `up` command recreates the application container, so application environment changes are applied immediately. Use `up --recreate` when changing PostgreSQL or Redis container images or Redis runtime configuration. Persistent data remains in named volumes.
+
+`POSTGRES_USER`, `POSTGRES_PASSWORD`, and `POSTGRES_DB` are applied only when PostgreSQL initializes an empty data volume. Changing them in `.env` and recreating the container does not change an existing database. Rotate a password with `ALTER ROLE`, and plan explicit migrations for user or database changes. To intentionally initialize a new empty database, first back up the old one and use `destroy --volumes`.
+
+Apple-specific handling of shared settings:
+
+| Setting | Apple workflow behavior |
+|---|---|
+| Application and gateway variables | Passed to Sub2API from `.env` |
+| `BIND_HOST`, `SERVER_PORT` | Used for the macOS published port |
+| `POSTGRES_USER`, `POSTGRES_PASSWORD`, `POSTGRES_DB` | PostgreSQL first initialization only |
+| `REDIS_PASSWORD` | Applied to Redis and Sub2API |
+| `DATABASE_PORT`, `REDIS_PORT` | Internal ports are fixed to 5432 and 6379 |
+| `POSTGRES_MAX_*`, `REDIS_MAXCLIENTS` | Not currently applied to the database/cache server |
+
+## Managed Resources
+
+The script creates only resources carrying the `org.sub2api.stack=apple-container` label:
+
+| Type | Names |
+|---|---|
+| Containers | `sub2api-apple`, `sub2api-apple-postgres`, `sub2api-apple-redis` |
+| Network | `sub2api-apple` |
+| Volumes | `sub2api-apple-data`, `sub2api-apple-postgres-data`, `sub2api-apple-redis-data` |
+
+The PostgreSQL volume is mounted at `/var/lib/postgresql`, retaining PostgreSQL 18's default child data directory. Sub2API data and its updatable runtime binary use separate child directories in `sub2api-apple-data`; Redis also stores data below its Apple volume mount point. This is required because Apple named volumes do not have Docker's copy-up and mount-point ownership behavior.
+
+## Networking
+
+Apple `container` 1.1 does not provide Compose-style network-scoped service aliases. After PostgreSQL and Redis start, the script reads their current private-network IPv4 addresses from `container inspect`, injects those addresses into a newly created application container, and then starts Sub2API. The script does not modify `~/.config/container/config.toml` or the macOS host resolver.
+
+All three services attach only to the private `sub2api-apple` network. Only the application publishes a host port; database and Redis ports remain unpublished.
+
+The application container is intentionally recreated by every `up` and `restart` operation because dependency VM addresses can change after they stop. Application data remains in `sub2api-apple-data`.
+
+The script checks the published `/health` endpoint from macOS before reporting success. Approve the Local Network prompt on first startup. If the internal probe succeeds but the host-port probe fails with a connection reset, enable Local Network access for `container-runtime-linux`, run `container system stop` followed by `container system start`, and then run `up` again. Runtime upgrades may prompt for permission again.
+
+## Web UI Updates
+
+The Web UI uses the same update flow as the Docker deployment: it downloads a release over GitHub, atomically replaces the active executable, and asks the application to restart. Docker supplies the restart policy in a Compose deployment; `apple-container.sh` supplies an equivalent process supervisor inside the Apple application container.
+
+The active executable lives in `sub2api-apple-data` so a later `up`, `restart`, or `up --recreate` does not discard an update downloaded from the Web UI. The script records the configured base image ID alongside it; when `APPLE_CONTAINER_SUB2API_IMAGE` resolves to a different image ID, the image's `/app/sub2api` becomes the new active executable. This keeps explicit image upgrades authoritative while preserving in-place updates across routine application-container recreation.
+
+If GitHub is not reachable directly, set `UPDATE_PROXY_URL` to a proxy address reachable from the Apple container VM. A proxy listening only on the Mac's `127.0.0.1` is not reachable as `127.0.0.1` from inside the VM; use an appropriately restricted host gateway listener instead.
+
+## Backup and Upgrade
+
+Pin image release tags or digests in `.env` before using this workflow for persistent data. Before an application or database image upgrade, create backups while the stack is healthy:
+
+```bash
+umask 077
+mkdir -p backups
+
+# Logical PostgreSQL backup.
+container exec sub2api-apple sh -c \
+  'PGPASSWORD="$DATABASE_PASSWORD" pg_dump -h "$DATABASE_HOST" -U "$DATABASE_USER" "$DATABASE_DBNAME"' \
+  > backups/sub2api.sql
+
+# Application configuration and local files.
+container exec sub2api-apple sh -c 'tar -C "$DATA_DIR" -czf - .' \
+  > backups/sub2api-data.tar.gz
+
+./apple-container.sh pull
+./apple-container.sh up --recreate
+./apple-container.sh status
+```
+
+Database migrations are forward-only. Keep the previous image reference and both backups until the upgraded stack has been validated; image rollback alone cannot reverse a migrated database. Test restore procedures before relying on this workflow for important data.
+
+To restore these backups into an existing stack, first ensure the image versions are compatible with the backup, then stop writers and replace both data sets:
+
+```bash
+# Ensure empty/current resources exist, then stop the stack.
+./apple-container.sh up
+./apple-container.sh down
+
+# Remove only the app container so a helper can mount its named volume.
+container delete sub2api-apple
+SUB2API_IMAGE=weishaw/sub2api:latest # Match APPLE_CONTAINER_SUB2API_IMAGE in .env.
+container run --rm --name sub2api-apple-data-restore \
+  --entrypoint /bin/sh \
+  --volume sub2api-apple-data:/restore \
+  --volume "$PWD/backups:/backup:ro" \
+  "$SUB2API_IMAGE" \
+  -c 'rm -rf /restore/data && mkdir -p /restore/data && tar -xzf /backup/sub2api-data.tar.gz -C /restore/data'
+
+# Restore the logical database while the application is absent.
+container start sub2api-apple-postgres
+until container exec sub2api-apple-postgres sh -c 'pg_isready -U "$POSTGRES_USER" -d "$POSTGRES_DB"'; do sleep 1; done
+container copy backups/sub2api.sql sub2api-apple-postgres:/tmp/sub2api.sql
+container exec sub2api-apple-postgres sh -c '
+  export PGPASSWORD="$POSTGRES_PASSWORD"
+  dropdb -h 127.0.0.1 -U "$POSTGRES_USER" --if-exists --force "$POSTGRES_DB"
+  createdb -h 127.0.0.1 -U "$POSTGRES_USER" "$POSTGRES_DB"
+  psql -h 127.0.0.1 -U "$POSTGRES_USER" -d "$POSTGRES_DB" -v ON_ERROR_STOP=1 -f /tmp/sub2api.sql
+  rm /tmp/sub2api.sql
+'
+
+./apple-container.sh up
+./apple-container.sh status
+```
+
+For disaster recovery after deleting the named volumes, run `up` once to create a fresh stack before following the restore sequence. Perform restore drills with non-production data first.
+
+To upgrade the Apple runtime itself:
+
+```bash
+./apple-container.sh down
+container system stop
+# Install/update Apple container 1.1.0 or newer.
+container system start
+./apple-container.sh up
+```
+
+## Operational Limitations
+
+- There is no `restart: unless-stopped` equivalent. Run `up` after reboot, or add your own launchd supervisor.
+- Health probes run during `up`, `restart`, and `status`; Apple `container` does not continuously schedule them.
+- Docker Compose, Testcontainers, Buildx, and tools requiring `/var/run/docker.sock` cannot use this runtime directly.
+- Named volume backup and restore must be tested before using this workflow for important data.
+- The script targets native `linux/arm64` images. The normal Sub2API release publishes an arm64 variant.
+- Runtime environment values, including credentials, are retained in Apple container configuration and are visible to users who can inspect the local runtime.
diff --git a/Caddyfile b/Caddyfile
new file mode 100644
index 0000000..77e1bf4
--- /dev/null
+++ b/Caddyfile
@@ -0,0 +1,112 @@
+{
+	servers {
+		max_header_size 64KB
+		timeouts {
+			read_header 10s
+			idle 2m
+		}
+	}
+}
+
+# 修改为你的域名
+api.sub2api.com {
+	# This baseline assumes clients connect directly to Caddy. When Caddy is
+	# behind a CDN, configure explicit trusted proxy CIDRs and {client_ip} as
+	# documented in EDGE_SECURITY.md; {remote_host} would otherwise be the CDN.
+	# =========================================================================
+	# TLS 安全配置
+	# =========================================================================
+	tls {
+		# 仅使用 TLS 1.2 和 1.3
+		protocols tls1.2 tls1.3
+
+		# 优先使用的加密套件
+		ciphers TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384 TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384 TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256 TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256 TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256
+	}
+
+	# =========================================================================
+	# 反向代理配置
+	# =========================================================================
+	reverse_proxy localhost:8080 {
+		# 健康检查
+		health_uri /health
+		health_interval 30s
+		health_timeout 10s
+		health_status 200
+
+		# 负载均衡策略（单节点可忽略，多节点时有用）
+		lb_policy round_robin
+		lb_try_duration 5s
+		lb_try_interval 250ms
+
+		# 仅从实际 TCP 对端生成转发头，避免透传客户端伪造值。
+		header_up X-Real-IP {remote_host}
+		header_up X-Forwarded-For {remote_host}
+		header_up X-Forwarded-Proto {scheme}
+		header_up X-Forwarded-Host {host}
+		# 连接池优化
+		transport http {
+			keepalive 120s
+			keepalive_idle_conns 256
+			read_buffer 16KB
+			write_buffer 16KB
+			compression off
+		}
+
+		# 故障转移
+		fail_duration 30s
+		max_fails 3
+		unhealthy_status 500 502 503 504
+	}
+
+	# =========================================================================
+	# 压缩配置
+	# =========================================================================
+	encode {
+		zstd
+		gzip 6
+		minimum_length 256
+		match {
+			# 不使用 text/*，否则 text/event-stream 会被压缩并缓冲到流结束
+			header Content-Type text/css*
+			header Content-Type text/csv*
+			header Content-Type text/html*
+			header Content-Type text/javascript*
+			header Content-Type text/markdown*
+			header Content-Type text/plain*
+			header Content-Type text/xml*
+			header Content-Type application/json*
+			header Content-Type application/javascript*
+			header Content-Type application/xml*
+			header Content-Type application/rss+xml*
+			header Content-Type image/svg+xml*
+		}
+	}
+
+	# =========================================================================
+	# 请求大小限制 (防止大文件攻击)
+	# =========================================================================
+	request_body {
+		max_size 256MB
+	}
+
+	# =========================================================================
+	# 日志配置
+	# =========================================================================
+	log {
+		output file /var/log/caddy/sub2api.log {
+			roll_size 50mb
+			roll_keep 10
+			roll_keep_for 720h
+		}
+		format json
+		level INFO
+	}
+
+	# =========================================================================
+	# 错误处理
+	# =========================================================================
+	handle_errors {
+		respond "{err.status_code} {err.status_text}"
+	}
+}
diff --git a/DATAMANAGEMENTD_CN.md b/DATAMANAGEMENTD_CN.md
new file mode 100644
index 0000000..774f03a
--- /dev/null
+++ b/DATAMANAGEMENTD_CN.md
@@ -0,0 +1,78 @@
+# datamanagementd 部署说明（数据管理）
+
+本文说明如何在宿主机部署 `datamanagementd`，并与主进程联动开启“数据管理”功能。
+
+## 1. 关键约束
+
+- 主进程固定探测路径：`/tmp/sub2api-datamanagement.sock`
+- 仅当该 Unix Socket 可连通且 `Health` 成功时，后台“数据管理”才会启用
+- `datamanagementd` 使用 SQLite 持久化元数据，不依赖主库
+
+## 2. 宿主机构建与运行
+
+```bash
+cd /opt/sub2api-src/datamanagement
+go build -o /opt/sub2api/datamanagementd ./cmd/datamanagementd
+
+mkdir -p /var/lib/sub2api/datamanagement
+chown -R sub2api:sub2api /var/lib/sub2api/datamanagement
+```
+
+手动启动示例：
+
+```bash
+/opt/sub2api/datamanagementd \
+  -socket-path /tmp/sub2api-datamanagement.sock \
+  -sqlite-path /var/lib/sub2api/datamanagement/datamanagementd.db \
+  -version 1.0.0
+```
+
+## 3. systemd 托管（推荐）
+
+仓库已提供示例服务文件：`deploy/sub2api-datamanagementd.service`
+
+```bash
+sudo cp deploy/sub2api-datamanagementd.service /etc/systemd/system/
+sudo systemctl daemon-reload
+sudo systemctl enable --now sub2api-datamanagementd
+sudo systemctl status sub2api-datamanagementd
+```
+
+查看日志：
+
+```bash
+sudo journalctl -u sub2api-datamanagementd -f
+```
+
+也可以使用一键安装脚本（自动安装二进制 + 注册 systemd）：
+
+```bash
+# 方式一：使用现成二进制
+sudo ./deploy/install-datamanagementd.sh --binary /path/to/datamanagementd
+
+# 方式二：从源码构建后安装
+sudo ./deploy/install-datamanagementd.sh --source /path/to/sub2api
+```
+
+## 4. Docker 部署联动
+
+若 `sub2api` 运行在 Docker 容器中，需要将宿主机 Socket 挂载到容器同路径：
+
+```yaml
+services:
+  sub2api:
+    volumes:
+      - /tmp/sub2api-datamanagement.sock:/tmp/sub2api-datamanagement.sock
+```
+
+建议在 `docker-compose.override.yml` 中维护该挂载，避免覆盖主 compose 文件。
+
+## 5. 依赖检查
+
+`datamanagementd` 执行备份时依赖以下工具：
+
+- `pg_dump`
+- `redis-cli`
+- `docker`（仅 `source_mode=docker_exec` 时）
+
+缺失依赖会导致对应任务失败，并在任务详情中体现错误信息。
diff --git a/DOCKER.md b/DOCKER.md
new file mode 100644
index 0000000..87d1f83
--- /dev/null
+++ b/DOCKER.md
@@ -0,0 +1,90 @@
+# Sub2API Docker Image
+
+Sub2API is an AI API Gateway Platform for distributing and managing AI product subscription API quotas.
+
+## Quick Start
+
+```bash
+docker run -d \
+  --name sub2api \
+  -p 8080:8080 \
+  -e DATABASE_URL="postgres://user:pass@host:5432/sub2api" \
+  -e REDIS_URL="redis://host:6379" \
+  weishaw/sub2api:latest
+```
+
+## Docker Compose
+
+```yaml
+version: '3.8'
+
+services:
+  sub2api:
+    image: weishaw/sub2api:latest
+    ports:
+      - "8080:8080"
+    environment:
+      - DATABASE_URL=postgres://postgres:postgres@db:5432/sub2api?sslmode=disable
+      - REDIS_URL=redis://redis:6379
+    depends_on:
+      - db
+      - redis
+
+  db:
+    image: postgres:15-alpine
+    environment:
+      - POSTGRES_USER=postgres
+      - POSTGRES_PASSWORD=postgres
+      - POSTGRES_DB=sub2api
+    volumes:
+      - postgres_data:/var/lib/postgresql/data
+
+  redis:
+    image: redis:7-alpine
+    volumes:
+      - redis_data:/data
+
+volumes:
+  postgres_data:
+  redis_data:
+```
+
+## Startup and Database Recovery
+
+Sub2API runs database migrations while starting. PostgreSQL may still be
+recovering briefly after a host or Docker daemon restart. The application
+retries transient PostgreSQL startup and connection errors with bounded
+exponential backoff, then continues startup when the database is ready.
+Permanent errors such as invalid credentials, migration checksum mismatches,
+SQL errors, and incompatible data fail immediately.
+
+The Compose deployment also checks PostgreSQL readiness with both `pg_isready`
+and a simple SQL query. `depends_on: condition: service_healthy` helps order a
+fresh Compose start, but application-level retries are still required when
+Docker restores existing containers after a host restart.
+
+## Environment Variables
+
+| Variable | Description | Required | Default |
+|----------|-------------|----------|---------|
+| `DATABASE_URL` | PostgreSQL connection string | Yes | - |
+| `REDIS_URL` | Redis connection string | Yes | - |
+| `PORT` | Server port | No | `8080` |
+| `GIN_MODE` | Gin framework mode (`debug`/`release`) | No | `release` |
+
+## Supported Architectures
+
+- `linux/amd64`
+- `linux/arm64`
+
+## Tags
+
+- `latest` - Latest stable release
+- `x.y.z` - Specific version
+- `x.y` - Latest patch of minor version
+- `x` - Latest minor of major version
+
+## Links
+
+- [GitHub Repository](https://github.com/weishaw/sub2api)
+- [Documentation](https://github.com/weishaw/sub2api#readme)
diff --git a/Dockerfile b/Dockerfile
new file mode 100644
index 0000000..d5c580b
--- /dev/null
+++ b/Dockerfile
@@ -0,0 +1,126 @@
+# =============================================================================
+# Sub2API Multi-Stage Dockerfile
+# =============================================================================
+# Stage 1: Build frontend
+# Stage 2: Build Go backend with embedded frontend
+# Stage 3: Final minimal image
+# =============================================================================
+
+ARG NODE_IMAGE=node:24-alpine
+ARG GOLANG_IMAGE=golang:1.27.2-alpine
+ARG ALPINE_IMAGE=alpine:3.20
+ARG GOPROXY=https://goproxy.cn,direct
+ARG GOSUMDB=sum.golang.google.cn
+
+# -----------------------------------------------------------------------------
+# Stage 1: Frontend Builder
+# -----------------------------------------------------------------------------
+FROM ${NODE_IMAGE} AS frontend-builder
+
+WORKDIR /app/frontend
+ENV NODE_OPTIONS=--max-old-space-size=1536
+
+# Install pnpm. Keep this pinned to the lockfile-compatible major version so
+# Docker builds remain reproducible when pnpm changes config validation rules.
+RUN corepack enable && corepack prepare pnpm@9.15.9 --activate
+
+# Install dependencies first (better caching)
+COPY frontend/package.json frontend/pnpm-lock.yaml ./
+RUN pnpm install --frozen-lockfile
+
+# Copy frontend source and build.
+# LegalDocumentView.vue (admin-compliance gate) build-time imports
+# ../../../../docs/legal/*.md?raw, so docs/legal/ must sit beside frontend/
+# in the image (WORKDIR /app/frontend -> resolves to /app/docs/legal/*.md).
+# Copy only that subtree to keep the build dependency minimal.
+COPY frontend/ ./
+COPY docs/legal/ /app/docs/legal/
+RUN pnpm run build
+
+# -----------------------------------------------------------------------------
+# Stage 2: Backend Builder
+# -----------------------------------------------------------------------------
+FROM ${GOLANG_IMAGE} AS backend-builder
+
+# Build arguments for version info (set by CI)
+ARG VERSION=
+ARG COMMIT=docker
+ARG DATE
+ARG GOPROXY
+ARG GOSUMDB
+
+ENV GOPROXY=${GOPROXY}
+ENV GOSUMDB=${GOSUMDB}
+
+# Install build dependencies
+RUN apk add --no-cache git ca-certificates tzdata
+
+WORKDIR /app/backend
+
+# Copy go mod files first (better caching)
+COPY backend/go.mod backend/go.sum ./
+RUN go mod download
+
+# Copy backend source first
+COPY backend/ ./
+
+# Copy frontend dist from previous stage (must be after backend copy to avoid being overwritten)
+COPY --from=frontend-builder /app/backend/internal/web/dist ./internal/web/dist
+
+# Build the binary (BuildType=release for CI builds, embed frontend)
+# Version precedence: build arg VERSION > exact git tag > cmd/server/VERSION
+RUN VERSION_VALUE="${VERSION}" && \
+    if [ -z "${VERSION_VALUE}" ]; then VERSION_VALUE="$(./scripts/resolve-version.sh)"; fi && \
+    DATE_VALUE="${DATE:-$(date -u +%Y-%m-%dT%H:%M:%SZ)}" && \
+    CGO_ENABLED=0 GOOS=linux go build \
+    -tags embed \
+    -ldflags="-s -w -X main.Version=${VERSION_VALUE} -X main.Commit=${COMMIT} -X main.Date=${DATE_VALUE} -X main.BuildType=release" \
+    -o /app/sub2api \
+    ./cmd/server
+
+# -----------------------------------------------------------------------------
+# Stage 3: Final Runtime Image
+# -----------------------------------------------------------------------------
+FROM ${ALPINE_IMAGE}
+
+# Labels
+LABEL maintainer="Wei-Shaw <github.com/Wei-Shaw>"
+LABEL description="Sub2API - AI API Gateway Platform"
+LABEL org.opencontainers.image.source="https://github.com/Wei-Shaw/sub2api"
+
+# Install runtime dependencies
+RUN apk add --no-cache \
+    ca-certificates \
+    tzdata \
+    curl \
+    su-exec \
+    && rm -rf /var/cache/apk/*
+
+# Create non-root user
+RUN addgroup -g 1000 sub2api && \
+    adduser -u 1000 -G sub2api -s /bin/sh -D sub2api
+
+# Set working directory
+WORKDIR /app
+
+# Copy binary and runtime fallback resources from builder
+COPY --from=backend-builder /app/sub2api /app/sub2api
+COPY --from=backend-builder --chown=sub2api:sub2api /app/backend/resources /app/resources
+
+# Create data directory
+RUN mkdir -p /app/data && chown -R sub2api:sub2api /app
+
+# Copy entrypoint script (fixes volume permissions then drops to sub2api)
+COPY deploy/docker-entrypoint.sh /app/docker-entrypoint.sh
+RUN chmod +x /app/docker-entrypoint.sh
+
+# Expose port (can be overridden by SERVER_PORT env var)
+EXPOSE 8080
+
+# Health check
+HEALTHCHECK --interval=30s --timeout=10s --start-period=10s --retries=3 \
+    CMD wget -q -T 5 -O /dev/null http://localhost:${SERVER_PORT:-8080}/health || exit 1
+
+# Run the application (entrypoint fixes /app/data ownership then execs as sub2api)
+ENTRYPOINT ["/app/docker-entrypoint.sh"]
+CMD ["/app/sub2api"]
diff --git a/EDGE_SECURITY.md b/EDGE_SECURITY.md
new file mode 100644
index 0000000..5e9ab10
--- /dev/null
+++ b/EDGE_SECURITY.md
@@ -0,0 +1,209 @@
+# Edge and HTTP Ingress Security
+
+Sub2API supports long-lived SSE and WebSocket requests. Protect the request
+ingress without imposing a response `WriteTimeout`: a write deadline would
+terminate healthy long generations and streams.
+
+## Application defaults
+
+- `server.max_header_bytes: 65536` limits HTTP/1 request headers to 64 KiB;
+  Go maps it to the corresponding HTTP/2 header-list limit.
+- `server.read_header_timeout: 10` bounds slow-header attacks. It does not
+  limit request processing or response streaming.
+- `server.max_request_body_size: 268435456` is the absolute 256 MiB safety net.
+- `gateway.max_body_size: 268435456` remains available to multimodal, Gemini,
+  image, video, and batch-image endpoints.
+- `gateway.text_max_body_size: 33554432` limits the known pure-text
+  `/embeddings` and `/alpha/search` endpoints to 32 MiB.
+- H2C defaults to 50 concurrent streams per connection, a 2 MiB connection
+  upload window, and a 512 KiB stream upload window.
+- Invalid credential abuse is limited in process by trusted client IP (IPv6
+  `/64`): 120 failures per 60 seconds followed by a 60-second block. This is a
+  per-instance safety net; multi-instance enforcement still belongs at the
+  load balancer, CDN, or WAF.
+
+Do not add a single application-wide request semaphore: an SSE request may
+legitimately occupy it for many minutes. Apply connection and unauthenticated
+request controls at the edge; authenticated user/API-key concurrency remains
+the application's responsibility.
+
+## Trusted client IPs
+
+`security.trust_forwarded_ip_for_api_key_acl` is enabled by default for upgrade
+compatibility. While enabled, raw forwarding headers take over client-IP
+resolution for logs and security-sensitive paths. Custom headers from
+`security.forwarded_client_ip_headers` are checked in configured order before
+the built-in `CF-Connecting-IP`, `X-Real-IP`, and `X-Forwarded-For` fallback.
+Header names are case-insensitive, normalized when loaded, de-duplicated, and
+limited to 16 unique valid HTTP field names. Header values must contain IP
+literals; comma-separated values are supported, invalid entries are skipped,
+and public addresses are preferred over private fallback addresses.
+
+The list can be supplied in YAML or with the comma-separated environment
+variable `SECURITY_FORWARDED_CLIENT_IP_HEADERS`; an explicitly empty environment
+value clears YAML values. It is also editable from the admin security settings
+and updates at runtime without a restart. A request snapshots the switch and
+header list together, so one request cannot mix old and new settings. Custom
+headers are ignored completely when the switch is disabled. In that mode Gin's
+`server.trusted_proxies` chain is authoritative: configure only the exact
+CIDR/IP addresses that connect directly to Sub2API. An explicit empty list
+trusts no forwarded client IPs.
+
+On the first upgrade to this mode, a legacy `false` value is changed to `true`
+only when `server.trusted_proxies` was not explicitly configured; explicit
+proxy policies remain in secure mode. New installations persist the configured
+custom header list during database initialization. Existing installations
+backfill a missing database value from the YAML configuration. A hidden
+migration marker prevents later administrator changes from being overwritten.
+If settings cannot be read or the persisted custom-header list is malformed,
+the process fails closed to trusted-proxy mode with no custom headers. If a
+migration write fails, the computed mode remains active for the current process
+and startup records a warning.
+
+Compatibility takeover accepts forwarded headers without validating the direct
+peer, including any configured custom header. Protect the origin from direct
+access while it is enabled. A CDN deployment must firewall the origin so only
+the CDN or load balancer can reach it, and that proxy must overwrite every
+trusted client-IP header rather than append an untrusted client value.
+
+Example for a proxy on the same host:
+
+```yaml
+server:
+  trusted_proxies:
+    - 127.0.0.1/32
+    - ::1/128
+```
+
+## Nginx baseline
+
+Define shared zones in the `http` block. Tune rates to measured legitimate
+traffic; the values below are conservative starting points, not universal
+capacity targets.
+
+```nginx
+limit_conn_zone $binary_remote_addr zone=sub2api_conn:20m;
+limit_req_zone  $binary_remote_addr zone=sub2api_auth:20m rate=5r/s;
+limit_req_zone  $binary_remote_addr zone=sub2api_api:40m rate=30r/s;
+map $http_upgrade $connection_upgrade {
+    default upgrade;
+    ''      close;
+}
+
+server {
+    listen 443 ssl http2;
+    server_name api.example.com;
+
+    client_header_timeout 10s;
+    client_max_body_size 256m;
+    large_client_header_buffers 4 16k;
+    limit_conn sub2api_conn 40;
+
+    location ~ ^/(auth|api/auth)/ {
+        limit_req zone=sub2api_auth burst=10 nodelay;
+        proxy_pass http://127.0.0.1:8080;
+    }
+
+    location ~ ^/(v1/)?(embeddings|alpha/search)$ {
+        client_max_body_size 32m;
+        limit_req zone=sub2api_api burst=60 nodelay;
+        proxy_pass http://127.0.0.1:8080;
+    }
+
+    location / {
+        limit_req zone=sub2api_api burst=60 nodelay;
+        proxy_http_version 1.1;
+        proxy_set_header Host $host;
+        proxy_set_header X-Real-IP $remote_addr;
+        proxy_set_header X-Forwarded-For $remote_addr;
+        proxy_set_header X-Forwarded-Proto $scheme;
+        proxy_set_header Upgrade $http_upgrade;
+        proxy_set_header Connection $connection_upgrade;
+        proxy_buffering off;
+        proxy_request_buffering off;
+        proxy_read_timeout 1800s;
+        proxy_send_timeout 1800s;
+        proxy_pass http://127.0.0.1:8080;
+    }
+}
+```
+
+If Nginx gzip is enabled in the `http` block, keep `text/event-stream` out of
+`gzip_types` and do not use `gzip_types *` for Sub2API. The
+`proxy_buffering off` setting above prevents proxy buffering, but it does not
+disable the gzip response filter. Use an explicit list for ordinary responses:
+
+```nginx
+gzip on;
+gzip_types text/plain text/css application/json application/javascript application/xml image/svg+xml;
+```
+
+If a shared global configuration cannot exclude SSE by content type, set
+`gzip off;` in the locations serving streaming API routes. This leaves gzip
+available for the web UI and static assets.
+
+Do not use an incoming `$http_x_forwarded_for` value unless Nginx real-IP
+processing is restricted to explicit trusted proxy CIDRs.
+
+## Caddy and CDN
+
+The bundled `deploy/Caddyfile` sets a 64 KiB header limit, a 10-second header
+timeout, a 256 MiB absolute body limit, and overwrites forwarded addresses from
+the TCP peer. It is therefore a direct-to-Caddy baseline. Do not use its
+`{remote_host}` forwarding lines unchanged behind a CDN: all clients would be
+attributed to a CDN egress address, collapsing rejection aggregation and the
+invalid-auth limiter onto unrelated users.
+
+The bundled Caddy configuration leaves `flush_interval` unset so Caddy can
+automatically flush `text/event-stream` responses while still propagating
+client cancellation upstream. Do not set it globally: positive values can add
+streaming latency, while Caddy 2.6.2's special `-1` mode also causes
+reverse-proxied requests to continue after clients disconnect. The
+configuration uses an explicit response content-type list for compression. Do
+not replace that list with `text/*` or the shorthand `encode gzip zstd`: both
+match `text/event-stream` and can buffer SSE until the response ends. Keep
+streaming responses uncompressed while retaining compression for the web UI,
+JSON, and static assets.
+
+For a CDN deployment, first firewall the origin so only current CDN egress
+CIDRs can connect. Then configure those exact ranges as Caddy trusted proxies
+and derive upstream headers from Caddy's parsed `{client_ip}`. For example:
+
+```caddyfile
+{
+	servers {
+		trusted_proxies static 192.0.2.0/24 2001:db8:1234::/48
+		trusted_proxies_strict
+		client_ip_headers CF-Connecting-IP X-Forwarded-For
+	}
+}
+
+api.example.com {
+	reverse_proxy 127.0.0.1:8080 {
+		header_up X-Real-IP {client_ip}
+		header_up X-Forwarded-For {client_ip}
+	}
+}
+```
+
+Replace the documentation ranges with the CDN's published, automatically
+maintained egress ranges. `CF-Connecting-IP` is safe here only because direct
+origin access is blocked and Caddy trusts only those TCP peers. Configure
+Sub2API `server.trusted_proxies` with the Caddy address/private subnet so the
+application accepts only Caddy's rewritten headers.
+
+Caddy core does not provide a general request-rate limiter; use a trusted
+CDN/WAF, a supported rate-limit module, or host firewall controls.
+
+At a CDN/WAF, configure connection limits, header/body limits, bot challenges,
+and per-IP/ASN rates before traffic reaches the origin. Allow origin ingress
+only from CDN egress CIDRs or a private load balancer. Keep the application port
+off the public Internet.
+
+## DDoS boundary
+
+Application checks reduce amplification after a connection reaches Go. They
+cannot absorb volumetric attacks, TLS floods, bandwidth saturation, or a large
+distributed source set. Those require upstream network capacity, CDN/WAF
+filtering, provider firewall rules, and origin isolation. Avoid high-cardinality
+metrics or per-request database security logs during rejection storms.
diff --git a/Makefile b/Makefile
new file mode 100644
index 0000000..05f3c79
--- /dev/null
+++ b/Makefile
@@ -0,0 +1,44 @@
+.PHONY: wire build build-embed test-unit test-integration test-e2e test-cover-integration
+
+VERSION ?= $(shell ./scripts/resolve-version.sh)
+LDFLAGS ?= -s -w -X main.Version=$(VERSION)
+
+wire:
+	@echo "生成 Wire 代码..."
+	@cd cmd/server && go generate
+	@echo "Wire 代码生成完成"
+
+build:
+	@echo "构建后端（不嵌入前端）..."
+	@go build -ldflags="$(LDFLAGS)" -o bin/server ./cmd/server
+	@echo "构建完成: bin/server"
+
+build-embed:
+	@echo "构建后端（嵌入前端）..."
+	@go build -tags embed -ldflags="$(LDFLAGS)" -o bin/server ./cmd/server
+	@echo "构建完成: bin/server (with embedded frontend)"
+
+test-unit:
+	@go test -tags unit ./... -count=1
+
+test-integration:
+	@go test -tags integration ./... -count=1 -race -parallel=8
+
+test-e2e:
+	@echo "运行 E2E 测试（需要本地服务器运行）..."
+	@go test -tags e2e ./internal/integration/... -count=1 -v
+
+test-cover-integration:
+	@echo "运行集成测试并生成覆盖率报告..."
+	@go test -tags=integration -cover -coverprofile=coverage.out -count=1 -race -parallel=8 ./...
+	@go tool cover -func=coverage.out | tail -1
+	@go tool cover -html=coverage.out -o coverage.html
+	@echo "覆盖率报告已生成: coverage.html"
+
+clean-coverage:
+	@rm -f coverage.out coverage.html
+	@echo "覆盖率文件已清理"
+
+clean: clean-coverage
+	@rm -rf bin/
+	@echo "构建产物已清理"
diff --git a/README.md b/README.md
new file mode 100644
index 0000000..b71334d
--- /dev/null
+++ b/README.md
@@ -0,0 +1,658 @@
+# Sub2API Deployment Files
+
+This directory contains files for deploying Sub2API on Linux servers and Apple-silicon Macs.
+
+## Deployment Methods
+
+| Method | Best For | Setup Wizard |
+|--------|----------|--------------|
+| **Docker Compose** | Quick setup, all-in-one | Not needed (auto-setup) |
+| **Apple container** | Native local stack on macOS 26 | Not needed (auto-setup) |
+| **Binary Install** | Production servers, systemd | Web-based wizard |
+
+## Files
+
+| File | Description |
+|------|-------------|
+| `docker-compose.yml` | Docker Compose configuration (named volumes) |
+| `docker-compose.local.yml` | Docker Compose configuration (local directories, easy migration) |
+| `docker-deploy.sh` | **One-click Docker deployment script (recommended)** |
+| `apple-container.sh` | Native Apple `container` lifecycle script |
+| `APPLE_CONTAINER.md` | Apple `container` deployment and operations guide |
+| `.env.example` | Container environment variables template |
+| `DOCKER.md` | Docker Hub documentation |
+| `install.sh` | One-click binary installation script |
+| `install-datamanagementd.sh` | datamanagementd 一键安装脚本 |
+| `sub2api.service` | Systemd service unit file |
+| `sub2api-datamanagementd.service` | datamanagementd systemd service unit file |
+| `DATAMANAGEMENTD_CN.md` | datamanagementd 部署与联动说明（中文） |
+| `config.example.yaml` | Example configuration file |
+| `EDGE_SECURITY.md` | Reverse proxy, CDN/WAF, trusted proxy, and ingress hardening guide |
+
+---
+
+## Apple container Deployment
+
+Apple-silicon Macs running macOS 26 can run the complete Sub2API, PostgreSQL, and Redis stack with Apple `container` 1.1.0 or newer:
+
+```bash
+./apple-container.sh init
+./apple-container.sh up
+./apple-container.sh status
+./apple-container.sh logs app -f
+```
+
+The script uses Apple named volumes, starts dependencies in order, and performs live readiness checks. The application container supervises the Sub2API process so the Web UI's update-and-restart flow can relaunch an updated binary. It does not provide host-level automatic startup; run `./apple-container.sh up` after a host reboot. Docker Compose remains the recommended production deployment path.
+
+See [APPLE_CONTAINER.md](./APPLE_CONTAINER.md) for configuration, upgrades, persistence, networking behavior, and limitations.
+
+---
+
+## Docker Deployment (Recommended)
+
+### Method 1: One-Click Deployment (Recommended)
+
+Use the automated preparation script for the easiest setup:
+
+```bash
+# Download and run the preparation script
+curl -sSL https://raw.githubusercontent.com/Wei-Shaw/sub2api/main/deploy/docker-deploy.sh | bash
+
+# Or download first, then run
+curl -sSL https://raw.githubusercontent.com/Wei-Shaw/sub2api/main/deploy/docker-deploy.sh -o docker-deploy.sh
+chmod +x docker-deploy.sh
+./docker-deploy.sh
+```
+
+**What the script does:**
+- Downloads `docker-compose.local.yml` and `.env.example`
+- Automatically generates secure secrets (JWT_SECRET, TOTP_ENCRYPTION_KEY, POSTGRES_PASSWORD)
+- Creates `.env` file with generated secrets
+- Creates necessary data directories (data/, postgres_data/, redis_data/)
+- **Displays generated credentials** (POSTGRES_PASSWORD, JWT_SECRET, etc.)
+
+**After running the script:**
+```bash
+# Start services
+docker compose -f docker-compose.local.yml up -d
+
+# View logs
+docker compose -f docker-compose.local.yml logs -f sub2api
+
+# If admin email/password were auto-generated, find them in logs:
+docker compose -f docker-compose.local.yml logs sub2api | grep "Generated admin"
+
+# Access Web UI
+# http://localhost:8080
+```
+
+### Method 2: Manual Deployment
+
+If you prefer manual control:
+
+```bash
+# Clone repository
+git clone https://github.com/Wei-Shaw/sub2api.git
+cd sub2api/deploy
+
+# Configure environment
+cp .env.example .env
+chmod 600 .env
+nano .env  # Set POSTGRES_PASSWORD and other required variables
+
+# Generate secure secrets (recommended)
+JWT_SECRET=$(openssl rand -hex 32)
+TOTP_ENCRYPTION_KEY=$(openssl rand -hex 32)
+echo "JWT_SECRET=${JWT_SECRET}" >> .env
+echo "TOTP_ENCRYPTION_KEY=${TOTP_ENCRYPTION_KEY}" >> .env
+
+# Create data directories
+mkdir -p data postgres_data redis_data
+
+# Start all services using local directory version
+docker compose -f docker-compose.local.yml up -d
+
+# View logs (check for auto-generated admin email and password)
+docker compose -f docker-compose.local.yml logs -f sub2api
+
+# Access Web UI
+# http://localhost:8080
+```
+
+### Deployment Version Comparison
+
+| Version | Data Storage | Migration | Best For |
+|---------|-------------|-----------|----------|
+| **docker-compose.local.yml** | Local directories (./data, ./postgres_data, ./redis_data) | ✅ Easy (tar entire directory) | Production, need frequent backups/migration |
+| **docker-compose.yml** | Named volumes (/var/lib/docker/volumes/) | ⚠️ Requires docker commands | Simple setup, don't need migration |
+
+**Recommendation:** Use `docker-compose.local.yml` (deployed by `docker-deploy.sh`) for easier data management and migration.
+
+### How Auto-Setup Works
+
+When using Docker Compose with `AUTO_SETUP=true`:
+
+1. On first run, the system automatically:
+   - Connects to PostgreSQL and Redis
+   - Applies database migrations (SQL files in `backend/migrations/*.sql`) and records them in `schema_migrations`
+   - Generates JWT secret (if not provided)
+   - Creates admin account (email and password auto-generated if not provided; a provided password must be 8-72 bytes)
+   - Writes config.yaml
+
+2. No manual Setup Wizard needed - just configure `.env` and start
+
+3. If `ADMIN_EMAIL` / `ADMIN_PASSWORD` are not set, check logs for the generated admin email (login username) and password:
+   ```bash
+   docker compose logs sub2api | grep "Generated admin"
+   ```
+
+### Startup and Database Recovery
+
+Sub2API applies database migrations during application startup. PostgreSQL can
+remain in its recovery/startup phase briefly after a host or Docker daemon
+restart. The application retries transient PostgreSQL startup and connection
+errors with bounded exponential backoff, then starts automatically when the
+database becomes ready. Authentication errors, migration checksum mismatches,
+SQL errors, and other permanent configuration or data errors fail immediately.
+
+The Compose example also uses a PostgreSQL health check that verifies both
+server readiness and a simple SQL query. `depends_on: condition: service_healthy`
+controls dependency ordering for a fresh Compose start, but it is not a
+replacement for application-level retries when Docker restores existing
+containers after a host restart.
+
+For systemd deployments, keep `Restart=always` and `RestartSec` configured in
+`sub2api.service`; the application retry covers transient database startup,
+while systemd remains the supervisor for permanent process exits. For
+Kubernetes, use a PostgreSQL readiness probe and retain the Sub2API startup
+retry behavior; configure the application liveness probe separately so a
+database recovery period is not treated as a permanent process failure.
+
+### Database Migration Notes (PostgreSQL)
+
+- Migrations are applied in lexicographic order (e.g. `001_...sql`, `002_...sql`).
+- `schema_migrations` tracks applied migrations (filename + checksum).
+- Migrations are forward-only; rollback requires a DB backup restore or a manual compensating SQL script.
+
+**Verify `users.allowed_groups` → `user_allowed_groups` backfill**
+
+During the incremental GORM→Ent migration, `users.allowed_groups` (legacy `BIGINT[]`) is being replaced by a normalized join table `user_allowed_groups(user_id, group_id)`.
+
+Run this query to compare the legacy data vs the join table:
+
+```sql
+WITH old_pairs AS (
+  SELECT DISTINCT u.id AS user_id, x.group_id
+  FROM users u
+  CROSS JOIN LATERAL unnest(u.allowed_groups) AS x(group_id)
+  WHERE u.allowed_groups IS NOT NULL
+)
+SELECT
+  (SELECT COUNT(*) FROM old_pairs)           AS old_pair_count,
+  (SELECT COUNT(*) FROM user_allowed_groups) AS new_pair_count;
+```
+
+### datamanagementd（数据管理）联动
+
+如需启用管理后台“数据管理”功能，请额外部署宿主机 `datamanagementd`：
+
+- 主进程固定探测 `/tmp/sub2api-datamanagement.sock`
+- Docker 场景下需把宿主机 Socket 挂载到容器内同路径
+- 详细步骤见：`deploy/DATAMANAGEMENTD_CN.md`
+
+### Commands
+
+For **local directory version** (docker-compose.local.yml):
+
+```bash
+# Start services
+docker compose -f docker-compose.local.yml up -d
+
+# Stop services
+docker compose -f docker-compose.local.yml down
+
+# View logs
+docker compose -f docker-compose.local.yml logs -f sub2api
+
+# Restart Sub2API only
+docker compose -f docker-compose.local.yml restart sub2api
+
+# Update to latest version
+docker compose -f docker-compose.local.yml pull
+docker compose -f docker-compose.local.yml up -d
+
+# Remove all data (caution!)
+docker compose -f docker-compose.local.yml down
+rm -rf data/ postgres_data/ redis_data/
+```
+
+For **named volumes version** (docker-compose.yml):
+
+```bash
+# Start services
+docker compose up -d
+
+# Stop services
+docker compose down
+
+# View logs
+docker compose logs -f sub2api
+
+# Restart Sub2API only
+docker compose restart sub2api
+
+# Update to latest version
+docker compose pull
+docker compose up -d
+
+# Remove all data (caution!)
+docker compose down -v
+```
+
+### Environment Variables
+
+| Variable | Required | Default | Description |
+|----------|----------|---------|-------------|
+| `POSTGRES_PASSWORD` | **Yes** | - | PostgreSQL password |
+| `JWT_SECRET` | **Recommended** | *(auto-generated)* | JWT secret (fixed for persistent sessions) |
+| `TOTP_ENCRYPTION_KEY` | **Recommended** | *(auto-generated)* | TOTP encryption key (fixed for persistent 2FA) |
+| `SERVER_PORT` | No | `8080` | Server port |
+| `ADMIN_EMAIL` | No | *(auto-generated)* | Admin email (login username) |
+| `ADMIN_PASSWORD` | No | *(auto-generated)* | Admin password (8-72 bytes) |
+| `TZ` | No | `Asia/Shanghai` | Timezone |
+| `UPDATE_GITHUB_TOKEN` | No | *(empty)* | Token for `api.github.com` release checks only; asset downloads remain anonymous. |
+| `GEMINI_OAUTH_CLIENT_ID` | No | *(builtin)* | Google OAuth client ID (Gemini OAuth). Leave empty to use the built-in Gemini CLI client. |
+| `GEMINI_OAUTH_CLIENT_SECRET` | No | *(builtin)* | Google OAuth client secret (Gemini OAuth). Leave empty to use the built-in Gemini CLI client. |
+| `GEMINI_OAUTH_SCOPES` | No | *(default)* | OAuth scopes (Gemini OAuth) |
+| `GEMINI_QUOTA_POLICY` | No | *(empty)* | JSON overrides for Gemini local quota simulation (Code Assist only). |
+
+See `.env.example` for all available options.
+
+> **Note:** The `docker-deploy.sh` script automatically generates `JWT_SECRET`, `TOTP_ENCRYPTION_KEY`, and `POSTGRES_PASSWORD` for you.
+
+### Easy Migration (Local Directory Version)
+
+When using `docker-compose.local.yml`, all data is stored in local directories, making migration simple:
+
+```bash
+# On source server: Stop services and create archive
+cd /path/to/deployment
+docker compose -f docker-compose.local.yml down
+cd ..
+tar czf sub2api-complete.tar.gz deployment/
+
+# Transfer to new server
+scp sub2api-complete.tar.gz user@new-server:/path/to/destination/
+
+# On new server: Extract and start
+tar xzf sub2api-complete.tar.gz
+cd deployment/
+docker compose -f docker-compose.local.yml up -d
+```
+
+Your entire deployment (configuration + data) is migrated!
+
+---
+
+## Gemini OAuth Configuration
+
+Sub2API supports three methods to connect to Gemini:
+
+### Method 1: Code Assist OAuth (Recommended for GCP Users)
+
+**No configuration needed** - always uses the built-in Gemini CLI OAuth client (public).
+
+1. Leave `GEMINI_OAUTH_CLIENT_ID` and `GEMINI_OAUTH_CLIENT_SECRET` empty
+2. In the Admin UI, create a Gemini OAuth account and select **"Code Assist"** type
+3. Complete the OAuth flow in your browser
+
+> Note: Even if you configure `GEMINI_OAUTH_CLIENT_ID` / `GEMINI_OAUTH_CLIENT_SECRET` for AI Studio OAuth,
+> Code Assist OAuth will still use the built-in Gemini CLI client.
+
+**Requirements:**
+- Google account with access to Google Cloud Platform
+- A GCP project (auto-detected or manually specified)
+
+**How to get Project ID (if auto-detection fails):**
+1. Go to [Google Cloud Console](https://console.cloud.google.com/)
+2. Click the project dropdown at the top of the page
+3. Copy the Project ID (not the project name) from the list
+4. Common formats: `my-project-123456` or `cloud-ai-companion-xxxxx`
+
+### Method 2: AI Studio OAuth (For Regular Google Accounts)
+
+Requires your own OAuth client credentials.
+
+**Step 1: Create OAuth Client in Google Cloud Console**
+
+1. Go to [Google Cloud Console - Credentials](https://console.cloud.google.com/apis/credentials)
+2. Create a new project or select an existing one
+3. **Enable the Generative Language API:**
+   - Go to "APIs & Services" → "Library"
+   - Search for "Generative Language API"
+   - Click "Enable"
+4. **Configure OAuth Consent Screen** (if not done):
+   - Go to "APIs & Services" → "OAuth consent screen"
+   - Choose "External" user type
+   - Fill in app name, user support email, developer contact
+   - Add scopes: `https://www.googleapis.com/auth/generative-language.retriever` (and optionally `https://www.googleapis.com/auth/cloud-platform`)
+   - Add test users (your Google account email)
+5. **Create OAuth 2.0 credentials:**
+   - Go to "APIs & Services" → "Credentials"
+   - Click "Create Credentials" → "OAuth client ID"
+   - Application type: **Web application** (or **Desktop app**)
+   - Name: e.g., "Sub2API Gemini"
+   - Authorized redirect URIs: Add `http://localhost:1455/auth/callback`
+6. Copy the **Client ID** and **Client Secret**
+7. **⚠️ Publish to Production (IMPORTANT):**
+   - Go to "APIs & Services" → "OAuth consent screen"
+   - Click "PUBLISH APP" to move from Testing to Production
+   - **Testing mode limitations:**
+     - Only manually added test users can authenticate (max 100 users)
+     - Refresh tokens expire after 7 days
+     - Users must be re-added periodically
+   - **Production mode:** Any Google user can authenticate, tokens don't expire
+   - Note: For sensitive scopes, Google may require verification (demo video, privacy policy)
+
+**Step 2: Configure Environment Variables**
+
+```bash
+GEMINI_OAUTH_CLIENT_ID=your-client-id.apps.googleusercontent.com
+GEMINI_OAUTH_CLIENT_SECRET=GOCSPX-your-client-secret
+
+# 可选：如需使用 Gemini CLI 内置 OAuth Client（Code Assist / Google One）
+# 安全说明：本仓库不会内置该 client_secret，请在运行环境通过环境变量注入。
+# GEMINI_CLI_OAUTH_CLIENT_SECRET=GOCSPX-your-built-in-secret
+```
+
+**Step 3: Create Account in Admin UI**
+
+1. Create a Gemini OAuth account and select **"AI Studio"** type
+2. Complete the OAuth flow
+   - After consent, your browser will be redirected to `http://localhost:1455/auth/callback?code=...&state=...`
+   - Copy the full callback URL (recommended) or just the `code` and paste it back into the Admin UI
+
+### Method 3: API Key (Simplest)
+
+1. Go to [Google AI Studio](https://aistudio.google.com/app/apikey)
+2. Click "Create API key"
+3. In Admin UI, create a Gemini **API Key** account
+4. Paste your API key (starts with `AIza...`)
+
+### Comparison Table
+
+| Feature | Code Assist OAuth | AI Studio OAuth | API Key |
+|---------|-------------------|-----------------|---------|
+| Setup Complexity | Easy (no config) | Medium (OAuth client) | Easy |
+| GCP Project Required | Yes | No | No |
+| Custom OAuth Client | No (built-in) | Yes (required) | N/A |
+| Rate Limits | GCP quota | Standard | Standard |
+| Best For | GCP developers | Regular users needing OAuth | Quick testing |
+
+---
+
+## Binary Installation
+
+For production servers using systemd.
+
+### One-Line Installation
+
+```bash
+curl -sSL https://raw.githubusercontent.com/Wei-Shaw/sub2api/main/deploy/install.sh | sudo bash
+```
+
+### Manual Installation
+
+1. Download the latest release from [GitHub Releases](https://github.com/Wei-Shaw/sub2api/releases)
+2. Extract and copy the binary to `/opt/sub2api/`
+3. Copy `sub2api.service` to `/etc/systemd/system/`
+4. Run:
+   ```bash
+   sudo systemctl daemon-reload
+   sudo systemctl enable sub2api
+   sudo systemctl start sub2api
+   ```
+5. Open the Setup Wizard in your browser to complete configuration
+
+### Commands
+
+```bash
+# Install
+sudo ./install.sh
+
+# Upgrade
+sudo ./install.sh upgrade
+
+# Uninstall
+sudo ./install.sh uninstall
+```
+
+### Service Management
+
+```bash
+# Start the service
+sudo systemctl start sub2api
+
+# Stop the service
+sudo systemctl stop sub2api
+
+# Restart the service
+sudo systemctl restart sub2api
+
+# Check status
+sudo systemctl status sub2api
+
+# View logs
+sudo journalctl -u sub2api -f
+
+# Enable auto-start on boot
+sudo systemctl enable sub2api
+```
+
+### Configuration
+
+#### Server Address and Port
+
+During installation, you will be prompted to configure the server listen address and port. These settings are stored in the systemd service file as environment variables.
+
+To change after installation:
+
+1. Edit the systemd service:
+   ```bash
+   sudo systemctl edit sub2api
+   ```
+
+2. Add or modify:
+   ```ini
+   [Service]
+   Environment=SERVER_HOST=0.0.0.0
+   Environment=SERVER_PORT=3000
+   ```
+
+3. Reload and restart:
+   ```bash
+   sudo systemctl daemon-reload
+   sudo systemctl restart sub2api
+   ```
+
+#### Gemini OAuth Configuration
+
+If you need to use AI Studio OAuth for Gemini accounts, add the OAuth client credentials to the systemd service file:
+
+1. Edit the service file:
+   ```bash
+   sudo nano /etc/systemd/system/sub2api.service
+   ```
+
+2. Add your OAuth credentials in the `[Service]` section (after the existing `Environment=` lines):
+   ```ini
+   Environment=GEMINI_OAUTH_CLIENT_ID=your-client-id.apps.googleusercontent.com
+   Environment=GEMINI_OAUTH_CLIENT_SECRET=GOCSPX-your-client-secret
+   ```
+
+   如需使用“内置 Gemini CLI OAuth Client”（Code Assist / Google One），还需要注入：
+   ```ini
+   Environment=GEMINI_CLI_OAUTH_CLIENT_SECRET=GOCSPX-your-built-in-secret
+   ```
+
+3. Reload and restart:
+   ```bash
+   sudo systemctl daemon-reload
+   sudo systemctl restart sub2api
+   ```
+
+> **Note:** Code Assist OAuth does not require any configuration - it uses the built-in Gemini CLI client.
+> See the [Gemini OAuth Configuration](#gemini-oauth-configuration) section above for detailed setup instructions.
+
+#### Application Configuration
+
+The main config file is at `/etc/sub2api/config.yaml` (created by Setup Wizard).
+
+### Prerequisites
+
+- Linux server (Ubuntu 20.04+, Debian 11+, CentOS 8+, etc.)
+- PostgreSQL 14+
+- Redis 6+
+- systemd
+
+### Directory Structure
+
+```
+/opt/sub2api/
+├── sub2api              # Main binary
+├── sub2api.backup       # Backup (after upgrade)
+└── data/                # Runtime data
+
+/etc/sub2api/
+└── config.yaml          # Configuration file
+```
+
+---
+
+## Troubleshooting
+
+### Docker
+
+For **local directory version**:
+
+```bash
+# Check container status
+docker compose -f docker-compose.local.yml ps
+
+# View detailed logs
+docker compose -f docker-compose.local.yml logs --tail=100 sub2api
+
+# Check database connection
+docker compose -f docker-compose.local.yml exec postgres pg_isready
+
+# Check Redis connection
+docker compose -f docker-compose.local.yml exec redis redis-cli ping
+
+# Restart all services
+docker compose -f docker-compose.local.yml restart
+
+# Check data directories
+ls -la data/ postgres_data/ redis_data/
+```
+
+For **named volumes version**:
+
+```bash
+# Check container status
+docker compose ps
+
+# View detailed logs
+docker compose logs --tail=100 sub2api
+
+# Check database connection
+docker compose exec postgres pg_isready
+
+# Check Redis connection
+docker compose exec redis redis-cli ping
+
+# Restart all services
+docker compose restart
+```
+
+### Binary Install
+
+```bash
+# Check service status
+sudo systemctl status sub2api
+
+# View recent logs
+sudo journalctl -u sub2api -n 50
+
+# Check config file
+sudo cat /etc/sub2api/config.yaml
+
+# Check PostgreSQL
+sudo systemctl status postgresql
+
+# Check Redis
+sudo systemctl status redis
+```
+
+### Common Issues
+
+1. **Port already in use**: Change `SERVER_PORT` in `.env` or systemd config
+2. **Database connection failed**: Check PostgreSQL is running and credentials are correct
+3. **Redis connection failed**: Check Redis is running and password is correct
+4. **Permission denied**: Ensure proper file ownership for binary install
+
+---
+
+## TLS Fingerprint Configuration
+
+Sub2API supports TLS fingerprint simulation to make requests appear as if they come from the official Claude CLI (Node.js client).
+
+> **💡 Tip:** Visit **[tls.sub2api.org](https://tls.sub2api.org/)** to get TLS fingerprint information for different devices and browsers.
+
+### Default Behavior
+
+- Built-in `claude_cli_v2` profile simulates Node.js 20.x + OpenSSL 3.x
+- JA3 Hash: `1a28e69016765d92e3b381168d68922c`
+- JA4: `t13d5911h1_a33745022dd6_1f22a2ca17c4`
+- Profile selection: `accountID % profileCount`
+
+### Configuration
+
+```yaml
+gateway:
+  tls_fingerprint:
+    enabled: true  # Global switch
+    profiles:
+      # Simple profile (uses default cipher suites)
+      profile_1:
+        name: "Profile 1"
+
+      # Profile with custom cipher suites (use compact array format)
+      profile_2:
+        name: "Profile 2"
+        cipher_suites: [4866, 4867, 4865, 49199, 49195, 49200, 49196]
+        curves: [29, 23, 24]
+        point_formats: 0
+
+      # Another custom profile
+      profile_3:
+        name: "Profile 3"
+        cipher_suites: [4865, 4866, 4867, 49199, 49200]
+        curves: [29, 23, 24, 25]
+```
+
+### Profile Fields
+
+| Field | Type | Description |
+|-------|------|-------------|
+| `name` | string | Display name (required) |
+| `cipher_suites` | []uint16 | Cipher suites in decimal. Empty = default |
+| `curves` | []uint16 | Elliptic curves in decimal. Empty = default |
+| `point_formats` | []uint8 | EC point formats. Empty = default |
+
+### Common Values Reference
+
+**Cipher Suites (TLS 1.3):** `4865` (AES_128_GCM), `4866` (AES_256_GCM), `4867` (CHACHA20)
+
+**Cipher Suites (TLS 1.2):** `49195`, `49196`, `49199`, `49200` (ECDHE variants)
+
+**Curves:** `29` (X25519), `23` (P-256), `24` (P-384), `25` (P-521)
diff --git a/apple-container.sh b/apple-container.sh
new file mode 100755
index 0000000..5a44ae5
--- /dev/null
+++ b/apple-container.sh
@@ -0,0 +1,996 @@
+#!/usr/bin/env bash
+
+set -euo pipefail
+
+SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
+ENV_FILE="${SUB2API_ENV_FILE:-${SCRIPT_DIR}/.env}"
+
+STACK_LABEL_KEY="org.sub2api.stack"
+STACK_LABEL_VALUE="apple-container"
+NETWORK_NAME="sub2api-apple"
+APP_CONTAINER="sub2api-apple"
+POSTGRES_CONTAINER="sub2api-apple-postgres"
+REDIS_CONTAINER="sub2api-apple-redis"
+APP_VOLUME="sub2api-apple-data"
+POSTGRES_VOLUME="sub2api-apple-postgres-data"
+REDIS_VOLUME="sub2api-apple-redis-data"
+PLATFORM="linux/arm64"
+
+TEMP_DIR=""
+LOCK_DIR="${TMPDIR:-/tmp}/sub2api-apple-container.lock"
+LOCK_ACQUIRED=false
+
+APP_IMAGE=""
+POSTGRES_IMAGE=""
+REDIS_IMAGE=""
+BIND_HOST=""
+HOST_PORT=""
+ACCESS_HOST=""
+POSTGRES_USER=""
+POSTGRES_PASSWORD=""
+POSTGRES_DB=""
+REDIS_PASSWORD=""
+TZ_VALUE=""
+NETWORK_SUBNET=""
+POSTGRES_ADDRESS=""
+REDIS_ADDRESS=""
+APP_ENV_FILE=""
+POSTGRES_ENV_FILE=""
+POSTGRES_PROBE_ENV_FILE=""
+REDIS_ENV_FILE=""
+
+info() {
+    printf '[INFO] %s\n' "$*"
+}
+
+warn() {
+    printf '[WARN] %s\n' "$*" >&2
+}
+
+die() {
+    printf '[ERROR] %s\n' "$*" >&2
+    exit 1
+}
+
+usage() {
+    cat <<'EOF'
+Usage: ./apple-container.sh <command> [options]
+
+Commands:
+  init                  Create .env and generate required secrets
+  up [--recreate]       Create and start the complete Sub2API stack
+  down                  Stop the stack and preserve all data
+  restart               Restart the stack in dependency order
+  status                Show container and workload health
+  logs <service> [-f]   Show logs for app, postgres, or redis
+  pull                  Pull all stack images for linux/arm64
+  destroy [options]     Delete stack containers and network
+
+Destroy options:
+  --volumes             Also delete all persistent data volumes
+  --yes                 Skip the confirmation prompt
+
+Environment:
+  SUB2API_ENV_FILE      Path to the deployment env file (default: deploy/.env)
+EOF
+}
+
+cleanup() {
+    local exit_code=$?
+
+    if [[ -n "${TEMP_DIR}" && -d "${TEMP_DIR}" ]]; then
+        rm -rf "${TEMP_DIR}"
+    fi
+    if [[ "${LOCK_ACQUIRED}" == true && -d "${LOCK_DIR}" ]]; then
+        rm -f "${LOCK_DIR}/pid"
+        rmdir "${LOCK_DIR}" 2>/dev/null || true
+    fi
+
+    exit "${exit_code}"
+}
+
+acquire_lock() {
+    if ! mkdir "${LOCK_DIR}" 2>/dev/null; then
+        local owner_pid=""
+        if [[ -f "${LOCK_DIR}/pid" ]]; then
+            owner_pid="$(<"${LOCK_DIR}/pid")"
+        fi
+        if [[ "${owner_pid}" =~ ^[0-9]+$ ]] && ! kill -0 "${owner_pid}" 2>/dev/null; then
+            rm -rf "${LOCK_DIR}"
+            mkdir "${LOCK_DIR}" || die "Failed to reclaim stale operation lock."
+        else
+            die "Another Sub2API Apple container operation is already running."
+        fi
+    fi
+    printf '%s\n' "$$" >"${LOCK_DIR}/pid"
+    LOCK_ACQUIRED=true
+    trap cleanup EXIT
+    trap 'exit 130' INT
+    trap 'exit 143' TERM
+    trap 'exit 129' HUP
+}
+
+require_command() {
+    command -v "$1" >/dev/null 2>&1 || die "Required command not found: $1"
+}
+
+require_container_version() {
+    local version_output major minor
+
+    require_command container
+    require_command plutil
+    version_output="$(container --version)"
+    if [[ ! "${version_output}" =~ ([0-9]+)\.([0-9]+)\.([0-9]+) ]]; then
+        die "Unable to parse Apple container version: ${version_output}"
+    fi
+
+    major="${BASH_REMATCH[1]}"
+    minor="${BASH_REMATCH[2]}"
+    if (( major < 1 || (major == 1 && minor < 1) )); then
+        die "Apple container 1.1.0 or newer is required; found ${version_output}."
+    fi
+}
+
+system_is_running() {
+    container system status >/dev/null 2>&1
+}
+
+start_system() {
+    if ! system_is_running; then
+        info "Starting Apple container services..."
+        container system start --enable-kernel-install
+    fi
+}
+
+list_resource_ids() {
+    case "$1" in
+        container) container list --all --quiet ;;
+        network) container network list --quiet ;;
+        volume) container volume list --quiet ;;
+        *) die "Unknown resource type: $1" ;;
+    esac
+}
+
+resource_exists() {
+    local resource_type=$1
+    local resource_name=$2
+    local output line
+
+    if ! output="$(list_resource_ids "${resource_type}")"; then
+        die "Failed to list Apple container ${resource_type} resources."
+    fi
+
+    while IFS= read -r line; do
+        if [[ "${line}" == "${resource_name}" ]]; then
+            return 0
+        fi
+    done <<<"${output}"
+
+    return 1
+}
+
+inspect_resource() {
+    case "$1" in
+        container) container inspect "$2" ;;
+        network) container network inspect "$2" ;;
+        volume) container volume inspect "$2" ;;
+        *) die "Unknown resource type: $1" ;;
+    esac
+}
+
+assert_resource_owned() {
+    local resource_type=$1
+    local resource_name=$2
+    local inspection compact
+
+    inspection="$(inspect_resource "${resource_type}" "${resource_name}" | \
+        plutil -extract 0.configuration.labels json -o - -)" || \
+        die "Failed to inspect ${resource_type} ${resource_name}."
+    compact="$(printf '%s' "${inspection}" | tr -d '[:space:]')"
+    if [[ "${compact}" != *"\"${STACK_LABEL_KEY}\":\"${STACK_LABEL_VALUE}\""* ]]; then
+        die "Refusing to manage existing ${resource_type} '${resource_name}' because it is not owned by this stack."
+    fi
+}
+
+preflight_stack_ownership() {
+    local resource_name
+
+    for resource_name in "${APP_CONTAINER}" "${REDIS_CONTAINER}" "${POSTGRES_CONTAINER}"; do
+        if resource_exists container "${resource_name}"; then
+            assert_resource_owned container "${resource_name}"
+        fi
+    done
+    if resource_exists network "${NETWORK_NAME}"; then
+        assert_resource_owned network "${NETWORK_NAME}"
+    fi
+    for resource_name in "${APP_VOLUME}" "${REDIS_VOLUME}" "${POSTGRES_VOLUME}"; do
+        if resource_exists volume "${resource_name}"; then
+            assert_resource_owned volume "${resource_name}"
+        fi
+    done
+}
+
+ensure_network() {
+    local existing_subnet
+    local -a network_args
+
+    if resource_exists network "${NETWORK_NAME}"; then
+        assert_resource_owned network "${NETWORK_NAME}"
+        if [[ -n "${NETWORK_SUBNET}" ]]; then
+            existing_subnet="$(inspect_resource network "${NETWORK_NAME}" | \
+                plutil -extract 0.configuration.ipv4Subnet raw -o - -)" || \
+                die "Unable to read the IPv4 subnet for ${NETWORK_NAME}."
+            if [[ "${existing_subnet}" != "${NETWORK_SUBNET}" ]]; then
+                die "Existing network '${NETWORK_NAME}' uses subnet '${existing_subnet}', but APPLE_CONTAINER_NETWORK_SUBNET is '${NETWORK_SUBNET}'. Run './apple-container.sh destroy --yes' to recreate the network while preserving volumes, then run 'up' again."
+            fi
+        fi
+        return
+    fi
+
+    info "Creating network ${NETWORK_NAME}..."
+    network_args=(--label "${STACK_LABEL_KEY}=${STACK_LABEL_VALUE}")
+    if [[ -n "${NETWORK_SUBNET}" ]]; then
+        network_args+=(--subnet "${NETWORK_SUBNET}")
+    fi
+    container network create "${network_args[@]}" "${NETWORK_NAME}" >/dev/null
+}
+
+ensure_volume() {
+    local volume_name=$1
+
+    if resource_exists volume "${volume_name}"; then
+        assert_resource_owned volume "${volume_name}"
+        return
+    fi
+
+    info "Creating volume ${volume_name}..."
+    container volume create \
+        --label "${STACK_LABEL_KEY}=${STACK_LABEL_VALUE}" \
+        "${volume_name}" >/dev/null
+}
+
+ensure_image_available() {
+    local image=$1
+
+    if container image inspect "${image}" >/dev/null 2>&1; then
+        return
+    fi
+    info "Pulling ${image}..."
+    container image pull --platform "${PLATFORM}" "${image}"
+}
+
+container_is_running() {
+    local container_name=$1
+    local output line
+
+    output="$(container list --quiet)" || die "Failed to list running Apple containers."
+    while IFS= read -r line; do
+        if [[ "${line}" == "${container_name}" ]]; then
+            return 0
+        fi
+    done <<<"${output}"
+
+    return 1
+}
+
+ensure_system() {
+    require_container_version
+    require_command curl
+    start_system
+}
+
+container_ipv4_address() {
+    local container_name=$1
+    local address
+
+    address="$(container inspect "${container_name}" | \
+        plutil -extract 0.status.networks.0.ipv4Address raw -o - -)" || \
+        die "Unable to read the network address for ${container_name}."
+    address="${address%%/*}"
+    [[ "${address}" =~ ^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$ ]] || \
+        die "Apple container returned an invalid IPv4 address for ${container_name}: ${address}"
+    printf '%s\n' "${address}"
+}
+
+read_env_value() {
+    local key=$1
+    local fallback=${2-}
+
+    awk -v wanted="${key}" -v fallback="${fallback}" '
+        BEGIN { found = 0 }
+        /^[[:space:]]*#/ || /^[[:space:]]*$/ { next }
+        {
+            separator = index($0, "=")
+            if (separator == 0) { next }
+            key = substr($0, 1, separator - 1)
+            if (key == wanted) {
+                value = substr($0, separator + 1)
+                sub(/\r$/, "", value)
+                found = 1
+            }
+        }
+        END {
+            if (found) { print value }
+            else { print fallback }
+        }
+    ' "${ENV_FILE}"
+}
+
+replace_env_value() {
+    local key=$1
+    local value=$2
+    local target_file=${3:-${ENV_FILE}}
+    local temp_file="${target_file}.tmp.$$"
+
+    awk -v wanted="${key}" -v replacement="${value}" '
+        BEGIN { replaced = 0 }
+        {
+            separator = index($0, "=")
+            key = separator == 0 ? "" : substr($0, 1, separator - 1)
+            if (key == wanted) {
+                if (!replaced) { print wanted "=" replacement }
+                replaced = 1
+                next
+            }
+            print
+        }
+        END {
+            if (!replaced) { print wanted "=" replacement }
+        }
+    ' "${target_file}" >"${temp_file}"
+    chmod 600 "${temp_file}"
+    mv "${temp_file}" "${target_file}"
+}
+
+generate_secret() {
+    openssl rand -hex 32
+}
+
+cmd_init() {
+    local env_dir temp_file postgres_secret jwt_secret totp_secret
+
+    require_command openssl
+
+    if [[ -e "${ENV_FILE}" ]]; then
+        die "Environment file already exists: ${ENV_FILE}"
+    fi
+
+    postgres_secret="$(generate_secret)" || die "Failed to generate PostgreSQL password."
+    jwt_secret="$(generate_secret)" || die "Failed to generate JWT secret."
+    totp_secret="$(generate_secret)" || die "Failed to generate TOTP encryption key."
+    [[ -n "${postgres_secret}" && -n "${jwt_secret}" && -n "${totp_secret}" ]] || \
+        die "Secret generation returned an empty value."
+
+    env_dir="$(dirname "${ENV_FILE}")"
+    temp_file="${ENV_FILE}.init.tmp.$$"
+    mkdir -p "${env_dir}"
+    cp "${SCRIPT_DIR}/.env.example" "${temp_file}"
+    chmod 600 "${temp_file}"
+    replace_env_value POSTGRES_PASSWORD "${postgres_secret}" "${temp_file}"
+    replace_env_value JWT_SECRET "${jwt_secret}" "${temp_file}"
+    replace_env_value TOTP_ENCRYPTION_KEY "${totp_secret}" "${temp_file}"
+    mv "${temp_file}" "${ENV_FILE}"
+
+    info "Created ${ENV_FILE} with generated secrets."
+    info "Review the file, then run: SUB2API_ENV_FILE='${ENV_FILE}' ${SCRIPT_DIR}/apple-container.sh up"
+}
+
+validate_port() {
+    local port=$1
+    local decimal_port
+
+    [[ "${port}" =~ ^[0-9]+$ ]] || die "SERVER_PORT must be numeric: ${port}"
+    decimal_port=$((10#${port}))
+    (( decimal_port >= 1025 && decimal_port <= 65535 )) || \
+        die "SERVER_PORT must be between 1025 and 65535 for Apple container port forwarding."
+}
+
+validate_ipv4_address() {
+    local address=$1
+    local first second third fourth extra octet
+
+    IFS=. read -r first second third fourth extra <<<"${address}"
+    [[ -n "${first}" && -n "${second}" && -n "${third}" && -n "${fourth}" && -z "${extra}" ]] || \
+        die "BIND_HOST must be a valid IPv4 address: ${address}"
+    for octet in "${first}" "${second}" "${third}" "${fourth}"; do
+        [[ "${octet}" =~ ^[0-9]+$ ]] || die "BIND_HOST must be a valid IPv4 address: ${address}"
+        (( 10#${octet} <= 255 )) || die "BIND_HOST must be a valid IPv4 address: ${address}"
+    done
+}
+
+validate_env_file_security() {
+    local owner mode permissions
+
+    [[ -f "${ENV_FILE}" ]] || die "Environment file not found: ${ENV_FILE}. Run '$0 init' first."
+    owner="$(stat -f '%u' "${ENV_FILE}")" || die "Unable to read owner for ${ENV_FILE}."
+    mode="$(stat -f '%Lp' "${ENV_FILE}")" || die "Unable to read permissions for ${ENV_FILE}."
+    [[ "${owner}" == "${EUID}" ]] || die "Environment file must be owned by the current user: ${ENV_FILE}"
+    [[ "${mode}" =~ ^[0-7]+$ ]] || die "Unable to parse permissions for ${ENV_FILE}: ${mode}"
+    permissions=$((8#${mode}))
+    (( (permissions & 077) == 0 )) || \
+        die "Environment file must not be readable by group or others. Run: chmod 600 '${ENV_FILE}'"
+}
+
+prepare_environment() {
+    validate_env_file_security
+
+    APP_IMAGE="$(read_env_value APPLE_CONTAINER_SUB2API_IMAGE weishaw/sub2api:latest)"
+    POSTGRES_IMAGE="$(read_env_value APPLE_CONTAINER_POSTGRES_IMAGE postgres:18-alpine)"
+    REDIS_IMAGE="$(read_env_value APPLE_CONTAINER_REDIS_IMAGE redis:8-alpine)"
+    BIND_HOST="$(read_env_value BIND_HOST 0.0.0.0)"
+    HOST_PORT="$(read_env_value SERVER_PORT 8080)"
+    POSTGRES_USER="$(read_env_value POSTGRES_USER sub2api)"
+    POSTGRES_PASSWORD="$(read_env_value POSTGRES_PASSWORD)"
+    POSTGRES_DB="$(read_env_value POSTGRES_DB sub2api)"
+    REDIS_PASSWORD="$(read_env_value REDIS_PASSWORD)"
+    TZ_VALUE="$(read_env_value TZ Asia/Shanghai)"
+    NETWORK_SUBNET="$(read_env_value APPLE_CONTAINER_NETWORK_SUBNET)"
+
+    [[ -n "${BIND_HOST}" ]] || die "BIND_HOST must not be empty."
+    validate_ipv4_address "${BIND_HOST}"
+    validate_port "${HOST_PORT}"
+    if [[ "${BIND_HOST}" == "0.0.0.0" ]]; then
+        ACCESS_HOST="127.0.0.1"
+    else
+        ACCESS_HOST="${BIND_HOST}"
+    fi
+    [[ -n "${POSTGRES_USER}" ]] || die "POSTGRES_USER must not be empty."
+    [[ -n "${POSTGRES_DB}" ]] || die "POSTGRES_DB must not be empty."
+    if [[ -z "${POSTGRES_PASSWORD}" || "${POSTGRES_PASSWORD}" == "change_this_secure_password" ]]; then
+        die "Set a secure POSTGRES_PASSWORD in ${ENV_FILE}."
+    fi
+
+    TEMP_DIR="$(mktemp -d "${TMPDIR:-/tmp}/sub2api-apple.XXXXXX")"
+    APP_ENV_FILE="${TEMP_DIR}/app.env"
+    POSTGRES_ENV_FILE="${TEMP_DIR}/postgres.env"
+    POSTGRES_PROBE_ENV_FILE="${TEMP_DIR}/postgres-probe.env"
+    REDIS_ENV_FILE="${TEMP_DIR}/redis.env"
+
+    cat >"${POSTGRES_ENV_FILE}" <<EOF
+POSTGRES_USER=${POSTGRES_USER}
+POSTGRES_PASSWORD=${POSTGRES_PASSWORD}
+POSTGRES_DB=${POSTGRES_DB}
+TZ=${TZ_VALUE}
+EOF
+
+    cat >"${POSTGRES_PROBE_ENV_FILE}" <<EOF
+PGPASSWORD=${POSTGRES_PASSWORD}
+EOF
+
+    cat >"${REDIS_ENV_FILE}" <<EOF
+REDIS_PASSWORD=${REDIS_PASSWORD}
+TZ=${TZ_VALUE}
+EOF
+    if [[ -n "${REDIS_PASSWORD}" ]]; then
+        printf 'REDISCLI_AUTH=%s\n' "${REDIS_PASSWORD}" >>"${REDIS_ENV_FILE}"
+    fi
+
+    chmod 600 "${POSTGRES_ENV_FILE}" "${POSTGRES_PROBE_ENV_FILE}" "${REDIS_ENV_FILE}"
+}
+
+prepare_app_environment() {
+    [[ -n "${POSTGRES_ADDRESS}" && -n "${REDIS_ADDRESS}" && -n "${APP_IMAGE_ID}" ]] || \
+        die "Dependency network addresses or application image ID are not available."
+
+    cp "${ENV_FILE}" "${APP_ENV_FILE}"
+    cat >>"${APP_ENV_FILE}" <<EOF
+
+AUTO_SETUP=true
+SERVER_HOST=0.0.0.0
+SERVER_PORT=8080
+DATABASE_HOST=${POSTGRES_ADDRESS}
+DATABASE_PORT=5432
+DATABASE_USER=${POSTGRES_USER}
+DATABASE_PASSWORD=${POSTGRES_PASSWORD}
+DATABASE_DBNAME=${POSTGRES_DB}
+DATABASE_SSLMODE=disable
+REDIS_HOST=${REDIS_ADDRESS}
+REDIS_PORT=6379
+REDIS_PASSWORD=${REDIS_PASSWORD}
+DATA_DIR=/app/storage/data
+APPLE_CONTAINER_SUB2API_IMAGE_ID=${APP_IMAGE_ID}
+EOF
+    chmod 600 "${APP_ENV_FILE}"
+}
+
+create_postgres_container() {
+    info "Creating PostgreSQL container..."
+    container create \
+        --name "${POSTGRES_CONTAINER}" \
+        --label "${STACK_LABEL_KEY}=${STACK_LABEL_VALUE}" \
+        --network "${NETWORK_NAME}" \
+        --platform "${PLATFORM}" \
+        --ulimit nofile=100000:100000 \
+        --env-file "${POSTGRES_ENV_FILE}" \
+        --volume "${POSTGRES_VOLUME}:/var/lib/postgresql" \
+        "${POSTGRES_IMAGE}" >/dev/null
+}
+
+create_redis_container() {
+    info "Creating Redis container..."
+    container create \
+        --name "${REDIS_CONTAINER}" \
+        --label "${STACK_LABEL_KEY}=${STACK_LABEL_VALUE}" \
+        --network "${NETWORK_NAME}" \
+        --platform "${PLATFORM}" \
+        --ulimit nofile=100000:100000 \
+        --env-file "${REDIS_ENV_FILE}" \
+        --volume "${REDIS_VOLUME}:/var/lib/redis" \
+        "${REDIS_IMAGE}" \
+        sh -c 'set -e; mkdir -p /var/lib/redis/data; chown redis:redis /var/lib/redis/data; exec /usr/local/bin/docker-entrypoint.sh redis-server --dir /var/lib/redis/data --save 60 1 --appendonly yes --appendfsync everysec ${REDIS_PASSWORD:+--requirepass "$REDIS_PASSWORD"}' \
+        >/dev/null
+}
+
+create_app_container() {
+    info "Creating Sub2API container..."
+    container create \
+        --name "${APP_CONTAINER}" \
+        --label "${STACK_LABEL_KEY}=${STACK_LABEL_VALUE}" \
+        --network "${NETWORK_NAME}" \
+        --platform "${PLATFORM}" \
+        --ulimit nofile=100000:100000 \
+        --publish "${BIND_HOST}:${HOST_PORT}:8080/tcp" \
+        --env-file "${APP_ENV_FILE}" \
+        --volume "${APP_VOLUME}:/app/storage" \
+        --entrypoint /bin/sh \
+        "${APP_IMAGE}" \
+        -c '
+set -e
+mkdir -p "$DATA_DIR"
+chown -R sub2api:sub2api "$DATA_DIR"
+
+runtime_dir=/app/storage/runtime
+runtime_binary="$runtime_dir/sub2api"
+image_marker="$runtime_dir/base-image-id"
+installed_image_id=""
+if [ -f "$image_marker" ]; then
+    installed_image_id="$(cat "$image_marker")"
+fi
+if [ ! -x "$runtime_binary" ] || [ "$installed_image_id" != "$APPLE_CONTAINER_SUB2API_IMAGE_ID" ]; then
+    mkdir -p "$runtime_dir"
+    cp /app/sub2api "${runtime_binary}.new"
+    chown sub2api:sub2api "${runtime_binary}.new"
+    chmod 0755 "${runtime_binary}.new"
+    mv "${runtime_binary}.new" "$runtime_binary"
+    printf "%s\n" "$APPLE_CONTAINER_SUB2API_IMAGE_ID" >"${image_marker}.new"
+    mv "${image_marker}.new" "$image_marker"
+    rm -f "${runtime_binary}.backup"
+fi
+chown -R sub2api:sub2api "$runtime_dir"
+
+child_pid=""
+stop() {
+    trap - TERM INT
+    if [ -n "$child_pid" ]; then
+        kill -TERM "$child_pid" 2>/dev/null || true
+        wait "$child_pid" 2>/dev/null || true
+    fi
+    exit 0
+}
+trap stop TERM INT
+
+while true; do
+    su-exec sub2api "$runtime_binary" &
+    child_pid=$!
+    set +e
+    wait "$child_pid"
+    status=$?
+    set -e
+    child_pid=""
+    echo "Sub2API exited with status ${status}; restarting in 1 second..." >&2
+    sleep 1
+done
+' \
+        >/dev/null
+}
+
+application_image_id() {
+    container image inspect "${APP_IMAGE}" | \
+        plutil -extract 0.id raw -o - -
+}
+
+ensure_container() {
+    local container_name=$1
+    local create_function=$2
+
+    if resource_exists container "${container_name}"; then
+        assert_resource_owned container "${container_name}"
+        return
+    fi
+
+    "${create_function}"
+}
+
+start_container_if_needed() {
+    local container_name=$1
+
+    if container_is_running "${container_name}"; then
+        return
+    fi
+
+    info "Starting ${container_name}..."
+    container start "${container_name}" >/dev/null
+}
+
+stop_container_if_running() {
+    local container_name=$1
+
+    if ! resource_exists container "${container_name}"; then
+        return
+    fi
+    assert_resource_owned container "${container_name}"
+    if container_is_running "${container_name}"; then
+        info "Stopping ${container_name}..."
+        container stop --time 30 "${container_name}" >/dev/null
+    fi
+}
+
+delete_container_if_present() {
+    local container_name=$1
+
+    if ! resource_exists container "${container_name}"; then
+        return
+    fi
+    assert_resource_owned container "${container_name}"
+    if container_is_running "${container_name}"; then
+        container stop --time 30 "${container_name}" >/dev/null
+    fi
+    info "Deleting ${container_name}..."
+    container delete "${container_name}" >/dev/null
+}
+
+wait_for_probe() {
+    local description=$1
+    local attempts=$2
+    shift 2
+
+    local attempt
+    for ((attempt = 1; attempt <= attempts; attempt++)); do
+        if "$@" >/dev/null 2>&1; then
+            info "${description} is ready."
+            return 0
+        fi
+        sleep 1
+    done
+
+    return 1
+}
+
+probe_postgres() {
+    container exec --env-file "${POSTGRES_PROBE_ENV_FILE}" \
+        "${POSTGRES_CONTAINER}" \
+        psql -h 127.0.0.1 -U "${POSTGRES_USER}" -d "${POSTGRES_DB}" \
+        -v ON_ERROR_STOP=1 -tAc 'SELECT 1'
+}
+
+probe_redis() {
+    container exec --env-file "${REDIS_ENV_FILE}" \
+        "${REDIS_CONTAINER}" \
+        redis-cli ping
+}
+
+probe_app() {
+    container exec "${APP_CONTAINER}" \
+        wget -q -T 5 -O /dev/null http://localhost:8080/health
+}
+
+probe_host_app() {
+    curl --fail --silent --show-error --max-time 5 \
+        "http://${ACCESS_HOST}:${HOST_PORT}/health"
+}
+
+show_failure_logs() {
+    local container_name=$1
+
+    warn "Last logs from ${container_name}:"
+    container logs -n 50 "${container_name}" >&2 || true
+}
+
+start_dependencies() {
+    start_container_if_needed "${POSTGRES_CONTAINER}"
+    if ! wait_for_probe "PostgreSQL" 90 probe_postgres; then
+        show_failure_logs "${POSTGRES_CONTAINER}"
+        die "PostgreSQL did not become ready."
+    fi
+
+    start_container_if_needed "${REDIS_CONTAINER}"
+    if ! wait_for_probe "Redis" 60 probe_redis; then
+        show_failure_logs "${REDIS_CONTAINER}"
+        die "Redis did not become ready."
+    fi
+}
+
+start_app() {
+    start_container_if_needed "${APP_CONTAINER}"
+    if ! wait_for_probe "Sub2API" 180 probe_app; then
+        show_failure_logs "${APP_CONTAINER}"
+        die "Sub2API did not become ready."
+    fi
+    if ! wait_for_probe "Sub2API host port" 15 probe_host_app; then
+        die "Host port forwarding failed. In System Settings > Privacy & Security > Local Network, allow container-runtime-linux; restart Apple container services; then run 'apple-container.sh up' again."
+    fi
+}
+
+cmd_up() {
+    local recreate=false
+
+    if [[ $# -gt 1 || ($# -eq 1 && "${1-}" != "--recreate") ]]; then
+        usage
+        exit 2
+    fi
+    if [[ $# -eq 1 ]]; then
+        recreate=true
+    fi
+
+    ensure_system
+    prepare_environment
+    preflight_stack_ownership
+    ensure_network
+    ensure_volume "${APP_VOLUME}"
+    ensure_volume "${POSTGRES_VOLUME}"
+    ensure_volume "${REDIS_VOLUME}"
+    ensure_image_available "${APP_IMAGE}"
+    ensure_image_available "${POSTGRES_IMAGE}"
+    ensure_image_available "${REDIS_IMAGE}"
+    APP_IMAGE_ID="$(application_image_id)" || \
+        die "Unable to inspect application image ID for ${APP_IMAGE}."
+    [[ -n "${APP_IMAGE_ID}" ]] || die "Application image ID must not be empty."
+
+    if [[ "${recreate}" == true ]]; then
+        delete_container_if_present "${APP_CONTAINER}"
+        delete_container_if_present "${REDIS_CONTAINER}"
+        delete_container_if_present "${POSTGRES_CONTAINER}"
+    fi
+
+    ensure_container "${POSTGRES_CONTAINER}" create_postgres_container
+    ensure_container "${REDIS_CONTAINER}" create_redis_container
+    start_dependencies
+    POSTGRES_ADDRESS="$(container_ipv4_address "${POSTGRES_CONTAINER}")"
+    REDIS_ADDRESS="$(container_ipv4_address "${REDIS_CONTAINER}")"
+    prepare_app_environment
+    # The dependency IPs may change whenever their lightweight VMs restart.
+    delete_container_if_present "${APP_CONTAINER}"
+    create_app_container
+    start_app
+
+    info "Sub2API is available at http://${ACCESS_HOST}:${HOST_PORT}"
+}
+
+cmd_down() {
+    require_container_version
+    if ! system_is_running; then
+        info "Apple container services are already stopped."
+        return
+    fi
+    preflight_stack_ownership
+    stop_container_if_running "${APP_CONTAINER}"
+    stop_container_if_running "${REDIS_CONTAINER}"
+    stop_container_if_running "${POSTGRES_CONTAINER}"
+    info "Sub2API stack stopped; persistent volumes were preserved."
+}
+
+cmd_restart() {
+    cmd_down
+    cmd_up
+}
+
+print_container_status() {
+    local service=$1
+    local container_name=$2
+
+    if ! resource_exists container "${container_name}"; then
+        printf '%-12s %s\n' "${service}" "missing"
+    elif container_is_running "${container_name}"; then
+        printf '%-12s %s\n' "${service}" "running"
+    else
+        printf '%-12s %s\n' "${service}" "stopped"
+    fi
+}
+
+cmd_status() {
+    local failed=0
+
+    require_container_version
+    if ! system_is_running; then
+        printf '%-12s %s\n' "system" "stopped"
+        return 1
+    fi
+
+    printf '%-12s %s\n' "system" "running"
+    preflight_stack_ownership
+    print_container_status app "${APP_CONTAINER}"
+    print_container_status postgres "${POSTGRES_CONTAINER}"
+    print_container_status redis "${REDIS_CONTAINER}"
+
+    if [[ -f "${ENV_FILE}" ]]; then
+        prepare_environment
+        if container_is_running "${POSTGRES_CONTAINER}" && probe_postgres >/dev/null 2>&1; then
+            printf '%-12s %s\n' "postgres" "healthy"
+        else
+            printf '%-12s %s\n' "postgres" "unhealthy"
+            failed=1
+        fi
+        if container_is_running "${REDIS_CONTAINER}" && probe_redis >/dev/null 2>&1; then
+            printf '%-12s %s\n' "redis" "healthy"
+        else
+            printf '%-12s %s\n' "redis" "unhealthy"
+            failed=1
+        fi
+        if container_is_running "${APP_CONTAINER}" && probe_app >/dev/null 2>&1; then
+            printf '%-12s %s\n' "app" "healthy"
+        else
+            printf '%-12s %s\n' "app" "unhealthy"
+            failed=1
+        fi
+        if container_is_running "${APP_CONTAINER}" && probe_host_app >/dev/null 2>&1; then
+            printf '%-12s %s\n' "host-port" "healthy"
+        else
+            printf '%-12s %s\n' "host-port" "unhealthy"
+            failed=1
+        fi
+    else
+        warn "Health probes require ${ENV_FILE}."
+        failed=1
+    fi
+
+    return "${failed}"
+}
+
+cmd_logs() {
+    local service=${1-}
+    local follow=${2-}
+    local container_name
+
+    [[ $# -ge 1 && $# -le 2 ]] || { usage; exit 2; }
+    if [[ -n "${follow}" && "${follow}" != "-f" && "${follow}" != "--follow" ]]; then
+        usage
+        exit 2
+    fi
+
+    case "${service}" in
+        app|sub2api) container_name="${APP_CONTAINER}" ;;
+        postgres) container_name="${POSTGRES_CONTAINER}" ;;
+        redis) container_name="${REDIS_CONTAINER}" ;;
+        *) die "Unknown service '${service}'. Use app, postgres, or redis." ;;
+    esac
+
+    require_container_version
+    system_is_running || die "Apple container services are not running."
+    resource_exists container "${container_name}" || die "Container not found: ${container_name}"
+    assert_resource_owned container "${container_name}"
+    if [[ -n "${follow}" ]]; then
+        container logs --follow "${container_name}"
+    else
+        container logs "${container_name}"
+    fi
+}
+
+cmd_pull() {
+    ensure_system
+    prepare_environment
+    info "Pulling ${APP_IMAGE}..."
+    container image pull --platform "${PLATFORM}" "${APP_IMAGE}"
+    info "Pulling ${POSTGRES_IMAGE}..."
+    container image pull --platform "${PLATFORM}" "${POSTGRES_IMAGE}"
+    info "Pulling ${REDIS_IMAGE}..."
+    container image pull --platform "${PLATFORM}" "${REDIS_IMAGE}"
+}
+
+confirm_destroy() {
+    local include_volumes=$1
+    local answer
+
+    if [[ "${include_volumes}" == true ]]; then
+        printf 'Delete the Sub2API stack and all persistent data? [y/N] '
+    else
+        printf 'Delete the Sub2API containers and network, preserving volumes? [y/N] '
+    fi
+    read -r answer
+    [[ "${answer}" == "y" || "${answer}" == "Y" ]]
+}
+
+delete_volume_if_present() {
+    local volume_name=$1
+
+    if resource_exists volume "${volume_name}"; then
+        assert_resource_owned volume "${volume_name}"
+        info "Deleting volume ${volume_name}..."
+        container volume delete "${volume_name}" >/dev/null
+    fi
+}
+
+cmd_destroy() {
+    local include_volumes=false
+    local assume_yes=false
+    local argument
+
+    for argument in "$@"; do
+        case "${argument}" in
+            --volumes) include_volumes=true ;;
+            --yes) assume_yes=true ;;
+            *) usage; exit 2 ;;
+        esac
+    done
+
+    require_container_version
+    start_system
+    preflight_stack_ownership
+    if [[ "${assume_yes}" != true ]] && ! confirm_destroy "${include_volumes}"; then
+        info "Cancelled."
+        return
+    fi
+
+    delete_container_if_present "${APP_CONTAINER}"
+    delete_container_if_present "${REDIS_CONTAINER}"
+    delete_container_if_present "${POSTGRES_CONTAINER}"
+
+    if resource_exists network "${NETWORK_NAME}"; then
+        assert_resource_owned network "${NETWORK_NAME}"
+        info "Deleting network ${NETWORK_NAME}..."
+        container network delete "${NETWORK_NAME}" >/dev/null
+    fi
+
+    if [[ "${include_volumes}" == true ]]; then
+        delete_volume_if_present "${APP_VOLUME}"
+        delete_volume_if_present "${REDIS_VOLUME}"
+        delete_volume_if_present "${POSTGRES_VOLUME}"
+        info "Sub2API stack and persistent data deleted."
+    else
+        info "Sub2API stack deleted; persistent volumes were preserved."
+    fi
+}
+
+main() {
+    local command=${1-}
+    if [[ $# -gt 0 ]]; then
+        shift
+    fi
+
+    case "${command}" in
+        init)
+            [[ $# -eq 0 ]] || { usage; exit 2; }
+            acquire_lock
+            cmd_init
+            ;;
+        up)
+            acquire_lock
+            cmd_up "$@"
+            ;;
+        down)
+            [[ $# -eq 0 ]] || { usage; exit 2; }
+            acquire_lock
+            cmd_down
+            ;;
+        restart)
+            [[ $# -eq 0 ]] || { usage; exit 2; }
+            acquire_lock
+            cmd_restart
+            ;;
+        status)
+            [[ $# -eq 0 ]] || { usage; exit 2; }
+            trap cleanup EXIT
+            cmd_status
+            ;;
+        logs)
+            cmd_logs "$@"
+            ;;
+        pull)
+            [[ $# -eq 0 ]] || { usage; exit 2; }
+            acquire_lock
+            cmd_pull
+            ;;
+        destroy)
+            acquire_lock
+            cmd_destroy "$@"
+            ;;
+        help|-h|--help)
+            usage
+            ;;
+        *)
+            usage
+            exit 2
+            ;;
+    esac
+}
+
+main "$@"
diff --git a/build_image.sh b/build_image.sh
new file mode 100755
index 0000000..2426f91
--- /dev/null
+++ b/build_image.sh
@@ -0,0 +1,13 @@
+#!/usr/bin/env bash
+# 本地构建镜像的快速脚本，避免在命令行反复输入构建参数。
+
+set -euo pipefail
+
+SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
+REPO_ROOT="$(cd "${SCRIPT_DIR}/.." && pwd)"
+
+docker build -t sub2api:latest \
+    --build-arg GOPROXY=https://goproxy.cn,direct \
+    --build-arg GOSUMDB=sum.golang.google.cn \
+    -f "${REPO_ROOT}/Dockerfile" \
+    "${REPO_ROOT}"
diff --git a/codex-instructions.md.tmpl b/codex-instructions.md.tmpl
new file mode 100644
index 0000000..87ad0a3
--- /dev/null
+++ b/codex-instructions.md.tmpl
@@ -0,0 +1,5 @@
+You are Codex, based on GPT-5. You are running as a coding agent in the Codex CLI on a user's computer.
+
+{{ if .ExistingInstructions }}
+{{ .ExistingInstructions }}
+{{ end }}
diff --git a/config.example.yaml b/config.example.yaml
new file mode 100644
index 0000000..7066f17
--- /dev/null
+++ b/config.example.yaml
@@ -0,0 +1,1299 @@
+# Sub2API Configuration File
+# Sub2API 配置文件
+#
+# Copy this file to /etc/sub2api/config.yaml and modify as needed
+# 复制此文件到 /etc/sub2api/config.yaml 并根据需要修改
+#
+# Documentation / 文档: https://github.com/Wei-Shaw/sub2api
+
+# =============================================================================
+# Server Configuration
+# 服务器配置
+# =============================================================================
+server:
+  # Bind address (0.0.0.0 for all interfaces)
+  # 绑定地址（0.0.0.0 表示监听所有网络接口）
+  host: "0.0.0.0"
+  # Port to listen on
+  # 监听端口
+  port: 8080
+  # Mode: "debug" for development, "release" for production
+  # 运行模式："debug" 用于开发，"release" 用于生产环境
+  mode: "release"
+  # Return Server-Timing for authenticated requests made by the Admin web UI
+  # 为管理端 Web 页面发出的已认证请求返回 Server-Timing
+  enable_server_timing: false
+  # Frontend base URL used to generate external links in emails (e.g. password reset)
+  # 用于生成邮件中的外部链接（例如：重置密码链接）的前端基础地址
+  # Example: "https://example.com"
+  frontend_url: ""
+  # Maximum time to receive complete request headers. Does not limit response streams.
+  # 完整读取请求头的最大时间；不限制响应流持续时间。
+  read_header_timeout: 10
+  # Request header limit in bytes (64 KiB); also bounds the HTTP/2 header list.
+  # 请求头上限（字节，默认 64 KiB）；同时约束 HTTP/2 header list。
+  max_header_bytes: 65536
+  # Keep-alive idle timeout in seconds.
+  # Keep-Alive 空闲连接超时（秒）。
+  idle_timeout: 120
+  # Trusted proxies used when security.trust_forwarded_ip_for_api_key_acl is false.
+  # List only the exact proxy addresses that connect directly to Sub2API.
+  # Set [] explicitly to disable forwarded-IP trust in high-security mode.
+  # security.trust_forwarded_ip_for_api_key_acl=false 时使用的可信代理。
+  # 只填写直接连接 Sub2API 的精确代理地址；显式设置 [] 可在高安全模式下
+  # 禁用转发 IP 信任。
+  trusted_proxies:
+    - 127.0.0.1/32
+    - ::1/128
+  # Global max request body size in bytes (default: 256MB)
+  # 全局最大请求体大小（字节，默认 256MB）
+  # Applies to all requests, especially important for h2c first request memory protection
+  # 适用于所有请求，对 h2c 第一请求的内存保护尤为重要
+  max_request_body_size: 268435456
+  # HTTP/2 Cleartext (h2c) configuration
+  # HTTP/2 Cleartext (h2c) 配置
+  h2c:
+    # Enable HTTP/2 Cleartext for client connections
+    # 启用 HTTP/2 Cleartext 客户端连接
+    enabled: true
+    # Max concurrent streams per connection
+    # 每个连接的最大并发流数量
+    max_concurrent_streams: 50
+    # Idle timeout for connections (seconds)
+    # 连接空闲超时时间（秒）
+    idle_timeout: 75
+    # Max frame size in bytes (default: 1MB)
+    # 最大帧大小（字节，默认 1MB）
+    max_read_frame_size: 1048576
+    # Max upload buffer per connection in bytes (default: 2MB)
+    # 每个连接的最大上传缓冲区（字节，默认 2MB）
+    max_upload_buffer_per_connection: 2097152
+    # Max upload buffer per stream in bytes (default: 512KB)
+    # 每个流的最大上传缓冲区（字节，默认 512KB）
+    max_upload_buffer_per_stream: 524288
+
+# =============================================================================
+# WebAuthn / Passkey Configuration
+# WebAuthn / Passkey 配置
+# =============================================================================
+# Passkeys require HTTPS in production. The RP ID is the domain only (no scheme
+# or port), while RP origins are exact browser origins.
+# Passkey 在生产环境要求 HTTPS。RP ID 只填写域名（不含协议和端口），RP origins
+# 填写浏览器访问使用的完整 Origin。
+webauthn:
+  enabled: false
+  rp_display_name: "Sub2API"
+  # Example / 示例: "sub2api.example.com"
+  rp_id: ""
+  # Example / 示例: ["https://sub2api.example.com"]
+  rp_origins: []
+
+# =============================================================================
+# Run Mode Configuration
+# 运行模式配置
+# =============================================================================
+# Run mode: "standard" (default) or "simple" (for internal use)
+# 运行模式："standard"（默认）或 "simple"（内部使用）
+# - standard: Full SaaS features with billing/balance checks
+# - standard: 完整 SaaS 功能，包含计费和余额校验
+# - simple: Hides SaaS features and skips billing/balance checks
+# - simple: 隐藏 SaaS 功能，跳过计费和余额校验
+run_mode: "standard"
+
+simple_mode:
+  # 仅控制简易模式启动时补齐默认分组；false 不删除已有分组，不改变运行时自动绑定或管理员并发设置。
+  # 环境变量：SIMPLE_MODE_AUTO_CREATE_DEFAULT_GROUPS
+  auto_create_default_groups: true
+
+# Enforce API-key 5h/1d/7d spending windows in simple mode; other billing stays disabled.
+simple_mode_key_rate_limit_enabled: false
+
+# =============================================================================
+# CORS Configuration
+# 跨域资源共享 (CORS) 配置
+# =============================================================================
+cors:
+  # Allowed origins list. Leave empty to disable cross-origin requests.
+  # 允许的来源列表。留空则禁用跨域请求。
+  allowed_origins: []
+  # Allow credentials (cookies/authorization headers). Cannot be used with "*".
+  # 允许携带凭证（cookies/授权头）。不能与 "*" 通配符同时使用。
+  allow_credentials: true
+
+# =============================================================================
+# Security Configuration
+# 安全配置
+# =============================================================================
+security:
+  # Legacy compatibility switch. When true, raw forwarded headers take over
+  # server.trusted_proxies. Set false to enforce the trusted proxy chain above.
+  # 旧版兼容开关。开启时原始转发头会接管 server.trusted_proxies；关闭后严格
+  # 使用上方配置的可信代理链。示例配置采用高安全模式。
+  trust_forwarded_ip_for_api_key_acl: false
+  # Optional client-IP headers for third-party CDNs, checked in list order before
+  # CF-Connecting-IP, X-Real-IP, and X-Forwarded-For. Valid only while the legacy
+  # compatibility switch above is true; maximum 16 unique HTTP header names.
+  # 第三方 CDN 的可选客户端 IP 请求头，按列表顺序优先于内置请求头解析。
+  # 仅在上方旧版兼容开关为 true 时生效；最多配置 16 个不重复的合法 HTTP 头名。
+  # Environment / 环境变量: SECURITY_FORWARDED_CLIENT_IP_HEADERS=True-Client-IP,X-CDN-Client-IP
+  forwarded_client_ip_headers: []
+  # Example / 示例:
+  # forwarded_client_ip_headers:
+  #   - "True-Client-IP"
+  #   - "X-CDN-Client-IP"
+  url_allowlist:
+    # Enable URL allowlist validation (disable to skip all URL checks)
+    # 启用 URL 白名单验证（禁用则跳过所有 URL 检查）
+    enabled: false
+    # Allowed upstream hosts for API proxying
+    # 允许代理的上游 API 主机列表
+    upstream_hosts:
+      - "api.openai.com"
+      - "api.anthropic.com"
+      - "api.kimi.com"
+      - "api.moonshot.ai"
+      - "api.moonshot.cn"
+      - "open.bigmodel.cn"
+      - "api.minimaxi.com"
+      - "opencode.ai"
+      - "generativelanguage.googleapis.com"
+      - "cloudcode-pa.googleapis.com"
+      - "*.openai.azure.com"
+    # Allowed hosts for pricing data download
+    # 允许下载定价数据的主机列表
+    pricing_hosts:
+      - "raw.githubusercontent.com"
+    # Allowed hosts for CRS sync (required when using CRS sync)
+    # 允许 CRS 同步的主机列表（使用 CRS 同步功能时必须配置）
+    crs_hosts: []
+    # Allow localhost/private IPs for upstream/pricing/CRS (use only in trusted networks)
+    # 允许本地/私有 IP 地址用于上游/定价/CRS（仅在可信网络中使用）
+    allow_private_hosts: true
+    # Allow http:// URLs when allowlist is disabled (default: true; set to false to require https)
+    # 白名单禁用时是否允许 http:// URL（默认: true，设为 false 则仅允许 https）
+    allow_insecure_http: true
+  response_headers:
+    # Enable configurable response header filtering (default: true)
+    # 启用可配置的响应头过滤（默认启用，过滤上游敏感响应头）
+    enabled: true
+    # Extra allowed response headers from upstream
+    # 额外允许的上游响应头
+    additional_allowed: []
+    # Force-remove response headers from upstream
+    # 强制移除的上游响应头
+    force_remove: []
+  csp:
+    # Enable Content-Security-Policy header
+    # 启用内容安全策略 (CSP) 响应头
+    enabled: true
+    # Default CSP policy (override if you host assets on other domains)
+    # 默认 CSP 策略（如果静态资源托管在其他域名，请自行覆盖）
+    # Note: __CSP_NONCE__ will be replaced with 'nonce-xxx' at request time for inline script security
+    # 注意：__CSP_NONCE__ 会在请求时被替换为 'nonce-xxx'，用于内联脚本安全
+    policy: "default-src 'self'; worker-src 'self' blob:; script-src 'self' __CSP_NONCE__ https://challenges.cloudflare.com https://*.alicdn.com https://static.cloudflareinsights.com https://turing.captcha.qcloud.com https://turing.captcha.gtimg.com https://ca.turing.captcha.qcloud.com https://global.turing.captcha.gtimg.com https://www.tycaptcha.com https://cloudcache.tencentcs.com https://*.stripe.com https://static.airwallex.com https://checkout.airwallex.com https://static-demo.airwallex.com https://checkout-demo.airwallex.com; style-src 'self' 'unsafe-inline' https://*.captcha.gtimg.com https://fonts.googleapis.com https://*.alicdn.com https://static.airwallex.com https://checkout.airwallex.com https://static-demo.airwallex.com https://checkout-demo.airwallex.com; img-src 'self' data: blob: https:; font-src 'self' data: https://fonts.gstatic.com; connect-src 'self' https://turing.captcha.qcloud.com https://www.tycaptcha.com https://rce.tencentrio.com https:; frame-src 'self' https://challenges.cloudflare.com https://turing.captcha.qcloud.com https://ca.turing.captcha.qcloud.com https://www.tycaptcha.com https://*.stripe.com https://checkout.airwallex.com https://checkout-demo.airwallex.com; frame-ancestors 'none'; base-uri 'self'; form-action 'self'"
+  proxy_probe:
+    # Allow skipping TLS verification for proxy probe (debug only)
+    # 允许代理探测时跳过 TLS 证书验证（仅用于调试）
+    insecure_skip_verify: false
+    # Optional ordered probe targets. Leave empty to use the built-in ip-api/ipify fallback.
+    # parser supports: ip-api, ipify, chatgpt-trace
+    # 可选的有序探测目标。留空时使用内置 ip-api/ipify 回退。
+    # parser 支持：ip-api、ipify、chatgpt-trace
+    urls: []
+    # urls:
+    #   - url: "https://chatgpt.com/cdn-cgi/trace"
+    #     parser: "chatgpt-trace"
+    #   - url: "https://api64.ipify.org?format=json"
+    #     parser: "ipify"
+  proxy_fallback:
+    # Allow auxiliary services (update check, pricing data) to fallback to direct
+    # connection when proxy initialization fails. Does NOT affect AI gateway connections.
+    # 辅助服务（更新检查、定价数据拉取）代理初始化失败时是否允许回退直连。
+    # 不影响 AI 账号网关连接。默认 false：fail-fast 防止 IP 泄露。
+    allow_direct_on_error: false
+
+# =============================================================================
+# Gateway Configuration
+# 网关配置
+# =============================================================================
+gateway:
+  # Timeout for waiting upstream response headers (seconds)
+  # 等待上游响应头超时时间（秒）
+  response_header_timeout: 600
+  # OpenAI/Codex upstream response header timeout (seconds, 0=disabled)
+  # OpenAI/Codex 等待上游响应头超时时间（秒，0=禁用本地响应头超时）
+  openai_response_header_timeout: 0
+  # Grok text Responses first-byte timeout (seconds, 0=disabled; default 120)
+  # Grok 文本 Responses 首字节超时时间（秒，0=禁用；默认 120）
+  grok_response_header_timeout: 120
+  # Native OpenAI HTTP Responses first semantic output timeout (seconds, 0=disabled)
+  # Includes response-header wait; does not apply to passthrough or WebSocket transports.
+  # A timed-out request may already have incurred upstream usage; account failover can therefore duplicate upstream billing.
+  # 超时请求可能已产生上游用量；切换账号重试可能导致上游重复计费。
+  # Pre-output attempt staging is capped at 8 MiB; overflow fails over without exposing partial SSE data.
+  # 首次输出前的单次尝试暂存上限为 8 MiB；溢出时切号且不暴露不完整 SSE 数据。
+  openai_first_output_timeout_seconds: 0
+  # Optional high/xhigh/max override (seconds, 0=use the standard timeout)
+  openai_high_effort_first_output_timeout_seconds: 0
+  # Max request body size in bytes (default: 256MB)
+  # 请求体最大字节数（默认 256MB）
+  max_body_size: 268435456
+  # Pure-text endpoint body limit (embeddings and alpha/search), default 32 MiB.
+  # 纯文本端点请求体上限（embeddings、alpha/search），默认 32 MiB。
+  text_max_body_size: 33554432
+  # Max bytes to read for non-stream upstream responses (default: 8MB)
+  # 非流式上游响应体读取上限（默认 8MB）
+  upstream_response_read_max_bytes: 8388608
+  # Max bytes to read for upstream model-list responses (default: 8MB)
+  # 上游模型列表响应体读取上限（默认 8MB）
+  models_list_read_max_bytes: 8388608
+  # Max bytes to read for proxy probe responses (default: 1MB)
+  # 代理探测响应体读取上限（默认 1MB）
+  proxy_probe_response_read_max_bytes: 1048576
+  # Enable Gemini upstream response header debug logs (default: false)
+  # 是否开启 Gemini 上游响应头调试日志（默认 false）
+  gemini_debug_response_headers: false
+  # Connection pool isolation strategy:
+  # 连接池隔离策略：
+  # - proxy: Isolate by proxy, same proxy shares connection pool (suitable for few proxies, many accounts)
+  # - proxy: 按代理隔离，同一代理共享连接池（适合代理少、账户多）
+  # - account: Isolate by account, same account shares connection pool (suitable for few accounts, strict isolation)
+  # - account: 按账户隔离，同一账户共享连接池（适合账户少、需严格隔离）
+  # - account_proxy: Isolate by account+proxy combination (default, finest granularity)
+  # - account_proxy: 按账户+代理组合隔离（默认，最细粒度）
+  connection_pool_isolation: "account_proxy"
+  # Force Codex CLI mode: treat all /openai/v1/responses requests as Codex CLI.
+  # 强制按 Codex CLI 处理 /openai/v1/responses 请求（用于网关未透传/改写 User-Agent 的兜底）。
+  #
+  # 注意：开启后会影响所有客户端的行为（不仅限于 VS Code / Codex CLI），请谨慎开启。
+  force_codex_cli: false
+  # Stop rewriting load-shed Codex originators to the official CLI identity.
+  # 关闭「把落在上游降载桶的 Codex originator 改写为官方 CLI 身份（codex_cli_rs）」。
+  #
+  # 上游 /backend-api/codex 按 originator 分桶调度容量：命中降载桶的请求即使 HTTP 200，
+  # 也会立刻推 server_is_overloaded 错误事件，网关据此判定瞬时上游故障并冷却账号，
+  # 对外表现为 Codex 账号频繁过载不可用。归一化只替换身份段，保留版本/OS/架构/终端指纹，
+  # 改写后 originator 与 User-Agent 首段仍然配套。
+  #
+  # 默认 false（即归一化开启）；仅当上游调整分桶、使归一化反而落入降载桶时才置 true。
+  disable_codex_originator_normalization: false
+  # Enable Codex image-generation bridge injection for /openai/v1/responses.
+  # 是否为 Codex /responses 请求自动注入 image_generation 工具与桥接指令。
+  #
+  # Default false keeps text-only Codex requests text-only. Explicit client-provided
+  # image_generation tools are still forwarded when the group allows image generation.
+  # 默认 false：保持纯文本 Codex 请求不被改写；客户端显式提供 image_generation tool 时，
+  # 仍会在分组允许图片生成的情况下正常转发。
+  codex_image_generation_bridge_enabled: false
+  # Optional: template file used to build the final top-level Codex `instructions`.
+  # 可选：用于构建最终 Codex 顶层 `instructions` 的模板文件路径。
+  #
+  # This is applied on the `/v1/messages -> Responses/Codex` conversion path,
+  # after Claude `system` has already been normalized into Codex `instructions`.
+  # 该模板作用于 `/v1/messages -> Responses/Codex` 转换链路，且发生在 Claude `system`
+  # 已经被归一化为 Codex `instructions` 之后。
+  #
+  # The template can reference:
+  # 模板可引用：
+  # - {{ .ExistingInstructions }} : converted client instructions/system
+  # - {{ .OriginalModel }}        : original requested model
+  # - {{ .NormalizedModel }}      : normalized routing model
+  # - {{ .BillingModel }}         : billing model
+  # - {{ .UpstreamModel }}        : final upstream model
+  #
+  # If you want to preserve client system prompts, keep {{ .ExistingInstructions }}
+  # somewhere in the template. If omitted, the template output fully replaces it.
+  # 如需保留客户端 system 提示词，请在模板中显式包含 {{ .ExistingInstructions }}。
+  # 若省略，则模板输出会完全覆盖它。
+  #
+  # Docker users can mount a host file to /app/data/codex-instructions.md.tmpl
+  # and point this field there.
+  # Docker 用户可将宿主机文件挂载到 /app/data/codex-instructions.md.tmpl，
+  # 然后把本字段指向该路径。
+  forced_codex_instructions_template_file: ""
+  # OpenAI 透传模式是否放行客户端超时头（如 x-stainless-timeout）
+  # 默认 false：过滤超时头，降低上游提前断流风险。
+  openai_passthrough_allow_timeout_headers: false
+  # Model used for OpenAI /responses/compact upstream requests (default: gpt-5.5).
+  # OpenAI /responses/compact 上游模型（默认 gpt-5.5）。
+  # Use this to avoid compact failures when newer models are not yet supported by the compact endpoint.
+  # 当 compact 端点暂未支持更新模型时，可通过这里降级规避失败。
+  openai_compact_model: "gpt-5.5"
+  # ChatGPT Frameless Live 单会话硬上限（秒）。
+  live:
+    max_session_duration_seconds: 3600
+  # OpenAI Responses WebSocket 配置（默认开启，可按需回滚到 HTTP）
+  openai_ws:
+    # 新版 WS mode 路由（默认关闭）。关闭时忽略账号级 WS mode（包括 http_bridge），保持 legacy ctx_pool 行为。
+    # 环境变量：GATEWAY_OPENAI_WS_MODE_ROUTER_V2_ENABLED=true
+    mode_router_v2_enabled: false
+    # ingress 默认模式：off|ctx_pool|passthrough|http_bridge（仅 mode_router_v2_enabled=true 生效；关闭时账号级 WS mode 被忽略）
+    # 兼容旧值：shared/dedicated 会按 ctx_pool 处理。
+    ingress_mode_default: ctx_pool
+    # 完整读取并解压首条客户端消息的总超时（秒）；大请求或慢链路可调高到 120-300。
+    client_first_message_timeout_seconds: 30
+    # Close a client WebSocket that stays idle between completed turns (seconds). Set 0 to disable.
+    ingress_inter_turn_idle_timeout_seconds: 300
+    # Limit live client WebSocket ingress sessions per API key across all instances. Set 0 to disable.
+    max_ingress_connections_per_api_key: 64
+    # 全局总开关，默认 true；关闭时所有请求保持原有 HTTP/SSE 路由
+    enabled: true
+    # 按账号类型细分开关
+    oauth_enabled: true
+    apikey_enabled: true
+    # 全局强制 OpenAI Responses 上游使用 HTTP/SSE，不使用 WebSocket（紧急回滚开关）。
+    # 此开关不强制 HTTP/1.1；HTTP/2 由 gateway.openai_http2 单独控制。
+    force_http: false
+    # 允许在 WSv2 下按策略恢复 store=true（默认 false）
+    allow_store_recovery: false
+    # ingress 模式收到 previous_response_not_found 时，自动去掉 previous_response_id 重试一次（默认 true）
+    ingress_previous_response_recovery_enabled: true
+    # store=false 且无可复用会话连接时的策略：
+    # strict=强制新建连接（隔离优先），adaptive=仅在高风险失败后强制新建，off=尽量复用（性能优先）
+    store_disabled_conn_mode: strict
+    # store=false 且无可复用会话连接时，是否强制新建连接（默认 true，优先会话隔离）
+    # 兼容旧配置：仅在 store_disabled_conn_mode 未配置时生效
+    store_disabled_force_new_conn: true
+    # 是否启用 WSv2 generate=false 预热（默认 false）
+    prewarm_generate_enabled: false
+    # 协议 feature 开关，v2 优先于 v1
+    responses_websockets: false
+    responses_websockets_v2: true
+    # 连接池参数（按账号池化复用）
+    max_conns_per_account: 128
+    min_idle_per_account: 4
+    max_idle_per_account: 12
+    # 是否按账号并发动态计算连接池上限：
+    # effective_max_conns = min(max_conns_per_account, ceil(account.concurrency * factor))
+    # 旧版及 mode_router_v2 的 ctx_pool 共用此开关和下方类型系数；关闭后使用 max_conns_per_account。
+    # mode_router_v2 下并发数 <= 0 的账号仍不可调度。
+    dynamic_max_conns_by_account_concurrency_enabled: true
+    # 按账号类型分别设置系数（OAuth / API Key）。
+    # ctx_pool 接入下每个客户端会话在整个生命周期（轮次之间也不释放）持有一条上游连接，
+    # 该上限限制的是同时持有连接的会话数，在飞请求数另由账号并发限制；
+    # 系数 1.0 会让存活会话数一到并发数，新会话就收到 1013 upstream websocket is busy。
+    # 空闲连接数另受 max_idle_per_account 裁剪。
+    oauth_max_conns_factor: 5.0
+    apikey_max_conns_factor: 5.0
+    dial_timeout_seconds: 10
+    read_timeout_seconds: 900
+    write_timeout_seconds: 120
+    pool_target_utilization: 0.7
+    queue_limit_per_conn: 64
+    # 流式写出批量 flush 参数
+    event_flush_batch_size: 1
+    event_flush_interval_ms: 10
+    # 预热触发冷却（毫秒）
+    prewarm_cooldown_ms: 300
+    # WS 回退到 HTTP 后的冷却时间（秒），用于避免 WS/HTTP 来回抖动；0 表示关闭冷却
+    fallback_cooldown_seconds: 30
+    # WS 重试退避参数（毫秒）
+    retry_backoff_initial_ms: 120
+    retry_backoff_max_ms: 2000
+    # 抖动比例（0-1）
+    retry_jitter_ratio: 0.2
+    # 单次请求 WS 重试总预算（毫秒）；建议设置为有限值，避免重试拉高 TTFT 长尾
+    retry_total_budget_ms: 5000
+    # payload_schema 日志采样率（0-1）；降低热路径日志放大
+    payload_log_sample_rate: 0.2
+    # 调度与粘连参数
+    lb_top_k: 7
+    sticky_session_ttl_seconds: 3600
+    # 会话哈希迁移兼容开关：新 key 未命中时回退读取旧 SHA-256 key
+    session_hash_read_old_fallback: true
+    # 会话哈希迁移兼容开关：写入时双写旧 SHA-256 key（短 TTL）
+    session_hash_dual_write_old: true
+    # context 元数据迁移兼容开关：保留旧 ctxkey.* 读取/注入桥接
+    metadata_bridge_enabled: true
+    sticky_response_id_ttl_seconds: 3600
+    # 兼容旧键：当 sticky_response_id_ttl_seconds 缺失时回退该值
+    sticky_previous_response_ttl_seconds: 3600
+    scheduler_score_weights:
+      priority: 1.0
+      load: 1.0
+      queue: 0.7
+      error_rate: 0.8
+      ttft: 0.5
+      # use-it-or-lose-it：倾向「会话窗口最早重置」的账号，剩余重置时间越短得分越高。
+      # 0 表示关闭（默认，不改变原有行为）；调大可让即将重置的账号被优先用尽。
+      reset: 0.0
+      # 倾向 7d 剩余额度更健康的账号；0 表示关闭（默认，不改变原有行为），小流量灰度可设为 0.3。
+      quota_headroom: 0.0
+      # 倾向上游声明倍率更低的账号；0 表示关闭（默认），建议启用时从 1.5 开始。
+      upstream_cost: 0.0
+  # OpenAI 高级调度器补充配置
+  openai_scheduler:
+    # 是否允许 session_hash sticky 在账号健康度恶化时临时逃逸；false 可一键回退旧行为
+    sticky_escape_enabled: true
+    # TTFT EWMA 超过该阈值（毫秒）时跳过 sticky，默认 15s，避免轻微抖动就逃逸
+    sticky_escape_ttft_ms: 15000
+    # 错误率 EWMA 超过该阈值时跳过 sticky，默认 0.5，仅在明显降级时触发
+    sticky_escape_error_rate: 0.5
+  # OpenAI HTTP upstream protocol strategy.
+  # OpenAI HTTP 上游协议策略（默认 HTTP/2；代理明确不兼容时可临时回退 HTTP/1.1）。
+  openai_http2:
+    enabled: true
+    allow_proxy_fallback_to_http1: true
+    fallback_error_threshold: 2
+    fallback_window_seconds: 60
+    fallback_ttl_seconds: 600
+  # OpenAI Responses SSE 代理断流熔断；按 proxy_id 跨账号隔离，仅影响下一次调度。
+  # 隔离是偏好而非硬闸：当全部候选账号都在被隔离代理下时自动放行（fail-open），
+  # 不会因熔断而返回"无可用账号"。3 秒内的并发断流合并为一次失败事件。
+  openai_proxy_stream_circuit:
+    disabled: false
+    failure_threshold: 2
+    window_seconds: 60
+    ttl_seconds: 600
+  # Grok free-tier local soft gate (scheduler filter only; admin QueryQuota/import probe bypasses it).
+  # Enabled by default because free detection requires an explicit subscription_tier/plan_type of "free".
+  # Stats/query failures fail open so DB issues do not block all Grok traffic.
+  grok:
+    # Email/password OAuth is off by default and hidden in the admin UI.
+    # Setting true enables POST /admin/grok/oauth/password (password → SSO → Build OAuth).
+    # Prefer SSO cookie, browser OAuth, or refresh_token re-auth in production.
+    password_auth_enabled: false
+    free_quota_soft_gate_enabled: true
+    free_quota_token_limit: 500000
+    free_quota_soft_gate_percent: 95
+    free_quota_window_hours: 24
+    # Stats cache for free-tier soft gate. Hot path never waits on DB: misses
+    # fail open and refresh in the background. Prefer >= 60s in production.
+    free_quota_stats_cache_seconds: 60
+  # HTTP upstream connection pool settings (HTTP/2 + multi-proxy scenario defaults)
+  # HTTP 上游连接池配置（HTTP/2 + 多代理场景默认值）
+  # Max idle connections across all hosts
+  # 所有主机的最大空闲连接数
+  max_idle_conns: 2560
+  # Max idle connections per host
+  # 每个主机的最大空闲连接数
+  max_idle_conns_per_host: 120
+  # Max connections per host
+  # 每个主机的最大连接数
+  max_conns_per_host: 1024
+  # Idle connection timeout (seconds)
+  # 空闲连接超时时间（秒）
+  idle_conn_timeout_seconds: 90
+  # Upstream client cache settings
+  # 上游连接池客户端缓存配置
+  # max_upstream_clients: Max cached clients, evicts least recently used when exceeded
+  # max_upstream_clients: 最大缓存客户端数量，超出后淘汰最久未使用的
+  max_upstream_clients: 5000
+  # client_idle_ttl_seconds: Client idle reclaim threshold (seconds), reclaimed when idle and no active requests
+  # client_idle_ttl_seconds: 客户端空闲回收阈值（秒），超时且无活跃请求时回收
+  client_idle_ttl_seconds: 900
+  # Concurrency slot expiration time (minutes)
+  # 并发槽位过期时间（分钟）
+  concurrency_slot_ttl_minutes: 30
+  # Stream data interval timeout (seconds), 0=disable
+  # 流数据间隔超时（秒），0=禁用
+  stream_data_interval_timeout: 180
+  # Stream keepalive interval (seconds), 0=disable
+  # 流式 keepalive 间隔（秒），0=禁用
+  stream_keepalive_interval: 10
+  # Image stream data interval timeout (seconds), 0=disable; independent from ordinary text streams
+  # 图片流数据间隔超时（秒），0=禁用；独立于普通文本流式
+  image_stream_data_interval_timeout: 900
+  # Image stream keepalive interval (seconds), 0=disable; independent from ordinary text streams
+  # 图片流式 keepalive 间隔（秒），0=禁用；独立于普通文本流式
+  image_stream_keepalive_interval: 10
+  # Non-streaming Images JSON keepalive interval (seconds), 0=disable; commits HTTP 200 after the first heartbeat
+  # 图片非流式 JSON keepalive 间隔（秒），0=禁用；首个心跳后 HTTP 状态会固化为 200
+  image_nonstream_keepalive_interval: 0
+  # Image generation independent concurrency limiter (process-local, default disabled)
+  # 图片生成独立并发限制（进程级，默认关闭；多实例总上限约为实例数×该值）
+  image_concurrency:
+    # Enable image-only concurrency protection; false keeps existing behavior unchanged
+    # 是否启用图片独立并发保护；false 保持现有行为不变
+    enabled: false
+    # Max concurrent image generation requests in this process, 0=unlimited
+    # 当前进程允许同时处理的图片生成请求数，0=不限制
+    max_concurrent_requests: 0
+    # Overflow mode when the image concurrency limit is full: reject/wait
+    # 图片并发满时的处理方式：reject=立即拒绝，wait=等待槽位
+    overflow_mode: "reject"
+    # Wait timeout for overflow_mode=wait (seconds), 0=do not wait
+    # wait 模式等待图片并发槽位的超时时间（秒），0=不等待
+    wait_timeout_seconds: 30
+    # Max image requests waiting in this process when overflow_mode=wait, 0=unlimited
+    # wait 模式当前进程允许排队等待的图片请求数，0=不限制
+    max_waiting_requests: 100
+  # SSE max line size in bytes (default: 40MB)
+  # SSE 单行最大字节数（默认 40MB）
+  max_line_size: 41943040
+  # Log upstream error response body summary (safe/truncated; does not log request content)
+  # 记录上游错误响应体摘要（安全/截断；不记录请求内容）
+  log_upstream_error_body: true
+  # Max bytes to log from upstream error body
+  # 记录上游错误响应体的最大字节数
+  log_upstream_error_body_max_bytes: 2048
+  # Auto inject anthropic-beta header for API-key accounts when needed (default: off)
+  # 需要时自动为 API-key 账户注入 anthropic-beta 头（默认：关闭）
+  inject_beta_for_apikey: false
+  # Allow failover on selected 400 errors (default: off)
+  # 允许在特定 400 错误时进行故障转移（默认：关闭）
+  failover_on_400: false
+  # Scheduling configuration
+  # 调度配置
+  scheduling:
+    # Sticky session max waiting queue size
+    # 粘性会话最大排队长度
+    sticky_session_max_waiting: 3
+    # Sticky session wait timeout (duration)
+    # 粘性会话等待超时（时间段）
+    sticky_session_wait_timeout: 120s
+    # Fallback wait timeout (duration)
+    # 兜底排队等待超时（时间段）
+    fallback_wait_timeout: 30s
+    # Fallback max waiting queue size
+    # 兜底最大排队长度
+    fallback_max_waiting: 100
+    # Prefer the account whose session window resets soonest (use-it-or-lose-it).
+    # 负载感知选择时优先用尽「会话窗口最早重置」的账号；false 保持
+    # 原有「优先级 → 负载率 → LRU」行为（默认）。
+    prefer_soonest_reset: false
+    # Enable batch load calculation for scheduling
+    # 启用调度批量负载计算
+    load_batch_enabled: true
+    # Tiny in-process TTL for batch load reads in milliseconds (0 disables)
+    # 调度批量负载读取的进程内短缓存 TTL（毫秒，0 表示禁用）
+    load_batch_cache_ttl_ms: 200
+    # Slot cleanup interval (duration)
+    # 并发槽位清理周期（时间段）
+    slot_cleanup_interval: 30s
+    # 是否允许受控回源到 DB（默认 true，保持现有行为）
+    db_fallback_enabled: true
+    # 受控回源超时（秒），0 表示不额外收紧超时
+    db_fallback_timeout_seconds: 0
+    # 受控回源限流（实例级 QPS），0 表示不限制
+    db_fallback_max_qps: 0
+    # outbox 轮询周期（秒）
+    outbox_poll_interval_seconds: 1
+    # outbox 滞后告警阈值（秒）
+    outbox_lag_warn_seconds: 5
+    # outbox 触发强制重建阈值（秒）
+    outbox_lag_rebuild_seconds: 10
+    # outbox 连续滞后触发次数
+    outbox_lag_rebuild_failures: 3
+    # outbox 积压触发重建阈值（行数）
+    outbox_backlog_rebuild_rows: 10000
+    # 全量重建周期（秒），0 表示禁用
+    full_rebuild_interval_seconds: 300
+  # TLS fingerprint simulation / TLS 指纹伪装
+  # Default profile "claude_cli_v2" simulates Node.js 20.x
+  # 默认模板 "claude_cli_v2" 模拟 Node.js 20.x 指纹
+  tls_fingerprint:
+    enabled: true
+    # profiles:
+    #   profile_1:
+    #     name: "Custom Profile 1"
+    #   profile_2:
+    #     name: "Custom Profile 2"
+
+# =============================================================================
+# Logging Configuration
+# 日志配置
+# =============================================================================
+log:
+  # Log level: debug/info/warn/error
+  # 日志级别：debug/info/warn/error
+  level: "info"
+  # Log format: json/console
+  # 日志格式：json/console
+  format: "console"
+  # Service name field written into each log line
+  # 每条日志都会附带 service 字段
+  service_name: "sub2api"
+  # Environment field written into each log line
+  # 每条日志都会附带 env 字段
+  env: "production"
+  # Include caller information
+  # 是否输出调用方位置信息
+  caller: true
+  # Stacktrace threshold: none/error/fatal
+  # 堆栈输出阈值：none/error/fatal
+  stacktrace_level: "error"
+  output:
+    # Keep stdout/stderr output for container log collection
+    # 保持标准输出用于容器日志采集
+    to_stdout: true
+    # Enable file output (default path auto-derived)
+    # 启用文件输出（默认路径自动推导）
+    to_file: true
+    # Empty means:
+    # - DATA_DIR set: {{DATA_DIR}}/logs/sub2api.log
+    # - otherwise: /app/data/logs/sub2api.log
+    # 留空时：
+    # - 设置 DATA_DIR：{{DATA_DIR}}/logs/sub2api.log
+    # - 否则：/app/data/logs/sub2api.log
+    file_path: ""
+  rotation:
+    # Max file size before rotation (MB)
+    # 单文件滚动阈值（MB）
+    max_size_mb: 100
+    # Number of rotated files to keep (0 means unlimited)
+    # 保留历史文件数量（0 表示不限制）
+    max_backups: 10
+    # Number of days to keep old log files (0 means unlimited)
+    # 历史日志保留天数（0 表示不限制）
+    max_age_days: 7
+    # Compress rotated files
+    # 是否压缩历史日志
+    compress: true
+    # Use local time for timestamp in rotated filename
+    # 滚动文件名时间戳使用本地时区
+    local_time: true
+  sampling:
+    # Enable zap sampler (reduce high-frequency repetitive logs)
+    # 启用 zap 采样（减少高频重复日志）
+    enabled: false
+    # Number of first entries per second to always log
+    # 每秒无采样保留的前 N 条日志
+    initial: 100
+    # Thereafter keep 1 out of N entries per second
+    # 之后每 N 条保留 1 条
+    thereafter: 100
+
+# Token refresh behavior
+# token 刷新行为控制
+token_refresh:
+  # Candidate accounts loaded per cursor page (maximum 1000)
+  # 每个游标分页加载的候选账号数量（最大 1000）
+  candidate_page_size: 200
+  # Maximum concurrent refresh attempts per provider (maximum 32)
+  # 每个平台的最大并发刷新数（最大 32）
+  provider_concurrency: 4
+  # Per-provider refresh requests per second in each server process (maximum 100)
+  # 每个服务进程中每个平台每秒允许的刷新请求数（最大 100）
+  provider_qps: 2
+  # Consecutive transient failures that contain a provider for the current cycle (maximum 100)
+  # 当前周期内触发平台级熔断的连续临时失败次数（最大 100）
+  provider_failure_threshold: 3
+  # Timeout for one upstream refresh attempt, in seconds (maximum 300)
+  # 单次上游刷新尝试的超时时间（秒，最大 300）
+  attempt_timeout_seconds: 15
+  # Total timeout for one background refresh cycle, in seconds (maximum 3600)
+  # 单个后台刷新周期的总超时时间（秒，最大 3600）
+  cycle_timeout_seconds: 240
+
+# =============================================================================
+# API Key Auth Cache Configuration
+# API Key 认证缓存配置
+# =============================================================================
+api_key_auth_cache:
+  # L1 cache size (entries), in-process LRU/TTL cache
+  # L1 缓存容量（条目数），进程内 LRU/TTL 缓存
+  l1_size: 65535
+  # L1 cache TTL (seconds)
+  # L1 缓存 TTL（秒）
+  l1_ttl_seconds: 15
+  # L2 cache TTL (seconds), stored in Redis
+  # L2 缓存 TTL（秒），Redis 中存储
+  l2_ttl_seconds: 300
+  # Negative cache TTL (seconds)
+  # 负缓存 TTL（秒）
+  negative_ttl_seconds: 30
+  # TTL jitter percent (0-100)
+  # TTL 抖动百分比（0-100）
+  jitter_percent: 10
+  # Enable singleflight for cache misses
+  # 缓存未命中时启用 singleflight 合并回源
+  singleflight: true
+  # Maximum concurrent database lookups for authentication cache misses
+  # 认证缓存未命中时允许并发回源数据库的最大数量
+  lookup_concurrency: 64
+  # Process-local invalid-auth abuse protection. Counts only missing, malformed,
+  # deprecated-query, and confirmed invalid credentials; valid requests and
+  # Redis/DB failures do not consume the budget.
+  # 本机无效鉴权防护：仅统计缺失、格式错误、废弃 query 及确认无效的凭据。
+  invalid_abuse:
+    enabled: true
+    # Invalid attempts per trusted client IP (IPv6 grouped by /64) per window.
+    # 每个可信客户端 IP（IPv6 按 /64 聚合）在窗口内允许的无效次数。
+    threshold: 120
+    window_seconds: 60
+    block_seconds: 60
+    # Maximum tracked client identities per process; memory remains bounded.
+    # 每进程最多跟踪的客户端身份数量，确保内存有界。
+    capacity: 16384
+
+# =============================================================================
+# API Key Creation Limits
+# 用户创建 API Key 的防滥用限制（0 表示不限制）
+# =============================================================================
+api_key_create:
+  # Maximum non-deleted API keys per user
+  # 单个用户同时存在（未删除）的 API Key 上限
+  max_active_per_user: 200
+  # Maximum API key creations per user per hour (custom and generated keys).
+  # Deleting a key does not refund the count, which blocks delete/recreate loops.
+  # 单个用户每小时可创建的 API Key 次数（自定义与自动生成均计入）；删除 Key 不返还次数，阻断删建循环
+  max_per_user_per_hour: 60
+
+# =============================================================================
+# Dashboard Cache Configuration
+# 仪表盘缓存配置
+# =============================================================================
+dashboard_cache:
+  # Enable dashboard cache
+  # 启用仪表盘缓存
+  enabled: true
+  # Redis key prefix for multi-environment isolation
+  # Redis key 前缀，用于多环境隔离
+  key_prefix: "sub2api:"
+  # Fresh TTL (seconds); within this window cached stats are considered fresh
+  # 新鲜阈值（秒）；命中后处于该窗口视为新鲜数据
+  stats_fresh_ttl_seconds: 15
+  # Cache TTL (seconds) stored in Redis
+  # Redis 缓存 TTL（秒）
+  stats_ttl_seconds: 30
+  # Async refresh timeout (seconds)
+  # 异步刷新超时（秒）
+  stats_refresh_timeout_seconds: 30
+
+# =============================================================================
+# Dashboard Aggregation Configuration
+# 仪表盘预聚合配置（重启生效）
+# =============================================================================
+dashboard_aggregation:
+  # Enable aggregation job
+  # 启用聚合作业
+  enabled: true
+  # Refresh interval (seconds)
+  # 刷新间隔（秒）
+  interval_seconds: 60
+  # Lookback window (seconds) for late-arriving data
+  # 回看窗口（秒），处理迟到数据
+  lookback_seconds: 120
+  # Allow manual backfill
+  # 允许手动回填
+  backfill_enabled: false
+  # Backfill max range (days)
+  # 回填最大跨度（天）
+  backfill_max_days: 31
+  # Recompute recent N days on startup
+  # 启动时重算最近 N 天
+  recompute_days: 2
+  # Retention windows (days)
+  # 保留窗口（天）
+  retention:
+    # Raw usage_logs retention
+    # 原始 usage_logs 保留天数
+    usage_logs_days: 90
+    # Hourly aggregation retention
+    # 小时聚合保留天数
+    hourly_days: 180
+    # Daily aggregation retention
+    # 日聚合保留天数
+    daily_days: 730
+
+# =============================================================================
+# Usage Cleanup Task Configuration
+# 使用记录清理任务配置（重启生效）
+# =============================================================================
+usage_cleanup:
+  # Enable cleanup task worker
+  # 启用清理任务执行器
+  enabled: true
+  # Max date range (days) per task
+  # 单次任务最大时间跨度（天）
+  max_range_days: 31
+  # Batch delete size
+  # 单批删除数量
+  batch_size: 5000
+  # Worker interval (seconds)
+  # 执行器轮询间隔（秒）
+  worker_interval_seconds: 10
+  # Task execution timeout (seconds)
+  # 单次任务最大执行时长（秒）
+  task_timeout_seconds: 1800
+
+# =============================================================================
+# HTTP 写接口幂等配置
+# Idempotency Configuration
+# =============================================================================
+idempotency:
+  # Observe-only 模式：
+  # true: 观察期，不带 Idempotency-Key 仍放行（但会记录）
+  # false: 强制期，不带 Idempotency-Key 直接拒绝（仅对接入幂等保护的接口生效）
+  observe_only: true
+  # 关键写接口幂等记录 TTL（秒）
+  default_ttl_seconds: 86400
+  # 系统操作接口（update/rollback/restart）幂等记录 TTL（秒）
+  system_operation_ttl_seconds: 3600
+  # processing 锁超时（秒）
+  processing_timeout_seconds: 30
+  # 可重试失败退避窗口（秒）
+  failed_retry_backoff_seconds: 5
+  # 持久化响应体最大长度（字节）
+  max_stored_response_len: 65536
+  # 过期幂等记录清理周期（秒）
+  cleanup_interval_seconds: 60
+  # 每轮清理最大删除条数
+  cleanup_batch_size: 500
+
+# =============================================================================
+# Concurrency Wait Configuration
+# 并发等待配置
+# =============================================================================
+concurrency:
+  # SSE ping interval during concurrency wait (seconds)
+  # 并发等待期间的 SSE ping 间隔（秒）
+  ping_interval: 10
+
+# =============================================================================
+# Database Configuration (PostgreSQL)
+# 数据库配置 (PostgreSQL)
+# =============================================================================
+database:
+  # Database host address
+  # 数据库主机地址
+  host: "localhost"
+  # Database port
+  # 数据库端口
+  port: 5432
+  # Database username
+  # 数据库用户名
+  user: "postgres"
+  # Database password
+  # 数据库密码
+  password: "your_secure_password_here"
+  # Database name
+  # 数据库名称
+  dbname: "sub2api"
+  # SSL mode: disable, prefer, require, verify-ca, verify-full
+  # SSL 模式：disable（禁用）, prefer（优先加密，默认）, require（要求）, verify-ca（验证CA）, verify-full（完全验证）
+  # 默认值为 "prefer"，数据库支持 SSL 时自动使用加密连接，不支持时回退明文
+  sslmode: "prefer"
+  # Max open connections (高并发场景建议 256+，需配合 PostgreSQL max_connections 调整)
+  # 最大打开连接数
+  max_open_conns: 256
+  # Max idle connections (建议为 max_open_conns 的 50%，减少频繁建连开销)
+  # 最大空闲连接数
+  max_idle_conns: 128
+  # Connection max lifetime (minutes)
+  # 连接最大存活时间（分钟）
+  conn_max_lifetime_minutes: 30
+  # Connection max idle time (minutes)
+  # 空闲连接最大存活时间（分钟）
+  conn_max_idle_time_minutes: 5
+
+# =============================================================================
+# Redis Configuration
+# Redis 配置
+# =============================================================================
+redis:
+  # Redis host address
+  # Redis 主机地址
+  host: "localhost"
+  # Redis port
+  # Redis 端口
+  port: 6379
+  # Redis ACL username (leave empty for default user)
+  # Redis ACL 用户名（使用默认用户时留空）
+  username: ""
+  # Redis password (leave empty if no password is set)
+  # Redis 密码（如果未设置密码则留空）
+  password: ""
+  # Database number (0-15)
+  # 数据库编号（0-15）
+  db: 0
+  # Connection pool size (max concurrent connections)
+  # 连接池大小（最大并发连接数）
+  pool_size: 1024
+  # Minimum number of idle connections (高并发场景建议 128+，保持足够热连接)
+  # 最小空闲连接数
+  min_idle_conns: 128
+  # Enable TLS/SSL connection
+  # 是否启用 TLS/SSL 连接
+  enable_tls: false
+
+# =============================================================================
+# Ops Monitoring (Optional)
+# 运维监控 (可选)
+# =============================================================================
+ops:
+  # Enable ops monitoring features (background jobs and APIs)
+  # 是否启用运维监控功能（后台任务和接口）
+  # Set to false to hide ops menu in sidebar and disable all ops features
+  # 设置为 false 可在左侧栏隐藏运维监控菜单并禁用所有运维监控功能
+  # Other detailed settings (cleanup, aggregation, etc.) are configured in ops settings dialog
+  # 其他详细设置（数据清理、预聚合等）在运维监控设置对话框中配置
+  enabled: true
+
+# =============================================================================
+# JWT Configuration
+# JWT 配置
+# =============================================================================
+jwt:
+  # IMPORTANT: Change this to a random string in production!
+  # 重要：生产环境中请更改为随机字符串！
+  # Generate with / 生成命令: openssl rand -hex 32
+  secret: "change-this-to-a-secure-random-string"
+  # Token expiration time in hours (max 168)
+  # 令牌过期时间（小时，最大 168）
+  expire_hour: 24
+  # Access Token 过期时间（分钟）
+  # 优先级说明：
+  # - >0: 按分钟生效（优先于 expire_hour）
+  # - =0: 回退使用 expire_hour
+  access_token_expire_minutes: 0
+
+# =============================================================================
+# TOTP (2FA) Configuration
+# TOTP 双因素认证配置
+# =============================================================================
+totp:
+  # IMPORTANT: Set a fixed encryption key for TOTP secrets.
+  # 重要：设置固定的 TOTP 加密密钥。
+  # If left empty, a random key will be generated on each startup, causing all
+  # existing TOTP configurations to become invalid (users won't be able to
+  # login with 2FA).
+  # 如果留空，每次启动将生成随机密钥，导致现有的 TOTP 配置失效（用户无法使用
+  # 双因素认证登录）。
+  # Generate with / 生成命令: openssl rand -hex 32
+  encryption_key: ""
+
+# =============================================================================
+# LinuxDo Connect OAuth Login (SSO)
+# LinuxDo Connect OAuth 登录（用于 Sub2API 用户登录）
+# =============================================================================
+linuxdo_connect:
+  enabled: false
+  client_id: ""
+  client_secret: ""
+  authorize_url: "https://connect.linux.do/oauth2/authorize"
+  token_url: "https://connect.linux.do/oauth2/token"
+  userinfo_url: "https://connect.linux.do/api/user"
+  scopes: "user"
+  # 示例: "https://your-domain.com/api/v1/auth/oauth/linuxdo/callback"
+  redirect_url: ""
+  # 安全提示：
+  # - 建议使用同源相对路径（以 / 开头），避免把 token 重定向到意外的第三方域名
+  # - 该地址不应包含 #fragment（本实现使用 URL fragment 传递 access_token）
+  frontend_redirect_url: "/auth/linuxdo/callback"
+  token_auth_method: "client_secret_post" # client_secret_post | client_secret_basic | none
+  # 注意：当 token_auth_method=none（public client）时，必须启用 PKCE
+  use_pkce: true
+  userinfo_email_path: ""
+  userinfo_id_path: ""
+  userinfo_username_path: ""
+
+# =============================================================================
+# Generic OIDC OAuth Login (SSO)
+# 通用 OIDC OAuth 登录（用于 Sub2API 用户登录）
+# =============================================================================
+oidc_connect:
+  enabled: false
+  provider_name: "OIDC"
+  client_id: ""
+  client_secret: ""
+  # 例如: "https://keycloak.example.com/realms/myrealm"
+  issuer_url: ""
+  # 可选: OIDC Discovery URL。为空时可手动填写 authorize/token/userinfo/jwks
+  discovery_url: ""
+  authorize_url: ""
+  token_url: ""
+  # 可选（仅补充 email/username，不用于 sub 可信绑定）
+  userinfo_url: ""
+  # validate_id_token=true 时必填
+  jwks_url: ""
+  scopes: "openid email profile"
+  # 示例: "https://your-domain.com/api/v1/auth/oauth/oidc/callback"
+  redirect_url: ""
+  # 安全提示：
+  # - 建议使用同源相对路径（以 / 开头），避免把 token 重定向到意外的第三方域名
+  # - 该地址不应包含 #fragment（本实现使用 URL fragment 传递 access_token）
+  frontend_redirect_url: "/auth/oidc/callback"
+  token_auth_method: "client_secret_post" # client_secret_post | client_secret_basic | none
+  # 注意：当 token_auth_method=none（public client）时，必须启用 PKCE
+  use_pkce: false
+  # 开启后强制校验 id_token 的签名和 claims（推荐）
+  validate_id_token: true
+  allowed_signing_algs: "RS256,ES256,PS256"
+  # 允许的时钟偏移（秒）
+  clock_skew_seconds: 120
+  # 若 Provider 返回 email_verified=false，是否拒绝登录
+  require_email_verified: false
+  userinfo_email_path: ""
+  userinfo_id_path: ""
+  userinfo_username_path: ""
+
+# =============================================================================
+# Default Settings
+# 默认设置
+# =============================================================================
+default:
+  # Initial admin account (created on first run)
+  # 初始管理员账户（首次运行时创建）
+  admin_email: "admin@example.com"
+  admin_password: "admin123"
+
+  # Default settings for new users
+  # 新用户默认设置
+  # Max concurrent requests per user
+  # 每用户最大并发请求数
+  user_concurrency: 5
+  # Initial balance for new users
+  # 新用户初始余额
+  user_balance: 0
+
+  # API key settings
+  # API 密钥设置
+  # Prefix for generated API keys
+  # 生成的 API 密钥前缀
+  api_key_prefix: "sk-"
+
+  # Rate multiplier (affects billing calculation)
+  # 费率倍数（影响计费计算）
+  rate_multiplier: 1.0
+
+# =============================================================================
+# Rate Limiting
+# 速率限制
+# =============================================================================
+rate_limit:
+  # Cooldown time (in minutes) when upstream returns 529 (overloaded)
+  # 上游返回 529（过载）时的冷却时间（分钟）
+  overload_cooldown_minutes: 10
+
+# =============================================================================
+# Local OAuth Transport Plugins (Optional)
+# 本地 OAuth 出站传输插件（可选）
+# =============================================================================
+plugins:
+  # Empty means {{DATA_DIR}}/plugins, or ./data/plugins when DATA_DIR is unset.
+  # 留空时使用 {{DATA_DIR}}/plugins；未设置 DATA_DIR 时使用 ./data/plugins。
+  data_dir: ""
+  # Keep false in production. Enable only for local development packages you built yourself.
+  # 生产环境应保持 false；仅调试自己构建的本地插件时临时开启。
+  allow_unsigned: false
+  # Additional Ed25519 public keys indexed by signature.json key_id.
+  # OpenAI Transport's public key is built in; this map only adds third-party publishers.
+  # 以 signature.json 中 key_id 为索引的额外 Ed25519 公钥。
+  # OpenAI Transport 公钥已内置，此处只需添加第三方发布者。
+  trusted_publishers: {}
+  max_upload_bytes: 134217728
+  max_uncompressed_bytes: 268435456
+  start_timeout_seconds: 15
+
+# =============================================================================
+# Pricing Data Source (Optional)
+# 定价数据源（可选）
+# =============================================================================
+pricing:
+  # URL to fetch model pricing data (default: model-price-repo main branch)
+  # 获取模型定价数据的 URL（默认：model-price-repo main 分支）
+  remote_url: "https://raw.githubusercontent.com/Wei-Shaw/model-price-repo/refs/heads/main//model_prices_and_context_window.json"
+  # Hash verification URL (optional)
+  # 哈希校验 URL（可选）
+  hash_url: "https://raw.githubusercontent.com/Wei-Shaw/model-price-repo/refs/heads/main//model_prices_and_context_window.sha256"
+  # Local data directory for caching
+  # 本地数据缓存目录
+  data_dir: "./data"
+  # Fallback pricing file: fills in models missing from the catalog. Edits are
+  # detected by content hash at the next hash check and reloaded without restart.
+  # 备用定价文件：只补目录缺失的模型。修改后在下一次哈希检查时按内容哈希自动重载，无需重启。
+  fallback_file: "./resources/model-pricing/model_prices_and_context_window.json"
+  # Override patch file (optional, highest priority): entries are shallow-merged
+  # field-by-field over catalog/fallback data; a null field value removes that field.
+  # Model names must match catalog keys exactly. Edits are detected by content hash
+  # at the next hash check and reloaded without restart.
+  # 覆盖补丁文件（可选，优先级最高）：条目按字段浅合并覆盖目录/回退数据，
+  # 字段值为 null 表示删除该字段。模型名须与目录键完全一致。
+  # 修改后在下一次哈希检查时按内容哈希自动重载，无需重启。
+  # override_file: "./data/model_pricing_overrides.json"
+  # Update interval in hours
+  # 更新间隔（小时）
+  update_interval_hours: 24
+  # Hash check interval in minutes. Each check compares the remote catalog hash and
+  # the local fallback/override file contents. Deleting a local file drops its
+  # entries at the next check; a present but non-JSON file keeps the previous data
+  # and is retried next check.
+  # 哈希检查间隔（分钟）。每次检查同时比对远程目录哈希与本地 fallback/override 文件内容；
+  # 删除本地文件会在下次检查时移除其条目，文件存在但不是 JSON 时保留旧数据、下次检查再试。
+  hash_check_interval_minutes: 10
+
+# =============================================================================
+# Billing Configuration
+# 计费配置
+# =============================================================================
+billing:
+  circuit_breaker:
+    # Enable circuit breaker for billing service
+    # 启用计费服务熔断器
+    enabled: true
+    # Number of failures before opening circuit
+    # 触发熔断的失败次数阈值
+    failure_threshold: 5
+    # Time to wait before attempting reset (seconds)
+    # 熔断后重试等待时间（秒）
+    reset_timeout_seconds: 30
+    # Number of requests to allow in half-open state
+    # 半开状态允许通过的请求数
+    half_open_requests: 3
+  # Conservative minimum balance required before forwarding balance-billed requests.
+  # Set to 0 to only require balance > 0.
+  # 余额计费请求转发前要求的保守最小余额；设为 0 则仅要求余额 > 0。
+  minimum_balance_reserve: 0.000001
+  # Cache TTL (seconds) for per-user × per-platform quota records
+  # 用户 × 平台 quota 缓存 TTL（秒），默认 86400=1天，覆盖典型 daily 窗口
+  user_platform_quota_cache_ttl_seconds: 86400
+  # In-flight balance reservation (Redis): at admission, estimate per-request cost
+  # (input estimate + output price x max_tokens) and atomically require
+  # cached_balance - in-flight reservations >= estimate. Released when the request ends.
+  # The first in-flight request of a user is always admitted (same as before).
+  # Fails open when the estimate cannot be computed or Redis is unavailable.
+  # 余额模式在途预留：准入时估算单请求费用，要求 缓存余额 - 在途预留合计 >= 估算；
+  # 用户无在途请求时始终放行（与旧行为一致）；估算失败/Redis 不可用时 fail-open。
+  inflight_reservation:
+    enabled: true
+    # Reservation TTL. Renewed every ttl/3 while the request is running; after the
+    # handler returns it is held (not renewed) until the async billing task has
+    # deducted the cached balance, so a stuck billing task frees it after at most one TTL.
+    # 预留 TTL（秒）。请求进行中每 ttl/3 续期；请求结束后不再续期，保持到异步计费
+    # 扣减余额缓存后释放，计费任务卡死时最多一个 TTL 后自动失效
+    ttl_seconds: 900
+    # Output tokens assumed when the request has no max_tokens
+    # 请求未携带 max_tokens 时假定的输出 token 数
+    default_max_tokens: 8192
+    # Cap for estimated output / input tokens
+    # 估算输出 / 输入 token 上限
+    max_output_tokens: 128000
+    max_input_tokens: 200000
+    # Cap for a single reservation in USD (0 = no cap)
+    # 单请求预留金额上限（USD，0 为不设上限）
+    max_reservation_usd: 0
+    # When a request cannot be priced (no base / group / channel pricing for the
+    # billing model), reject it instead of admitting it without reservation.
+    # 无法为请求定价（计费模型无基础/分组/渠道定价）时拒绝请求；默认 false 为放行不预留（节流告警日志）
+    fail_closed_on_unpriced: false
+
+# =============================================================================
+# Turnstile Configuration
+# Turnstile 人机验证配置
+# =============================================================================
+turnstile:
+  # Require Turnstile in release mode (when enabled, login/register will fail if not configured)
+  # 在 release 模式下要求 Turnstile 验证（启用后，若未配置则登录/注册会失败）
+  required: false
+
+# =============================================================================
+# Gemini OAuth (Required for Gemini accounts)
+# Gemini OAuth 配置（Gemini 账户必需）
+# =============================================================================
+# Sub2API supports TWO Gemini OAuth modes:
+# Sub2API 支持两种 Gemini OAuth 模式：
+#
+# 1. Code Assist OAuth (requires GCP project_id)
+# 1. Code Assist OAuth（需要 GCP project_id）
+#    - Uses: cloudcode-pa.googleapis.com (Code Assist API)
+#    - 使用：cloudcode-pa.googleapis.com（Code Assist API）
+#
+# 2. AI Studio OAuth (no project_id needed)
+# 2. AI Studio OAuth（不需要 project_id）
+#    - Uses: generativelanguage.googleapis.com (AI Studio API)
+#    - 使用：generativelanguage.googleapis.com（AI Studio API）
+#
+# Default: Uses Gemini CLI's public OAuth credentials (same as Google's official CLI tool)
+# 默认：使用 Gemini CLI 的公开 OAuth 凭证（与 Google 官方 CLI 工具相同）
+gemini:
+  oauth:
+    # OAuth 客户端配置说明：
+    # 1) 留空 client_id/client_secret：使用 Gemini CLI 内置 OAuth Client（其 client_secret 需通过环境变量注入）
+    #    - GEMINI_CLI_OAUTH_CLIENT_SECRET
+    # 2) 同时设置 client_id/client_secret：使用你自建的 OAuth Client（推荐，权限更完整）
+    #
+    # 注意：client_id 与 client_secret 必须同时为空或同时非空。
+    client_id: ""
+    client_secret: ""
+    # Optional scopes (space-separated). Leave empty to auto-select based on oauth_type.
+    # 可选的权限范围（空格分隔）。留空则根据 oauth_type 自动选择。
+    scopes: ""
+  quota:
+    # Optional: local quota simulation for Gemini Code Assist (local billing).
+    # 可选：Gemini Code Assist 本地配额模拟（本地计费）。
+    # These values are used for UI progress + precheck scheduling, not official Google quotas.
+    # 这些值用于 UI 进度显示和预检调度，并非 Google 官方配额。
+    tiers:
+      LEGACY:
+        # Pro model requests per day
+        # Pro 模型每日请求数
+        pro_rpd: 50
+        # Flash model requests per day
+        # Flash 模型每日请求数
+        flash_rpd: 1500
+        # Cooldown time (minutes) after hitting quota
+        # 达到配额后的冷却时间（分钟）
+        cooldown_minutes: 30
+      PRO:
+        # Pro model requests per day
+        # Pro 模型每日请求数
+        pro_rpd: 1500
+        # Flash model requests per day
+        # Flash 模型每日请求数
+        flash_rpd: 4000
+        # Cooldown time (minutes) after hitting quota
+        # 达到配额后的冷却时间（分钟）
+        cooldown_minutes: 5
+      ULTRA:
+        # Pro model requests per day
+        # Pro 模型每日请求数
+        pro_rpd: 2000
+        # Flash model requests per day (0 = unlimited)
+        # Flash 模型每日请求数（0 = 无限制）
+        flash_rpd: 0
+        # Cooldown time (minutes) after hitting quota
+        # 达到配额后的冷却时间（分钟）
+        cooldown_minutes: 5
+
+# =============================================================================
+# Update Configuration (在线更新配置)
+# =============================================================================
+update:
+  # Proxy URL for accessing GitHub (used for online updates and pricing data)
+  # 用于访问 GitHub 的代理地址（用于在线更新和定价数据获取）
+  # Supports: http, https, socks5, socks5h
+  # Examples:
+  #   - HTTP proxy: "http://127.0.0.1:7890"
+  #   - SOCKS5 proxy: "socks5://127.0.0.1:1080"
+  #   - With authentication: "http://user:pass@proxy.example.com:8080"
+  # Leave empty for direct connection (recommended for overseas servers)
+  # 留空表示直连（适用于海外服务器）
+  proxy_url: ""
+
+# =============================================================================
+# Image Storage (异步图片任务结果对象存储)
+# =============================================================================
+# 长耗时生图套 Cloudflare 会 524 超时，异步图片任务接口（/v1/images/generations/async
+# 等）先返回 task_id，再由客户端轮询 /v1/images/tasks/{task_id} 获取结果。
+#
+# 这里配置一个 S3 兼容对象存储（AWS S3 / Cloudflare R2 / 阿里云 OSS / MinIO 等），
+# 任务完成后把生成的图片上传到对象存储，只在 Redis 存一个短链接，避免 gpt-image-1 等
+# 返回的大 base64 结果把 Redis 撑爆。
+#
+# enabled 同时是异步图片任务功能的总开关：为 false 或凭证未配全时，异步生图接口
+# 整体返回 404、不创建任务、不写 Redis。
+#
+# 换其它厂商对象存储：只要它兼容 S3 API 即可直接用；如需完全自定义，实现
+# service.ImageStorage 接口（Save(ctx, key, contentType, data) -> url）即可。
+image_storage:
+  enabled: false
+  # S3 兼容端点。AWS 官方可留空；R2 形如 https://<account_id>.r2.cloudflarestorage.com
+  endpoint: ""
+  # 区域。Cloudflare R2 用 "auto"
+  region: "auto"
+  bucket: ""
+  access_key_id: ""
+  secret_access_key: ""
+  # 对象 key 前缀
+  prefix: "images/"
+  # MinIO / 需要路径风格（path-style）访问的桶设为 true
+  force_path_style: false
+  # 若填写公开桶 / CDN 域名，则返回 public_base_url/key 永久直链；
+  # 留空则返回带过期时间的 presigned 临时链接
+  public_base_url: ""
+  # public_base_url 为空时，presigned 链接的有效时长（小时）
+  presign_expiry_hours: 24
+  # 当上游返回的是图片 url 时，下载该图片再转存的字节上限（默认 32MB）
+  max_download_bytes: 33554432
diff --git a/docker-compose.dev.yml b/docker-compose.dev.yml
new file mode 100644
index 0000000..45789f4
--- /dev/null
+++ b/docker-compose.dev.yml
@@ -0,0 +1,175 @@
+# =============================================================================
+# Sub2API Docker Compose - Local Development Build
+# =============================================================================
+# Build from local source code for testing changes.
+#
+# Usage:
+#   cd deploy
+#   docker compose -f docker-compose.dev.yml up --build
+# =============================================================================
+
+services:
+  sub2api:
+    build:
+      context: ..
+      dockerfile: Dockerfile
+      args:
+        NPM_CONFIG_REGISTRY: ${NPM_CONFIG_REGISTRY:-https://registry.npmmirror.com}
+    container_name: sub2api-dev
+    restart: unless-stopped
+    security_opt:
+      - no-new-privileges:true
+    ports:
+      - "${BIND_HOST:-127.0.0.1}:${SERVER_PORT:-8080}:8080"
+    volumes:
+      - ./data:/app/data:Z
+    environment:
+      - AUTO_SETUP=true
+      - SERVER_HOST=0.0.0.0
+      - SERVER_PORT=8080
+      - SERVER_MODE=debug
+      - ENABLE_SERVER_TIMING=${ENABLE_SERVER_TIMING:-false}
+      - RUN_MODE=${RUN_MODE:-standard}
+      - SIMPLE_MODE_AUTO_CREATE_DEFAULT_GROUPS=${SIMPLE_MODE_AUTO_CREATE_DEFAULT_GROUPS:-}
+      - SIMPLE_MODE_KEY_RATE_LIMIT_ENABLED=${SIMPLE_MODE_KEY_RATE_LIMIT_ENABLED:-false}
+      - DATABASE_HOST=postgres
+      - DATABASE_PORT=5432
+      - DATABASE_USER=${POSTGRES_USER:-sub2api}
+      - DATABASE_PASSWORD=${POSTGRES_PASSWORD:?POSTGRES_PASSWORD is required}
+      - DATABASE_DBNAME=${POSTGRES_DB:-sub2api}
+      - DATABASE_SSLMODE=disable
+      - REDIS_HOST=redis
+      - REDIS_PORT=6379
+      - REDIS_USERNAME=${REDIS_USERNAME:-}
+      - REDIS_PASSWORD=${REDIS_PASSWORD:-}
+      - REDIS_DB=${REDIS_DB:-0}
+      - ADMIN_EMAIL=${ADMIN_EMAIL:-}
+      - ADMIN_PASSWORD=${ADMIN_PASSWORD:-}
+      - JWT_SECRET=${JWT_SECRET:-}
+      - SETUP_MIGRATION_TIMEOUT_SECONDS=${SETUP_MIGRATION_TIMEOUT_SECONDS:-0}
+      - TOTP_ENCRYPTION_KEY=${TOTP_ENCRYPTION_KEY:-}
+      - TZ=${TZ:-Asia/Shanghai}
+      # Local mainland-China development proxy. Containers cannot use
+      # 127.0.0.1 for the host proxy, so default to Docker Desktop's host name.
+      - HTTP_PROXY=${SUB2API_DEV_HTTP_PROXY:-http://host.docker.internal:7897}
+      - HTTPS_PROXY=${SUB2API_DEV_HTTPS_PROXY:-http://host.docker.internal:7897}
+      - ALL_PROXY=${SUB2API_DEV_ALL_PROXY:-socks5://host.docker.internal:7897}
+      - NO_PROXY=${SUB2API_DEV_NO_PROXY:-127.0.0.1,localhost,::1,postgres,redis,sub2api,192.168.0.0/16,10.0.0.0/8,172.16.0.0/12,.local}
+      # Gateway values come from Compose .env or the shell.
+      # Fallbacks mirror Sub2API backend defaults so omitted values preserve behavior.
+      - GATEWAY_FORCE_CODEX_CLI=${GATEWAY_FORCE_CODEX_CLI:-false}
+      - GATEWAY_OPENAI_COMPACT_MODEL=${GATEWAY_OPENAI_COMPACT_MODEL:-gpt-5.5}
+      - SUB2API_IMAGES_MAIN_MODEL=${SUB2API_IMAGES_MAIN_MODEL:-gpt-5.6-luna}
+      - GATEWAY_OPENAI_RESPONSE_HEADER_TIMEOUT=${GATEWAY_OPENAI_RESPONSE_HEADER_TIMEOUT:-0}
+      - GATEWAY_OPENAI_WS_FORCE_HTTP=${GATEWAY_OPENAI_WS_FORCE_HTTP:-false}
+      - GATEWAY_OPENAI_HTTP2_ENABLED=${GATEWAY_OPENAI_HTTP2_ENABLED:-true}
+      - GATEWAY_OPENAI_HTTP2_ALLOW_PROXY_FALLBACK_TO_HTTP1=${GATEWAY_OPENAI_HTTP2_ALLOW_PROXY_FALLBACK_TO_HTTP1:-true}
+      - GATEWAY_OPENAI_HTTP2_FALLBACK_ERROR_THRESHOLD=${GATEWAY_OPENAI_HTTP2_FALLBACK_ERROR_THRESHOLD:-2}
+      - GATEWAY_OPENAI_HTTP2_FALLBACK_WINDOW_SECONDS=${GATEWAY_OPENAI_HTTP2_FALLBACK_WINDOW_SECONDS:-60}
+      - GATEWAY_OPENAI_HTTP2_FALLBACK_TTL_SECONDS=${GATEWAY_OPENAI_HTTP2_FALLBACK_TTL_SECONDS:-600}
+      - GATEWAY_OPENAI_PROXY_STREAM_CIRCUIT_FAILURE_THRESHOLD=${GATEWAY_OPENAI_PROXY_STREAM_CIRCUIT_FAILURE_THRESHOLD:-2}
+      - GATEWAY_OPENAI_PROXY_STREAM_CIRCUIT_WINDOW_SECONDS=${GATEWAY_OPENAI_PROXY_STREAM_CIRCUIT_WINDOW_SECONDS:-60}
+      - GATEWAY_OPENAI_PROXY_STREAM_CIRCUIT_TTL_SECONDS=${GATEWAY_OPENAI_PROXY_STREAM_CIRCUIT_TTL_SECONDS:-600}
+      - GATEWAY_MAX_BODY_SIZE=${GATEWAY_MAX_BODY_SIZE:-268435456}
+      - GATEWAY_MAX_CONNS_PER_HOST=${GATEWAY_MAX_CONNS_PER_HOST:-1024}
+      - GATEWAY_MAX_IDLE_CONNS=${GATEWAY_MAX_IDLE_CONNS:-2560}
+      - GATEWAY_MAX_IDLE_CONNS_PER_HOST=${GATEWAY_MAX_IDLE_CONNS_PER_HOST:-120}
+      - GATEWAY_SCHEDULING_STICKY_SESSION_MAX_WAITING=${GATEWAY_SCHEDULING_STICKY_SESSION_MAX_WAITING:-3}
+      - GATEWAY_SCHEDULING_STICKY_SESSION_WAIT_TIMEOUT=${GATEWAY_SCHEDULING_STICKY_SESSION_WAIT_TIMEOUT:-120s}
+      - GATEWAY_SCHEDULING_FALLBACK_WAIT_TIMEOUT=${GATEWAY_SCHEDULING_FALLBACK_WAIT_TIMEOUT:-30s}
+      - GATEWAY_SCHEDULING_FALLBACK_MAX_WAITING=${GATEWAY_SCHEDULING_FALLBACK_MAX_WAITING:-100}
+      - GATEWAY_SCHEDULING_LOAD_BATCH_ENABLED=${GATEWAY_SCHEDULING_LOAD_BATCH_ENABLED:-true}
+      - GATEWAY_SCHEDULING_SLOT_CLEANUP_INTERVAL=${GATEWAY_SCHEDULING_SLOT_CLEANUP_INTERVAL:-30s}
+      - GATEWAY_SCHEDULING_DB_FALLBACK_ENABLED=${GATEWAY_SCHEDULING_DB_FALLBACK_ENABLED:-true}
+      - GATEWAY_SCHEDULING_DB_FALLBACK_TIMEOUT_SECONDS=${GATEWAY_SCHEDULING_DB_FALLBACK_TIMEOUT_SECONDS:-0}
+      - GATEWAY_SCHEDULING_DB_FALLBACK_MAX_QPS=${GATEWAY_SCHEDULING_DB_FALLBACK_MAX_QPS:-0}
+      - GATEWAY_SCHEDULING_OUTBOX_POLL_INTERVAL_SECONDS=${GATEWAY_SCHEDULING_OUTBOX_POLL_INTERVAL_SECONDS:-1}
+      - GATEWAY_SCHEDULING_OUTBOX_LAG_WARN_SECONDS=${GATEWAY_SCHEDULING_OUTBOX_LAG_WARN_SECONDS:-5}
+      - GATEWAY_SCHEDULING_OUTBOX_LAG_REBUILD_SECONDS=${GATEWAY_SCHEDULING_OUTBOX_LAG_REBUILD_SECONDS:-10}
+      - GATEWAY_SCHEDULING_OUTBOX_LAG_REBUILD_FAILURES=${GATEWAY_SCHEDULING_OUTBOX_LAG_REBUILD_FAILURES:-3}
+      - GATEWAY_SCHEDULING_OUTBOX_BACKLOG_REBUILD_ROWS=${GATEWAY_SCHEDULING_OUTBOX_BACKLOG_REBUILD_ROWS:-10000}
+      - GATEWAY_SCHEDULING_FULL_REBUILD_INTERVAL_SECONDS=${GATEWAY_SCHEDULING_FULL_REBUILD_INTERVAL_SECONDS:-300}
+      - GATEWAY_IMAGE_STREAM_DATA_INTERVAL_TIMEOUT=${GATEWAY_IMAGE_STREAM_DATA_INTERVAL_TIMEOUT:-900}
+      - GATEWAY_IMAGE_STREAM_KEEPALIVE_INTERVAL=${GATEWAY_IMAGE_STREAM_KEEPALIVE_INTERVAL:-10}
+      - GATEWAY_IMAGE_NONSTREAM_KEEPALIVE_INTERVAL=${GATEWAY_IMAGE_NONSTREAM_KEEPALIVE_INTERVAL:-0}
+      - GATEWAY_IMAGE_CONCURRENCY_ENABLED=${GATEWAY_IMAGE_CONCURRENCY_ENABLED:-false}
+      - GATEWAY_IMAGE_CONCURRENCY_MAX_CONCURRENT_REQUESTS=${GATEWAY_IMAGE_CONCURRENCY_MAX_CONCURRENT_REQUESTS:-0}
+      - GATEWAY_IMAGE_CONCURRENCY_OVERFLOW_MODE=${GATEWAY_IMAGE_CONCURRENCY_OVERFLOW_MODE:-reject}
+      - GATEWAY_IMAGE_CONCURRENCY_WAIT_TIMEOUT_SECONDS=${GATEWAY_IMAGE_CONCURRENCY_WAIT_TIMEOUT_SECONDS:-30}
+      - GATEWAY_IMAGE_CONCURRENCY_MAX_WAITING_REQUESTS=${GATEWAY_IMAGE_CONCURRENCY_MAX_WAITING_REQUESTS:-100}
+      - BATCH_IMAGE_ENABLED=${BATCH_IMAGE_ENABLED:-true}
+      - BATCH_IMAGE_QUEUE_ENABLED=${BATCH_IMAGE_QUEUE_ENABLED:-true}
+      - BATCH_IMAGE_VERTEX_ENABLED=${BATCH_IMAGE_VERTEX_ENABLED:-true}
+      - BATCH_IMAGE_VERTEX_PROJECT_ID=${BATCH_IMAGE_VERTEX_PROJECT_ID:-project-28424c50-8df2-46e2-a27}
+      - BATCH_IMAGE_VERTEX_LOCATION=${BATCH_IMAGE_VERTEX_LOCATION:-global}
+      - BATCH_IMAGE_VERTEX_MANAGED_GCS_BUCKET=${BATCH_IMAGE_VERTEX_MANAGED_GCS_BUCKET:-sub2-batch-image-prod-project-28424c50-8df2-46e2-a27}
+      - BATCH_IMAGE_VERTEX_MANAGED_GCS_PREFIX=${BATCH_IMAGE_VERTEX_MANAGED_GCS_PREFIX:-batch-image/prod/{batch_id}}
+      - BATCH_IMAGE_VERTEX_INPUT_RETENTION_HOURS=${BATCH_IMAGE_VERTEX_INPUT_RETENTION_HOURS:-24}
+      - BATCH_IMAGE_VERTEX_OUTPUT_RETENTION_HOURS=${BATCH_IMAGE_VERTEX_OUTPUT_RETENTION_HOURS:-72}
+    depends_on:
+      postgres:
+        condition: service_healthy
+      redis:
+        condition: service_healthy
+    networks:
+      - sub2api-network
+    healthcheck:
+      test: ["CMD", "wget", "-q", "-T", "5", "-O", "/dev/null", "http://localhost:8080/health"]
+      interval: 30s
+      timeout: 10s
+      retries: 3
+      start_period: 30s
+
+  postgres:
+    image: postgres:18-alpine
+    container_name: sub2api-postgres-dev
+    restart: unless-stopped
+    volumes:
+      - ./postgres_data:/var/lib/postgresql/data:Z
+    environment:
+      - POSTGRES_USER=${POSTGRES_USER:-sub2api}
+      - POSTGRES_PASSWORD=${POSTGRES_PASSWORD:?POSTGRES_PASSWORD is required}
+      - POSTGRES_DB=${POSTGRES_DB:-sub2api}
+      - PGDATA=/var/lib/postgresql/data
+      - TZ=${TZ:-Asia/Shanghai}
+    networks:
+      - sub2api-network
+    healthcheck:
+      test: ["CMD-SHELL", "pg_isready -U ${POSTGRES_USER:-sub2api} -d ${POSTGRES_DB:-sub2api}"]
+      interval: 10s
+      timeout: 5s
+      retries: 5
+      start_period: 10s
+
+  redis:
+    image: redis:8-alpine
+    container_name: sub2api-redis-dev
+    restart: unless-stopped
+    volumes:
+      - ./redis_data:/data:Z
+    command:
+      - redis-server
+      - --save
+      - "60"
+      - "1"
+      - --appendonly
+      - "yes"
+      - --appendfsync
+      - everysec
+      - --requirepass
+      - ${REDIS_PASSWORD:-}
+    environment:
+      - TZ=${TZ:-Asia/Shanghai}
+      - REDISCLI_AUTH=${REDIS_PASSWORD:-}
+    networks:
+      - sub2api-network
+    healthcheck:
+      test: ["CMD", "redis-cli", "ping"]
+      interval: 10s
+      timeout: 5s
+      retries: 5
+      start_period: 5s
+
+networks:
+  sub2api-network:
+    driver: bridge
diff --git a/docker-compose.local.yml b/docker-compose.local.yml
new file mode 100644
index 0000000..32bc439
--- /dev/null
+++ b/docker-compose.local.yml
@@ -0,0 +1,296 @@
+# =============================================================================
+# Sub2API Docker Compose - Local Directory Version
+# =============================================================================
+# This configuration uses local directories for data storage instead of named
+# volumes, making it easy to migrate the entire deployment by simply copying
+# the deploy directory.
+#
+# Quick Start:
+#   1. Copy .env.example to .env and configure
+#   2. mkdir -p data postgres_data redis_data
+#   3. docker-compose -f docker-compose.local.yml up -d
+#   4. Check logs: docker-compose -f docker-compose.local.yml logs -f sub2api
+#   5. Access: http://localhost:8080
+#
+# Migration to New Server:
+#   1. docker-compose -f docker-compose.local.yml down
+#   2. tar czf sub2api-deploy.tar.gz deploy/
+#   3. Transfer to new server and extract
+#   4. docker-compose -f docker-compose.local.yml up -d
+# =============================================================================
+
+services:
+  # ===========================================================================
+  # Sub2API Application
+  # ===========================================================================
+  sub2api:
+    image: weishaw/sub2api:latest
+    container_name: sub2api
+    restart: unless-stopped
+    security_opt:
+      - no-new-privileges:true
+    ulimits:
+      nofile:
+        soft: 100000
+        hard: 100000
+    ports:
+      - "${BIND_HOST:-0.0.0.0}:${SERVER_PORT:-8080}:8080"
+    volumes:
+      # Local directory mapping for easy migration
+      - ./data:/app/data:Z
+      # Optional: Mount custom config.yaml (uncomment and create the file first)
+      # Copy config.example.yaml to config.yaml, modify it, then uncomment:
+      # - ./config.yaml:/app/data/config.yaml
+    environment:
+      # =======================================================================
+      # Auto Setup (REQUIRED for Docker deployment)
+      # =======================================================================
+      - AUTO_SETUP=true
+
+      # =======================================================================
+      # Server Configuration
+      # =======================================================================
+      - SERVER_HOST=0.0.0.0
+      - SERVER_PORT=8080
+      - SERVER_MODE=${SERVER_MODE:-release}
+      - ENABLE_SERVER_TIMING=${ENABLE_SERVER_TIMING:-false}
+      - RUN_MODE=${RUN_MODE:-standard}
+      - SIMPLE_MODE_AUTO_CREATE_DEFAULT_GROUPS=${SIMPLE_MODE_AUTO_CREATE_DEFAULT_GROUPS:-}
+      - SIMPLE_MODE_KEY_RATE_LIMIT_ENABLED=${SIMPLE_MODE_KEY_RATE_LIMIT_ENABLED:-false}
+      - UPDATE_GITHUB_TOKEN=${UPDATE_GITHUB_TOKEN:-}
+
+      # =======================================================================
+      # Database Configuration (PostgreSQL)
+      # =======================================================================
+      - DATABASE_HOST=postgres
+      - DATABASE_PORT=5432
+      - DATABASE_USER=${POSTGRES_USER:-sub2api}
+      - DATABASE_PASSWORD=${POSTGRES_PASSWORD:?POSTGRES_PASSWORD is required}
+      - DATABASE_DBNAME=${POSTGRES_DB:-sub2api}
+      - DATABASE_SSLMODE=disable
+      - DATABASE_MAX_OPEN_CONNS=${DATABASE_MAX_OPEN_CONNS:-50}
+      - DATABASE_MAX_IDLE_CONNS=${DATABASE_MAX_IDLE_CONNS:-10}
+      - DATABASE_CONN_MAX_LIFETIME_MINUTES=${DATABASE_CONN_MAX_LIFETIME_MINUTES:-30}
+      - DATABASE_CONN_MAX_IDLE_TIME_MINUTES=${DATABASE_CONN_MAX_IDLE_TIME_MINUTES:-5}
+
+      # =======================================================================
+      # Redis Configuration
+      # =======================================================================
+      - REDIS_HOST=redis
+      - REDIS_PORT=6379
+      - REDIS_USERNAME=${REDIS_USERNAME:-}
+      - REDIS_PASSWORD=${REDIS_PASSWORD:-}
+      - REDIS_DB=${REDIS_DB:-0}
+      - REDIS_POOL_SIZE=${REDIS_POOL_SIZE:-1024}
+      - REDIS_MIN_IDLE_CONNS=${REDIS_MIN_IDLE_CONNS:-10}
+      - REDIS_ENABLE_TLS=${REDIS_ENABLE_TLS:-false}
+
+      # =======================================================================
+      # Admin Account (auto-created on first run)
+      # =======================================================================
+      - ADMIN_EMAIL=${ADMIN_EMAIL:-}
+      - ADMIN_PASSWORD=${ADMIN_PASSWORD:-}
+
+      # =======================================================================
+      # JWT Configuration
+      # =======================================================================
+      # IMPORTANT: Set a fixed JWT_SECRET to prevent login sessions from being
+      # invalidated after container restarts. If left empty, a random secret
+      # will be generated on each startup.
+      # Generate a secure secret: openssl rand -hex 32
+      - JWT_SECRET=${JWT_SECRET:-}
+      - JWT_EXPIRE_HOUR=${JWT_EXPIRE_HOUR:-24}
+
+      # =======================================================================
+      # Setup Configuration
+      # =======================================================================
+      - SETUP_MIGRATION_TIMEOUT_SECONDS=${SETUP_MIGRATION_TIMEOUT_SECONDS:-0}
+
+      # =======================================================================
+      # TOTP (2FA) Configuration
+      # =======================================================================
+      # IMPORTANT: Set a fixed encryption key for TOTP secrets. If left empty,
+      # a random key will be generated on each startup, causing all existing
+      # TOTP configurations to become invalid (users won't be able to login
+      # with 2FA).
+      # Generate a secure key: openssl rand -hex 32
+      - TOTP_ENCRYPTION_KEY=${TOTP_ENCRYPTION_KEY:-}
+
+      # =======================================================================
+      # Timezone Configuration
+      # This affects ALL time operations in the application:
+      # - Database timestamps
+      # - Usage statistics "today" boundary
+      # - Subscription expiry times
+      # - Log timestamps
+      # Common values: Asia/Shanghai, America/New_York, Europe/London, UTC
+      # =======================================================================
+      - TZ=${TZ:-Asia/Shanghai}
+
+      # =======================================================================
+      # Gemini OAuth Configuration (for Gemini accounts)
+      # =======================================================================
+      - GEMINI_OAUTH_CLIENT_ID=${GEMINI_OAUTH_CLIENT_ID:-}
+      - GEMINI_OAUTH_CLIENT_SECRET=${GEMINI_OAUTH_CLIENT_SECRET:-}
+      - GEMINI_OAUTH_SCOPES=${GEMINI_OAUTH_SCOPES:-}
+      - GEMINI_QUOTA_POLICY=${GEMINI_QUOTA_POLICY:-}
+
+      # Built-in OAuth client secrets (optional)
+      # SECURITY: This repo does not embed third-party client_secret.
+      - GEMINI_CLI_OAUTH_CLIENT_SECRET=${GEMINI_CLI_OAUTH_CLIENT_SECRET:-}
+      - ANTIGRAVITY_OAUTH_CLIENT_SECRET=${ANTIGRAVITY_OAUTH_CLIENT_SECRET:-}
+      - ANTIGRAVITY_USER_AGENT_VERSION=${ANTIGRAVITY_USER_AGENT_VERSION:-}
+
+      # =======================================================================
+      # Security Configuration (URL Allowlist)
+      # =======================================================================
+      # Enable URL allowlist validation (false to skip allowlist checks)
+      - SECURITY_URL_ALLOWLIST_ENABLED=${SECURITY_URL_ALLOWLIST_ENABLED:-false}
+      # Allow insecure HTTP URLs when allowlist is disabled (default: true; set to false to require https)
+      - SECURITY_URL_ALLOWLIST_ALLOW_INSECURE_HTTP=${SECURITY_URL_ALLOWLIST_ALLOW_INSECURE_HTTP:-true}
+      # Allow private IP addresses for upstream/pricing/CRS (default: true; set to false to block private hosts)
+      - SECURITY_URL_ALLOWLIST_ALLOW_PRIVATE_HOSTS=${SECURITY_URL_ALLOWLIST_ALLOW_PRIVATE_HOSTS:-true}
+      # Upstream hosts whitelist (comma-separated, only used when enabled=true)
+      - SECURITY_URL_ALLOWLIST_UPSTREAM_HOSTS=${SECURITY_URL_ALLOWLIST_UPSTREAM_HOSTS:-}
+
+      # =======================================================================
+      # Update Configuration (在线更新配置)
+      # =======================================================================
+      # Proxy for accessing GitHub (online updates + pricing data)
+      # Examples: http://host:port, socks5://host:port
+      - UPDATE_PROXY_URL=${UPDATE_PROXY_URL:-}
+
+      # =======================================================================
+      # Gateway Upstream, Scheduling & Image Configuration
+      # =======================================================================
+      # Gateway values come from Compose .env or the shell.
+      # Fallbacks mirror Sub2API backend defaults so omitted values preserve behavior.
+      - GATEWAY_FORCE_CODEX_CLI=${GATEWAY_FORCE_CODEX_CLI:-false}
+      - GATEWAY_OPENAI_COMPACT_MODEL=${GATEWAY_OPENAI_COMPACT_MODEL:-gpt-5.5}
+      - SUB2API_IMAGES_MAIN_MODEL=${SUB2API_IMAGES_MAIN_MODEL:-gpt-5.6-luna}
+      - GATEWAY_OPENAI_RESPONSE_HEADER_TIMEOUT=${GATEWAY_OPENAI_RESPONSE_HEADER_TIMEOUT:-0}
+      - GATEWAY_OPENAI_WS_FORCE_HTTP=${GATEWAY_OPENAI_WS_FORCE_HTTP:-false}
+      - GATEWAY_OPENAI_HTTP2_ENABLED=${GATEWAY_OPENAI_HTTP2_ENABLED:-true}
+      - GATEWAY_OPENAI_HTTP2_ALLOW_PROXY_FALLBACK_TO_HTTP1=${GATEWAY_OPENAI_HTTP2_ALLOW_PROXY_FALLBACK_TO_HTTP1:-true}
+      - GATEWAY_OPENAI_HTTP2_FALLBACK_ERROR_THRESHOLD=${GATEWAY_OPENAI_HTTP2_FALLBACK_ERROR_THRESHOLD:-2}
+      - GATEWAY_OPENAI_HTTP2_FALLBACK_WINDOW_SECONDS=${GATEWAY_OPENAI_HTTP2_FALLBACK_WINDOW_SECONDS:-60}
+      - GATEWAY_OPENAI_HTTP2_FALLBACK_TTL_SECONDS=${GATEWAY_OPENAI_HTTP2_FALLBACK_TTL_SECONDS:-600}
+      - GATEWAY_OPENAI_PROXY_STREAM_CIRCUIT_FAILURE_THRESHOLD=${GATEWAY_OPENAI_PROXY_STREAM_CIRCUIT_FAILURE_THRESHOLD:-2}
+      - GATEWAY_OPENAI_PROXY_STREAM_CIRCUIT_WINDOW_SECONDS=${GATEWAY_OPENAI_PROXY_STREAM_CIRCUIT_WINDOW_SECONDS:-60}
+      - GATEWAY_OPENAI_PROXY_STREAM_CIRCUIT_TTL_SECONDS=${GATEWAY_OPENAI_PROXY_STREAM_CIRCUIT_TTL_SECONDS:-600}
+      - GATEWAY_MAX_BODY_SIZE=${GATEWAY_MAX_BODY_SIZE:-268435456}
+      - GATEWAY_MAX_CONNS_PER_HOST=${GATEWAY_MAX_CONNS_PER_HOST:-1024}
+      - GATEWAY_MAX_IDLE_CONNS=${GATEWAY_MAX_IDLE_CONNS:-2560}
+      - GATEWAY_MAX_IDLE_CONNS_PER_HOST=${GATEWAY_MAX_IDLE_CONNS_PER_HOST:-120}
+      - GATEWAY_SCHEDULING_STICKY_SESSION_MAX_WAITING=${GATEWAY_SCHEDULING_STICKY_SESSION_MAX_WAITING:-3}
+      - GATEWAY_SCHEDULING_STICKY_SESSION_WAIT_TIMEOUT=${GATEWAY_SCHEDULING_STICKY_SESSION_WAIT_TIMEOUT:-120s}
+      - GATEWAY_SCHEDULING_FALLBACK_WAIT_TIMEOUT=${GATEWAY_SCHEDULING_FALLBACK_WAIT_TIMEOUT:-30s}
+      - GATEWAY_SCHEDULING_FALLBACK_MAX_WAITING=${GATEWAY_SCHEDULING_FALLBACK_MAX_WAITING:-100}
+      - GATEWAY_SCHEDULING_LOAD_BATCH_ENABLED=${GATEWAY_SCHEDULING_LOAD_BATCH_ENABLED:-true}
+      - GATEWAY_SCHEDULING_SLOT_CLEANUP_INTERVAL=${GATEWAY_SCHEDULING_SLOT_CLEANUP_INTERVAL:-30s}
+      - GATEWAY_SCHEDULING_DB_FALLBACK_ENABLED=${GATEWAY_SCHEDULING_DB_FALLBACK_ENABLED:-true}
+      - GATEWAY_SCHEDULING_DB_FALLBACK_TIMEOUT_SECONDS=${GATEWAY_SCHEDULING_DB_FALLBACK_TIMEOUT_SECONDS:-0}
+      - GATEWAY_SCHEDULING_DB_FALLBACK_MAX_QPS=${GATEWAY_SCHEDULING_DB_FALLBACK_MAX_QPS:-0}
+      - GATEWAY_SCHEDULING_OUTBOX_POLL_INTERVAL_SECONDS=${GATEWAY_SCHEDULING_OUTBOX_POLL_INTERVAL_SECONDS:-1}
+      - GATEWAY_SCHEDULING_OUTBOX_LAG_WARN_SECONDS=${GATEWAY_SCHEDULING_OUTBOX_LAG_WARN_SECONDS:-5}
+      - GATEWAY_SCHEDULING_OUTBOX_LAG_REBUILD_SECONDS=${GATEWAY_SCHEDULING_OUTBOX_LAG_REBUILD_SECONDS:-10}
+      - GATEWAY_SCHEDULING_OUTBOX_LAG_REBUILD_FAILURES=${GATEWAY_SCHEDULING_OUTBOX_LAG_REBUILD_FAILURES:-3}
+      - GATEWAY_SCHEDULING_OUTBOX_BACKLOG_REBUILD_ROWS=${GATEWAY_SCHEDULING_OUTBOX_BACKLOG_REBUILD_ROWS:-10000}
+      - GATEWAY_SCHEDULING_FULL_REBUILD_INTERVAL_SECONDS=${GATEWAY_SCHEDULING_FULL_REBUILD_INTERVAL_SECONDS:-300}
+      - GATEWAY_IMAGE_STREAM_DATA_INTERVAL_TIMEOUT=${GATEWAY_IMAGE_STREAM_DATA_INTERVAL_TIMEOUT:-900}
+      - GATEWAY_IMAGE_STREAM_KEEPALIVE_INTERVAL=${GATEWAY_IMAGE_STREAM_KEEPALIVE_INTERVAL:-10}
+      - GATEWAY_IMAGE_NONSTREAM_KEEPALIVE_INTERVAL=${GATEWAY_IMAGE_NONSTREAM_KEEPALIVE_INTERVAL:-0}
+      - GATEWAY_IMAGE_CONCURRENCY_ENABLED=${GATEWAY_IMAGE_CONCURRENCY_ENABLED:-false}
+      - GATEWAY_IMAGE_CONCURRENCY_MAX_CONCURRENT_REQUESTS=${GATEWAY_IMAGE_CONCURRENCY_MAX_CONCURRENT_REQUESTS:-0}
+      - GATEWAY_IMAGE_CONCURRENCY_OVERFLOW_MODE=${GATEWAY_IMAGE_CONCURRENCY_OVERFLOW_MODE:-reject}
+      - GATEWAY_IMAGE_CONCURRENCY_WAIT_TIMEOUT_SECONDS=${GATEWAY_IMAGE_CONCURRENCY_WAIT_TIMEOUT_SECONDS:-30}
+      - GATEWAY_IMAGE_CONCURRENCY_MAX_WAITING_REQUESTS=${GATEWAY_IMAGE_CONCURRENCY_MAX_WAITING_REQUESTS:-100}
+    depends_on:
+      postgres:
+        condition: service_healthy
+      redis:
+        condition: service_healthy
+    networks:
+      - sub2api-network
+    healthcheck:
+      test: ["CMD", "wget", "-q", "-T", "5", "-O", "/dev/null", "http://localhost:8080/health"]
+      interval: 30s
+      timeout: 10s
+      retries: 3
+      start_period: 30s
+
+  # ===========================================================================
+  # PostgreSQL Database
+  # ===========================================================================
+  postgres:
+    image: postgres:18-alpine
+    container_name: sub2api-postgres
+    restart: unless-stopped
+    ulimits:
+      nofile:
+        soft: 100000
+        hard: 100000
+    volumes:
+      # Local directory mapping for easy migration
+      - ./postgres_data:/var/lib/postgresql/data:Z
+    environment:
+      - POSTGRES_USER=${POSTGRES_USER:-sub2api}
+      - POSTGRES_PASSWORD=${POSTGRES_PASSWORD:?POSTGRES_PASSWORD is required}
+      - POSTGRES_DB=${POSTGRES_DB:-sub2api}
+      - PGDATA=/var/lib/postgresql/data
+      - TZ=${TZ:-Asia/Shanghai}
+    networks:
+      - sub2api-network
+    healthcheck:
+      test: ["CMD-SHELL", "pg_isready -U ${POSTGRES_USER:-sub2api} -d ${POSTGRES_DB:-sub2api}"]
+      interval: 10s
+      timeout: 5s
+      retries: 5
+      start_period: 10s
+    # 注意：不暴露端口到宿主机，应用通过内部网络连接
+    # 如需调试，可临时添加：ports: ["127.0.0.1:5433:5432"]
+
+  # ===========================================================================
+  # Redis Cache
+  # ===========================================================================
+  redis:
+    image: redis:8-alpine
+    container_name: sub2api-redis
+    restart: unless-stopped
+    ulimits:
+      nofile:
+        soft: 100000
+        hard: 100000
+    volumes:
+      # Local directory mapping for easy migration
+      - ./redis_data:/data:Z
+    command:
+      - redis-server
+      - --save
+      - "60"
+      - "1"
+      - --appendonly
+      - "yes"
+      - --appendfsync
+      - everysec
+      - --requirepass
+      - ${REDIS_PASSWORD:-}
+    environment:
+      - TZ=${TZ:-Asia/Shanghai}
+      # REDISCLI_AUTH is used by redis-cli for authentication (safer than -a flag)
+      - REDISCLI_AUTH=${REDIS_PASSWORD:-}
+    networks:
+      - sub2api-network
+    healthcheck:
+      test: ["CMD", "redis-cli", "ping"]
+      interval: 10s
+      timeout: 5s
+      retries: 5
+      start_period: 5s
+
+# =============================================================================
+# Networks
+# =============================================================================
+networks:
+  sub2api-network:
+    driver: bridge
diff --git a/docker-compose.standalone.yml b/docker-compose.standalone.yml
new file mode 100644
index 0000000..fe9619d
--- /dev/null
+++ b/docker-compose.standalone.yml
@@ -0,0 +1,164 @@
+# =============================================================================
+# Sub2API Docker Compose - Standalone Configuration
+# =============================================================================
+# This configuration runs only the Sub2API application.
+# PostgreSQL and Redis must be provided externally.
+#
+# Usage:
+#   1. Copy .env.example to .env and configure database/redis connection
+#   2. docker-compose -f docker-compose.standalone.yml up -d
+#   3. Access: http://localhost:8080
+# =============================================================================
+
+services:
+  sub2api:
+    image: weishaw/sub2api:latest
+    container_name: sub2api
+    restart: unless-stopped
+    security_opt:
+      - no-new-privileges:true
+    ulimits:
+      nofile:
+        soft: 100000
+        hard: 100000
+    ports:
+      - "${BIND_HOST:-0.0.0.0}:${SERVER_PORT:-8080}:8080"
+    volumes:
+      - sub2api_data:/app/data
+    extra_hosts:
+      - "host.docker.internal:host-gateway"
+    environment:
+      # =======================================================================
+      # Auto Setup
+      # =======================================================================
+      - AUTO_SETUP=true
+
+      # =======================================================================
+      # Server Configuration
+      # =======================================================================
+      - SERVER_HOST=0.0.0.0
+      - SERVER_PORT=8080
+      - SERVER_MODE=${SERVER_MODE:-release}
+      - ENABLE_SERVER_TIMING=${ENABLE_SERVER_TIMING:-false}
+      - RUN_MODE=${RUN_MODE:-standard}
+      - SIMPLE_MODE_AUTO_CREATE_DEFAULT_GROUPS=${SIMPLE_MODE_AUTO_CREATE_DEFAULT_GROUPS:-}
+      - SIMPLE_MODE_KEY_RATE_LIMIT_ENABLED=${SIMPLE_MODE_KEY_RATE_LIMIT_ENABLED:-false}
+      - UPDATE_GITHUB_TOKEN=${UPDATE_GITHUB_TOKEN:-}
+
+      # =======================================================================
+      # Database Configuration (PostgreSQL) - Required
+      # =======================================================================
+      - DATABASE_HOST=${DATABASE_HOST:?DATABASE_HOST is required}
+      - DATABASE_PORT=${DATABASE_PORT:-5432}
+      - DATABASE_USER=${DATABASE_USER:-sub2api}
+      - DATABASE_PASSWORD=${DATABASE_PASSWORD:?DATABASE_PASSWORD is required}
+      - DATABASE_DBNAME=${DATABASE_DBNAME:-sub2api}
+      - DATABASE_SSLMODE=${DATABASE_SSLMODE:-disable}
+      - DATABASE_MAX_OPEN_CONNS=${DATABASE_MAX_OPEN_CONNS:-50}
+      - DATABASE_MAX_IDLE_CONNS=${DATABASE_MAX_IDLE_CONNS:-10}
+      - DATABASE_CONN_MAX_LIFETIME_MINUTES=${DATABASE_CONN_MAX_LIFETIME_MINUTES:-30}
+      - DATABASE_CONN_MAX_IDLE_TIME_MINUTES=${DATABASE_CONN_MAX_IDLE_TIME_MINUTES:-5}
+
+      # =======================================================================
+      # Redis Configuration - Required
+      # =======================================================================
+      - REDIS_HOST=${REDIS_HOST:?REDIS_HOST is required}
+      - REDIS_PORT=${REDIS_PORT:-6379}
+      - REDIS_USERNAME=${REDIS_USERNAME:-}
+      - REDIS_PASSWORD=${REDIS_PASSWORD:-}
+      - REDIS_DB=${REDIS_DB:-0}
+      - REDIS_POOL_SIZE=${REDIS_POOL_SIZE:-1024}
+      - REDIS_MIN_IDLE_CONNS=${REDIS_MIN_IDLE_CONNS:-10}
+      - REDIS_ENABLE_TLS=${REDIS_ENABLE_TLS:-false}
+
+      # =======================================================================
+      # Admin Account (auto-created on first run)
+      # =======================================================================
+      - ADMIN_EMAIL=${ADMIN_EMAIL:-}
+      - ADMIN_PASSWORD=${ADMIN_PASSWORD:-}
+
+      # =======================================================================
+      # JWT Configuration
+      # =======================================================================
+      - JWT_SECRET=${JWT_SECRET:-}
+      - JWT_EXPIRE_HOUR=${JWT_EXPIRE_HOUR:-24}
+
+      # =======================================================================
+      # Setup Configuration
+      # =======================================================================
+      - SETUP_MIGRATION_TIMEOUT_SECONDS=${SETUP_MIGRATION_TIMEOUT_SECONDS:-0}
+
+      # =======================================================================
+      # Timezone Configuration
+      # =======================================================================
+      - TZ=${TZ:-Asia/Shanghai}
+
+      # =======================================================================
+      # Gemini OAuth Configuration (optional)
+      # =======================================================================
+      - GEMINI_OAUTH_CLIENT_ID=${GEMINI_OAUTH_CLIENT_ID:-}
+      - GEMINI_OAUTH_CLIENT_SECRET=${GEMINI_OAUTH_CLIENT_SECRET:-}
+      - GEMINI_OAUTH_SCOPES=${GEMINI_OAUTH_SCOPES:-}
+      - GEMINI_QUOTA_POLICY=${GEMINI_QUOTA_POLICY:-}
+
+      # Built-in OAuth client secrets (optional)
+      # SECURITY: This repo does not embed third-party client_secret.
+      - GEMINI_CLI_OAUTH_CLIENT_SECRET=${GEMINI_CLI_OAUTH_CLIENT_SECRET:-}
+      - ANTIGRAVITY_OAUTH_CLIENT_SECRET=${ANTIGRAVITY_OAUTH_CLIENT_SECRET:-}
+      - ANTIGRAVITY_USER_AGENT_VERSION=${ANTIGRAVITY_USER_AGENT_VERSION:-}
+
+      # =======================================================================
+      # Gateway Upstream, Scheduling & Image Configuration
+      # =======================================================================
+      # Gateway values come from Compose .env or the shell.
+      # Fallbacks mirror Sub2API backend defaults so omitted values preserve behavior.
+      - GATEWAY_FORCE_CODEX_CLI=${GATEWAY_FORCE_CODEX_CLI:-false}
+      - GATEWAY_OPENAI_COMPACT_MODEL=${GATEWAY_OPENAI_COMPACT_MODEL:-gpt-5.5}
+      - SUB2API_IMAGES_MAIN_MODEL=${SUB2API_IMAGES_MAIN_MODEL:-gpt-5.6-luna}
+      - GATEWAY_OPENAI_RESPONSE_HEADER_TIMEOUT=${GATEWAY_OPENAI_RESPONSE_HEADER_TIMEOUT:-0}
+      - GATEWAY_OPENAI_WS_FORCE_HTTP=${GATEWAY_OPENAI_WS_FORCE_HTTP:-false}
+      - GATEWAY_OPENAI_HTTP2_ENABLED=${GATEWAY_OPENAI_HTTP2_ENABLED:-true}
+      - GATEWAY_OPENAI_HTTP2_ALLOW_PROXY_FALLBACK_TO_HTTP1=${GATEWAY_OPENAI_HTTP2_ALLOW_PROXY_FALLBACK_TO_HTTP1:-true}
+      - GATEWAY_OPENAI_HTTP2_FALLBACK_ERROR_THRESHOLD=${GATEWAY_OPENAI_HTTP2_FALLBACK_ERROR_THRESHOLD:-2}
+      - GATEWAY_OPENAI_HTTP2_FALLBACK_WINDOW_SECONDS=${GATEWAY_OPENAI_HTTP2_FALLBACK_WINDOW_SECONDS:-60}
+      - GATEWAY_OPENAI_HTTP2_FALLBACK_TTL_SECONDS=${GATEWAY_OPENAI_HTTP2_FALLBACK_TTL_SECONDS:-600}
+      - GATEWAY_OPENAI_PROXY_STREAM_CIRCUIT_FAILURE_THRESHOLD=${GATEWAY_OPENAI_PROXY_STREAM_CIRCUIT_FAILURE_THRESHOLD:-2}
+      - GATEWAY_OPENAI_PROXY_STREAM_CIRCUIT_WINDOW_SECONDS=${GATEWAY_OPENAI_PROXY_STREAM_CIRCUIT_WINDOW_SECONDS:-60}
+      - GATEWAY_OPENAI_PROXY_STREAM_CIRCUIT_TTL_SECONDS=${GATEWAY_OPENAI_PROXY_STREAM_CIRCUIT_TTL_SECONDS:-600}
+      - GATEWAY_MAX_BODY_SIZE=${GATEWAY_MAX_BODY_SIZE:-268435456}
+      - GATEWAY_MAX_CONNS_PER_HOST=${GATEWAY_MAX_CONNS_PER_HOST:-1024}
+      - GATEWAY_MAX_IDLE_CONNS=${GATEWAY_MAX_IDLE_CONNS:-2560}
+      - GATEWAY_MAX_IDLE_CONNS_PER_HOST=${GATEWAY_MAX_IDLE_CONNS_PER_HOST:-120}
+      - GATEWAY_SCHEDULING_STICKY_SESSION_MAX_WAITING=${GATEWAY_SCHEDULING_STICKY_SESSION_MAX_WAITING:-3}
+      - GATEWAY_SCHEDULING_STICKY_SESSION_WAIT_TIMEOUT=${GATEWAY_SCHEDULING_STICKY_SESSION_WAIT_TIMEOUT:-120s}
+      - GATEWAY_SCHEDULING_FALLBACK_WAIT_TIMEOUT=${GATEWAY_SCHEDULING_FALLBACK_WAIT_TIMEOUT:-30s}
+      - GATEWAY_SCHEDULING_FALLBACK_MAX_WAITING=${GATEWAY_SCHEDULING_FALLBACK_MAX_WAITING:-100}
+      - GATEWAY_SCHEDULING_LOAD_BATCH_ENABLED=${GATEWAY_SCHEDULING_LOAD_BATCH_ENABLED:-true}
+      - GATEWAY_SCHEDULING_SLOT_CLEANUP_INTERVAL=${GATEWAY_SCHEDULING_SLOT_CLEANUP_INTERVAL:-30s}
+      - GATEWAY_SCHEDULING_DB_FALLBACK_ENABLED=${GATEWAY_SCHEDULING_DB_FALLBACK_ENABLED:-true}
+      - GATEWAY_SCHEDULING_DB_FALLBACK_TIMEOUT_SECONDS=${GATEWAY_SCHEDULING_DB_FALLBACK_TIMEOUT_SECONDS:-0}
+      - GATEWAY_SCHEDULING_DB_FALLBACK_MAX_QPS=${GATEWAY_SCHEDULING_DB_FALLBACK_MAX_QPS:-0}
+      - GATEWAY_SCHEDULING_OUTBOX_POLL_INTERVAL_SECONDS=${GATEWAY_SCHEDULING_OUTBOX_POLL_INTERVAL_SECONDS:-1}
+      - GATEWAY_SCHEDULING_OUTBOX_LAG_WARN_SECONDS=${GATEWAY_SCHEDULING_OUTBOX_LAG_WARN_SECONDS:-5}
+      - GATEWAY_SCHEDULING_OUTBOX_LAG_REBUILD_SECONDS=${GATEWAY_SCHEDULING_OUTBOX_LAG_REBUILD_SECONDS:-10}
+      - GATEWAY_SCHEDULING_OUTBOX_LAG_REBUILD_FAILURES=${GATEWAY_SCHEDULING_OUTBOX_LAG_REBUILD_FAILURES:-3}
+      - GATEWAY_SCHEDULING_OUTBOX_BACKLOG_REBUILD_ROWS=${GATEWAY_SCHEDULING_OUTBOX_BACKLOG_REBUILD_ROWS:-10000}
+      - GATEWAY_SCHEDULING_FULL_REBUILD_INTERVAL_SECONDS=${GATEWAY_SCHEDULING_FULL_REBUILD_INTERVAL_SECONDS:-300}
+      - GATEWAY_IMAGE_STREAM_DATA_INTERVAL_TIMEOUT=${GATEWAY_IMAGE_STREAM_DATA_INTERVAL_TIMEOUT:-900}
+      - GATEWAY_IMAGE_STREAM_KEEPALIVE_INTERVAL=${GATEWAY_IMAGE_STREAM_KEEPALIVE_INTERVAL:-10}
+      - GATEWAY_IMAGE_NONSTREAM_KEEPALIVE_INTERVAL=${GATEWAY_IMAGE_NONSTREAM_KEEPALIVE_INTERVAL:-0}
+      - GATEWAY_IMAGE_CONCURRENCY_ENABLED=${GATEWAY_IMAGE_CONCURRENCY_ENABLED:-false}
+      - GATEWAY_IMAGE_CONCURRENCY_MAX_CONCURRENT_REQUESTS=${GATEWAY_IMAGE_CONCURRENCY_MAX_CONCURRENT_REQUESTS:-0}
+      - GATEWAY_IMAGE_CONCURRENCY_OVERFLOW_MODE=${GATEWAY_IMAGE_CONCURRENCY_OVERFLOW_MODE:-reject}
+      - GATEWAY_IMAGE_CONCURRENCY_WAIT_TIMEOUT_SECONDS=${GATEWAY_IMAGE_CONCURRENCY_WAIT_TIMEOUT_SECONDS:-30}
+      - GATEWAY_IMAGE_CONCURRENCY_MAX_WAITING_REQUESTS=${GATEWAY_IMAGE_CONCURRENCY_MAX_WAITING_REQUESTS:-100}
+    healthcheck:
+      test: ["CMD", "wget", "-q", "-T", "5", "-O", "/dev/null", "http://localhost:8080/health"]
+      interval: 30s
+      timeout: 10s
+      retries: 3
+      start_period: 30s
+
+volumes:
+  sub2api_data:
+    driver: local
diff --git a/docker-compose.yml b/docker-compose.yml
new file mode 100644
index 0000000..84c9864
--- /dev/null
+++ b/docker-compose.yml
@@ -0,0 +1,331 @@
+# =============================================================================
+# Sub2API Docker Compose Configuration
+# =============================================================================
+# Quick Start:
+#   1. Copy .env.example to .env and configure
+#   2. docker-compose up -d
+#   3. Check logs: docker-compose logs -f sub2api
+#   4. Access: http://localhost:8080
+#
+# All configuration is done via environment variables.
+# No Setup Wizard needed - the system auto-initializes on first run.
+# =============================================================================
+
+services:
+  # ===========================================================================
+  # Sub2API Application
+  # ===========================================================================
+  sub2api:
+    image: weishaw/sub2api:latest
+    container_name: sub2api
+    restart: unless-stopped
+    security_opt:
+      - no-new-privileges:true
+    ulimits:
+      nofile:
+        soft: 100000
+        hard: 100000
+    ports:
+      - "${BIND_HOST:-0.0.0.0}:${SERVER_PORT:-8080}:8080"
+    volumes:
+      # Data persistence (config.yaml will be auto-generated here)
+      - sub2api_data:/app/data
+      # Optional: Mount custom config.yaml (uncomment and create the file first)
+      # Copy config.example.yaml to config.yaml, modify it, then uncomment:
+      # - ./config.yaml:/app/data/config.yaml
+      # Optional: Mount a custom Codex instructions template file, then point
+      # gateway.forced_codex_instructions_template_file at /app/data/codex-instructions.md.tmpl
+      # in config.yaml.
+      # - ./codex-instructions.md.tmpl:/app/data/codex-instructions.md.tmpl:ro
+    environment:
+      # =======================================================================
+      # Auto Setup (REQUIRED for Docker deployment)
+      # =======================================================================
+      - AUTO_SETUP=true
+
+      # =======================================================================
+      # Server Configuration
+      # =======================================================================
+      - SERVER_HOST=0.0.0.0
+      - SERVER_PORT=8080
+      - SERVER_MODE=${SERVER_MODE:-release}
+      - ENABLE_SERVER_TIMING=${ENABLE_SERVER_TIMING:-false}
+      - RUN_MODE=${RUN_MODE:-standard}
+      - SIMPLE_MODE_AUTO_CREATE_DEFAULT_GROUPS=${SIMPLE_MODE_AUTO_CREATE_DEFAULT_GROUPS:-}
+      - SIMPLE_MODE_KEY_RATE_LIMIT_ENABLED=${SIMPLE_MODE_KEY_RATE_LIMIT_ENABLED:-false}
+      - UPDATE_GITHUB_TOKEN=${UPDATE_GITHUB_TOKEN:-}
+      - ALIPAY_MOBILE_PRECREATE_DEEP_LINK=${ALIPAY_MOBILE_PRECREATE_DEEP_LINK:-}
+
+      # =======================================================================
+      # Database Configuration (PostgreSQL)
+      # =======================================================================
+      - DATABASE_HOST=postgres
+      - DATABASE_PORT=5432
+      - DATABASE_USER=${POSTGRES_USER:-sub2api}
+      - DATABASE_PASSWORD=${POSTGRES_PASSWORD:?POSTGRES_PASSWORD is required}
+      - DATABASE_DBNAME=${POSTGRES_DB:-sub2api}
+      - DATABASE_SSLMODE=disable
+      - DATABASE_MAX_OPEN_CONNS=${DATABASE_MAX_OPEN_CONNS:-50}
+      - DATABASE_MAX_IDLE_CONNS=${DATABASE_MAX_IDLE_CONNS:-10}
+      - DATABASE_CONN_MAX_LIFETIME_MINUTES=${DATABASE_CONN_MAX_LIFETIME_MINUTES:-30}
+      - DATABASE_CONN_MAX_IDLE_TIME_MINUTES=${DATABASE_CONN_MAX_IDLE_TIME_MINUTES:-5}
+
+      # =======================================================================
+      # Redis Configuration
+      # =======================================================================
+      - REDIS_HOST=redis
+      - REDIS_PORT=6379
+      - REDIS_USERNAME=${REDIS_USERNAME:-}
+      - REDIS_PASSWORD=${REDIS_PASSWORD:-}
+      - REDIS_DB=${REDIS_DB:-0}
+      - REDIS_POOL_SIZE=${REDIS_POOL_SIZE:-1024}
+      - REDIS_MIN_IDLE_CONNS=${REDIS_MIN_IDLE_CONNS:-10}
+      - REDIS_ENABLE_TLS=${REDIS_ENABLE_TLS:-false}
+
+      # =======================================================================
+      # Admin Account (auto-created on first run)
+      # =======================================================================
+      - ADMIN_EMAIL=${ADMIN_EMAIL:-}
+      - ADMIN_PASSWORD=${ADMIN_PASSWORD:-}
+
+      # =======================================================================
+      # JWT Configuration
+      # =======================================================================
+      # IMPORTANT: Set a fixed JWT_SECRET to prevent login sessions from being
+      # invalidated after container restarts. If left empty, a random secret
+      # will be generated on each startup.
+      # Generate a secure secret: openssl rand -hex 32
+      - JWT_SECRET=${JWT_SECRET:-}
+      - JWT_EXPIRE_HOUR=${JWT_EXPIRE_HOUR:-24}
+
+      # =======================================================================
+      # Setup Configuration
+      # =======================================================================
+      - SETUP_MIGRATION_TIMEOUT_SECONDS=${SETUP_MIGRATION_TIMEOUT_SECONDS:-0}
+
+      # =======================================================================
+      # TOTP (2FA) Configuration
+      # =======================================================================
+      # IMPORTANT: Set a fixed encryption key for TOTP secrets. If left empty,
+      # a random key will be generated on each startup, causing all existing
+      # TOTP configurations to become invalid (users won't be able to login
+      # with 2FA).
+      # Generate a secure key: openssl rand -hex 32
+      - TOTP_ENCRYPTION_KEY=${TOTP_ENCRYPTION_KEY:-}
+
+      # =======================================================================
+      # Timezone Configuration
+      # This affects ALL time operations in the application:
+      # - Database timestamps
+      # - Usage statistics "today" boundary
+      # - Subscription expiry times
+      # - Log timestamps
+      # Common values: Asia/Shanghai, America/New_York, Europe/London, UTC
+      # =======================================================================
+      - TZ=${TZ:-Asia/Shanghai}
+
+      # =======================================================================
+      # Gemini OAuth Configuration (for Gemini accounts)
+      # =======================================================================
+      - GEMINI_OAUTH_CLIENT_ID=${GEMINI_OAUTH_CLIENT_ID:-}
+      - GEMINI_OAUTH_CLIENT_SECRET=${GEMINI_OAUTH_CLIENT_SECRET:-}
+      - GEMINI_OAUTH_SCOPES=${GEMINI_OAUTH_SCOPES:-}
+      - GEMINI_QUOTA_POLICY=${GEMINI_QUOTA_POLICY:-}
+
+      # Built-in OAuth client secrets (optional)
+      # SECURITY: This repo does not embed third-party client_secret.
+      - GEMINI_CLI_OAUTH_CLIENT_SECRET=${GEMINI_CLI_OAUTH_CLIENT_SECRET:-}
+      - ANTIGRAVITY_OAUTH_CLIENT_SECRET=${ANTIGRAVITY_OAUTH_CLIENT_SECRET:-}
+      - ANTIGRAVITY_USER_AGENT_VERSION=${ANTIGRAVITY_USER_AGENT_VERSION:-}
+
+      # =======================================================================
+      # Security Configuration (URL Allowlist)
+      # =======================================================================
+      # Enable URL allowlist validation (false to skip allowlist checks)
+      - SECURITY_URL_ALLOWLIST_ENABLED=${SECURITY_URL_ALLOWLIST_ENABLED:-false}
+      # Allow insecure HTTP URLs when allowlist is disabled (default: true; set to false to require https)
+      - SECURITY_URL_ALLOWLIST_ALLOW_INSECURE_HTTP=${SECURITY_URL_ALLOWLIST_ALLOW_INSECURE_HTTP:-true}
+      # Allow private IP addresses for upstream/pricing/CRS (default: true; set to false to block private hosts)
+      - SECURITY_URL_ALLOWLIST_ALLOW_PRIVATE_HOSTS=${SECURITY_URL_ALLOWLIST_ALLOW_PRIVATE_HOSTS:-true}
+      # Upstream hosts whitelist (comma-separated, only used when enabled=true)
+      - SECURITY_URL_ALLOWLIST_UPSTREAM_HOSTS=${SECURITY_URL_ALLOWLIST_UPSTREAM_HOSTS:-}
+
+      # =======================================================================
+      # Update Configuration (在线更新配置)
+      # =======================================================================
+      # Proxy for accessing GitHub (online updates + pricing data)
+      # Examples: http://host:port, socks5://host:port
+      - UPDATE_PROXY_URL=${UPDATE_PROXY_URL:-}
+
+      # =======================================================================
+      # Gateway Upstream, Scheduling & Image Configuration
+      # =======================================================================
+      # Gateway values come from Compose .env or the shell.
+      # Fallbacks mirror Sub2API backend defaults so omitted values preserve behavior.
+      - GATEWAY_FORCE_CODEX_CLI=${GATEWAY_FORCE_CODEX_CLI:-false}
+      - GATEWAY_OPENAI_COMPACT_MODEL=${GATEWAY_OPENAI_COMPACT_MODEL:-gpt-5.5}
+      - SUB2API_IMAGES_MAIN_MODEL=${SUB2API_IMAGES_MAIN_MODEL:-gpt-5.6-luna}
+      - GATEWAY_OPENAI_RESPONSE_HEADER_TIMEOUT=${GATEWAY_OPENAI_RESPONSE_HEADER_TIMEOUT:-0}
+      - GATEWAY_OPENAI_WS_FORCE_HTTP=${GATEWAY_OPENAI_WS_FORCE_HTTP:-false}
+      - GATEWAY_OPENAI_HTTP2_ENABLED=${GATEWAY_OPENAI_HTTP2_ENABLED:-true}
+      - GATEWAY_OPENAI_HTTP2_ALLOW_PROXY_FALLBACK_TO_HTTP1=${GATEWAY_OPENAI_HTTP2_ALLOW_PROXY_FALLBACK_TO_HTTP1:-true}
+      - GATEWAY_OPENAI_HTTP2_FALLBACK_ERROR_THRESHOLD=${GATEWAY_OPENAI_HTTP2_FALLBACK_ERROR_THRESHOLD:-2}
+      - GATEWAY_OPENAI_HTTP2_FALLBACK_WINDOW_SECONDS=${GATEWAY_OPENAI_HTTP2_FALLBACK_WINDOW_SECONDS:-60}
+      - GATEWAY_OPENAI_HTTP2_FALLBACK_TTL_SECONDS=${GATEWAY_OPENAI_HTTP2_FALLBACK_TTL_SECONDS:-600}
+      - GATEWAY_OPENAI_PROXY_STREAM_CIRCUIT_FAILURE_THRESHOLD=${GATEWAY_OPENAI_PROXY_STREAM_CIRCUIT_FAILURE_THRESHOLD:-2}
+      - GATEWAY_OPENAI_PROXY_STREAM_CIRCUIT_WINDOW_SECONDS=${GATEWAY_OPENAI_PROXY_STREAM_CIRCUIT_WINDOW_SECONDS:-60}
+      - GATEWAY_OPENAI_PROXY_STREAM_CIRCUIT_TTL_SECONDS=${GATEWAY_OPENAI_PROXY_STREAM_CIRCUIT_TTL_SECONDS:-600}
+      - GATEWAY_MAX_BODY_SIZE=${GATEWAY_MAX_BODY_SIZE:-268435456}
+      - GATEWAY_MAX_CONNS_PER_HOST=${GATEWAY_MAX_CONNS_PER_HOST:-1024}
+      - GATEWAY_MAX_IDLE_CONNS=${GATEWAY_MAX_IDLE_CONNS:-2560}
+      - GATEWAY_MAX_IDLE_CONNS_PER_HOST=${GATEWAY_MAX_IDLE_CONNS_PER_HOST:-120}
+      - GATEWAY_SCHEDULING_STICKY_SESSION_MAX_WAITING=${GATEWAY_SCHEDULING_STICKY_SESSION_MAX_WAITING:-3}
+      - GATEWAY_SCHEDULING_STICKY_SESSION_WAIT_TIMEOUT=${GATEWAY_SCHEDULING_STICKY_SESSION_WAIT_TIMEOUT:-120s}
+      - GATEWAY_SCHEDULING_FALLBACK_WAIT_TIMEOUT=${GATEWAY_SCHEDULING_FALLBACK_WAIT_TIMEOUT:-30s}
+      - GATEWAY_SCHEDULING_FALLBACK_MAX_WAITING=${GATEWAY_SCHEDULING_FALLBACK_MAX_WAITING:-100}
+      - GATEWAY_SCHEDULING_LOAD_BATCH_ENABLED=${GATEWAY_SCHEDULING_LOAD_BATCH_ENABLED:-true}
+      - GATEWAY_SCHEDULING_SLOT_CLEANUP_INTERVAL=${GATEWAY_SCHEDULING_SLOT_CLEANUP_INTERVAL:-30s}
+      - GATEWAY_SCHEDULING_DB_FALLBACK_ENABLED=${GATEWAY_SCHEDULING_DB_FALLBACK_ENABLED:-true}
+      - GATEWAY_SCHEDULING_DB_FALLBACK_TIMEOUT_SECONDS=${GATEWAY_SCHEDULING_DB_FALLBACK_TIMEOUT_SECONDS:-0}
+      - GATEWAY_SCHEDULING_DB_FALLBACK_MAX_QPS=${GATEWAY_SCHEDULING_DB_FALLBACK_MAX_QPS:-0}
+      - GATEWAY_SCHEDULING_OUTBOX_POLL_INTERVAL_SECONDS=${GATEWAY_SCHEDULING_OUTBOX_POLL_INTERVAL_SECONDS:-1}
+      - GATEWAY_SCHEDULING_OUTBOX_LAG_WARN_SECONDS=${GATEWAY_SCHEDULING_OUTBOX_LAG_WARN_SECONDS:-5}
+      - GATEWAY_SCHEDULING_OUTBOX_LAG_REBUILD_SECONDS=${GATEWAY_SCHEDULING_OUTBOX_LAG_REBUILD_SECONDS:-10}
+      - GATEWAY_SCHEDULING_OUTBOX_LAG_REBUILD_FAILURES=${GATEWAY_SCHEDULING_OUTBOX_LAG_REBUILD_FAILURES:-3}
+      - GATEWAY_SCHEDULING_OUTBOX_BACKLOG_REBUILD_ROWS=${GATEWAY_SCHEDULING_OUTBOX_BACKLOG_REBUILD_ROWS:-10000}
+      - GATEWAY_SCHEDULING_FULL_REBUILD_INTERVAL_SECONDS=${GATEWAY_SCHEDULING_FULL_REBUILD_INTERVAL_SECONDS:-300}
+      - GATEWAY_IMAGE_STREAM_DATA_INTERVAL_TIMEOUT=${GATEWAY_IMAGE_STREAM_DATA_INTERVAL_TIMEOUT:-900}
+      - GATEWAY_IMAGE_STREAM_KEEPALIVE_INTERVAL=${GATEWAY_IMAGE_STREAM_KEEPALIVE_INTERVAL:-10}
+      - GATEWAY_IMAGE_NONSTREAM_KEEPALIVE_INTERVAL=${GATEWAY_IMAGE_NONSTREAM_KEEPALIVE_INTERVAL:-0}
+      - GATEWAY_IMAGE_CONCURRENCY_ENABLED=${GATEWAY_IMAGE_CONCURRENCY_ENABLED:-false}
+      - GATEWAY_IMAGE_CONCURRENCY_MAX_CONCURRENT_REQUESTS=${GATEWAY_IMAGE_CONCURRENCY_MAX_CONCURRENT_REQUESTS:-0}
+      - GATEWAY_IMAGE_CONCURRENCY_OVERFLOW_MODE=${GATEWAY_IMAGE_CONCURRENCY_OVERFLOW_MODE:-reject}
+      - GATEWAY_IMAGE_CONCURRENCY_WAIT_TIMEOUT_SECONDS=${GATEWAY_IMAGE_CONCURRENCY_WAIT_TIMEOUT_SECONDS:-30}
+      - GATEWAY_IMAGE_CONCURRENCY_MAX_WAITING_REQUESTS=${GATEWAY_IMAGE_CONCURRENCY_MAX_WAITING_REQUESTS:-100}
+    depends_on:
+      postgres:
+        condition: service_healthy
+      redis:
+        condition: service_healthy
+    networks:
+      - sub2api-network
+    healthcheck:
+      test:
+        [
+          "CMD",
+          "wget",
+          "-q",
+          "-T",
+          "5",
+          "-O",
+          "/dev/null",
+          "http://localhost:8080/health",
+        ]
+      interval: 30s
+      timeout: 10s
+      retries: 3
+      # The application also retries transient database startup errors. This
+      # grace period keeps Compose from declaring it unhealthy during bootstrap.
+      start_period: 120s
+
+  # ===========================================================================
+  # PostgreSQL Database
+  # ===========================================================================
+  postgres:
+    image: postgres:18-alpine
+    container_name: sub2api-postgres
+    restart: unless-stopped
+    ulimits:
+      nofile:
+        soft: 100000
+        hard: 100000
+    # Pass the tuning values documented in .env.example to postgres. The
+    # fallbacks are the postgres:18 stock defaults, so nothing changes when
+    # the variables are not set.
+    command: >
+      postgres
+      -c max_connections=${POSTGRES_MAX_CONNECTIONS:-100}
+      -c shared_buffers=${POSTGRES_SHARED_BUFFERS:-128MB}
+      -c effective_cache_size=${POSTGRES_EFFECTIVE_CACHE_SIZE:-4GB}
+      -c maintenance_work_mem=${POSTGRES_MAINTENANCE_WORK_MEM:-64MB}
+    volumes:
+      - postgres_data:/var/lib/postgresql/data
+    environment:
+      # postgres:18-alpine 默认 PGDATA=/var/lib/postgresql/18/docker（位于镜像声明的匿名卷 /var/lib/postgresql 内）。
+      # 若不显式设置 PGDATA，则即使挂载了 postgres_data 到 /var/lib/postgresql/data，数据也不会落盘到该命名卷，
+      # docker compose down/up 后会触发 initdb 重新初始化，导致用户/密码等数据丢失。
+      - PGDATA=/var/lib/postgresql/data
+      - POSTGRES_USER=${POSTGRES_USER:-sub2api}
+      - POSTGRES_PASSWORD=${POSTGRES_PASSWORD:?POSTGRES_PASSWORD is required}
+      - POSTGRES_DB=${POSTGRES_DB:-sub2api}
+      - TZ=${TZ:-Asia/Shanghai}
+    networks:
+      - sub2api-network
+    healthcheck:
+      test:
+        [
+          "CMD-SHELL",
+          "pg_isready -U ${POSTGRES_USER:-sub2api} -d ${POSTGRES_DB:-sub2api} && psql -U ${POSTGRES_USER:-sub2api} -d ${POSTGRES_DB:-sub2api} -Atqc 'SELECT 1' >/dev/null",
+        ]
+      interval: 10s
+      timeout: 5s
+      retries: 18
+      start_period: 60s
+    # 注意：不暴露端口到宿主机，应用通过内部网络连接
+    # 如需调试，可临时添加：ports: ["127.0.0.1:5433:5432"]
+
+  # ===========================================================================
+  # Redis Cache
+  # ===========================================================================
+  redis:
+    image: redis:8-alpine
+    container_name: sub2api-redis
+    restart: unless-stopped
+    ulimits:
+      nofile:
+        soft: 100000
+        hard: 100000
+    volumes:
+      - redis_data:/data
+    command:
+      - redis-server
+      - --save
+      - "60"
+      - "1"
+      - --appendonly
+      - "yes"
+      - --appendfsync
+      - everysec
+      - --requirepass
+      - ${REDIS_PASSWORD:-}
+    environment:
+      - TZ=${TZ:-Asia/Shanghai}
+      # REDISCLI_AUTH is used by redis-cli for authentication (safer than -a flag)
+      - REDISCLI_AUTH=${REDIS_PASSWORD:-}
+    networks:
+      - sub2api-network
+    healthcheck:
+      test: ["CMD", "redis-cli", "ping"]
+      interval: 10s
+      timeout: 5s
+      retries: 5
+      start_period: 5s
+    # 注意：不暴露端口到宿主机，应用通过内部网络连接
+    # 如需调试，可临时添加：ports: ["127.0.0.1:6379:6379"]
+# =============================================================================
+# Volumes
+# =============================================================================
+volumes:
+  sub2api_data:
+    driver: local
+  postgres_data:
+    driver: local
+  redis_data:
+    driver: local
+
+# =============================================================================
+# Networks
+# =============================================================================
+networks:
+  sub2api-network:
+    driver: bridge
diff --git a/docker-deploy.sh b/docker-deploy.sh
new file mode 100644
index 0000000..97e8e8e
--- /dev/null
+++ b/docker-deploy.sh
@@ -0,0 +1,184 @@
+#!/bin/bash
+# =============================================================================
+# Sub2API Docker Deployment Preparation Script
+# =============================================================================
+# This script prepares deployment files for Sub2API:
+#   - Downloads docker-compose.local.yml and .env.example
+#   - Generates secure secrets (JWT_SECRET, TOTP_ENCRYPTION_KEY, POSTGRES_PASSWORD)
+#   - Generates a random admin login email (ADMIN_EMAIL)
+#   - Creates necessary data directories
+#
+# After running this script, you can start services with:
+#   docker-compose up -d
+# =============================================================================
+
+set -e
+
+# Colors for output
+RED='\033[0;31m'
+GREEN='\033[0;32m'
+YELLOW='\033[1;33m'
+BLUE='\033[0;34m'
+NC='\033[0m' # No Color
+
+# GitHub raw content base URL
+GITHUB_RAW_URL="https://raw.githubusercontent.com/Wei-Shaw/sub2api/main/deploy"
+
+# Print colored message
+print_info() {
+    echo -e "${BLUE}[INFO]${NC} $1"
+}
+
+print_success() {
+    echo -e "${GREEN}[SUCCESS]${NC} $1"
+}
+
+print_warning() {
+    echo -e "${YELLOW}[WARNING]${NC} $1"
+}
+
+print_error() {
+    echo -e "${RED}[ERROR]${NC} $1"
+}
+
+# Generate random secret
+generate_secret() {
+    openssl rand -hex 32
+}
+
+# Generate a random admin login email so new installs never use a guessable default
+generate_admin_email() {
+    local suffix
+    suffix=$(openssl rand -hex 6) || return 1
+    [ -n "$suffix" ] || return 1
+    echo "admin-${suffix}@sub2api.local"
+}
+
+# Check if command exists
+command_exists() {
+    command -v "$1" >/dev/null 2>&1
+}
+
+# Main installation function
+main() {
+    echo ""
+    echo "=========================================="
+    echo "  Sub2API Deployment Preparation"
+    echo "=========================================="
+    echo ""
+
+    # Check if openssl is available
+    if ! command_exists openssl; then
+        print_error "openssl is not installed. Please install openssl first."
+        exit 1
+    fi
+
+    # Check if deployment already exists
+    if [ -f "docker-compose.yml" ] && [ -f ".env" ]; then
+        print_warning "Deployment files already exist in current directory."
+        read -p "Overwrite existing files? (y/N): " -r
+        echo
+        if [[ ! $REPLY =~ ^[Yy]$ ]]; then
+            print_info "Cancelled."
+            exit 0
+        fi
+    fi
+
+    # Download docker-compose.local.yml and save as docker-compose.yml
+    print_info "Downloading docker-compose.yml..."
+    if command_exists curl; then
+        curl -sSL "${GITHUB_RAW_URL}/docker-compose.local.yml" -o docker-compose.yml
+    elif command_exists wget; then
+        wget -q "${GITHUB_RAW_URL}/docker-compose.local.yml" -O docker-compose.yml
+    else
+        print_error "Neither curl nor wget is installed. Please install one of them."
+        exit 1
+    fi
+    print_success "Downloaded docker-compose.yml"
+
+    # Download .env.example
+    print_info "Downloading .env.example..."
+    if command_exists curl; then
+        curl -sSL "${GITHUB_RAW_URL}/.env.example" -o .env.example
+    else
+        wget -q "${GITHUB_RAW_URL}/.env.example" -O .env.example
+    fi
+    print_success "Downloaded .env.example"
+
+    # Generate .env file with auto-generated secrets
+    print_info "Generating secure secrets..."
+    echo ""
+
+    # Generate secrets
+    JWT_SECRET=$(generate_secret)
+    TOTP_ENCRYPTION_KEY=$(generate_secret)
+    POSTGRES_PASSWORD=$(generate_secret)
+    ADMIN_EMAIL=$(generate_admin_email)
+
+    # Create .env from .env.example
+    cp .env.example .env
+
+    # Update .env with generated secrets (cross-platform compatible)
+    if sed --version >/dev/null 2>&1; then
+        # GNU sed (Linux)
+        sed -i "s/^JWT_SECRET=.*/JWT_SECRET=${JWT_SECRET}/" .env
+        sed -i "s/^TOTP_ENCRYPTION_KEY=.*/TOTP_ENCRYPTION_KEY=${TOTP_ENCRYPTION_KEY}/" .env
+        sed -i "s/^POSTGRES_PASSWORD=.*/POSTGRES_PASSWORD=${POSTGRES_PASSWORD}/" .env
+        sed -i "s/^ADMIN_EMAIL=.*/ADMIN_EMAIL=${ADMIN_EMAIL}/" .env
+    else
+        # BSD sed (macOS)
+        sed -i '' "s/^JWT_SECRET=.*/JWT_SECRET=${JWT_SECRET}/" .env
+        sed -i '' "s/^TOTP_ENCRYPTION_KEY=.*/TOTP_ENCRYPTION_KEY=${TOTP_ENCRYPTION_KEY}/" .env
+        sed -i '' "s/^POSTGRES_PASSWORD=.*/POSTGRES_PASSWORD=${POSTGRES_PASSWORD}/" .env
+        sed -i '' "s/^ADMIN_EMAIL=.*/ADMIN_EMAIL=${ADMIN_EMAIL}/" .env
+    fi
+
+    # Create data directories
+    print_info "Creating data directories..."
+    mkdir -p data postgres_data redis_data
+    print_success "Created data directories"
+
+    # Set secure permissions for .env file (readable/writable only by owner)
+    chmod 600 .env
+    echo ""
+
+    # Display completion message
+    echo "=========================================="
+    echo "  Preparation Complete!"
+    echo "=========================================="
+    echo ""
+    echo "Generated secure credentials:"
+    echo "  POSTGRES_PASSWORD:     ${POSTGRES_PASSWORD}"
+    echo "  JWT_SECRET:            ${JWT_SECRET}"
+    echo "  TOTP_ENCRYPTION_KEY:   ${TOTP_ENCRYPTION_KEY}"
+    echo "  ADMIN_EMAIL:           ${ADMIN_EMAIL}  (admin login username)"
+    echo ""
+    print_warning "These credentials have been saved to .env file."
+    print_warning "Please keep them secure and do not share publicly!"
+    echo ""
+    echo "Directory structure:"
+    echo "  docker-compose.yml        - Docker Compose configuration"
+    echo "  .env                      - Environment variables (generated secrets)"
+    echo "  .env.example              - Example template (for reference)"
+    echo "  data/                     - Application data (will be created on first run)"
+    echo "  postgres_data/            - PostgreSQL data"
+    echo "  redis_data/               - Redis data"
+    echo ""
+    echo "Next steps:"
+    echo "  1. (Optional) Edit .env to customize configuration"
+    echo "  2. Start services:"
+    echo "     docker-compose up -d"
+    echo ""
+    echo "  3. View logs:"
+    echo "     docker-compose logs -f sub2api"
+    echo ""
+    echo "  4. Access Web UI:"
+    echo "     http://localhost:8080"
+    echo ""
+    print_info "If admin password is not set in .env, it will be auto-generated."
+    print_info "Check logs for the generated admin password on first startup."
+    echo ""
+}
+
+# Run main function
+main "$@"
diff --git a/docker-entrypoint.sh b/docker-entrypoint.sh
new file mode 100644
index 0000000..47ab6bf
--- /dev/null
+++ b/docker-entrypoint.sh
@@ -0,0 +1,23 @@
+#!/bin/sh
+set -e
+
+# Fix data directory permissions when running as root.
+# Docker named volumes / host bind-mounts may be owned by root,
+# preventing the non-root sub2api user from writing files.
+if [ "$(id -u)" = "0" ]; then
+    mkdir -p /app/data
+    # Use || true to avoid failure on read-only mounted files (e.g. config.yaml:ro)
+    chown -R sub2api:sub2api /app/data 2>/dev/null || true
+    # Re-invoke this script as sub2api so the flag-detection below
+    # also runs under the correct user.
+    exec su-exec sub2api "$0" "$@"
+fi
+
+# Compatibility: if the first arg looks like a flag (e.g. --help),
+# prepend the default binary so it behaves the same as the old
+# ENTRYPOINT ["/app/sub2api"] style.
+if [ "${1#-}" != "$1" ]; then
+    set -- /app/sub2api "$@"
+fi
+
+exec "$@"
diff --git a/handoff_record.md b/handoff_record.md
new file mode 100644
index 0000000..aaf2cc8
--- /dev/null
+++ b/handoff_record.md
@@ -0,0 +1,383 @@
+# sub2api（StarNexus）配置与操作交接记录
+
+- 记录日期：2026-10-10（最后更新：2026-10-11 11:15 北京时间，完成《修复复查 10:13 版》整改与自动同步）
+- 服务器：`ssa`（RackNerd，192.3.41.32，Ubuntu 24.04，宝塔面板，时区 UTC，1C/2GB）
+- 项目目录：`/opt/sub2api`（二进制 + `config.yaml`，systemd 服务 `sub2api`，监听 127.0.0.1:8080）
+- sub2api 版本：0.2.15（commit f2669c8，源码 `github.com/Wei-Shaw/sub2api` 可获取）
+- 对外域名：`apiacc.itssx.com`（经 Cloudflare，推荐）、`api.itssx.com`（直连）
+- 上游：Nexus 8 号车（`https://nexus.itssx.com`，合作商身份）
+- 本文件不含任何密钥原文，只记录存放位置。
+
+---
+
+## 目录与一体化管理（2026-10-11 整合）
+
+- **项目根目录 `/opt/sub2api`**（root 所有，755）：`sub2api` 主程序、`config.yaml`、`data/`（这三项属 sub2api 用户，主程序只写 data/）、`ops/` 运维程序与配置（root 所有）、`relay/` Key 查询页（前端 dist/src、后端 server/key_query.py，root 所有，管理并入根目录 run）、`run` 一体化管理脚本、`handoff_record.md`。
+- 2026-10-11 16:44 清理：旧链接 `/opt/sub2api-ops`、`/opt/sub2api/relay-web`，旧副本 `/opt/sub2api-ops.bak/`，ops 下 `*.bak.20261011`、过期的 `ops/key_query.py`，`relay/run.orig`，`config.yaml.bak.20261010072103` 已移到 `/root/backup/opt-cleanup-20261011084433/`（可找回），`__pycache__` 已删除。`/opt` 下现只有 `sub2api/` 与 Docker 的 `containerd/`。
+- 同时修复：relay 搬入 `/opt/sub2api/relay` 后 nginx 仍指向不存在的 `/opt/sub2api-relay/dist`，Key 查询页 500；已改 `relay.itssx.com.conf` 与 `extension/*/sub2api-relay-web.conf`（原文件备份在 `/root/backup/`），三个入口恢复 200。
+- **权限要求**：root 会执行 `ops/`、`run`、`relay/run`，这些及上级目录不得属 sub2api 用户（否则 sub2api 程序被攻破即可提权）。代价：sub2api 后台「在线更新」无法在根目录写新文件，升级请以 root 操作。
+- **`/opt/sub2api/run`（项目唯一入口，需 root）**：不带参数进菜单，按数字键立即执行：1 重启 sub2api（含分组路由、统一路由）、2 重启 relay 及相关服务（按需构建前端、重启 key-query、nginx -t 后重载、检查两个域名 /relay/key）、3 一起启动、4 更新 sub2api（GitHub `Wei-Shaw/sub2api` 最新版，`checksums.txt` 校验 → 文件入库 + 数据库本机备份 + 旧程序存 `/root/backup/sub2api-bin/` → 替换重启 → 60 秒未就绪自动回滚）、5 同步 Nexus 数据。命令行：`restart-sub2api`、`restart-relay`、`start`、`update [--check]`、`sync`、`status`、`backup {all|files|db|r2|list|restore-files|check}`、`report`、`logs`。relay 自己的 run 已移除（移至 `/root/backup/opt-cleanup-20261011084433/`）。2026-10-11 实测：菜单、检查更新、重启 relay（两域名 200）、重启 sub2api（6 秒）、同步均正常；「更新」的安装路径因已是最新版 v0.2.15 未实际执行。
+- **文件入库**：`ops/snapshot_files.py` 按 `ops/snapshot_paths.json` 把配置、运维程序、relay、nginx 配置、前端覆盖、systemd 单元、凭据文件、宝塔计划任务定义（虚拟文件 bt-panel/crontab.json）存入 `s2a_ops.file_snapshots`（当前版）与 `file_snapshot_history`（变化时留历史，每文件 30 版）。宝塔任务 #11 每天北京 01:00 执行，随后 02:00 的数据库备份即包含全部文件。还原：`run backup restore-files [目录]`（只写到指定目录，不覆盖现有文件）；2026-10-11 实测 77 个文件逐字节一致。
+- `run backup all`：文件入库 → 本机数据库备份（`/www/backup/database/pgsql/sub2api`，保留 14 份）→ 上传 R2 `sub2api/manual/` + config.yaml 备份。
+
+## 0. 当前状态一览
+
+| 维度                | 状态                                                                                                                                |
+| ------------------- | ----------------------------------------------------------------------------------------------------------------------------------- |
+| 配置与 Nexus 一致性 | `config-audit.sh` 511 项，仅 grok/grok45 Nexus 新增 3 个 `grok-imagine-image*` 画图模型未同步（按要求暂不处理画图）；其余 0 问题    |
+| 计费与 Nexus 一致性 | Claude / OpenAI Chat / Codex 协议全部一致（含缓存读写、长上下文阶梯、flex、priority、联网搜索、别名映射、按张生图）；例外见第 12 节 |
+| 一个 Key 用全部分组 | 75 条路径，安全测试全部通过                                                                                                         |
+| 真实客户端          | Claude Code 13 组通过、Codex CLI 12 组通过                                                                                          |
+| 服务                | sub2api、route-auth、nginx、PostgreSQL、Redis 正常；近 1 小时无错误；证书到 2027-01-07                                              |
+| 监控与备份          | 5 个渠道监控（30 分钟）、邮件告警收件人已配置；数据库备份恢复演练通过，每天 03:00 自动演练                                          |
+
+## 1. 总体架构
+
+```
+用户 ──HTTPS──▶ Cloudflare(apiacc) / 直连(api) ──▶ nginx(宝塔)
+   ├─ /api/<分组路径>/...  ─▶ auth_request 127.0.0.1:8091(route-auth) 换成该用户的分组 Key ─▶ sub2api
+   ├─ /v1/... /v1beta/...  ─▶ sub2api（用户 Key 绑定的分组）
+   └─ 其余（前端/管理接口） ─▶ sub2api
+sub2api ──公网 HTTPS（池模式直连，无代理）──▶ Nexus 主线路 nexus.itssx.com（23.254.221.220）
+```
+
+- 一个 Key 用全部分组：URL 前缀 `/api/<分组路径>/` 选分组，与 Nexus 官网路径一致；余额按用户结算、所有分组共用。
+- 一个分组支持多协议：15 个分组均为 **composite（组合）平台**，按接口把请求分给 anthropic / openai / gemini 账号，协议转换与模型别名映射由 Nexus 原生完成。
+
+## 2. 分组、倍率、账号与协议
+
+售价倍率 = Nexus「默认分组」；账号（成本）倍率 = Nexus「合作商」。售价 = 单价 × 分组倍率；成本 = 单价 × 账号倍率。
+
+| sub2api 分组          | Nexus 路径                     | 售价 | 成本 | 启用账号（id:平台）              | 开放协议                             | 渠道                  |
+| --------------------- | ------------------------------ | ---- | ---- | -------------------------------- | ------------------------------------ | --------------------- |
+| #3 codex_eco          | `codex_eco`                    | 1.28 | 1    | 1:openai 20:anthropic            | Claude/Chat/Codex                    | #1                    |
+| #4 codex              | `codex/codex`                  | 1.28 | 1    | 3:openai 23:anthropic            | Claude/Chat/Codex + 生图             | #2                    |
+| #5 codex_pro          | `codex/codex_pro`              | 1.28 | 1    | 4:openai 24:anthropic            | Claude/Chat/Codex + 生图             | #3                    |
+| #6 codex_sp           | `codex_sp`                     | 1.28 | 1.28 | 5:openai 26:anthropic            | Claude/Chat/Codex                    | #4                    |
+| #7 grok               | `grok`                         | 1.28 | 1    | 6:openai 29:anthropic            | Claude/Chat/Codex                    | #5                    |
+| #8 grok45             | `grok45`                       | 1.28 | 1    | 7:openai 31:anthropic            | Claude/Chat/Codex                    | #6                    |
+| #9 混合渠道cc_pro_max | `claude_code/mixed_cc_pro_max` | 2.98 | 2.68 | 8:anthropic 32:openai            | Claude/Chat/Codex                    | #7                    |
+| #10 kiro              | `kiro`                         | 2.98 | 2.68 | 9:anthropic 34:openai            | Claude/Chat/Codex                    | #8                    |
+| #11 office3_2         | `claude_code/office3_2`        | 4.98 | 4.68 | 10:anthropic                     | 仅 Claude Code 客户端                | #9                    |
+| #12 glm               | `claude_code/cc_glm`           | 2.98 | 2.98 | 11:anthropic 36:openai 37:gemini | 全部 4 种                            | #10                   |
+| #13 glm_global        | `claude_code/cc_glm_global`    | 2.98 | 2.98 | 12:anthropic 38:openai 39:gemini | 全部 4 种                            | #11                   |
+| #14 deepseek          | `deepseek`                     | 4.2  | 4.2  | 13:anthropic 40:openai 41:gemini | 全部 4 种（峰谷 ×2）                 | #12                   |
+| #15 cc_codex_56       | `cc_codex_56`                  | 1.28 | 1    | 14:anthropic                     | Claude（Chat 由 sub2api 转换也可用） | #13                   |
+| #16 gemini            | `gemini_1`                     | 3.3  | 2.98 | 15:gemini 42:openai 43:anthropic | 全部 4 种（Claude Code 见第 12 节）  | #14                   |
+| #17 codex画图         | `codex_image`                  | 1    | 1    | 16:openai                        | 图片接口                             | #15（无条目，按张价） |
+
+- 已停用的 gemini 账号（关闭 Gemini 协议，见第 3 节）：21、22、25、27、28、30、33、35。
+- 所有上游账号：apikey、base_url = `https://nexus.itssx.com/api/<Nexus 路径>`、**池模式开启**、anthropic 账号开启自动透传。
+- **上游倍率探测与同步全部关闭**（2026-10-11）：Nexus 对探测一律声明 1 倍，与实扣（合作商档）不符；若开启同步会把成本倍率错改为 1、利润虚高。同步脚本新建/更新账号均强制关闭。
+- 倍率修改位置：售价 = **自动跟随 Nexus 普通（默认分组）倍率**（2026-10-11 12:40 起，后台手改会在下个整点被同步改回）；单个用户特价 = 「分组管理 → 该分组 → 专属倍率」（覆盖分组倍率，目前 0 条）；成本 = 账号倍率，由同步按 Nexus 合作商档维护，勿手改。
+- 账号白名单 = Nexus 该分组在对应协议下的模型（原生 + 别名，原名透传，由 Nexus 映射）。
+- 分组开关：全部 `long_context_pricing_enabled=true`；codex/codex_pro/codex画图 `allow_image_generation=true`；office3_2 `claude_code_only=true`。
+- Kimi、minimax_global 在 Nexus 已禁用，未接入。
+
+| 协议                  | 接口后缀                                                  | 走的账号  |
+| --------------------- | --------------------------------------------------------- | --------- |
+| Claude（Claude Code） | `/v1/messages`、`/v1/messages/count_tokens`               | anthropic |
+| OpenAI Chat           | `/v1/chat/completions`                                    | openai    |
+| Codex / Responses     | `/v1/responses`                                           | openai    |
+| Gemini（Gemini CLI）  | `/v1beta/models/<模型>:generateContent` 等                | gemini    |
+| 图片                  | `/v1/images/...`，或 Responses 的 `image_generation` 工具 | openai    |
+
+## 3. 定价与计费
+
+- 每个分组一个渠道（`Nexus-<slug>`，#1–#15），按平台分别定价，`apply_pricing_to_account_stats` 开启。
+- 单价照搬 Nexus 模型定价（`/api-go/relay/model-pricing`）：输入/输出/缓存读/缓存写 5m/1h、长上下文阶梯、fast（priority）/flex 倍率。
+- **别名按实际执行模型计价**（Nexus 按映射后的模型扣费，已实测）：如 glm 分组的 `claude-opus-4-8` 按 `glm-5.3` 计价。
+- deepseek：峰谷 ×2，北京时间 09:00–12:00、14:00–18:00，**含周末**（来自 Nexus `peakPricing`）。
+- 生图按张：codex、codex画图 1K/2K/4K = $0.5/0.6/0.8；codex_pro = $0.25/0.3/0.4。**生图模型不建渠道条目**（否则 sub2api 改走 token 计费）。
+
+### 2026-10-10 计费修复记录
+
+| 问题                                                           | 影响                      | 修复                                             | 复测                                               |
+| -------------------------------------------------------------- | ------------------------- | ------------------------------------------------ | -------------------------------------------------- |
+| 分组 `long_context_pricing_enabled` 默认关闭，渠道阶梯价不生效 | 长上下文少收约 5 倍       | 全部开启，写入同步脚本                           | office3_2 haiku-5-5 24 万 token：$0.152527 = Nexus |
+| codex画图渠道给 gpt-image 配了 token 价                        | 每张少收约 9.5 倍         | 生图模型不建渠道条目                             | $0.500000 vs Nexus $0.50009                        |
+| codex/codex_pro 未开图片生成                                   | 生图 403                  | `allow_image_generation` 随 Nexus `imagePricing` | 生图成功并按张计费                                 |
+| 别名按请求模型计价、白名单混入其他协议模型                     | 多收/少收数倍             | 每分组独立渠道、按协议取白名单                   | 全量对账一致                                       |
+| 8 个分组 Gemini 协议用量由 Nexus 报错                          | 多收 1.9–4.2 倍或少收 38% | **关闭这 8 个分组的 Gemini 协议**                | 关闭后无不一致记录                                 |
+
+### 计费验证（真实请求对账，`billing_audit.py`）
+
+- 一致：Claude / Chat / Codex 全部请求；场景覆盖缓存读、缓存写 5m（上游未返回 1h 缓存）、长上下文阶梯、flex 半价、priority（上游按 default 处理，两边同价）、Claude 与 Responses 联网搜索（Nexus 搜索费为 0）、别名映射、office3_2、kiro（Nexus 不计输入 token，两边一致）、Gemini 协议（glm/glm_global/deepseek/gemini）。
+- deepseek 峰谷（2026-10-11 09:30 高峰时段自动实测）：`deepseek-v4-flash` sub2api 原价 0.00021 = Nexus 0.00021；别名 `claude-haiku-4-5`→`deepseek-flash` 0.000273 = Nexus 0.000273，**一致**。
+
+## 4. 一个 Key 用全部分组（路径路由）
+
+- 鉴权服务：`/opt/sub2api/ops/route_auth.py`，宝塔计划任务守护（见 4.2 节，127.0.0.1:8091，以 sub2api 用户运行）。
+  - Key 来源：`Authorization: Bearer` / `x-api-key` / `x-goog-api-key` / `?key=`；格式只约束 `[A-Za-z0-9._-]{8,128}`（兼容自定义 Key），查库一律 psql 变量绑定。
+  - **以原 Key 为授权与预算主体**（2026-10-11 重写）：① 原 Key 未删除、active、未过期，用户 active；② 原 Key 的 IP 白/黑名单（nginx 传真实 IP `X-Client-IP`）；③ 目标分组 active，专属分组须在用户授权列表；④ 「原 Key + 其全部映射 Key」合计用量对比原 Key 的总额度与 5h/1d/7d 限额（不缓存）；⑤ 返回**该原 Key** 在目标分组的映射 Key，名称 `[路由] <slug> ←#<原 Key id>`，在 `pg_advisory_xact_lock` 事务锁内创建，有效期与原 Key 同步；映射 Key 被管理员禁用则拒绝。
+  - 缓存：原 Key 10s、映射 Key 30s。拒绝统一以 `403 + X-Route-Reason` 返回，nginx 映射为：notfound→404、quota→429、ip→403、group/key_disabled→403、unavailable（数据库异常，拒绝而非放行）→503；无效 Key→401。
+  - 旧版按「用户+分组」共用的 15 个 `[路由] <slug>` Key 已停用（保留审计记录）。
+  - **v3（2026-10-11 第二次复查后）**：父子关系存独立表 `s2a_ops.route_keys`（不再靠名称识别；旧映射 Key 已迁入）；目标分组授权与主服务 `CanBindGroup` 一致（含用户「限制公开分组」，仅开放标准分组）；合计额度含已删除的映射 Key，5h/1d/7d 改为按使用日志滚动窗口统一计算；映射 Key 本身由主服务强制约束——IP 白名单仅 `127.0.0.2`（nginx 路由入口转发时 `X-Forwarded-For: "$remote_addr, 127.0.0.2"`），有效期、总额度、5h/1d/7d 限额与原 Key 同步，**直接拿映射 Key 调 `/v1` 会被主服务以 IP 拒绝**；映射 Key 不能再作为原 Key 使用。代价：经路由请求在使用日志中的 IP 显示为 127.0.0.2（真实 IP 由路由鉴权按原 Key 名单校验）。主服务 Key 鉴权缓存最长 5 分钟，已有映射 Key 的约束变更最多 5 分钟后生效。额度为「请求前检查、结算后累计」，与主服务自身 Key 额度相同，并发可能小幅超出，不是预占式。
+  - v3 安全回归（全部通过）：映射 Key 直连 `/v1` → 403；直连并伪造 `X-Forwarded-For/CF-Connecting-IP: 127.0.0.2` → 403；白名单 Key 伪造 `CF-Connecting-IP` → 403；合计额度用尽 → 429；用户开启限制公开分组 → 403；经路由 Chat / Claude / Gemini `?key=` → 200。
+- 路由表：`/opt/sub2api/ops/route_groups.json`（75 条：每个分组 `/api/<slug>`、Nexus 原路径、`/api/{codex,openai,claude_code,gemini}/<slug>`；协议由后缀决定）。
+- nginx：`/www/server/panel/vhost/nginx/extension/{apiacc,api}.itssx.com/sub2api-group-router.conf` + `/www/server/panel/vhost/nginx/sub2api-route-proxy.inc`（关闭缓冲/缓存，超时 3600s，支持流式）。
+- 生成器：`python3 -I /opt/sub2api/ops/gen_router.py`，随后 `nginx -t && nginx -s reload`，并在宝塔执行任务 #10「路由服务重启」。
+- 用户侧：公告「接入地址：一个 Key 用全部分组」（id 1，弹窗，标注各分组开放协议）；「API 密钥」页自定义接入点 10 条（上限 10）。
+- 客户端：Claude Code `ANTHROPIC_BASE_URL=https://apiacc.itssx.com/api/<分组>`；Codex/OpenAI `https://apiacc.itssx.com/api/<分组>/v1`；Gemini CLI `GOOGLE_GEMINI_BASE_URL=https://apiacc.itssx.com/api/<分组>`。
+- 安全测试（全部通过）：无/格式错误/不存在/禁用/过期 Key、所属用户禁用 → 401 JSON；SQL 注入 → 401；未知分组 → 404；外部访问内部鉴权接口 → 404；8091 仅本机监听；sub2api 自身 `/api/v1` 不受影响。v2 新增 15 项：额度用尽/5h 限额→429、IP 白名单外/黑名单→403、专属未授权分组→403、映射 Key 被禁用→403、原 Key 过期→401、自定义格式 Key→200、并发首次请求只建 1 个映射 Key。
+- 功能测试：48 项（12 组 × 4 协议）+ 20 项（5 组 × 4 种协议前缀）全部 200；四种协议流式逐块推送；Claude Code 13 组、Codex CLI 12 组通过。
+- 回退：删除两个 `sub2api-group-router.conf`，`nginx -t && nginx -s reload`；停用宝塔任务 #9 并结束 8091 端口进程。
+
+## 4.0 统一路由（自动匹配，2026-10-11）
+
+- 分组 #19「统一路由（自动匹配）」：排序第一（sort_order 0，其余分组 = Nexus sort + 10）；本身不定价、不绑账号。创建 Key 未选分组时前端默认用它（nginx 覆盖 `/assets/KeysView-yfsfsMmS.js`，原文件 `.orig`，配置 `extension/*/sub2api-keys-default-group.conf`；sub2api 升级后文件名变化即失效）。
+- 请求链路：不带分组路径的 `/v1/…`、`/v1beta/…` → nginx `auth_request /__s2a_auto_check`（route_auth `/check`，按 Key 所属分组返回上游名）→ 绑定 #19 的 Key 走 `upstream s2a_auto`（`auto_proxy.py`，宝塔计划任务守护，127.0.0.1:8093），其他 Key 照旧直连 sub2api；判定异常 `error_page` 回退直连（`@s2a_direct`）。配置：`vhost/nginx/0.s2a_auto_upstream.conf`、`sub2api-auto-select.inc`、`extension/*/sub2api-auto-route.conf`，主配置 `/v1/` 的 proxy_pass 改为 include（备份 `*.conf.bak.20261011065219`）。
+- **设置（宝塔可见）**：配置文件 `/opt/sub2api/ops/auto_route_config.json`（宝塔「文件」可编辑）：`order_mode` = alphabet（默认，按分组名称字母顺序，中文名在后）/ nexus / custom，`prefer_native`（原生模型优先），`sync_group_list_order`（后台分组列表同顺序，统一路由固定第一）。宝塔计划任务 #8「sub2api 统一路由：刷新匹配表」每小时整点执行 `refresh-auto-route.sh`，改配置后点「执行」立即生效，任务日志列出每个模型的候选分组顺序。
+- 2026-10-11 各厂商实测（统一路由 Key）：OpenAI（gpt-5.5/gpt-6-astra/gpt-6.1-sol，OpenAI/Codex/Claude 协议）→ codex；Anthropic（haiku-4-5/sonnet-4-6/opus-4-8/sonnet-5-5，Claude/OpenAI 协议）→ kiro；Google（gemini-3-flash/3.1-pro，Gemini/OpenAI/Claude 协议）→ gemini；xAI（grok-4.5/4.7）→ grok；智谱（glm-5.1/4.7/4.5-air）→ glm，glm-4.5-air 在 glm 返回「不支持该模型」后自动切到 glm_global；DeepSeek（v4-flash/v4-pro，三种协议）→ deepseek。全部 200，按命中分组倍率计费。上游返回「模型不支持」的 400/404 也会换下一个分组。
+- 匹配：按请求协议（/v1/messages → Claude；/v1beta → Gemini；其余 → OpenAI）与模型名，查索引 `/opt/sub2api/ops/auto_route_index.json`（`gen_auto_index.py`，随宝塔任务 #4 每小时刷新）：Nexus 官方顺序，**原生提供该模型的分组优先、别名分组兜底**（`PREFER_NATIVE`）。逐个经 route_auth `/auth` 取该分组子 Key 后转发 sub2api；返回 403/429/5xx/529 换下一个分组；原 Key 的额度/IP/无效 Key 直接返回。响应头 `X-S2A-Routed-Group` 标注命中分组。`GET /v1/models`、`/v1beta/models` 返回全部可用模型。
+- 计费：在命中的真实分组按其倍率扣费（实测 codex_eco ×1.28、混合 ×2.98、deepseek ×4.2、gemini ×3.3）。
+- 限制：不支持 WebSocket（返回 400 提示改用 HTTP 或分组地址）；某分组被 Nexus 限流时 sub2api 内部会等待重试（实测 glm 约 2.5 分钟后才返回 429），之后才切换下一个分组。
+- 回退：删除 `extension/*/sub2api-auto-route.conf`、`sub2api-keys-default-group.conf`，主配置 `/v1/` 恢复 `proxy_pass http://sub2api;`（或用备份），`nginx -t && nginx -s reload`；在宝塔停用任务 #9 后执行 `svc-watchdog.sh` 停止（或 kill 8093 端口进程）。
+
+## 4.2 路由服务运行方式（全部在宝塔管理，2026-10-11）
+
+- 两个常驻程序：`route_auth.py`（分组路由鉴权 8091）、`auto_proxy.py`（统一路由 8093），以 `sub2api` 用户运行，日志 `/var/log/sub2api-ops/{route_auth,auto_proxy,watchdog}.log`。
+- 宝塔计划任务 #9「sub2api 路由服务守护」每分钟执行 `svc-watchdog.sh ensure`：确保常驻守护循环在运行（flock 单实例），守护循环每 3 秒检查端口，未监听即重启（实测强杀后 2 秒恢复）；重启服务器后最迟 1 分钟恢复。
+- 注意：批量修改宝塔计划任务时面板每次都会重启 cron，过快会触发 systemd 启动频率限制使 cron 进入 failed（2026-10-11 16:30 发生过，已手动恢复）；守护脚本重启服务前会先 `systemctl reset-failed`。
+- **全服务自检（2026-10-11 16:03 起）**：同一守护循环每 30 秒检查 nginx（HTTP 响应）、sub2api（/health）、PostgreSQL（pg_isready）、Redis（PING）、sub2api-key-query（8092 端口）、cron、宝塔面板（bt status），连续 3 次失败按各自方式重启（init.d 或 systemctl）并邮件通知（同一服务每小时最多一封）；两个路由程序每 3 秒做 HTTP 健康检查（`/check`、`/__health`），卡死连续 3 次即杀掉重启。实测：强杀统一路由 2 秒恢复；停掉 key-query 约 90 秒被守护重启恢复；cron 被宝塔自身约 20 秒拉起。`svc-watchdog.sh status` 一次看全部状态。
+- 开机自启：sub2api、sub2api-key-query、cron（systemd enabled）；nginx、pgsql、redis（宝塔 rc 启动脚本）；**宝塔面板 2026-10-11 补设开机自启**（`systemctl enable bt`，原先未设置）；两个路由程序与守护循环由任务 #9 在开机后 1 分钟内启动。
+- 注意：守护脚本开启 pipefail，判断不能用 `命令 | grep -q`（会因 SIGPIPE 误判，曾导致 16:02 误重启宝塔面板一次并发出误报邮件）。
+- 宝塔计划任务 #10「sub2api 路由服务重启」：改程序后点「执行」；每月 1 日北京 05:00 例行重启。`svc-watchdog.sh status` 查看状态。
+- 原 systemd 单元 `sub2api-route-auth`、`sub2api-auto-proxy` 已 disable 并停止（单元文件保留在 `/etc/systemd/system/`，未删除）；不要重新启用，否则会与守护任务抢端口。
+- 宝塔中可见位置：「计划任务」#4–#10；「网站 → api.itssx.com / apiacc.itssx.com → 设置 → 配置文件」中 `/v1/` 的 include；「文件」`/www/server/panel/vhost/nginx/extension/<站点>/sub2api-*.conf`、`/www/server/panel/vhost/nginx/sub2api-*.inc`、`0.s2a_auto_upstream.conf`、`0.sub2api_upstream.conf`；配置与脚本 `/opt/sub2api/ops/`。
+- `sub2api` 主程序本身与 `sub2api-key-query`（relay 页面后端，非本次部署）仍为 systemd 服务，未改动。
+
+## 4.1 Nexus「API 文档」额外功能对照（2026-10-10 实测）
+
+Nexus 页面右下角「API 文档」列出 9 个接口，逐一实测结果：
+
+| Nexus 接口                                              | 说明                                        | Nexus 实测                     | 本站现状                                                |
+| ------------------------------------------------------- | ------------------------------------------- | ------------------------------ | ------------------------------------------------------- |
+| `/v1/chat/completions`、`/v1/responses`、`/v1/messages` | 对话                                        | 可用                           | ✅ 已支持（见第 2、4 节）                               |
+| `/v1/responses/compact`                                 | Codex 远程对话压缩                          | 有路由，codex 三组当时上游 529 | ✅ 透传已通（当时同样 503/529），待 Nexus 恢复后实测    |
+| `/v1/embeddings`                                        | 文本向量                                    | Nexus 无 embedding 模型        | 不适用                                                  |
+| `/v1/audio/speech`、`/v1/audio/transcriptions`          | TTS / STT                                   | Nexus 无语音模型               | 不适用                                                  |
+| `/api/common/v1/search`                                 | 独立联网搜索（按 `searchContextCost` 计费） | **501 Web search 未启用**      | 不适用；路由层对 `/api/<分组>/common/...` 返回 JSON 404 |
+| `/api/common/v1/web/fetch`                              | 网页抓取                                    | **501 Web fetch 未启用**       | 同上                                                    |
+| `/relay/video/tasks`                                    | 视频/音乐异步任务                           | 可用分组中无视频模型           | 不适用                                                  |
+
+- 模型内置的联网搜索（Claude `web_search` 工具、Responses `web_search` 工具）已实测可用，计费与 Nexus 一致（Nexus 搜索费为 0）。
+- 独立搜索复核（2026-10-10）：真实地址仅 `/api/common/v1/search`（分组路径写法均 400/404/405）；无 Key 返回 401，带 Key（Bearer 或 x-api-key）返回 **501 Web search 未启用**；指定 tavily/brave/serper/exa/perplexity/minimax、带 billingModel/group 均为 501 → Nexus 全局关闭，非参数或 provider 问题。
+- 若日后 Nexus 开放独立搜索/抓取：sub2api 无对应接口与计费，不能直接转发（会造成用户免费使用）。方案：在路由鉴权层旁加小服务，调用 Nexus 后按其单次价 × 分组倍率从用户余额扣费并记账。
+- 修复：路由层原先把非 `/v1/`、`/v1beta/` 后缀转给 sub2api，会返回前端 HTML（200）；现已改为 JSON 404（`gen_router.py`）。
+- 2026-10-11 10:30 Codex 恢复后复测优先模型（gpt-5.5、gpt-5.6-sol、gpt-6-astra、gpt-6-sol、gpt-6.1-sol）：codex_eco/codex/codex_pro 经 sub2api 对话与流式 15/15 正常，计费对账 37/37 与 Nexus 一致；codex_sp 在 Nexus 现仅开放 gpt-6-astra（正常），其余 4 个 Nexus 也返回 400。对话压缩 `/responses/compact` 直连 Nexus 所有模型仍 529 或 100 秒无响应，属 Nexus 侧未恢复。
+- 对话压缩 2026-10-11 09:30 复测：codex_eco/codex/codex_pro 直连 Nexus 均 529，sub2api 对应 503，Nexus 侧仍不可用，待其恢复后再测。
+
+## 4.3 relay（Key 查询页 /relay/key，2026-10-11 重写）
+
+- 后端 `relay/server/key_query.py`（systemd `sub2api-key-query`，127.0.0.1:8092）：分组信息全部动态生成——名称、倍率、备注、排序、专属/限制来自 groups 表；接入路径来自 `ops/route_groups.json`（统一路由为不带分组的地址）；协议与模型来自 `ops/auto_route_index.json`；生图、仅 Claude Code、峰谷加价来自 groups / channel_model_pricing；按用户计算可用分组（专属、限制公开分组）与专属倍率。Key 查询返回余额、额度、5h/1d/7d 用量、近 7 天按日/按分组/按模型统计、最近 20 条调用、最近使用时间（含路由子 Key）；状态区分额度用完/停用/账户停用/过期/余额不足。每 IP 每分钟 20 次查询。数据库用**只读账号 relay_ro**（凭据 `relay/server/.db.env`，root:sub2api 640），不再用 postgres。
+- 前端 `relay/src/index.html` → `run restart-relay` 每次用 Tailwind v4.3.3 编译到 `relay/dist/`（Node 由宝塔 Node.js 版本管理器安装在 `/www/server/nodejs/v24.21.0`，run 自动查找；`node_modules` 已在服务器重新 `npm install`）。Key 改为请求头传递（不进网址与日志）；动态内容一律 HTML 转义；标题「StarNexus - 余额查询」，新图标（渐变方块四角星，SVG 内联，favicon 同源）；主题按钮在内容区右上角，切换不弹提示；防闪烁脚本与 theme_mode（白天/黑夜/跟随系统）一致；边框统一 1px。
+- **分组数据全部来自数据库**（2026-10-11 18:00 起）：宝塔任务 #8 每小时运行 `gen_auto_index.py`，除生成统一路由匹配表外，同时把 Nexus 的分组标签（`s2a_ops.nexus_tags`：按量、月卡、国产、官方claude、deepseek、grok 及颜色）与每个分组的路径、排序、标签、协议与模型（`s2a_ops.group_meta`，含统一路由）写入数据库；relay 只读这两张表 + groups 等业务表（只读账号 relay_ro 已授权），页面打开时不请求 Nexus、不读文件。
+- 分组筛选：「全部」+ 有分组的 Nexus 标签（带 Nexus 颜色与数量），可点击筛选；卡片显示所属标签。近黑色标签（grok #000000）用中性色显示，深色模式下标签文字调亮。
+- 视觉：深色模式改为深蓝灰（页面 #1c2638、卡片 #243049、内嵌 #1a2333、分隔线 #3a4a68，主题变量 `--color-night-*` 在 `relay/src/input.css`）；卡片、按钮、输入框默认 2px 淡色边框，表格行分隔 1px；悬停（`.hv`，参考 tailwindcss.com：不加阴影、不改粗细）时 2px 边框变主题色并轻微染底色。
+- 线路测速（参考 Nexus）：请求各线路 `/api/common/healthz`（nginx `extension/*/sub2api-healthz.conf` 直接返回 200、允许跨域、no-store），预热 1 次后测 3 次取中位数，<200ms 绿、<500ms 黄、其余红、失败红，最快的标「最快」；页面加载自动测速，不可点击。
+- 2026-10-11 晚调整：Key 输入框 1px 细边框，悬停/聚焦变主题色并带外圈光晕（ring）；查询成功不提示，失败在输入框上方红字显示；查询成功的 Key 存浏览器本地（最多 10 个，完整显示，可逐个移除），聚焦输入框弹出列表；去掉粘贴按钮；图标不可点击、无悬停效果。公告读 sub2api `announcements`（active、在生效期、targeting 为空，最多 3 条，后端 30 秒缓存），Markdown 渲染（先转义，链接仅 http/https），header 右下角「公告」按钮打开全屏居中弹窗（× / 点遮罩 / Esc 关闭）。去除所有「sub2api 实时/互通」标识。余额区合并为一张卡：账户余额标签；已使用/总金额、剩余金额、累计充值（橙色）三列居中（22px）；下排 Key 备注名称、状态、过期时间、最后调用时间（20px）；无单独限额时 已使用=账户累计消费（后端新增 `user_used`）、总金额=已使用+余额，有限额时按 Key 限额、剩余取 min(限额剩余, 余额)；金额千位分隔 `usd()`；去掉滚动窗口卡片与进度条。
+- 修复的历史问题：页面主脚本引用不存在的 `themeToggle` 元素导致初始化中断（测速一直「测速中…」、分组不显示）；`<head>` 图标标签残留使左上角显示 `" />`；nginx 指向已不存在的 `/opt/sub2api-relay/dist` 导致 500。原文件备份 `/root/backup/relay-20261011091424/`。
+
+## 5. 充值与支付
+
+- 支付渠道：易支付（`https://www.ezfp.cn`，商户 6996，MD5），微信 + 支付宝；回调 `https://apiacc.itssx.com/api/v1/payment/webhook/easypay`，返回 `/payment/result`；易支付后台已授权域名。
+- 充值规则（照搬 Nexus 8 号车）：折扣模式，倍率 1，最低 6、最高 1000：
+
+| 到账 | 6      | 15    | 30     | 50     | 100    | 300    | 1000    |
+| ---- | ------ | ----- | ------ | ------ | ------ | ------ | ------- |
+| 折扣 | 50.33% | 54%   | 57%    | 62%    | 63.25% | 68%    | 68%     |
+| 实付 | ¥2.98  | ¥6.90 | ¥12.90 | ¥19.00 | ¥36.75 | ¥96.00 | ¥320.00 |
+
+- 快捷金额按钮：nginx 精确覆盖 `/www/wwwroot/sub2api-overrides/assets/PaymentView-BNDwo4pe.js`（原文件 `.orig`），配置 `extension/*/sub2api-recharge-amounts.conf`；**升级 sub2api 后自动失效**。
+- 充值说明（Markdown 分行带符号）、商品名「StarNexus 充值 … 美元」。
+- 已测：微信、支付宝下单返回付款码/链接，¥2.98 正确（测试订单 #1 FAILED、#2/#3 CANCELLED）。**真实付款到账未验证。**
+- 进价：合作商 10000 刀 ¥2800（¥0.28/刀）；售价 ¥0.32–0.497/刀。
+
+## 6. 站点与安全设置
+
+- 站点 StarNexus；前端地址与 API 地址 `https://apiacc.itssx.com`。
+- 开放注册 + 邮箱验证 + Turnstile（`apiacc`、`api` 均在白名单）；SMTP QQ 邮箱 465 TLS，测试邮件成功；已有新用户注册成功。
+- 管理员已绑定 TOTP；step-up 已开启；管理员 API Key 已删除（运维脚本临时生成、用完即删）。
+- **Key IP 白名单不再信任客户端转发头**（`api_key_acl_trust_forwarded_ip=false`，2026-10-11）：原设置下直连 `api.itssx.com` 可伪造 `CF-Connecting-IP` 绕过 Key 的 IP 白名单；现按 `server.trusted_proxies`（127.0.0.1）可信链取 IP，CF 入口由 nginx realip 还原真实 IP。
+- 邀请返利 5%；新用户默认并发 10、余额 0。
+- `config.yaml` 新增 `totp.encryption_key`（**不可修改或丢失**）。
+
+## 7. 备份
+
+| 内容        | 方式                                                          | 位置 / 计划                                                                                                                                               |
+| ----------- | ------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| 数据库      | sub2api 内置备份 → R2                                         | 桶 `sub2api`，前缀 `sub2api/`；cron `0 2 * * *` = 每天北京时间 02:00；保留 30 天/30 份，每月 1 日归档                                                     |
+| 恢复演练    | `/opt/sub2api/ops/backup-restore-check.sh`（宝塔计划任务 #5） | 每天北京 03:00：要求存在当天定时备份 → R2 下载 → 恢复到临时库 `sub2api_restore_check` → 比对表数/关键表行数 → 删除临时库；日志 `backup_restore_check.log` |
+| config.yaml | `/usr/local/sbin/sub2api-config-backup.sh`（宝塔计划任务 #6） | R2 `sub2api/config/`；每天 04:00；SHA256 回读校验；日志 `/var/log/sub2api-config-backup.log`                                                              |
+| 同步前快照  | `nexus-sync.sh --apply` 自动                                  | `/root/backup/sub2api_before_nexus_sync_*.sql.gz`（每次写入前）                                                                                           |
+
+- **定时任务统一在宝塔「计划任务」管理**（2026-10-11 迁入，`/etc/cron.d` 中已无 sub2api 任务）。面板时间为服务器 UTC：#4 Nexus 对账与自动同步（每小时 :00）、#5 备份恢复演练（UTC 19:00 = 北京 03:00）、#6 config.yaml 备份到 R2（UTC 20:00 = 北京 04:00）、#2 本地备份数据库与配置到 `/www/backup/database/pgsql/sub2api`（UTC 21:00 = 北京 05:00，保留 14 份）。脚本失败时面板日志写「★ 执行失败」而非 Successful。数据库备份到 R2（北京 02:00）由 sub2api 后台「数据管理 → 备份」的计划控制，不在面板中。运维锁等待上限 15 分钟。
+- 依赖：`/usr/local/bin/{pg_dump,psql}` 软链到宝塔 PostgreSQL 18。
+- 2026-10-11 02:30 首次自动演练：定时备份（02:00，scheduled）恢复 0 报错，各表行数与生产一致，通过。
+- 2026-10-11 手动演练：最新备份（10-10 20:42 手动）恢复 0 报错、100 张表齐全，结果通过（该备份早于首条使用日志，故 usage_logs 为 0，属正常）。首次定时备份将在 10-11 02:00 执行，02:30 自动验证。
+- 支付渠道配置为明文 JSON 存储，数据库备份含上游/支付密钥 → R2 桶必须私有。
+
+## 8. 运维脚本（`/opt/sub2api/ops/`）
+
+| 脚本                         | 作用                                                                                                                                                              |
+| ---------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| `lib.sh`                     | 公共函数：`Q`（psql）、`ops_lock`（全局 flock，防并发）、`with_admin_key`（临时管理员 Key，退出时**精确恢复原值或删除**）、导出账号/渠道现状                      |
+| `nexus-sync.sh [--apply]`    | 从 Nexus 实时同步组合分组、账号白名单、路由、渠道定价、分组开关。**预览完全只读**（不建临时 Key，现状由数据库只读导出）；`--apply` 加锁、先 pg_dump、再两阶段写入 |
+| `config-audit.sh`            | 配置对账（业务只读）：逐项比对 Nexus 与 sub2api，含账号并发=50、`restrict_models`、`apply_pricing_to_account_stats`                                               |
+| `backup-restore-check.sh`    | 数据库备份恢复演练（见第 7 节）                                                                                                                                   |
+| `billing_audit.py <起始UTC>` | 计费对账：usage_logs 与 Nexus key-logs 逐条比对原价（需 `NEXUS_KEY`、`PGPASSWORD`）                                                                               |
+| `gen_router.py`              | 生成路径路由映射与 nginx 配置                                                                                                                                     |
+| `route_auth.py`              | 路径路由鉴权服务                                                                                                                                                  |
+| `deepseek-peak-check.sh`     | 一次性峰谷实测（cron `sub2api-deepseek-peak-check`，执行后自删）                                                                                                  |
+
+关键规则（写在 `nexus_sync.py` 中）：
+
+- `GEMINI_BILLING_MISMATCH`：关闭 Gemini 协议的分组集合；Nexus 修复后移除并 `--apply` 即恢复（对应 gemini 账号自动重新启用）。
+- 两阶段：阶段一为全部分组计算目标（白名单、单价、路由），**任一模型 Nexus 无定价则整体中止、不写任何东西**；阶段二才写入。路由按差异增量更新（先加缺的再删多的，不再全删重建）；渠道单次 PUT。
+- 渠道 `restrict_models=true`（白名单外模型直接拒绝，避免无价模型被免费调用）；按张计费的分组（codex画图 #15）为 false，因生图模型故意不建条目。
+- 账号并发统一 50（Nexus 该 Key 不限并发；原 10 易排队）。
+- 分组倍率未纳入同步（Nexus 调倍率需手动改分组倍率与账号倍率）；新增分组需同时改 `nexus_sync.py` 的 `GROUPS` 与 `gen_router.py` 的 `NEXUS_PATHS`。
+- **自动跟随 Nexus**（`nexus-auto-sync.sh`，宝塔计划任务 #4 每小时整点）：对账 → 有差异则 `nexus-sync.sh --apply`（含写前 pg_dump）→ 再对账 → 用站点 SMTP 邮件通知管理员（`notify.py`）。同步范围：分组名称与备注、模型增删、别名、价格/阶梯/峰谷、协议、图片开关与按张单价、成本倍率（=合作商）、**售价倍率（= Nexus 普通/默认分组，变化时邮件列出原价→新价）**。售价过低（现金口径亏损）时报警。保护：任一模型无定价、分组模型数骤减一半以上、Nexus 分组消失 → 整体中止只发邮件；Nexus 新分组只通知（需人工建分组）；同一组无法自动消除的差异只通知一次。日志 `auto_sync.log`。
+- 画图/视频模型：分组在 Nexus 有按张价（imagePricing）才开放并按张计费；否则跳过（Nexus 这类模型 token 价为 0，按 token 计等于免费）。2026-10-11 Nexus 给 grok 开了按张画图（$0.3/0.4/0.5），已自动同步；grok45 无按张价，跳过。
+- `lib.sh` v2：`tmpfile 变量名` 在当前 Shell 登记（修复 `$(tmpfile)` 子 Shell 登记丢失导致快照残留）；`--apply` 先加锁再读现状快照；EXIT/INT/TERM/HUP 统一清理；临时管理员 Key 替换前先把原状态写入持久化记录 `/var/lib/sub2api-ops/admin-key.orig`（目录 700，重启不丢），若被 SIGKILL/宕机重启中断，下次 `ops_lock`（宝塔任务 #4 每小时调用）自动按记录恢复，已用 kill -9 实测恢复哨兵原值。**密钥不进进程命令行**：`Qv`/`route_auth.py` 的参数经 psql 标准输入 `\set` 传入，R2 密钥经 `curl -K <(printf …)` 传入；route-auth 异常日志只记异常类型与 psql 报错首行。旧版脚本备份 `/root/backup/ops-scripts-20261011/`。
+
+## 9. 服务器改动清单与回退
+
+| 改动                 | 路径                                                                                                                 | 回退                                                      |
+| -------------------- | -------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------- |
+| pg_dump/psql 软链    | `/usr/local/bin/{pg_dump,psql}`                                                                                      | 删除软链（内置备份会失败）                                |
+| config.yaml 加密密钥 | `/opt/sub2api/config.yaml`（备份 `config.yaml.bak.20261010072103`）                                                  | 不建议回退                                                |
+| 充值金额覆盖         | `/www/wwwroot/sub2api-overrides/`、`extension/*/sub2api-recharge-amounts.conf`                                       | 删除 conf 并 reload                                       |
+| 路径路由             | `extension/*/sub2api-group-router.conf`、`sub2api-route-proxy.inc`、`/etc/systemd/system/sub2api-route-auth.service` | 见第 4 节                                                 |
+| 备份任务             | `/usr/local/sbin/sub2api-config-backup.sh`、宝塔计划任务 #6、`/root/.config/sub2api-r2.env`                          | 宝塔停用任务                                              |
+| 恢复演练             | `/opt/sub2api/ops/backup-restore-check.sh`、宝塔计划任务 #5                                                          | 宝塔停用任务                                              |
+| 监控告警             | 后台「渠道监控」#1–5、运维告警规则（3/4 停用，新增 3 条）、邮件通知配置                                              | 后台停用对应项                                            |
+| 自动同步             | `/opt/sub2api/ops/nexus-auto-sync.sh`、`notify.py`、宝塔计划任务 #4                                                  | 宝塔停用任务                                              |
+| 映射 Key 父子表      | `s2a_ops.route_keys`（sub2api 库内独立 schema）、设置 `api_key_acl_trust_forwarded_ip=false`                         | 恢复 `/root/backup/ops-scripts-20261011/` 旧脚本          |
+| 运维脚本             | `/opt/sub2api/ops/`、`/root/.config/sub2api-nexus.env`                                                               | —                                                         |
+| 同步写入的数据库变更 | 分组/账号/路由/渠道                                                                                                  | 用 `/root/backup/sub2api_before_nexus_sync_*.sql.gz` 恢复 |
+
+## 10. 敏感信息存放位置（不在本文件中）
+
+| 信息                           | 位置                                                                 |
+| ------------------------------ | -------------------------------------------------------------------- |
+| Nexus key                      | sub2api 账号凭据（数据库）、`/root/.config/sub2api-nexus.env`（600） |
+| R2 访问密钥                    | sub2api 备份设置（加密）、`/root/.config/sub2api-r2.env`（600）      |
+| 易支付 PKey                    | sub2api 支付渠道（数据库明文 JSON）                                  |
+| Turnstile 秘钥、SMTP 授权码    | sub2api 系统设置（数据库）                                           |
+| TOTP 加密密钥、数据库密码、JWT | `/opt/sub2api/config.yaml`（600）                                    |
+
+## 11. 测试数据（可清理）
+
+- 管理员测试 Key `proto-test-*`（id 2–7）及 `[路由] *` Key（管理员名下）。
+- 测试订单 #1–#3；试点分组 #18 及账号 17–19、渠道 #16（已停用）。
+- 管理员测试余额（初始 9999，测试共消耗约 $3）；测试图片 `~/Desktop/ai_000000/codex_image_test*.png`（本机）。
+
+## 12. 已知问题与待办
+
+0. **《配置问题复查 23:28 版》整改结果（2026-10-11）**：
+   - 01/04 路由未保留原 Key 限制、缓存/并发/Key 格式 → 已修复（第 4 节）。
+   - 02 账户成本偏低 → **误报**：`account_stats_cost` 存的是倍率前费用，但后台所有统计 SQL 均按 `COALESCE(account_stats_cost,total_cost) × account_rate_multiplier` 计算（`usage_log_repo_stats.go` 等）；日志 193 后台账户成本 0.012927918 = 复查推算值。若关闭 `apply_pricing_to_account_stats` 反而会退回内置价目表（无别名价），故保持开启。
+     第二次复查仍列为高：已用后台接口 `/admin/dashboard/groups` 实测——glm 分组账户成本 0.073174（=Σ 倍率前费用 0.024555 × 2.98），deepseek 0.223404（=0.053192 × 4.2）；日志 200 账户成本 0.000210 × 4.2 = 0.000882，与复查期望值一致。数据库字段存倍率前值，展示/统计一律乘账号倍率，结论不变。
+   - 03 预览写数据库 → 已修复（预览只读；写入加锁并精确恢复原管理员 Key 设置，已用哨兵值验证）。
+   - 05 同步非原子/无价跳过/restrict_models → 已修复（第 8 节）。Fast/Flex：sub2api 每模型只有一个 fast、一个 flex 倍率；Nexus 对 gpt-5.5 priority（无阶梯 ×2）、gpt-5.4、gpt-5.4-mini、gemini-3.1-pro-preview flex 的分项倍率不完全统一，取主要项，属结构限制，实测影响可忽略。
+   - 06 监控告警 → 已配置：渠道监控 5 个（kiro、glm、codex_eco、deepseek、gemini_1 直连 Nexus，每 30 分钟，用便宜模型；gemini_1 因 Nexus 的 `gemini-3.1-flash-lite-preview` 持续 529，改用 `gemini-3-flash-preview`）；邮件告警收件人为管理员邮箱，最低级别 warning（P0/P1），每小时最多 6 封、60 秒合并，含恢复通知；每日 09:00 日报、错误摘要、账号健康报告；测试邮件与告警邮件均已确认送达。原 P99/P95 延迟规则使用当前版本不支持的指标（永不触发）已停用；新增「上游错误率 >30%」「异常账号 ≥3」「限流账号 ≥5」规则。
+   - 07 共享上游容量 → 经营约束：31 个启用账号共用 1 个 Nexus Key，账号数不等于独立容量；容量以 Nexus 侧为准，已把并发提到 50 并以渠道监控/告警观察。
+   - 未处理（按要求）：使用文档、凭据轮换、余额监控。
+   - **第三次复查（11:09 版）整改**：恢复记录持久化（同上）；密钥不进命令行（同上）；Fast/Flex：sub2api 每模型只有一个 fast/flex 倍率，Nexus 档位价各字段比例或阶梯结构不同时，改为取输入比例并在同步与对账输出中明确列出「ℹ 计费结构限制」（不再静默省略）。当前实际使用的受影响项：gpt-5.5 priority/flex、gemini-3.1-pro-preview flex 仅在超长上下文（> 阶梯阈值）且指定服务档位时与 Nexus 有偏差；实测上游对 priority 请求按 default 处理。跨资源同步非单事务：写前 pg*dump + 写后再对账 + 残留差异邮件，失败按 `/root/backup/sub2api_before_nexus_sync*\*.sql.gz` 恢复。
+   - **第四次复查（11:50 版）整改**：
+     - 账户成本口径：新增「经营日报」邮件（`daily-report.sh`，宝塔任务 #7，每天北京 09:00），逐级列出 基础费用 → 客户扣费 → 上游消耗（本站按合作商倍率）→ **逐笔匹配 Nexus key-logs 的实扣**（同分组、输出 token、原价/输入 token、±10 分钟）→ 采购成本 ¥ → 估算收入 ¥ → 毛利；未匹配的 Nexus 扣费单列为「未匹配的上游消耗」（可能是直接用 Nexus Key 调用，也可能是匹配遗漏）。2026-10-11 实测 48/48 笔与 Nexus 实扣逐笔一致；10-10 的偏差来自当天配置调整期（长上下文关闭、画图按 token、成本倍率调整），属历史数据。
+     - Fast/Flex：整体倍率取输入、输出两个主要字段（含各级阶梯）的最大比例，主要成本不低于 Nexus；次要字段偏差只提示（Nexus 有录入异常，如 codex-auto-review priority 阶梯缓存读 25 倍）；档位阶梯与基础阶梯不对应时阻止自动同步。2026-10-11 12:04 曾因初版规则把异常字段放大成 ×25 而触发一次同步，校验阶段即中止、未写入，并发出一封「同步失败」邮件（误报），已修正。
+     - 亏损告警：改为现金口径（售价倍率 × 客户最低充值单价 < 成本倍率 × 进价 才报亏损），参数在 `/opt/sub2api/ops/business.json`（进价 0.28、最低充值单价 0.32，调价后改这里）。
+   - **经营日报 v2（2026-10-11 12:30）**：资金与利润（当日实收、累计充值、退款、支付通道费、消耗折算收入、上游成本、返利、消耗口径毛利、现金净流入）；分组倍率与当日经营（Nexus 普通/供应商倍率、本站售价/成本——售价高于 Nexus 橙色↑、低于蓝色↓，成本与合作商不符红色≠；大额档毛利率、客户消耗、收入、成本、毛利、测试消耗）；客户明细（脱敏邮箱、注册日、消耗、按实际购买单价折算收入、成本、毛利、当日充值、余额、主要分组）；上游成本逐笔核对；未匹配的上游消耗。摘要含客户总数/活跃/新增、客户余额合计、Nexus 余额（仅显示）。支付通道费率在 business.json 的 pay_channel_fee_percent（默认 0，按易支付实际费率填写）。
+   - **第五次复查（12:20 版）**：Fast/Flex 主要字段基础价为 0 或无可用比例时改为阻止同步；措辞改为「未匹配的上游消耗」；12:25 当前代码自动同步成功（508 项 0 问题），12:04 那次失败为 ×25 规则缺陷导致的校验中止、未写入。档位阶梯少于基础阶梯（如 gpt-5.5 priority 无长上下文阶梯）时按基础阶梯 × 倍率，长上下文 priority 会多收，属已知且接受的偏差。
+   - **2026-10-11 14:20 清理与对齐**：经确认删除测试分组 #18（软删除）、其账号 #17–19（软删除）、渠道 #16，停用测试 Key #7；删除前备份 `/root/backup/sub2api_before_delete_group18_20261011062245.sql.gz`，使用日志保留。分组名称与备注改为跟随 Nexus（备注 = Nexus 公告摘要 noticeSummary，原先描述中暴露的上游地址已去除），纳入自动同步与对账。站内公告 1 增加「创建 Key 时分组随便选，推荐 codex_eco」、更新子 Key 说明、标注 codex/codex_pro/grok 支持生图。创建 Key 必须选分组是 sub2api 前端限制，按决定不覆盖前端。
+   - **运维邮件统一为 HTML 表格**（`notify.py` 渲染，附纯文本版本；`mail_report.py` 组织内容）：自动同步结果（模型变化/成本倍率/账号变化/需人工/提示分表）、Nexus 默认倍率变化提醒（含建议与大额档毛利）、对账失败、恢复演练失败、config 备份失败、经营日报。sub2api 自带的告警邮件与日报为程序内置模板，未改。
+   - **账户成本（三次复查均列为高，结论：误报，不改）**：`account_stats_cost` 字段按设计存倍率前费用，sub2api 所有统计与后台展示一律再乘 `account_rate_multiplier`（源码 `usage_log_repo_stats.go`、`dashboard_aggregation_repo.go`、`usage_log_repo_dashboard.go`）。若把字段改存乘后值会被重复相乘。复核方法：后台 `/admin/dashboard/groups` 的 account_cost 与 `Σ account_stats_cost × account_rate_multiplier` 相等（2026-10-11 实测 glm 0.073174 = 0.024555 × 2.98）；复查表中的「推算上游余额费用」列正是后台显示的账户成本。Nexus 实扣倍率已用 key-logs 的 userCost/rawCost 核实 = 合作商档。
+1. **Responses 生图少收文字 token 费**（未修复）：codex/codex_pro 经 Responses `image_generation` 工具生图时，Nexus = 按张价 + gpt-5.5 文字 token（实测约 $0.018/张），sub2api 只收按张价（代码在有图片时只按张计费，无配置项）。直接图片接口差额约 $0.0001/张。修复需改 sub2api 源码重新编译发布，或接受/略调高图片单价补偿。
+2. **8 个分组关闭了 Gemini 协议**（codex_eco、codex、codex_pro、codex_sp、grok、grok45、混合渠道、kiro）：原因是 Nexus 的 Gemini 格式响应用量与其扣费不一致（缺 `cachedContentTokenCount`，Claude 类少报输出/缓存写）。可向 Nexus 反馈，修复后按第 8 节恢复。
+3. **gemini 分组 + Claude Code 超时**：直连 Nexus 同样超时，属 Nexus 侧问题。
+4. deepseek 峰谷已实测一致（见第 3 节）；对话压缩仍因 Nexus 529 未能实测。
+   4.2 **低流量告警误报**：sub2api 告警规则没有「最少请求数」，流量很低时几次失败就能让错误率/成功率规则触发（2026-10-11 09:32 由压缩测试 3 次 503 触发，已人工标记恢复）；无新请求时事件不会自动恢复。收到 P0/P1 邮件时先看渠道监控是否也报错。
+   4.1 grok 画图已随 Nexus 自动开放（按张计费，见第 8 节）；grok45 无按张价不开放。
+5. **真实付款到账未验证**：付一笔 ¥2.98，核对回调与余额。
+6. **凭据轮换**：R2 密钥、Cloudflare `cfut_` 令牌（未使用，直接删）、易支付 MD5、Nexus key、Turnstile 秘钥曾出现在对话中。更新位置：R2 → 后台备份设置 + `/root/.config/sub2api-r2.env`；Nexus key → `/root/.config/sub2api-nexus.env` + 全部上游账号。
+7. **Cloudflare 浏览器完整性检查**：`apiacc` 拦截 UA 为 `Python-urllib` 的请求（1010）；官方 SDK/requests/Node/Go/curl 正常，`api.itssx.com` 不受影响。
+8. **sub2api 升级注意**：充值按钮覆盖失效；路由鉴权直接读写 `api_keys` 表、组合分组行为需回归；升级前先备份并跑 `config-audit.sh`。
+9. 代理池中有 1 个未使用的代理。
+10. 延迟（ssa → Nexus）：主线路首字节约 100ms（当前使用）；加速线路相近偶有抖动；香港约 720ms；日本不可达。
+
+## 13. 本机（管理端）相关
+
+- `~/.ssh/config` 为 `ssa` 增加自动回退：直连握手失败（Shadowrocket 节点屏蔽出站 22 端口）时经腾讯云 `ss` 跳转（备份 `~/.ssh/config.bak.20261010152348`）。
+- 全局规则已更新：浏览器自动化可用 Chrome Beta 或 Microsoft Edge。
+
+- **代码文件与内容统一归集到 /opt/sub2api（2026-10-11）**：
+  - 前端静态文件：物理路径 /opt/sub2api/relay-web/index.html（软链 /www/wwwroot/sub2api-relay-web 保持兼容）。
+  - 后端服务源码：物理路径 /opt/sub2api/key_query.py，systemd 服务 sub2api-key-query 已更新 WorkingDirectory=/opt/sub2api。
+  - 运维与路由脚本：物理路径 /opt/sub2api/ops/（软链 /opt/sub2api/ops 保持历史调用兼容）。
+  - 宝塔面板配置：站点 4 path 字段已更新为 /opt/sub2api/relay-web，Nginx 配置 root/alias 均直指物理路径。
+
+- **独立工程化与预编译 Tailwind CSS 改造（2026-10-11）**：
+  - 目录隔离：与 /opt/sub2api 根目录彻底区分，建立独立工程目录 /opt/sub2api-relay/。
+  - 核心入口脚本：/opt/sub2api-relay/run，支持 start / stop / restart / build / status。
+  - 预编译 CSS：移除外部 CDN 运行时编译器，采用编译产物 dist/tailwind.css（38KB 单文件极速加载，零外部网络依赖）。
+  - 后端归位：后端只读微服务置于 /opt/sub2api-relay/server/key_query.py，sub2api-key-query 服务已更新工作目录。
+  - 产物发布目录：Nginx 与宝塔站点物理根目录直接映射至 /opt/sub2api-relay/dist。
+
+- **加速线路卡片样式与高精度 RTT 测速优化（2026-10-11）**：
+  - 样式优化：加速线路卡片移除 hover 悬浮与点击变框效果，保持固定纯净的 2px 静态边框，卡片内 URL 与复制按钮独立可用。
+  - 延迟测速对齐 Nexus 官网：剥离浏览器冷启动阶段的 DNS 解析与 TLS 握手开销，基于 HTTP/2 长连接复用与 Resource Timing API (responseEnd - requestStart)，测出真实的边缘纯网络往返时延（RTT，12ms~35ms 绿色常亮）。
+  - 项目归位：位于 /opt/sub2api/relay，配备独立管理脚本 ./run。
+
+- **线路区域纯静态化展示改造（2026-10-11）**：
+  - 顶部线路卡片纯粹展示 URL 与实时延迟，彻底移除复制按钮及 URL 上的点击复制交互。
+  - 外层容器无 hover 边框变化、无点击边框动效，保持静止内敛的高级科技质感。
+
+- **主题菜单、居中气泡与纯净展示优化（2026-10-11）**：
+  - 主题下拉菜单：右上角支持 hover 弹出菜单，提供「白天模式(☀️)」、「黑夜模式(🌙)」、「跟随系统(💻)」，带图标并自动持久化。
+  - 全局居中顶部气泡：所有错误与提示（如 API Key 不存在、已复制等）统一改为全页面水平左右居中、距离顶部一定距离的悬浮胶囊气泡。
+  - 移除悬浮 title 提示：全站彻底清理系统级 title 悬浮小黄条提示。
+  - 顶部标题居中：完全同步 sub2api 原生 Logo 与标题副标题，移除互通徽章并居中呈现。
+
+## 14. 审计整改（2026-10-11 20:20 北京时间，依据《sub2api 最新审计 20:08》）
+
+- **统一路由重试边界**（`auto_proxy.py`）：只在请求确定未执行时换分组（连接/发送失败、403、429、503、522、529、明确不支持模型）；500/502/504/520/524 及「已发出但读不到响应」不再重发，后者返回 502 并说明可能已执行。切换或结果未知时写 `/var/log/sub2api-ops/auto_proxy.log`（时间、路径、模型、尝试路径，不含 Key），响应头 `X-S2A-Route-Attempts` 带尝试路径。路由鉴权不可用时返回 503（原先处理线程异常断开）。代价：502/504 等不再自动跨分组兜底，由客户端自行重试。
+- **日报订单口径**（`daily_report.py`）：按 sub2api 0.2.15 源码，`amount` 已是含赠送的到账余额，原 `amount + bonus_amount` 重复计入赠送（实测订单 ¥2.98→$6.00 被算成 0.33 ¥/$，正确 0.497）；`refund_amount` 是退回的余额$ 而非人民币，退款¥ = pay_amount × refund_amount / amount。客户单价改为余额订单「退款后净实付 / 退款后净到账」，只扣 REFUNDED/PARTIALLY_REFUNDED；订阅订单不参与单价与到账余额。
+- **Fast/Flex 阻断补齐**（`nexus_sync.py`）：档位阶梯主要字段「基础无价」同样阻止自动同步；`config_audit.py` 把 STRUCT_ERRORS 计为问题（不再「问题 0」掩盖阻断）。近似计价本身是 sub2api 单倍率结构限制，未改变。
+- **旧 systemd 单元**：`sub2api-route-auth`/`sub2api-auto-proxy` ExecStart 改为 `/opt/sub2api/ops/`，加注释说明由看门狗运行；保持 disabled。
+- 备份与回退：`/root/backup/ops_before_audit_fix_20261011121925/`（4 个脚本、2 个单元、本文件）；回退 = 拷回原文件，`daemon-reload`，auto_proxy 需杀进程由看门狗拉起。
+- 仍待确认：`business.json` 支付通道费率（当前 0）；返利成本按 accrue × 进价是否符合返利提现/转余额规则；Fast/Flex 是否接受近似计价。
+- 补充（20:30）：易支付不按笔扣费，仅提现收结算手续费 0.1%（最低提现 100 元，T+1），`business.json` 的 `pay_channel_fee_percent` 已改为 0.1（按实收计提）。Fast/Flex 按 Nexus：输入/输出两个主要字段倍率与 Nexus 完全一致（当前 priority ×2、flex ×0.5）；缓存/1h 写入/阶梯差异是 sub2api 0.2.15 渠道只能配一个 fast/flex 倍率的限制，完全一致需改源码重编译。截至 10-11 使用记录中 priority 0 笔、flex 1 笔（测试），实际影响可忽略。
+
+## 15. 统一路由协议过滤与同步保护（2026-10-11 19:00–20:40 北京时间）
+
+- **问题**：统一路由 Key 请求 `claude-haiku-4-5`（/v1/messages）返回 400「该分组不支持 /messages 端点 [gemini_1]」。Nexus 18:00 起 gemini_1 的 `supportedEndpoints` 不再含 `claude_messages`（官网「支持的协议」按 `types`/`formatSource` 仍显示 Claude 转换，属 Nexus 侧显示与网关不一致；直连 Nexus 实测 /messages 一律 400 endpoint_not_supported，trace t1da0052iij）。本站匹配表只看账号平台，gemini_1 按字母序排在 kiro 前被选中。
+- **修复**：`gen_auto_index.py` 按 Nexus `supportedEndpoints` 过滤协议（PLAT_ENDPOINTS）；`auto_proxy.py` 的 UNSUPPORTED 加入 `endpoint_not_supported`（换下一分组）。
+- **同步卡住的根因**：18:00 自动同步已发现 gemini_1 应停用 anthropic 账号，但「模型数骤减超过一半」保护把 64→22（去掉的 42 个都在 anthropic 账号上）误判为 Nexus 异常而中止，之后同差异每小时跳过。`nexus_sync.py` 改为只比较仍开放协议的模型数；重新同步后 #43 gemini_1-anthropic 停用（Nexus 恢复端点时同步会自动启用），分组 #16 路由 -6。停用后 /api/gemini_1 的 Claude 请求由 sub2api 自行转换到 Gemini 账号。
+- **自动同步改进**（`nexus-auto-sync.sh`）：同一差异 6 小时后自动重试一次（原先永久跳过直到差异变化）；同步成功后立即执行 `refresh-auto-route.sh`，不再等整点任务 #8。宝塔任务 #8 名称路径改为 `/opt/sub2api/ops/`（面板库备份 `/root/backup/bt-default.db.*`）。
+- **验证**：统一路由 haiku（加速/直连）200、Claude Code 客户端 OK、kiro 路径 200；对账一致（检查项 466）。gemini 模型当时 Nexus 侧 529（直连 Nexus 同样 529，约 39 秒），与本站无关，待 Nexus 恢复后复测 /api/gemini_1 的 Claude 转换。
+
+- **Fast/Flex 改为不亏本（20:41）**：`nexus_sync.py` 的 `ratio()` 改为取全部 token 字段（输入/输出/缓存读/缓存写/1h 缓存写）× 基础与各级阶梯中「Nexus 档位价 / 本站标准价」的最大值；Nexus 未给某级/某字段档位价时按可能的最高价（档位基础价与该级标准价取大）估计。保底后 Flex ≥ ×1 或 Fast > Nexus 输入/输出比例 1.5 倍的模型，由同步脚本写入 sub2api 设置 `openai_fast_policy_settings` 的 filter 规则（去除 service_tier，按标准档执行与计费；规则以 error_message 标记为 nexus-sync 自动管理，人工规则保留）。`config_audit.py` 同时核对倍率与策略。当前结果：Fast 去除 codex-auto-review、gpt-reserve（Nexus 长上下文缓存读/写价疑似填反，保底需 ×25）、gpt-6-astra、gpt-6.1-sol（1h 缓存写需 ×3.2）；Flex 去除 gpt-5.5、claude-haiku-5-5、gemini-3.1-pro-preview（含映射到它的 gpt-image-* 别名）；gpt-6-astra/gpt-6.1-sol Flex 改 ×0.8 保留。策略只作用于 OpenAI 网关路径，Anthropic/Gemini 原生路径仍按保底倍率计费（不少收）。同步前备份 `/root/backup/sub2api_before_nexus_sync_20261011124141.sql.gz`；脚本与原策略备份在 `/root/backup/ops_before_audit_fix_20261011121925/round2_124123/`。
+- **第三轮整改（20:52，依据审计 20:43 版）**：
+  - 统一路由：只在 `connect()` 失败（一个字节未发出）时换分组；开始发送后的任何异常（写入或读响应）都按结果未知返回 502 不重发，尝试记录为异常类名。
+  - Fast/Flex 倍率：字段纳入图片输入/输出；本站标准价按 price_entry 与 sub2api 回退规则（显式 0 保留，缺失才回退；图片价只在基础层，图片输入为 0 回退文本输入价）；比例按 4 位小数向上取整。
+  - **新发现并修复**：sub2api 对渠道未配倍率的模型默认 Flex ×0.5、Fast/Ultrafast ×2（`billing_service.go` serviceTierCostMultiplier），而 Nexus 只有 22 个模型有 Flex 价、19 个有 Fast 价、没有 Ultrafast 价。现在 Nexus 无 Flex 价的模型 `flex_multiplier` 固定 1；策略三条自动管理规则：ultrafast 全部去除；flex 只放行有 Nexus Flex 价且保底后仍有折扣的 31 个模型，其余去除（pass + fallback filter）；priority 去除 4 个（同上轮）。Nexus 无 Fast 价的模型 sub2api 按 ×2 或目录价收，不少收，未改。
+  - 切换窗口：同步写入前先把策略收紧（Ultrafast/Flex 全部去除、Fast 去除取新旧并集），全部写入完成后再落最终策略；中途失败则停在收紧状态，下次同步恢复。
+  - 日报：费用行改名「提现结算费（计提）」，说明实际在提现时扣。
+  - 仍需实账验证：首笔真实付款/退款核对日报口径；去档位后的实际扣费可在日报「上游成本逐笔核对」中观察。
+  - 备份：`/root/backup/ops_before_audit_fix_20261011121925/round3_125125/`（4 个脚本 + 原策略）；同步前数据库备份见 `/root/backup/` 最新 `sub2api_before_nexus_sync_*`。
+- **档位与扣费实测（2026-10-11 21:03，管理员 Key #75 经正式入口，13 笔最小请求，Nexus 实扣合计约 $0.024）**：成功的 8 笔（Chat/Responses/Claude 三协议、codex_eco/codex/kiro、统一路由）本站原价 = Nexus rawCost、本站上游成本 = Nexus userCost，逐笔精确到 1e-8；客户扣费 = 成本 × 1.28（codex 系）/ 成本 × 1.11（kiro 售价 2.98 ÷ 成本 2.68）。策略去除档位实测生效：Ultrafast（Chat、Responses）、codex-auto-review Fast、gpt-5.5 Flex 到达 Nexus 时 requestedServiceTier 为空、按 default 计费，本站同按标准档。gpt-6-luna Fast 放行后 Nexus 自行过滤（serviceTierFiltered=true，实际 default），本站按上游返回档位降为 default 计费，两边一致。**Flex 目前 Nexus 一律拒绝**（gpt-6-luna Chat/Responses、codex_eco/codex 均 400 "Unsupported service_tier: flex"，一次 503），失败请求两边均不扣费；10-10 记录的 flex 半价一致已不再适用。是否对 Flex 全部去除档位（客户请求改按标准价成功执行）待决定。
+- **Flex 全部去除（21:14，按决定）**：`nexus_sync.py` 新增开关 `FLEX_ENABLED = False`：Flex 策略对全部模型 filter，全部渠道 `flex_multiplier = 1`（166 条）。实测 gpt-6-luna 带 flex 的 Chat/Responses 请求由原来的 400 变为 200，Nexus 收到的档位为空、按 default 扣费，本站按标准价计费，原价与 Nexus 实扣一致。Nexus 恢复支持 Flex 后把开关改为 True 再同步即可放行（仍按保底倍率）。备份 `/root/backup/ops_before_audit_fix_20261011121925/round4_131346/`。
+- **Gemini/Claude 协议 Fast 实测与对齐（21:22）**：Gemini 原生协议无档位（sub2api 不识别），标准档两边一致。实测发现三处本站多收（不亏）：Gemini 模型经 OpenAI 协议带 priority 时 Nexus 收不到档位、按标准价扣，本站 ×1.8；claude-opus-5 `speed=fast` Nexus 实际 fast 但无 Fast 价、按标准价扣，本站按 sub2api 默认 ×2；Claude 经 OpenAI 协议 priority 同样 Nexus 按标准价，本站 ×2。已改：Nexus 无 Fast 价的模型 `fast_multiplier = 1`；`FAST_NOT_DELIVERED = ("gemini-",)` 的模型 Fast 去除。复测 4 笔（含 opus-5-5 有 Fast 价的对照）本站原价/上游成本与 Nexus 逐笔一致。备份 `round5_132214/`。
+- **手动退款登记（21:40）**：易支付退款需联系客服线下处理，sub2api 0.2.15 无「只记账不调网关」的退款方式（退款必调网关；支付实例 refund_enabled=false 时直接拒绝）。新增 `/opt/sub2api/ops/manual-refund.sh <订单号> <退回余额$> [原因] [--apply]`（`manual_refund.py`）：按原生成功路径单事务扣回余额（最多扣到 0）、订单置 REFUNDED/PARTIALLY_REFUNDED、写 REFUND_SUCCESS 审计（manual=true、网关退款¥ = 实付 × 退回 / 到账），不回收返利（同原生），清余额缓存；--apply 前备份订单与用户行到 `/root/backup/manual_refund_*.json`。已做预览、回滚演练（数据未变）与非法输入测试。订单 #4（用户 #2，实付 ¥2.98，到账 $6.00）已在易支付线下退款，待确认退款金额后登记。
+- **订单 #4 退款登记（22:14）**：易支付客服线下退款 ¥1，`manual-refund.sh 4 1元 --apply` 登记（金额参数支持人民币，按实付/到账折算）：订单 PARTIALLY_REFUNDED、refund_amount $2.01、用户 #2 余额 $15.6458 → $13.6358、审计 REFUND_SUCCESS（admin:manual）。日报核对：退款 ¥1.00；客户净单价 (2.98−1.00)/(6−2.01)=0.4962 ¥/$，收入 ¥0.1758 一致。退款口径实账验证完成。备份 `/root/backup/manual_refund_4_20261011141412.json`。
+- **relay 页面退款登记（22:35）**：`https://apiacc.itssx.com/relay/key`（或 `api.itssx.com/relay/key`）在同一浏览器已登录 sub2api 管理员时，查询区下方出现「退款登记」面板（`relay.itssx.com` 不同源，读不到登录状态，不显示）。输入订单号 → 显示客户、状态、实付、到账（含赠送）、购买单价、当前余额；输入实际退款人民币，自动按 实付¥/到账$ 折算扣回美元（全额退款扣回全部到账），两次点击确认后写入。后端 `relay/server/key_query.py` 新增 `GET /api/relay/admin/me`、`GET /api/relay/admin/order?id=`、`POST /api/relay/admin/refund`：用浏览器的 sub2api 登录 token（localStorage `auth_token`）调 `127.0.0.1:8080/api/v1/auth/me` 校验 role=admin（转发 UA，兼容会话绑定），每 IP 每分钟 30 次；写库用新建最小权限账号 `relay_refund`（凭据 `relay/server/.refund_db.env` root:sub2api 640；仅能读订单/用户的必要列、改退款相关列与余额、插入审计日志）；单条 SQL（数据修改 CTE）原子完成，审计 operator=`admin:<id>:relay`，detail 含 balanceBefore/statusBefore 便于回退；sub2api 审计表 (order_id, action) 唯一索引保证同一订单只能登记一次。验证：管理员校验、订单查询、不存在/非法/已退款/已取消/缺确认/篡改签名均按预期；最小权限账号在 BEGIN…ROLLBACK 中执行同一 SQL 成功且数据未变；页面浅色/深色截图正常。
+- **relay 构建脚本修复**：`run build` 原先找不到宝塔安装的 Node（不在 PATH），一直静默复用 11:07 的旧 tailwind.css（之后页面新增的样式类都未生效）；现在自动加入 `/www/server/nodejs/v*/bin` 并优先用项目 `node_modules/.bin/tailwindcss`，找不到编译器时改为醒目警告。`run restart` 只重启后端，改前端后需 `run build`。备份 `/root/backup/relay-refund-20261011142449/`。
+- **退款登记页 v2（23:05，替换上一版「sub2api 管理员面板」）**：查询页右上「退款」按钮（与「公告」并列；小屏在副标题下方）→ `/relay/refund.html`（三个域名都可用）。独立账号登录（与 sub2api 后台无关）：账号表 `s2a_ops.refund_users`（scrypt 加盐哈希），会话表 `s2a_ops.refund_sessions`（只存 token 的 sha256，12 小时，Cookie HttpOnly/Secure/SameSite=Strict、Path=/api/relay/refund）；每 IP 每分钟 10 次登录、连续 5 次失败锁 15 分钟、写操作需 `X-Requested-With: s2a-refund`；首次登录可强制改密，页面可改密（改后其他会话失效）。账号管理（服务器 root）：`/opt/sub2api/relay/run refund-user list|add|passwd|disable|enable <账号>`（密码交互输入）。订单列表：搜索（订单号/客户 ID/邮箱/交易号）、状态、支付方式、退款有无、下单日期筛选，分页 20/50/100，汇总实付/已退。**同一订单可多次退款**：台账 `s2a_ops.manual_refunds`（每次一行：¥、扣回 $、实扣、余额前、状态前后、原因、操作人），订单 refund_amount 累加，累计到账额即 REFUNDED；sub2api 审计 (order_id, action) 唯一，故 action = `MANUAL_REFUND_<台账 id>`；剩余可退 ¥ = 实付 − 已退 ¥，退完剩余时扣回全部剩余 $（含赠送）。单条 SQL 原子完成并复核已退金额未变。订单 #4 的 ¥1 已回填为台账 #1。日报退款改按台账（按退款时间计入当天）+ 台账外原生退款；客户净单价用台账人民币。旧命令行 `manual-refund.sh` 已停用（不写台账）。`relay_refund` 增加 s2a_ops 三张表与订单列表所需列的权限。验证：31 项端到端（登录/错误/锁定/改密/Cookie 属性/防跨站/筛选与注入/详情/超额/取消单/多次退款与退完（回滚）/退出）全部通过；页面三视图浅色/深色、查询页桌面/手机截图正常。备份：数据库 `/root/backup/sub2api_before_refund_schema_20261011144033.sql.gz`，relay `/root/backup/relay-refund2-20261011144938/`，ops `round6_145133/`。**待用户创建自己的账号**。
+- **退款页 v3（23:25）**：右上角加主题切换（白天/黑夜/跟随系统，与查询页共用 theme_mode）；修改密码卡片边框改主题紫。**退款记录可删除**：订单详情的每条记录「删除 → 确认删除」，后端 `POST /api/relay/refund/revoke {ledger_id, confirm}` 单条语句原子完成：退回当次实际扣回的余额、订单 refund_amount 减当次 $（减到 0 恢复 COMPLETED、refund_at 清空，否则 PARTIALLY_REFUNDED、refund_at 取剩余最近一次）、台账行软删除（deleted_at/deleted_by/delete_reason，`relay_refund` 仅能改这三列）、审计 `MANUAL_REFUND_<id>_REVOKED`、清余额缓存；已删除记录灰显留痕，所有合计、剩余可退与日报均排除。**新增登记**：列表工具栏「+ 新增登记」输入订单号直达；详情中表单默认收起，点「+ 新增登记」展开。验证：拒绝路径（未登录/缺防跨站头/缺确认/不存在）与单事务删除演练（余额退回 $2.01、订单恢复已完成、台账留痕，ROLLBACK 后不变）全部通过；页面截图浅色/深色正常。备份 `/root/backup/relay-refund3-20261011151728/`。
+- **审计整改 round7（23:45）**：①**余额缓存从未清除成功**：服务以 sub2api 用户运行，宝塔 `redis-cli` 为 redis:redis 700，每次登记/删除提交后都抛 PermissionError → 接口返回 500「未确认」（23:30 删除台账 #1 即如此：数据库已提交、页面报失败）。改为 Python 直连 RESP `DEL`，只认 `:0/:1`；失败时台账 `cache_cleared_at` 保持为空，后台线程每分钟补清（实测补清成功），接口返回 `cache_cleared`，页面提示。②**登记幂等**：台账新增 `request_id uuid`（唯一索引 `manual_refunds_request_id_key`），页面每次操作生成 UUID，网络错误/5xx 重试沿用、4xx/成功/关弹窗换新；后端同 ID 返回首次结果（`duplicate`），金额或订单不一致、已被删除则拒绝；并发同请求由唯一约束拦截后返回首次结果。`relay_refund` 增加 `UPDATE(cache_cleared_at)`。③**日报混合退款**：原生部分统一为「refund_amount − 台账 $（不含已删除）」折算，时间取原生 `REFUND_SUCCESS` 审计（排除 admin:manual），无则 refund_at；不再以「有台账」排除整单。④**Fast/Flex 规则重复根因**：21:51 sub2api 后台保存设置会重写策略、丢掉 filter 规则的 error_message 标记（白名单规则补 fallback_action=pass），22:00 同步把副本当人工规则保留并再加一组。`nexus_sync.py` 记录写过的自动规则签名（`ops/policy_managed_history.json`），无标记且签名相同的视为自动规则替换；`config_audit.py` 报告同档多条自动规则。已同步：策略恢复 3 条（差异 0）。注意：人工规则请写自己的 error_message 或与自动规则不同，否则会被当作自动规则。验证：12 项回滚式幂等/缓存测试（服务用户、同一事务、ROLLBACK，数据前后一致）、日报混合退款模拟（旧 ¥1.00 → 新 ¥1.50 = 期望）、剥离策略识别测试全部通过。备份 `/root/backup/audit_fix_round7_20261011153116/`（5 个文件 + s2a_ops 导出 + 原策略），迁移 SQL `/root/backup/manual_refunds_migrate_20261011.sql`。**待确认**：台账 #1（订单 #4 线下退款 ¥1，真实发生）已于 23:30 被页面删除，订单 #4 现为 COMPLETED、用户 #2 余额已加回 $2.01；若非有意，请在页面对订单 #4 重新登记 ¥1。
+- **退款页 v4（2026-10-12 00:05，基于 round7 版本修改）**：订单详情「支付」拆为「支付方式」「支付时间」；「交易号」「商户单号」点击复制。**已删除的退款可恢复**：`POST /api/relay/refund/restore {ledger_id, confirm}`，单条语句原子完成：按当次 $ 重新扣回余额（最多到 0）、订单已退金额加回并重算状态、清除删除标记、记 restored_at/restored_by、更新台账 deducted/balance_before（之后再删按新扣回额退回）、cache_cleared_at 置空走 round7 的缓存补清；订单剩余可退不足或状态不允许时拒绝。审计 action 改为带微秒时间戳后缀（`MANUAL_REFUND_<id>_REVOKED_<ts>` / `_RESTORED_<ts>`），避免同一台账多次删除/恢复撞 (order_id, action) 唯一索引。`relay_refund` 增加 UPDATE(deducted, balance_before, restored_at, restored_by)。验证：拒绝路径 + 单事务「恢复 → 再删除」演练（扣回 $2.01、部分退款、恢复人记录、再删不冲突，ROLLBACK 后不变）全部通过。台账 #1（订单 #4 ¥1）**仍为已删除**，如需恢复在页面订单 #4 点「恢复」。备份 `/root/backup/relay-refund4-20261011160137/`。
+- **审计整改 round8（2026-10-12 00:35）**：结果未确认的退款登记改为持久化核对：页面把未确认登记（订单、¥、原因、request_id、时间）存 localStorage `s2a_refund_pending`（按订单），关窗/刷新不丢；未核对前该订单只能按原金额和原因用原 request_id 重试，改金额/原因被拦截。重新打开订单时调新接口 `GET /api/relay/refund/request?id=<request_id>` 核对：已写入 → 提示成功并清除；查不到且超过 60 秒（后端写库最长约 10 秒）→ 确认未写入并清除；60 秒内 → 表单预填原值供重试。仍不防跨浏览器/跨设备的重复（需要线下退款凭证号唯一约束才能做到）。撤销/恢复复核：15 项回滚式测试（两轮删除/恢复、重复删除/恢复被拒、剩余额度不足恢复被拒且数据不变、余额不足恢复扣到 0 后再删按实扣退回、Redis 不可用恢复成功并留待补清、request_id 核对）全部通过，数据前后一致。日报口径保持：恢复后按原 created_at 计入（视为更正历史登记，不是恢复当日新现金流）。备份 `/root/backup/audit_fix_round8_20261011162131/`。
+- **审计整改 round9（2026-10-12 11:10）**：①**结果未确认的登记改由服务器原子作废**，不再用「60 秒查不到即未写入」的本机时间推断：新表 `s2a_ops.refund_requests(request_id 主键, state done/abandoned)`；登记写库语句同事务插入 done，新接口 `POST /api/relay/refund/abandon {request_id}` 插入 abandoned（on conflict do nothing 后读状态）——在途的同 ID 写入会先持有主键，作废等它结束再判定；作废后同 ID 写入撞主键整条失败。页面重新打开订单时直接调作废接口：已写入则提示结果并刷新详情，否则提示「未写入，已在服务器作废」。`relay_refund` 授予该表 SELECT/INSERT；已有带 request_id 的台账已回填 done。②**备份恢复演练覆盖 s2a_ops**：`backup-restore-check.sh` 新增 s2a_ops 表数与唯一索引数一致、manual_refunds/refund_users/route_keys/group_meta/nexus_tags 行数（>0，台账与退款账号 ≤ 生产）、台账→订单与子 Key→Key 关联缺失为 0；已确认 R2 定时备份本身包含 s2a_ops，并实跑演练通过（8 表/10 唯一索引一致，关联缺失 0）。新表在下次 02:00 备份后纳入表数比对。验证：作废语义 10 项（含两会话并发等待）与 round7/8 回归测试全部通过，均回滚，数据前后一致。备份 `/root/backup/audit_fix_round9_20261012025843/`（3 个文件、迁移前 s2a_ops 导出、迁移 SQL）。
diff --git a/install-datamanagementd.sh b/install-datamanagementd.sh
new file mode 100644
index 0000000..8d53134
--- /dev/null
+++ b/install-datamanagementd.sh
@@ -0,0 +1,123 @@
+#!/usr/bin/env bash
+
+set -euo pipefail
+
+# 用法：
+#   sudo ./install-datamanagementd.sh --binary /path/to/datamanagementd
+# 或：
+#   sudo ./install-datamanagementd.sh --source /path/to/sub2api/repo
+
+BIN_PATH=""
+SOURCE_PATH=""
+INSTALL_DIR="/opt/sub2api"
+DATA_DIR="/var/lib/sub2api/datamanagement"
+SERVICE_FILE_NAME="sub2api-datamanagementd.service"
+
+function print_help() {
+  cat <<'EOF'
+用法:
+  install-datamanagementd.sh [--binary <datamanagementd二进制路径>] [--source <仓库路径>]
+
+参数:
+  --binary  指定已构建的 datamanagementd 二进制路径
+  --source  指定 sub2api 仓库路径（脚本会执行 go build）
+  -h, --help 显示帮助
+
+示例:
+  sudo ./install-datamanagementd.sh --binary ./datamanagement/datamanagementd
+  sudo ./install-datamanagementd.sh --source /opt/sub2api-src
+EOF
+}
+
+while [[ $# -gt 0 ]]; do
+  case "$1" in
+    --binary)
+      BIN_PATH="${2:-}"
+      shift 2
+      ;;
+    --source)
+      SOURCE_PATH="${2:-}"
+      shift 2
+      ;;
+    -h|--help)
+      print_help
+      exit 0
+      ;;
+    *)
+      echo "未知参数: $1"
+      print_help
+      exit 1
+      ;;
+  esac
+done
+
+if [[ -n "$BIN_PATH" && -n "$SOURCE_PATH" ]]; then
+  echo "错误: --binary 与 --source 只能二选一"
+  exit 1
+fi
+
+if [[ -z "$BIN_PATH" && -z "$SOURCE_PATH" ]]; then
+  echo "错误: 必须提供 --binary 或 --source"
+  exit 1
+fi
+
+if [[ "$(id -u)" -ne 0 ]]; then
+  echo "错误: 请使用 root 权限执行（例如 sudo）"
+  exit 1
+fi
+
+if [[ -n "$SOURCE_PATH" ]]; then
+  if [[ ! -d "$SOURCE_PATH/datamanagement" ]]; then
+    echo "错误: 无效仓库路径，未找到 $SOURCE_PATH/datamanagement"
+    exit 1
+  fi
+  echo "[1/6] 从源码构建 datamanagementd..."
+  (cd "$SOURCE_PATH/datamanagement" && go build -o datamanagementd ./cmd/datamanagementd)
+  BIN_PATH="$SOURCE_PATH/datamanagement/datamanagementd"
+fi
+
+if [[ ! -f "$BIN_PATH" ]]; then
+  echo "错误: 二进制文件不存在: $BIN_PATH"
+  exit 1
+fi
+
+if ! id sub2api >/dev/null 2>&1; then
+  echo "[2/6] 创建系统用户 sub2api..."
+  useradd --system --no-create-home --shell /usr/sbin/nologin sub2api
+else
+  echo "[2/6] 系统用户 sub2api 已存在，跳过创建"
+fi
+
+echo "[3/6] 安装 datamanagementd 二进制..."
+mkdir -p "$INSTALL_DIR"
+install -m 0755 "$BIN_PATH" "$INSTALL_DIR/datamanagementd"
+
+echo "[4/6] 准备数据目录..."
+mkdir -p "$DATA_DIR"
+chown -R sub2api:sub2api /var/lib/sub2api
+chmod 0750 "$DATA_DIR"
+
+SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
+SERVICE_TEMPLATE="$SCRIPT_DIR/$SERVICE_FILE_NAME"
+if [[ ! -f "$SERVICE_TEMPLATE" ]]; then
+  echo "错误: 未找到服务模板 $SERVICE_TEMPLATE"
+  exit 1
+fi
+
+echo "[5/6] 安装 systemd 服务..."
+cp "$SERVICE_TEMPLATE" "/etc/systemd/system/$SERVICE_FILE_NAME"
+systemctl daemon-reload
+systemctl enable --now sub2api-datamanagementd
+
+echo "[6/6] 完成，当前状态："
+systemctl --no-pager --full status sub2api-datamanagementd || true
+
+cat <<'EOF'
+
+下一步建议：
+1. 查看日志：sudo journalctl -u sub2api-datamanagementd -f
+2. 在 sub2api（容器部署时）挂载 socket:
+   /tmp/sub2api-datamanagement.sock:/tmp/sub2api-datamanagement.sock
+3. 进入管理后台“数据管理”页面确认 agent=enabled
+
+EOF
diff --git a/install.sh b/install.sh
new file mode 100644
index 0000000..246347c
--- /dev/null
+++ b/install.sh
@@ -0,0 +1,1232 @@
+#!/bin/bash
+#
+# Sub2API Installation Script
+# Sub2API 安装脚本
+# Usage: curl -sSL https://raw.githubusercontent.com/Wei-Shaw/sub2api/main/deploy/install.sh | bash
+#
+
+set -e
+
+# Bash 4+ is required for associative arrays used by the localized message table.
+# Keep this guard before any Bash 4-only syntax so older shells fail with a clear hint.
+if [ -z "${BASH_VERSION:-}" ]; then
+    echo "Error: This installer must be run with Bash 4.0 or later." >&2
+    echo "Please install Bash 4+ and run it with that interpreter." >&2
+    exit 1
+fi
+
+BASH_MAJOR_VERSION="${BASH_VERSION%%.*}"
+if [ "$BASH_MAJOR_VERSION" -lt 4 ]; then
+    echo "Error: Bash 4.0 or later is required. Current version: $BASH_VERSION" >&2
+    echo "Please install Bash 4+ and retry with that interpreter." >&2
+    exit 1
+fi
+
+# Colors
+RED='\033[0;31m'
+GREEN='\033[0;32m'
+YELLOW='\033[1;33m'
+BLUE='\033[0;34m'
+CYAN='\033[0;36m'
+NC='\033[0m' # No Color
+
+# Configuration
+GITHUB_REPO="Wei-Shaw/sub2api"
+INSTALL_DIR="/opt/sub2api"
+SERVICE_NAME="sub2api"
+SERVICE_USER="sub2api"
+CONFIG_DIR="/etc/sub2api"
+
+# Server configuration (will be set by user)
+SERVER_HOST="0.0.0.0"
+SERVER_PORT="8080"
+
+# Language (default: zh = Chinese)
+LANG_CHOICE="zh"
+
+# ============================================================
+# Language strings / 语言字符串
+# ============================================================
+
+# Chinese strings
+declare -A MSG_ZH=(
+    # General
+    ["info"]="信息"
+    ["success"]="成功"
+    ["warning"]="警告"
+    ["error"]="错误"
+
+    # Language selection
+    ["select_lang"]="请选择语言 / Select language"
+    ["lang_zh"]="中文"
+    ["lang_en"]="English"
+    ["enter_choice"]="请输入选择 (默认: 1)"
+
+    # Installation
+    ["install_title"]="Sub2API 安装脚本"
+    ["run_as_root"]="请使用 root 权限运行 (使用 sudo)"
+    ["detected_platform"]="检测到平台"
+    ["unsupported_arch"]="不支持的架构"
+    ["unsupported_os"]="不支持的操作系统"
+    ["missing_deps"]="缺少依赖"
+    ["install_deps_first"]="请先安装以下依赖"
+    ["fetching_version"]="正在获取最新版本..."
+    ["latest_version"]="最新版本"
+    ["failed_get_version"]="获取最新版本失败"
+    ["downloading"]="正在下载"
+    ["download_failed"]="下载失败"
+    ["verifying_checksum"]="正在校验文件..."
+    ["checksum_verified"]="校验通过"
+    ["checksum_failed"]="校验失败"
+    ["checksum_not_found"]="无法验证校验和（checksums.txt 未找到）"
+    ["extracting"]="正在解压..."
+    ["binary_installed"]="二进制文件已安装到"
+    ["user_exists"]="用户已存在"
+    ["creating_user"]="正在创建系统用户"
+    ["user_created"]="用户已创建"
+    ["setting_up_dirs"]="正在设置目录..."
+    ["dirs_configured"]="目录配置完成"
+    ["installing_service"]="正在安装 systemd 服务..."
+    ["service_installed"]="systemd 服务已安装"
+    ["ready_for_setup"]="准备就绪，可以启动设置向导"
+
+    # Completion
+    ["install_complete"]="Sub2API 安装完成！"
+    ["install_dir"]="安装目录"
+    ["next_steps"]="后续步骤"
+    ["step1_check_services"]="确保 PostgreSQL 和 Redis 正在运行："
+    ["step2_start_service"]="启动 Sub2API 服务："
+    ["step3_enable_autostart"]="设置开机自启："
+    ["step4_open_wizard"]="在浏览器中打开设置向导："
+    ["wizard_guide"]="设置向导将引导您完成："
+    ["wizard_db"]="数据库配置"
+    ["wizard_redis"]="Redis 配置"
+    ["wizard_admin"]="管理员账号创建"
+    ["useful_commands"]="常用命令"
+    ["cmd_status"]="查看状态"
+    ["cmd_logs"]="查看日志"
+    ["cmd_restart"]="重启服务"
+    ["cmd_stop"]="停止服务"
+
+    # Upgrade
+    ["upgrading"]="正在升级 Sub2API..."
+    ["current_version"]="当前版本"
+    ["stopping_service"]="正在停止服务..."
+    ["backup_created"]="备份已创建"
+    ["starting_service"]="正在启动服务..."
+    ["upgrade_complete"]="升级完成！"
+
+    # Version install
+    ["installing_version"]="正在安装指定版本"
+    ["version_not_found"]="指定版本不存在"
+    ["same_version"]="已经是该版本，无需操作"
+    ["rollback_complete"]="版本回退完成！"
+    ["install_version_complete"]="指定版本安装完成！"
+    ["validating_version"]="正在验证版本..."
+    ["available_versions"]="可用版本列表"
+    ["fetching_versions"]="正在获取可用版本..."
+    ["not_installed"]="Sub2API 尚未安装，请先执行全新安装"
+    ["fresh_install_hint"]="用法"
+
+    # Uninstall
+    ["uninstall_confirm"]="这将从系统中移除 Sub2API。"
+    ["are_you_sure"]="确定要继续吗？(y/N)"
+    ["uninstall_cancelled"]="卸载已取消"
+    ["removing_files"]="正在移除文件..."
+    ["removing_install_dir"]="正在移除安装目录..."
+    ["removing_user"]="正在移除用户..."
+    ["config_not_removed"]="配置目录未被移除"
+    ["remove_manually"]="如不再需要，请手动删除"
+    ["removing_install_lock"]="正在移除安装锁文件..."
+    ["install_lock_removed"]="安装锁文件已移除，重新安装时将进入设置向导"
+    ["purge_prompt"]="是否同时删除配置目录？这将清除所有配置和数据 [y/N]: "
+    ["removing_config_dir"]="正在移除配置目录..."
+    ["uninstall_complete"]="Sub2API 已卸载"
+
+    # Help
+    ["usage"]="用法"
+    ["cmd_none"]="(无参数)"
+    ["cmd_install"]="安装 Sub2API"
+    ["cmd_upgrade"]="升级到最新版本"
+    ["cmd_uninstall"]="卸载 Sub2API"
+    ["cmd_install_version"]="安装/回退到指定版本"
+    ["cmd_list_versions"]="列出可用版本"
+    ["opt_version"]="指定要安装的版本号 (例如: v1.0.0)"
+
+    # Server configuration
+    ["server_config_title"]="服务器配置"
+    ["server_config_desc"]="配置 Sub2API 服务监听地址"
+    ["server_host_prompt"]="服务器监听地址"
+    ["server_host_hint"]="0.0.0.0 表示监听所有网卡，127.0.0.1 仅本地访问"
+    ["server_port_prompt"]="服务器端口"
+    ["server_port_hint"]="建议使用 1024-65535 之间的端口"
+    ["server_config_summary"]="服务器配置"
+    ["invalid_port"]="无效端口号，请输入 1-65535 之间的数字"
+
+    # Service management
+    ["starting_service"]="正在启动服务..."
+    ["service_started"]="服务已启动"
+    ["service_start_failed"]="服务启动失败，请检查日志"
+    ["enabling_autostart"]="正在设置开机自启..."
+    ["autostart_enabled"]="开机自启已启用"
+    ["getting_public_ip"]="正在获取公网 IP..."
+    ["public_ip_failed"]="无法获取公网 IP，使用本地 IP"
+)
+
+# English strings
+declare -A MSG_EN=(
+    # General
+    ["info"]="INFO"
+    ["success"]="SUCCESS"
+    ["warning"]="WARNING"
+    ["error"]="ERROR"
+
+    # Language selection
+    ["select_lang"]="请选择语言 / Select language"
+    ["lang_zh"]="中文"
+    ["lang_en"]="English"
+    ["enter_choice"]="Enter your choice (default: 1)"
+
+    # Installation
+    ["install_title"]="Sub2API Installation Script"
+    ["run_as_root"]="Please run as root (use sudo)"
+    ["detected_platform"]="Detected platform"
+    ["unsupported_arch"]="Unsupported architecture"
+    ["unsupported_os"]="Unsupported OS"
+    ["missing_deps"]="Missing dependencies"
+    ["install_deps_first"]="Please install them first"
+    ["fetching_version"]="Fetching latest version..."
+    ["latest_version"]="Latest version"
+    ["failed_get_version"]="Failed to get latest version"
+    ["downloading"]="Downloading"
+    ["download_failed"]="Download failed"
+    ["verifying_checksum"]="Verifying checksum..."
+    ["checksum_verified"]="Checksum verified"
+    ["checksum_failed"]="Checksum verification failed"
+    ["checksum_not_found"]="Could not verify checksum (checksums.txt not found)"
+    ["extracting"]="Extracting..."
+    ["binary_installed"]="Binary installed to"
+    ["user_exists"]="User already exists"
+    ["creating_user"]="Creating system user"
+    ["user_created"]="User created"
+    ["setting_up_dirs"]="Setting up directories..."
+    ["dirs_configured"]="Directories configured"
+    ["installing_service"]="Installing systemd service..."
+    ["service_installed"]="Systemd service installed"
+    ["ready_for_setup"]="Ready for Setup Wizard"
+
+    # Completion
+    ["install_complete"]="Sub2API installation completed!"
+    ["install_dir"]="Installation directory"
+    ["next_steps"]="NEXT STEPS"
+    ["step1_check_services"]="Make sure PostgreSQL and Redis are running:"
+    ["step2_start_service"]="Start Sub2API service:"
+    ["step3_enable_autostart"]="Enable auto-start on boot:"
+    ["step4_open_wizard"]="Open the Setup Wizard in your browser:"
+    ["wizard_guide"]="The Setup Wizard will guide you through:"
+    ["wizard_db"]="Database configuration"
+    ["wizard_redis"]="Redis configuration"
+    ["wizard_admin"]="Admin account creation"
+    ["useful_commands"]="USEFUL COMMANDS"
+    ["cmd_status"]="Check status"
+    ["cmd_logs"]="View logs"
+    ["cmd_restart"]="Restart"
+    ["cmd_stop"]="Stop"
+
+    # Upgrade
+    ["upgrading"]="Upgrading Sub2API..."
+    ["current_version"]="Current version"
+    ["stopping_service"]="Stopping service..."
+    ["backup_created"]="Backup created"
+    ["starting_service"]="Starting service..."
+    ["upgrade_complete"]="Upgrade completed!"
+
+    # Version install
+    ["installing_version"]="Installing specified version"
+    ["version_not_found"]="Specified version not found"
+    ["same_version"]="Already at this version, no action needed"
+    ["rollback_complete"]="Version rollback completed!"
+    ["install_version_complete"]="Specified version installed!"
+    ["validating_version"]="Validating version..."
+    ["available_versions"]="Available versions"
+    ["fetching_versions"]="Fetching available versions..."
+    ["not_installed"]="Sub2API is not installed. Please run a fresh install first"
+    ["fresh_install_hint"]="Usage"
+
+    # Uninstall
+    ["uninstall_confirm"]="This will remove Sub2API from your system."
+    ["are_you_sure"]="Are you sure? (y/N)"
+    ["uninstall_cancelled"]="Uninstall cancelled"
+    ["removing_files"]="Removing files..."
+    ["removing_install_dir"]="Removing installation directory..."
+    ["removing_user"]="Removing user..."
+    ["config_not_removed"]="Config directory was NOT removed."
+    ["remove_manually"]="Remove it manually if you no longer need it."
+    ["removing_install_lock"]="Removing install lock file..."
+    ["install_lock_removed"]="Install lock removed. Setup wizard will appear on next install."
+    ["purge_prompt"]="Also remove config directory? This will delete all config and data [y/N]: "
+    ["removing_config_dir"]="Removing config directory..."
+    ["uninstall_complete"]="Sub2API has been uninstalled"
+
+    # Help
+    ["usage"]="Usage"
+    ["cmd_none"]="(none)"
+    ["cmd_install"]="Install Sub2API"
+    ["cmd_upgrade"]="Upgrade to the latest version"
+    ["cmd_uninstall"]="Remove Sub2API"
+    ["cmd_install_version"]="Install/rollback to a specific version"
+    ["cmd_list_versions"]="List available versions"
+    ["opt_version"]="Specify version to install (e.g., v1.0.0)"
+
+    # Server configuration
+    ["server_config_title"]="Server Configuration"
+    ["server_config_desc"]="Configure Sub2API server listen address"
+    ["server_host_prompt"]="Server listen address"
+    ["server_host_hint"]="0.0.0.0 listens on all interfaces, 127.0.0.1 for local only"
+    ["server_port_prompt"]="Server port"
+    ["server_port_hint"]="Recommended range: 1024-65535"
+    ["server_config_summary"]="Server configuration"
+    ["invalid_port"]="Invalid port number, please enter a number between 1-65535"
+
+    # Service management
+    ["starting_service"]="Starting service..."
+    ["service_started"]="Service started"
+    ["service_start_failed"]="Service failed to start, please check logs"
+    ["enabling_autostart"]="Enabling auto-start on boot..."
+    ["autostart_enabled"]="Auto-start enabled"
+    ["getting_public_ip"]="Getting public IP..."
+    ["public_ip_failed"]="Failed to get public IP, using local IP"
+)
+
+# Get message based on current language
+msg() {
+    local key="$1"
+    if [ "$LANG_CHOICE" = "en" ]; then
+        echo "${MSG_EN[$key]}"
+    else
+        echo "${MSG_ZH[$key]}"
+    fi
+}
+
+# Print functions
+print_info() {
+    echo -e "${BLUE}[$(msg 'info')]${NC} $1"
+}
+
+print_success() {
+    echo -e "${GREEN}[$(msg 'success')]${NC} $1"
+}
+
+print_warning() {
+    echo -e "${YELLOW}[$(msg 'warning')]${NC} $1"
+}
+
+print_error() {
+    echo -e "${RED}[$(msg 'error')]${NC} $1"
+}
+
+# Check if running interactively (can access terminal)
+# When piped (curl | bash), stdin is not a terminal, but /dev/tty may still be available
+is_interactive() {
+    # Check if /dev/tty is available (works even when piped)
+    [ -e /dev/tty ] && [ -r /dev/tty ] && [ -w /dev/tty ]
+}
+
+# Select language
+select_language() {
+    # If not interactive (piped), use default language
+    if ! is_interactive; then
+        LANG_CHOICE="zh"
+        return
+    fi
+
+    echo ""
+    echo -e "${CYAN}=============================================="
+    echo "  $(msg 'select_lang')"
+    echo "==============================================${NC}"
+    echo ""
+    echo "  1) $(msg 'lang_zh') (默认/default)"
+    echo "  2) $(msg 'lang_en')"
+    echo ""
+
+    read -p "$(msg 'enter_choice'): " lang_input < /dev/tty
+
+    case "$lang_input" in
+        2|en|EN|english|English)
+            LANG_CHOICE="en"
+            ;;
+        *)
+            LANG_CHOICE="zh"
+            ;;
+    esac
+
+    echo ""
+}
+
+# Validate port number
+validate_port() {
+    local port="$1"
+    if [[ "$port" =~ ^[0-9]+$ ]] && [ "$port" -ge 1 ] && [ "$port" -le 65535 ]; then
+        return 0
+    fi
+    return 1
+}
+
+# Configure server settings
+configure_server() {
+    # If not interactive (piped), use default settings
+    if ! is_interactive; then
+        print_info "$(msg 'server_config_summary'): ${SERVER_HOST}:${SERVER_PORT} (default)"
+        return
+    fi
+
+    echo ""
+    echo -e "${CYAN}=============================================="
+    echo "  $(msg 'server_config_title')"
+    echo "==============================================${NC}"
+    echo ""
+    echo -e "${BLUE}$(msg 'server_config_desc')${NC}"
+    echo ""
+
+    # Server host
+    echo -e "${YELLOW}$(msg 'server_host_hint')${NC}"
+    read -p "$(msg 'server_host_prompt') [${SERVER_HOST}]: " input_host < /dev/tty
+    if [ -n "$input_host" ]; then
+        SERVER_HOST="$input_host"
+    fi
+
+    echo ""
+
+    # Server port
+    echo -e "${YELLOW}$(msg 'server_port_hint')${NC}"
+    while true; do
+        read -p "$(msg 'server_port_prompt') [${SERVER_PORT}]: " input_port < /dev/tty
+        if [ -z "$input_port" ]; then
+            # Use default
+            break
+        elif validate_port "$input_port"; then
+            SERVER_PORT="$input_port"
+            break
+        else
+            print_error "$(msg 'invalid_port')"
+        fi
+    done
+
+    echo ""
+    print_info "$(msg 'server_config_summary'): ${SERVER_HOST}:${SERVER_PORT}"
+    echo ""
+}
+
+# Check if running as root
+check_root() {
+    # Use 'id -u' instead of $EUID for better compatibility
+    # $EUID may not work reliably when script is piped to bash
+    if [ "$(id -u)" -ne 0 ]; then
+        print_error "$(msg 'run_as_root')"
+        exit 1
+    fi
+}
+
+# Detect OS and architecture
+detect_platform() {
+    OS=$(uname -s | tr '[:upper:]' '[:lower:]')
+    ARCH=$(uname -m)
+
+    case "$ARCH" in
+        x86_64)
+            ARCH="amd64"
+            ;;
+        aarch64|arm64)
+            ARCH="arm64"
+            ;;
+        *)
+            print_error "$(msg 'unsupported_arch'): $ARCH"
+            exit 1
+            ;;
+    esac
+
+    case "$OS" in
+        linux)
+            OS="linux"
+            ;;
+        darwin)
+            OS="darwin"
+            ;;
+        *)
+            print_error "$(msg 'unsupported_os'): $OS"
+            exit 1
+            ;;
+    esac
+
+    print_info "$(msg 'detected_platform'): ${OS}_${ARCH}"
+}
+
+# Check dependencies
+check_dependencies() {
+    local missing=()
+
+    if ! command -v curl &> /dev/null; then
+        missing+=("curl")
+    fi
+
+    if ! command -v tar &> /dev/null; then
+        missing+=("tar")
+    fi
+
+    if [ ${#missing[@]} -gt 0 ]; then
+        print_error "$(msg 'missing_deps'): ${missing[*]}"
+        print_info "$(msg 'install_deps_first')"
+        exit 1
+    fi
+}
+
+# Authenticate only GitHub REST API requests. Release asset downloads must stay anonymous.
+github_api_curl() {
+    local arg
+    local expect_value=false
+    local url
+
+    if [ "$#" -lt 1 ]; then
+        echo "github_api_curl requires exactly one GitHub API URL" >&2
+        return 2
+    fi
+    url="${!#}"
+
+    # Keep authenticated invocations constrained to the options used below. In
+    # particular, curl config, --url, and --next could add another destination.
+    for arg in "${@:1:$#-1}"; do
+        if [ "$expect_value" = true ]; then
+            expect_value=false
+            continue
+        fi
+        case "$arg" in
+            -s|--silent)
+                ;;
+            --connect-timeout|--max-time|-o|--output|-w|--write-out)
+                expect_value=true
+                ;;
+            *)
+                echo "Unsafe github_api_curl argument: $arg" >&2
+                return 2
+                ;;
+        esac
+    done
+
+    if [ "$expect_value" = true ] || [[ "$url" != https://api.github.com/* ]]; then
+        echo "github_api_curl requires exactly one GitHub API URL" >&2
+        return 2
+    fi
+
+    if [ -n "${UPDATE_GITHUB_TOKEN:-}" ]; then
+        if [[ "$UPDATE_GITHUB_TOKEN" == *$'\n'* || "$UPDATE_GITHUB_TOKEN" == *$'\r'* || "$UPDATE_GITHUB_TOKEN" == *'"'* || "$UPDATE_GITHUB_TOKEN" == *'\'* ]]; then
+            echo "UPDATE_GITHUB_TOKEN contains unsupported characters" >&2
+            return 2
+        fi
+        printf 'header = "Authorization: Bearer %s"\n' "$UPDATE_GITHUB_TOKEN" | UPDATE_GITHUB_TOKEN= GITHUB_TOKEN= GH_TOKEN= curl -q --globoff --config - "$@"
+    else
+        UPDATE_GITHUB_TOKEN= GITHUB_TOKEN= GH_TOKEN= curl -q --globoff "$@"
+    fi
+}
+
+# Get latest release version
+get_latest_version() {
+    print_info "$(msg 'fetching_version')"
+    LATEST_VERSION=$(github_api_curl -s --connect-timeout 10 --max-time 30 "https://api.github.com/repos/${GITHUB_REPO}/releases/latest" 2>/dev/null | grep '"tag_name"' | sed -E 's/.*"([^"]+)".*/\1/')
+
+    if [ -z "$LATEST_VERSION" ]; then
+        print_error "$(msg 'failed_get_version')"
+        print_info "Please check your network connection or try again later."
+        exit 1
+    fi
+
+    print_info "$(msg 'latest_version'): $LATEST_VERSION"
+}
+
+# List available versions
+list_versions() {
+    print_info "$(msg 'fetching_versions')"
+
+    local versions
+    versions=$(github_api_curl -s --connect-timeout 10 --max-time 30 "https://api.github.com/repos/${GITHUB_REPO}/releases" 2>/dev/null | grep '"tag_name"' | sed -E 's/.*"([^"]+)".*/\1/' | head -20)
+
+    if [ -z "$versions" ]; then
+        print_error "$(msg 'failed_get_version')"
+        print_info "Please check your network connection or try again later."
+        exit 1
+    fi
+
+    echo ""
+    echo "$(msg 'available_versions'):"
+    echo "----------------------------------------"
+    echo "$versions" | while read -r version; do
+        echo "  $version"
+    done
+    echo "----------------------------------------"
+    echo ""
+}
+
+# Validate if a version exists
+validate_version() {
+    local version="$1"
+
+    # Check for empty version
+    if [ -z "$version" ]; then
+        print_error "$(msg 'opt_version')" >&2
+        exit 1
+    fi
+
+    # Ensure version starts with 'v'
+    if [[ ! "$version" =~ ^v ]]; then
+        version="v$version"
+    fi
+
+    print_info "$(msg 'validating_version') $version" >&2
+
+    # Check if the release exists
+    local http_code
+    http_code=$(github_api_curl -s -o /dev/null -w "%{http_code}" --connect-timeout 10 --max-time 30 "https://api.github.com/repos/${GITHUB_REPO}/releases/tags/${version}" 2>/dev/null)
+
+    # Check for network errors (empty or non-numeric response)
+    if [ -z "$http_code" ] || ! [[ "$http_code" =~ ^[0-9]+$ ]]; then
+        print_error "Network error: Failed to connect to GitHub API" >&2
+        exit 1
+    fi
+
+    if [ "$http_code" != "200" ]; then
+        print_error "$(msg 'version_not_found'): $version" >&2
+        echo "" >&2
+        list_versions >&2
+        exit 1
+    fi
+
+    # Return the normalized version (to stdout)
+    echo "$version"
+}
+
+# Get current installed version
+get_current_version() {
+    if [ -f "$INSTALL_DIR/sub2api" ]; then
+        # Use grep -E for better compatibility (works on macOS and Linux)
+        "$INSTALL_DIR/sub2api" --version 2>/dev/null | grep -oE 'v?[0-9]+\.[0-9]+\.[0-9]+' | head -1 || echo "unknown"
+    else
+        echo "not_installed"
+    fi
+}
+
+# Download and extract
+download_and_extract() {
+    local version_num=${LATEST_VERSION#v}
+    local archive_name="sub2api_${version_num}_${OS}_${ARCH}.tar.gz"
+    local download_url="https://github.com/${GITHUB_REPO}/releases/download/${LATEST_VERSION}/${archive_name}"
+    local checksum_url="https://github.com/${GITHUB_REPO}/releases/download/${LATEST_VERSION}/checksums.txt"
+
+    print_info "$(msg 'downloading') ${archive_name}..."
+
+    # Create temp directory
+    TEMP_DIR=$(mktemp -d)
+    trap "rm -rf $TEMP_DIR" EXIT
+
+    # Download archive
+    if ! curl -sL "$download_url" -o "$TEMP_DIR/$archive_name"; then
+        print_error "$(msg 'download_failed')"
+        exit 1
+    fi
+
+    # Download and verify checksum
+    print_info "$(msg 'verifying_checksum')"
+    if curl -sL "$checksum_url" -o "$TEMP_DIR/checksums.txt" 2>/dev/null; then
+        local expected_checksum=$(grep "$archive_name" "$TEMP_DIR/checksums.txt" | awk '{print $1}')
+        local actual_checksum=$(sha256sum "$TEMP_DIR/$archive_name" | awk '{print $1}')
+
+        if [ "$expected_checksum" != "$actual_checksum" ]; then
+            print_error "$(msg 'checksum_failed')"
+            print_error "Expected: $expected_checksum"
+            print_error "Actual: $actual_checksum"
+            exit 1
+        fi
+        print_success "$(msg 'checksum_verified')"
+    else
+        print_warning "$(msg 'checksum_not_found')"
+    fi
+
+    # Extract
+    print_info "$(msg 'extracting')"
+    tar -xzf "$TEMP_DIR/$archive_name" -C "$TEMP_DIR"
+
+    # Create install directory
+    mkdir -p "$INSTALL_DIR"
+
+    # Copy binary
+    cp "$TEMP_DIR/sub2api" "$INSTALL_DIR/sub2api"
+    chmod +x "$INSTALL_DIR/sub2api"
+
+    # Copy deploy files if they exist in the archive
+    if [ -d "$TEMP_DIR/deploy" ]; then
+        cp -r "$TEMP_DIR/deploy/"* "$INSTALL_DIR/" 2>/dev/null || true
+    fi
+
+    print_success "$(msg 'binary_installed') $INSTALL_DIR/sub2api"
+}
+
+# Create system user
+create_user() {
+    if id "$SERVICE_USER" &>/dev/null; then
+        print_info "$(msg 'user_exists'): $SERVICE_USER"
+        # Fix: Ensure existing user has /bin/sh shell for sudo to work
+        # Previous versions used /bin/false which prevents sudo execution
+        local current_shell
+        current_shell=$(getent passwd "$SERVICE_USER" 2>/dev/null | cut -d: -f7)
+        if [ "$current_shell" = "/bin/false" ] || [ "$current_shell" = "/sbin/nologin" ]; then
+            print_info "Fixing user shell for sudo compatibility..."
+            if usermod -s /bin/sh "$SERVICE_USER" 2>/dev/null; then
+                print_success "User shell updated to /bin/sh"
+            else
+                print_warning "Failed to update user shell. Service restart may not work automatically."
+                print_warning "Manual fix: sudo usermod -s /bin/sh $SERVICE_USER"
+            fi
+        fi
+    else
+        print_info "$(msg 'creating_user') $SERVICE_USER..."
+        # Use /bin/sh instead of /bin/false to allow sudo execution
+        # The user still cannot login interactively (no password set)
+        useradd -r -s /bin/sh -d "$INSTALL_DIR" "$SERVICE_USER"
+        print_success "$(msg 'user_created')"
+    fi
+}
+
+# Setup directories and permissions
+setup_directories() {
+    print_info "$(msg 'setting_up_dirs')"
+
+    # Create directories
+    mkdir -p "$INSTALL_DIR"
+    mkdir -p "$INSTALL_DIR/data"
+    mkdir -p "$CONFIG_DIR"
+
+    # Set ownership
+    chown -R "$SERVICE_USER:$SERVICE_USER" "$INSTALL_DIR"
+    chown -R "$SERVICE_USER:$SERVICE_USER" "$CONFIG_DIR"
+
+    print_success "$(msg 'dirs_configured')"
+}
+
+# Install systemd service
+install_service() {
+    print_info "$(msg 'installing_service')"
+
+    # Create service file with configured host and port
+    cat > /etc/systemd/system/sub2api.service << EOF
+[Unit]
+Description=Sub2API - AI API Gateway Platform
+Documentation=https://github.com/Wei-Shaw/sub2api
+After=network.target postgresql.service redis.service
+Wants=postgresql.service redis.service
+
+[Service]
+Type=simple
+User=sub2api
+Group=sub2api
+WorkingDirectory=/opt/sub2api
+ExecStart=/opt/sub2api/sub2api
+Restart=always
+RestartSec=5
+StandardOutput=journal
+StandardError=journal
+SyslogIdentifier=sub2api
+
+# Security hardening
+NoNewPrivileges=true
+ProtectSystem=strict
+ProtectHome=true
+PrivateTmp=true
+ReadWritePaths=/opt/sub2api
+
+# Environment - Server configuration
+Environment=GIN_MODE=release
+Environment=SERVER_HOST=${SERVER_HOST}
+Environment=SERVER_PORT=${SERVER_PORT}
+
+[Install]
+WantedBy=multi-user.target
+EOF
+
+    # Reload systemd
+    systemctl daemon-reload
+
+    print_success "$(msg 'service_installed')"
+}
+
+# Prepare for setup wizard (no config file needed - setup wizard will create it)
+prepare_for_setup() {
+    print_success "$(msg 'ready_for_setup')"
+}
+
+# Get public IP address
+get_public_ip() {
+    print_info "$(msg 'getting_public_ip')"
+
+    # Try to get public IP from ipinfo.io
+    local response
+    response=$(curl -s --connect-timeout 5 --max-time 10 "https://ipinfo.io/json" 2>/dev/null)
+
+    if [ -n "$response" ]; then
+        # Extract IP from JSON response using grep and sed (no jq dependency)
+        PUBLIC_IP=$(echo "$response" | grep -o '"ip": *"[^"]*"' | sed 's/"ip": *"\([^"]*\)"/\1/')
+        if [ -n "$PUBLIC_IP" ]; then
+            print_success "Public IP: $PUBLIC_IP"
+            return 0
+        fi
+    fi
+
+    # Fallback to local IP
+    print_warning "$(msg 'public_ip_failed')"
+    PUBLIC_IP=$(hostname -I 2>/dev/null | awk '{print $1}' || echo "YOUR_SERVER_IP")
+    return 1
+}
+
+# Start service
+start_service() {
+    print_info "$(msg 'starting_service')"
+
+    if systemctl start sub2api; then
+        print_success "$(msg 'service_started')"
+        return 0
+    else
+        print_error "$(msg 'service_start_failed')"
+        print_info "sudo journalctl -u sub2api -n 50"
+        return 1
+    fi
+}
+
+# Enable service auto-start
+enable_autostart() {
+    print_info "$(msg 'enabling_autostart')"
+
+    if systemctl enable sub2api 2>/dev/null; then
+        print_success "$(msg 'autostart_enabled')"
+        return 0
+    else
+        print_warning "Failed to enable auto-start"
+        return 1
+    fi
+}
+
+# Print completion message
+print_completion() {
+    # Use PUBLIC_IP which was set by get_public_ip()
+    # Determine display address
+    local display_host="${PUBLIC_IP:-YOUR_SERVER_IP}"
+    if [ "$SERVER_HOST" = "127.0.0.1" ]; then
+        display_host="127.0.0.1"
+    fi
+
+    echo ""
+    echo "=============================================="
+    print_success "$(msg 'install_complete')"
+    echo "=============================================="
+    echo ""
+    echo "$(msg 'install_dir'): $INSTALL_DIR"
+    echo "$(msg 'server_config_summary'): ${SERVER_HOST}:${SERVER_PORT}"
+    echo ""
+    echo "=============================================="
+    echo "  $(msg 'step4_open_wizard')"
+    echo "=============================================="
+    echo ""
+    print_info "     http://${display_host}:${SERVER_PORT}"
+    echo ""
+    echo "     $(msg 'wizard_guide')"
+    echo "     - $(msg 'wizard_db')"
+    echo "     - $(msg 'wizard_redis')"
+    echo "     - $(msg 'wizard_admin')"
+    echo ""
+    echo "=============================================="
+    echo "  $(msg 'useful_commands')"
+    echo "=============================================="
+    echo ""
+    echo "  $(msg 'cmd_status'):   sudo systemctl status sub2api"
+    echo "  $(msg 'cmd_logs'):     sudo journalctl -u sub2api -f"
+    echo "  $(msg 'cmd_restart'):  sudo systemctl restart sub2api"
+    echo "  $(msg 'cmd_stop'):     sudo systemctl stop sub2api"
+    echo ""
+    echo "=============================================="
+}
+
+# Upgrade function
+upgrade() {
+    # Check if Sub2API is installed
+    if [ ! -f "$INSTALL_DIR/sub2api" ]; then
+        print_error "$(msg 'not_installed')"
+        print_info "$(msg 'fresh_install_hint'): $0 install"
+        exit 1
+    fi
+
+    print_info "$(msg 'upgrading')"
+
+    # Get current version
+    CURRENT_VERSION=$("$INSTALL_DIR/sub2api" --version 2>/dev/null | grep -oE 'v?[0-9]+\.[0-9]+\.[0-9]+' || echo "unknown")
+    print_info "$(msg 'current_version'): $CURRENT_VERSION"
+
+    # Stop service
+    if systemctl is-active --quiet sub2api; then
+        print_info "$(msg 'stopping_service')"
+        systemctl stop sub2api
+    fi
+
+    # Backup current binary
+    cp "$INSTALL_DIR/sub2api" "$INSTALL_DIR/sub2api.backup"
+    print_info "$(msg 'backup_created'): $INSTALL_DIR/sub2api.backup"
+
+    # Download and install new version
+    get_latest_version
+    download_and_extract
+
+    # Set permissions
+    chown "$SERVICE_USER:$SERVICE_USER" "$INSTALL_DIR/sub2api"
+
+    # Start service
+    print_info "$(msg 'starting_service')"
+    systemctl start sub2api
+
+    print_success "$(msg 'upgrade_complete')"
+}
+
+# Install specific version (for upgrade or rollback)
+# Requires: Sub2API must already be installed
+install_version() {
+    local target_version="$1"
+
+    # Check if Sub2API is installed
+    if [ ! -f "$INSTALL_DIR/sub2api" ]; then
+        print_error "$(msg 'not_installed')"
+        print_info "$(msg 'fresh_install_hint'): $0 install -v $target_version"
+        exit 1
+    fi
+
+    # Validate and normalize version
+    target_version=$(validate_version "$target_version")
+
+    print_info "$(msg 'installing_version'): $target_version"
+
+    # Get current version
+    local current_version
+    current_version=$(get_current_version)
+    print_info "$(msg 'current_version'): $current_version"
+
+    # Check if same version
+    if [ "$current_version" = "$target_version" ] || [ "$current_version" = "${target_version#v}" ]; then
+        print_warning "$(msg 'same_version')"
+        exit 0
+    fi
+
+    # Stop service if running
+    if systemctl is-active --quiet sub2api; then
+        print_info "$(msg 'stopping_service')"
+        systemctl stop sub2api
+    fi
+
+    # Backup current binary (for potential recovery)
+    if [ -f "$INSTALL_DIR/sub2api" ]; then
+        local backup_name
+        if [ "$current_version" != "unknown" ] && [ "$current_version" != "not_installed" ]; then
+            backup_name="sub2api.backup.${current_version}"
+        else
+            backup_name="sub2api.backup.$(date +%Y%m%d%H%M%S)"
+        fi
+        cp "$INSTALL_DIR/sub2api" "$INSTALL_DIR/$backup_name"
+        print_info "$(msg 'backup_created'): $INSTALL_DIR/$backup_name"
+    fi
+
+    # Set LATEST_VERSION to the target version for download_and_extract
+    LATEST_VERSION="$target_version"
+
+    # Download and install
+    download_and_extract
+
+    # Set permissions
+    chown "$SERVICE_USER:$SERVICE_USER" "$INSTALL_DIR/sub2api"
+
+    # Start service
+    print_info "$(msg 'starting_service')"
+    if systemctl start sub2api; then
+        print_success "$(msg 'service_started')"
+    else
+        print_error "$(msg 'service_start_failed')"
+        print_info "sudo journalctl -u sub2api -n 50"
+    fi
+
+    # Print completion message
+    local new_version
+    new_version=$(get_current_version)
+    echo ""
+    echo "=============================================="
+    print_success "$(msg 'install_version_complete')"
+    echo "=============================================="
+    echo ""
+    echo "  $(msg 'current_version'): $new_version"
+    echo ""
+}
+
+# Uninstall function
+uninstall() {
+    print_warning "$(msg 'uninstall_confirm')"
+
+    # If not interactive (piped), require -y flag or skip confirmation
+    if ! is_interactive; then
+        if [ "${FORCE_YES:-}" != "true" ]; then
+            print_error "Non-interactive mode detected. Use 'curl ... | bash -s -- uninstall -y' to confirm."
+            exit 1
+        fi
+    else
+        read -p "$(msg 'are_you_sure') " -n 1 -r < /dev/tty
+        echo
+        if [[ ! $REPLY =~ ^[Yy]$ ]]; then
+            print_info "$(msg 'uninstall_cancelled')"
+            exit 0
+        fi
+    fi
+
+    print_info "$(msg 'stopping_service')"
+    systemctl stop sub2api 2>/dev/null || true
+    systemctl disable sub2api 2>/dev/null || true
+
+    print_info "$(msg 'removing_files')"
+    rm -f /etc/systemd/system/sub2api.service
+    systemctl daemon-reload
+
+    print_info "$(msg 'removing_install_dir')"
+    rm -rf "$INSTALL_DIR"
+
+    print_info "$(msg 'removing_user')"
+    userdel "$SERVICE_USER" 2>/dev/null || true
+
+    # Remove install lock file (.installed) to allow fresh setup on reinstall
+    print_info "$(msg 'removing_install_lock')"
+    rm -f "$CONFIG_DIR/.installed" 2>/dev/null || true
+    rm -f "$INSTALL_DIR/.installed" 2>/dev/null || true
+    print_success "$(msg 'install_lock_removed')"
+
+    # Ask about config directory removal (interactive mode only)
+    local remove_config=false
+    if [ "${PURGE:-}" = "true" ]; then
+        remove_config=true
+    elif is_interactive; then
+        read -p "$(msg 'purge_prompt')" -n 1 -r < /dev/tty
+        echo
+        if [[ $REPLY =~ ^[Yy]$ ]]; then
+            remove_config=true
+        fi
+    fi
+
+    if [ "$remove_config" = true ]; then
+        print_info "$(msg 'removing_config_dir')"
+        rm -rf "$CONFIG_DIR"
+    else
+        print_warning "$(msg 'config_not_removed'): $CONFIG_DIR"
+        print_warning "$(msg 'remove_manually')"
+    fi
+
+    print_success "$(msg 'uninstall_complete')"
+}
+
+# Main
+main() {
+    # Parse flags first
+    local target_version=""
+    local positional_args=()
+
+    while [[ $# -gt 0 ]]; do
+        case "$1" in
+            -y|--yes)
+                FORCE_YES="true"
+                shift
+                ;;
+            --purge)
+                PURGE="true"
+                shift
+                ;;
+            -v|--version)
+                if [ -n "${2:-}" ] && [[ ! "$2" =~ ^- ]]; then
+                    target_version="$2"
+                    shift 2
+                else
+                    echo "Error: --version requires a version argument"
+                    exit 1
+                fi
+                ;;
+            --version=*)
+                target_version="${1#*=}"
+                if [ -z "$target_version" ]; then
+                    echo "Error: --version requires a version argument"
+                    exit 1
+                fi
+                shift
+                ;;
+            *)
+                positional_args+=("$1")
+                shift
+                ;;
+        esac
+    done
+
+    # Restore positional arguments
+    set -- "${positional_args[@]}"
+
+    # Select language first
+    select_language
+
+    echo ""
+    echo "=============================================="
+    echo "       $(msg 'install_title')"
+    echo "=============================================="
+    echo ""
+
+    # Parse commands
+    case "${1:-}" in
+        upgrade|update)
+            check_root
+            detect_platform
+            check_dependencies
+            if [ -n "$target_version" ]; then
+                # Upgrade to specific version
+                install_version "$target_version"
+            else
+                # Upgrade to latest
+                upgrade
+            fi
+            exit 0
+            ;;
+        install)
+            # Install with optional version
+            check_root
+            detect_platform
+            check_dependencies
+            if [ -n "$target_version" ]; then
+                # Install specific version (fresh install or rollback)
+                if [ -f "$INSTALL_DIR/sub2api" ]; then
+                    # Already installed, treat as version change
+                    install_version "$target_version"
+                else
+                    # Fresh install with specific version
+                    configure_server
+                    LATEST_VERSION=$(validate_version "$target_version")
+                    download_and_extract
+                    create_user
+                    setup_directories
+                    install_service
+                    prepare_for_setup
+                    get_public_ip
+                    start_service
+                    enable_autostart
+                    print_completion
+                fi
+            else
+                # Fresh install with latest version
+                configure_server
+                get_latest_version
+                download_and_extract
+                create_user
+                setup_directories
+                install_service
+                prepare_for_setup
+                get_public_ip
+                start_service
+                enable_autostart
+                print_completion
+            fi
+            exit 0
+            ;;
+        rollback)
+            # Rollback to a specific version (alias for install with version)
+            if [ -z "$target_version" ] && [ -n "${2:-}" ]; then
+                target_version="$2"
+            fi
+            if [ -z "$target_version" ]; then
+                print_error "$(msg 'opt_version')"
+                echo ""
+                echo "Usage: $0 rollback -v <version>"
+                echo "       $0 rollback <version>"
+                echo ""
+                list_versions
+                exit 1
+            fi
+            check_root
+            detect_platform
+            check_dependencies
+            install_version "$target_version"
+            exit 0
+            ;;
+        list-versions|versions)
+            list_versions
+            exit 0
+            ;;
+        uninstall|remove)
+            check_root
+            uninstall
+            exit 0
+            ;;
+        --help|-h)
+            echo "$(msg 'usage'): $0 [command] [options]"
+            echo ""
+            echo "Commands:"
+            echo "  $(msg 'cmd_none')            $(msg 'cmd_install')"
+            echo "  install              $(msg 'cmd_install')"
+            echo "  upgrade              $(msg 'cmd_upgrade')"
+            echo "  rollback <version>   $(msg 'cmd_install_version')"
+            echo "  list-versions        $(msg 'cmd_list_versions')"
+            echo "  uninstall            $(msg 'cmd_uninstall')"
+            echo ""
+            echo "Options:"
+            echo "  -v, --version <ver>  $(msg 'opt_version')"
+            echo "  -y, --yes            Skip confirmation prompts (for uninstall)"
+            echo ""
+            echo "Examples:"
+            echo "  $0                        # Install latest version"
+            echo "  $0 install -v v0.1.0      # Install specific version"
+            echo "  $0 upgrade                # Upgrade to latest"
+            echo "  $0 upgrade -v v0.2.0      # Upgrade to specific version"
+            echo "  $0 rollback v0.1.0        # Rollback to v0.1.0"
+            echo "  $0 list-versions          # List available versions"
+            echo ""
+            exit 0
+            ;;
+    esac
+
+    # Default: Fresh install with latest version
+    check_root
+    detect_platform
+    check_dependencies
+
+    if [ -n "$target_version" ]; then
+        # Install specific version
+        if [ -f "$INSTALL_DIR/sub2api" ]; then
+            install_version "$target_version"
+        else
+            configure_server
+            LATEST_VERSION=$(validate_version "$target_version")
+            download_and_extract
+            create_user
+            setup_directories
+            install_service
+            prepare_for_setup
+            get_public_ip
+            start_service
+            enable_autostart
+            print_completion
+        fi
+    else
+        # Install latest version
+        configure_server
+        get_latest_version
+        download_and_extract
+        create_user
+        setup_directories
+        install_service
+        prepare_for_setup
+        get_public_ip
+        start_service
+        enable_autostart
+        print_completion
+    fi
+}
+
+main "$@"
diff --git a/ops/auto_proxy.py b/ops/auto_proxy.py
new file mode 100644
index 0000000..c6d6de5
--- /dev/null
+++ b/ops/auto_proxy.py
@@ -0,0 +1,395 @@
+"""统一路由（自动匹配）代理：127.0.0.1:8093，仅处理绑定「统一路由」分组的 Key 发往不带分组路径的请求。
+
+流程：识别协议与模型 → 按索引（Nexus 官方顺序，原生模型优先、别名兜底）列出候选分组 →
+逐个经路由鉴权（route_auth /auth，校验原 Key 的额度/IP/分组授权并取得该分组子 Key）→ 转发给 sub2api。
+只在请求确定未被执行时换下一个候选分组：连接未建立、拒绝该客户端（403）、限流（429）、
+无可用账号或过载（503/529）、未连上源站（522）、明确不支持该模型。开始发送后结果未知（写入/读响应异常）
+或可能已在上游执行的错误（500/502/504/520/524）不重发，避免重复生成与重复扣费，直接返回给客户端。
+原 Key 自身的限制（额度、IP、Key 无效）直接返回。发生切换或结果未知时把尝试路径写入日志
+（/var/log/sub2api-ops/auto_proxy.log），响应头 X-S2A-Route-Attempts 同样带上，便于账单核对。
+扣费发生在命中的真实分组（按该分组倍率），统一路由分组本身不定价。
+索引：/opt/sub2api/ops/auto_route_index.json（gen_auto_index.py 每小时生成）。
+"""
+
+import json
+import os
+import re
+import sys
+import http.client
+import threading
+from datetime import datetime, timedelta, timezone
+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
+
+INDEX = "/opt/sub2api/ops/auto_route_index.json"
+ROUTE_IP = "127.0.0.2"  # 与路由鉴权的映射 Key IP 白名单一致
+# 这些状态表示请求未被执行，可安全换分组；500/502/504/520/524 可能已在上游执行，不在此列
+RETRY_STATUS = {403, 429, 503, 522, 529}
+BJ = timezone(timedelta(hours=8))
+HOP = {
+    "connection",
+    "keep-alive",
+    "proxy-authenticate",
+    "proxy-authorization",
+    "te",
+    "trailers",
+    "transfer-encoding",
+    "upgrade",
+    "content-length",
+    "host",
+}
+AUTH_HEADERS = {"authorization", "x-api-key", "x-goog-api-key"}
+# 上游明确表示「该分组不支持此模型 / 此端点」的 400/404，也换下一个分组（其他 400 如参数错误直接返回）
+UNSUPPORTED = (
+    "没有可用的渠道支持该模型",
+    "not supported by any configured account",
+    "model_not_found",
+    "model not found",
+    "unsupported model",
+    "No available accounts",
+    "endpoint_not_supported",  # 上游分组不开放该协议端点（如 gemini_1 不支持 /messages）
+)
+GEMINI_RE = re.compile(r"^/v1beta/models/([^/:]+):")
+DENY = {  # 路由鉴权拒绝原因 → 对外状态码与说明；group/notfound 表示该分组不可用，换下一个
+    "quota": (429, "rate_limit_error", "API key quota or rate limit exceeded"),
+    "ip": (403, "permission_error", "Client IP not allowed for this API key"),
+    "key_disabled": (403, "permission_error", "API key disabled for this group"),
+    "unavailable": (503, "api_error", "Route service unavailable, please retry"),
+}
+
+_index, _mtime, _lock = {}, 0.0, threading.Lock()
+
+
+def index():
+    global _index, _mtime
+    try:
+        m = os.path.getmtime(INDEX)
+    except OSError:
+        return _index
+    if m != _mtime:
+        with _lock:
+            _index, _mtime = json.load(open(INDEX)), m
+    return _index
+
+
+def protocol_of(path):
+    if path.startswith("/v1beta/"):
+        return "gemini"
+    if path.startswith("/v1/messages"):
+        return "anthropic"
+    return "openai"
+
+
+def candidates(plat, model):
+    idx = index()
+    native = [
+        g
+        for g in idx.get("groups", [])
+        if model in g["protocols"].get(plat, {}).get("native", [])
+    ]
+    alias = [
+        g
+        for g in idx.get("groups", [])
+        if model in g["protocols"].get(plat, {}).get("alias", [])
+    ]
+    if not idx.get("prefer_native", True):  # 不区分原生/别名：严格按官方顺序
+        order = [g["slug"] for g in idx.get("groups", [])]
+        return sorted(native + alias, key=lambda g: order.index(g["slug"]))
+    return native + alias
+
+
+def model_list(plat):
+    seen = []
+    for g in index().get("groups", []):
+        p = g["protocols"].get(plat, {})
+        for m in p.get("native", []) + p.get("alias", []):
+            if m not in seen:
+                seen.append(m)
+    return seen
+
+
+def body_model(body, ctype):
+    if not body:
+        return ""
+    if "multipart/form-data" in (ctype or ""):
+        m = re.search(rb'name="model"\r\n\r\n([^\r\n]+)', body)
+        return m.group(1).decode(errors="ignore").strip() if m else ""
+    try:
+        return str(json.loads(body).get("model") or "").strip()
+    except (ValueError, AttributeError):
+        return ""
+
+
+class Handler(BaseHTTPRequestHandler):
+    protocol_version = "HTTP/1.1"
+
+    def log_message(self, fmt, *args):  # 不记录含 Key 的请求行
+        pass
+
+    # ---------- 工具 ----------
+    def read_body(self):
+        if self.headers.get("Transfer-Encoding", "").lower() == "chunked":
+            data = b""
+            while True:
+                size = int(self.rfile.readline().split(b";")[0].strip() or b"0", 16)
+                if size == 0:
+                    while self.rfile.readline() not in (b"\r\n", b"\n", b""):
+                        pass
+                    return data
+                data += self.rfile.read(size)
+                self.rfile.readline()
+        n = int(self.headers.get("Content-Length") or 0)
+        return self.rfile.read(n) if n else b""
+
+    def send_json(self, code, obj, extra=None):
+        data = json.dumps(obj, ensure_ascii=False).encode()
+        self.send_response(code)
+        self.send_header("Content-Type", "application/json")
+        self.send_header("Content-Length", str(len(data)))
+        for k, v in (extra or {}).items():
+            self.send_header(k, v)
+        self.send_header("Connection", "close")
+        self.end_headers()
+        self.wfile.write(data)
+        self.close_connection = True
+
+    def error(self, code, typ, msg, extra=None):
+        self.send_json(code, {"error": {"type": typ, "message": msg}}, extra)
+
+    def trace(self, model, final):
+        """记录候选尝试路径（不含 Key 与查询串）；只在切换过分组或结果未知时写日志。"""
+        if len(self.attempts) > 1 or final == "unknown":
+            print(
+                f"{datetime.now(BJ):%F %T} {self.command} {self.path.partition('?')[0]} "
+                f"model={model} attempts={','.join(self.attempts)} final={final}",
+                file=sys.stderr,
+                flush=True,
+            )
+        return ",".join(self.attempts)
+
+    def route(self, slug, query):
+        """调用路由鉴权取得该分组子 Key。返回 (状态, 映射 Key 或拒绝原因, 映射查询串)。"""
+        c = http.client.HTTPConnection("127.0.0.1", 8091, timeout=15)
+        h = {
+            "X-Route-Group": slug,
+            "X-Original-Args": query,
+            "X-Client-IP": self.headers.get("X-Real-IP", ""),
+        }
+        for k in ("Authorization", "x-api-key", "x-goog-api-key"):
+            if self.headers.get(k):
+                h[k] = self.headers[k]
+        try:
+            c.request("GET", "/auth", headers=h)
+            r = c.getresponse()
+            r.read()
+            if r.status == 200:
+                return (
+                    200,
+                    r.getheader("X-Mapped-Key"),
+                    r.getheader("X-Mapped-Query") or "",
+                )
+            return r.status, r.getheader("X-Route-Reason") or "", ""
+        except (
+            OSError,
+            http.client.HTTPException,
+        ):  # 路由鉴权不可用：返回 503，不让处理线程异常断开
+            return 503, "unavailable", ""
+        finally:
+            c.close()
+
+    # ---------- 主流程 ----------
+    def handle_any(self):
+        if self.headers.get("Upgrade", "").lower() == "websocket":
+            return self.error(
+                400,
+                "invalid_request_error",
+                "统一路由暂不支持 WebSocket，请改用 HTTP 或分组地址 /api/<分组>",
+            )
+        path, _, query = self.path.partition("?")
+        if path == "/__health":  # 守护脚本健康检查
+            return self.send_json(
+                200, {"status": "ok", "groups": len(index().get("groups", []))}
+            )
+        plat = protocol_of(path)
+        body = self.read_body() if self.command in ("POST", "PUT", "PATCH") else b""
+
+        # 模型列表：返回统一路由可用的全部模型
+        if self.command == "GET" and path.rstrip("/") in (
+            "/v1/models",
+            "/v1beta/models",
+        ):
+            models = model_list("gemini" if path.startswith("/v1beta") else plat)
+            if path.startswith("/v1beta"):
+                return self.send_json(
+                    200,
+                    {
+                        "models": [
+                            {"name": f"models/{m}", "displayName": m} for m in models
+                        ]
+                    },
+                )
+            return self.send_json(
+                200,
+                {
+                    "object": "list",
+                    "has_more": False,
+                    "data": [
+                        {
+                            "id": m,
+                            "object": "model",
+                            "type": "model",
+                            "display_name": m,
+                            "owned_by": "starnexus",
+                        }
+                        for m in models
+                    ],
+                },
+            )
+
+        gm = GEMINI_RE.match(path)
+        model = (
+            gm.group(1) if gm else body_model(body, self.headers.get("Content-Type"))
+        )
+        if not model:
+            return self.error(
+                400, "invalid_request_error", "统一路由需要在请求中指定 model"
+            )
+        cands = candidates(plat, model)
+        if not cands:
+            return self.error(
+                404,
+                "not_found_error",
+                f"统一路由：没有分组支持模型 {model}（{plat} 协议），请检查模型名或使用分组地址 /api/<分组>",
+            )
+
+        last, self.attempts = None, []
+        for i, g in enumerate(cands):
+            slug = g["slug"]
+            status, mapped, mq = self.route(slug, query)
+            if status == 401:
+                return self.error(401, "authentication_error", "Invalid API key")
+            if status != 200:
+                if mapped in DENY:
+                    return self.error(*DENY[mapped])
+                continue  # group / notfound：该分组对此 Key 不可用，换下一个
+            headers = {
+                k: v
+                for k, v in self.headers.items()
+                if k.lower() not in HOP | AUTH_HEADERS
+            }
+            if self.headers.get("x-goog-api-key"):
+                headers["x-goog-api-key"] = mapped
+            if self.headers.get("x-api-key"):
+                headers["x-api-key"] = mapped
+            headers["Authorization"] = f"Bearer {mapped}"
+            headers["Host"] = self.headers.get("Host", "")
+            headers["X-Forwarded-For"] = (
+                f"{self.headers.get('X-Real-IP', '')}, {ROUTE_IP}"
+            )
+            headers["Content-Length"] = str(len(body))
+            up = http.client.HTTPConnection("127.0.0.1", 8080, timeout=3600)
+            try:
+                up.connect()
+            except OSError:
+                # 连接未建立：一个字节都没发出，sub2api 不可能执行，可安全换下一个
+                up.close()
+                self.attempts.append(f"{slug}:connect_error")
+                last = (502, None)
+                continue
+            try:
+                up.request(self.command, path + mq, body=body or None, headers=headers)
+                resp = up.getresponse()
+            except (OSError, http.client.HTTPException) as e:
+                # 已开始发送后的任何异常：对端可能已接收并执行，不重发，交由客户端核对后决定
+                up.close()
+                self.attempts.append(f"{slug}:{type(e).__name__}")
+                trail = self.trace(model, "unknown")
+                return self.error(
+                    502,
+                    "api_error",
+                    f"统一路由：分组 {slug} 请求发送或响应读取失败，请求可能已执行，为避免重复扣费未自动重试；"
+                    "请先在用量记录中确认再决定是否重试",
+                    {"X-S2A-Routed-Group": slug, "X-S2A-Route-Attempts": trail},
+                )
+            self.attempts.append(f"{slug}:{resp.status}")
+            if resp.status in RETRY_STATUS and i < len(cands) - 1:
+                resp.read()
+                up.close()
+                last = (resp.status, slug)
+                continue
+            if resp.status in (400, 404) and i < len(cands) - 1:
+                data = resp.read()
+                up.close()
+                if any(
+                    m.lower() in data.decode(errors="ignore").lower()
+                    for m in UNSUPPORTED
+                ):
+                    last = (resp.status, slug)
+                    continue
+                return self.relay_bytes(resp, data, slug, self.trace(model, slug))
+            return self.relay(resp, up, slug, self.trace(model, slug))
+        code = last[0] if last else 503
+        self.trace(model, "none")
+        return self.error(
+            code if code >= 400 else 503,
+            "api_error",
+            f"统一路由：支持模型 {model} 的分组当前都不可用，请稍后重试",
+            {"X-S2A-Route-Attempts": ",".join(self.attempts)}
+            if self.attempts
+            else None,
+        )
+
+    def relay_bytes(self, resp, data, slug, trail):
+        """已读出的完整响应（非流式错误）原样返回。"""
+        self.send_response(resp.status)
+        for k, v in resp.getheaders():
+            if k.lower() not in HOP:
+                self.send_header(k, v)
+        self.send_header("X-S2A-Routed-Group", slug)
+        self.send_header("X-S2A-Route-Attempts", trail)
+        self.send_header("Content-Length", str(len(data)))
+        self.send_header("Connection", "close")
+        self.end_headers()
+        self.wfile.write(data)
+        self.close_connection = True
+
+    def relay(self, resp, up, slug, trail):
+        """把 sub2api 的响应原样（流式）回给客户端，并标注命中的分组与尝试路径。"""
+        try:
+            self.send_response(resp.status)
+            length = resp.getheader("Content-Length")
+            for k, v in resp.getheaders():
+                if k.lower() not in HOP:
+                    self.send_header(k, v)
+            self.send_header("X-S2A-Routed-Group", slug)
+            self.send_header("X-S2A-Route-Attempts", trail)
+            if length is not None:
+                self.send_header("Content-Length", length)
+            else:
+                self.send_header("Transfer-Encoding", "chunked")
+            self.send_header("Connection", "close")
+            self.end_headers()
+            while True:
+                chunk = resp.read1(65536)
+                if not chunk:
+                    break
+                if length is None:
+                    self.wfile.write(b"%x\r\n%s\r\n" % (len(chunk), chunk))
+                else:
+                    self.wfile.write(chunk)
+                self.wfile.flush()
+            if length is None:
+                self.wfile.write(b"0\r\n\r\n")
+                self.wfile.flush()
+        except (BrokenPipeError, ConnectionResetError):
+            pass
+        finally:
+            up.close()
+            self.close_connection = True
+
+    do_GET = do_POST = do_PUT = do_PATCH = do_DELETE = handle_any
+
+
+if __name__ == "__main__":
+    srv = ThreadingHTTPServer(("127.0.0.1", 8093), Handler)
+    srv.daemon_threads = True
+    srv.serve_forever()
diff --git a/ops/auto_route_config.json b/ops/auto_route_config.json
new file mode 100644
index 0000000..fd1ea43
--- /dev/null
+++ b/ops/auto_route_config.json
@@ -0,0 +1,11 @@
+{
+ "说明": "统一路由（自动匹配）设置。修改后到宝塔「计划任务」对「sub2api 统一路由：刷新匹配表」点「执行」立即生效（否则每小时整点自动生效）。",
+ "order_mode": "alphabet",
+ "order_mode_可选值": "alphabet = 按分组名称字母顺序（中文名排在英文之后）；nexus = 按 Nexus 官方分组顺序；custom = 按下方 custom_order",
+ "custom_order": ["codex_eco", "codex", "codex_pro", "codex_sp", "codex_image", "grok", "grok45", "mixed_cc_pro_max", "kiro", "office3_2", "cc_glm", "cc_glm_global", "deepseek", "cc_codex_56", "gemini_1"],
+ "custom_order_说明": "仅 order_mode = custom 时生效，填 Nexus 分组标识（slug），未列出的分组排在最后",
+ "prefer_native": true,
+ "prefer_native_说明": "true = 原生提供该模型的分组优先，把模型名映射成其他模型的分组（如 codex_eco 里的 claude-* 实为 GPT）排在后面兜底；false = 严格按上面的顺序",
+ "sync_group_list_order": true,
+ "sync_group_list_order_说明": "true = 后台/创建 Key 时的分组列表也按此顺序显示（统一路由固定第一）"
+}
diff --git a/ops/backup-restore-check.sh b/ops/backup-restore-check.sh
new file mode 100755
index 0000000..43bc415
--- /dev/null
+++ b/ops/backup-restore-check.sh
@@ -0,0 +1,98 @@
+#!/usr/bin/env bash
+# sub2api 数据库备份恢复演练（只读生产库）：
+#   1. 读取 sub2api 备份记录，取最新 completed 备份；--expect-scheduled 时要求它是今天的定时备份
+#   2. 从 R2 下载 → gzip 校验 → 恢复到临时库 sub2api_restore_check
+#   3. 比对表数量与关键表行数（备份行数应 >0 且 ≤ 当前生产库；usage_logs 可为 0），以及 s2a_ops 的表数、
+#      唯一索引、关键表行数与关联完整性，结果写日志
+#   4. 删除临时库与下载文件
+# 用法: backup-restore-check.sh [--expect-scheduled]   日志: /opt/sub2api/ops/backup_restore_check.log
+set -uo pipefail
+LOG=/opt/sub2api/ops/backup_restore_check.log
+exec >>"$LOG" 2>&1
+echo "==== $(date -Is) 开始"
+source /root/.config/sub2api-r2.env
+source /opt/sub2api/ops/lib.sh
+ops_lock
+BIN=/www/server/pgsql/bin
+DB=sub2api_restore_check
+WORK=$(mktemp -d /root/sub2api_restore_check.XXXX)
+cleanup() {
+	local rc=$?
+	$BIN/dropdb -h localhost -U postgres --if-exists "$DB"
+	rm -f -- "$WORK/backup.sql.gz" "$WORK/restore.log" && rmdir -- "$WORK"
+	if [ $rc -ne 0 ]; then # 失败时发表格邮件（成功不发，避免每日打扰）
+		python3 -I /opt/sub2api/ops/mail_report.py restore "$LOG" | python3 -I /opt/sub2api/ops/notify.py json ||
+			echo "失败通知邮件发送失败"
+	fi
+}
+trap cleanup EXIT
+
+read -r ID TRIGGER STARTED KEY < <(Q "select value from settings where key='backup_records'" | python3 -c "
+import json, sys
+from datetime import datetime
+rows = [r for r in json.load(sys.stdin) if r['status'] == 'completed']
+rows.sort(key=lambda r: datetime.fromisoformat(r['started_at']))
+r = rows[-1]
+print(r['id'], r.get('triggered_by'), r['started_at'], r['s3_key'])")
+echo "最新备份 $ID 触发=$TRIGGER 开始=$STARTED"
+if [ "${1:-}" = "--expect-scheduled" ]; then
+	today=$(TZ=Asia/Shanghai date +%F)
+	if [ "$TRIGGER" = manual ] || [ "${STARTED:0:10}" != "$today" ]; then
+		echo "失败：未发现今天（$today）的定时备份"
+		exit 1
+	fi
+fi
+
+curl -sS -m 300 --aws-sigv4 "aws:amz:auto:s3" \
+	-K <(printf 'user = "%s:%s"\n' "$R2_ACCESS_KEY_ID" "$R2_SECRET_ACCESS_KEY") \
+	-o "$WORK/backup.sql.gz" "${R2_ENDPOINT}/${R2_BUCKET}/$KEY" || {
+	echo "失败：下载 $KEY"
+	exit 1
+}
+gzip -t "$WORK/backup.sql.gz" || {
+	echo "失败：gzip 损坏"
+	exit 1
+}
+echo "下载完成 $(stat -c %s "$WORK/backup.sql.gz") 字节"
+
+$BIN/dropdb -h localhost -U postgres --if-exists "$DB"
+$BIN/createdb -h localhost -U postgres "$DB"
+gunzip -c "$WORK/backup.sql.gz" | $BIN/psql -h localhost -U postgres -d "$DB" -q >"$WORK/restore.log" 2>&1
+errors=$(grep -c ERROR "$WORK/restore.log")
+echo "恢复报错 $errors 行"
+grep -m3 ERROR "$WORK/restore.log"
+
+R() { $BIN/psql -h localhost -U postgres -d "$DB" -At -c "$1"; }
+ok=1
+tables_b=$(R "select count(*) from information_schema.tables where table_schema='public'")
+tables_p=$(Q "select count(*) from information_schema.tables where table_schema='public'")
+echo "表数 备份=$tables_b 生产=$tables_p"
+[ "$tables_b" = "$tables_p" ] || ok=0
+for t in users api_keys groups accounts channels channel_model_pricing usage_logs settings; do
+	b=$(R "select count(*) from $t") p=$(Q "select count(*) from $t")
+	echo "  $t 备份=$b 生产=$p"
+	# usage_logs 在早期备份中可能为空，只要求不超过生产库
+	{ { [ "$t" = usage_logs ] || [ "${b:-0}" -gt 0 ]; } && [ "${b:-0}" -le "$p" ]; } || ok=0
+done
+# 运维自建 schema s2a_ops（退款台账/请求、退款账号、父子 Key、分组元数据等）：表数、唯一索引、关键表行数与关联
+S2A="table_schema='s2a_ops'"
+UIX="schemaname='s2a_ops' and indexdef like 'CREATE UNIQUE%'"
+sb=$(R "select count(*) from information_schema.tables where $S2A") sp=$(Q "select count(*) from information_schema.tables where $S2A")
+ib=$(R "select count(*) from pg_indexes where $UIX") ip=$(Q "select count(*) from pg_indexes where $UIX")
+echo "s2a_ops 表数 备份=$sb 生产=$sp，唯一索引 备份=$ib 生产=$ip"
+{ [ "${sb:-0}" -gt 0 ] && [ "$sb" = "$sp" ] && [ "$ib" = "$ip" ]; } || ok=0
+for t in manual_refunds refund_users route_keys group_meta nexus_tags; do
+	b=$(R "select count(*) from s2a_ops.$t") p=$(Q "select count(*) from s2a_ops.$t")
+	echo "  s2a_ops.$t 备份=$b 生产=$p"
+	[ "${b:-0}" -gt 0 ] || ok=0
+	# 台账与退款账号只增不删（台账软删除、账号只停用），备份不应多于生产
+	case $t in manual_refunds | refund_users) [ "${b:-0}" -le "$p" ] || ok=0 ;; esac
+done
+orph=$(R "select (select count(*) from s2a_ops.manual_refunds m where not exists (select 1 from payment_orders o where o.id = m.order_id))
+         + (select count(*) from s2a_ops.route_keys r where not exists (select 1 from api_keys k where k.id = r.mapped_id)
+                                                        or not exists (select 1 from api_keys k where k.id = r.parent_id))")
+echo "  s2a_ops 关联缺失（台账→订单、子 Key→Key）=$orph"
+[ "$orph" = 0 ] || ok=0
+[ "$errors" -eq 0 ] || ok=0
+[ $ok = 1 ] && echo "结果：通过" || echo "结果：失败"
+[ $ok = 1 ]
diff --git a/ops/billing_audit.py b/ops/billing_audit.py
new file mode 100644
index 0000000..ce73331
--- /dev/null
+++ b/ops/billing_audit.py
@@ -0,0 +1,63 @@
+"""对账：sub2api usage_logs 与 Nexus key-logs 逐条比对原价（rawCost）。
+
+在 ssa 本机运行：python3 -I billing_audit.py <起始时间 UTC, 如 2026-10-10T13:00:00>
+环境变量 NEXUS_KEY、PGPASSWORD。按 (输出 token, 原价) 精确配对，再按 token 组合配对找出不一致。
+"""
+import json
+import os
+import subprocess
+import sys
+import urllib.request
+from collections import Counter
+
+since = sys.argv[1]
+N = os.environ["NEXUS_KEY"]
+
+
+def nexus_logs(limit_pages=20):
+    rows = []
+    for page in range(1, limit_pages + 1):
+        url = f"https://nexus.itssx.com/api-go/relay/key-logs?key={N}&pageNum={page}&pageSize=100"
+        d = json.load(urllib.request.urlopen(url, timeout=60))["data"]
+        batch = d.get("rows") or d.get("list") or d.get("records") or []
+        rows += batch
+        if len(batch) < 100 or (batch and batch[-1].get("requestTime", "") < since):
+            break
+    return [r for r in rows if r.get("requestTime", "") >= since]
+
+
+q = f"""select json_agg(json_build_object('id',u.id,'g',u.group_id,'plat',a.platform,'inb',u.inbound_endpoint,
+  'req',u.requested_model,'it',u.input_tokens,'ot',u.output_tokens,'cr',u.cache_read_tokens,
+  'cc',u.cache_creation_tokens,'cc1h',u.cache_creation_1h_tokens,'base',u.total_cost,'img',u.image_output_tokens)
+  order by u.id) from usage_logs u join accounts a on a.id=u.account_id
+  where u.created_at >= '{since}+00'"""
+s2 = json.loads(subprocess.run(["/www/server/pgsql/bin/psql", "-h", "localhost", "-U", "postgres", "-d", "sub2api",
+                                "-At", "-c", q], capture_output=True, text=True, check=True).stdout or "null") or []
+nx = nexus_logs()
+used = set()
+ok, mism, unmatched = [], [], []
+for u in s2:
+    hit = [i for i, r in enumerate(nx) if i not in used and r.get("outputTokens") == u["ot"]
+           and abs((r.get("rawCost") or 0) - u["base"]) < 1e-9]
+    if hit:
+        used.add(hit[0]); ok.append(u); continue
+    near = [i for i, r in enumerate(nx) if i not in used and r.get("outputTokens") == u["ot"]
+            and (r.get("inputTokens") or 0) + (r.get("cacheReadTokens") or 0) == u["it"] + u["cr"]]
+    if near:
+        i = near[0]; used.add(i); mism.append((u, nx[i]))
+    else:
+        unmatched.append(u)
+
+proto = lambda u: "Gemini" if u["inb"].startswith("/v1beta") else u["inb"]
+print(f"sub2api 请求 {len(s2)} 条，Nexus 记录 {len(nx)} 条（{since} 之后）")
+print(f"✅ 金额完全一致: {len(ok)}  按协议: {dict(Counter(proto(u) for u in ok))}")
+print(f"❌ 金额不一致: {len(mism)}")
+for u, r in mism:
+    print(f"   g{u['g']:<3}{proto(u):24}{u['req']:22} s2={u['base']:.6f} nexus={r.get('rawCost'):.6f} "
+          f"({u['base']/r['rawCost']:.2f}x) s2[in{u['it']} cr{u['cr']} cc{u['cc']}] nx[in{r.get('inputTokens')} "
+          f"cr{r.get('cacheReadTokens')} cw{r.get('cacheWriteTokens')}/{r.get('cacheWrite1hTokens')}] {r.get('model')}")
+print(f"? 未配对: {len(unmatched)}")
+for u in unmatched:
+    print(f"   g{u['g']:<3}{proto(u):24}{u['req']:22} s2={u['base']:.6f} in{u['it']} out{u['ot']} cr{u['cr']} cc{u['cc']}")
+left = [r for i, r in enumerate(nx) if i not in used]
+print(f"Nexus 有而 sub2api 无: {len(left)}（含直连 Nexus 的测试请求）")
diff --git a/ops/business.json b/ops/business.json
new file mode 100644
index 0000000..776da2c
--- /dev/null
+++ b/ops/business.json
@@ -0,0 +1,6 @@
+{
+ "说明": "经营参数（人民币/美元余额）：进价、客户最低充值单价、支付通道费率（易支付不按笔扣费，仅提现时收结算手续费，当前 0.1%，以提现页面显示为准；按实收计提，最低提现 100 元、T+1 只影响到账时间）。亏损告警、邮件毛利与经营日报都读取此文件。",
+ "buy_cny_per_usd": 0.28,
+ "sell_cny_per_usd_min": 0.32,
+ "pay_channel_fee_percent": 0.1
+}
diff --git a/ops/config-audit.sh b/ops/config-audit.sh
new file mode 100755
index 0000000..fbea0ca
--- /dev/null
+++ b/ops/config-audit.sh
@@ -0,0 +1,12 @@
+#!/usr/bin/env bash
+# 配置对账：Nexus 实时数据 vs sub2api 配置。业务配置只读；需临时管理员 Key 查询，加锁并在结束时恢复原值。
+set -euo pipefail
+source /root/.config/sub2api-nexus.env
+export NEXUS_KEY
+source /opt/sub2api/ops/lib.sh
+ops_lock
+with_admin_key
+tmpfile S2A_BINDINGS_REAL
+export S2A_BINDINGS_REAL
+export_bindings >"$S2A_BINDINGS_REAL"
+python3 -I /opt/sub2api/ops/config_audit.py
diff --git a/ops/config_audit.py b/ops/config_audit.py
new file mode 100644
index 0000000..bbbcbc9
--- /dev/null
+++ b/ops/config_audit.py
@@ -0,0 +1,295 @@
+"""配置对账：Nexus 实时数据 vs sub2api 当前配置（只读）。
+
+在 ssa 本机运行（由 config-audit.sh 注入 S2A_ADMIN_KEY / NEXUS_KEY）。
+检查：分组平台/售价倍率/图片价/开关、账号成本倍率/上游地址/池模式、账号白名单、组合路由、渠道单价（逐模型逐平台）。
+"""
+
+import json
+import os
+import sys
+
+sys.argv = [sys.argv[0]]  # nexus_sync 只在 --apply 时写入；这里复用其数据构建逻辑
+os.environ.setdefault("S2A_BINDINGS", "/dev/null")
+import importlib.util
+
+ADMIN = "http://127.0.0.1:8080/api/v1/admin"
+spec = importlib.util.spec_from_file_location("ns", "/opt/sub2api/ops/nexus_sync.py")
+src = open("/opt/sub2api/ops/nexus_sync.py").read()
+# 只取函数与常量定义，不执行同步主循环
+head = src.split("# ---------- 现状")[0]
+ns = {}
+exec(compile(head, "nexus_sync_head", "exec"), ns)
+ns["ACCOUNT_CONCURRENCY_EXPECTED"] = 50
+admin, nexus, GROUPS, ENDPOINTS = (
+    ns["admin"],
+    ns["nexus"],
+    ns["GROUPS"],
+    ns["ENDPOINTS"],
+)
+allowed, pricing, price_entry, as_list, family = (
+    ns["allowed"],
+    ns["pricing"],
+    ns["price_entry"],
+    ns["as_list"],
+    ns["family"],
+)
+tiers = {}
+kq = ns["kq"]
+for kg in kq["keyGroups"]:
+    for a in kg["aiGroups"]:
+        tiers.setdefault(a["id"], {})[kg["name"]] = float(
+            a.get("globalFallbackRatio") or 0
+        )
+
+bind = json.load(open(os.environ["S2A_BINDINGS_REAL"]))
+groups = {
+    g["id"]: g for g in admin("GET", "/groups?page=1&page_size=100").get("items", [])
+}
+channels = {}
+for c in admin("GET", "/channels?page=1&page_size=100").get("items", []):
+    full = admin("GET", f"/channels/{c['id']}")
+    for gid in full.get("group_ids") or []:
+        channels[gid] = full
+
+issues, checked = [], 0
+BIZ = json.load(open("/opt/sub2api/ops/business.json"))
+
+
+ISSUE_DATA = []  # 结构化问题（供邮件表格），kind: config / rate_change / loss / group
+fast_filter, flex_pass = (
+    set(),
+    set(),
+)  # Fast/Flex 策略应去除/放行的模型（与 nexus_sync 同规则）
+
+
+def bad(slug, msg, kind="config", **extra):
+    issues.append(f"{slug:16} {msg}")
+    ISSUE_DATA.append({"slug": slug, "kind": kind, "msg": msg, **extra})
+
+
+for slug in sorted(set(allowed) - set(GROUPS)):
+    bad(slug, "Nexus 新分组未接入（需人工）", kind="group")
+for slug, (gid, path) in GROUPS.items():
+    if slug not in allowed:
+        bad(slug, "Nexus 已不再提供该分组（需人工）", kind="group")
+        continue
+    g, ng = groups[gid], allowed[slug]
+    t = tiers[ng["id"]]
+    checked += 1
+    if g["platform"] != "composite":
+        bad(slug, f"平台 {g['platform']}")
+    if g.get("name") != ng["name"]:
+        bad(slug, f"名称「{g.get('name')}」≠ Nexus「{ng['name']}」")
+    if (g.get("description") or "") != (ng.get("noticeSummary") or ""):
+        bad(slug, f"备注与 Nexus 不一致（Nexus：{ng.get('noticeSummary') or '空'}）")
+    # 售价倍率跟随 Nexus 默认分组（普通用户）倍率：不一致即为差异，自动同步会改回
+    if abs(float(g["rate_multiplier"]) - t["默认分组"]) > 1e-9:
+        bad(
+            slug,
+            f"售价倍率 {float(g['rate_multiplier']):g} ≠ Nexus 普通 {t['默认分组']:g}",
+            kind="sell_rate",
+            old=float(g["rate_multiplier"]),
+            new=t["默认分组"],
+            cost=t["合作商"],
+        )
+    # 现金口径：客户按最低充值单价付费 vs 你按进价付 Nexus。售价倍率 × 最低单价 < 成本倍率 × 进价 才是真亏损
+    sell_rate = float(g["rate_multiplier"])
+    cash_margin = 1 - (BIZ["buy_cny_per_usd"] * t["合作商"]) / (
+        BIZ["sell_cny_per_usd_min"] * sell_rate
+    )
+    if cash_margin < 0:
+        bad(
+            slug,
+            f"售价倍率 {sell_rate:g} 过低：大额充值客户每笔亏损（现金毛利 {cash_margin:.1%}，"
+            f"盈亏平衡需 ≥ ×{BIZ['buy_cny_per_usd'] / BIZ['sell_cny_per_usd_min'] * t['合作商']:.4g}）",
+            kind="loss",
+            sell=sell_rate,
+            cost=t["合作商"],
+        )
+    if not g.get("long_context_pricing_enabled"):
+        bad(slug, "长上下文计费未开启")
+    img = ng.get("imagePricing")
+    if bool(g.get("allow_image_generation")) != bool(img):
+        bad(slug, f"图片开关 {g.get('allow_image_generation')} 与 Nexus 不符")
+    if img:
+        for k, v in img.items():
+            if abs(float(g.get(f"image_price_{k[5:]}") or -1) - float(v)) > 1e-9:
+                bad(slug, f"图片单价 {k} ≠ {v}")
+    if g.get("status") != "active":
+        bad(slug, f"状态 {g.get('status')}")
+    # 期望协议/模型
+    resp = nexus(f"/api/{path}/v1/models")
+    by_type = resp.get("modelsByType") or {}
+    want = {}
+    for ep in ng.get("supportedEndpoints") or []:
+        if ep not in ENDPOINTS:
+            continue
+        if ep == "gemini_generate" and slug in ns["GEMINI_BILLING_MISMATCH"]:
+            continue
+        plat, types, _ = ENDPOINTS[ep]
+        for ty in types:
+            for m in by_type.get(ty, []):
+                mp = as_list(m.get("mappedTo"))
+                target = mp[0] if mp and mp != [m["id"]] else m["id"]
+                # 与同步规则一致：无按张价的分组不开放画图/视频模型
+                if ns["skip_media"](ng, target):
+                    continue
+                want.setdefault(plat, {}).setdefault(m["id"], target)
+    accs = {a["platform"]: a for a in bind.get(str(gid), []) if a["status"] == "active"}
+    skipped_img = 0
+    if routes_gem := [
+        r
+        for r in (admin("GET", f"/groups/{gid}/composite-routes") or [])
+        if r.get("endpoint") == "gemini" and "gemini" not in want
+    ]:
+        bad(slug, f"Gemini 协议已关闭但仍有 {len(routes_gem)} 条 gemini 路由")
+    if set(accs) != set(want):
+        bad(slug, f"账号平台 {sorted(accs)} ≠ 期望 {sorted(want)}")
+    for plat, models in want.items():
+        a = accs.get(plat)
+        if not a:
+            continue
+        if a["base"] != f"https://nexus.itssx.com/api/{path}":
+            bad(slug, f"{plat} base_url {a['base']}")
+        if not a["key_ok"]:
+            bad(slug, f"{plat} api_key 不一致")
+        if a["pool"] is not True:
+            bad(slug, f"{plat} 池模式未开")
+        if a["status"] != "active":
+            bad(slug, f"{plat} 账号状态 {a['status']}")
+        if abs(float(a["rate"]) - t["合作商"]) > 1e-9:
+            bad(slug, f"{plat} 成本倍率 {a['rate']} ≠ 合作商 {t['合作商']}")
+        if int(a.get("concurrency") or 0) != ns["ACCOUNT_CONCURRENCY_EXPECTED"]:
+            bad(
+                slug,
+                f"{plat} 并发 {a.get('concurrency')} ≠ {ns['ACCOUNT_CONCURRENCY_EXPECTED']}",
+            )
+        if sorted((a["mm"] or {}).keys()) != sorted(models):
+            bad(
+                slug,
+                f"{plat} 白名单不符 差异 {sorted(set(models) ^ set((a['mm'] or {}).keys()))[:6]}",
+            )
+        # 渠道单价
+        ch = channels.get(gid)
+        cur = {
+            (e["platform"], m): e
+            for e in (ch or {}).get("model_pricing", [])
+            for m in e["models"]
+        }
+        for m, target in models.items():
+            checked += 1
+            if target not in pricing:
+                bad(slug, f"{plat} {m}->{target} Nexus 无定价")
+                continue
+            if img and pricing[target].get("mode") == "image_generation":
+                skipped_img += 1
+                if (plat, m) in cur:
+                    bad(slug, f"{plat} {m} 生图模型不应有 token 定价")
+                continue
+            exp, ce = price_entry(target, ng.get("peakPricing")), cur.get((plat, m))
+            if target in ns["FILTER_TIERS"]["priority"]:
+                fast_filter.add(m)
+            if target in ns["FLEX_OK"]:
+                flex_pass.add(m)
+            if not ce:
+                bad(slug, f"{plat} {m} 缺渠道定价")
+                continue
+            for k in (
+                "input_price",
+                "output_price",
+                "cache_read_price",
+                "cache_write_price",
+                "cache_write_1h_price",
+                "fast_multiplier",
+                "flex_multiplier",
+                "image_input_price",
+                "image_output_price",
+            ):
+                if abs((ce.get(k) or 0) - (exp.get(k) or 0)) > 1e-15:
+                    bad(slug, f"{plat} {m}->{target} {k} {ce.get(k)} ≠ {exp.get(k)}")
+                    break
+            if len(ce.get("intervals") or []) != len(exp.get("intervals") or []):
+                bad(slug, f"{plat} {m} 阶梯数不符")
+            for a_iv, e_iv in zip(
+                sorted(ce.get("intervals") or [], key=lambda x: x["min_tokens"]),
+                exp.get("intervals") or [],
+            ):
+                if (
+                    a_iv["min_tokens"] != e_iv["min_tokens"]
+                    or abs(
+                        (a_iv.get("input_price") or 0) - (e_iv.get("input_price") or 0)
+                    )
+                    > 1e-15
+                ):
+                    bad(slug, f"{plat} {m} 阶梯价不符")
+                    break
+            if bool(ce.get("time_pricing")) != bool(exp.get("time_pricing")):
+                bad(slug, f"{plat} {m} 峰谷配置不符")
+            elif (
+                exp.get("time_pricing")
+                and ce["time_pricing"].get("weekdays_only")
+                != exp["time_pricing"]["weekdays_only"]
+            ):
+                bad(slug, f"{plat} {m} 峰谷 weekdays_only 不符")
+    ch = channels.get(gid) or {}
+    want_restrict = skipped_img == 0 and bool(ch.get("model_pricing"))
+    if bool(ch.get("restrict_models")) != want_restrict:
+        bad(slug, f"restrict_models={ch.get('restrict_models')} 期望 {want_restrict}")
+    if not ch.get("apply_pricing_to_account_stats"):
+        bad(slug, "apply_pricing_to_account_stats 未开启")
+    # 路由覆盖
+    routes = admin("GET", f"/groups/{gid}/composite-routes") or []
+    have = {
+        (r["public_model"], r["endpoint"], r["target_platform"])
+        for r in routes
+        if r.get("enabled")
+    }
+    for plat, models in want.items():
+        eps = {
+            e
+            for ep in ng.get("supportedEndpoints") or []
+            if ep in ENDPOINTS and ENDPOINTS[ep][0] == plat
+            for e in ENDPOINTS[ep][2]
+        }
+        for fam in {family(m) for m in models}:
+            for e in eps:
+                if (fam, e, plat) not in have:
+                    bad(slug, f"缺路由 {fam} {e}->{plat}")
+
+# 无法用单一倍率表达的档位价会阻止自动同步，对账同样计为问题（否则「问题 0」会掩盖阻断）
+for msg in ns["STRUCT_ERRORS"].values():
+    bad("计费结构", msg)
+want = {r["service_tier"]: r for r in ns["managed_rules"](fast_filter, flex_pass)}
+have_list = ns["current_managed"](ns["read_policy"]())
+have = {r["service_tier"]: r for r in have_list}
+for tier in sorted({r["service_tier"] for r in have_list}):
+    n = sum(r["service_tier"] == tier for r in have_list)
+    if n > 1:
+        bad(
+            "Fast/Flex策略",
+            f"{tier} 有 {n} 条自动规则（含 sub2api 后台保存后丢失标记的副本），需重写",
+        )
+for tier in sorted(set(want) | set(have)):
+    checked += 1
+    if want.get(tier) != have.get(tier):
+        bad(
+            "Fast/Flex策略",
+            f"{tier} 规则不符：应为 {want.get(tier)}，实际 {have.get(tier)}",
+        )
+
+print(f"检查项 {checked}，问题 {len(issues)}")
+print("\n".join(issues) if issues else "全部与 Nexus 一致")
+# 已知的计费结构限制（sub2api 无法精确表达的 Nexus 档位价），仅提示，不计入问题
+for n in ns["STRUCT_NOTES"].values():
+    print("ℹ 计费结构限制 " + n)
+if os.environ.get("AUDIT_JSON"):
+    with open(os.environ["AUDIT_JSON"], "w") as f:
+        json.dump(
+            {
+                "checked": checked,
+                "issues": ISSUE_DATA,
+                "notes": list(ns["STRUCT_NOTES"].values()),
+            },
+            f,
+            ensure_ascii=False,
+        )
diff --git a/ops/daily-report.sh b/ops/daily-report.sh
new file mode 100755
index 0000000..ef3dfdd
--- /dev/null
+++ b/ops/daily-report.sh
@@ -0,0 +1,7 @@
+#!/usr/bin/env bash
+# 每日经营日报（宝塔计划任务，每天北京 09:00）。用法: daily-report.sh [YYYY-MM-DD]，默认昨天
+set -euo pipefail
+source /root/.config/sub2api-nexus.env
+export NEXUS_KEY
+source /opt/sub2api/ops/lib.sh # 提供 PGPASSWORD
+python3 -I /opt/sub2api/ops/daily_report.py "$@" | python3 -I /opt/sub2api/ops/notify.py json
diff --git a/ops/daily_report.py b/ops/daily_report.py
new file mode 100644
index 0000000..f0786ff
--- /dev/null
+++ b/ops/daily_report.py
@@ -0,0 +1,582 @@
+"""每日经营日报（表格邮件）：前一个北京自然日的资金、各分组倍率与经营、客户明细，并逐笔与 Nexus 实扣核对。
+
+口径：
+  客户消耗 $     = Σ usage_logs.actual_cost（基础价 × 售价倍率，从客户余额扣）
+  上游成本 $     = 逐笔匹配到的 Nexus 实扣 userCost；匹配不到用本站计算值
+                   Σ COALESCE(account_stats_cost, total_cost) × account_rate_multiplier（合作商倍率）
+  收入 ¥         = 客户消耗 × 该客户实际购买单价（历史余额订单 退款后净实付¥ / 退款后净到账$；无订单按最低充值单价估）
+  订单字段（sub2api 0.2.15 源码 payment_order.go / payment_refund.go）：amount = 到账余额$（已含赠送 bonus_amount）、
+                   pay_amount = 实付¥、refund_amount = 退回的余额$，网关退款¥ = pay_amount × refund_amount / amount
+  成本 ¥         = 上游成本 × 进价；毛利 = 收入 − 成本（管理员测试消耗只计成本、不计收入）
+  未匹配上游消耗 = Nexus 有扣费但匹配不到本站记录（可能是直接用 Nexus Key 调用，也可能是匹配遗漏）
+经营参数：/opt/sub2api/ops/business.json。用法: daily-report.sh [YYYY-MM-DD]（默认昨天）
+"""
+
+import json
+import os
+import subprocess
+import sys
+import urllib.request
+from datetime import datetime, timedelta, timezone
+
+BJ = timezone(timedelta(hours=8))
+PSQL = "/www/server/pgsql/bin/psql"
+BIZ = json.load(open("/opt/sub2api/ops/business.json"))
+BUY, SELL_MIN = BIZ["buy_cny_per_usd"], BIZ["sell_cny_per_usd_min"]
+FEE_PCT = float(BIZ.get("pay_channel_fee_percent") or 0)
+NEXUS_KEY = os.environ["NEXUS_KEY"]
+WINDOW = 600  # 逐笔匹配允许的时间差（秒）
+BLUE = "#1d4ed8"
+
+day = (
+    datetime.strptime(sys.argv[1], "%Y-%m-%d").date()
+    if len(sys.argv) > 1
+    else (datetime.now(BJ) - timedelta(days=1)).date()
+)
+start = datetime(day.year, day.month, day.day, tzinfo=BJ)
+end = start + timedelta(days=1)
+S, E = start.isoformat(), end.isoformat()
+PAID = "('PAID','RECHARGING','COMPLETED','PARTIALLY_REFUNDED','REFUNDED','REFUND_REQUESTED','REFUNDING','REFUND_PENDING')"
+# 只有退款成功的订单才真正退钱、扣余额（申请中/处理中的 refund_amount 只是申请额）
+REFUNDED = "status in ('REFUNDED','PARTIALLY_REFUNDED')"
+REFUND_USD = f"(case when {REFUNDED} then coalesce(refund_amount,0) else 0 end)"
+# 退款台账 s2a_ops.manual_refunds（relay 退款登记页，同一订单可多次退款）按实际人民币记；台账以外的 sub2api 原生退款
+# 按 实付 × 退回$ / 到账$ 折算
+LEDGER = "(select coalesce(sum(m.{0}),0) from s2a_ops.manual_refunds m where m.order_id = payment_orders.id and m.deleted_at is null)"
+NATIVE_CNY = f"round(pay_amount * greatest(coalesce(refund_amount,0) - {LEDGER.format('usd')}, 0) / amount, 2)"
+REFUND_CNY = f"(case when {REFUNDED} and amount > 0 then {LEDGER.format('cny')} + {NATIVE_CNY} else 0 end)"
+# 原生退款部分的发生时间：台账登记会覆盖订单 refund_at，故优先取 sub2api 原生 REFUND_SUCCESS 审计时间
+# （admin:manual 是旧命令行补登记，已回填进台账）
+NATIVE_AT = (
+    "coalesce((select max(a.created_at) from payment_audit_logs a where a.order_id = payment_orders.id::text "
+    "and a.action = 'REFUND_SUCCESS' and a.operator <> 'admin:manual'), refund_at)"
+)
+
+
+def q(sql):
+    out = subprocess.run(
+        [
+            PSQL,
+            "-h",
+            "localhost",
+            "-U",
+            "postgres",
+            "-d",
+            "sub2api",
+            "-qAt",
+            "-F",
+            "\t",
+        ],
+        input=sql,
+        capture_output=True,
+        text=True,
+        check=True,
+        env=os.environ,
+    ).stdout
+    return [line.split("\t") for line in out.splitlines() if line]
+
+
+def nexus_get(path):
+    req = urllib.request.Request(
+        "https://nexus.itssx.com" + path, headers={"User-Agent": "sub2api-ops/1.0"}
+    )
+    return json.load(urllib.request.urlopen(req, timeout=60)).get("data") or {}
+
+
+def short(name):
+    return (name or "").split("(")[0].split("（")[0].strip()
+
+
+def money(v, unit="$", nd=4):
+    return f"{unit}{v:,.{nd}f}"
+
+
+def mask(email):
+    name, _, dom = (email or "").partition("@")
+    return (name[:2] + "***" + ("@" + dom if dom else "")) if name else "—"
+
+
+def x(v):
+    return f"×{v:g}"
+
+
+# ---------- 本站基础数据 ----------
+groups = {
+    int(r[0]): (short(r[1]), float(r[2]))
+    for r in q(
+        "select id, name, rate_multiplier from groups where deleted_at is null and status = 'active'"
+    )
+}
+costs = {
+    int(r[0]): float(r[1])
+    for r in q(
+        "select ag.group_id, max(a.rate_multiplier) from account_groups ag join accounts a on a.id = ag.account_id "
+        "where a.status = 'active' and a.deleted_at is null group by ag.group_id"
+    )
+}
+users = {
+    int(r[0]): dict(
+        email=r[1], admin=r[2] == "admin", created=r[3], balance=float(r[4])
+    )
+    for r in q(
+        "select id, email, role, to_char(created_at at time zone 'Asia/Shanghai','MM-DD'), balance "
+        "from users where deleted_at is null"
+    )
+}
+# 每位客户的实际购买单价（历史余额订单 退款后净实付¥ / 退款后净到账$；amount 已含赠送）
+price = {
+    int(r[0]): float(r[1]) / float(r[2])
+    for r in q(
+        f"""select user_id, sum(pay_amount - {REFUND_CNY}), sum(amount - {REFUND_USD}) from payment_orders
+        where status in {PAID} and order_type = 'balance' group by user_id having sum(amount - {REFUND_USD}) > 0"""
+    )
+}
+logs = q(f"""select u.group_id, u.output_tokens, u.input_tokens, u.cache_read_tokens, u.total_cost, u.actual_cost,
+                    coalesce(u.account_stats_cost, u.total_cost) * coalesce(u.account_rate_multiplier, 1),
+                    extract(epoch from u.created_at), u.user_id
+             from usage_logs u where u.created_at >= '{S}' and u.created_at < '{E}' order by u.id""")
+
+# ---------- Nexus：分组倍率、余额、扣费日志 ----------
+nexus_rates, nexus_balance = {}, None
+try:
+    kq = nexus_get(f"/api-go/relay/key-query?key={NEXUS_KEY}")
+    tiers = {}
+    for kg in kq.get("keyGroups") or []:
+        for a in kg.get("aiGroups") or []:
+            tiers.setdefault(a["id"], {})[kg["name"]] = float(
+                a.get("globalFallbackRatio") or 0
+            )
+    for g in kq.get("allowedGroups") or []:
+        t = tiers.get(g["id"], {})
+        nexus_rates[short(g.get("name"))] = (t.get("默认分组"), t.get("合作商"))
+    nexus_balance = float((kq.get("userPool") or {}).get("balance") or 0)
+except Exception:
+    pass
+
+nexus_rows = []
+try:
+    for page in range(1, 300):
+        d = nexus_get(
+            f"/api-go/relay/key-logs?key={NEXUS_KEY}&pageNum={page}&pageSize=100"
+        )
+        page_logs = (
+            (d.get("list") or d.get("records") or d.get("items"))
+            if isinstance(d, dict)
+            else d
+        )
+        if not page_logs:
+            break
+        older = False
+        for r in page_logs:
+            t = datetime.fromisoformat(
+                r["requestTime"].replace("Z", "+00:00")
+            ).timestamp()
+            if t < start.timestamp() - WINDOW:
+                older = True
+            elif t < end.timestamp() + WINDOW:
+                nexus_rows.append((t, r))
+        if older:
+            break
+except Exception:
+    nexus_rows = None
+used = set()
+
+
+def match(group, ot, it, cr, base, ts):
+    """逐笔匹配：同一分组、输出 token 相同、时间相差在窗口内，且原价相同（优先）或输入+缓存读相同。"""
+    if nexus_rows is None:
+        return None
+    cands = [
+        (i, r)
+        for i, (t, r) in enumerate(nexus_rows)
+        if i not in used
+        and short(r.get("groupName")) == group
+        and abs(t - ts) <= WINDOW
+        and int(r.get("outputTokens") or 0) == ot
+    ]
+    rules = (
+        lambda r: abs(float(r.get("rawCost") or 0) - base) < 1e-9,
+        lambda r: (
+            int(r.get("inputTokens") or 0) + int(r.get("cacheReadTokens") or 0)
+            == it + cr
+        ),
+    )
+    for rule in rules:
+        for i, r in cands:
+            if rule(r):
+                used.add(i)
+                return float(r.get("userCost") or 0)
+    return None
+
+
+# ---------- 逐笔汇总：分组 × 客户 ----------
+G = {}  # gid -> 汇总
+U = {}  # uid -> 汇总
+for gid, ot, it, cr, base, cust, up, ts, uid in logs:
+    gid, uid = int(gid or 0), int(uid)
+    base, cust, up = float(base or 0), float(cust or 0), float(up or 0)
+    gname = groups.get(gid, (f"#{gid}", 0))[0]
+    nx = match(gname, int(ot or 0), int(it or 0), int(cr or 0), base, float(ts))
+    cost_usd = nx if nx is not None else up
+    admin = users.get(uid, {}).get("admin", False)
+    rev = 0.0 if admin else cust * price.get(uid, SELL_MIN)
+    g = G.setdefault(
+        gid,
+        dict(
+            n=0,
+            cust=0.0,
+            test=0.0,
+            rev=0.0,
+            cost=0.0,
+            up=0.0,
+            matched=0,
+            mup=0.0,
+            mnx=0.0,
+        ),
+    )
+    g["n"] += 1
+    g["test" if admin else "cust"] += cust
+    g["rev"] += rev
+    g["cost"] += cost_usd * BUY
+    g["up"] += up
+    if nx is not None:
+        g["matched"] += 1
+        g["mup"] += up
+        g["mnx"] += nx
+    u = U.setdefault(uid, dict(n=0, cust=0.0, rev=0.0, cost=0.0, groups={}))
+    u["n"] += 1
+    u["cust"] += cust
+    u["rev"] += rev
+    u["cost"] += cost_usd * BUY
+    u["groups"][gname] = u["groups"].get(gname, 0) + cust
+
+unmatched = {}
+for i, (t, r) in enumerate(nexus_rows or []):
+    if i not in used and start.timestamp() <= t < end.timestamp():
+        m = unmatched.setdefault(short(r.get("groupName")), [0, 0.0])
+        m[0] += 1
+        m[1] += float(r.get("userCost") or 0)
+unmatched_cny = sum(v[1] for v in unmatched.values()) * BUY
+
+# ---------- 资金 ----------
+od = q(f"""select count(*), coalesce(sum(pay_amount),0), coalesce(sum(amount) filter (where order_type = 'balance'),0)
+           from payment_orders where status in {PAID} and paid_at >= '{S}' and paid_at < '{E}'""")[
+    0
+]
+orders_n, paid_cny, credited_usd = int(od[0]), float(od[1]), float(od[2])
+paid_all, orders_all = (lambda r: (float(r[1]), int(r[0])))(
+    q(
+        f"select count(*), coalesce(sum(pay_amount),0) from payment_orders where status in {PAID}"
+    )[0]
+)
+refund_cny = float(
+    q(
+        f"""select (select coalesce(sum(cny),0) from s2a_ops.manual_refunds where deleted_at is null and created_at >= '{S}' and created_at < '{E}')
+             + (select coalesce(sum({NATIVE_CNY}),0) from payment_orders
+                where {REFUNDED} and amount > 0 and {NATIVE_AT} >= '{S}' and {NATIVE_AT} < '{E}')"""
+    )[0][0]
+)
+rebate_usd = float(
+    q(
+        f"select coalesce(sum(amount),0) from user_affiliate_ledger where action = 'accrue' "
+        f"and created_at >= '{S}' and created_at < '{E}'"
+    )[0][0]
+)
+fee_cny = paid_cny * FEE_PCT / 100
+customers = [u for u in users.values() if not u["admin"]]
+new_users = int(
+    q(
+        f"select count(*) from users where role <> 'admin' and created_at >= '{S}' and created_at < '{E}'"
+    )[0][0]
+)
+active = sum(1 for uid in U if not users.get(uid, {}).get("admin"))
+day_paid = {
+    int(r[0]): float(r[1])
+    for r in q(
+        f"select user_id, sum(pay_amount) from payment_orders where status in {PAID} "
+        f"and paid_at >= '{S}' and paid_at < '{E}' group by user_id"
+    )
+}
+
+cust_rev = sum(g["rev"] for g in G.values())
+cust_cost = sum(
+    u["cost"] for uid, u in U.items() if not users.get(uid, {}).get("admin")
+)
+test_cost = sum(u["cost"] for uid, u in U.items() if users.get(uid, {}).get("admin"))
+rebate_cny = rebate_usd * BUY
+gross = cust_rev - cust_cost - rebate_cny
+all_cost = sum(g["cost"] for g in G.values()) + unmatched_cny
+cash = paid_cny - refund_cny - fee_cny - all_cost
+
+
+def tone(v):
+    return "good" if v >= 0 else "bad"
+
+
+sections = [
+    {
+        "heading": "资金与利润",
+        "note": "消耗口径：客户当日用掉的余额按其实际购买单价折算收入 − 对应上游成本 − 返利成本；"
+        "现金口径：当日实收 − 退款 − 提现结算费（按实收计提，实际在提现时扣）− 当日全部上游支出（含测试与未匹配消耗）。",
+        "columns": ["项目", "当日", "说明"],
+        "rows": [
+            [
+                "实收充值",
+                {"text": money(paid_cny, "¥", 2), "bold": True},
+                f"{orders_n} 笔，到账余额 {money(credited_usd, '$', 2)}",
+            ],
+            ["累计充值", money(paid_all, "¥", 2), f"累计 {orders_all} 笔已支付订单"],
+            ["退款", money(refund_cny, "¥", 2), ""],
+            [
+                "提现结算费（计提）",
+                money(fee_cny, "¥", 2),
+                f"实收 × {FEE_PCT:g}%，易支付在提现时扣（business.json）",
+            ],
+            [
+                "客户消耗",
+                money(sum(g["cust"] for g in G.values())),
+                f"{active} 位活跃客户",
+            ],
+            ["消耗折算收入", money(cust_rev, "¥"), "按各客户实际购买单价"],
+            ["客户对应上游成本", money(cust_cost, "¥"), "Nexus 实扣 × 进价"],
+            [
+                "返利发放",
+                money(rebate_cny, "¥"),
+                f"{money(rebate_usd)} 余额，按进价折算",
+            ],
+            [
+                {"text": "消耗口径毛利", "bold": True},
+                {"text": money(gross, "¥"), "bold": True, "tone": tone(gross)},
+                f"毛利率 {gross / cust_rev:.1%}" if cust_rev else "—",
+            ],
+            [
+                "测试与未匹配支出",
+                money(test_cost + unmatched_cny, "¥"),
+                "管理员测试 + 未匹配上游消耗",
+            ],
+            [
+                {"text": "现金净流入", "bold": True},
+                {"text": money(cash, "¥", 2), "bold": True, "tone": tone(cash)},
+                "实收 − 退款 − 结算费计提 − 全部上游支出",
+            ],
+        ],
+    }
+]
+
+
+def diff_cell(mine, ref):
+    """本站倍率与 Nexus 对应倍率比较：高于红底↑、低于蓝底↓、一致无底色；Nexus 无数据时灰色。"""
+    if ref is None:
+        return {"text": x(mine), "tone": "muted"}
+    if abs(mine - ref) < 1e-9:
+        return x(mine)
+    up = mine > ref
+    return {
+        "text": f"{x(mine)} {'↑' if up else '↓'}",
+        "bold": True,
+        "tone": "bad" if up else BLUE,
+        "bg": "#fee2e2" if up else "#dbeafe",
+    }
+
+
+# 分组倍率与当日经营
+rows, tot = [], dict(cust=0.0, test=0.0, rev=0.0, cost=0.0)
+for gid, (name, sell) in sorted(
+    groups.items(),
+    key=lambda i: (-G.get(i[0], {}).get("cust", 0), -G.get(i[0], {}).get("test", 0)),
+):
+    if gid not in costs:
+        continue
+    cost = costs[gid]
+    n_def, n_sup = nexus_rates.get(name, (None, None))
+    sell_cell = diff_cell(sell, n_def)
+    cost_cell = diff_cell(cost, n_sup)
+    m = 1 - (BUY * cost) / (SELL_MIN * sell) if sell else 0
+    g = G.get(gid, dict(cust=0.0, test=0.0, rev=0.0, cost=0.0))
+    cust_part_cost = (
+        g["cost"] * (g["cust"] / (g["cust"] + g["test"]))
+        if (g["cust"] + g["test"])
+        else 0
+    )
+    gp = g["rev"] - cust_part_cost
+    rows.append(
+        [
+            name,
+            "—" if n_def is None else x(n_def),
+            sell_cell,
+            "—" if n_sup is None else x(n_sup),
+            cost_cell,
+            {
+                "text": f"{m:.1%}",
+                "tone": "good" if m >= 0.1 else ("warn" if m >= 0 else "bad"),
+            },
+            money(g["cust"]) if g["cust"] else "—",
+            money(g["rev"], "¥") if g["rev"] else "—",
+            money(cust_part_cost, "¥") if cust_part_cost else "—",
+            {"text": money(gp, "¥"), "tone": tone(gp), "bold": True}
+            if g["cust"]
+            else "—",
+            {"text": money(g["test"]), "tone": "muted"} if g["test"] else "—",
+        ]
+    )
+    tot["cust"] += g["cust"]
+    tot["test"] += g["test"]
+    tot["rev"] += g["rev"]
+    tot["cost"] += cust_part_cost
+rows.append(
+    [
+        {"text": "合计", "bold": True},
+        "",
+        "",
+        "",
+        "",
+        "",
+        money(tot["cust"]),
+        money(tot["rev"], "¥"),
+        money(tot["cost"], "¥"),
+        {
+            "text": money(tot["rev"] - tot["cost"], "¥"),
+            "bold": True,
+            "tone": tone(tot["rev"] - tot["cost"]),
+        },
+        money(tot["test"]),
+    ]
+)
+sections.append(
+    {
+        "heading": "分组倍率与当日经营",
+        "note": "本站售价对比 Nexus 普通、本站成本对比 Nexus 供应商：红底↑ 高于、蓝底↓ 低于、无底色 一致（成本不一致应排查）。"
+        f"大额档毛利率按客户 ¥{SELL_MIN}/$、进价 ¥{BUY}/$ 计算。消耗/收入/成本/毛利只含客户，测试消耗单列。",
+        "columns": [
+            "分组",
+            "Nexus 普通",
+            "本站售价",
+            "Nexus 供应商",
+            "本站成本",
+            "大额档毛利率",
+            "客户消耗",
+            "收入",
+            "上游成本",
+            "毛利",
+            "测试消耗",
+        ],
+        "rows": rows,
+    }
+)
+
+# 客户明细
+crow = []
+for uid, u in sorted(U.items(), key=lambda i: -i[1]["cust"]):
+    info = users.get(uid, dict(email=f"#{uid}", admin=False, created="—", balance=0.0))
+    top = "、".join(sorted(u["groups"], key=lambda k: -u["groups"][k])[:3])
+    if info["admin"]:
+        crow.append(
+            [
+                {"text": "管理员（测试）", "tone": "muted"},
+                info["created"],
+                u["n"],
+                money(u["cust"]),
+                "—",
+                money(u["cost"], "¥"),
+                {"text": "测试支出", "tone": "muted"},
+                money(day_paid.get(uid, 0), "¥", 2),
+                money(info["balance"], "$", 2),
+                top,
+            ]
+        )
+        continue
+    gp = u["rev"] - u["cost"]
+    crow.append(
+        [
+            mask(info["email"]),
+            info["created"],
+            u["n"],
+            money(u["cust"]),
+            money(u["rev"], "¥") + ("" if uid in price else "（估）"),
+            money(u["cost"], "¥"),
+            {"text": money(gp, "¥"), "tone": tone(gp), "bold": True},
+            money(day_paid.get(uid, 0), "¥", 2),
+            money(info["balance"], "$", 2),
+            top,
+        ]
+    )
+sections.append(
+    {
+        "heading": "客户明细",
+        "note": "按当日消耗排序，邮箱已脱敏；收入按该客户历史余额订单扣除已退款后的实际购买单价折算，标「估」为无订单客户（按最低充值单价）。",
+        "columns": [
+            "客户",
+            "注册",
+            "请求",
+            "消耗",
+            "收入",
+            "上游成本",
+            "毛利",
+            "当日充值",
+            "当前余额",
+            "主要分组",
+        ],
+        "rows": crow or [[{"text": "当日没有使用记录", "tone": "muted"}] + [""] * 9],
+    }
+)
+
+# 上游成本逐笔核对
+chk = []
+for gid, g in sorted(G.items(), key=lambda i: -(i[1]["cust"] + i[1]["test"])):
+    if nexus_rows is None or not g["matched"]:
+        c = {"text": "无法核对" if nexus_rows is None else "未匹配到", "tone": "muted"}
+    elif abs(g["mnx"] - g["mup"]) <= max(1e-6, g["mup"] * 0.01):
+        c = {"text": "一致", "tone": "good"}
+    else:
+        c = {"text": f"本站{(g['mup'] - g['mnx']) / g['mnx']:+.1%}", "tone": "bad"}
+    chk.append(
+        [
+            groups.get(gid, (f"#{gid}", 0))[0],
+            g["n"],
+            f"{g['matched']}/{g['n']}",
+            money(g["mup"]),
+            money(g["mnx"]),
+            c,
+        ]
+    )
+if chk:
+    sections.append(
+        {
+            "heading": "上游成本逐笔核对",
+            "note": "本站按合作商倍率算出的上游消耗 vs Nexus 实扣（同分组、输出 token、原价或输入 token、时间 ±10 分钟启发式匹配，无请求 ID 关联）。",
+            "columns": ["分组", "请求", "匹配", "本站计算", "Nexus 实扣", "结论"],
+            "rows": chk,
+        }
+    )
+if unmatched:
+    sections.append(
+        {
+            "heading": "未匹配的上游消耗",
+            "note": "Nexus 有扣费但匹配不到本站记录。可能是直接用 Nexus Key 调用（如测试），也可能是匹配遗漏；计入当日支出。",
+            "columns": ["Nexus 分组", "请求", "Nexus 实扣", "成本"],
+            "rows": [
+                [k, n, money(v), money(v * BUY, "¥")]
+                for k, (n, v) in sorted(unmatched.items(), key=lambda i: -i[1][1])
+            ],
+        }
+    )
+
+report = {
+    "title": f"经营日报 {day.isoformat()}"
+    + (f"（截至 {datetime.now(BJ):%H:%M}）" if day == datetime.now(BJ).date() else ""),
+    "status": "info" if gross >= 0 else "warn",
+    "subtitle": f"统计区间：{day.isoformat()} 00:00–24:00（北京时间）· 宝塔计划任务每日 09:00 发送",
+    "summary": [
+        [
+            "当日实收 / 累计充值",
+            f"{money(paid_cny, '¥', 2)} / {money(paid_all, '¥', 2)}",
+        ],
+        ["消耗口径毛利", money(gross, "¥", 2)],
+        ["客户 总数 / 活跃 / 新增", f"{len(customers)} / {active} / {new_users}"],
+        ["客户余额合计", money(sum(c["balance"] for c in customers), "$", 2)],
+        ["Nexus 余额", "—" if nexus_balance is None else money(nexus_balance, "$", 2)],
+    ],
+    "sections": sections,
+    "footer": "成本口径：基础价 × 合作商倍率（逐笔以 Nexus 实扣核对）× 进价。经营参数见 /opt/sub2api/ops/business.json。",
+}
+print(json.dumps(report, ensure_ascii=False))
diff --git a/ops/deepseek-peak-check.sh b/ops/deepseek-peak-check.sh
new file mode 100755
index 0000000..ef65fd4
--- /dev/null
+++ b/ops/deepseek-peak-check.sh
@@ -0,0 +1,29 @@
+#!/usr/bin/env bash
+# 一次性：高峰时段发 deepseek 请求，对比 sub2api 与 Nexus 原价，结果写日志后删除自身 cron
+set -uo pipefail
+LOG=/opt/sub2api/ops/deepseek_peak_check.log
+source /root/.config/sub2api-nexus.env
+P=/www/server/pgsql/bin/psql; export PGPASSWORD=$(awk '/^database:/{f=1} f&&/password:/{print $2; exit}' /opt/sub2api/config.yaml | tr -d "\"'")
+K=$($P -h localhost -U postgres -d sub2api -At -c "select key from api_keys where id=2")
+{ echo "== $(TZ=Asia/Shanghai date '+%F %T %Z') deepseek 峰谷实测"
+  for m in claude-haiku-4-5 deepseek-v4-flash; do
+    curl -s -m 120 -o /dev/null -w "$m HTTP %{http_code}\n" -H "x-api-key: $K" -H 'anthropic-version: 2023-06-01' -H 'content-type: application/json' https://api.itssx.com/api/deepseek/v1/messages -d "{\"model\":\"$m\",\"max_tokens\":20,\"messages\":[{\"role\":\"user\",\"content\":\"hi\"}]}"
+  done
+  sleep 10
+  $P -h localhost -U postgres -d sub2api -At -c "select 'sub2api: '||requested_model||' in '||input_tokens||' out '||output_tokens||' cr '||cache_read_tokens||' 原价 '||round(total_cost::numeric,8) from usage_logs where group_id=14 and created_at > now()-interval '5 min' order by id"
+  curl -s -m 60 "https://nexus.itssx.com/api-go/relay/key-logs?key=$NEXUS_KEY&pageNum=1&pageSize=6" | python3 -c '
+import json,sys
+d=json.load(sys.stdin)["data"]; rows=d.get("rows") or d.get("list") or d
+for r in rows[:6]:
+  if "deepseek" in r.get("groupName",""): print("Nexus  :", r.get("model"),"in",r.get("inputTokens"),"out",r.get("outputTokens"),"cr",r.get("cacheReadTokens"),"原价",r.get("rawCost"))'
+} >> "$LOG" 2>&1
+
+{ echo "== 对话压缩 /v1/responses/compact（经 sub2api 与直连 Nexus）"
+  B='{"model":"gpt-5.5","input":[{"type":"message","role":"user","content":[{"type":"input_text","text":"我们在讨论 nginx 反向代理配置。"}]}],"instructions":"You are Codex."}'
+  for g in codex_eco codex/codex codex/codex_pro; do
+    echo "sub2api $g: $(curl -s -m 120 -o /tmp/cmp.json -w '%{http_code}' -H "Authorization: Bearer $K" -H 'content-type: application/json' https://api.itssx.com/api/$g/v1/responses/compact -d "$B") $(head -c 160 /tmp/cmp.json)"
+    echo "Nexus   $g: $(curl -s -m 120 -o /tmp/cmp.json -w '%{http_code}' -H "Authorization: Bearer $NEXUS_KEY" -H 'content-type: application/json' https://nexus.itssx.com/api/$g/v1/responses/compact -d "$B") $(head -c 160 /tmp/cmp.json)"
+  done; rm -f /tmp/cmp.json
+  sleep 8; $P -h localhost -U postgres -d sub2api -At -c "select 'sub2api 计费: g'||group_id||' '||inbound_endpoint||' '||requested_model||' in '||input_tokens||' out '||output_tokens||' 原价 '||round(total_cost::numeric,8) from usage_logs where inbound_endpoint like '%compact%' and created_at > now()-interval '10 min' order by id"
+} >> "$LOG" 2>&1
+rm -f /etc/cron.d/sub2api-deepseek-peak-check
diff --git a/ops/gen_auto_index.py b/ops/gen_auto_index.py
new file mode 100644
index 0000000..39e1133
--- /dev/null
+++ b/ops/gen_auto_index.py
@@ -0,0 +1,294 @@
+"""生成统一路由的「模型 → 分组」匹配索引：/opt/sub2api/ops/auto_route_index.json。
+
+顺序：Nexus 官方分组顺序（allowedGroups.sort）。每个分组按协议（anthropic/openai/gemini）列出本站实际开放的模型
+（启用账号的白名单），并区分原生模型与别名（Nexus modelsByType 中 mappedTo 指向其他模型的为别名）。
+统一路由匹配时：原生提供该模型的分组优先，别名分组排在后面兜底（PREFER_NATIVE）。
+由 nexus-auto-sync.sh 每小时调用（需 NEXUS_KEY、PGPASSWORD）；也可手动运行。
+"""
+
+import json
+import os
+import subprocess
+import urllib.request
+
+OUT = "/opt/sub2api/ops/auto_route_index.json"
+PSQL = "/www/server/pgsql/bin/psql"
+NEXUS_KEY = os.environ["NEXUS_KEY"]
+CONFIG = json.load(open("/opt/sub2api/ops/auto_route_config.json"))
+PREFER_NATIVE = bool(CONFIG.get("prefer_native", True))
+ORDER_MODE = CONFIG.get("order_mode", "alphabet")
+TYPE_TO_PLAT = {
+    "claude_code": "anthropic",
+    "openai": "openai",
+    "codex": "openai",
+    "images": "openai",
+    "gemini": "gemini",
+}
+
+
+def q(sql):
+    out = subprocess.run(
+        [
+            PSQL,
+            "-h",
+            "localhost",
+            "-U",
+            "postgres",
+            "-d",
+            "sub2api",
+            "-qAt",
+            "-F",
+            "\t",
+        ],
+        input=sql,
+        capture_output=True,
+        text=True,
+        check=True,
+        env=os.environ,
+    ).stdout
+    return [line.split("\t") for line in out.splitlines() if line]
+
+
+def nexus(path):
+    req = urllib.request.Request(
+        "https://nexus.itssx.com" + path,
+        headers={
+            "Authorization": f"Bearer {NEXUS_KEY}",
+            "User-Agent": "sub2api-ops/1.0",
+        },
+    )
+    return json.load(urllib.request.urlopen(req, timeout=60))
+
+
+def short(name):
+    return (name or "").split("(")[0].split("（")[0].strip()
+
+
+route_groups = json.load(
+    open("/opt/sub2api/ops/route_groups.json")
+)  # 路径 -> {group_id, slug}
+slug_by_gid = {v["group_id"]: v["slug"] for v in route_groups.values()}
+unified = q(
+    "select id from groups where name like '统一路由%' and deleted_at is null and status = 'active' limit 1"
+)
+unified_gid = int(unified[0][0]) if unified else None
+
+# 本站：各分组各协议启用账号的模型白名单
+wl = {}
+for (
+    gid,
+    plat,
+    mm,
+) in q("""select ag.group_id, a.platform, coalesce(a.credentials->'model_mapping', '{}'::jsonb)::text
+                          from account_groups ag join accounts a on a.id = ag.account_id
+                          where a.status = 'active' and a.deleted_at is null"""):
+    wl.setdefault(int(gid), {}).setdefault(plat, set()).update(json.loads(mm).keys())
+active = {
+    int(r[0])
+    for r in q("select id from groups where deleted_at is null and status = 'active'")
+}
+
+PLAT_ENDPOINTS = {
+    "anthropic": {"claude_messages"},
+    "openai": {"openai_chat_completions", "openai_responses"},
+    "gemini": {"gemini_generate"},
+}
+kq = nexus(f"/api-go/relay/key-query?key={NEXUS_KEY}")["data"]
+groups = []
+
+
+def order_key(g):
+    """匹配顺序：alphabet 按分组名称（ASCII 字母在前，中文在后，不区分大小写）；nexus 按官方 sort；custom 按配置。"""
+    if ORDER_MODE == "nexus":
+        return (int(g.get("sort") or 0),)
+    if ORDER_MODE == "custom":
+        lst = CONFIG.get("custom_order") or []
+        return (
+            lst.index(g["slug"]) if g["slug"] in lst else len(lst),
+            short(g["name"]).lower(),
+        )
+    name = short(g["name"])
+    return (not name[:1].isascii(), name.lower())
+
+
+for g in sorted(kq["allowedGroups"], key=order_key):
+    gid = next((i for i, s in slug_by_gid.items() if s == g["slug"]), None)
+    if gid is None or gid not in active or gid not in wl:
+        continue
+    endpoint_path = g["endpoint"].split("/api/", 1)[1]
+    # 别名：Nexus 中 mappedTo 指向其他模型
+    alias = set()
+    try:
+        by_type = nexus(f"/api/{endpoint_path}/v1/models").get("modelsByType") or {}
+        for t, ms in by_type.items():
+            for m in ms:
+                mt = m.get("mappedTo")
+                mt = mt if isinstance(mt, list) else ([mt] if mt else [])
+                if mt and mt != [m["id"]]:
+                    alias.add((TYPE_TO_PLAT.get(t), m["id"]))
+    except Exception:
+        pass
+    # Nexus 实际开放的端点（supportedEndpoints）；未开放的协议不参与匹配（如 gemini_1 不开放 claude_messages）
+    eps = set(g.get("supportedEndpoints") or [])
+    protocols = {}
+    for plat, models in wl[gid].items():
+        if eps and not eps & PLAT_ENDPOINTS.get(plat, set()):
+            continue
+        protocols[plat] = {
+            "native": sorted(m for m in models if (plat, m) not in alias),
+            "alias": sorted(m for m in models if (plat, m) in alias),
+        }
+    groups.append(
+        {
+            "slug": g["slug"],
+            "name": short(g["name"]),
+            "gid": gid,
+            "path": g["slug"],
+            "protocols": protocols,
+            "tags": [t["id"] for t in g.get("tags") or []],
+            "nexus_path": endpoint_path,
+        }
+    )
+
+
+# ---------- 写入数据库（relay 页面只读数据库，不直接请求 Nexus） ----------
+def psql_set(name, value):
+    v = str(value).replace("\\", "\\\\").replace("'", "\\'")
+    return f"\\set {name} '{v}'\n"
+
+
+unified_protocols = {}
+for g in groups:
+    for plat, ms in g["protocols"].items():
+        u = unified_protocols.setdefault(plat, {"native": set(), "alias": set()})
+        u["native"] |= set(ms["native"])
+        u["alias"] |= set(ms["alias"])
+meta_rows = [
+    {
+        "group_id": g["gid"],
+        "slug": g["slug"],
+        "nexus_path": g["nexus_path"],
+        "route_path": f"/api/{g['slug']}",
+        "sort": i + 1,
+        "tags": g["tags"],
+        "protocols": g["protocols"],
+        "is_unified": False,
+    }
+    for i, g in enumerate(groups)
+]
+if unified_gid:
+    meta_rows.insert(
+        0,
+        {
+            "group_id": unified_gid,
+            "slug": "auto",
+            "nexus_path": "",
+            "route_path": "",
+            "sort": 0,
+            "tags": [],
+            "protocols": {
+                p: {k: sorted(v) for k, v in d.items()}
+                for p, d in unified_protocols.items()
+            },
+            "is_unified": True,
+        },
+    )
+tag_rows = [
+    {"id": t["id"], "name": t["name"], "color": t.get("color"), "sort": i}
+    for i, t in enumerate(kq.get("availableTags") or [])
+]
+subprocess.run(
+    [
+        PSQL,
+        "-h",
+        "localhost",
+        "-U",
+        "postgres",
+        "-d",
+        "sub2api",
+        "-qAt",
+        "-v",
+        "ON_ERROR_STOP=1",
+    ],
+    input=psql_set("tags", json.dumps(tag_rows, ensure_ascii=False))
+    + psql_set("meta", json.dumps(meta_rows, ensure_ascii=False))
+    + """
+begin;
+create schema if not exists s2a_ops;
+create table if not exists s2a_ops.nexus_tags (
+  id int primary key, name text not null, color text, sort int, updated_at timestamptz not null default now());
+create table if not exists s2a_ops.group_meta (
+  group_id bigint primary key, slug text not null, nexus_path text, route_path text, sort int,
+  tags jsonb not null default '[]', protocols jsonb not null default '{}', is_unified boolean not null default false,
+  updated_at timestamptz not null default now());
+delete from s2a_ops.nexus_tags;
+insert into s2a_ops.nexus_tags (id, name, color, sort)
+  select id, name, color, sort from jsonb_to_recordset(:'tags'::jsonb) as x(id int, name text, color text, sort int);
+delete from s2a_ops.group_meta;
+insert into s2a_ops.group_meta (group_id, slug, nexus_path, route_path, sort, tags, protocols, is_unified)
+  select group_id, slug, nexus_path, route_path, sort, tags, protocols, is_unified
+  from jsonb_to_recordset(:'meta'::jsonb)
+       as x(group_id bigint, slug text, nexus_path text, route_path text, sort int, tags jsonb, protocols jsonb, is_unified boolean);
+do $$ begin
+  if exists (select 1 from pg_roles where rolname = 'relay_ro') then
+    grant usage on schema s2a_ops to relay_ro;
+    grant select on s2a_ops.nexus_tags, s2a_ops.group_meta to relay_ro;
+  end if;
+end $$;
+commit;
+""",
+    capture_output=True,
+    text=True,
+    check=True,
+    env=os.environ,
+)
+
+index = {
+    "unified_gid": unified_gid,
+    "prefer_native": PREFER_NATIVE,
+    "order_mode": ORDER_MODE,
+    "groups": groups,
+}
+tmp = OUT + ".tmp"
+with open(tmp, "w") as f:
+    json.dump(index, f, ensure_ascii=False, indent=1)
+os.chmod(tmp, 0o644)
+os.replace(tmp, OUT)
+print(f"统一路由索引：{len(groups)} 个分组，统一路由分组 id={unified_gid}")
+print(f"匹配顺序：{ORDER_MODE}，原生模型优先：{'是' if PREFER_NATIVE else '否'}")
+print("顺序：" + " → ".join(g["name"] for g in groups))
+# 每个模型（按协议）的候选分组，便于在宝塔计划任务日志中查看
+PLAT_NAME = {"anthropic": "Claude", "openai": "OpenAI/Codex", "gemini": "Gemini"}
+for plat in ("anthropic", "openai", "gemini"):
+    models = sorted(
+        {
+            m
+            for g in groups
+            for k in ("native", "alias")
+            for m in g["protocols"].get(plat, {}).get(k, [])
+        }
+    )
+    print(f"\n== {PLAT_NAME[plat]} 协议（{len(models)} 个模型）")
+    for m in models:
+        nat = [
+            g["name"]
+            for g in groups
+            if m in g["protocols"].get(plat, {}).get("native", [])
+        ]
+        ali = [
+            g["name"]
+            for g in groups
+            if m in g["protocols"].get(plat, {}).get("alias", [])
+        ]
+        seq = (
+            nat + ali
+            if PREFER_NATIVE
+            else [
+                g["name"]
+                for g in groups
+                if m
+                in g["protocols"].get(plat, {}).get("native", [])
+                + g["protocols"].get(plat, {}).get("alias", [])
+            ]
+        )
+        print(f"  {m:34} → " + " → ".join(seq[:6]) + (" …" if len(seq) > 6 else ""))
diff --git a/ops/gen_router.py b/ops/gen_router.py
new file mode 100644
index 0000000..acacc20
--- /dev/null
+++ b/ops/gen_router.py
@@ -0,0 +1,108 @@
+"""生成分组路径路由配置：/opt/sub2api/ops/route_groups.json 与各站点 nginx 配置。
+
+用法: python3 -I gen_router.py
+路径与 Nexus 官网一致（/api/<Nexus 路径>/...），带前缀的分组额外提供省略前缀的短别名。
+"""
+
+import json
+from pathlib import Path
+
+# Nexus 路径 -> (sub2api 分组 id, slug)
+NEXUS_PATHS = {
+    "codex_eco": (3, "codex_eco"),
+    "codex/codex": (4, "codex"),
+    "codex/codex_pro": (5, "codex_pro"),
+    "codex_sp": (6, "codex_sp"),
+    "grok": (7, "grok"),
+    "grok45": (8, "grok45"),
+    "claude_code/mixed_cc_pro_max": (9, "mixed_cc_pro_max"),
+    "kiro": (10, "kiro"),
+    "claude_code/office3_2": (11, "office3_2"),
+    "claude_code/cc_glm": (12, "cc_glm"),
+    "claude_code/cc_glm_global": (13, "cc_glm_global"),
+    "deepseek": (14, "deepseek"),
+    "cc_codex_56": (15, "cc_codex_56"),
+    "gemini_1": (16, "gemini_1"),
+    "codex_image": (17, "codex_image"),
+}
+# Nexus 官网地址有两种：统一地址 /api/<slug>，以及按协议分开 /api/<codex|openai|claude_code|gemini>/<slug>。
+# 每个分组都生成全部 5 种写法（Nexus 地址的超集），用户照抄官网任意地址都能用；协议仍由 URL 后缀决定。
+PROTOCOL_PREFIXES = ("codex", "openai", "claude_code", "gemini")
+routes = {}
+for path, (gid, slug) in NEXUS_PATHS.items():
+    for p in (path, slug, *(f"{prefix}/{slug}" for prefix in PROTOCOL_PREFIXES)):
+        routes.setdefault(p, {"group_id": gid, "slug": slug})
+Path("/opt/sub2api/ops/route_groups.json").write_text(
+    json.dumps(routes, ensure_ascii=False, indent=1)
+)
+
+PROXY_INC = Path("/www/server/panel/vhost/nginx/sub2api-route-proxy.inc")
+PROXY_INC.write_text("""# 由 /opt/sub2api/ops/gen_router.py 生成：分组路径路由的公共代理参数
+auth_request /__s2a_route_auth;
+auth_request_set $s2a_key $upstream_http_x_mapped_key;
+auth_request_set $s2a_qs $upstream_http_x_mapped_query;
+auth_request_set $s2a_reason $upstream_http_x_route_reason;
+error_page 401 = @s2a_route_401;
+error_page 403 = @s2a_route_403;
+proxy_set_header Authorization "Bearer $s2a_key";
+proxy_set_header x-api-key $s2a_key;
+proxy_set_header x-goog-api-key $s2a_key;
+proxy_pass http://sub2api$uri$s2a_qs;
+proxy_cache off;
+proxy_next_upstream off;
+proxy_http_version 1.1;
+proxy_set_header Upgrade $http_upgrade;
+proxy_set_header Connection $sub2api_connection;
+proxy_buffering off;
+proxy_request_buffering off;
+chunked_transfer_encoding on;
+proxy_connect_timeout 60s;
+proxy_send_timeout 3600s;
+proxy_read_timeout 3600s;
+proxy_set_header Host $host;
+proxy_set_header X-Real-IP $remote_addr;
+# 来源标记：sub2api 按可信代理链取最右侧非可信地址 = 127.0.0.2；映射 Key 的 IP 白名单只允许该地址，
+# 因此映射 Key 只能经本入口使用（直接调 /v1 时最右侧是真实客户端 IP，会被拒绝）
+proxy_set_header X-Forwarded-For "$remote_addr, 127.0.0.2";
+proxy_set_header X-Forwarded-Host $host;
+proxy_set_header X-Forwarded-Port $server_port;
+proxy_set_header X-Forwarded-Proto $scheme;
+""")
+
+err = lambda code, typ, msg: (
+    f"location @s2a_route_{code} {{\n    default_type application/json;\n"
+    f'    return {code} \'{{"error":{{"type":"{typ}","message":"{msg}"}}}}\';\n}}\n'
+)
+site = [
+    "# 由 /opt/sub2api/ops/gen_router.py 生成：一个 Key 按 /api/<分组>/ 访问全部分组（与 Nexus 路径一致）",
+    "# 回退：删除本文件后 nginx -t && nginx -s reload",
+    "location = /__s2a_route_auth {\n    internal;\n    proxy_pass http://127.0.0.1:8091/auth;\n"
+    '    proxy_pass_request_body off;\n    proxy_set_header Content-Length "";\n'
+    "    proxy_set_header X-Route-Group $s2a_route_group;\n    proxy_set_header X-Original-Args $s2a_route_args;\n"
+    "    proxy_set_header X-Client-IP $remote_addr;\n"
+    "    proxy_cache off;\n}",
+    err(401, "authentication_error", "Invalid API key"),
+    # 鉴权服务统一回 403 + X-Route-Reason，这里映射为对外状态码
+    "location @s2a_route_403 {\n    default_type application/json;\n"
+    '    if ($s2a_reason = notfound) { return 404 \'{"error":{"type":"not_found_error","message":"Unknown group path"}}\'; }\n'
+    '    if ($s2a_reason = quota) { return 429 \'{"error":{"type":"rate_limit_error","message":"API key quota or rate limit exceeded"}}\'; }\n'
+    '    if ($s2a_reason = ip) { return 403 \'{"error":{"type":"permission_error","message":"Client IP not allowed for this API key"}}\'; }\n'
+    '    if ($s2a_reason = unavailable) { return 503 \'{"error":{"type":"api_error","message":"Route service unavailable, please retry"}}\'; }\n'
+    '    return 403 \'{"error":{"type":"permission_error","message":"API key not allowed for this group"}}\';\n}\n',
+]
+for path in sorted(routes, key=len, reverse=True):
+    # 子请求里的 $args 是子请求自己的（为空），须在主请求阶段先保存原始查询串（Gemini ?key=）
+    # 只放行 /v1/ 与 /v1beta/ 接口；其余后缀（如 /common/v1/search）sub2api 不支持，
+    # 若转发会落到前端 SPA 返回 HTML，故直接返回 JSON 404
+    site.append(
+        f'location ^~ /api/{path}/ {{\n    set $s2a_route_group "{path}";\n    set $s2a_route_args $args;\n'
+        f"    default_type application/json;\n"
+        f'    if ($uri !~ "^/api/{path}/(v1|v1beta)/") {{\n'
+        f'        return 404 \'{{"error":{{"type":"not_found_error","message":"Unsupported endpoint for this group"}}}}\';\n    }}\n'
+        f"    rewrite ^/api/{path}/(.*)$ /$1 break;\n    include {PROXY_INC};\n}}"
+    )
+for domain in ("apiacc.itssx.com", "api.itssx.com"):
+    Path(
+        f"/www/server/panel/vhost/nginx/extension/{domain}/sub2api-group-router.conf"
+    ).write_text("\n".join(site) + "\n")
+print(f"路由 {len(routes)} 条：" + ", ".join(sorted(routes)))
diff --git a/ops/lib.sh b/ops/lib.sh
new file mode 100644
index 0000000..d1f3d54
--- /dev/null
+++ b/ops/lib.sh
@@ -0,0 +1,101 @@
+#!/usr/bin/env bash
+# sub2api 运维脚本公共函数：数据库访问、全局互斥锁、临时管理员 Key（保存并恢复原值）、临时文件
+P=/www/server/pgsql/bin/psql
+export PGPASSWORD=$(awk '/^database:/{f=1} f&&/password:/{print $2; exit}' /opt/sub2api/config.yaml | tr -d "\"'")
+Q() { $P -h localhost -U postgres -d sub2api -At -v ON_ERROR_STOP=1 -c "$1"; }
+# 带变量绑定的查询：值经 psql 标准输入的 \set 传入（不出现在命令行/进程列表中）。
+# 用法：Qv "select :'a'" a=值 ...；SQL 中用 :'名称' 引用（psql 负责加引号转义）
+Qv() {
+	local sql=$1 sets="" kv k v
+	shift
+	for kv in "$@"; do
+		k=${kv%%=*}
+		v=${kv#*=}
+		v=${v//\\/\\\\}
+		v=${v//\'/\\\'}
+		sets+="\\set $k '$v'"$'\n'
+	done
+	$P -h localhost -U postgres -d sub2api -qAt -v ON_ERROR_STOP=1 <<<"$sets$sql"
+}
+
+_TMPFILES=()
+_ADMIN_KEY_SET=0
+# 记录被替换前的原状态，供异常中断（含 SIGKILL、宕机重启）后恢复；放持久化目录，重启不丢
+OPS_STATE_DIR=/var/lib/sub2api-ops
+ADMIN_KEY_JOURNAL=$OPS_STATE_DIR/admin-key.orig
+
+# 退出清理（正常退出、Ctrl-C、TERM、HUP 均执行）；SIGKILL/宕机重启由下次 ops_lock 按持久化记录恢复
+# （宝塔计划任务 #4 每小时整点调用 ops_lock，重启后最迟一小时内自动恢复）
+_ops_cleanup() {
+	[[ $_ADMIN_KEY_SET == 1 ]] && _restore_admin_key
+	((${#_TMPFILES[@]})) && rm -f -- "${_TMPFILES[@]}"
+	return 0
+}
+trap _ops_cleanup EXIT
+trap 'exit 130' INT TERM HUP
+
+# 在当前 Shell 创建并登记临时文件（不能用 $(tmpfile)：子 Shell 里的登记会丢失）。用法：tmpfile 变量名
+tmpfile() {
+	local -n _ref=$1
+	_ref=$(mktemp)
+	chmod 600 "$_ref"
+	_TMPFILES+=("$_ref")
+}
+
+# 全局互斥：同一时间只允许一个运维脚本持有临时管理员 Key / 写配置
+ops_lock() {
+	exec 9>/run/lock/sub2api-ops.lock
+	flock -w 900 9 || {
+		echo "另一个运维脚本正在运行，已放弃" >&2
+		exit 1
+	}
+	# 上一次运行被强制终止（SIGKILL/宕机）时遗留的临时管理员 Key：按日志恢复原状态
+	if [[ -s $ADMIN_KEY_JOURNAL ]]; then
+		echo "发现上次中断遗留的临时管理员 Key，按日志恢复原状态" >&2
+		_load_journal && _restore_admin_key
+	fi
+}
+
+_load_journal() {
+	_ORIG_EXISTS=$(sed -n 1p "$ADMIN_KEY_JOURNAL")
+	_ORIG_VALUE=$(sed -n '2,$p' "$ADMIN_KEY_JOURNAL")
+}
+
+# 临时管理员 Key：须先 ops_lock。先把原状态写入日志再替换，退出时精确恢复（原来有值写回，原来没有则删除）
+with_admin_key() {
+	(: >&9) 2>/dev/null || {
+		echo "with_admin_key 须在 ops_lock 之后调用" >&2
+		exit 1
+	}
+	_ORIG_EXISTS=$(Q "select count(*) from settings where key='admin_api_key'")
+	_ORIG_VALUE=$(Q "select value from settings where key='admin_api_key'")
+	(
+		umask 077
+		mkdir -p "$OPS_STATE_DIR"
+		printf '%s\n%s' "$_ORIG_EXISTS" "$_ORIG_VALUE" >"$ADMIN_KEY_JOURNAL.tmp"
+		sync "$ADMIN_KEY_JOURNAL.tmp" 2>/dev/null
+		mv -f "$ADMIN_KEY_JOURNAL.tmp" "$ADMIN_KEY_JOURNAL"
+	) || {
+		echo "无法写入管理员 Key 恢复记录，已放弃" >&2
+		exit 1
+	}
+	export S2A_ADMIN_KEY="admin-$(openssl rand -hex 32)"
+	_ADMIN_KEY_SET=1
+	Qv "insert into settings(key,value,updated_at) values('admin_api_key', :'v', now())
+	    on conflict(key) do update set value = excluded.value, updated_at = now();" v="$S2A_ADMIN_KEY" >/dev/null
+}
+
+_restore_admin_key() {
+	if [[ $_ORIG_EXISTS == "1" ]]; then
+		Qv "update settings set value = :'v', updated_at = now() where key = 'admin_api_key';" v="$_ORIG_VALUE" >/dev/null
+	else
+		Q "delete from settings where key='admin_api_key'" >/dev/null
+	fi && rm -f -- "$ADMIN_KEY_JOURNAL" && _ADMIN_KEY_SET=0
+}
+
+export_bindings() { # 分组 -> 账号（只读）
+	Qv "select coalesce(json_object_agg(gid, accs),'{}') from (select ag.group_id::text gid, json_agg(json_build_object('id',a.id,'platform',a.platform,'status',a.status,'rate',a.rate_multiplier,'rate_multiplier',a.rate_multiplier,'base',a.credentials->>'base_url','key_ok',(a.credentials->>'api_key') = :'nk','pool',a.credentials->'pool_mode','mm',a.credentials->'model_mapping','concurrency',a.concurrency)) accs from account_groups ag join accounts a on a.id=ag.account_id and a.deleted_at is null group by ag.group_id) t" nk="$NEXUS_KEY"
+}
+export_channels() { # 渠道 -> 分组（只读）
+	Q "select coalesce(json_agg(json_build_object('id',c.id,'group_ids',(select coalesce(json_agg(cg.group_id),'[]') from channel_groups cg where cg.channel_id=c.id))),'[]') from channels c"
+}
diff --git a/ops/mail_report.py b/ops/mail_report.py
new file mode 100644
index 0000000..6f3cb1f
--- /dev/null
+++ b/ops/mail_report.py
@@ -0,0 +1,339 @@
+"""把运维脚本的结构化结果整理成邮件报告 JSON（交给 notify.py json 渲染成表格邮件）。
+
+用法:
+  python3 -I mail_report.py sync    <对账前.json> <同步.json> <对账后.json> <同步退出码> [备份文件]
+  python3 -I mail_report.py restore <backup_restore_check.log>      恢复演练最近一次结果
+"""
+
+import json
+import re
+import sys
+from datetime import datetime, timedelta, timezone
+
+NOW = datetime.now(timezone(timedelta(hours=8))).strftime("%Y-%m-%d %H:%M")
+_BIZ = json.load(open("/opt/sub2api/ops/business.json"))
+BUY, SELL_MIN = (
+    _BIZ["buy_cny_per_usd"],
+    _BIZ["sell_cny_per_usd_min"],
+)  # 进价、客户最低充值单价（¥/$）
+PLAT = {"anthropic": "Claude", "openai": "OpenAI/Codex", "gemini": "Gemini"}
+
+
+def load(path):
+    try:
+        with open(path) as f:
+            return json.load(f)
+    except (OSError, ValueError):
+        return {}
+
+
+def x(v):
+    return f"×{float(v):g}"
+
+
+def margin(sell, cost):
+    return 1 - (BUY * cost) / (SELL_MIN * sell) if sell else 0
+
+
+def sell_cell(sell, ref):
+    """售价与 Nexus 普通倍率比较：高于红底↑、低于蓝底↓、一致无底色。"""
+    if abs(sell - ref) < 1e-9:
+        return x(sell)
+    up = sell > ref
+    return {
+        "text": f"{x(sell)} {'↑' if up else '↓'}",
+        "bold": True,
+        "tone": "bad" if up else "#1d4ed8",
+        "bg": "#fee2e2" if up else "#dbeafe",
+    }
+
+
+def tone_margin(m):
+    return "bad" if m < 0 else ("warn" if m < 0.1 else "good")
+
+
+def sync_report(a1, s, a2, rc, backup=""):
+    i1, i2 = a1.get("issues", []), a2.get("issues", [])
+    events, errors, notes = s.get("events", []), s.get("errors", []), s.get("notes", [])
+    rate = [i for i in i1 if i["kind"] == "rate_change"]
+    loss = [i for i in i1 + i2 if i["kind"] == "loss"]
+    loss = list({i["slug"]: i for i in loss}.values())
+    manual = [i for i in i2 if i["kind"] != "rate_change"] + [
+        {"slug": "同步校验", "msg": e} for e in errors
+    ]
+    config_before = [
+        i for i in i1 if i["kind"] == "config"
+    ]  # sell_rate 差异已在「售价倍率」表中体现
+
+    if rc != 0 or errors:
+        status, title = "error", "Nexus 自动同步失败，未写入或部分写入"
+    elif manual or loss:
+        status, title = "warn", "Nexus 配置变化需人工处理"
+    elif rate and not config_before and not events:
+        status, title = "info", "Nexus 默认分组倍率变化提醒"
+    else:
+        status, title = "ok", "Nexus 配置变化已自动同步"
+
+    secs = []
+    if rate:
+        rows = []
+        for i in rate:
+            m = margin(i["sell"], i["cost"])
+            if i["sell"] < i["new"] - 1e-9:
+                tip = {
+                    "text": f"可上调至 {x(i['new'])}（与 Nexus 同价）",
+                    "tone": "warn",
+                }
+            elif i["sell"] > i["new"] + 1e-9:
+                tip = {"text": "本站已高于 Nexus 新价", "tone": "warn"}
+            else:
+                tip = {"text": "与 Nexus 一致，无需调整", "tone": "good"}
+            rows.append(
+                [
+                    i["slug"],
+                    x(i["old"]),
+                    {"text": x(i["new"]), "bold": True},
+                    sell_cell(i["sell"], i["new"]),
+                    x(i["cost"]),
+                    {"text": f"{m:.1%}", "tone": tone_margin(m)},
+                    tip,
+                ]
+            )
+        secs.append(
+            {
+                "heading": "Nexus 默认分组倍率变化（售价由你决定，未自动修改）",
+                "note": f"修改位置：后台 → 分组管理 → 编辑 → 费率倍数。毛利按进价 ¥{BUY}/$、客户最低充值单价 ¥{SELL_MIN}/$ 计算。",
+                "columns": [
+                    "分组",
+                    "Nexus 原倍率",
+                    "Nexus 新倍率",
+                    "本站售价",
+                    "本站成本",
+                    "大额档毛利",
+                    "建议",
+                ],
+                "rows": rows,
+            }
+        )
+    if loss:
+        secs.append(
+            {
+                "heading": "售价过低：大额充值客户每笔亏损",
+                "columns": ["分组", "本站售价", "成本（合作商）", "大额档毛利"],
+                "rows": [
+                    [
+                        i["slug"],
+                        {"text": x(i["sell"]), "tone": "bad", "bold": True},
+                        x(i["cost"]),
+                        {"text": f"{margin(i['sell'], i['cost']):.1%}", "tone": "bad"},
+                    ]
+                    for i in loss
+                ],
+            }
+        )
+    sr = [e for e in events if e["kind"] == "sell_rate"]
+    if sr:
+        srows = []
+        for e in sr:
+            m = margin(e["new"], e["cost"])
+            up = e["new"] > e["old"]
+            srows.append(
+                [
+                    e["slug"],
+                    x(e["old"]),
+                    {
+                        "text": f"{x(e['new'])} {'↑' if up else '↓'}",
+                        "bold": True,
+                        "tone": "bad" if up else "#1d4ed8",
+                        "bg": "#fee2e2" if up else "#dbeafe",
+                    },
+                    x(e["cost"]),
+                    {"text": f"{m:.1%}", "tone": tone_margin(m)},
+                ]
+            )
+        secs.append(
+            {
+                "heading": "售价倍率已自动跟随 Nexus 普通",
+                "note": "客户扣费从同步完成起按新倍率计算。红底↑ 涨价、蓝底↓ 降价。",
+                "columns": [
+                    "分组",
+                    "原售价",
+                    "新售价（= Nexus 普通）",
+                    "成本（合作商）",
+                    "大额档毛利率",
+                ],
+                "rows": srows,
+            }
+        )
+    mc = [e for e in events if e["kind"] == "model_change"]
+    if mc:
+        secs.append(
+            {
+                "heading": "模型变化（已自动同步）",
+                "columns": ["分组", "协议", "新增模型", "移除模型"],
+                "rows": [
+                    [
+                        e["slug"],
+                        PLAT.get(e["plat"], e["plat"]),
+                        {
+                            "text": "、".join(e["added"]) or "—",
+                            "tone": "good" if e["added"] else "muted",
+                        },
+                        {
+                            "text": "、".join(e["removed"]) or "—",
+                            "tone": "bad" if e["removed"] else "muted",
+                        },
+                    ]
+                    for e in mc
+                ],
+            }
+        )
+    cr = [e for e in events if e["kind"] == "cost_rate"]
+    if cr:
+        secs.append(
+            {
+                "heading": "成本倍率变化（已按 Nexus 合作商档同步）",
+                "columns": ["分组", "协议", "原成本", "新成本"],
+                "rows": [
+                    [
+                        e["slug"],
+                        PLAT.get(e["plat"], e["plat"]),
+                        x(e["old"]),
+                        {
+                            "text": x(e["new"]),
+                            "bold": True,
+                            "tone": "bad" if e["new"] > e["old"] else "good",
+                        },
+                    ]
+                    for e in cr
+                ],
+            }
+        )
+    acc = [e for e in events if e["kind"] in ("account_new", "account_disabled")]
+    if acc:
+        secs.append(
+            {
+                "heading": "上游账号变化",
+                "columns": ["分组", "协议", "操作"],
+                "rows": [
+                    [
+                        e["slug"],
+                        PLAT.get(e["plat"], e["plat"]),
+                        {"text": f"新建（{e['models']} 个模型）", "tone": "good"}
+                        if e["kind"] == "account_new"
+                        else {
+                            "text": f"停用账号 #{e['id']}（协议已不开放）",
+                            "tone": "warn",
+                        },
+                    ]
+                    for e in acc
+                ],
+            }
+        )
+    if config_before:
+        secs.append(
+            {
+                "heading": "同步前检测到的差异",
+                "columns": ["分组", "差异"],
+                "rows": [[i["slug"], i["msg"]] for i in config_before],
+            }
+        )
+    if manual:
+        secs.append(
+            {
+                "heading": "需要人工处理",
+                "columns": ["分组 / 项目", "说明"],
+                "rows": [
+                    [i["slug"], {"text": i["msg"], "tone": "bad"}] for i in manual
+                ],
+            }
+        )
+    tips = [["同步提示", n] for n in notes] + [
+        ["计费结构限制", n] for n in a2.get("notes", a1.get("notes", []))
+    ]
+    if tips:
+        secs.append(
+            {
+                "heading": "提示（无需处理）",
+                "columns": ["类型", "说明"],
+                "rows": [[t, {"text": n, "tone": "muted"}] for t, n in tips],
+            }
+        )
+
+    summary = [
+        ["检查项", a2.get("checked") or a1.get("checked") or "—"],
+        ["同步前差异", len(i1)],
+        ["同步后差异", len(i2)],
+        ["同步结果", "成功" if rc == 0 and not errors else "失败"],
+    ]
+    footer = "日志：/opt/sub2api/ops/auto_sync.log"
+    if backup:
+        footer += f"　·　写入前数据库备份：{backup}"
+    return {
+        "title": title,
+        "status": status,
+        "subtitle": f"{NOW}（北京时间）· 每小时整点自动对账",
+        "summary": summary,
+        "sections": secs,
+        "footer": footer,
+    }
+
+
+def restore_report(log_path):
+    lines = open(log_path, encoding="utf-8").read().splitlines()
+    start = max(i for i, l in enumerate(lines) if l.startswith("==== "))
+    block = lines[start:]
+    rows, info = [], []
+    for l in block:
+        m = re.match(r"\s+(\S+) 备份=(\S*) 生产=(\S*)", l)
+        if m:
+            t, b, p = m.groups()
+            okv = (
+                b.isdigit()
+                and p.isdigit()
+                and (t == "usage_logs" or int(b) > 0)
+                and int(b) <= int(p)
+            )
+            rows.append(
+                [
+                    t,
+                    b,
+                    p,
+                    {
+                        "text": "正常" if okv else "异常",
+                        "tone": "good" if okv else "bad",
+                    },
+                ]
+            )
+        elif not l.startswith("====") and l.strip():
+            info.append(l.strip())
+    passed = any("结果：通过" in l for l in block)
+    return {
+        "title": "数据库备份恢复演练" + ("通过" if passed else "失败"),
+        "status": "ok" if passed else "error",
+        "subtitle": f"{NOW}（北京时间）· 宝塔计划任务 #5",
+        "sections": (
+            [
+                {
+                    "heading": "关键表行数核对",
+                    "columns": ["表", "备份", "生产", "结论"],
+                    "rows": rows,
+                }
+            ]
+            if rows
+            else []
+        )
+        + [{"heading": "执行记录", "text": "\n".join(info)}],
+        "footer": f"日志：{log_path}",
+    }
+
+
+if __name__ == "__main__":
+    if sys.argv[1] == "sync":
+        a1, s, a2 = (load(p) for p in sys.argv[2:5])
+        report = sync_report(
+            a1, s, a2, int(sys.argv[5]), sys.argv[6] if len(sys.argv) > 6 else ""
+        )
+    else:
+        report = restore_report(sys.argv[2])
+    print(json.dumps(report, ensure_ascii=False))
diff --git a/ops/manual-refund.sh b/ops/manual-refund.sh
new file mode 100755
index 0000000..f5b674c
--- /dev/null
+++ b/ops/manual-refund.sh
@@ -0,0 +1,18 @@
+#!/usr/bin/env bash
+# 手动退款登记（钱已在支付平台线下退回后，在 sub2api 补记）。说明见 manual_refund.py。
+# 用法: manual-refund.sh <订单号> <金额：余额美元 3 或人民币 1元> [原因] [--apply]；不加 --apply 只预览。
+# --apply 前把订单与用户行备份到 /root/backup/manual_refund_<订单号>_<时间>.json
+set -euo pipefail
+source /opt/sub2api/ops/lib.sh # 提供 PGPASSWORD 与 ops_lock
+if [[ " $* " == *" --apply "* ]]; then
+	ops_lock
+	f=/root/backup/manual_refund_${1}_$(date +%Y%m%d%H%M%S).json
+	(
+		umask 077
+		Qv "select json_build_object('order', (select row_to_json(o) from payment_orders o where id = :'oid'),
+			'user_balance', (select json_build_object('id', u.id, 'balance', u.balance) from users u
+			 join payment_orders o on o.user_id = u.id where o.id = :'oid'))" oid="$1" >"$f"
+	)
+	echo "已备份: $f"
+fi
+python3 -I /opt/sub2api/ops/manual_refund.py "$@"
diff --git a/ops/manual_refund.py b/ops/manual_refund.py
new file mode 100644
index 0000000..99563bd
--- /dev/null
+++ b/ops/manual_refund.py
@@ -0,0 +1,134 @@
+"""手动退款登记：钱已在支付平台线下退回（如易支付需联系客服退款），在 sub2api 中补记退款。
+
+与 sub2api 0.2.15 退款成功路径一致（payment_refund.go：DeductAvailableBalance + markRefundOk），只是不调用支付网关：
+  - 扣回客户余额：min(退回余额$, 当前余额)，与原生「最多扣到 0」相同；
+  - 订单状态：退回额 < 到账额 → PARTIALLY_REFUNDED，否则 REFUNDED；写 refund_amount / refund_reason / refund_at；
+  - 审计日志：REFUND_SUCCESS，detail 标注 manual=true、网关退款¥（= 实付 × 退回 / 到账，与原生同公式）；
+  - 不回收返利（原生退款同样不回收）；清除该用户余额缓存，使新余额立即生效。
+全部在一个数据库事务内完成；订单状态不允许退款或退回额超过到账额时拒绝。
+
+用法（经 manual-refund.sh 调用，提供 PGPASSWORD 与锁）：
+  manual-refund.sh <订单号> <金额> [原因]            预览（只读）
+  manual-refund.sh <订单号> <金额> [原因] --apply    写入
+  金额：余额美元（3 或 '$3'）或实际退款人民币（'¥1' 或 1元，按订单实付/到账折算）
+"""
+
+raise SystemExit(
+    "manual-refund.sh 已停用：请在 https://apiacc.itssx.com/relay/refund.html 登记退款"
+    "（支持同一订单多次退款，并写入退款台账 s2a_ops.manual_refunds；本脚本不写台账，继续使用会导致日报退款口径错误）。"
+)
+import json  # noqa: E402
+import os
+import subprocess
+import sys
+
+PSQL = "/www/server/pgsql/bin/psql"
+REDIS = "/www/server/redis/src/redis-cli"
+REFUNDABLE = ("COMPLETED", "REFUND_REQUESTED", "REFUND_FAILED")
+
+args = [a for a in sys.argv[1:] if a != "--apply"]
+APPLY = "--apply" in sys.argv
+if len(args) < 2:
+    raise SystemExit(__doc__)
+oid, amt_arg = int(args[0]), args[1].strip()
+# 金额可写余额 $（如 3 或 $3），也可写人民币（如 ¥1 或 1元，按订单 实付¥/到账$ 折算成退回余额）
+CNY = amt_arg.startswith(("¥", "￥")) or amt_arg.endswith("元")
+amt_val = float(amt_arg.strip("$¥￥元 "))
+reason = (args[2] if len(args) > 2 else "线下退款（支付平台客服处理）").strip()
+if "$r$" in reason:
+    raise SystemExit("原因含非法字符")
+
+
+def q(sql):
+    return subprocess.run(
+        [
+            PSQL,
+            "-h",
+            "localhost",
+            "-U",
+            "postgres",
+            "-d",
+            "sub2api",
+            "-qAt",
+            "-v",
+            "ON_ERROR_STOP=1",
+        ],
+        input=sql,
+        capture_output=True,
+        text=True,
+        check=True,
+        env=os.environ,
+    ).stdout.strip()
+
+
+o = json.loads(
+    q(
+        f"""select row_to_json(t) from (select o.id, o.user_id, o.order_type, o.status, o.amount, o.pay_amount,
+        o.bonus_amount, o.refund_amount, o.payment_trade_no is not null as has_trade, u.balance
+        from payment_orders o join users u on u.id = o.user_id where o.id = {oid}) t"""
+    )
+    or "null"
+)
+if not o:
+    raise SystemExit(f"订单 {oid} 不存在")
+if o["order_type"] != "balance":
+    raise SystemExit(f"订单类型 {o['order_type']} 不是余额充值，本脚本不处理")
+if o["status"] not in REFUNDABLE:
+    raise SystemExit(f"订单状态 {o['status']} 不允许退款（允许：{REFUNDABLE}）")
+amount, pay, balance = float(o["amount"]), float(o["pay_amount"]), float(o["balance"])
+refund = round(amt_val * amount / pay, 2) if CNY else round(amt_val, 2)
+if refund <= 0:
+    raise SystemExit("退回金额必须大于 0")
+if refund - amount > 0.005:
+    raise SystemExit(f"退回余额 ${refund} 超过订单到账 ${amount}")
+gateway_cny = pay if abs(refund - amount) <= 0.005 else round(pay * refund / amount, 2)
+deduct = round(min(refund, max(balance, 0)), 8)
+status = "PARTIALLY_REFUNDED" if refund < amount else "REFUNDED"
+
+print(f"订单 #{oid}  用户 #{o['user_id']}  状态 {o['status']} → {status}")
+print(f"  到账 ${amount}（含赠送 ${o['bonus_amount']}），实付 ¥{pay}")
+print(f"  退回余额 ${refund} → 对应网关退款 ¥{gateway_cny}（请与支付平台实际退款核对）")
+print(
+    f"  扣回余额 ${deduct}（当前余额 ${balance:.8f} → ${balance - deduct:.8f}）"
+    + ("；余额不足，按原生规则最多扣到 0" if deduct < refund else "")
+)
+print(f"  原因：{reason}")
+if not APPLY:
+    print("预览（未写入）。确认后加 --apply 执行。")
+    sys.exit(0)
+
+detail = json.dumps(
+    {
+        "refundAmount": refund,
+        "reason": reason,
+        "balanceDeducted": deduct,
+        "force": False,
+        "manual": True,
+        "gatewayRefundCny": gateway_cny,
+        "gateway": "offline",
+    },
+    ensure_ascii=False,
+)
+res = q(
+    f"""begin;
+do $do$ begin
+  perform 1 from payment_orders where id = {oid} and status in {REFUNDABLE} for update;
+  if not found then raise exception '订单状态已变化，未写入'; end if;
+end $do$;
+with target as (select id, balance from users where id = {o["user_id"]} and deleted_at is null for update),
+upd as (update users u set balance = target.balance - least({refund}, greatest(target.balance, 0)), updated_at = now()
+        from target where u.id = target.id returning target.balance - u.balance as deducted)
+select deducted from upd;
+update payment_orders set status = '{status}', refund_amount = {refund}, refund_reason = $r${reason}$r$,
+       refund_at = now(), force_refund = false, updated_at = now()
+ where id = {oid} and status in {REFUNDABLE};
+insert into payment_audit_logs(order_id, action, detail, operator) values ('{oid}', 'REFUND_SUCCESS', $r${detail}$r$, 'admin:manual');
+commit;"""
+)
+print("已写入：", res.replace("\n", " "))
+subprocess.run(
+    [REDIS, "-h", "127.0.0.1", "-p", "6379", "del", f"billing:balance:{o['user_id']}"],
+    capture_output=True,
+    check=False,
+)
+print("已清除余额缓存 billing:balance:%s" % o["user_id"])
diff --git a/ops/nexus-auto-sync.sh b/ops/nexus-auto-sync.sh
new file mode 100755
index 0000000..6247e82
--- /dev/null
+++ b/ops/nexus-auto-sync.sh
@@ -0,0 +1,64 @@
+#!/usr/bin/env bash
+# 自动跟随 Nexus：对账 → 有差异则 nexus-sync.sh --apply → 再对账 → 邮件通知管理员。
+# 同一组差异若自动同步无法消除（如 Nexus 新分组、模型数骤减保护），只通知一次；6 小时后自动重试一次（排除临时异常）。
+# 同步成功后立即刷新统一路由匹配表，不必等下一个整点。
+# 定时：宝塔计划任务 #4（每小时整点）；日志 /opt/sub2api/ops/auto_sync.log
+set -uo pipefail
+OPS=/opt/sub2api/ops
+STATE=$OPS/auto_sync.state
+exec >>"$OPS/auto_sync.log" 2>&1
+source "$OPS/lib.sh" # 提供 PGPASSWORD 给 notify.py
+ts() { TZ=Asia/Shanghai date '+%F %T'; }
+issues() { sed -n '2,$p' <<<"$1" | grep -v -e '^全部与 Nexus 一致$' -e '^ℹ'; }
+digest() { sha256sum | cut -c1-16; }
+notify_text() { python3 -I "$OPS/notify.py" "$1" "$2" <<<"$3" || echo "$(ts) 邮件发送失败"; }
+J1=$(mktemp) JS=$(mktemp) J2=$(mktemp)
+trap 'rm -f -- "$J1" "$JS" "$J2"' EXIT
+
+if ! A1=$(AUDIT_JSON=$J1 "$OPS/config-audit.sh" 2>&1); then
+	h=$(digest <<<"fail")
+	if [ "$(cat "$STATE" 2>/dev/null)" != "$h" ]; then
+		notify_text "Nexus 对账失败（未做任何修改）" error "$(ts) 对账脚本执行失败，可能是 Nexus 接口异常或网络问题；恢复后会自动继续。
+
+$(tail -20 <<<"$A1")"
+		echo "$h" >"$STATE"
+	fi
+	echo "$(ts) 对账失败：$(tail -1 <<<"$A1")"
+	exit 1
+fi
+I1=$(issues "$A1")
+if [ -z "$I1" ]; then
+	echo "$(ts) 一致（$(head -1 <<<"$A1")）"
+	rm -f -- "$STATE"
+	exit 0
+fi
+h1=$(digest <<<"$I1")
+if [ "$(cat "$STATE" 2>/dev/null)" = "$h1" ]; then
+	age=$(($(date +%s) - $(stat -c %Y "$STATE")))
+	if [ "$age" -lt 21600 ]; then
+		echo "$(ts) 差异与上次相同（已通知，自动同步无法消除），跳过；$(((21600 - age) / 60)) 分钟后重试"
+		exit 0
+	fi
+	echo "$(ts) 差异已持续 6 小时，重试同步"
+fi
+
+echo "$(ts) 发现差异，开始自动同步：
+$I1"
+S=$(SYNC_JSON=$JS "$OPS/nexus-sync.sh" --apply 2>&1)
+rc=$?
+echo "$S"
+A2=$(AUDIT_JSON=$J2 "$OPS/config-audit.sh" 2>&1)
+I2=$(issues "$A2")
+backup=$(sed -n 's/^已备份: \(\S*\).*/\1/p' <<<"$S")
+if [ $rc -eq 0 ]; then # 分组/模型/协议可能已变化，立即刷新统一路由匹配表
+	bash "$OPS/refresh-auto-route.sh" >/dev/null 2>&1 && echo "$(ts) 统一路由匹配表已刷新" ||
+		echo "$(ts) 统一路由匹配表刷新失败（整点任务会再试）"
+fi
+if [ $rc -eq 0 ] && [ -z "$I2" ]; then
+	rm -f -- "$STATE"
+else
+	digest <<<"${I2:-$I1}" >"$STATE"
+fi
+python3 -I "$OPS/mail_report.py" sync "$J1" "$JS" "$J2" "$rc" "$backup" | python3 -I "$OPS/notify.py" json ||
+	echo "$(ts) 邮件发送失败"
+echo "$(ts) 同步完成（退出码 $rc，同步后差异 $(grep -c . <<<"$I2")）"
diff --git a/ops/nexus-sync.sh b/ops/nexus-sync.sh
new file mode 100755
index 0000000..e784fa4
--- /dev/null
+++ b/ops/nexus-sync.sh
@@ -0,0 +1,24 @@
+#!/usr/bin/env bash
+# 用法: nexus-sync.sh          预览（只读：只查 Nexus 与本地数据库，不调用管理接口、不写任何数据）
+#       nexus-sync.sh --apply  写入（先加锁，再读取现状快照；写入前 pg_dump 备份；临时管理员 Key 用完恢复原值）
+#       附加 --force 可跳过「模型数骤减」保护
+set -euo pipefail
+source /root/.config/sub2api-nexus.env
+export NEXUS_KEY
+source /opt/sub2api/ops/lib.sh
+if [[ " $* " == *" --apply "* ]]; then
+	ops_lock # 先锁后读快照，保证计划基于最新现状
+	f=/root/backup/sub2api_before_nexus_sync_$(date +%Y%m%d%H%M%S).sql.gz
+	(
+		umask 077
+		/www/server/pgsql/bin/pg_dump -h localhost -U postgres -d sub2api --no-owner --no-acl | gzip >"$f"
+	)
+	echo "已备份: $f ($(du -h "$f" | cut -f1))"
+	with_admin_key
+fi
+tmpfile S2A_BINDINGS
+tmpfile S2A_CHANNELS
+export S2A_BINDINGS S2A_CHANNELS
+export_bindings >"$S2A_BINDINGS"
+export_channels >"$S2A_CHANNELS"
+python3 -I /opt/sub2api/ops/nexus_sync.py "$@"
diff --git a/ops/nexus_default_rates.json b/ops/nexus_default_rates.json
new file mode 100644
index 0000000..4ed744f
--- /dev/null
+++ b/ops/nexus_default_rates.json
@@ -0,0 +1,17 @@
+{
+ "codex_eco": 1.28,
+ "codex": 1.28,
+ "codex_pro": 1.28,
+ "codex_sp": 1.28,
+ "grok": 1.28,
+ "grok45": 1.28,
+ "mixed_cc_pro_max": 2.98,
+ "kiro": 2.98,
+ "office3_2": 4.98,
+ "cc_glm": 2.98,
+ "cc_glm_global": 2.98,
+ "deepseek": 4.2,
+ "cc_codex_56": 1.28,
+ "gemini_1": 3.3,
+ "codex_image": 1.0
+}
\ No newline at end of file
diff --git a/ops/nexus_sync.py b/ops/nexus_sync.py
new file mode 100644
index 0000000..9f6f974
--- /dev/null
+++ b/ops/nexus_sync.py
@@ -0,0 +1,887 @@
+"""把 Nexus 分组同步为 sub2api 组合分组：一个分组同时支持 Nexus 该分组开放的全部协议。
+
+在 ssa 本机运行。环境变量:
+  S2A_ADMIN_KEY  临时管理员 Key（调用 127.0.0.1:8080 管理接口）
+  NEXUS_KEY      Nexus 上游 key
+用法:
+  python3 -I nexus_sync.py            预览（不写入）
+  python3 -I nexus_sync.py --apply    写入
+每次运行都从 Nexus 实时拉取分组/协议/模型/价格，可反复执行（幂等）。
+"""
+
+import json
+import math
+import os
+import sys
+import urllib.error
+import urllib.request
+
+APPLY = "--apply" in sys.argv
+ADMIN = "http://127.0.0.1:8080/api/v1/admin"
+S2A_KEY = os.environ.get("S2A_ADMIN_KEY", "")  # 仅 --apply 时需要
+NEXUS_KEY = os.environ["NEXUS_KEY"]
+NEXUS = "https://nexus.itssx.com"
+
+# Nexus slug -> (sub2api 分组 id, 上游路径)。分组名/倍率等已按 Nexus 配好，这里只管协议与模型。
+GROUPS = {
+    "codex_eco": (3, "codex_eco"),
+    "codex": (4, "codex/codex"),
+    "codex_pro": (5, "codex/codex_pro"),
+    "codex_sp": (6, "codex_sp"),
+    "grok": (7, "grok"),
+    "grok45": (8, "grok45"),
+    "mixed_cc_pro_max": (9, "claude_code/mixed_cc_pro_max"),
+    "kiro": (10, "kiro"),
+    "office3_2": (11, "claude_code/office3_2"),
+    "cc_glm": (12, "claude_code/cc_glm"),
+    "cc_glm_global": (13, "claude_code/cc_glm_global"),
+    "deepseek": (14, "deepseek"),
+    "cc_codex_56": (15, "cc_codex_56"),
+    "gemini_1": (16, "gemini_1"),
+    "codex_image": (17, "codex_image"),
+}
+# Nexus 的 Gemini 格式响应对这些分组报的用量与其自身扣费不一致（缺 cachedContentTokenCount、
+# 少报输出/缓存写入），sub2api 无法按 Nexus 口径计费（实测多收 1.9–4.2 倍或少收 38%），故暂不开放
+# Gemini 协议；其余协议不受影响。Nexus 修复后从此集合移除并重新 --apply 即可恢复。（2026-10-10）
+GEMINI_BILLING_MISMATCH = {
+    "codex_eco",
+    "codex",
+    "codex_pro",
+    "codex_sp",
+    "grok",
+    "grok45",
+    "mixed_cc_pro_max",
+    "kiro",
+}
+# Nexus 接口 -> (sub2api 平台, Nexus modelsByType 协议键, sub2api 组合路由 endpoint 列表)
+ENDPOINTS = {
+    "claude_messages": ("anthropic", ["claude_code"], ["messages", "count_tokens"]),
+    "openai_chat_completions": ("openai", ["openai", "codex"], ["chat_completions"]),
+    "openai_responses": ("openai", ["codex", "openai"], ["responses"]),
+    "gemini_generate": ("gemini", ["gemini"], ["gemini"]),
+    "openai_images": ("openai", ["images"], ["images"]),
+    "openai_images_edit": ("openai", ["images"], ["images"]),
+}
+
+
+def http(method, url, body=None, headers=None):
+    req = urllib.request.Request(
+        url,
+        method=method,
+        data=None if body is None else json.dumps(body).encode(),
+        headers={"Content-Type": "application/json", **(headers or {})},
+    )
+    try:
+        with urllib.request.urlopen(req, timeout=60) as r:
+            return json.load(r)
+    except urllib.error.HTTPError as e:
+        return json.load(e)
+
+
+def admin(method, path, body=None):
+    if method != "GET" and not APPLY:
+        return {}
+    if not S2A_KEY:  # 预览模式不应调用管理接口
+        raise SystemExit(f"内部错误：预览模式调用了管理接口 {method} {path}")
+    d = http(method, ADMIN + path, body, {"x-api-key": S2A_KEY})
+    if d.get("code") != 0:
+        raise SystemExit(
+            f"{method} {path} 失败: {d.get('message')} {json.dumps(d, ensure_ascii=False)[:300]}"
+        )
+    return d.get("data") or {}
+
+
+def nexus(path):
+    return http("GET", NEXUS + path, headers={"Authorization": f"Bearer {NEXUS_KEY}"})
+
+
+# ---------- 定价 ----------
+pricing = {m["name"]: m for m in nexus("/api-go/relay/model-pricing")["data"]}
+kq = nexus(f"/api-go/relay/key-query?key={NEXUS_KEY}")["data"]
+allowed = {g["slug"]: g for g in kq["allowedGroups"]}
+PRICE_KEYS = (
+    "input_price",
+    "output_price",
+    "cache_read_price",
+    "cache_write_price",
+    "cache_write_1h_price",
+)
+
+
+def per_token(v):
+    return None if v in (None, "") else float(f"{float(v) / 1e6:.10g}")
+
+
+RATIO_FIELDS = (
+    ("input", "input_per_million_tokens"),
+    ("output", "output_per_million_tokens"),
+    ("cache_read", "cache_read_per_million_tokens"),
+    ("cache_write", "cache_write_per_million_tokens"),
+    ("cache_write_1h", "cache_write_1h_per_million_tokens"),
+    ("image_input", "image_input_per_million_tokens"),
+    ("image_output", "image_output_per_million_tokens"),
+)
+# sub2api 每个模型只有一个 fast/flex 倍率，作用于全部字段（含图片 token）与长上下文阶梯价。为保证不少于 Nexus（不亏本）：
+#  - 倍率取「全部 token 字段（输入、输出、缓存读、缓存写、1h 缓存写、图片输入、图片输出）× 基础价与各级阶梯」中
+#    Nexus 档位价 / 本站标准价的最大值，按 4 位小数向上取整；比 Nexus 多收的字段只提示（STRUCT_NOTES）；
+#  - 本站标准价按 price_entry 与 sub2api 的回退规则计算（显式 0 保留为 0，只有缺失才回退）；
+#  - Nexus 某级或某字段没有档位价时，按它可能收取的最高价估计：档位基础价与该级标准价取大（即假设不打折）；
+#  - 本站标准价为 0 而 Nexus 档位收费、档位阶梯比基础多或阈值不同 → 倍率无法表达，记入 STRUCT_ERRORS，阻止自动同步；
+#  - Nexus 没有 Flex 价的模型 flex_multiplier 固定 1（sub2api 默认 Flex ×0.5 会少收）。
+# 另由 sub2api「OpenAI Fast/Flex 策略」去除无法按 Nexus 价计费的档位（按标准档执行与计费）：
+#  - Ultrafast：Nexus 无此档价格，一律去除；
+#  - Flex：FLEX_ENABLED=False 时全部去除且 flex_multiplier 一律为 1（2026-10-11 实测 Nexus 拒绝 Flex：
+#    "Unsupported service_tier: flex"，按决定改为按标准档执行与计费）；为 True 时只放行有 Nexus Flex 价且保底后
+#    仍有折扣（<1）的模型，其余去除；
+#  - Fast：保底倍率超过 Nexus 输入/输出比例 1.5 倍、或 Fast 到不了 Nexus（FAST_NOT_DELIVERED）的模型去除；
+#    Nexus 无 Fast 价的模型 fast_multiplier = 1（Nexus 按标准价扣，本站同价）。
+#  渠道倍率仍保留保底值，策略覆盖不到的路径（非 OpenAI 网关）也不会少收。
+MAIN_FIELDS = ("input", "output")
+TOKEN_FIELDS = (
+    "input",
+    "output",
+    "cache_read",
+    "cache_write",
+    "cache_write_1h",
+    "image_input",
+    "image_output",
+)
+STRUCT_NOTES, STRUCT_ERRORS = {}, {}
+FILTER_TIERS = {"priority": set(), "flex": set()}  # 需去除档位的 Nexus 实际执行模型
+# 实测（2026-10-11）Fast 到不了 Nexus 的模型前缀：经 OpenAI 协议请求时 Nexus 记录的请求档位为空、按标准价扣费
+FAST_NOT_DELIVERED = ("gemini-",)
+FLEX_ENABLED = False  # Nexus 恢复支持 Flex 后改为 True 并重新同步即可放行
+FLEX_OK = set()  # Flex 可按 Nexus 价放行的实际执行模型
+FAST_LIMIT = 1.5
+POLICY_MARK = "nexus-sync 自动管理：该模型此档位无法按 Nexus 价计费，已去除 service_tier 按标准档执行"
+PSQL = "/www/server/pgsql/bin/psql"
+
+
+def _psql(sql):
+    import subprocess
+
+    return subprocess.run(
+        [PSQL, "-h", "localhost", "-U", "postgres", "-d", "sub2api", "-qAt"],
+        input=sql,
+        capture_output=True,
+        text=True,
+        check=True,
+        env=os.environ,
+    ).stdout.strip()
+
+
+def read_policy():
+    """sub2api 设置表中的 OpenAI Fast/Flex 策略（sub2api 每次请求直接读库，无缓存）。"""
+    v = _psql("select value from settings where key = 'openai_fast_policy_settings'")
+    return json.loads(v) if v else {"rules": []}
+
+
+def _rule(tier, action, models=None, fallback=None):
+    r = {
+        "service_tier": tier,
+        "action": action,
+        "scope": "all",
+        "error_message": POLICY_MARK,
+    }
+    if models:
+        r["model_whitelist"] = sorted(models)
+    if fallback:
+        r["fallback_action"] = fallback
+    return r
+
+
+def managed_rules(fast_filter, flex_pass):
+    """本脚本管理的规则（error_message = POLICY_MARK 标记）。"""
+    rules = [
+        _rule("ultrafast", "filter"),
+        _rule("flex", "pass", flex_pass, "filter")
+        if flex_pass
+        else _rule("flex", "filter"),
+    ]
+    if fast_filter:
+        rules.append(_rule("priority", "filter", fast_filter))
+    return rules
+
+
+# sub2api 后台保存网关设置时会重写整份策略：filter 规则的 error_message 被丢弃、白名单规则补上
+# fallback_action=pass（2026-10-11 21:51 实测），标记随之丢失。故另记本脚本写过的规则签名，
+# 无 error_message 且签名与之相同的规则仍按自动规则处理（替换而不是当人工规则保留，避免重复和过期限制）。
+POLICY_HISTORY = "/opt/sub2api/ops/policy_managed_history.json"
+
+
+def _sig(r):
+    d = {k: v for k, v in r.items() if k != "error_message"}
+    if d.get("fallback_action") == "pass":
+        del d["fallback_action"]  # sub2api 默认值
+    for k, v in d.items():
+        if isinstance(v, list):
+            d[k] = sorted(v)
+    return json.dumps(d, sort_keys=True, ensure_ascii=False)
+
+
+def _history(policy):
+    try:
+        sigs = set(json.load(open(POLICY_HISTORY)))
+    except (OSError, ValueError):
+        sigs = set()
+    return sigs | {
+        _sig(r)
+        for r in policy.get("rules") or []
+        if r.get("error_message") == POLICY_MARK
+    }
+
+
+def _is_managed(r, hist):
+    msg = r.get("error_message")
+    return msg == POLICY_MARK or (not msg and _sig(r) in hist)
+
+
+def current_managed(policy):
+    """本脚本管理的规则，含被 sub2api 后台保存去掉标记的副本（副本不等于期望规则，会触发重写）。"""
+    hist = _history(policy)
+    return [r for r in policy.get("rules") or [] if _is_managed(r, hist)]
+
+
+def with_managed(current, rules):
+    """保留人工规则；管理规则排在最前（同级规则首条命中）。"""
+    hist = _history(current)
+    return {
+        "rules": rules
+        + [r for r in current.get("rules") or [] if not _is_managed(r, hist)]
+    }
+
+
+def write_policy(policy):
+    data = json.dumps(policy, ensure_ascii=False)
+    if "$pol$" in data:
+        raise SystemExit("策略内容含非法分隔符")
+    _psql(
+        "insert into settings(key, value, updated_at) values ('openai_fast_policy_settings', "
+        f"$pol${data}$pol$, now()) on conflict(key) do update set value = excluded.value, updated_at = now()"
+    )
+    try:
+        old = json.load(open(POLICY_HISTORY))
+    except (OSError, ValueError):
+        old = []
+    new = [_sig(r) for r in policy["rules"] if r.get("error_message") == POLICY_MARK]
+    keep = [s for s in old if s not in new] + new
+    with open(POLICY_HISTORY + ".tmp", "w") as f:
+        json.dump(keep[-200:], f, ensure_ascii=False, indent=1)
+    os.replace(POLICY_HISTORY + ".tmp", POLICY_HISTORY)
+
+
+def num(d, label):
+    """Nexus 价格字段（每百万 token）转数字；缺失/空返回 None（Nexus 偶有 "$0.20" 形式）。"""
+    v = (d or {}).get(f"{label}_per_million_tokens")
+    if v in (None, ""):
+        return None
+    try:
+        return float(str(v).lstrip("$"))
+    except ValueError:
+        return None
+
+
+def _first(*vals):
+    return next((v for v in vals if v is not None), None)
+
+
+def ours_price(lv_is_base, std, base, f):
+    """本站该级该字段的标准价（每百万 token），与 price_entry 写入的渠道价及 sub2api 回退规则一致。"""
+
+    def lvl(label):  # 阶梯缺失时 price_entry 用基础价补齐；显式 0 保留
+        return (
+            num(std, label) if lv_is_base else _first(num(std, label), num(base, label))
+        )
+
+    if f == "cache_write_1h":  # 无 1h 价时 sub2api 按 5m 缓存写价计
+        return _first(lvl("cache_write_1h"), lvl("cache_write"))
+    if f == "image_input":  # 渠道图片价只在基础层；为 0/缺失时回退到该级文本输入价
+        return num(base, "image_input") or lvl("input")
+    if f == "image_output":  # 缺失时回退到该级文本输出价；显式 0 表示免费
+        return _first(num(base, "image_output"), lvl("output"))
+    return lvl(f)
+
+
+def field_ratios(sub, base):
+    rs = {}
+    for label, f in RATIO_FIELDS:
+        try:
+            a, b = float(sub.get(f) or 0), float(base.get(f) or 0)
+        except (TypeError, ValueError):
+            continue
+        if b > 0 and a > 0:
+            rs[label] = round(a / b, 4)
+        elif a > 0:
+            rs[label] = "基础无价"
+        elif b > 0:
+            rs[label] = "档位无价"
+    return rs
+
+
+def ratio(target, tier_name, sub, base):
+    rs = field_ratios(sub, base)
+    main = [rs[k] for k in MAIN_FIELDS if isinstance(rs.get(k), float)]
+    zero_base = [k for k in MAIN_FIELDS if rs.get(k) == "基础无价"]
+    if zero_base or (not main and rs):
+        # 主要字段基础价为 0 而档位收费，或没有任何可用主要比例：无法保证不少收，阻止自动同步
+        STRUCT_ERRORS[(target, tier_name)] = (
+            f"{target} {tier_name}: 主要字段无法用倍率表达 {rs}，无法保证不少收，已阻止自动同步"
+        )
+    if not main:
+        return None
+    bt, st = base.get("price_tiers") or [], sub.get("price_tiers") or []
+    if len(st) > len(bt) or [t.get("threshold") for t in st] != [
+        t.get("threshold") for t in bt[: len(st)]
+    ]:
+        STRUCT_ERRORS[(target, tier_name)] = (
+            f"{target} {tier_name}: 档位阶梯与基础阶梯不对应（基础 {len(bt)} 级，档位 {len(st)} 级），"
+            "无法保证不少收，已阻止自动同步"
+        )
+        return None
+    # 逐级逐字段：need = Nexus 档位价（缺失时取可能的最高价）/ 本站标准价
+    needs, unpriced = {}, []
+    levels = [("基础", base, sub)] + [
+        (f"第{k + 1}级", t, st[k] if k < len(st) else None) for k, t in enumerate(bt)
+    ]
+    for lv, std, nx_lv in levels:
+        for f in TOKEN_FIELDS:
+            ours = ours_price(lv == "基础", std, base, f)
+            nx = num(nx_lv, f)
+            if (
+                nx is None
+            ):  # Nexus 未给该级/该字段档位价：取档位基础价与该级标准价的较大者
+                nx = max(
+                    [v for v in (num(sub, f), num(std, f)) if v is not None],
+                    default=None,
+                )
+            if not nx:
+                continue
+            if not ours:
+                unpriced.append(f"{lv}.{f}")
+                continue
+            needs[f"{lv}.{f}"] = math.ceil(nx / ours * 1e4 - 1e-6) / 1e4
+    if unpriced:
+        STRUCT_ERRORS[(target, tier_name)] = (
+            f"{target} {tier_name}: Nexus 档位对 {unpriced} 收费而标准价为 0，倍率无法表达，已阻止自动同步"
+        )
+    r = max([max(main)] + list(needs.values()))
+    if tier_name == "flex":
+        (FILTER_TIERS["flex"] if r >= 1 else FLEX_OK).add(target)
+    elif r > FAST_LIMIT * max(main):
+        FILTER_TIERS[tier_name].add(target)
+    over = {k: v for k, v in needs.items() if v < r}
+    if r > max(main) or over:
+        raised = {k: v for k, v in needs.items() if v == r}
+        STRUCT_NOTES[(target, tier_name)] = (
+            f"{target} {tier_name}: 按 ×{r} 计（取最高字段 {raised}"
+            + (f"，其余字段多收 {over}" if over else "")
+            + f"；Nexus 输入/输出比例 ×{max(main)}）"
+        )
+    return r
+
+
+def price_entry(target, peak=None):
+    pr = pricing[target]["pricing"]
+    e = {
+        "billing_mode": "token",
+        "input_price": per_token(pr.get("input_per_million_tokens")),
+        "output_price": per_token(pr.get("output_per_million_tokens")),
+        "cache_read_price": per_token(pr.get("cache_read_per_million_tokens")),
+        "cache_write_price": per_token(pr.get("cache_write_per_million_tokens")),
+        "cache_write_1h_price": per_token(pr.get("cache_write_1h_per_million_tokens")),
+        "image_input_price": per_token(pr.get("image_input_per_million_tokens")),
+        "image_output_price": per_token(pr.get("image_output_per_million_tokens")),
+    }
+    for key, sub in (
+        ("fast_multiplier", "priority_pricing"),
+        ("flex_multiplier", "flex_pricing"),
+    ):
+        if key == "flex_multiplier" and not FLEX_ENABLED:
+            continue
+        if pr.get(sub) and (r := ratio(target, sub.split("_")[0], pr[sub], pr)):
+            e[key] = r
+    if not pr.get("priority_pricing"):
+        # Nexus 无 Fast 价时按标准价扣费（实测 claude-opus-5 speed=fast：Nexus 实际 fast、按标准价扣），
+        # 本站同按标准价；不设置时 sub2api 默认 ×2 或目录价，比 Nexus 多收
+        e["fast_multiplier"] = 1.0
+    if target.startswith(
+        FAST_NOT_DELIVERED
+    ):  # Fast 到不了 Nexus：去除档位，按标准档执行与计费
+        FILTER_TIERS["priority"].add(target)
+    if not (FLEX_ENABLED and pr.get("flex_pricing")):
+        # 不放行 Flex 或 Nexus 无 Flex 价：不给折扣（sub2api 默认 ×0.5 会少收）
+        e["flex_multiplier"] = 1.0
+    tiers = pr.get("price_tiers") or []
+    if tiers:
+        base = {k: e[k] for k in PRICE_KEYS}
+        ivs = [
+            {
+                "min_tokens": 0,
+                "max_tokens": int(tiers[0]["threshold"]),
+                "tier_label": f"<= {int(tiers[0]['threshold'])}",
+                **base,
+                "sort_order": 0,
+            }
+        ]
+        for i, t in enumerate(tiers):
+            iv = {
+                "min_tokens": int(t["threshold"]),
+                "max_tokens": int(tiers[i + 1]["threshold"])
+                if i + 1 < len(tiers)
+                else None,
+                "tier_label": f"> {int(t['threshold'])}",
+                "sort_order": i + 1,
+                "input_price": per_token(t.get("input_per_million_tokens")),
+                "output_price": per_token(t.get("output_per_million_tokens")),
+                "cache_read_price": per_token(t.get("cache_read_per_million_tokens")),
+                "cache_write_price": per_token(t.get("cache_write_per_million_tokens")),
+                "cache_write_1h_price": per_token(
+                    t.get("cache_write_1h_per_million_tokens")
+                ),
+            }
+            for k in PRICE_KEYS:
+                if iv[k] is None:
+                    iv[k] = base[k]
+            ivs.append(iv)
+        e["intervals"] = ivs
+    if peak:
+        e["time_pricing"] = {
+            "timezone": "Asia/Shanghai",
+            "weekdays_only": bool(peak.get("weekdaysOnly")),
+            "periods": [
+                {
+                    "start_time": w["start"],
+                    "end_time": w["end"],
+                    "multiplier": peak["multiplier"],
+                }
+                for w in peak["windows"]
+            ],
+        }
+    return {k: v for k, v in e.items() if v is not None}
+
+
+def as_list(x):
+    return x if isinstance(x, list) else ([x] if x else [])
+
+
+def family(model):
+    """路由用的模型前缀：取第一个 '-' 前的部分（claude- / gpt- / grok- / glm- ...）。"""
+    head = model.split("-", 1)[0]
+    return head + "-" if "-" in model else model
+
+
+MEDIA_MODES = {"image_generation", "video_generation"}
+
+
+def skip_media(group, target):
+    """按张/按秒计价的画图、视频模型：仅当分组有 Nexus imagePricing（sub2api 按张计费）时开放；
+    否则 sub2api 只能按 token 计费（Nexus 这类模型 token 价为 0），等于免费使用，故不开放。"""
+    return (
+        not group.get("imagePricing")
+        and (pricing.get(target) or {}).get("mode") in MEDIA_MODES
+    )
+
+
+# Nexus 各分组倍率：售价 = 「默认分组」档，成本 = 「合作商」档
+tiers = {}
+for kg in kq["keyGroups"]:
+    for a in kg["aiGroups"]:
+        tiers.setdefault(a["id"], {})[kg["name"]] = float(
+            a.get("globalFallbackRatio") or 0
+        )
+
+
+# ---------- 现状（由外层从数据库只读导出，预览不调用管理接口）----------
+# S2A_BINDINGS: {"<group_id>": [{"id","platform","status","rate_multiplier"}]}
+# S2A_CHANNELS: [{"id", "group_ids": [...]}]
+bindings = json.load(open(os.environ["S2A_BINDINGS"]))
+channels = json.load(open(os.environ["S2A_CHANNELS"]))
+ACCOUNT_CONCURRENCY = 50  # Nexus 该 key 并发不限；同组同协议共享此上限（原 10 易排队）
+
+
+# ---------- 阶段一：为全部分组计算目标状态（不写入），任何校验失败整体中止 ----------
+FORCE = "--force" in sys.argv  # 跳过「模型数骤减」保护
+plan, errors, notes = [], [], []
+FAST_FILTER, FLEX_PASS = set(), set()  # 策略按对外模型名匹配：Fast 去除 / Flex 放行
+for slug in sorted(set(allowed) - set(GROUPS)):
+    notes.append(
+        f"Nexus 新分组 {slug}（{allowed[slug].get('endpoint')}）未接入：需人工建分组后加入 GROUPS / gen_router.py"
+    )
+for slug, (gid, path) in GROUPS.items():
+    if slug not in allowed:
+        errors.append(f"{slug}: Nexus 已不再提供该分组（需人工处理）")
+        continue
+    g = allowed[slug]
+    rates = tiers.get(g["id"], {})
+    sell, cost = rates.get("默认分组"), rates.get("合作商")
+    if not (sell and cost):
+        errors.append(f"{slug}: Nexus 未返回默认分组/合作商倍率")
+    skipped = set()
+    resp = nexus(f"/api/{path}/v1/models")
+    by_type = resp.get("modelsByType") or {}
+    plats = {}  # sub2api 平台 -> {"targets": {model: 实际执行模型}, "endpoints": set()}
+    for ep in g.get("supportedEndpoints") or []:
+        if ep not in ENDPOINTS:
+            continue
+        if ep == "gemini_generate" and slug in GEMINI_BILLING_MISMATCH:
+            continue
+        plat, types, route_eps = ENDPOINTS[ep]
+        p = plats.setdefault(plat, {"targets": {}, "endpoints": set()})
+        p["endpoints"].update(route_eps)
+        for t in types:
+            for m in by_type.get(t, []):
+                mapped = as_list(m.get("mappedTo"))
+                target = mapped[0] if mapped and mapped != [m["id"]] else m["id"]
+                if skip_media(g, target):
+                    skipped.add(m["id"])
+                    continue
+                p["targets"].setdefault(m["id"], target)
+    for p in plats.values():
+        if not p["targets"]:  # 兜底：无 modelsByType 时用原生列表
+            p["targets"] = {
+                m["id"]: m["id"]
+                for m in resp.get("data", [])
+                if not skip_media(g, m["id"])
+            }
+    if not plats:
+        errors.append(f"{slug}: Nexus 未返回任何可用协议/模型")
+    if skipped:
+        notes.append(f"{slug}: 跳过按张/按秒计价模型（分组无按张价）{sorted(skipped)}")
+    # 保护：模型总数骤减（Nexus 接口异常时可能返回残缺列表）则中止，避免误删；确认无误可加 --force
+    # 只比较仍开放的协议：Nexus 在 supportedEndpoints 中明确关闭的协议属于正常变化，其账号照常停用
+    old_total = sum(
+        len(a.get("mm") or {})
+        for a in bindings.get(str(gid), [])
+        if a.get("status") == "active" and a.get("platform") in plats
+    )
+    new_total = sum(len(p["targets"]) for p in plats.values())
+    if not FORCE and old_total >= 4 and new_total < old_total * 0.5:
+        errors.append(
+            f"{slug}: 模型数 {old_total} → {new_total} 骤减超过一半，疑似 Nexus 异常（确认后加 --force）"
+        )
+
+    # 渠道定价：各平台各自一份，别名按实际执行模型计价
+    entries, image_only_models = [], 0
+    for plat, p in plats.items():
+        merged = {}
+        for model, target in sorted(p["targets"].items()):
+            if target not in pricing:
+                errors.append(f"{slug} {plat} {model}->{target} 无 Nexus 定价")
+                continue
+            # Nexus 对该分组生图按张收费（imagePricing）。渠道里若有 token 计价，sub2api 会改走 token
+            # 计费（实测少收约 10 倍），所以生图模型不建渠道条目，让分组 image_price_1k/2k/4k 生效。
+            if (
+                g.get("imagePricing")
+                and pricing[target].get("mode") == "image_generation"
+            ):
+                image_only_models += 1
+                continue
+            e = price_entry(target, g.get("peakPricing"))
+            if target in FILTER_TIERS["priority"]:
+                FAST_FILTER.add(model)
+            if target in FLEX_OK:
+                FLEX_PASS.add(model)
+            merged.setdefault(json.dumps(e, sort_keys=True), (e, []))[1].append(model)
+        entries += [{**e, "platform": plat, "models": ms} for e, ms in merged.values()]
+
+    routes = {
+        (prefix, ep, plat)
+        for plat, p in plats.items()
+        for prefix in {family(m) for m in p["targets"]}
+        for ep in p["endpoints"]
+    }
+    plan.append(
+        {
+            "slug": slug,
+            "gid": gid,
+            "path": path,
+            "g": g,
+            "plats": plats,
+            "entries": entries,
+            "sell": sell,
+            "cost": cost,
+            "routes": routes,
+            # 全部模型都有渠道价时开启 restrict_models（未定价模型直接拒绝，防免费调用）；
+            # 纯按张生图分组（无渠道条目）不能开启，否则会拒绝全部请求
+            "restrict": image_only_models == 0 and bool(entries),
+            "channel": next(
+                (c for c in channels if gid in (c.get("group_ids") or [])), None
+            ),
+        }
+    )
+
+for n in STRUCT_NOTES.values():
+    print("  ⚠ 计费结构限制 " + n)
+for n in notes:
+    print("  ⚠ " + n)
+EVENTS = []  # 结构化变更记录（供邮件表格）
+
+
+def dump_sync_json(applied):
+    if os.environ.get("SYNC_JSON"):
+        with open(os.environ["SYNC_JSON"], "w") as f:
+            json.dump(
+                {
+                    "applied": applied,
+                    "errors": errors,
+                    "notes": notes,
+                    "events": EVENTS,
+                },
+                f,
+                ensure_ascii=False,
+            )
+
+
+errors += list(STRUCT_ERRORS.values())
+if errors:
+    print("校验失败，未写入任何配置：")
+    print("\n".join("  ✗ " + e for e in errors))
+    dump_sync_json(False)
+    sys.exit(1)
+
+# ---------- 阶段二：写入（预览模式只打印计划）----------
+summary = []
+cur_policy = read_policy()
+want_rules = managed_rules(FAST_FILTER, FLEX_PASS)
+if APPLY and want_rules != current_managed(cur_policy):
+    old_fast = next(
+        (
+            set(r.get("model_whitelist") or [])
+            for r in current_managed(cur_policy)
+            if r["service_tier"] == "priority"
+        ),
+        set(),
+    )
+    write_policy(with_managed(cur_policy, managed_rules(FAST_FILTER | old_fast, set())))
+for it in plan:
+    slug, gid, path, g, plats = it["slug"], it["gid"], it["path"], it["g"], it["plats"]
+    group_accounts = bindings.get(str(gid), [])
+    for plat, p in plats.items():
+        models = sorted(p["targets"])
+        mapping = {m: m for m in models}
+        acc = next((a for a in group_accounts if a["platform"] == plat), None)
+        extra = {"anthropic_passthrough": True} if plat == "anthropic" else {}
+        if acc and APPLY:
+            full = admin("GET", f"/accounts/{acc['id']}")
+            cred = {
+                k: v
+                for k, v in (full.get("credentials") or {}).items()
+                if k != "api_key"
+            }
+            cred.update(
+                base_url=f"{NEXUS}/api/{path}", pool_mode=True, model_mapping=mapping
+            )
+            ex = {
+                k: v
+                for k, v in (full.get("extra") or {}).items()
+                if k
+                not in (
+                    "upstream_billing_probe",
+                    "upstream_billing_probe_enabled",
+                    "upstream_billing_rate_sync_enabled",
+                    "quota_used",
+                    "quota_daily_used",
+                    "quota_daily_start",
+                    "quota_weekly_used",
+                    "quota_weekly_start",
+                )
+            }
+            ex.update(extra)
+            admin(
+                "PUT",
+                f"/accounts/{acc['id']}",
+                {
+                    "name": f"{slug}-{plat}",
+                    "credentials": cred,
+                    "extra": ex,
+                    "status": "active",
+                    "concurrency": ACCOUNT_CONCURRENCY,
+                    "rate_multiplier": it["cost"],
+                    # Nexus 对倍率探测一律声明 1 倍（与实扣不符），关闭探测与同步，成本倍率只按合作商档维护
+                    "upstream_billing_probe_enabled": False,
+                    "upstream_billing_rate_sync_enabled": False,
+                    "confirm_mixed_channel_risk": True,
+                },
+            )
+        elif not acc:
+            admin(
+                "POST",
+                "/accounts",
+                {
+                    "name": f"{slug}-{plat}",
+                    "platform": plat,
+                    "type": "apikey",
+                    "credentials": {
+                        "api_key": NEXUS_KEY,
+                        "base_url": f"{NEXUS}/api/{path}",
+                        "pool_mode": True,
+                        "model_mapping": mapping,
+                    },
+                    "extra": extra,
+                    "concurrency": ACCOUNT_CONCURRENCY,
+                    "priority": 1,
+                    "rate_multiplier": it["cost"],
+                    "group_ids": [gid],
+                    "upstream_billing_probe_enabled": False,
+                    "upstream_billing_rate_sync_enabled": False,
+                    "confirm_mixed_channel_risk": True,
+                },
+            )
+        if acc and set(models) != set(acc.get("mm") or {}):
+            EVENTS.append(
+                {
+                    "kind": "model_change",
+                    "slug": slug,
+                    "plat": plat,
+                    "added": sorted(set(models) - set(acc.get("mm") or {})),
+                    "removed": sorted(set(acc.get("mm") or {}) - set(models)),
+                }
+            )
+            summary.append(
+                f"  {slug:16} {plat:9} 模型变化 +{sorted(set(models) - set(acc.get('mm') or {}))} "
+                f"-{sorted(set(acc.get('mm') or {}) - set(models))}"
+            )
+        if acc and abs(float(acc.get("rate") or 0) - it["cost"]) > 1e-9:
+            EVENTS.append(
+                {
+                    "kind": "cost_rate",
+                    "slug": slug,
+                    "plat": plat,
+                    "old": float(acc.get("rate") or 0),
+                    "new": it["cost"],
+                }
+            )
+            summary.append(
+                f"  {slug:16} {plat:9} 成本倍率 {acc.get('rate')} → {it['cost']}"
+            )
+        if not acc:
+            EVENTS.append(
+                {
+                    "kind": "account_new",
+                    "slug": slug,
+                    "plat": plat,
+                    "models": len(models),
+                }
+            )
+        summary.append(
+            f"  {slug:16} {plat:9} 账号{'更新' if acc else '新建'} 模型{len(models):>2} "
+            f"接口 {','.join(sorted(p['endpoints']))}"
+        )
+    # 不再开放协议的账号停用而非删除，便于恢复
+    for a in group_accounts:
+        if a["platform"] not in plats and a.get("status") != "inactive":
+            admin("PUT", f"/accounts/{a['id']}", {"status": "inactive"})
+            EVENTS.append(
+                {
+                    "kind": "account_disabled",
+                    "slug": slug,
+                    "plat": a["platform"],
+                    "id": a["id"],
+                }
+            )
+            summary.append(
+                f"  {slug:16} {a['platform']:9} 账号 #{a['id']} 停用（协议未开放）"
+            )
+
+    # 分组：组合平台；图片开关随 Nexus imagePricing；长上下文计费必须开启（关闭时阶梯价不生效，实测少收约 5 倍）
+    cur_sell = (
+        float((admin("GET", f"/groups/{gid}") or {}).get("rate_multiplier") or 0)
+        if APPLY
+        else None
+    )
+    if cur_sell is not None and abs(cur_sell - it["sell"]) > 1e-9:
+        EVENTS.append(
+            {
+                "kind": "sell_rate",
+                "slug": slug,
+                "old": cur_sell,
+                "new": it["sell"],
+                "cost": it["cost"],
+            }
+        )
+        summary.append(
+            f"  {slug:16} 售价倍率 {cur_sell:g} → {it['sell']:g}（跟随 Nexus 普通）"
+        )
+    admin(
+        "PUT",
+        f"/groups/{gid}",
+        {
+            "platform": "composite",
+            "allow_messages_dispatch": False,
+            # 售价倍率跟随 Nexus「默认分组」（普通用户）倍率；后台手改会在下次同步被覆盖
+            "rate_multiplier": it["sell"],
+            # 名称与备注跟随 Nexus（备注 = Nexus 分组公告摘要 noticeSummary，无则留空）
+            "name": g["name"],
+            "description": g.get("noticeSummary") or "",
+            "allow_image_generation": bool(g.get("imagePricing")),
+            "long_context_pricing_enabled": True,
+            # 按张单价随 Nexus imagePricing（price1k/2k/4k → image_price_1k/2k/4k）
+            **{
+                f"image_price_{k[5:]}": float(v)
+                for k, v in (g.get("imagePricing") or {}).items()
+                if k.startswith("price")
+            },
+        },
+    )
+
+    # 路由：增量更新，先补齐缺失再删除多余，更新过程中不出现无路由窗口
+    current = {}
+    if APPLY:
+        for r in admin("GET", f"/groups/{gid}/composite-routes") or []:
+            current[(r["public_model"], r["endpoint"], r["target_platform"])] = r
+    for prefix, ep, plat in sorted(it["routes"] - set(current)):
+        admin(
+            "POST",
+            f"/groups/{gid}/composite-routes",
+            {
+                "public_model": prefix,
+                "match_type": "prefix",
+                "endpoint": ep,
+                "target_platform": plat,
+                "upstream_model": "",
+                "priority": 0,
+                "enabled": True,
+            },
+        )
+    for key in set(current) - it["routes"]:
+        admin("DELETE", f"/groups/{gid}/composite-routes/{current[key]['id']}")
+    added = len(it["routes"] - set(current)) if APPLY else len(it["routes"])
+    removed = len(set(current) - it["routes"])
+
+    # 渠道：单次 PUT 整体替换（服务端单事务）
+    body = {
+        "name": f"Nexus-{slug}",
+        "description": f"Nexus {slug} 全协议定价（别名按实际执行模型计价）",
+        "group_ids": [gid],
+        "model_pricing": it["entries"],
+        "restrict_models": it["restrict"],
+        "apply_pricing_to_account_stats": True,
+    }
+    admin("PUT", f"/channels/{it['channel']['id']}", body) if it["channel"] else admin(
+        "POST", "/channels", body
+    )
+    summary.append(
+        f"  {slug:16} → 组合分组 #{gid}，路由 {len(it['routes'])} 条（+{added}/-{removed}），"
+        f"定价 {len(it['entries'])} 条，限制未定价模型={'是' if it['restrict'] else '否'}"
+    )
+
+# OpenAI Fast/Flex 策略（只改本脚本管理的规则）：最终规则在全部写入完成后落库
+if want_rules != current_managed(cur_policy):
+    if APPLY:
+        write_policy(with_managed(cur_policy, want_rules))
+    old = {r["service_tier"]: r for r in current_managed(cur_policy)}
+    for r in want_rules:
+        if old.get(r["service_tier"]) != r:
+            desc = (
+                f"放行 {r.get('model_whitelist')}，其余去除"
+                if r["action"] == "pass"
+                else f"去除 {r.get('model_whitelist') or '全部模型'}"
+            )
+            EVENTS.append(
+                {"kind": "fast_policy", "tier": r["service_tier"], "rule": desc}
+            )
+            summary.append(f"  Fast/Flex 策略 {r['service_tier']}：{desc}")
+
+print(("已写入" if APPLY else "预览（未写入，未调用管理接口）") + "：")
+print("\n".join(summary))
+dump_sync_json(APPLY)
diff --git a/ops/notify.py b/ops/notify.py
new file mode 100644
index 0000000..ca4bd5f
--- /dev/null
+++ b/ops/notify.py
@@ -0,0 +1,245 @@
+"""用 sub2api 后台的 SMTP 设置给管理员发运维通知（HTML 表格邮件 + 纯文本备用）。
+
+用法:
+  python3 -I notify.py json  < 报告.json        结构化报告（推荐）
+  python3 -I notify.py "标题" [ok|warn|error|info] < 正文.txt   纯文本（渲染为单个代码块）
+报告 JSON:
+  {"title": "...", "status": "ok|warn|error|info", "subtitle": "...",
+   "summary": [["项目", "值"], ...],
+   "sections": [{"heading": "...", "note": "...", "columns": [...], "rows": [[单元格, ...], ...]},
+                {"heading": "...", "text": "预格式化文本"}],
+   "footer": "..."}
+单元格可为字符串/数字，或 {"text": ..., "tone": "good|bad|warn|muted", "bold": true}。
+收件人：sub2api 管理员账号邮箱；SMTP 参数读自数据库 settings（与站点发信一致）。
+"""
+
+import html
+import json
+import re
+import os
+import smtplib
+import ssl
+import subprocess
+import sys
+from email.header import Header
+from email.mime.multipart import MIMEMultipart
+from email.mime.text import MIMEText
+from email.utils import formataddr
+
+PSQL = "/www/server/pgsql/bin/psql"
+STATUS = {  # 标题栏颜色与图标
+    "ok": ("#15803d", "✅"),
+    "warn": ("#b45309", "⚠️"),
+    "error": ("#b91c1c", "❌"),
+    "info": ("#1d4ed8", "ℹ️"),
+}
+TONE = {"good": "#15803d", "bad": "#b91c1c", "warn": "#b45309", "muted": "#64748b"}
+FONT = "-apple-system,BlinkMacSystemFont,'Segoe UI','PingFang SC','Microsoft YaHei',sans-serif"
+
+
+def q(sql):
+    return subprocess.run(
+        [
+            PSQL,
+            "-h",
+            "localhost",
+            "-U",
+            "postgres",
+            "-d",
+            "sub2api",
+            "-qAt",
+            "-F",
+            "\t",
+            "-c",
+            sql,
+        ],
+        capture_output=True,
+        text=True,
+        check=True,
+        env=os.environ,
+    ).stdout.strip()
+
+
+def cell_parts(c):
+    if isinstance(c, dict):
+        return str(c.get("text", "")), c.get("tone"), bool(c.get("bold")), c.get("bg")
+    return ("" if c is None else str(c)), None, False, None
+
+
+NUMERIC = re.compile(r"^[+\-]?[×$¥]?-?[\d,]+(\.\d+)?%?(\s*[↑↓≠])?(\s*（估）)?$")
+
+
+def is_number(s):
+    """整格是数值（可带 × $ ¥ % 与 ↑↓≠ 标记）才右对齐；以数字开头的说明文字不算。"""
+    return bool(NUMERIC.match(s.strip()))
+
+
+def render_table(columns, rows):
+    th = "".join(
+        f'<th style="background:#f1f5f9;color:#334155;font-weight:600;text-align:left;'
+        f'padding:8px 10px;border-bottom:2px solid #cbd5e1;white-space:nowrap">{html.escape(str(c))}</th>'
+        for c in columns
+    )
+    body = []
+    for i, row in enumerate(rows):
+        bg = "#ffffff" if i % 2 == 0 else "#f8fafc"
+        tds = []
+        for c in row:
+            text, tone, bold, cbg = cell_parts(c)
+            style = (
+                f"padding:7px 10px;border-bottom:1px solid #e2e8f0;vertical-align:top"
+            )
+            if is_number(text):
+                style += ";text-align:right;font-variant-numeric:tabular-nums;white-space:nowrap"
+            if tone:
+                style += f";color:{TONE.get(tone, tone)}"
+            if bold:
+                style += ";font-weight:600"
+            if cbg:  # 单元格底色（用于突出差异）
+                style += f";background:{cbg}"
+            tds.append(f'<td style="{style}">{html.escape(text)}</td>')
+        body.append(f'<tr style="background:{bg}">{"".join(tds)}</tr>')
+    # 外层可横向滚动，窄屏邮箱也能看到完整表格
+    return (
+        '<div style="width:100%;overflow-x:auto;-webkit-overflow-scrolling:touch">'
+        '<table role="presentation" cellspacing="0" cellpadding="0" style="width:100%;min-width:100%;border-collapse:collapse;'
+        'border:1px solid #e2e8f0;font-size:12.5px;line-height:1.5">'
+        f"<thead><tr>{th}</tr></thead><tbody>{''.join(body)}</tbody></table></div>"
+    )
+
+
+def render_html(r):
+    color, icon = STATUS.get(r.get("status", "info"), STATUS["info"])
+    parts = [
+        f'<div style="background:#f1f5f9;padding:24px 12px;font-family:{FONT};color:#0f172a">',
+        '<div style="max-width:1280px;margin:0 auto;background:#ffffff;border-radius:12px;overflow:hidden;'
+        'box-shadow:0 1px 3px rgba(15,23,42,.08)">',
+        f'<div style="background:{color};color:#ffffff;padding:20px 24px">'
+        f'<div style="font-size:12px;opacity:.85;letter-spacing:.5px">STARNEXUS 运维通知</div>'
+        f'<div style="font-size:20px;font-weight:700;margin-top:4px">{icon} {html.escape(r["title"])}</div>'
+        + (
+            f'<div style="font-size:13px;opacity:.9;margin-top:6px">{html.escape(r["subtitle"])}</div>'
+            if r.get("subtitle")
+            else ""
+        )
+        + "</div>",
+        '<div style="padding:18px 20px">',
+    ]
+    if r.get("summary"):
+        cells = "".join(
+            f'<td style="padding:10px 14px;border:1px solid #e2e8f0;background:#f8fafc;width:{100 // len(r["summary"])}%">'
+            f'<div style="font-size:12px;color:#64748b">{html.escape(str(k))}</div>'
+            f'<div style="font-size:16px;font-weight:700;margin-top:2px">{html.escape(str(v))}</div></td>'
+            for k, v in r["summary"]
+        )
+        parts.append(
+            '<table role="presentation" cellspacing="0" cellpadding="0" style="width:100%;border-collapse:collapse;'
+            f'margin-bottom:18px"><tr>{cells}</tr></table>'
+        )
+    for s in r.get("sections", []):
+        parts.append(
+            f'<h3 style="font-size:15px;margin:20px 0 8px;color:#0f172a;border-left:4px solid {color};'
+            f'padding-left:8px">{html.escape(s["heading"])}</h3>'
+        )
+        if s.get("note"):
+            parts.append(
+                f'<div style="font-size:12px;color:#64748b;margin:0 0 8px">{html.escape(s["note"])}</div>'
+            )
+        if s.get("columns"):
+            parts.append(render_table(s["columns"], s.get("rows") or []))
+        if s.get("text"):
+            parts.append(
+                '<pre style="background:#0f172a;color:#e2e8f0;padding:12px 14px;border-radius:8px;font-size:12px;'
+                f'white-space:pre-wrap;word-break:break-all;margin:0">{html.escape(s["text"])}</pre>'
+            )
+    parts.append("</div>")
+    parts.append(
+        '<div style="padding:14px 24px;background:#f8fafc;border-top:1px solid #e2e8f0;font-size:12px;color:#64748b">'
+        + html.escape(r.get("footer") or "由 ssa 服务器 /opt/sub2api/ops 自动发送")
+        + "</div></div></div>"
+    )
+    return "".join(parts)
+
+
+def width(s):
+    return sum(2 if ord(ch) > 0x2E80 else 1 for ch in s)
+
+
+def render_text(r):
+    out = [f"【{r['title']}】", r.get("subtitle", ""), ""]
+    for k, v in r.get("summary", []):
+        out.append(f"{k}：{v}")
+    for s in r.get("sections", []):
+        out += ["", f"■ {s['heading']}"]
+        if s.get("note"):
+            out.append(s["note"])
+        if s.get("columns"):
+            rows = [[cell_parts(c)[0] for c in row] for row in s.get("rows") or []]
+            cols = [str(c) for c in s["columns"]]
+            ws = [
+                max([width(cols[i])] + [width(r_[i]) for r_ in rows])
+                for i in range(len(cols))
+            ]
+            fmt = lambda vals: "  ".join(
+                v + " " * (ws[i] - width(v)) for i, v in enumerate(vals)
+            ).rstrip()
+            out += [fmt(cols), "  ".join("-" * w for w in ws)] + [
+                fmt(r_) for r_ in rows
+            ]
+        if s.get("text"):
+            out.append(s["text"])
+    out += ["", r.get("footer") or ""]
+    return "\n".join(out)
+
+
+def send(report):
+    cfg = dict(
+        line.split("\t", 1)
+        for line in q(
+            "select key, value from settings where key like 'smtp_%'"
+        ).splitlines()
+        if "\t" in line
+    )
+    to = q(
+        "select email from users where role = 'admin' and deleted_at is null order by id limit 1"
+    )
+    msg = MIMEMultipart("alternative")
+    msg["Subject"] = Header(f"[StarNexus] {report['title']}", "utf-8")
+    msg["From"] = formataddr(
+        (
+            str(Header(cfg.get("smtp_from_name") or "StarNexus", "utf-8")),
+            cfg["smtp_from"],
+        )
+    )
+    msg["To"] = to
+    msg.attach(MIMEText(render_text(report), "plain", "utf-8"))
+    msg.attach(MIMEText(render_html(report), "html", "utf-8"))
+    port = int(cfg.get("smtp_port") or 465)
+    if port == 465:
+        s = smtplib.SMTP_SSL(
+            cfg["smtp_host"], port, context=ssl.create_default_context(), timeout=30
+        )
+    else:
+        s = smtplib.SMTP(cfg["smtp_host"], port, timeout=30)
+        if cfg.get("smtp_use_tls") == "true":
+            s.starttls(context=ssl.create_default_context())
+    with s:
+        s.login(cfg["smtp_username"], cfg["smtp_password"])
+        s.sendmail(cfg["smtp_from"], [to], msg.as_string())
+    print(f"已发送通知：{report['title']}")
+
+
+if __name__ == "__main__":
+    if sys.argv[1:2] == ["json"]:
+        report = json.load(sys.stdin)
+    else:
+        title = sys.argv[1].removeprefix("[StarNexus] ")
+        report = {
+            "title": title,
+            "status": sys.argv[2] if len(sys.argv) > 2 else "info",
+            "sections": [{"heading": "详情", "text": sys.stdin.read()}],
+        }
+    if os.environ.get("NOTIFY_PREVIEW"):  # 只输出 HTML，不发送（用于预览）
+        print(render_html(report))
+    else:
+        send(report)
diff --git a/ops/refresh-auto-route.sh b/ops/refresh-auto-route.sh
new file mode 100755
index 0000000..4343851
--- /dev/null
+++ b/ops/refresh-auto-route.sh
@@ -0,0 +1,28 @@
+#!/usr/bin/env bash
+# 统一路由：按 auto_route_config.json 刷新「模型 → 分组」匹配表，并（可选）同步后台分组列表顺序。
+# 宝塔计划任务「sub2api 统一路由：刷新匹配表」每小时整点执行；改配置后可在面板点「执行」立即生效。
+set -euo pipefail
+OPS=/opt/sub2api/ops
+source /root/.config/sub2api-nexus.env
+export NEXUS_KEY
+source "$OPS/lib.sh"
+python3 -I "$OPS/gen_auto_index.py"
+if python3 -c "import json,sys;sys.exit(0 if json.load(open('$OPS/auto_route_config.json')).get('sync_group_list_order', True) else 1)"; then
+	body=$(python3 -c "
+import json
+d = json.load(open('$OPS/auto_route_index.json'))
+ups = ([{'id': d['unified_gid'], 'sort_order': 0}] if d.get('unified_gid') else []) + \
+      [{'id': g['gid'], 'sort_order': (i + 1) * 10} for i, g in enumerate(d['groups'])]
+print(json.dumps({'updates': ups}))")
+	cur=$(Q "select string_agg(id||':'||sort_order, ',' order by id) from groups where deleted_at is null")
+	want=$(python3 -c "import json,sys;print(','.join(f\"{u['id']}:{u['sort_order']}\" for u in sorted(json.loads(sys.argv[1])['updates'], key=lambda u: u['id'])))" "$body")
+	if [ "$cur" != "$want" ]; then
+		ops_lock
+		with_admin_key
+		r=$(curl -s -m 30 -X PUT -H content-type:application/json -K <(printf 'header = "x-api-key: %s"\n' "$S2A_ADMIN_KEY") \
+			http://127.0.0.1:8080/api/v1/admin/groups/sort-order --data-binary "$body" | python3 -c "import json,sys;print(json.load(sys.stdin).get('code'))")
+		echo "后台分组列表顺序已更新（结果 $r）"
+	else
+		echo "后台分组列表顺序无需调整"
+	fi
+fi
diff --git a/ops/route_auth.py b/ops/route_auth.py
new file mode 100644
index 0000000..3121b10
--- /dev/null
+++ b/ops/route_auth.py
@@ -0,0 +1,367 @@
+"""sub2api 分组路径路由的鉴权服务（供 nginx auth_request 调用）。
+
+客户端只用一个 Key（原 Key），按 URL 前缀 /api/<分组路径>/ 选择分组。本服务以原 Key 为授权与预算主体：
+  1. 校验原 Key（未删除、active、未过期）与所属用户（active）；
+  2. 按原 Key 的 IP 白/黑名单校验真实客户端 IP；
+  3. 校验目标分组：active、标准分组，且符合主服务 CanBindGroup 规则
+     （专属分组、或用户开启「限制公开分组」时，须在用户授权分组列表中）；
+  4. 「原 Key + 其全部映射 Key（含已删除）」合计：总额度按 quota_used，5h/1d/7d 按使用日志滚动窗口统一计算；
+  5. 返回该原 Key 在目标分组的映射 Key（不存在则在事务锁内创建）。
+映射 Key 与原 Key 的父子关系存于 s2a_ops.route_keys（不靠名称识别）。映射 Key 由主服务强制约束：
+  - IP 白名单仅 ROUTE_IP：nginx 分组入口转发时把来源标记为该内部地址，直接拿映射 Key 调 /v1 会被主服务拒绝；
+  - 有效期、总额度、5h/1d/7d 限额与原 Key 同步（单个映射 Key 也不会超过原 Key 的上限）。
+注意：额度为请求前检查、结算后累计（与主服务自身 Key 额度相同），并发请求可能小幅超出，不是预占式限额。
+
+监听 127.0.0.1:8091，GET /auth。请求头：X-Route-Group（分组路径）、X-Original-Args（原始查询串）、
+X-Client-IP（nginx $remote_addr，已按 Cloudflare 还原真实 IP）。
+响应：200 + X-Mapped-Key / X-Mapped-Query；401 Key 无效；其余拒绝一律 403 + X-Route-Reason
+（notfound / ip / group / quota / key_disabled / unavailable），由 nginx 映射为对外状态码。
+"""
+
+import ipaddress
+import json
+import os
+import re
+import secrets
+import subprocess
+import threading
+import time
+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
+from urllib.parse import parse_qsl, urlencode
+
+ROUTES = json.load(
+    open(os.environ.get("ROUTE_GROUPS", "/opt/sub2api/ops/route_groups.json"))
+)
+PSQL = "/www/server/pgsql/bin/psql"
+# sub2api 允许自定义 Key；只做长度与字符集约束，真正的安全靠 psql 变量绑定
+KEY_RE = re.compile(r"^[A-Za-z0-9._\-]{8,128}$")
+MAIN_TTL, MAPPED_TTL = 10, 30
+MAPPED_PREFIX = "[路由]"
+ROUTE_IP = "127.0.0.2"  # 与 gen_router.py 生成的 nginx X-Forwarded-For 一致
+ROUTE_IP_JSON = json.dumps([ROUTE_IP])
+
+
+def _db_password():
+    in_db = False
+    for line in open("/opt/sub2api/config.yaml"):
+        if line.startswith("database:"):
+            in_db = True
+        elif in_db and line.strip().startswith("password:"):
+            return line.split(":", 1)[1].strip().strip("\"'")
+    raise SystemExit("config.yaml 中未找到数据库密码")
+
+
+ENV = {**os.environ, "PGPASSWORD": _db_password()}
+
+
+def psql_quote(value):
+    """psql \\set 单引号参数内的转义：反斜杠与单引号。"""
+    return str(value).replace("\\", "\\\\").replace("'", "\\'")
+
+
+def sql(query, **params):
+    """psql 变量绑定（:'name' 由 psql 负责引号转义），返回行列表（制表符分隔）。"""
+    args = [
+        PSQL,
+        "-h",
+        "localhost",
+        "-U",
+        "postgres",
+        "-d",
+        "sub2api",
+        "-qAt",
+        "-F",
+        "\t",
+        "-v",
+        "ON_ERROR_STOP=1",
+    ]
+    # 参数经标准输入的 \set 传入，Key 等敏感值不出现在命令行/进程列表中
+    sets = "".join(f"\\set {k} '{psql_quote(v)}'\n" for k, v in params.items())
+    out = subprocess.run(
+        args,
+        input=sets + query,
+        capture_output=True,
+        text=True,
+        env=ENV,
+        timeout=10,
+        check=True,
+    ).stdout
+    return [line.split("\t") for line in out.splitlines() if line]
+
+
+def init_schema():
+    """父子关系表；首次启动时把旧版按名称关联（「[路由] <slug> ←#<id>」）的映射 Key 迁入。"""
+    sql("""create schema if not exists s2a_ops;
+create table if not exists s2a_ops.route_keys (
+  mapped_id bigint primary key, parent_id bigint not null, group_id bigint not null,
+  user_id bigint not null, created_at timestamptz not null default now());
+create index if not exists route_keys_parent_group on s2a_ops.route_keys (parent_id, group_id);
+insert into s2a_ops.route_keys (mapped_id, parent_id, group_id, user_id)
+  select k.id, substring(k.name from '←#([0-9]+)$')::bigint, k.group_id, k.user_id
+  from api_keys k where k.name ~ '^\\[路由\\] .* ←#[0-9]+$'
+on conflict (mapped_id) do nothing;""")
+
+
+_cache, _lock = {}, threading.Lock()
+
+
+def cached(key, ttl, loader):
+    now = time.time()
+    with _lock:
+        hit = _cache.get(key)
+        if hit and hit[0] > now:
+            return hit[1]
+    value = loader()
+    with _lock:
+        _cache[key] = (now + ttl, value)
+    return value
+
+
+def load_main(api_key):
+    """原 Key 与用户状态、IP 名单、额度设置。无效（或本身就是映射 Key）返回 None。"""
+    rows = sql(
+        """select k.id, k.user_id, coalesce(k.ip_whitelist::text,'[]'), coalesce(k.ip_blacklist::text,'[]'),
+                         k.quota, k.rate_limit_5h, k.rate_limit_1d, k.rate_limit_7d,
+                         coalesce(extract(epoch from k.expires_at)::bigint::text, '')
+                  from api_keys k join users u on u.id = k.user_id
+                  where k.key = :'k' and k.deleted_at is null and k.status = 'active'
+                    and (k.expires_at is null or k.expires_at > now())
+                    and u.deleted_at is null and u.status = 'active'
+                    and not exists (select 1 from s2a_ops.route_keys r where r.mapped_id = k.id);""",
+        k=api_key,
+    )
+    if not rows:
+        return None
+    r = rows[0]
+    return {
+        "id": int(r[0]),
+        "user_id": int(r[1]),
+        "white": json.loads(r[2] or "[]"),
+        "black": json.loads(r[3] or "[]"),
+        "quota": float(r[4]),
+        "rl": (float(r[5]), float(r[6]), float(r[7])),
+        "expires": r[8],
+    }
+
+
+def family_usage(main_id):
+    """原 Key 及其全部映射 Key（含已删除）的合计：总额度用量、近 5h/1d/7d 实际扣费（滚动窗口）。"""
+    rows = sql(
+        """with fam as (select :'m'::bigint as id
+                               union select mapped_id from s2a_ops.route_keys where parent_id = :'m')
+                  select (select coalesce(sum(quota_used),0) from api_keys where id in (select id from fam)),
+                         coalesce(sum(actual_cost) filter (where created_at > now() - interval '5 hours'),0),
+                         coalesce(sum(actual_cost) filter (where created_at > now() - interval '1 day'),0),
+                         coalesce(sum(actual_cost),0)
+                  from usage_logs where api_key_id in (select id from fam)
+                    and created_at > now() - interval '7 days';""",
+        m=main_id,
+    )
+    return tuple(float(x) for x in rows[0])
+
+
+def group_allowed(user_id, group_id):
+    """与主服务 User.CanBindGroup 一致；只开放标准（非订阅）分组。"""
+    rows = sql(
+        """select g.status = 'active' and g.deleted_at is null and coalesce(g.subscription_type,'standard') = 'standard'
+                         and ((not g.is_exclusive and not u.restrict_public_groups)
+                              or exists (select 1 from user_allowed_groups a where a.user_id = u.id and a.group_id = g.id))
+                  from groups g, users u where g.id = :'g' and u.id = :'u';""",
+        u=user_id,
+        g=group_id,
+    )
+    return bool(rows) and rows[0][0] == "t"
+
+
+def load_mapped(main, group_id, slug):
+    """查找或创建原 Key 在目标分组的映射 Key（advisory 事务锁防并发重复创建），并同步约束。"""
+    params = dict(
+        u=main["user_id"],
+        g=group_id,
+        m=main["id"],
+        n=f"{MAPPED_PREFIX} {slug} ←#{main['id']}",
+        k="sk-" + secrets.token_hex(32),
+        exp=main["expires"],
+        ipw=ROUTE_IP_JSON,
+        q=main["quota"],
+        r5=main["rl"][0],
+        r1=main["rl"][1],
+        r7=main["rl"][2],
+    )
+    rows = sql(
+        """begin;
+select pg_advisory_xact_lock(hashtext('s2a-route:' || :'m' || ':' || :'g'));
+with ex as (select 1 from s2a_ops.route_keys r join api_keys k on k.id = r.mapped_id
+            where r.parent_id = :'m' and r.group_id = :'g' and k.deleted_at is null),
+     ins as (insert into api_keys (user_id, key, name, group_id, status, ip_whitelist, created_at, updated_at)
+             select :'u', :'k', :'n', :'g', 'active', :'ipw'::jsonb, now(), now()
+             where not exists (select 1 from ex) returning id)
+insert into s2a_ops.route_keys (mapped_id, parent_id, group_id, user_id) select id, :'m', :'g', :'u' from ins;
+update api_keys k set
+    expires_at = case when :'exp' = '' then null else to_timestamp(nullif(:'exp','')::bigint) end,
+    ip_whitelist = :'ipw'::jsonb, ip_blacklist = '[]'::jsonb,
+    quota = :'q'::numeric, rate_limit_5h = :'r5'::numeric, rate_limit_1d = :'r1'::numeric, rate_limit_7d = :'r7'::numeric,
+    status = case when k.status = 'quota_exhausted' and (:'q'::numeric = 0 or k.quota_used < :'q'::numeric)
+                  then 'active' else k.status end,
+    updated_at = now()
+  from s2a_ops.route_keys r
+  where r.mapped_id = k.id and r.parent_id = :'m' and r.group_id = :'g' and k.deleted_at is null
+    and (k.expires_at is distinct from (case when :'exp' = '' then null else to_timestamp(nullif(:'exp','')::bigint) end)
+         or k.ip_whitelist is distinct from :'ipw'::jsonb or coalesce(k.ip_blacklist,'[]'::jsonb) <> '[]'::jsonb
+         or k.quota <> :'q'::numeric or k.rate_limit_5h <> :'r5'::numeric
+         or k.rate_limit_1d <> :'r1'::numeric or k.rate_limit_7d <> :'r7'::numeric
+         or (k.status = 'quota_exhausted' and (:'q'::numeric = 0 or k.quota_used < :'q'::numeric)));
+select k.key, k.status from s2a_ops.route_keys r join api_keys k on k.id = r.mapped_id
+  where r.parent_id = :'m' and r.group_id = :'g' and k.deleted_at is null order by k.id limit 1;
+commit;""",
+        **params,
+    )
+    if not rows or rows[-1][1] != "active":
+        return None  # 映射 Key 被管理员禁用：尊重该设置
+    return rows[-1][0]
+
+
+def ip_ok(main, client_ip):
+    try:
+        ip = ipaddress.ip_address(client_ip)
+    except ValueError:
+        return not main["white"]  # 无法识别 IP 时，仅在未设白名单时放行
+    inside = lambda nets: any(
+        ip in ipaddress.ip_network(n, strict=False) for n in nets if n
+    )
+    if main["black"] and inside(main["black"]):
+        return False
+    return not main["white"] or inside(main["white"])
+
+
+AUTO_INDEX = "/opt/sub2api/ops/auto_route_index.json"
+
+
+def unified_gid():
+    """统一路由分组 id（读自动匹配索引，按文件修改时间缓存）。"""
+    try:
+        mtime = os.path.getmtime(AUTO_INDEX)
+    except OSError:
+        return None
+    return cached(
+        ("unified", mtime), 3600, lambda: json.load(open(AUTO_INDEX)).get("unified_gid")
+    )
+
+
+def key_group(api_key):
+    rows = sql(
+        "select group_id from api_keys where key = :'k' and deleted_at is null;",
+        k=api_key,
+    )
+    return int(rows[0][0]) if rows and rows[0][0] else None
+
+
+class Handler(BaseHTTPRequestHandler):
+    def log_message(self, fmt, *args):  # 不记录含 Key 的请求行
+        pass
+
+    def deny(self, reason):
+        # nginx auth_request 只认 2xx/401/403，其余会变成 500；统一回 403 并用 X-Route-Reason 说明原因，
+        # 由 nginx 映射成 404/429/503 等对外状态码与 JSON 错误
+        self.reply(403, {"X-Route-Reason": reason})
+
+    def reply(self, code, headers=None):
+        self.send_response(code)
+        for k, v in (headers or {}).items():
+            self.send_header(k, v)
+        self.send_header("Content-Length", "0")
+        self.end_headers()
+
+    def request_key(self, args):
+        auth = self.headers.get("Authorization", "")
+        return (
+            (auth[7:].strip() if auth.lower().startswith("bearer ") else "")
+            or self.headers.get("x-api-key", "").strip()
+            or self.headers.get("x-goog-api-key", "").strip()
+            or args.get("key", "").strip()
+        )
+
+    def check_upstream(self):
+        """不带分组路径的请求：Key 绑定统一路由分组 → 交给自动匹配服务，否则直连 sub2api（任何异常都直连，保持原行为）。"""
+        upstream = "sub2api"
+        try:
+            args = dict(
+                parse_qsl(
+                    self.headers.get("X-Original-Args", ""), keep_blank_values=True
+                )
+            )
+            key = self.request_key(args)
+            unified = unified_gid()
+            if unified and KEY_RE.match(key):
+                gid = cached(("keygroup", key), MAIN_TTL, lambda: key_group(key))
+                if gid == unified:
+                    upstream = "s2a_auto"
+        except Exception as exc:
+            print(f"route-auth check error: {type(exc).__name__}", flush=True)
+        self.reply(200, {"X-S2A-Upstream": upstream})
+
+    def do_GET(self):
+        if self.path.startswith("/check"):
+            return self.check_upstream()
+        route = ROUTES.get(self.headers.get("X-Route-Group", ""))
+        if not route:
+            return self.deny("notfound")
+        args = dict(
+            parse_qsl(self.headers.get("X-Original-Args", ""), keep_blank_values=True)
+        )
+        auth = self.headers.get("Authorization", "")
+        key = (
+            (auth[7:].strip() if auth.lower().startswith("bearer ") else "")
+            or self.headers.get("x-api-key", "").strip()
+            or self.headers.get("x-goog-api-key", "").strip()
+            or args.get("key", "").strip()
+        )
+        if not KEY_RE.match(key):
+            return self.reply(401)
+        try:
+            main = cached(("main", key), MAIN_TTL, lambda: load_main(key))
+            if main is None:
+                return self.reply(401)
+            if not ip_ok(main, self.headers.get("X-Client-IP", "")):
+                return self.deny("ip")
+            gid = route["group_id"]
+            if not cached(
+                ("grp", main["user_id"], gid),
+                MAIN_TTL,
+                lambda: group_allowed(main["user_id"], gid),
+            ):
+                return self.deny("group")
+            if main["quota"] > 0 or any(main["rl"]):
+                used, u5, u1, u7 = family_usage(main["id"])  # 不缓存，保证额度及时生效
+                if (main["quota"] > 0 and used >= main["quota"]) or any(
+                    lim > 0 and val >= lim for lim, val in zip(main["rl"], (u5, u1, u7))
+                ):
+                    return self.deny("quota")
+            sig = (main["id"], gid, main["expires"], main["quota"], main["rl"])
+            mapped = cached(
+                ("mapped", *sig),
+                MAPPED_TTL,
+                lambda: load_mapped(main, gid, route["slug"]),
+            )
+            if mapped is None:
+                return self.deny("key_disabled")
+        except Exception as exc:  # 数据库异常时拒绝而不是放行
+            # 只记录异常类型与 psql 报错首行；不输出命令参数或输入（可能含 Key）
+            detail = ""
+            if isinstance(exc, subprocess.CalledProcessError):
+                detail = (exc.stderr or "").strip().splitlines()[:1]
+                detail = detail[0][:200] if detail else f"exit {exc.returncode}"
+            print(f"route-auth error: {type(exc).__name__} {detail}", flush=True)
+            return self.deny("unavailable")
+        if "key" in args:
+            args["key"] = mapped
+        query = urlencode(args)
+        self.reply(
+            200,
+            {"X-Mapped-Key": mapped, "X-Mapped-Query": ("?" + query) if query else ""},
+        )
+
+
+if __name__ == "__main__":
+    init_schema()
+    ThreadingHTTPServer(("127.0.0.1", 8091), Handler).serve_forever()
diff --git a/ops/route_groups.json b/ops/route_groups.json
new file mode 100644
index 0000000..e31652b
--- /dev/null
+++ b/ops/route_groups.json
@@ -0,0 +1,302 @@
+{
+ "codex_eco": {
+  "group_id": 3,
+  "slug": "codex_eco"
+ },
+ "codex/codex_eco": {
+  "group_id": 3,
+  "slug": "codex_eco"
+ },
+ "openai/codex_eco": {
+  "group_id": 3,
+  "slug": "codex_eco"
+ },
+ "claude_code/codex_eco": {
+  "group_id": 3,
+  "slug": "codex_eco"
+ },
+ "gemini/codex_eco": {
+  "group_id": 3,
+  "slug": "codex_eco"
+ },
+ "codex/codex": {
+  "group_id": 4,
+  "slug": "codex"
+ },
+ "codex": {
+  "group_id": 4,
+  "slug": "codex"
+ },
+ "openai/codex": {
+  "group_id": 4,
+  "slug": "codex"
+ },
+ "claude_code/codex": {
+  "group_id": 4,
+  "slug": "codex"
+ },
+ "gemini/codex": {
+  "group_id": 4,
+  "slug": "codex"
+ },
+ "codex/codex_pro": {
+  "group_id": 5,
+  "slug": "codex_pro"
+ },
+ "codex_pro": {
+  "group_id": 5,
+  "slug": "codex_pro"
+ },
+ "openai/codex_pro": {
+  "group_id": 5,
+  "slug": "codex_pro"
+ },
+ "claude_code/codex_pro": {
+  "group_id": 5,
+  "slug": "codex_pro"
+ },
+ "gemini/codex_pro": {
+  "group_id": 5,
+  "slug": "codex_pro"
+ },
+ "codex_sp": {
+  "group_id": 6,
+  "slug": "codex_sp"
+ },
+ "codex/codex_sp": {
+  "group_id": 6,
+  "slug": "codex_sp"
+ },
+ "openai/codex_sp": {
+  "group_id": 6,
+  "slug": "codex_sp"
+ },
+ "claude_code/codex_sp": {
+  "group_id": 6,
+  "slug": "codex_sp"
+ },
+ "gemini/codex_sp": {
+  "group_id": 6,
+  "slug": "codex_sp"
+ },
+ "grok": {
+  "group_id": 7,
+  "slug": "grok"
+ },
+ "codex/grok": {
+  "group_id": 7,
+  "slug": "grok"
+ },
+ "openai/grok": {
+  "group_id": 7,
+  "slug": "grok"
+ },
+ "claude_code/grok": {
+  "group_id": 7,
+  "slug": "grok"
+ },
+ "gemini/grok": {
+  "group_id": 7,
+  "slug": "grok"
+ },
+ "grok45": {
+  "group_id": 8,
+  "slug": "grok45"
+ },
+ "codex/grok45": {
+  "group_id": 8,
+  "slug": "grok45"
+ },
+ "openai/grok45": {
+  "group_id": 8,
+  "slug": "grok45"
+ },
+ "claude_code/grok45": {
+  "group_id": 8,
+  "slug": "grok45"
+ },
+ "gemini/grok45": {
+  "group_id": 8,
+  "slug": "grok45"
+ },
+ "claude_code/mixed_cc_pro_max": {
+  "group_id": 9,
+  "slug": "mixed_cc_pro_max"
+ },
+ "mixed_cc_pro_max": {
+  "group_id": 9,
+  "slug": "mixed_cc_pro_max"
+ },
+ "codex/mixed_cc_pro_max": {
+  "group_id": 9,
+  "slug": "mixed_cc_pro_max"
+ },
+ "openai/mixed_cc_pro_max": {
+  "group_id": 9,
+  "slug": "mixed_cc_pro_max"
+ },
+ "gemini/mixed_cc_pro_max": {
+  "group_id": 9,
+  "slug": "mixed_cc_pro_max"
+ },
+ "kiro": {
+  "group_id": 10,
+  "slug": "kiro"
+ },
+ "codex/kiro": {
+  "group_id": 10,
+  "slug": "kiro"
+ },
+ "openai/kiro": {
+  "group_id": 10,
+  "slug": "kiro"
+ },
+ "claude_code/kiro": {
+  "group_id": 10,
+  "slug": "kiro"
+ },
+ "gemini/kiro": {
+  "group_id": 10,
+  "slug": "kiro"
+ },
+ "claude_code/office3_2": {
+  "group_id": 11,
+  "slug": "office3_2"
+ },
+ "office3_2": {
+  "group_id": 11,
+  "slug": "office3_2"
+ },
+ "codex/office3_2": {
+  "group_id": 11,
+  "slug": "office3_2"
+ },
+ "openai/office3_2": {
+  "group_id": 11,
+  "slug": "office3_2"
+ },
+ "gemini/office3_2": {
+  "group_id": 11,
+  "slug": "office3_2"
+ },
+ "claude_code/cc_glm": {
+  "group_id": 12,
+  "slug": "cc_glm"
+ },
+ "cc_glm": {
+  "group_id": 12,
+  "slug": "cc_glm"
+ },
+ "codex/cc_glm": {
+  "group_id": 12,
+  "slug": "cc_glm"
+ },
+ "openai/cc_glm": {
+  "group_id": 12,
+  "slug": "cc_glm"
+ },
+ "gemini/cc_glm": {
+  "group_id": 12,
+  "slug": "cc_glm"
+ },
+ "claude_code/cc_glm_global": {
+  "group_id": 13,
+  "slug": "cc_glm_global"
+ },
+ "cc_glm_global": {
+  "group_id": 13,
+  "slug": "cc_glm_global"
+ },
+ "codex/cc_glm_global": {
+  "group_id": 13,
+  "slug": "cc_glm_global"
+ },
+ "openai/cc_glm_global": {
+  "group_id": 13,
+  "slug": "cc_glm_global"
+ },
+ "gemini/cc_glm_global": {
+  "group_id": 13,
+  "slug": "cc_glm_global"
+ },
+ "deepseek": {
+  "group_id": 14,
+  "slug": "deepseek"
+ },
+ "codex/deepseek": {
+  "group_id": 14,
+  "slug": "deepseek"
+ },
+ "openai/deepseek": {
+  "group_id": 14,
+  "slug": "deepseek"
+ },
+ "claude_code/deepseek": {
+  "group_id": 14,
+  "slug": "deepseek"
+ },
+ "gemini/deepseek": {
+  "group_id": 14,
+  "slug": "deepseek"
+ },
+ "cc_codex_56": {
+  "group_id": 15,
+  "slug": "cc_codex_56"
+ },
+ "codex/cc_codex_56": {
+  "group_id": 15,
+  "slug": "cc_codex_56"
+ },
+ "openai/cc_codex_56": {
+  "group_id": 15,
+  "slug": "cc_codex_56"
+ },
+ "claude_code/cc_codex_56": {
+  "group_id": 15,
+  "slug": "cc_codex_56"
+ },
+ "gemini/cc_codex_56": {
+  "group_id": 15,
+  "slug": "cc_codex_56"
+ },
+ "gemini_1": {
+  "group_id": 16,
+  "slug": "gemini_1"
+ },
+ "codex/gemini_1": {
+  "group_id": 16,
+  "slug": "gemini_1"
+ },
+ "openai/gemini_1": {
+  "group_id": 16,
+  "slug": "gemini_1"
+ },
+ "claude_code/gemini_1": {
+  "group_id": 16,
+  "slug": "gemini_1"
+ },
+ "gemini/gemini_1": {
+  "group_id": 16,
+  "slug": "gemini_1"
+ },
+ "codex_image": {
+  "group_id": 17,
+  "slug": "codex_image"
+ },
+ "codex/codex_image": {
+  "group_id": 17,
+  "slug": "codex_image"
+ },
+ "openai/codex_image": {
+  "group_id": 17,
+  "slug": "codex_image"
+ },
+ "claude_code/codex_image": {
+  "group_id": 17,
+  "slug": "codex_image"
+ },
+ "gemini/codex_image": {
+  "group_id": 17,
+  "slug": "codex_image"
+ }
+}
\ No newline at end of file
diff --git a/ops/snapshot_files.py b/ops/snapshot_files.py
new file mode 100644
index 0000000..0f283fa
--- /dev/null
+++ b/ops/snapshot_files.py
@@ -0,0 +1,187 @@
+"""把项目相关文件存入数据库（s2a_ops.file_snapshots / file_snapshot_history），随数据库备份一起异地保存。
+
+用法（需 root，PGPASSWORD 由 run 或 lib.sh 提供）：
+  snapshot_files.py save                 采集并入库（内容变化才写历史，每个文件保留最近 30 版）
+  snapshot_files.py list                 列出库中文件
+  snapshot_files.py restore [目录]        把库中最新版本还原到目录（默认 /root/sub2api-restore-<时间>/，按原绝对路径存放，不覆盖现有文件）
+收录范围：/opt/sub2api/ops/snapshot_paths.json（glob，支持 ** 递归；exclude 为排除的片段）。
+另外导出宝塔计划任务定义（sub2api 相关）为虚拟文件 bt-panel/crontab.json。
+"""
+
+import base64
+import glob
+import grp
+import hashlib
+import json
+import os
+import pwd
+import sqlite3
+import subprocess
+import sys
+import time
+
+PSQL = "/www/server/pgsql/bin/psql"
+CONF = "/opt/sub2api/ops/snapshot_paths.json"
+KEEP = 30
+
+
+def psql(sql, capture=True):
+    r = subprocess.run(
+        [
+            PSQL,
+            "-h",
+            "localhost",
+            "-U",
+            "postgres",
+            "-d",
+            "sub2api",
+            "-qAt",
+            "-v",
+            "ON_ERROR_STOP=1",
+        ],
+        input=sql,
+        capture_output=True,
+        text=True,
+        env=os.environ,
+    )
+    if r.returncode != 0:
+        raise SystemExit("数据库错误：" + r.stderr.strip()[:300])
+    return r.stdout
+
+
+def q(s):
+    return "'" + s.replace("'", "''") + "'"
+
+
+SCHEMA = """create schema if not exists s2a_ops;
+create table if not exists s2a_ops.file_snapshots (
+  path text primary key, sha256 text not null, size bigint not null, mode text, owner text, grp text,
+  content bytea not null, captured_at timestamptz not null default now());
+create table if not exists s2a_ops.file_snapshot_history (
+  id bigserial primary key, path text not null, sha256 text not null, size bigint not null,
+  content bytea not null, captured_at timestamptz not null default now());
+create index if not exists file_snapshot_history_path on s2a_ops.file_snapshot_history (path, captured_at desc);
+"""
+
+
+def collect():
+    conf = json.load(open(CONF))
+    files = {}
+    for pattern in conf["include"]:
+        for p in glob.glob(pattern, recursive=True):
+            if os.path.isfile(p) and not any(x in p for x in conf.get("exclude", [])):
+                files[os.path.realpath(p) if conf.get("resolve_links") else p] = None
+    out = []
+    for p in sorted(files):
+        st = os.stat(p)
+        if st.st_size > conf.get("max_file_bytes", 5_000_000):
+            continue
+        data = open(p, "rb").read()
+        out.append(
+            (
+                p,
+                data,
+                oct(st.st_mode & 0o7777),
+                pwd.getpwuid(st.st_uid).pw_name,
+                grp.getgrgid(st.st_gid).gr_name,
+            )
+        )
+    # 宝塔计划任务定义（面板数据库），便于重建任务
+    try:
+        db = sqlite3.connect("file:/www/server/panel/data/default.db?mode=ro", uri=True)
+        db.row_factory = sqlite3.Row
+        rows = [
+            dict(r)
+            for r in db.execute(
+                "select * from crontab where name like '%sub2api%' or sBody like '%sub2api%'"
+            )
+        ]
+        for r in rows:  # 附上面板生成的执行脚本内容
+            try:
+                r["_script"] = open(f"/www/server/cron/{r['echo']}").read()
+            except OSError:
+                pass
+        out.append(
+            (
+                "bt-panel/crontab.json",
+                json.dumps(rows, ensure_ascii=False, indent=1).encode(),
+                None,
+                None,
+                None,
+            )
+        )
+    except Exception as exc:
+        print("导出宝塔计划任务失败：", exc)
+    return out
+
+
+def save():
+    psql(SCHEMA)
+    current = dict(
+        line.split("\t")
+        for line in psql(
+            "\\pset fieldsep '\\t'\nselect path, sha256 from s2a_ops.file_snapshots;"
+        ).splitlines()
+        if "\t" in line
+    )
+    items = collect()
+    changed, total = 0, 0
+    sql = ["begin;"]
+    for path, data, mode, owner, group in items:
+        total += 1
+        h = hashlib.sha256(data).hexdigest()
+        if current.get(path) == h:
+            continue
+        changed += 1
+        b = base64.b64encode(data).decode()
+        sql.append(f"""insert into s2a_ops.file_snapshots (path, sha256, size, mode, owner, grp, content, captured_at)
+values ({q(path)}, '{h}', {len(data)}, {q(mode or "")}, {q(owner or "")}, {q(group or "")}, decode('{b}', 'base64'), now())
+on conflict (path) do update set sha256 = excluded.sha256, size = excluded.size, mode = excluded.mode, owner = excluded.owner,
+  grp = excluded.grp, content = excluded.content, captured_at = now();
+insert into s2a_ops.file_snapshot_history (path, sha256, size, content) values ({q(path)}, '{h}', {len(data)}, decode('{b}', 'base64'));""")
+    paths = [p for p, *_ in items]
+    sql.append(f"""delete from s2a_ops.file_snapshot_history h using (
+  select id, row_number() over (partition by path order by captured_at desc) rn from s2a_ops.file_snapshot_history) x
+  where h.id = x.id and x.rn > {KEEP};""")
+    sql.append("commit;")
+    psql("\n".join(sql))
+    gone = sorted(set(current) - set(paths))
+    size = psql("select pg_size_pretty(sum(size)) from s2a_ops.file_snapshots;").strip()
+    print(
+        f"文件入库：共 {total} 个，本次变化 {changed} 个，库中合计 {size}"
+        + (f"；{len(gone)} 个文件已不存在（库中保留旧内容）" if gone else "")
+    )
+
+
+def list_files():
+    print(
+        psql(
+            "\\pset fieldsep ' | '\nselect to_char(captured_at at time zone 'Asia/Shanghai','MM-DD HH24:MI'), lpad(size::text, 8), path "
+            "from s2a_ops.file_snapshots order by path;"
+        )
+    )
+
+
+def restore(target):
+    target = target or f"/root/sub2api-restore-{time.strftime('%Y%m%d%H%M%S')}"
+    rows = psql(
+        "\\pset fieldsep '\\t'\nselect path, mode, translate(encode(content, 'base64'), E'\\n', '') from s2a_ops.file_snapshots;"
+    ).splitlines()
+    n = 0
+    for line in rows:
+        path, mode, b64 = line.split("\t")
+        dest = os.path.join(target, path.lstrip("/"))
+        os.makedirs(os.path.dirname(dest), exist_ok=True)
+        with open(dest, "wb") as f:
+            f.write(base64.b64decode(b64))
+        os.chmod(dest, int(mode, 8) if mode else 0o600)
+        n += 1
+    os.chmod(target, 0o700)
+    print(f"已还原 {n} 个文件到 {target}（按原绝对路径存放；核对后再手动复制回原位置）")
+
+
+if __name__ == "__main__":
+    cmd = sys.argv[1] if len(sys.argv) > 1 else "save"
+    {"save": save, "list": list_files}.get(
+        cmd, lambda: restore(sys.argv[2] if len(sys.argv) > 2 else None)
+    )()
diff --git a/ops/snapshot_paths.json b/ops/snapshot_paths.json
new file mode 100644
index 0000000..0790fef
--- /dev/null
+++ b/ops/snapshot_paths.json
@@ -0,0 +1,36 @@
+{
+ "说明": "存入数据库的文件范围（glob，** 递归）。每天随数据库备份异地保存；用 /opt/sub2api/run 的「备份」功能或宝塔任务执行。",
+ "include": [
+  "/opt/sub2api/config.yaml",
+  "/opt/sub2api/run",
+  "/opt/sub2api/handoff_record.md",
+  "/opt/sub2api/sub2api.service",
+  "/opt/sub2api/ops/*",
+  "/opt/sub2api/relay/package*.json",
+  "/opt/sub2api/relay/server/**",
+  "/opt/sub2api/relay/src/**",
+  "/opt/sub2api/relay/dist/**",
+  "/opt/sub2api/data/pages/**",
+  "/etc/systemd/system/sub2api*.service",
+  "/usr/local/sbin/sub2api-config-backup.sh",
+  "/www/server/panel/script/custom/backup-sub2api.sh",
+  "/www/server/panel/vhost/nginx/api.itssx.com.conf",
+  "/www/server/panel/vhost/nginx/apiacc.itssx.com.conf",
+  "/www/server/panel/vhost/nginx/0.*.conf",
+  "/www/server/panel/vhost/nginx/sub2api-*.inc",
+  "/www/server/panel/vhost/nginx/extension/*/*.conf",
+  "/www/server/proxy_project/sites/**",
+  "/www/wwwroot/sub2api-overrides/**",
+  "/root/.config/sub2api-*.env",
+  "/www/server/panel/vhost/nginx/relay.itssx.com.conf",
+  "/www/server/panel/vhost/cert/**"
+ ],
+ "exclude": [
+  "node_modules",
+  "__pycache__",
+  ".log",
+  ".bak.",
+  "auto_route_index.json"
+ ],
+ "max_file_bytes": 5000000
+}
diff --git a/ops/svc-watchdog.sh b/ops/svc-watchdog.sh
new file mode 100755
index 0000000..aec8e3b
--- /dev/null
+++ b/ops/svc-watchdog.sh
@@ -0,0 +1,182 @@
+#!/usr/bin/env bash
+# sub2api 全服务自检与自动重启（由宝塔计划任务管理）：
+#   svc-watchdog.sh ensure   确保常驻守护进程在运行（宝塔任务 #9 每分钟执行；已在运行则立即退出；开机后 1 分钟内自动启动）
+#   svc-watchdog.sh restart  重启两个路由程序（宝塔任务 #10）
+#   svc-watchdog.sh status   查看全部服务健康状态
+# 守护循环：
+#   - 每 3 秒：route_auth（8091 分组路由鉴权）、auto_proxy（8093 统一路由）做 HTTP 健康检查，未运行立即启动，
+#     连续 3 次无响应（卡死）则杀掉重启；以 sub2api 用户运行。
+#   - 每 30 秒：nginx、sub2api、PostgreSQL、Redis、sub2api-key-query、cron、宝塔面板做健康检查，
+#     连续 3 次失败按各自方式重启；每次重启发邮件（同一服务每小时最多一封）。
+# 日志：/var/log/sub2api-ops/watchdog.log；程序日志 /var/log/sub2api-ops/<程序>.log
+set -uo pipefail
+export PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
+OPS=/opt/sub2api/ops
+LOGDIR=/var/log/sub2api-ops
+RUN=/run/sub2api-ops
+APPS="route_auth:8091:/check auto_proxy:8093:/__health"
+SYSTEM="nginx sub2api postgres redis key_query cron btpanel"
+mkdir -p "$LOGDIR" "$RUN"
+chown sub2api:sub2api "$LOGDIR"
+
+ts() { TZ=Asia/Shanghai date '+%F %T'; }
+log() { echo "$(ts) $*" >>"$LOGDIR/watchdog.log"; }
+listening() { [ -n "$(ss -ltnH "sport = :$1")" ]; }
+http_ok() { [[ "$(curl -s -m 5 -o /dev/null -w '%{http_code}' "$1" 2>/dev/null)" == [23]* ]]; }
+
+# ---------- 两个路由程序 ----------
+start_app() { # 名称 端口
+	local name=$1 port=$2
+	setsid runuser -u sub2api -- /usr/bin/python3 -I "$OPS/$name.py" >>"$LOGDIR/$name.log" 2>&1 </dev/null 8>&- &
+	for _ in $(seq 1 20); do
+		listening "$port" && {
+			log "已启动 $name（端口 $port）"
+			return 0
+		}
+		sleep 0.25
+	done
+	log "启动 $name 失败，见 $LOGDIR/$name.log"
+	return 1
+}
+
+stop_app() { # 名称 端口
+	local port=$2 pid
+	pid=$(ss -ltnpH "sport = :$port" | grep -o 'pid=[0-9]*' | head -1 | cut -d= -f2)
+	[ -n "$pid" ] && kill "$pid" 2>/dev/null
+	for _ in $(seq 1 20); do
+		listening "$port" || return 0
+		sleep 0.25
+	done
+	[ -n "$pid" ] && kill -9 "$pid" 2>/dev/null
+}
+
+# ---------- 系统服务：检测与重启方式 ----------
+check() {
+	case $1 in
+	nginx) curl -s -m 5 -o /dev/null http://127.0.0.1/ ;; # 有任何 HTTP 响应即正常
+	sub2api) http_ok http://127.0.0.1:8080/health ;;
+	postgres) /www/server/pgsql/bin/pg_isready -q -h 127.0.0.1 -p 5432 -t 5 ;;
+	redis) [ "$(timeout 5 /www/server/redis/src/redis-cli -h 127.0.0.1 -p 6379 ping 2>/dev/null)" = PONG ] ;;
+	key_query) listening 8092 ;;
+	cron) pgrep -x cron >/dev/null ;;
+	btpanel) [[ "$(/etc/init.d/bt status 2>/dev/null)" == *"Bt-Panel"*"already running"* ]] ;; # 不用管道（pipefail 下 grep -q 会误判）
+	esac
+}
+
+restart_svc() {
+	case $1 in
+	nginx) /etc/init.d/nginx restart || {
+		pkill -x nginx
+		/etc/init.d/nginx start
+	} ;;
+	sub2api)
+		systemctl reset-failed sub2api
+		systemctl restart sub2api
+		;;
+	postgres) /etc/init.d/pgsql restart ;;
+	redis) /etc/init.d/redis restart ;;
+	key_query)
+		systemctl reset-failed sub2api-key-query
+		systemctl restart sub2api-key-query
+		;;
+	cron)
+		systemctl reset-failed cron
+		systemctl restart cron
+		;; # 先清除失败标记，避免 start-limit 后无法拉起
+	btpanel) /etc/init.d/bt restart ;;
+	esac
+}
+
+notify() { # 服务 说明（同一服务每小时最多一封）
+	local stamp="$RUN/notify.$1" now
+	now=$(date +%s)
+	[ -f "$stamp" ] && [ $((now - $(cat "$stamp"))) -lt 3600 ] && return 0
+	echo "$now" >"$stamp"
+	(
+		source "$OPS/lib.sh"
+		python3 -I "$OPS/notify.py" "服务自动重启：$1" warn <<<"$(ts)（北京时间）
+服务：$1
+情况：$2
+守护日志：$LOGDIR/watchdog.log"
+	) >/dev/null 2>&1 &
+}
+
+supervise() { # 常驻循环（持有锁，保证只有一个）
+	exec 8>"$RUN/supervisor.lock"
+	flock -n 8 || exit 0
+	log "守护进程启动"
+	declare -A fail
+	local tick=0
+	while true; do
+		for a in $APPS; do
+			IFS=: read -r name port path <<<"$a"
+			if ! listening "$port"; then
+				start_app "$name" "$port"
+				fail[$name]=0
+			elif http_ok "http://127.0.0.1:$port$path"; then
+				fail[$name]=0
+			else
+				fail[$name]=$((${fail[$name]:-0} + 1))
+				if [ "${fail[$name]}" -ge 3 ]; then
+					log "$name 端口在但连续 3 次无响应，重启"
+					stop_app "$name" "$port"
+					start_app "$name" "$port"
+					notify "$name" "进程卡死（端口在但无响应），已重启"
+					fail[$name]=0
+				fi
+			fi
+		done
+		if [ $((tick % 10)) -eq 0 ]; then # 约每 30 秒
+			for s in $SYSTEM; do
+				if check "$s"; then
+					fail[$s]=0
+					continue
+				fi
+				fail[$s]=$((${fail[$s]:-0} + 1))
+				log "$s 健康检查失败（第 ${fail[$s]} 次）"
+				if [ "${fail[$s]}" -ge 3 ]; then
+					restart_svc "$s" >>"$LOGDIR/watchdog.log" 2>&1 8>&- # 拉起的进程不继承守护锁
+					sleep 5
+					if check "$s"; then
+						log "$s 已重启恢复"
+						notify "$s" "连续 3 次健康检查失败，已自动重启并恢复"
+					else
+						log "$s 重启后仍异常"
+						notify "$s" "连续 3 次健康检查失败，自动重启后仍异常，请人工处理"
+					fi
+					fail[$s]=0
+				fi
+			done
+		fi
+		tick=$((tick + 1))
+		sleep 3
+	done
+}
+
+case "${1:-ensure}" in
+ensure)
+	if flock -n "$RUN/supervisor.lock" true 2>/dev/null; then
+		setsid nohup "$0" supervise >/dev/null 2>&1 </dev/null &
+		sleep 2
+		echo "$(ts) 守护进程未运行，已启动"
+	fi
+	;;
+supervise) supervise ;;
+restart)
+	for a in $APPS; do
+		IFS=: read -r name port _ <<<"$a"
+		stop_app "$name" "$port"
+	done
+	"$0" ensure >/dev/null
+	sleep 4
+	"$0" status
+	;;
+status)
+	flock -n "$RUN/supervisor.lock" true 2>/dev/null && echo "守护进程：未运行" || echo "守护进程：运行中"
+	for a in $APPS; do
+		IFS=: read -r name port path <<<"$a"
+		http_ok "http://127.0.0.1:$port$path" && echo "$name：正常" || echo "$name：异常"
+	done
+	for s in $SYSTEM; do check "$s" && echo "$s：正常" || echo "$s：异常"; done
+	;;
+esac
diff --git a/relay/package-lock.json b/relay/package-lock.json
new file mode 100644
index 0000000..acee524
--- /dev/null
+++ b/relay/package-lock.json
@@ -0,0 +1,1107 @@
+{
+  "name": "relay_build",
+  "version": "1.0.0",
+  "lockfileVersion": 3,
+  "requires": true,
+  "packages": {
+    "": {
+      "name": "relay_build",
+      "version": "1.0.0",
+      "license": "ISC",
+      "dependencies": {
+        "@tailwindcss/cli": "^4.3.3",
+        "tailwindcss": "^4.3.3"
+      }
+    },
+    "node_modules/@jridgewell/gen-mapping": {
+      "version": "0.3.13",
+      "resolved": "https://registry.npmmirror.com/@jridgewell/gen-mapping/-/gen-mapping-0.3.13.tgz",
+      "integrity": "sha512-2kkt/7niJ6MgEPxF0bYdQ6etZaA+fQvDcLKckhy1yIQOzaoKjBBjSj63/aLVjYE3qhRt5dvM+uUyfCg6UKCBbA==",
+      "license": "MIT",
+      "dependencies": {
+        "@jridgewell/sourcemap-codec": "^1.5.0",
+        "@jridgewell/trace-mapping": "^0.3.24"
+      }
+    },
+    "node_modules/@jridgewell/remapping": {
+      "version": "2.3.5",
+      "resolved": "https://registry.npmmirror.com/@jridgewell/remapping/-/remapping-2.3.5.tgz",
+      "integrity": "sha512-LI9u/+laYG4Ds1TDKSJW2YPrIlcVYOwi2fUC6xB43lueCjgxV4lffOCZCtYFiH6TNOX+tQKXx97T4IKHbhyHEQ==",
+      "license": "MIT",
+      "dependencies": {
+        "@jridgewell/gen-mapping": "^0.3.5",
+        "@jridgewell/trace-mapping": "^0.3.24"
+      }
+    },
+    "node_modules/@jridgewell/resolve-uri": {
+      "version": "3.1.2",
+      "resolved": "https://registry.npmmirror.com/@jridgewell/resolve-uri/-/resolve-uri-3.1.2.tgz",
+      "integrity": "sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw==",
+      "license": "MIT",
+      "engines": {
+        "node": ">=6.0.0"
+      }
+    },
+    "node_modules/@jridgewell/sourcemap-codec": {
+      "version": "1.6.0",
+      "resolved": "https://registry.npmmirror.com/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.6.0.tgz",
+      "integrity": "sha512-T7jf+5zgsZHwNJ4lvQ7/aezbyk0nNX+zJVWpmHA7VYsEx7a7qr5Rg5IbtJFqkgze5Y2sruq1RUY8Q837Od7iFw==",
+      "license": "MIT"
+    },
+    "node_modules/@jridgewell/trace-mapping": {
+      "version": "0.3.31",
+      "resolved": "https://registry.npmmirror.com/@jridgewell/trace-mapping/-/trace-mapping-0.3.31.tgz",
+      "integrity": "sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==",
+      "license": "MIT",
+      "dependencies": {
+        "@jridgewell/resolve-uri": "^3.1.0",
+        "@jridgewell/sourcemap-codec": "^1.4.14"
+      }
+    },
+    "node_modules/@parcel/watcher": {
+      "version": "2.5.1",
+      "resolved": "https://registry.npmmirror.com/@parcel/watcher/-/watcher-2.5.1.tgz",
+      "integrity": "sha512-dfUnCxiN9H4ap84DvD2ubjw+3vUNpstxa0TneY/Paat8a3R4uQZDLSvWjmznAY/DoahqTHl9V46HF/Zs3F29pg==",
+      "hasInstallScript": true,
+      "license": "MIT",
+      "dependencies": {
+        "detect-libc": "^1.0.3",
+        "is-glob": "^4.0.3",
+        "micromatch": "^4.0.5",
+        "node-addon-api": "^7.0.0"
+      },
+      "engines": {
+        "node": ">= 10.0.0"
+      },
+      "funding": {
+        "type": "opencollective",
+        "url": "https://opencollective.com/parcel"
+      },
+      "optionalDependencies": {
+        "@parcel/watcher-android-arm64": "2.5.1",
+        "@parcel/watcher-darwin-arm64": "2.5.1",
+        "@parcel/watcher-darwin-x64": "2.5.1",
+        "@parcel/watcher-freebsd-x64": "2.5.1",
+        "@parcel/watcher-linux-arm-glibc": "2.5.1",
+        "@parcel/watcher-linux-arm-musl": "2.5.1",
+        "@parcel/watcher-linux-arm64-glibc": "2.5.1",
+        "@parcel/watcher-linux-arm64-musl": "2.5.1",
+        "@parcel/watcher-linux-x64-glibc": "2.5.1",
+        "@parcel/watcher-linux-x64-musl": "2.5.1",
+        "@parcel/watcher-win32-arm64": "2.5.1",
+        "@parcel/watcher-win32-ia32": "2.5.1",
+        "@parcel/watcher-win32-x64": "2.5.1"
+      }
+    },
+    "node_modules/@parcel/watcher-android-arm64": {
+      "version": "2.5.1",
+      "resolved": "https://registry.npmmirror.com/@parcel/watcher-android-arm64/-/watcher-android-arm64-2.5.1.tgz",
+      "integrity": "sha512-KF8+j9nNbUN8vzOFDpRMsaKBHZ/mcjEjMToVMJOhTozkDonQFFrRcfdLWn6yWKCmJKmdVxSgHiYvTCef4/qcBA==",
+      "cpu": [
+        "arm64"
+      ],
+      "license": "MIT",
+      "optional": true,
+      "os": [
+        "android"
+      ],
+      "engines": {
+        "node": ">= 10.0.0"
+      },
+      "funding": {
+        "type": "opencollective",
+        "url": "https://opencollective.com/parcel"
+      }
+    },
+    "node_modules/@parcel/watcher-darwin-arm64": {
+      "version": "2.5.1",
+      "resolved": "https://registry.npmmirror.com/@parcel/watcher-darwin-arm64/-/watcher-darwin-arm64-2.5.1.tgz",
+      "integrity": "sha512-eAzPv5osDmZyBhou8PoF4i6RQXAfeKL9tjb3QzYuccXFMQU0ruIc/POh30ePnaOyD1UXdlKguHBmsTs53tVoPw==",
+      "cpu": [
+        "arm64"
+      ],
+      "license": "MIT",
+      "optional": true,
+      "os": [
+        "darwin"
+      ],
+      "engines": {
+        "node": ">= 10.0.0"
+      },
+      "funding": {
+        "type": "opencollective",
+        "url": "https://opencollective.com/parcel"
+      }
+    },
+    "node_modules/@parcel/watcher-darwin-x64": {
+      "version": "2.5.1",
+      "resolved": "https://registry.npmmirror.com/@parcel/watcher-darwin-x64/-/watcher-darwin-x64-2.5.1.tgz",
+      "integrity": "sha512-1ZXDthrnNmwv10A0/3AJNZ9JGlzrF82i3gNQcWOzd7nJ8aj+ILyW1MTxVk35Db0u91oD5Nlk9MBiujMlwmeXZg==",
+      "cpu": [
+        "x64"
+      ],
+      "license": "MIT",
+      "optional": true,
+      "os": [
+        "darwin"
+      ],
+      "engines": {
+        "node": ">= 10.0.0"
+      },
+      "funding": {
+        "type": "opencollective",
+        "url": "https://opencollective.com/parcel"
+      }
+    },
+    "node_modules/@parcel/watcher-freebsd-x64": {
+      "version": "2.5.1",
+      "resolved": "https://registry.npmmirror.com/@parcel/watcher-freebsd-x64/-/watcher-freebsd-x64-2.5.1.tgz",
+      "integrity": "sha512-SI4eljM7Flp9yPuKi8W0ird8TI/JK6CSxju3NojVI6BjHsTyK7zxA9urjVjEKJ5MBYC+bLmMcbAWlZ+rFkLpJQ==",
+      "cpu": [
+        "x64"
+      ],
+      "license": "MIT",
+      "optional": true,
+      "os": [
+        "freebsd"
+      ],
+      "engines": {
+        "node": ">= 10.0.0"
+      },
+      "funding": {
+        "type": "opencollective",
+        "url": "https://opencollective.com/parcel"
+      }
+    },
+    "node_modules/@parcel/watcher-linux-arm-glibc": {
+      "version": "2.5.1",
+      "resolved": "https://registry.npmmirror.com/@parcel/watcher-linux-arm-glibc/-/watcher-linux-arm-glibc-2.5.1.tgz",
+      "integrity": "sha512-RCdZlEyTs8geyBkkcnPWvtXLY44BCeZKmGYRtSgtwwnHR4dxfHRG3gR99XdMEdQ7KeiDdasJwwvNSF5jKtDwdA==",
+      "cpu": [
+        "arm"
+      ],
+      "libc": [
+        "glibc"
+      ],
+      "license": "MIT",
+      "optional": true,
+      "os": [
+        "linux"
+      ],
+      "engines": {
+        "node": ">= 10.0.0"
+      },
+      "funding": {
+        "type": "opencollective",
+        "url": "https://opencollective.com/parcel"
+      }
+    },
+    "node_modules/@parcel/watcher-linux-arm-musl": {
+      "version": "2.5.1",
+      "resolved": "https://registry.npmmirror.com/@parcel/watcher-linux-arm-musl/-/watcher-linux-arm-musl-2.5.1.tgz",
+      "integrity": "sha512-6E+m/Mm1t1yhB8X412stiKFG3XykmgdIOqhjWj+VL8oHkKABfu/gjFj8DvLrYVHSBNC+/u5PeNrujiSQ1zwd1Q==",
+      "cpu": [
+        "arm"
+      ],
+      "libc": [
+        "musl"
+      ],
+      "license": "MIT",
+      "optional": true,
+      "os": [
+        "linux"
+      ],
+      "engines": {
+        "node": ">= 10.0.0"
+      },
+      "funding": {
+        "type": "opencollective",
+        "url": "https://opencollective.com/parcel"
+      }
+    },
+    "node_modules/@parcel/watcher-linux-arm64-glibc": {
+      "version": "2.5.1",
+      "resolved": "https://registry.npmmirror.com/@parcel/watcher-linux-arm64-glibc/-/watcher-linux-arm64-glibc-2.5.1.tgz",
+      "integrity": "sha512-LrGp+f02yU3BN9A+DGuY3v3bmnFUggAITBGriZHUREfNEzZh/GO06FF5u2kx8x+GBEUYfyTGamol4j3m9ANe8w==",
+      "cpu": [
+        "arm64"
+      ],
+      "libc": [
+        "glibc"
+      ],
+      "license": "MIT",
+      "optional": true,
+      "os": [
+        "linux"
+      ],
+      "engines": {
+        "node": ">= 10.0.0"
+      },
+      "funding": {
+        "type": "opencollective",
+        "url": "https://opencollective.com/parcel"
+      }
+    },
+    "node_modules/@parcel/watcher-linux-arm64-musl": {
+      "version": "2.5.1",
+      "resolved": "https://registry.npmmirror.com/@parcel/watcher-linux-arm64-musl/-/watcher-linux-arm64-musl-2.5.1.tgz",
+      "integrity": "sha512-cFOjABi92pMYRXS7AcQv9/M1YuKRw8SZniCDw0ssQb/noPkRzA+HBDkwmyOJYp5wXcsTrhxO0zq1U11cK9jsFg==",
+      "cpu": [
+        "arm64"
+      ],
+      "libc": [
+        "musl"
+      ],
+      "license": "MIT",
+      "optional": true,
+      "os": [
+        "linux"
+      ],
+      "engines": {
+        "node": ">= 10.0.0"
+      },
+      "funding": {
+        "type": "opencollective",
+        "url": "https://opencollective.com/parcel"
+      }
+    },
+    "node_modules/@parcel/watcher-linux-x64-glibc": {
+      "version": "2.5.1",
+      "resolved": "https://registry.npmmirror.com/@parcel/watcher-linux-x64-glibc/-/watcher-linux-x64-glibc-2.5.1.tgz",
+      "integrity": "sha512-GcESn8NZySmfwlTsIur+49yDqSny2IhPeZfXunQi48DMugKeZ7uy1FX83pO0X22sHntJ4Ub+9k34XQCX+oHt2A==",
+      "cpu": [
+        "x64"
+      ],
+      "libc": [
+        "glibc"
+      ],
+      "license": "MIT",
+      "optional": true,
+      "os": [
+        "linux"
+      ],
+      "engines": {
+        "node": ">= 10.0.0"
+      },
+      "funding": {
+        "type": "opencollective",
+        "url": "https://opencollective.com/parcel"
+      }
+    },
+    "node_modules/@parcel/watcher-linux-x64-musl": {
+      "version": "2.5.1",
+      "resolved": "https://registry.npmmirror.com/@parcel/watcher-linux-x64-musl/-/watcher-linux-x64-musl-2.5.1.tgz",
+      "integrity": "sha512-n0E2EQbatQ3bXhcH2D1XIAANAcTZkQICBPVaxMeaCVBtOpBZpWJuf7LwyWPSBDITb7In8mqQgJ7gH8CILCURXg==",
+      "cpu": [
+        "x64"
+      ],
+      "libc": [
+        "musl"
+      ],
+      "license": "MIT",
+      "optional": true,
+      "os": [
+        "linux"
+      ],
+      "engines": {
+        "node": ">= 10.0.0"
+      },
+      "funding": {
+        "type": "opencollective",
+        "url": "https://opencollective.com/parcel"
+      }
+    },
+    "node_modules/@parcel/watcher-win32-arm64": {
+      "version": "2.5.1",
+      "resolved": "https://registry.npmmirror.com/@parcel/watcher-win32-arm64/-/watcher-win32-arm64-2.5.1.tgz",
+      "integrity": "sha512-RFzklRvmc3PkjKjry3hLF9wD7ppR4AKcWNzH7kXR7GUe0Igb3Nz8fyPwtZCSquGrhU5HhUNDr/mKBqj7tqA2Vw==",
+      "cpu": [
+        "arm64"
+      ],
+      "license": "MIT",
+      "optional": true,
+      "os": [
+        "win32"
+      ],
+      "engines": {
+        "node": ">= 10.0.0"
+      },
+      "funding": {
+        "type": "opencollective",
+        "url": "https://opencollective.com/parcel"
+      }
+    },
+    "node_modules/@parcel/watcher-win32-ia32": {
+      "version": "2.5.1",
+      "resolved": "https://registry.npmmirror.com/@parcel/watcher-win32-ia32/-/watcher-win32-ia32-2.5.1.tgz",
+      "integrity": "sha512-c2KkcVN+NJmuA7CGlaGD1qJh1cLfDnQsHjE89E60vUEMlqduHGCdCLJCID5geFVM0dOtA3ZiIO8BoEQmzQVfpQ==",
+      "cpu": [
+        "ia32"
+      ],
+      "license": "MIT",
+      "optional": true,
+      "os": [
+        "win32"
+      ],
+      "engines": {
+        "node": ">= 10.0.0"
+      },
+      "funding": {
+        "type": "opencollective",
+        "url": "https://opencollective.com/parcel"
+      }
+    },
+    "node_modules/@parcel/watcher-win32-x64": {
+      "version": "2.5.1",
+      "resolved": "https://registry.npmmirror.com/@parcel/watcher-win32-x64/-/watcher-win32-x64-2.5.1.tgz",
+      "integrity": "sha512-9lHBdJITeNR++EvSQVUcaZoWupyHfXe1jZvGZ06O/5MflPcuPLtEphScIBL+AiCWBO46tDSHzWyD0uDmmZqsgA==",
+      "cpu": [
+        "x64"
+      ],
+      "license": "MIT",
+      "optional": true,
+      "os": [
+        "win32"
+      ],
+      "engines": {
+        "node": ">= 10.0.0"
+      },
+      "funding": {
+        "type": "opencollective",
+        "url": "https://opencollective.com/parcel"
+      }
+    },
+    "node_modules/@tailwindcss/cli": {
+      "version": "4.3.3",
+      "resolved": "https://registry.npmmirror.com/@tailwindcss/cli/-/cli-4.3.3.tgz",
+      "integrity": "sha512-ZvS/n1ZHOBKcVlhkt8l5NNr1EDXk1NboYO5CYDOs6NUmvT9z6bzkwsosaJftY57T/3gWNzWMJzIXLodZC8ssdw==",
+      "license": "MIT",
+      "dependencies": {
+        "@parcel/watcher": "2.5.1",
+        "@tailwindcss/node": "4.3.3",
+        "@tailwindcss/oxide": "4.3.3",
+        "enhanced-resolve": "^5.24.1",
+        "mri": "^1.2.0",
+        "picocolors": "^1.1.1",
+        "tailwindcss": "4.3.3"
+      },
+      "bin": {
+        "tailwindcss": "dist/index.mjs"
+      }
+    },
+    "node_modules/@tailwindcss/node": {
+      "version": "4.3.3",
+      "resolved": "https://registry.npmmirror.com/@tailwindcss/node/-/node-4.3.3.tgz",
+      "integrity": "sha512-/T8IKEsf9VTU6tLjgC7+sv2mOPtQxzE2jMw7u4Tt40Tx+QSZxpzh95/H6cMKoja9XuW7iMdLJYBB0o9G1CaAgg==",
+      "license": "MIT",
+      "dependencies": {
+        "@jridgewell/remapping": "^2.3.5",
+        "enhanced-resolve": "^5.24.1",
+        "jiti": "^2.7.0",
+        "lightningcss": "1.32.0",
+        "magic-string": "^0.30.21",
+        "source-map-js": "^1.2.1",
+        "tailwindcss": "4.3.3"
+      }
+    },
+    "node_modules/@tailwindcss/oxide": {
+      "version": "4.3.3",
+      "resolved": "https://registry.npmmirror.com/@tailwindcss/oxide/-/oxide-4.3.3.tgz",
+      "integrity": "sha512-krXjAikiaFSPaK/FkAQT5UTx3VormQaiZ5hBFlJZ9UFQGB/rwg1MZIhHAG9smMQRTdyJxP6Qt5MwMtdyU5FWrA==",
+      "license": "MIT",
+      "engines": {
+        "node": ">= 20"
+      },
+      "optionalDependencies": {
+        "@tailwindcss/oxide-android-arm64": "4.3.3",
+        "@tailwindcss/oxide-darwin-arm64": "4.3.3",
+        "@tailwindcss/oxide-darwin-x64": "4.3.3",
+        "@tailwindcss/oxide-freebsd-x64": "4.3.3",
+        "@tailwindcss/oxide-linux-arm-gnueabihf": "4.3.3",
+        "@tailwindcss/oxide-linux-arm64-gnu": "4.3.3",
+        "@tailwindcss/oxide-linux-arm64-musl": "4.3.3",
+        "@tailwindcss/oxide-linux-x64-gnu": "4.3.3",
+        "@tailwindcss/oxide-linux-x64-musl": "4.3.3",
+        "@tailwindcss/oxide-wasm32-wasi": "4.3.3",
+        "@tailwindcss/oxide-win32-arm64-msvc": "4.3.3",
+        "@tailwindcss/oxide-win32-x64-msvc": "4.3.3"
+      }
+    },
+    "node_modules/@tailwindcss/oxide-android-arm64": {
+      "version": "4.3.3",
+      "resolved": "https://registry.npmmirror.com/@tailwindcss/oxide-android-arm64/-/oxide-android-arm64-4.3.3.tgz",
+      "integrity": "sha512-Y85A2gmPSkl5Ve5qR86GL4HT509cFqQh1aes9p3sSkyTPwt0Pppf3GkwGe4JPACcRYjgJIEhQgM6dBClnr0NYw==",
+      "cpu": [
+        "arm64"
+      ],
+      "license": "MIT",
+      "optional": true,
+      "os": [
+        "android"
+      ],
+      "engines": {
+        "node": ">= 20"
+      }
+    },
+    "node_modules/@tailwindcss/oxide-darwin-arm64": {
+      "version": "4.3.3",
+      "resolved": "https://registry.npmmirror.com/@tailwindcss/oxide-darwin-arm64/-/oxide-darwin-arm64-4.3.3.tgz",
+      "integrity": "sha512-BiaWatpBcERQFDlOjRDpIVXuFK5PJez5SA4JMg6VYZdBYU+qKfV/vqjcIs+IYmtitf1xYQZTwXvU/8y4lfZUGw==",
+      "cpu": [
+        "arm64"
+      ],
+      "license": "MIT",
+      "optional": true,
+      "os": [
+        "darwin"
+      ],
+      "engines": {
+        "node": ">= 20"
+      }
+    },
+    "node_modules/@tailwindcss/oxide-darwin-x64": {
+      "version": "4.3.3",
+      "resolved": "https://registry.npmmirror.com/@tailwindcss/oxide-darwin-x64/-/oxide-darwin-x64-4.3.3.tgz",
+      "integrity": "sha512-fAeUqfV5ndhxRwai8cXGzdLvul9utWOmeTkv69unv4ZXixjn61Z+p9lCWdwOwA3TYboG3BwdVuN/RDjhBRl0mw==",
+      "cpu": [
+        "x64"
+      ],
+      "license": "MIT",
+      "optional": true,
+      "os": [
+        "darwin"
+      ],
+      "engines": {
+        "node": ">= 20"
+      }
+    },
+    "node_modules/@tailwindcss/oxide-freebsd-x64": {
+      "version": "4.3.3",
+      "resolved": "https://registry.npmmirror.com/@tailwindcss/oxide-freebsd-x64/-/oxide-freebsd-x64-4.3.3.tgz",
+      "integrity": "sha512-iyf5bV6+wnAlflVeEy7R25dupxTNECZN5QMI0qNT6eT+EgaGdZcKhGkr5SdoaWiLJ3spLqIY9VCeSGrwmtg4kw==",
+      "cpu": [
+        "x64"
+      ],
+      "license": "MIT",
+      "optional": true,
+      "os": [
+        "freebsd"
+      ],
+      "engines": {
+        "node": ">= 20"
+      }
+    },
+    "node_modules/@tailwindcss/oxide-linux-arm-gnueabihf": {
+      "version": "4.3.3",
+      "resolved": "https://registry.npmmirror.com/@tailwindcss/oxide-linux-arm-gnueabihf/-/oxide-linux-arm-gnueabihf-4.3.3.tgz",
+      "integrity": "sha512-aAYUprJAJQWWbRrPvtjdroZ56Md+JM8pMiopS6xGEwDfLhqj+2ver2p4nU4Mb3CRqcMmNBjo8KkUgcxhkzVQGQ==",
+      "cpu": [
+        "arm"
+      ],
+      "license": "MIT",
+      "optional": true,
+      "os": [
+        "linux"
+      ],
+      "engines": {
+        "node": ">= 20"
+      }
+    },
+    "node_modules/@tailwindcss/oxide-linux-arm64-gnu": {
+      "version": "4.3.3",
+      "resolved": "https://registry.npmmirror.com/@tailwindcss/oxide-linux-arm64-gnu/-/oxide-linux-arm64-gnu-4.3.3.tgz",
+      "integrity": "sha512-nDxldcEENOxZRzC2uu9jrutZdAAQtb+8WWDCSnWL1zvBk1+FN+x6MtDViPB5AJMfttVCUhehGWus3XBPgatM/w==",
+      "cpu": [
+        "arm64"
+      ],
+      "libc": [
+        "glibc"
+      ],
+      "license": "MIT",
+      "optional": true,
+      "os": [
+        "linux"
+      ],
+      "engines": {
+        "node": ">= 20"
+      }
+    },
+    "node_modules/@tailwindcss/oxide-linux-arm64-musl": {
+      "version": "4.3.3",
+      "resolved": "https://registry.npmmirror.com/@tailwindcss/oxide-linux-arm64-musl/-/oxide-linux-arm64-musl-4.3.3.tgz",
+      "integrity": "sha512-Md44bD6veX/PC5iyF8cDVnw4HBIANZepRZZ7a8DQOvkfo5WUBwcp6iAuCUz23u+4SUkhJlD3eL7hNdW8ezd/kA==",
+      "cpu": [
+        "arm64"
+      ],
+      "libc": [
+        "musl"
+      ],
+      "license": "MIT",
+      "optional": true,
+      "os": [
+        "linux"
+      ],
+      "engines": {
+        "node": ">= 20"
+      }
+    },
+    "node_modules/@tailwindcss/oxide-linux-x64-gnu": {
+      "version": "4.3.3",
+      "resolved": "https://registry.npmmirror.com/@tailwindcss/oxide-linux-x64-gnu/-/oxide-linux-x64-gnu-4.3.3.tgz",
+      "integrity": "sha512-tx7us1muwOKAKWao2v/GaafFeQboE6aj88vC6ziN2NCGcRm8gWUhwjzg+YdVB1e4boAtdtma4L43onunI6NS4w==",
+      "cpu": [
+        "x64"
+      ],
+      "libc": [
+        "glibc"
+      ],
+      "license": "MIT",
+      "optional": true,
+      "os": [
+        "linux"
+      ],
+      "engines": {
+        "node": ">= 20"
+      }
+    },
+    "node_modules/@tailwindcss/oxide-linux-x64-musl": {
+      "version": "4.3.3",
+      "resolved": "https://registry.npmmirror.com/@tailwindcss/oxide-linux-x64-musl/-/oxide-linux-x64-musl-4.3.3.tgz",
+      "integrity": "sha512-SJxX60smvHgasZoBy11dX6YRjXJFovwWBoedhbQPOBzgFWBHGB+TVPWB9BxzR7TTxU8FQZAI2AyiNCMzFm8Img==",
+      "cpu": [
+        "x64"
+      ],
+      "libc": [
+        "musl"
+      ],
+      "license": "MIT",
+      "optional": true,
+      "os": [
+        "linux"
+      ],
+      "engines": {
+        "node": ">= 20"
+      }
+    },
+    "node_modules/@tailwindcss/oxide-wasm32-wasi": {
+      "version": "4.3.3",
+      "resolved": "https://registry.npmmirror.com/@tailwindcss/oxide-wasm32-wasi/-/oxide-wasm32-wasi-4.3.3.tgz",
+      "integrity": "sha512-jx1+rPhY/5Ympkktd656HBWEBLxP7dH06losBLjjf5vgCODXvi9KhtftWcMIwTFIDqBr7cRnQkdLnAG+IOlGvQ==",
+      "bundleDependencies": [
+        "@napi-rs/wasm-runtime",
+        "@emnapi/core",
+        "@emnapi/runtime",
+        "@tybys/wasm-util",
+        "@emnapi/wasi-threads",
+        "tslib"
+      ],
+      "cpu": [
+        "wasm32"
+      ],
+      "license": "MIT",
+      "optional": true,
+      "dependencies": {
+        "@emnapi/core": "^1.11.1",
+        "@emnapi/runtime": "^1.11.1",
+        "@emnapi/wasi-threads": "^1.2.2",
+        "@napi-rs/wasm-runtime": "^1.1.4",
+        "@tybys/wasm-util": "^0.10.2",
+        "tslib": "^2.8.1"
+      },
+      "engines": {
+        "node": ">=14.0.0"
+      }
+    },
+    "node_modules/@tailwindcss/oxide-win32-arm64-msvc": {
+      "version": "4.3.3",
+      "resolved": "https://registry.npmmirror.com/@tailwindcss/oxide-win32-arm64-msvc/-/oxide-win32-arm64-msvc-4.3.3.tgz",
+      "integrity": "sha512-3rc292Ca2ceK6Ulcc/bAVnTs/3nDtoPhyEKlgPv+yQJQi/JS/AMJlqzxvlDacL1nekbrcf6bTqp/jV4qgnPxNQ==",
+      "cpu": [
+        "arm64"
+      ],
+      "license": "MIT",
+      "optional": true,
+      "os": [
+        "win32"
+      ],
+      "engines": {
+        "node": ">= 20"
+      }
+    },
+    "node_modules/@tailwindcss/oxide-win32-x64-msvc": {
+      "version": "4.3.3",
+      "resolved": "https://registry.npmmirror.com/@tailwindcss/oxide-win32-x64-msvc/-/oxide-win32-x64-msvc-4.3.3.tgz",
+      "integrity": "sha512-yJ0pwIVc/nYeGoV02WtsN8KYyLQv7kyI2wDnkezyJlGGjkd4QLwDGAwl47YpPJeuI0M0ObaXGSPjvWDPeTPggw==",
+      "cpu": [
+        "x64"
+      ],
+      "license": "MIT",
+      "optional": true,
+      "os": [
+        "win32"
+      ],
+      "engines": {
+        "node": ">= 20"
+      }
+    },
+    "node_modules/braces": {
+      "version": "3.0.3",
+      "resolved": "https://registry.npmmirror.com/braces/-/braces-3.0.3.tgz",
+      "integrity": "sha512-yQbXgO/OSZVD2IsiLlro+7Hf6Q18EJrKSEsdoMzKePKXct3gvD8oLcOQdIzGupr5Fj+EDe8gO/lxc1BzfMpxvA==",
+      "license": "MIT",
+      "dependencies": {
+        "fill-range": "^7.1.1"
+      },
+      "engines": {
+        "node": ">=8"
+      }
+    },
+    "node_modules/detect-libc": {
+      "version": "1.0.3",
+      "resolved": "https://registry.npmmirror.com/detect-libc/-/detect-libc-1.0.3.tgz",
+      "integrity": "sha512-pGjwhsmsp4kL2RTz08wcOlGN83otlqHeD/Z5T8GXZB+/YcpQ/dgo+lbU8ZsGxV0HIvqqxo9l7mqYwyYMD9bKDg==",
+      "license": "Apache-2.0",
+      "bin": {
+        "detect-libc": "bin/detect-libc.js"
+      },
+      "engines": {
+        "node": ">=0.10"
+      }
+    },
+    "node_modules/enhanced-resolve": {
+      "version": "5.26.0",
+      "resolved": "https://registry.npmmirror.com/enhanced-resolve/-/enhanced-resolve-5.26.0.tgz",
+      "integrity": "sha512-9vhedylFonb2YGogzUKX6+Ja72gOJbN1QHAqdrvqLwhdl/QWbKopzoUC9EbQNVsAns/bx/4uyqalrQAoy1IByw==",
+      "license": "MIT",
+      "dependencies": {
+        "graceful-fs": "^4.2.4",
+        "tapable": "^2.3.3"
+      },
+      "engines": {
+        "node": ">=10.13.0"
+      }
+    },
+    "node_modules/fill-range": {
+      "version": "7.1.1",
+      "resolved": "https://registry.npmmirror.com/fill-range/-/fill-range-7.1.1.tgz",
+      "integrity": "sha512-YsGpe3WHLK8ZYi4tWDg2Jy3ebRz2rXowDxnld4bkQB00cc/1Zw9AWnC0i9ztDJitivtQvaI9KaLyKrc+hBW0yg==",
+      "license": "MIT",
+      "dependencies": {
+        "to-regex-range": "^5.0.1"
+      },
+      "engines": {
+        "node": ">=8"
+      }
+    },
+    "node_modules/graceful-fs": {
+      "version": "4.2.11",
+      "resolved": "https://registry.npmmirror.com/graceful-fs/-/graceful-fs-4.2.11.tgz",
+      "integrity": "sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ==",
+      "license": "ISC"
+    },
+    "node_modules/is-extglob": {
+      "version": "2.1.1",
+      "resolved": "https://registry.npmmirror.com/is-extglob/-/is-extglob-2.1.1.tgz",
+      "integrity": "sha512-SbKbANkN603Vi4jEZv49LeVJMn4yGwsbzZworEoyEiutsN3nJYdbO36zfhGJ6QEDpOZIFkDtnq5JRxmvl3jsoQ==",
+      "license": "MIT",
+      "engines": {
+        "node": ">=0.10.0"
+      }
+    },
+    "node_modules/is-glob": {
+      "version": "4.0.3",
+      "resolved": "https://registry.npmmirror.com/is-glob/-/is-glob-4.0.3.tgz",
+      "integrity": "sha512-xelSayHH36ZgE7ZWhli7pW34hNbNl8Ojv5KVmkJD4hBdD3th8Tfk9vYasLM+mXWOZhFkgZfxhLSnrwRr4elSSg==",
+      "license": "MIT",
+      "dependencies": {
+        "is-extglob": "^2.1.1"
+      },
+      "engines": {
+        "node": ">=0.10.0"
+      }
+    },
+    "node_modules/is-number": {
+      "version": "7.0.0",
+      "resolved": "https://registry.npmmirror.com/is-number/-/is-number-7.0.0.tgz",
+      "integrity": "sha512-41Cifkg6e8TylSpdtTpeLVMqvSBEVzTttHvERD741+pnZ8ANv0004MRL43QKPDlK9cGvNp6NZWZUBlbGXYxxng==",
+      "license": "MIT",
+      "engines": {
+        "node": ">=0.12.0"
+      }
+    },
+    "node_modules/jiti": {
+      "version": "2.7.0",
+      "resolved": "https://registry.npmmirror.com/jiti/-/jiti-2.7.0.tgz",
+      "integrity": "sha512-AC/7JofJvZGrrneWNaEnJeOLUx+JlGt7tNa0wZiRPT4MY1wmfKjt2+6O2p2uz2+skll8OZZmJMNqeke7kKbNgQ==",
+      "license": "MIT",
+      "bin": {
+        "jiti": "lib/jiti-cli.mjs"
+      }
+    },
+    "node_modules/lightningcss": {
+      "version": "1.32.0",
+      "resolved": "https://registry.npmmirror.com/lightningcss/-/lightningcss-1.32.0.tgz",
+      "integrity": "sha512-NXYBzinNrblfraPGyrbPoD19C1h9lfI/1mzgWYvXUTe414Gz/X1FD2XBZSZM7rRTrMA8JL3OtAaGifrIKhQ5yQ==",
+      "license": "MPL-2.0",
+      "dependencies": {
+        "detect-libc": "^2.0.3"
+      },
+      "engines": {
+        "node": ">= 12.0.0"
+      },
+      "funding": {
+        "type": "opencollective",
+        "url": "https://opencollective.com/parcel"
+      },
+      "optionalDependencies": {
+        "lightningcss-android-arm64": "1.32.0",
+        "lightningcss-darwin-arm64": "1.32.0",
+        "lightningcss-darwin-x64": "1.32.0",
+        "lightningcss-freebsd-x64": "1.32.0",
+        "lightningcss-linux-arm-gnueabihf": "1.32.0",
+        "lightningcss-linux-arm64-gnu": "1.32.0",
+        "lightningcss-linux-arm64-musl": "1.32.0",
+        "lightningcss-linux-x64-gnu": "1.32.0",
+        "lightningcss-linux-x64-musl": "1.32.0",
+        "lightningcss-win32-arm64-msvc": "1.32.0",
+        "lightningcss-win32-x64-msvc": "1.32.0"
+      }
+    },
+    "node_modules/lightningcss-android-arm64": {
+      "version": "1.32.0",
+      "resolved": "https://registry.npmmirror.com/lightningcss-android-arm64/-/lightningcss-android-arm64-1.32.0.tgz",
+      "integrity": "sha512-YK7/ClTt4kAK0vo6w3X+Pnm0D2cf2vPHbhOXdoNti1Ga0al1P4TBZhwjATvjNwLEBCnKvjJc2jQgHXH0NEwlAg==",
+      "cpu": [
+        "arm64"
+      ],
+      "license": "MPL-2.0",
+      "optional": true,
+      "os": [
+        "android"
+      ],
+      "engines": {
+        "node": ">= 12.0.0"
+      },
+      "funding": {
+        "type": "opencollective",
+        "url": "https://opencollective.com/parcel"
+      }
+    },
+    "node_modules/lightningcss-darwin-arm64": {
+      "version": "1.32.0",
+      "resolved": "https://registry.npmmirror.com/lightningcss-darwin-arm64/-/lightningcss-darwin-arm64-1.32.0.tgz",
+      "integrity": "sha512-RzeG9Ju5bag2Bv1/lwlVJvBE3q6TtXskdZLLCyfg5pt+HLz9BqlICO7LZM7VHNTTn/5PRhHFBSjk5lc4cmscPQ==",
+      "cpu": [
+        "arm64"
+      ],
+      "license": "MPL-2.0",
+      "optional": true,
+      "os": [
+        "darwin"
+      ],
+      "engines": {
+        "node": ">= 12.0.0"
+      },
+      "funding": {
+        "type": "opencollective",
+        "url": "https://opencollective.com/parcel"
+      }
+    },
+    "node_modules/lightningcss-darwin-x64": {
+      "version": "1.32.0",
+      "resolved": "https://registry.npmmirror.com/lightningcss-darwin-x64/-/lightningcss-darwin-x64-1.32.0.tgz",
+      "integrity": "sha512-U+QsBp2m/s2wqpUYT/6wnlagdZbtZdndSmut/NJqlCcMLTWp5muCrID+K5UJ6jqD2BFshejCYXniPDbNh73V8w==",
+      "cpu": [
+        "x64"
+      ],
+      "license": "MPL-2.0",
+      "optional": true,
+      "os": [
+        "darwin"
+      ],
+      "engines": {
+        "node": ">= 12.0.0"
+      },
+      "funding": {
+        "type": "opencollective",
+        "url": "https://opencollective.com/parcel"
+      }
+    },
+    "node_modules/lightningcss-freebsd-x64": {
+      "version": "1.32.0",
+      "resolved": "https://registry.npmmirror.com/lightningcss-freebsd-x64/-/lightningcss-freebsd-x64-1.32.0.tgz",
+      "integrity": "sha512-JCTigedEksZk3tHTTthnMdVfGf61Fky8Ji2E4YjUTEQX14xiy/lTzXnu1vwiZe3bYe0q+SpsSH/CTeDXK6WHig==",
+      "cpu": [
+        "x64"
+      ],
+      "license": "MPL-2.0",
+      "optional": true,
+      "os": [
+        "freebsd"
+      ],
+      "engines": {
+        "node": ">= 12.0.0"
+      },
+      "funding": {
+        "type": "opencollective",
+        "url": "https://opencollective.com/parcel"
+      }
+    },
+    "node_modules/lightningcss-linux-arm-gnueabihf": {
+      "version": "1.32.0",
+      "resolved": "https://registry.npmmirror.com/lightningcss-linux-arm-gnueabihf/-/lightningcss-linux-arm-gnueabihf-1.32.0.tgz",
+      "integrity": "sha512-x6rnnpRa2GL0zQOkt6rts3YDPzduLpWvwAF6EMhXFVZXD4tPrBkEFqzGowzCsIWsPjqSK+tyNEODUBXeeVHSkw==",
+      "cpu": [
+        "arm"
+      ],
+      "license": "MPL-2.0",
+      "optional": true,
+      "os": [
+        "linux"
+      ],
+      "engines": {
+        "node": ">= 12.0.0"
+      },
+      "funding": {
+        "type": "opencollective",
+        "url": "https://opencollective.com/parcel"
+      }
+    },
+    "node_modules/lightningcss-linux-arm64-gnu": {
+      "version": "1.32.0",
+      "resolved": "https://registry.npmmirror.com/lightningcss-linux-arm64-gnu/-/lightningcss-linux-arm64-gnu-1.32.0.tgz",
+      "integrity": "sha512-0nnMyoyOLRJXfbMOilaSRcLH3Jw5z9HDNGfT/gwCPgaDjnx0i8w7vBzFLFR1f6CMLKF8gVbebmkUN3fa/kQJpQ==",
+      "cpu": [
+        "arm64"
+      ],
+      "libc": [
+        "glibc"
+      ],
+      "license": "MPL-2.0",
+      "optional": true,
+      "os": [
+        "linux"
+      ],
+      "engines": {
+        "node": ">= 12.0.0"
+      },
+      "funding": {
+        "type": "opencollective",
+        "url": "https://opencollective.com/parcel"
+      }
+    },
+    "node_modules/lightningcss-linux-arm64-musl": {
+      "version": "1.32.0",
+      "resolved": "https://registry.npmmirror.com/lightningcss-linux-arm64-musl/-/lightningcss-linux-arm64-musl-1.32.0.tgz",
+      "integrity": "sha512-UpQkoenr4UJEzgVIYpI80lDFvRmPVg6oqboNHfoH4CQIfNA+HOrZ7Mo7KZP02dC6LjghPQJeBsvXhJod/wnIBg==",
+      "cpu": [
+        "arm64"
+      ],
+      "libc": [
+        "musl"
+      ],
+      "license": "MPL-2.0",
+      "optional": true,
+      "os": [
+        "linux"
+      ],
+      "engines": {
+        "node": ">= 12.0.0"
+      },
+      "funding": {
+        "type": "opencollective",
+        "url": "https://opencollective.com/parcel"
+      }
+    },
+    "node_modules/lightningcss-linux-x64-gnu": {
+      "version": "1.32.0",
+      "resolved": "https://registry.npmmirror.com/lightningcss-linux-x64-gnu/-/lightningcss-linux-x64-gnu-1.32.0.tgz",
+      "integrity": "sha512-V7Qr52IhZmdKPVr+Vtw8o+WLsQJYCTd8loIfpDaMRWGUZfBOYEJeyJIkqGIDMZPwPx24pUMfwSxxI8phr/MbOA==",
+      "cpu": [
+        "x64"
+      ],
+      "libc": [
+        "glibc"
+      ],
+      "license": "MPL-2.0",
+      "optional": true,
+      "os": [
+        "linux"
+      ],
+      "engines": {
+        "node": ">= 12.0.0"
+      },
+      "funding": {
+        "type": "opencollective",
+        "url": "https://opencollective.com/parcel"
+      }
+    },
+    "node_modules/lightningcss-linux-x64-musl": {
+      "version": "1.32.0",
+      "resolved": "https://registry.npmmirror.com/lightningcss-linux-x64-musl/-/lightningcss-linux-x64-musl-1.32.0.tgz",
+      "integrity": "sha512-bYcLp+Vb0awsiXg/80uCRezCYHNg1/l3mt0gzHnWV9XP1W5sKa5/TCdGWaR/zBM2PeF/HbsQv/j2URNOiVuxWg==",
+      "cpu": [
+        "x64"
+      ],
+      "libc": [
+        "musl"
+      ],
+      "license": "MPL-2.0",
+      "optional": true,
+      "os": [
+        "linux"
+      ],
+      "engines": {
+        "node": ">= 12.0.0"
+      },
+      "funding": {
+        "type": "opencollective",
+        "url": "https://opencollective.com/parcel"
+      }
+    },
+    "node_modules/lightningcss-win32-arm64-msvc": {
+      "version": "1.32.0",
+      "resolved": "https://registry.npmmirror.com/lightningcss-win32-arm64-msvc/-/lightningcss-win32-arm64-msvc-1.32.0.tgz",
+      "integrity": "sha512-8SbC8BR40pS6baCM8sbtYDSwEVQd4JlFTOlaD3gWGHfThTcABnNDBda6eTZeqbofalIJhFx0qKzgHJmcPTnGdw==",
+      "cpu": [
+        "arm64"
+      ],
+      "license": "MPL-2.0",
+      "optional": true,
+      "os": [
+        "win32"
+      ],
+      "engines": {
+        "node": ">= 12.0.0"
+      },
+      "funding": {
+        "type": "opencollective",
+        "url": "https://opencollective.com/parcel"
+      }
+    },
+    "node_modules/lightningcss-win32-x64-msvc": {
+      "version": "1.32.0",
+      "resolved": "https://registry.npmmirror.com/lightningcss-win32-x64-msvc/-/lightningcss-win32-x64-msvc-1.32.0.tgz",
+      "integrity": "sha512-Amq9B/SoZYdDi1kFrojnoqPLxYhQ4Wo5XiL8EVJrVsB8ARoC1PWW6VGtT0WKCemjy8aC+louJnjS7U18x3b06Q==",
+      "cpu": [
+        "x64"
+      ],
+      "license": "MPL-2.0",
+      "optional": true,
+      "os": [
+        "win32"
+      ],
+      "engines": {
+        "node": ">= 12.0.0"
+      },
+      "funding": {
+        "type": "opencollective",
+        "url": "https://opencollective.com/parcel"
+      }
+    },
+    "node_modules/lightningcss/node_modules/detect-libc": {
+      "version": "2.1.2",
+      "resolved": "https://registry.npmmirror.com/detect-libc/-/detect-libc-2.1.2.tgz",
+      "integrity": "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==",
+      "license": "Apache-2.0",
+      "engines": {
+        "node": ">=8"
+      }
+    },
+    "node_modules/magic-string": {
+      "version": "0.30.21",
+      "resolved": "https://registry.npmmirror.com/magic-string/-/magic-string-0.30.21.tgz",
+      "integrity": "sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ==",
+      "license": "MIT",
+      "dependencies": {
+        "@jridgewell/sourcemap-codec": "^1.5.5"
+      }
+    },
+    "node_modules/micromatch": {
+      "version": "4.0.8",
+      "resolved": "https://registry.npmmirror.com/micromatch/-/micromatch-4.0.8.tgz",
+      "integrity": "sha512-PXwfBhYu0hBCPw8Dn0E+WDYb7af3dSLVWKi3HGv84IdF4TyFoC0ysxFd0Goxw7nSv4T/PzEJQxsYsEiFCKo2BA==",
+      "license": "MIT",
+      "dependencies": {
+        "braces": "^3.0.3",
+        "picomatch": "^2.3.1"
+      },
+      "engines": {
+        "node": ">=8.6"
+      }
+    },
+    "node_modules/mri": {
+      "version": "1.2.0",
+      "resolved": "https://registry.npmmirror.com/mri/-/mri-1.2.0.tgz",
+      "integrity": "sha512-tzzskb3bG8LvYGFF/mDTpq3jpI6Q9wc3LEmBaghu+DdCssd1FakN7Bc0hVNmEyGq1bq3RgfkCb3cmQLpNPOroA==",
+      "license": "MIT",
+      "engines": {
+        "node": ">=4"
+      }
+    },
+    "node_modules/node-addon-api": {
+      "version": "7.1.1",
+      "resolved": "https://registry.npmmirror.com/node-addon-api/-/node-addon-api-7.1.1.tgz",
+      "integrity": "sha512-5m3bsyrjFWE1xf7nz7YXdN4udnVtXK6/Yfgn5qnahL6bCkf2yKt4k3nuTKAtT4r3IG8JNR2ncsIMdZuAzJjHQQ==",
+      "license": "MIT"
+    },
+    "node_modules/picocolors": {
+      "version": "1.1.1",
+      "resolved": "https://registry.npmmirror.com/picocolors/-/picocolors-1.1.1.tgz",
+      "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==",
+      "license": "ISC"
+    },
+    "node_modules/picomatch": {
+      "version": "2.3.2",
+      "resolved": "https://registry.npmmirror.com/picomatch/-/picomatch-2.3.2.tgz",
+      "integrity": "sha512-V7+vQEJ06Z+c5tSye8S+nHUfI51xoXIXjHQ99cQtKUkQqqO1kO/KCJUfZXuB47h/YBlDhah2H3hdUGXn8ie0oA==",
+      "license": "MIT",
+      "engines": {
+        "node": ">=8.6"
+      },
+      "funding": {
+        "url": "https://github.com/sponsors/jonschlinkert"
+      }
+    },
+    "node_modules/source-map-js": {
+      "version": "1.2.2",
+      "resolved": "https://registry.npmmirror.com/source-map-js/-/source-map-js-1.2.2.tgz",
+      "integrity": "sha512-KGj/8Y43x35aZVDtt+J4mK1hoLGHULMYfSkODJNQjNDC3oW1PqPoxMwo0pLUsWM/UEGzON/NxeHywEfNXNP3Vw==",
+      "license": "BSD-3-Clause",
+      "engines": {
+        "node": ">=0.10.0"
+      }
+    },
+    "node_modules/tailwindcss": {
+      "version": "4.3.3",
+      "resolved": "https://registry.npmmirror.com/tailwindcss/-/tailwindcss-4.3.3.tgz",
+      "integrity": "sha512-gOhV3P7ufE62QDGg1zVaTgCR+EtPv92k2nIhVcVKcLmxT1sUBsQGhnZj175j+MqRt4zLF7ic+sCYjfhxMxj7YQ==",
+      "license": "MIT"
+    },
+    "node_modules/tapable": {
+      "version": "2.3.3",
+      "resolved": "https://registry.npmmirror.com/tapable/-/tapable-2.3.3.tgz",
+      "integrity": "sha512-uxc/zpqFg6x7C8vOE7lh6Lbda8eEL9zmVm/PLeTPBRhh1xCgdWaQ+J1CUieGpIfm2HdtsUpRv+HshiasBMcc6A==",
+      "license": "MIT",
+      "engines": {
+        "node": ">=6"
+      },
+      "funding": {
+        "type": "opencollective",
+        "url": "https://opencollective.com/webpack"
+      }
+    },
+    "node_modules/to-regex-range": {
+      "version": "5.0.1",
+      "resolved": "https://registry.npmmirror.com/to-regex-range/-/to-regex-range-5.0.1.tgz",
+      "integrity": "sha512-65P7iz6X5yEr1cwcgvQxbbIw7Uk3gOy5dIdtZ4rDveLqhrdJP+Li/Hx6tyK0NEb+2GCyneCMJiGqrADCSNk8sQ==",
+      "license": "MIT",
+      "dependencies": {
+        "is-number": "^7.0.0"
+      },
+      "engines": {
+        "node": ">=8.0"
+      }
+    }
+  }
+}
diff --git a/relay/package.json b/relay/package.json
new file mode 100644
index 0000000..f723c6f
--- /dev/null
+++ b/relay/package.json
@@ -0,0 +1,17 @@
+{
+  "name": "relay_build",
+  "version": "1.0.0",
+  "description": "",
+  "main": "index.js",
+  "scripts": {
+    "test": "echo \"Error: no test specified\" && exit 1"
+  },
+  "keywords": [],
+  "author": "",
+  "license": "ISC",
+  "type": "commonjs",
+  "dependencies": {
+    "@tailwindcss/cli": "^4.3.3",
+    "tailwindcss": "^4.3.3"
+  }
+}
diff --git a/relay/run b/relay/run
new file mode 100755
index 0000000..73c90e5
--- /dev/null
+++ b/relay/run
@@ -0,0 +1,172 @@
+#!/usr/bin/env bash
+# ==============================================================================
+# StarNexus Relay Web 一键管理与运行脚本
+# 项目目录: /opt/sub2api/relay
+# 功能: 编译 Tailwind CSS、管理独立后端服务、健康检查
+# ==============================================================================
+
+set -e
+
+PROJECT_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
+DIST_DIR="${PROJECT_ROOT}/dist"
+SRC_DIR="${PROJECT_ROOT}/src"
+SERVER_DIR="${PROJECT_ROOT}/server"
+SYSTEMD_SERVICE="sub2api-key-query"
+BACKEND_PORT=8092
+
+color_green="\033[32m"
+color_yellow="\033[33m"
+color_red="\033[31m"
+color_cyan="\033[36m"
+color_reset="\033[0m"
+
+log_info() { echo -e "${color_cyan}[INFO]${color_reset} $1"; }
+log_ok() { echo -e "${color_green}[OK]${color_reset}   $1"; }
+log_warn() { echo -e "${color_yellow}[WARN]${color_reset} $1"; }
+log_err() { echo -e "${color_red}[ERR]${color_reset}  $1"; }
+
+# 1. 构建编译流程 (预编译 Tailwind CSS 与发布产物)
+do_build() {
+	log_info "正在编译 Tailwind CSS 并同步静态发布产物..."
+	mkdir -p "${DIST_DIR}"
+
+	# 宝塔 Node.js 版本管理器安装的 Node 不在默认 PATH 中，自动加入（取版本号最大者）
+	if ! command -v node >/dev/null 2>&1; then
+		for d in $(ls -d /www/server/nodejs/v*/bin 2>/dev/null | sort -V); do
+			[ -x "$d/node" ] && NODE_BIN="$d"
+		done
+		[ -n "${NODE_BIN:-}" ] && PATH="${NODE_BIN}:${PATH}"
+	fi
+
+	# 优先使用项目自带 standalone tailwindcss CLI，其次项目依赖中的 @tailwindcss/cli（不联网）
+	if [ -x "${PROJECT_ROOT}/bin/tailwindcss" ]; then
+		log_info "使用本地独立 Tailwind CLI 进行编译..."
+		"${PROJECT_ROOT}/bin/tailwindcss" -i "${SRC_DIR}/input.css" -o "${DIST_DIR}/tailwind.css" --minify
+	elif [ -x "${PROJECT_ROOT}/node_modules/.bin/tailwindcss" ] && command -v node >/dev/null 2>&1; then
+		log_info "使用项目依赖 @tailwindcss/cli（$(node -v)）编译..."
+		"${PROJECT_ROOT}/node_modules/.bin/tailwindcss" -i "${SRC_DIR}/input.css" -o "${DIST_DIR}/tailwind.css" --minify
+	elif command -v npx >/dev/null 2>&1; then
+		log_info "使用系统 npx @tailwindcss/cli 编译..."
+		npx @tailwindcss/cli -i "${SRC_DIR}/input.css" -o "${DIST_DIR}/tailwind.css" --minify
+	else
+		# 如果当前没有编译工具，但已有预编译的 tailwind.css 产物，直接复用
+		if [ -f "${DIST_DIR}/tailwind.css" ]; then
+			log_warn "未找到 Tailwind 编译器，复用旧的 tailwind.css（$(du -h "${DIST_DIR}/tailwind.css" | cut -f1)）：页面新增的样式类不会生效！"
+		else
+			log_err "缺少 Tailwind 编译器且无预编译产物！请在本地运行构建后同步产物。"
+			exit 1
+		fi
+	fi
+
+	# 同步 HTML 源码到发布目录
+	cp "${SRC_DIR}"/*.html "${DIST_DIR}/"
+	chown -R sub2api:sub2api "${DIST_DIR}" 2>/dev/null || true
+	log_ok "前端发布产物已就绪: ${DIST_DIR}/*.html 与 ${DIST_DIR}/tailwind.css"
+}
+
+# 2. 启动服务流程
+do_start() {
+	log_info "正在启动 StarNexus Relay Web 服务..."
+
+	# 检查产物
+	if [ ! -f "${DIST_DIR}/index.html" ] || [ ! -f "${DIST_DIR}/tailwind.css" ]; then
+		log_warn "未检测到静态编译产物，自动执行构建..."
+		do_build
+	fi
+
+	# 启动/重启 systemd 守护进程
+	if command -v systemctl >/dev/null 2>&1; then
+		log_info "启动后端微服务 (systemd: ${SYSTEMD_SERVICE})..."
+		systemctl restart "${SYSTEMD_SERVICE}"
+	else
+		log_info "直接运行后端微服务进程..."
+		pkill -f "${SERVER_DIR}/key_query.py" 2>/dev/null || true
+		nohup python3 -I "${SERVER_DIR}/key_query.py" >/dev/null 2>&1 &
+	fi
+
+	sleep 1
+
+	# 校验服务健康
+	if curl -s "http://127.0.0.1:${BACKEND_PORT}/health" | grep -q '"ok"'; then
+		log_ok "后端微服务已就绪 (127.0.0.1:${BACKEND_PORT})"
+	else
+		log_err "后端微服务响应异常，请检查: journalctl -u ${SYSTEMD_SERVICE} -n 20"
+		exit 1
+	fi
+
+	# 平滑重载 Nginx
+	if command -v nginx >/dev/null 2>&1; then
+		nginx -t >/dev/null 2>&1 && nginx -s reload >/dev/null 2>&1 || true
+		log_ok "Nginx 路由与静态服务已平滑刷新"
+	fi
+
+	echo ""
+	echo -e "${color_green}================================================================${color_reset}"
+	echo -e "${color_green}🎉 StarNexus Relay Web 已成功启动并运行！${color_reset}"
+	echo -e "  - 项目物理目录: ${color_cyan}${PROJECT_ROOT}${color_reset}"
+	echo -e "  - 前端静态产物: ${color_cyan}${DIST_DIR} (编译版 Tailwind CSS)${color_reset}"
+	echo -e "  - 后端微服务:   ${color_cyan}127.0.0.1:${BACKEND_PORT} (key_query.py)${color_reset}"
+	echo -e "  - 加速访问地址: ${color_yellow}https://apiacc.itssx.com/relay/key${color_reset}"
+	echo -e "  - 直连访问地址: ${color_yellow}https://api.itssx.com/relay/key${color_reset}"
+	echo -e "  - 宝塔独立预览: ${color_yellow}http://192.3.41.32:8088/${color_reset}"
+	echo -e "${color_green}================================================================${color_reset}"
+}
+
+# 3. 停止服务流程
+do_stop() {
+	log_info "正在停止 StarNexus Relay Web 服务..."
+	if command -v systemctl >/dev/null 2>&1; then
+		systemctl stop "${SYSTEMD_SERVICE}" 2>/dev/null || true
+	fi
+	pkill -f "${SERVER_DIR}/key_query.py" 2>/dev/null || true
+	log_ok "服务已停止"
+}
+
+# 4. 状态查询流程
+do_status() {
+	echo -e "${color_cyan}=== StarNexus Relay Web 状态检查 ===${color_reset}"
+	echo "项目路径: ${PROJECT_ROOT}"
+	echo "静态产物:"
+	ls -lh "${DIST_DIR}" 2>/dev/null || echo "无"
+
+	echo -e "\n后端微服务:"
+	if command -v systemctl >/dev/null 2>&1; then
+		systemctl status "${SYSTEMD_SERVICE}" --no-pager | head -n 10 || true
+	fi
+
+	echo -e "\n端口监听状态 (127.0.0.1:${BACKEND_PORT}):"
+	ss -tulpn | grep "${BACKEND_PORT}" || echo "未监听"
+
+	echo -e "\n健康检查响应:"
+	curl -s "http://127.0.0.1:${BACKEND_PORT}/health" && echo "" || echo "连接失败"
+}
+
+# 命令行参数路由
+case "${1:-start}" in
+start)
+	do_start
+	;;
+stop)
+	do_stop
+	;;
+restart)
+	do_stop
+	sleep 1
+	do_start
+	;;
+build)
+	do_build
+	;;
+status)
+	do_status
+	;;
+refund-user)
+	# 退款登记页账号管理：list | add <账号> | passwd <账号> | disable <账号> | enable <账号>
+	source /opt/sub2api/ops/lib.sh # 提供数据库管理员 PGPASSWORD
+	python3 -I "${SERVER_DIR}/refund_users.py" "${@:2}"
+	;;
+*)
+	echo "用法: $0 {start|stop|restart|build|status|refund-user}"
+	exit 1
+	;;
+esac
diff --git a/relay/server/key_query.py b/relay/server/key_query.py
new file mode 100644
index 0000000..fab2b62
--- /dev/null
+++ b/relay/server/key_query.py
@@ -0,0 +1,1405 @@
+"""StarNexus Relay：Key 查询与公共信息服务（只读，数据实时来自 sub2api 数据库）。监听 127.0.0.1:8092。
+
+分组信息全部动态生成，与 sub2api 保持一致：
+  - 名称、倍率、备注、状态、排序、专属/限制：groups 表（备注 = Nexus 公告摘要，随自动同步更新）
+  - 接入路径、排序、Nexus 标签、协议与模型：s2a_ops.group_meta / s2a_ops.nexus_tags
+    （宝塔任务 #8 每小时由 gen_auto_index.py 从 Nexus 与各分组账号白名单同步入库；页面只读数据库）
+  - 生图、仅 Claude Code、峰谷加价：groups / channel_model_pricing
+  - 用户维度：可用分组（专属分组、限制公开分组）、专属倍率（user_group_rate_multipliers）
+接口：GET /public-info；GET /key-query（Key 放在 Authorization: Bearer 或 x-api-key 头，兼容 ?key=）。
+数据库使用只读账号 relay_ro（凭据 /opt/sub2api/relay/server/.db.env），每 IP 每分钟最多 20 次 Key 查询。
+
+退款登记页 /relay/refund.html（独立账号登录，同一订单可多次退款；钱已在支付平台线下退回后补记）：
+  POST /refund/login、/refund/logout、/refund/password；GET /refund/me、/refund/orders、/refund/order?id=、/refund/request?id=<request_id>；
+  POST /refund/abandon {"request_id"}（结果未确认的登记：已写入返回结果，否则在服务器作废，之后同 ID 不可再写入）；
+  POST /refund/refund {"order_id", "cny", "reason", "request_id": UUID, "confirm": true}（同一 request_id 重试只登记一次）
+  余额缓存清除失败的登记/删除由后台线程每分钟重试（台账 cache_cleared_at 为空即待清）。
+  POST /refund/revoke {"ledger_id", "reason", "confirm": true}（删除一次登记：退回余额、扣减已退金额，台账留痕）
+  POST /refund/restore {"ledger_id", "confirm": true}（恢复已删除的登记：重新扣回余额、加回已退金额）
+  账号在服务器上用 `/opt/sub2api/relay/run refund-user ...` 管理；写库用最小权限账号 relay_refund（.refund_db.env）。
+"""
+
+import hashlib
+import hmac
+import json
+import os
+import re
+import secrets
+import socket
+import subprocess
+import threading
+import time
+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
+from urllib.parse import parse_qsl, urlparse
+
+PSQL = "/www/server/pgsql/bin/psql"
+OPS = "/opt/sub2api/ops"
+DB_ENV = "/opt/sub2api/relay/server/.db.env"
+KEY_RE = re.compile(r"^[A-Za-z0-9._\-]{8,128}$")
+HOSTS = {"acc": "https://apiacc.itssx.com", "direct": "https://api.itssx.com"}
+RECOMMENDED = {
+    "codex_eco",
+    "codex",
+    "mixed_cc_pro_max",
+    "kiro",
+    "deepseek",
+    "__unified__",
+}
+PLAT_PROTOCOLS = {
+    "anthropic": ["Claude"],
+    "openai": ["OpenAI Chat", "Codex"],
+    "gemini": ["Gemini"],
+}
+QUERY_LIMIT_PER_MIN = 20
+REFUND_DB_ENV = "/opt/sub2api/relay/server/.refund_db.env"
+REDIS_ADDR = ("127.0.0.1", 6379)  # 无密码，与 /opt/sub2api/config.yaml 一致
+REFUNDABLE = ("COMPLETED", "PARTIALLY_REFUNDED", "REFUND_REQUESTED", "REFUND_FAILED")
+
+
+def _db_env(path=DB_ENV, user="relay_ro"):
+    env = dict(os.environ)
+    try:
+        for line in open(path):
+            k, _, v = line.strip().partition("=")
+            if k in ("PGUSER", "PGPASSWORD"):
+                env[k] = v
+    except OSError:
+        pass
+    env.setdefault("PGUSER", user)
+    return env
+
+
+ENV = _db_env()
+REFUND_ENV = _db_env(REFUND_DB_ENV, "relay_refund")
+
+
+def psql_quote(value):
+    return str(value).replace("\\", "\\\\").replace("'", "\\'")
+
+
+def sql(query, _env=None, **params):
+    """参数经标准输入 \\set 传入（不进命令行），:'name' 由 psql 负责转义。_env 默认只读账号。"""
+    sets = "".join(f"\\set {k} '{psql_quote(v)}'\n" for k, v in params.items())
+    out = subprocess.run(
+        [
+            PSQL,
+            "-h",
+            "localhost",
+            "-d",
+            "sub2api",
+            "-qAt",
+            "-F",
+            "\t",
+            "-v",
+            "ON_ERROR_STOP=1",
+        ],
+        input=sets + query,
+        capture_output=True,
+        text=True,
+        env=_env or ENV,
+        timeout=10,
+        check=True,
+    ).stdout
+    return [line.split("\t") for line in out.splitlines() if line]
+
+
+_cache, _lock = {}, threading.Lock()
+
+
+def cached(key, ttl, loader):
+    now = time.time()
+    with _lock:
+        hit = _cache.get(key)
+        if hit and hit[0] > now:
+            return hit[1]
+    value = loader()
+    with _lock:
+        _cache[key] = (now + ttl, value)
+    return value
+
+
+def short(name):
+    return (name or "").split("(")[0].split("（")[0].strip()
+
+
+def mask_key(k):
+    return k[:4] + "***" + k[-2:] if len(k) <= 12 else k[:7] + "..." + k[-4:]
+
+
+# ---------------- 分组（与 sub2api 同步） ----------------
+def nexus_tags():
+    """Nexus 分组标签（后台每小时同步到 s2a_ops.nexus_tags）。"""
+    return [
+        {"id": int(r[0]), "name": r[1], "color": r[2] or "#6366f1"}
+        for r in sql(
+            "select id, name, color from s2a_ops.nexus_tags order by sort, id;"
+        )
+    ]
+
+
+def group_catalog():
+    """所有启用分组的静态信息（不含用户维度），全部读自数据库，缓存 60 秒。
+    groups：名称、倍率、备注、专属、生图、仅 Claude Code；s2a_ops.group_meta：路径、排序、Nexus 标签、协议与模型
+    （由宝塔任务 #8 每小时从 Nexus 与账号白名单同步）；channel_model_pricing：峰谷加价。"""
+    tags = {t["id"]: t for t in nexus_tags()}
+    peak = {
+        int(r[0]): json.loads(r[1])
+        for r in sql(
+            """select distinct on (cg.group_id) cg.group_id, mp.time_pricing::text
+           from channel_model_pricing mp join channel_groups cg on cg.channel_id = mp.channel_id
+           where mp.time_pricing is not null;"""
+        )
+    }
+    rows = sql("""select g.id, g.name, g.rate_multiplier, g.is_exclusive, coalesce(g.description, ''), g.claude_code_only,
+                         g.allow_image_generation, m.slug, m.route_path, m.tags::text, m.protocols::text, m.is_unified
+                  from groups g join s2a_ops.group_meta m on m.group_id = g.id
+                  where g.deleted_at is null and g.status = 'active' and coalesce(g.subscription_type, 'standard') = 'standard'
+                  order by m.sort, g.id;""")
+    out = []
+    for (
+        gid,
+        name,
+        rate,
+        excl,
+        desc,
+        cc_only,
+        img,
+        slug,
+        path,
+        tag_ids,
+        protos,
+        unified,
+    ) in rows:
+        gid, unified = int(gid), unified == "t"
+        protos = json.loads(protos or "{}")
+        protocols = []
+        for plat in ("anthropic", "openai", "gemini"):
+            if plat in protos:
+                protocols += PLAT_PROTOCOLS[plat]
+        if img == "t" and "openai" in protos:
+            protocols.append("生图")
+        if cc_only == "t":
+            protocols = ["Claude"]
+        models = {
+            p: sorted(set(v.get("native", []) + v.get("alias", [])))
+            for p, v in protos.items()
+        }
+        notes = []
+        if unified:
+            notes.append(
+                "按请求的模型自动匹配可用分组（原生模型优先，失败自动换下一个），按命中分组的倍率扣费"
+            )
+        elif desc:
+            notes.append(desc)
+        if gid in peak:
+            pk = peak[gid]
+            spans = "、".join(
+                f"{x['start_time']}–{x['end_time']}" for x in pk.get("periods", [])
+            )
+            mult = pk.get("periods", [{}])[0].get("multiplier", "")
+            notes.append(
+                f"高峰时段（北京 {spans}{'，仅工作日' if pk.get('weekdays_only') else ''}）价格 ×{mult}"
+            )
+        if cc_only == "t":
+            notes.append("仅支持 Claude Code 客户端")
+        out.append(
+            {
+                "id": gid,
+                "slug": slug,
+                "name": short(name),
+                "display_name": short(name),
+                "raw_name": name,
+                "tags": [tags[t] for t in json.loads(tag_ids or "[]") if t in tags],
+                "rate_multiplier": float(rate),
+                "is_unified": unified,
+                "is_exclusive": excl == "t",
+                "claude_code_only": cc_only == "t",
+                "allow_image": img == "t",
+                "protocols": protocols or ["OpenAI Chat"],
+                "models": models,
+                "model_count": len({m for ms in models.values() for m in ms}),
+                "notice": "；".join(notes),
+                "is_recommended": slug in RECOMMENDED or unified,
+                "path": path or "",
+                "base_url_acc": f"{HOSTS['acc']}{path or ''}",
+                "base_url_direct": f"{HOSTS['direct']}{path or ''}",
+                "v1_url_acc": f"{HOSTS['acc']}{path or ''}/v1",
+                "v1_url_direct": f"{HOSTS['direct']}{path or ''}/v1",
+                "claude_export": f"export ANTHROPIC_BASE_URL={HOSTS['acc']}{path or ''}",
+            }
+        )
+    return out
+
+
+def groups_for_user(uid=None):
+    groups = [dict(g) for g in cached("catalog", 60, group_catalog)]
+    if uid is None:
+        for g in groups:
+            g["can_access"] = not g["is_exclusive"]
+        return groups
+    restrict = sql("select restrict_public_groups from users where id = :'u';", u=uid)
+    restrict = bool(restrict) and restrict[0][0] == "t"
+    allowed = {
+        int(r[0])
+        for r in sql(
+            "select group_id from user_allowed_groups where user_id = :'u';", u=uid
+        )
+    }
+    rates = {
+        int(r[0]): float(r[1])
+        for r in sql(
+            "select group_id, rate_multiplier from user_group_rate_multipliers where user_id = :'u';",
+            u=uid,
+        )
+    }
+    for g in groups:
+        # 与 sub2api User.CanBindGroup 一致：专属分组、或用户开启「限制公开分组」时须在授权列表中
+        g["can_access"] = (
+            (not g["is_exclusive"] and not restrict)
+            or g["id"] in allowed
+            or g["is_unified"]
+        )
+        if g["id"] in rates:
+            g["user_rate_multiplier"] = rates[g["id"]]
+    return groups
+
+
+def announcements():
+    rows = sql("""select coalesce(json_agg(t)::text, '[]') from (
+                    select id, title, content,
+                           to_char(created_at at time zone 'Asia/Shanghai', 'YYYY-MM-DD') as created_at
+                    from announcements
+                    where status = 'active'
+                      and (starts_at is null or starts_at <= now()) and (ends_at is null or ends_at > now())
+                      and coalesce(targeting, '{}'::jsonb) = '{}'::jsonb  -- 定向公告只给指定用户，不在公共页展示
+                    order by id desc limit 3) t;""")
+    try:
+        return json.loads(rows[0][0]) if rows else []
+    except ValueError:
+        return []
+
+
+# ---------------- Key 查询 ----------------
+def query_key_data(api_key):
+    rows = sql(
+        """select k.id, k.user_id, k.name, k.status, k.quota, k.quota_used,
+                         to_char(k.expires_at at time zone 'Asia/Shanghai', 'YYYY-MM-DD HH24:MI'),
+                         to_char(k.created_at at time zone 'Asia/Shanghai', 'YYYY-MM-DD HH24:MI'),
+                         to_char(k.last_used_at at time zone 'Asia/Shanghai', 'YYYY-MM-DD HH24:MI:SS'),
+                         k.rate_limit_5h, k.rate_limit_1d, k.rate_limit_7d,
+                         coalesce(k.ip_whitelist::text, '[]'), coalesce(k.ip_blacklist::text, '[]'),
+                         u.balance, u.status, u.total_recharged, (k.expires_at is not null and k.expires_at <= now()),
+                         coalesce(g.name, ''), k.group_id
+                  from api_keys k join users u on u.id = k.user_id left join groups g on g.id = k.group_id
+                  where k.key = :'k' and k.deleted_at is null
+                    and not exists (select 1 from s2a_ops.route_keys r where r.mapped_id = k.id);""",
+        k=api_key,
+    )
+    if not rows:
+        if sql(
+            "select 1 from api_keys k join s2a_ops.route_keys r on r.mapped_id = k.id where k.key = :'k';",
+            k=api_key,
+        ):
+            return {"error": "这是系统自动生成的路由子 Key，请查询您创建的主 Key"}
+        return {"error": "API Key 不存在或已删除，请核对后再试"}
+    (
+        kid,
+        uid,
+        name,
+        kstatus,
+        quota,
+        quota_used,
+        expires,
+        created,
+        last_used,
+        rl5,
+        rl1,
+        rl7,
+        ipw,
+        ipb,
+        balance,
+        ustatus,
+        recharged,
+        expired,
+        key_group,
+        key_gid,
+    ) = rows[0]
+    kid, uid, quota = int(kid), int(uid), float(quota)
+
+    # 原 Key + 全部路由子 Key 合计
+    fam = """with fam as (select :'m'::bigint as id union select mapped_id from s2a_ops.route_keys where parent_id = :'m')"""
+    agg = sql(
+        fam
+        + """
+        select (select coalesce(sum(quota_used), 0) from api_keys where id in (select id from fam)),
+               coalesce(sum(actual_cost) filter (where created_at > now() - interval '5 hours'), 0),
+               coalesce(sum(actual_cost) filter (where created_at > now() - interval '1 day'), 0),
+               coalesce(sum(actual_cost), 0),
+               count(*) filter (where created_at > now() - interval '1 day'), count(*)
+        from usage_logs where api_key_id in (select id from fam) and created_at > now() - interval '7 days';""",
+        m=kid,
+    )[0]
+    # 最近使用：主 Key 自身或任一路由子 Key 的最近一次调用
+    lu = sql(
+        fam
+        + """select to_char(max(created_at) at time zone 'Asia/Shanghai', 'YYYY-MM-DD HH24:MI:SS')
+                      from usage_logs where api_key_id in (select id from fam);""",
+        m=kid,
+    )
+    if lu and lu[0] and lu[0][0] and (not last_used or lu[0][0] > last_used):
+        last_used = lu[0][0]
+    # 账户累计消费（该用户全部 Key）
+    user_used = float(
+        sql(
+            "select coalesce(sum(actual_cost), 0) from usage_logs where user_id = :'u';",
+            u=uid,
+        )[0][0]
+    )
+    total_used, u5, u1, u7, req24, req7 = (
+        float(agg[0]),
+        float(agg[1]),
+        float(agg[2]),
+        float(agg[3]),
+        int(agg[4]),
+        int(agg[5]),
+    )
+
+    by_group = [
+        {
+            "group": short(r[0]) or "未知",
+            "requests": int(r[1]),
+            "tokens": int(r[2]),
+            "cost": float(r[3]),
+        }
+        for r in sql(
+            fam
+            + """
+        select g.name, count(*), coalesce(sum(l.input_tokens + l.output_tokens + l.cache_read_tokens + l.cache_creation_tokens), 0),
+               coalesce(sum(l.actual_cost), 0)
+        from usage_logs l left join groups g on g.id = l.group_id
+        where l.api_key_id in (select id from fam) and l.created_at > now() - interval '7 days'
+        group by g.name order by 4 desc;""",
+            m=kid,
+        )
+    ]
+    by_model = [
+        {"model": r[0], "requests": int(r[1]), "tokens": int(r[2]), "cost": float(r[3])}
+        for r in sql(
+            fam
+            + """
+        select coalesce(nullif(l.requested_model, ''), l.model), count(*),
+               coalesce(sum(l.input_tokens + l.output_tokens + l.cache_read_tokens + l.cache_creation_tokens), 0),
+               coalesce(sum(l.actual_cost), 0)
+        from usage_logs l where l.api_key_id in (select id from fam) and l.created_at > now() - interval '7 days'
+        group by 1 order by 4 desc limit 20;""",
+            m=kid,
+        )
+    ]
+    daily = [
+        {"date": r[0], "requests": int(r[1]), "cost": float(r[2])}
+        for r in sql(
+            fam
+            + """
+        select to_char(d, 'MM-DD'), count(l.id), coalesce(sum(l.actual_cost), 0)
+        from generate_series((now() at time zone 'Asia/Shanghai')::date - 6, (now() at time zone 'Asia/Shanghai')::date, interval '1 day') d
+        left join usage_logs l on l.api_key_id in (select id from fam)
+             and (l.created_at at time zone 'Asia/Shanghai')::date = d::date
+        group by d order by d;""",
+            m=kid,
+        )
+    ]
+    recent = [
+        {
+            "time": r[0],
+            "group": short(r[1]) or "未知",
+            "model": r[2],
+            "tokens": int(r[3] or 0),
+            "cost": float(r[4] or 0),
+            "duration_ms": int(r[5] or 0),
+            "stream": r[6] == "t",
+        }
+        for r in sql(
+            fam
+            + """
+        select to_char(l.created_at at time zone 'Asia/Shanghai', 'MM-DD HH24:MI:SS'), g.name,
+               coalesce(nullif(l.requested_model, ''), l.model),
+               l.input_tokens + l.output_tokens + l.cache_read_tokens + l.cache_creation_tokens,
+               l.actual_cost, l.duration_ms, l.stream
+        from usage_logs l left join groups g on g.id = l.group_id
+        where l.api_key_id in (select id from fam) order by l.created_at desc limit 20;""",
+            m=kid,
+        )
+    ]
+
+    if kstatus == "quota_exhausted" or (quota > 0 and total_used >= quota):
+        status, text = "quota_exhausted", "额度已用完"
+    elif kstatus != "active":
+        status, text = "disabled", "已停用"
+    elif ustatus != "active":
+        status, text = "user_disabled", "账户已停用"
+    elif expired == "t":
+        status, text = "expired", "已过期"
+    elif float(balance) <= 0:
+        status, text = "no_balance", "余额不足"
+    else:
+        status, text = "active", "正常使用中"
+    return {
+        "key_info": {
+            "id": kid,
+            "name": name or "未命名 Key",
+            "masked_key": mask_key(api_key),
+            "status": status,
+            "status_text": text,
+            "created_at": created,
+            "expires_at": expires or None,
+            "last_used_at": last_used or None,
+            "default_group": short(key_group),
+            "ip_whitelist": json.loads(ipw or "[]"),
+            "ip_blacklist": json.loads(ipb or "[]"),
+        },
+        "balance_info": {
+            "user_balance": round(float(balance), 4),
+            "total_recharged": round(float(recharged or 0), 2),
+            "user_used": round(user_used, 4),
+            "quota": round(quota, 4) if quota > 0 else None,
+            "quota_used": round(total_used, 4),
+            "quota_remain": round(max(0.0, quota - total_used), 4)
+            if quota > 0
+            else None,
+            "has_quota_limit": quota > 0,
+        },
+        "rate_limits": {
+            "limit_5h": float(rl5),
+            "used_5h": round(u5, 4),
+            "limit_1d": float(rl1),
+            "used_1d": round(u1, 4),
+            "limit_7d": float(rl7),
+            "used_7d": round(u7, 4),
+            "requests_24h": req24,
+            "requests_7d": req7,
+        },
+        "usage_by_group": by_group,
+        "usage_by_model": by_model,
+        "daily": daily,
+        "recent_logs": recent,
+        "groups": groups_for_user(uid),
+    }
+
+
+# ---------------- 退款登记（独立账号登录，支持同一订单多次退款） ----------------
+# 账号：s2a_ops.refund_users（scrypt 加盐哈希；服务器上 `run refund-user` 管理）；
+# 会话：随机 token，库里只存 sha256（s2a_ops.refund_sessions），12 小时，HttpOnly+Secure+SameSite=Strict Cookie；
+# 防暴力：每 IP 每分钟 10 次登录，同一账号连续 5 次失败锁 15 分钟；写操作另需 X-Requested-With 头（防跨站）。
+# 台账：s2a_ops.manual_refunds 每次退款一行；订单 refund_amount 累加，累计达到到账额即 REFUNDED，否则 PARTIALLY_REFUNDED；
+# sub2api 审计表 (order_id, action) 唯一，故每次退款 action = MANUAL_REFUND_<台账 id>。
+SESSION_COOKIE = "s2a_refund"
+SESSION_HOURS = 12
+LOGIN_LIMIT_PER_MIN = 10
+LOCK_AFTER, LOCK_MINUTES = 5, 15
+PW_MIN = 10
+CSRF_HEADER = ("X-Requested-With", "s2a-refund")
+RID_RE = r"[0-9a-f]{8}(-[0-9a-f]{4}){3}-[0-9a-f]{12}"  # request_id（UUID）
+ORDER_STATUSES = (
+    "PENDING", "PAID", "RECHARGING", "COMPLETED", "CANCELLED", "FAILED", "EXPIRED",
+    "REFUND_REQUESTED", "REFUNDING", "REFUND_PENDING", "PARTIALLY_REFUNDED", "REFUNDED", "REFUND_FAILED",
+)  # fmt: skip
+
+
+def hash_password(pw, salt=None):
+    salt = salt or os.urandom(16)
+    dk = hashlib.scrypt(pw.encode(), salt=salt, n=2**14, r=8, p=1, dklen=32)
+    return f"scrypt$16384$8$1${salt.hex()}${dk.hex()}"
+
+
+def verify_password(pw, stored):
+    try:
+        _, n, r, p, salt, dk = stored.split("$")
+        got = hashlib.scrypt(
+            pw.encode(),
+            salt=bytes.fromhex(salt),
+            n=int(n),
+            r=int(r),
+            p=int(p),
+            dklen=32,
+        )
+        return hmac.compare_digest(got.hex(), dk)
+    except (ValueError, TypeError):
+        return False
+
+
+_DUMMY_HASH = hash_password(secrets.token_hex(8))
+
+
+def rsql(query, **params):
+    return sql(query, _env=REFUND_ENV, **params)
+
+
+def session_user(token):
+    if not token or len(token) > 200:
+        return None
+    rows = rsql(
+        """select u.id, u.username, u.must_change from s2a_ops.refund_sessions s
+           join s2a_ops.refund_users u on u.id = s.user_id
+           where s.token_hash = :'h' and s.expires_at > now() and u.enabled;""",
+        h=hashlib.sha256(token.encode()).hexdigest(),
+    )
+    if not rows:
+        return None
+    return {
+        "id": int(rows[0][0]),
+        "username": rows[0][1],
+        "must_change": rows[0][2] == "t",
+        "token_hash": hashlib.sha256(token.encode()).hexdigest(),
+    }
+
+
+def login(username, password, ip, ua):
+    """返回 (状态码, 结果, token)。不区分「账号不存在」与「密码错误」。"""
+    username = (username or "").strip()[:64]
+    rows = rsql(
+        """select id, pw_hash, enabled, coalesce(locked_until > now(), false),
+                  ceil(extract(epoch from (locked_until - now())) / 60)
+           from s2a_ops.refund_users where username = :'u';""",
+        u=username,
+    )
+    if not rows:
+        verify_password(
+            password or "", _DUMMY_HASH
+        )  # 时间开销一致，避免探测账号是否存在
+        return 401, {"message": "账号或密码错误"}, None
+    uid, pw_hash, enabled, locked, mins = rows[0]
+    if locked == "t":
+        return (
+            423,
+            {"message": f"连续输错次数过多，账号已锁定，请 {mins or 1} 分钟后再试"},
+            None,
+        )
+    if enabled != "t" or not verify_password(password or "", pw_hash):
+        rsql(
+            f"""update s2a_ops.refund_users set
+                  locked_until = case when failed + 1 >= {LOCK_AFTER} then now() + interval '{LOCK_MINUTES} minutes'
+                                      else locked_until end,
+                  failed = case when failed + 1 >= {LOCK_AFTER} then 0 else failed + 1 end
+               where id = :'id'::int;""",
+            id=uid,
+        )
+        return 401, {"message": "账号或密码错误"}, None
+    token = secrets.token_urlsafe(32)
+    rows = rsql(
+        f"""delete from s2a_ops.refund_sessions where expires_at < now();
+            update s2a_ops.refund_users set failed = 0, locked_until = null, last_login_at = now() where id = :'id'::int;
+            insert into s2a_ops.refund_sessions(token_hash, user_id, expires_at, ip, ua)
+            values (:'h', :'id'::int, now() + interval '{SESSION_HOURS} hours', :'ip', :'ua');
+            select must_change from s2a_ops.refund_users where id = :'id'::int;""",
+        id=uid,
+        h=hashlib.sha256(token.encode()).hexdigest(),
+        ip=ip[:64],
+        ua=ua[:256],
+    )
+    return (
+        200,
+        {"username": username, "must_change": bool(rows) and rows[-1][0] == "t"},
+        token,
+    )
+
+
+def change_password(user, old, new):
+    rows = rsql(
+        "select pw_hash from s2a_ops.refund_users where id = :'id'::int;", id=user["id"]
+    )
+    if not rows or not verify_password(old or "", rows[0][0]):
+        raise ValueError("原密码不正确")
+    if len(new or "") < PW_MIN:
+        raise ValueError(f"新密码至少 {PW_MIN} 位")
+    if new == old:
+        raise ValueError("新密码不能与原密码相同")
+    rsql(
+        """update s2a_ops.refund_users set pw_hash = :'ph', must_change = false where id = :'id'::int;
+           delete from s2a_ops.refund_sessions where user_id = :'id'::int and token_hash <> :'h';""",
+        ph=hash_password(new),
+        id=user["id"],
+        h=user["token_hash"],
+    )
+
+
+# 已退人民币：台账合计 + 台账以外（sub2api 原生退款）按 实付 × 退回$ / 到账$ 折算
+REFUNDED_CNY = """(coalesce(m.cny, 0) + case when o.amount > 0 and o.refund_amount > coalesce(m.usd, 0)
+                     then round(o.pay_amount * (o.refund_amount - coalesce(m.usd, 0)) / o.amount, 2) else 0 end)"""
+ORDER_FROM = """from payment_orders o
+     left join users u on u.id = o.user_id
+     left join (select order_id, sum(cny) cny, sum(usd) usd, count(*) n from s2a_ops.manual_refunds
+           where deleted_at is null group by order_id) m
+       on m.order_id = o.id"""
+
+
+def list_orders(args):
+    page = max(1, min(int(args.get("page") or 1), 10000))
+    size = int(args.get("size") or 20)
+    size = size if size in (20, 50, 100) else 20
+    where, params = ["true"], {}
+    q = (args.get("q") or "").strip()[:100]
+    if q:
+        params["q"] = q
+        params["ql"] = (
+            "%" + q.replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_") + "%"
+        )
+        cond = "o.user_email ilike :'ql' or u.email ilike :'ql' or o.out_trade_no ilike :'ql' or o.payment_trade_no ilike :'ql'"
+        if q.isdigit() and len(q) <= 18:
+            cond = "o.id = :'q'::bigint or o.user_id = :'q'::bigint or " + cond
+        where.append(f"({cond})")
+    status = [s for s in (args.get("status") or "").split(",") if s in ORDER_STATUSES]
+    if status:
+        where.append("o.status in (" + ",".join(f"'{s}'" for s in status) + ")")
+    if args.get("pay") in ("wxpay", "alipay"):
+        params["pay"] = args["pay"]
+        where.append("o.payment_type = :'pay'")
+    for k, op in (("from", ">="), ("to", "<")):
+        v = args.get(k) or ""
+        if re.fullmatch(r"\d{4}-\d{2}-\d{2}", v):
+            params[k] = v
+            day = f":'{k}'::date" + (" + 1" if k == "to" else "")
+            where.append(
+                f"o.created_at {op} ({day})::timestamp at time zone 'Asia/Shanghai'"
+            )
+    if args.get("refunded") == "1":
+        where.append("(o.refund_amount > 0 or m.n > 0)")
+    elif args.get("refunded") == "0":
+        where.append("o.refund_amount = 0 and m.n is null")
+    w = " and ".join(where)
+    rows = rsql(
+        f"""select count(*), coalesce(sum(o.pay_amount) filter (where o.paid_at is not null), 0),
+                   coalesce(sum({REFUNDED_CNY}), 0)
+            {ORDER_FROM} where {w};
+            select row_to_json(t) from (
+              select o.id, o.user_id, coalesce(u.email, o.user_email) email, o.order_type, o.status, o.payment_type,
+                     o.pay_amount, o.amount, o.bonus_amount, o.refund_amount, {REFUNDED_CNY} refunded_cny,
+                     coalesce(m.n, 0) refund_count, o.created_at, o.paid_at, o.out_trade_no, o.payment_trade_no
+              {ORDER_FROM} where {w} order by o.id desc limit {size} offset {(page - 1) * size}) t;""",
+        **params,
+    )
+    total, paid_sum, refunded_sum = rows[0]
+    items = [json.loads(r[0]) for r in rows[1:]]
+    for it in items:
+        for k in (
+            "pay_amount",
+            "amount",
+            "bonus_amount",
+            "refund_amount",
+            "refunded_cny",
+        ):
+            it[k] = float(it[k] or 0)
+    return {
+        "total": int(total),
+        "page": page,
+        "size": size,
+        "items": items,
+        "paid_sum": float(paid_sum),
+        "refunded_sum": float(refunded_sum),
+    }
+
+
+def order_detail(oid):
+    rows = rsql(
+        f"""select row_to_json(t) from (
+              select o.id, o.user_id, coalesce(u.email, o.user_email) email, o.order_type, o.status, o.payment_type,
+                     o.pay_amount, o.amount, o.bonus_amount, o.refund_amount, {REFUNDED_CNY} refunded_cny,
+                     o.created_at, o.paid_at, o.out_trade_no, o.payment_trade_no, u.balance
+              {ORDER_FROM} where o.id = :'oid'::bigint) t;
+            select row_to_json(r) from (select id, cny, usd, deducted, status_before, status_after, reason, operator, created_at,
+                     deleted_at, deleted_by, delete_reason, restored_at, restored_by
+              from s2a_ops.manual_refunds where order_id = :'oid'::bigint order by id) r;""",
+        oid=oid,
+    )
+    if not rows:
+        return None
+    o = json.loads(rows[0][0])
+    for k in (
+        "pay_amount",
+        "amount",
+        "bonus_amount",
+        "refund_amount",
+        "refunded_cny",
+        "balance",
+    ):
+        o[k] = float(o.get(k) or 0)
+    o["history"] = [json.loads(r[0]) for r in rows[1:]]
+    o["remaining_usd"] = round(max(o["amount"] - o["refund_amount"], 0), 2)
+    o["remaining_cny"] = round(max(o["pay_amount"] - o["refunded_cny"], 0), 2)
+    why = None
+    if o["order_type"] != "balance":
+        why = "不是余额充值订单"
+    elif o["status"] not in REFUNDABLE:
+        why = f"订单状态 {o['status']} 不能退款"
+    elif o["pay_amount"] <= 0 or o["amount"] <= 0:
+        why = "订单金额异常"
+    elif o["remaining_usd"] <= 0 or o["remaining_cny"] <= 0:
+        why = "已全额退款"
+    o["refundable"], o["not_refundable_reason"] = why is None, why
+    return o
+
+
+def refund_plan(o, cny):
+    """人民币 → 扣回美元：按订单 实付¥/到账$ 折算；退完剩余人民币时扣回全部剩余到账（含赠送）。"""
+    cny = round(cny, 2)
+    if not (cny > 0) or cny - o["remaining_cny"] > 0.005:
+        raise ValueError(f"退款金额需大于 0 且不超过剩余可退 ¥{o['remaining_cny']:.2f}")
+    usd = round(cny * o["amount"] / o["pay_amount"], 2)
+    if abs(cny - o["remaining_cny"]) <= 0.005:
+        usd = o["remaining_usd"]
+    usd = min(usd, o["remaining_usd"])
+    if usd <= 0:
+        raise ValueError("折算后扣回金额为 0，请提高退款金额")
+    total = o["refund_amount"] + usd
+    return {
+        "cny": cny,
+        "usd": usd,
+        "deduct": round(min(usd, max(o["balance"], 0)), 8),
+        "status": "REFUNDED" if total >= o["amount"] - 0.005 else "PARTIALLY_REFUNDED",
+    }
+
+
+def clear_balance_cache(uid):
+    """删 sub2api 余额缓存。服务以 sub2api 用户运行，无权执行宝塔 redis-cli（redis:redis 700），
+    故直接发 RESP DEL；只有返回删除个数 :0/:1 才算成功，连不上、鉴权失败、超时都算失败。"""
+    key = f"billing:balance:{int(uid)}".encode()
+    cmd = b"*2\r\n$3\r\nDEL\r\n$%d\r\n%s\r\n" % (len(key), key)
+    try:
+        with socket.create_connection(REDIS_ADDR, timeout=3) as s:
+            s.sendall(cmd)
+            reply = s.recv(64)
+    except OSError:
+        return False
+    return reply in (b":0\r\n", b":1\r\n")
+
+
+def settle_cache(lid, uid):
+    """登记/删除提交后清余额缓存：成功则记 cache_cleared_at；失败保持为空，由 cache_retry_loop 自动重试。"""
+    if not clear_balance_cache(uid):
+        print(f"余额缓存清除失败 用户#{uid} 台账#{lid}，后台将自动重试", flush=True)
+        return False
+    try:
+        rsql(
+            "update s2a_ops.manual_refunds set cache_cleared_at = now() where id = :'lid'::bigint;",
+            lid=lid,
+        )
+    except Exception:
+        pass  # 缓存已删，标记写失败只会让后台多删一次
+    return True
+
+
+def cache_retry_loop():
+    while True:
+        time.sleep(60)
+        try:
+            rows = rsql(
+                """select id, user_id from s2a_ops.manual_refunds where cache_cleared_at is null
+                   order by id limit 50;"""
+            )
+            for lid, uid in rows:
+                if settle_cache(lid, uid):
+                    print(f"余额缓存补清成功 用户#{uid} 台账#{lid}", flush=True)
+        except Exception as e:
+            print(f"余额缓存补清异常: {type(e).__name__}", flush=True)
+
+
+def find_request(rid):
+    rows = rsql(
+        """select row_to_json(t) from (select id, order_id, cny, usd, deducted, balance_before, status_after,
+                  deleted_at, cache_cleared_at from s2a_ops.manual_refunds where request_id = :'rid'::uuid) t;""",
+        rid=rid,
+    )
+    return json.loads(rows[0][0]) if rows else None
+
+
+def replay_refund(prev, oid, cny):
+    """同一 request_id 重试：返回首次结果，不再写库。"""
+    if int(prev["order_id"]) != oid or abs(float(prev["cny"]) - round(cny, 2)) > 0.005:
+        raise ValueError("请求标识与原登记不一致，请关闭后重新打开订单再登记")
+    if prev["deleted_at"]:
+        raise ValueError("这次登记此前已成功，但已被删除；如需再退请关闭后重新登记")
+    return {
+        "cny": float(prev["cny"]),
+        "usd": float(prev["usd"]),
+        "status": prev["status_after"],
+        "deducted": float(prev["deducted"]),
+        "balance_before": float(prev["balance_before"]),
+        "ledger_id": int(prev["id"]),
+        "cache_cleared": prev["cache_cleared_at"] is not None,
+        "duplicate": True,
+    }
+
+
+ABANDONED_MSG = "这次登记已作废（确认未写入），请关闭后重新打开订单再登记"
+
+
+def request_state(rid):
+    rows = rsql(
+        "select state from s2a_ops.refund_requests where request_id = :'rid'::uuid;",
+        rid=rid,
+    )
+    return rows[0][0] if rows else None
+
+
+def abandon_request(user, rid):
+    """作废结果未确认的登记：已写入则返回首次结果；未写入则原子记 abandoned，之后同 ID 的写入撞主键失败。
+    在途的同 ID 写入会先持有该主键，本语句等它结束后再判断，不依赖超时推断。"""
+    rows = rsql(
+        """insert into s2a_ops.refund_requests(request_id, state, operator)
+           values (:'rid'::uuid, 'abandoned', :'op') on conflict (request_id) do nothing;
+           select state from s2a_ops.refund_requests where request_id = :'rid'::uuid;""",
+        rid=rid,
+        op=f"relay:{user['username']}",
+    )
+    return rows[-1][0] if rows else None
+
+
+def request_result(rid, state=None):
+    prev = find_request(rid)
+    data = {"found": prev is not None, "abandoned": state == "abandoned"}
+    if prev:
+        data.update(
+            order_id=int(prev["order_id"]),
+            ledger_id=int(prev["id"]),
+            cny=float(prev["cny"]),
+            deducted=float(prev["deducted"]),
+            status=prev["status_after"],
+            deleted=prev["deleted_at"] is not None,
+        )
+    return data
+
+
+def execute_refund(user, oid, cny, reason, rid):
+    # request_id：页面每次登记操作生成一个 UUID，网络失败重试时沿用；台账唯一约束保证同一操作只登记一次
+    # s2a_ops.refund_requests 以 request_id 为主键：登记写 done、作废写 abandoned，同一 ID 只能有一种结果
+    prev = find_request(rid)
+    if prev:
+        return replay_refund(prev, oid, cny)
+    if request_state(rid) == "abandoned":
+        raise ValueError(ABANDONED_MSG)
+    o = order_detail(oid)
+    if not o:
+        raise ValueError("订单不存在")
+    if not o["refundable"]:
+        raise ValueError(o["not_refundable_reason"])
+    p = refund_plan(o, cny)
+    # 单条语句（数据修改 CTE）原子完成：锁订单并复核剩余额度 → 扣余额（最多到 0）→ 写台账 → 改订单 → 写审计；
+    # 订单状态或已退金额在此期间变化则什么都不写
+    try:
+        rows = _insert_refund(user, oid, o, p, reason, rid)
+    except Exception:
+        # 并发的同一请求、已被作废（主键冲突）或执行超时：已写入则按首次结果返回
+        prev = find_request(rid)
+        if prev:
+            return replay_refund(prev, oid, cny)
+        if request_state(rid) == "abandoned":
+            raise ValueError(ABANDONED_MSG)
+        raise
+    if not rows or rows[0][3] != "1":
+        prev = find_request(rid)
+        if prev:
+            return replay_refund(prev, oid, cny)
+        raise ValueError("订单在此期间已变化，未写入任何数据，请刷新后重试")
+    lid = int(rows[0][2])
+    cache_ok = settle_cache(lid, o["user_id"])
+    print(
+        f"退款登记 {user['username']} 订单#{oid} ¥{p['cny']} → 扣回 ${rows[0][1]}（{p['status']}，台账#{lid}）",
+        flush=True,
+    )
+    return {
+        **p,
+        "deducted": float(rows[0][1]),
+        "balance_before": float(rows[0][0]),
+        "ledger_id": lid,
+        "cache_cleared": cache_ok,
+    }
+
+
+def _insert_refund(user, oid, o, p, reason, rid):
+    return rsql(
+        f"""with chk as (select id, status, refund_amount, amount from payment_orders
+                         where id = :'oid'::bigint and order_type = 'balance' and status in {REFUNDABLE}
+                           and refund_amount = :'ra'::numeric and refund_amount + :'usd'::numeric <= amount + 0.005
+                         for update),
+           target as (select u.id, u.balance from users u, chk where u.id = :'uid'::bigint and u.deleted_at is null
+                      for update of u),
+           upd as (update users u set balance = target.balance - least(:'usd'::numeric, greatest(target.balance, 0)),
+                          updated_at = now()
+                   from target where u.id = target.id
+                   returning target.balance as before, target.balance - u.balance as deducted),
+           led as (insert into s2a_ops.manual_refunds(order_id, user_id, cny, usd, deducted, balance_before,
+                                                      status_before, status_after, reason, operator, request_id)
+                   select chk.id, :'uid'::bigint, :'cny'::numeric, :'usd'::numeric, upd.deducted, upd.before,
+                          chk.status, :'st', :'reason', :'op', :'rid'::uuid
+                   from chk, upd returning id),
+           claim as (insert into s2a_ops.refund_requests(request_id, state, operator)
+                     select :'rid'::uuid, 'done', :'op' from chk, upd returning 1),
+           ord as (update payment_orders po set status = :'st', refund_amount = chk.refund_amount + :'usd'::numeric,
+                          refund_reason = :'reason', refund_at = now(), force_refund = false, updated_at = now()
+                   from chk, upd where po.id = chk.id returning po.id),
+           ins as (insert into payment_audit_logs(order_id, action, detail, operator)
+                   select :'oid', 'MANUAL_REFUND_' || led.id,
+                          json_build_object('refundAmount', :'usd'::numeric, 'reason', :'reason',
+                                            'balanceDeducted', upd.deducted, 'balanceBefore', upd.before,
+                                            'statusBefore', chk.status, 'statusAfter', :'st', 'force', false,
+                                            'manual', true, 'gatewayRefundCny', :'cny'::numeric,
+                                            'gateway', 'offline', 'ledgerId', led.id, 'via', 'relay')::text,
+                          :'op'
+                   from chk, upd, led, ord returning 1)
+           select upd.before, upd.deducted, (select id from led), (select count(*) from ins) from upd;""",
+        oid=oid,
+        uid=o["user_id"],
+        ra=o["refund_amount"],
+        usd=p["usd"],
+        st=p["status"],
+        reason=reason,
+        cny=p["cny"],
+        op=f"relay:{user['username']}",
+        rid=rid,
+    )
+
+
+def revoke_refund(user, lid, reason):
+    """删除（撤销）一次退款登记：退回当次实际扣回的余额，订单已退金额减去当次 $ 并重算状态（减到 0 恢复为
+    COMPLETED），台账行标记删除（保留记录），写审计 MANUAL_REFUND_<id>_REVOKED_<时间戳>。单条语句原子完成。"""
+    rows = rsql(
+        """with led as (select id, order_id, user_id, usd, deducted from s2a_ops.manual_refunds
+                        where id = :'lid'::bigint and deleted_at is null for update),
+           chk as (select o.id, o.status, o.refund_amount from payment_orders o, led
+                   where o.id = led.order_id and o.status in ('PARTIALLY_REFUNDED', 'REFUNDED')
+                     and o.refund_amount >= led.usd - 0.005 for update of o),
+           target as (select u.id, u.balance from users u, led, chk where u.id = led.user_id and u.deleted_at is null
+                      for update of u),
+           upd as (update users u set balance = target.balance + led.deducted, updated_at = now()
+                   from target, led where u.id = target.id
+                   returning target.balance as before, u.balance as after),
+           amt as (select greatest(chk.refund_amount - led.usd, 0) v from chk, led),
+           ord as (update payment_orders po
+                   set refund_amount = amt.v,
+                       status = case when amt.v <= 0.005 then 'COMPLETED' else 'PARTIALLY_REFUNDED' end,
+                       refund_at = case when amt.v <= 0.005 then null
+                                   else coalesce((select max(m.created_at) from s2a_ops.manual_refunds m
+                                                  where m.order_id = po.id and m.deleted_at is null and m.id <> led.id),
+                                                 po.refund_at) end,
+                       updated_at = now()
+                   from chk, amt, led, upd where po.id = chk.id returning po.status),
+           del as (update s2a_ops.manual_refunds m set deleted_at = now(), deleted_by = :'op', delete_reason = :'reason',
+                          cache_cleared_at = null
+                   from led, ord where m.id = led.id returning m.id),
+           ins as (insert into payment_audit_logs(order_id, action, detail, operator)
+                   select led.order_id::text,
+                          'MANUAL_REFUND_' || led.id || '_REVOKED_' || to_char(clock_timestamp(), 'YYYYMMDDHH24MISSUS'),
+                          json_build_object('ledgerId', led.id, 'refundAmount', led.usd, 'balanceRestored', led.deducted,
+                                            'balanceBefore', upd.before, 'statusBefore', chk.status,
+                                            'statusAfter', (select status from ord), 'reason', :'reason',
+                                            'manual', true, 'via', 'relay')::text,
+                          :'op'
+                   from led, chk, upd, del returning 1)
+           select upd.before, upd.after, (select status from ord), (select count(*) from ins),
+                  (select order_id from led), (select user_id from led) from upd;""",
+        lid=lid,
+        op=f"relay:{user['username']}",
+        reason=reason,
+    )
+    if not rows or rows[0][3] != "1":
+        raise ValueError("该退款记录不存在、已删除，或订单状态已变化，未做任何修改")
+    before, after, status, _, oid, uid = rows[0]
+    cache_ok = settle_cache(lid, uid)
+    print(
+        f"删除退款登记 {user['username']} 台账#{lid} 订单#{oid} 余额 ${before} → ${after}（{status}）",
+        flush=True,
+    )
+    return {
+        "order_id": int(oid),
+        "balance_before": float(before),
+        "balance_after": float(after),
+        "status": status,
+        "cache_cleared": cache_ok,
+    }
+
+
+def restore_refund(user, lid):
+    """恢复一次已删除的退款登记：按当次 $ 重新扣回余额（最多扣到 0）、订单已退金额加回并重算状态，清除删除标记，
+    记录恢复人与时间并更新本次实际扣回额（之后再删除时按它退回）；订单剩余可退不足或状态不允许时拒绝。
+    写审计 MANUAL_REFUND_<id>_RESTORED_<时间戳>。单条语句原子完成。"""
+    rows = rsql(
+        f"""with led as (select id, order_id, user_id, cny, usd, created_at from s2a_ops.manual_refunds
+                        where id = :'lid'::bigint and deleted_at is not null for update),
+           chk as (select o.id, o.status, o.refund_amount, o.amount from payment_orders o, led
+                   where o.id = led.order_id and o.order_type = 'balance' and o.status in {REFUNDABLE}
+                     and o.refund_amount + led.usd <= o.amount + 0.005 for update of o),
+           target as (select u.id, u.balance from users u, led, chk where u.id = led.user_id and u.deleted_at is null
+                      for update of u),
+           upd as (update users u set balance = target.balance - least(led.usd, greatest(target.balance, 0)),
+                          updated_at = now()
+                   from target, led where u.id = target.id
+                   returning target.balance as before, target.balance - u.balance as deducted),
+           st as (select case when chk.refund_amount + led.usd >= chk.amount - 0.005 then 'REFUNDED'
+                              else 'PARTIALLY_REFUNDED' end v from chk, led),
+           ord as (update payment_orders po
+                   set refund_amount = chk.refund_amount + led.usd, status = st.v,
+                       refund_at = greatest(coalesce(po.refund_at, led.created_at), led.created_at),
+                       force_refund = false, updated_at = now()
+                   from chk, led, st, upd where po.id = chk.id returning po.status),
+           res as (update s2a_ops.manual_refunds m
+                   set deleted_at = null, deleted_by = null, delete_reason = null,
+                       restored_at = now(), restored_by = :'op',
+                       deducted = upd.deducted, balance_before = upd.before, cache_cleared_at = null
+                   from led, upd, ord where m.id = led.id returning m.id),
+           ins as (insert into payment_audit_logs(order_id, action, detail, operator)
+                   select led.order_id::text,
+                          'MANUAL_REFUND_' || led.id || '_RESTORED_' || to_char(clock_timestamp(), 'YYYYMMDDHH24MISSUS'),
+                          json_build_object('ledgerId', led.id, 'refundAmount', led.usd, 'gatewayRefundCny', led.cny,
+                                            'balanceDeducted', upd.deducted, 'balanceBefore', upd.before,
+                                            'statusBefore', chk.status, 'statusAfter', st.v,
+                                            'manual', true, 'via', 'relay')::text,
+                          :'op'
+                   from led, chk, upd, st, res returning 1)
+           select upd.before, upd.deducted, (select status from ord), (select count(*) from ins),
+                  (select order_id from led), (select user_id from led), (select usd from led) from upd;""",
+        lid=lid,
+        op=f"relay:{user['username']}",
+    )
+    if not rows or rows[0][3] != "1":
+        raise ValueError(
+            "无法恢复：记录不存在或未删除，或订单剩余可退额度不足、状态不允许（如已全额退款）"
+        )
+    before, deducted, status, _, oid, uid, usd = rows[0]
+    cache_ok = settle_cache(lid, uid)
+    print(
+        f"恢复退款登记 {user['username']} 台账#{lid} 订单#{oid} 扣回 ${deducted}（{status}）",
+        flush=True,
+    )
+    return {
+        "order_id": int(oid),
+        "usd": float(usd),
+        "deducted": float(deducted),
+        "balance_before": float(before),
+        "status": status,
+        "cache_cleared": cache_ok,
+    }
+
+
+# ---------------- 限流 ----------------
+_hits, _hits_lock = {}, threading.Lock()
+
+
+def allow(ip, limit=QUERY_LIMIT_PER_MIN):
+    now = time.time()
+    with _hits_lock:
+        q = [t for t in _hits.get(ip, []) if t > now - 60]
+        if len(q) >= limit:
+            _hits[ip] = q
+            return False
+        q.append(now)
+        _hits[ip] = q
+        if len(_hits) > 10000:
+            _hits.clear()
+        return True
+
+
+class Handler(BaseHTTPRequestHandler):
+    def log_message(self, fmt, *args):  # 不记录含 Key 的请求行
+        pass
+
+    def send_json(self, code, payload, headers=None):
+        body = json.dumps(payload, ensure_ascii=False).encode("utf-8")
+        self.send_response(code)
+        self.send_header("Content-Type", "application/json; charset=utf-8")
+        self.send_header("Cache-Control", "no-store")
+        self.send_header("Content-Length", str(len(body)))
+        for k, v in (headers or {}).items():
+            self.send_header(k, v)
+        self.end_headers()
+        self.wfile.write(body)
+
+    # ---------- 退款登记接口（/api/relay/refund/...） ----------
+    def client_ip(self):
+        return (
+            (self.headers.get("X-Real-IP") or self.client_address[0])
+            + "|"
+            + (self.headers.get("CF-Connecting-IP") or "")
+        )
+
+    def session_token(self):
+        for part in (self.headers.get("Cookie") or "").split(";"):
+            k, _, v = part.strip().partition("=")
+            if k == SESSION_COOKIE:
+                return v
+        return ""
+
+    def set_session_cookie(self, token, max_age):
+        return {
+            "Set-Cookie": f"{SESSION_COOKIE}={token}; Path=/api/relay/refund; HttpOnly; Secure; "
+            f"SameSite=Strict; Max-Age={max_age}"
+        }
+
+    def read_json(self):
+        n = int(self.headers.get("Content-Length") or 0)
+        if n <= 0 or n > 4096:
+            raise ValueError("请求格式错误")
+        return json.loads(self.rfile.read(n))
+
+    def refund_api(self, method):
+        """处理 /refund/... 请求；不是本组路径返回 False。"""
+        path = urlparse(self.path).path.rstrip("/")
+        for pre in ("/api/relay", "/api-go/relay"):
+            if path.startswith(pre + "/refund"):
+                path = path[len(pre) :]
+                break
+        if not path.startswith("/refund"):
+            return False
+        args = dict(parse_qsl(urlparse(self.path).query))
+        ip = self.client_ip()
+        if method == "POST" and self.headers.get(CSRF_HEADER[0]) != CSRF_HEADER[1]:
+            self.send_json(403, {"code": 403, "message": "请求来源不正确"})
+            return True
+        try:
+            if path == "/refund/login" and method == "POST":
+                if not allow("login:" + ip, LOGIN_LIMIT_PER_MIN):
+                    self.send_json(
+                        429,
+                        {"code": 429, "message": "登录尝试过于频繁，请 1 分钟后再试"},
+                    )
+                    return True
+                body = self.read_json()
+                code, res, token = login(
+                    body.get("username"),
+                    body.get("password"),
+                    ip,
+                    self.headers.get("User-Agent", ""),
+                )
+                if token:
+                    print(f"退款页登录 {res['username']} {ip}", flush=True)
+                    self.send_json(
+                        200,
+                        {"code": 0, "data": res},
+                        self.set_session_cookie(token, SESSION_HOURS * 3600),
+                    )
+                else:
+                    print(f"退款页登录失败 {ip}", flush=True)
+                    self.send_json(code, {"code": code, **res})
+                return True
+            if not allow("refund:" + ip, 120):
+                self.send_json(
+                    429, {"code": 429, "message": "操作过于频繁，请稍后再试"}
+                )
+                return True
+            user = session_user(self.session_token())
+            if path == "/refund/logout" and method == "POST":
+                if user:
+                    rsql(
+                        "delete from s2a_ops.refund_sessions where token_hash = :'h';",
+                        h=user["token_hash"],
+                    )
+                self.send_json(200, {"code": 0}, self.set_session_cookie("", 0))
+                return True
+            if not user:
+                self.send_json(401, {"code": 401, "message": "请先登录"})
+                return True
+            if path == "/refund/me" and method == "GET":
+                self.send_json(
+                    200,
+                    {
+                        "code": 0,
+                        "data": {
+                            "username": user["username"],
+                            "must_change": user["must_change"],
+                        },
+                    },
+                )
+                return True
+            if path == "/refund/password" and method == "POST":
+                body = self.read_json()
+                change_password(user, body.get("old"), body.get("new"))
+                print(f"退款页改密 {user['username']}", flush=True)
+                self.send_json(200, {"code": 0})
+                return True
+            if user["must_change"]:
+                self.send_json(
+                    403, {"code": "must_change", "message": "首次登录请先修改密码"}
+                )
+                return True
+            if path == "/refund/orders" and method == "GET":
+                self.send_json(200, {"code": 0, "data": list_orders(args)})
+                return True
+            if path == "/refund/order" and method == "GET":
+                if not re.fullmatch(r"\d{1,18}", args.get("id", "")):
+                    raise ValueError("订单号格式不正确")
+                o = order_detail(int(args["id"]))
+                if not o:
+                    self.send_json(404, {"code": 404, "message": "订单不存在"})
+                else:
+                    self.send_json(200, {"code": 0, "data": o})
+                return True
+            if path == "/refund/request" and method == "GET":
+                # 页面核对结果未确认的登记：按 request_id 查是否已写入
+                rid = args.get("id", "").lower()
+                if not re.fullmatch(RID_RE, rid):
+                    raise ValueError("请求标识格式不正确")
+                self.send_json(
+                    200, {"code": 0, "data": request_result(rid, request_state(rid))}
+                )
+                return True
+            if path == "/refund/abandon" and method == "POST":
+                # 页面重新打开订单时处理结果未确认的登记：已写入返回结果，否则在服务器作废该 request_id
+                rid = str(self.read_json().get("request_id") or "").lower()
+                if not re.fullmatch(RID_RE, rid):
+                    raise ValueError("请求标识格式不正确")
+                state = abandon_request(user, rid)
+                if state == "abandoned":
+                    print(f"作废未确认登记 {user['username']} {rid}", flush=True)
+                self.send_json(200, {"code": 0, "data": request_result(rid, state)})
+                return True
+            if path == "/refund/restore" and method == "POST":
+                body = self.read_json()
+                if body.get("confirm") is not True:
+                    raise ValueError("缺少确认")
+                self.send_json(
+                    200,
+                    {
+                        "code": 0,
+                        "data": restore_refund(user, int(body.get("ledger_id"))),
+                    },
+                )
+                return True
+            if path == "/refund/revoke" and method == "POST":
+                body = self.read_json()
+                if body.get("confirm") is not True:
+                    raise ValueError("缺少确认")
+                reason = (
+                    re.sub(r"\s+", " ", str(body.get("reason") or "")).strip()[:200]
+                    or "删除登记"
+                )
+                self.send_json(
+                    200,
+                    {
+                        "code": 0,
+                        "data": revoke_refund(user, int(body.get("ledger_id")), reason),
+                    },
+                )
+                return True
+            if path == "/refund/refund" and method == "POST":
+                body = self.read_json()
+                if body.get("confirm") is not True:
+                    raise ValueError("缺少确认")
+                reason = (
+                    re.sub(r"\s+", " ", str(body.get("reason") or "")).strip()[:200]
+                    or "线下退款（支付平台客服处理）"
+                )
+                rid = str(body.get("request_id") or "").lower()
+                if not re.fullmatch(RID_RE, rid):
+                    raise ValueError("页面版本过旧，请刷新页面后再登记")
+                res = execute_refund(
+                    user, int(body.get("order_id")), float(body.get("cny")), reason, rid
+                )
+                self.send_json(200, {"code": 0, "data": res})
+                return True
+            self.send_json(404, {"code": 404, "message": "Not Found"})
+        except (ValueError, TypeError) as e:
+            self.send_json(400, {"code": 400, "message": str(e) or "参数错误"})
+        except Exception as e:
+            print(f"退款接口异常 {path}: {type(e).__name__}", flush=True)
+            msg = (
+                "登记结果未确认：可直接再次点击确认重试（同一次操作不会重复登记），或关闭后刷新订单查看"
+                if path == "/refund/refund"
+                else "服务异常，请稍后再试"
+            )
+            self.send_json(500, {"code": 500, "message": msg})
+        return True
+
+    def do_POST(self):
+        if not self.refund_api("POST"):
+            self.send_json(404, {"code": 404, "message": "Not Found"})
+
+    def do_GET(self):
+        if self.refund_api("GET"):
+            return None
+        parsed = urlparse(self.path)
+        path = parsed.path.rstrip("/")
+        args = dict(parse_qsl(parsed.query))
+        if path in ("", "/health"):
+            return self.send_json(200, {"status": "ok", "service": "sub2api-key-query"})
+        if path in (
+            "/public-info",
+            "/api/relay/public-info",
+            "/api-go/relay/public-info",
+        ):
+            try:
+                return self.send_json(
+                    200,
+                    {
+                        "code": 0,
+                        "data": {
+                            "service_name": "StarNexus Relay",
+                            "routes": [
+                                {
+                                    "id": "acc",
+                                    "name": "推荐加速线路 (Cloudflare)",
+                                    "url": HOSTS["acc"],
+                                    "badge": "推荐",
+                                    "description": "全球 Anycast 加速，延迟优选",
+                                },
+                                {
+                                    "id": "direct",
+                                    "name": "直连主线路 (US West)",
+                                    "url": HOSTS["direct"],
+                                    "badge": "直连",
+                                    "description": "美国西岸直连，无代理层",
+                                },
+                            ],
+                            "common_endpoints": {
+                                "openai_v1": f"{HOSTS['acc']}/v1",
+                                "claude_code": f"{HOSTS['acc']}/api/<分组>",
+                            },
+                            "groups": groups_for_user(None),
+                            "tags": cached("tags", 60, nexus_tags),
+                            "announcements": cached("anno", 30, announcements),
+                            "updated_at": time.strftime("%Y-%m-%d %H:%M:%S"),
+                        },
+                    },
+                )
+            except Exception as e:
+                print(f"public-info 异常: {type(e).__name__}", flush=True)
+                return self.send_json(
+                    500, {"code": 500, "message": "加载数据失败，请稍后再试"}
+                )
+        if path in ("/key-query", "/api/relay/key-query", "/api-go/relay/key-query"):
+            if not allow(self.headers.get("X-Real-IP") or self.client_address[0]):
+                return self.send_json(
+                    429, {"code": 429, "message": "查询过于频繁，请 1 分钟后再试"}
+                )
+            auth = self.headers.get("Authorization", "")
+            key = (
+                (auth[7:].strip() if auth.lower().startswith("bearer ") else "")
+                or self.headers.get("x-api-key", "").strip()
+                or args.get("key", "").strip()
+            )
+            if not key:
+                return self.send_json(
+                    400, {"code": 400, "message": "请输入待查询的 API Key"}
+                )
+            if not KEY_RE.match(key):
+                return self.send_json(
+                    400, {"code": 400, "message": "API Key 格式不正确"}
+                )
+            try:
+                res = query_key_data(key)
+                if "error" in res:
+                    return self.send_json(404, {"code": 404, "message": res["error"]})
+                return self.send_json(
+                    200, {"code": 0, "message": "success", "data": res}
+                )
+            except Exception as e:
+                print(f"Key 查询异常: {type(e).__name__}", flush=True)
+                return self.send_json(
+                    500, {"code": 500, "message": "查询服务发生异常，请稍后再试"}
+                )
+        return self.send_json(404, {"code": 404, "message": "Not Found"})
+
+
+if __name__ == "__main__":
+    srv = ThreadingHTTPServer(("127.0.0.1", 8092), Handler)
+    srv.daemon_threads = True
+    threading.Thread(target=cache_retry_loop, daemon=True).start()
+    print("sub2api-key-query 服务已启动在 127.0.0.1:8092", flush=True)
+    srv.serve_forever()
diff --git a/relay/server/refund_users.py b/relay/server/refund_users.py
new file mode 100644
index 0000000..5b7fd55
--- /dev/null
+++ b/relay/server/refund_users.py
@@ -0,0 +1,104 @@
+"""退款登记页账号管理（在服务器上以 root 运行，经 `/opt/sub2api/relay/run refund-user` 调用）。
+
+  run refund-user list              列出账号
+  run refund-user add <账号>         新建账号（交互输入密码，至少 10 位）
+  run refund-user passwd <账号>      重设密码（同时解锁、踢下线该账号所有会话）
+  run refund-user disable <账号>     停用（立即踢下线）
+  run refund-user enable <账号>      启用
+密码只存 scrypt 加盐哈希（s2a_ops.refund_users），与 key_query.py 的校验算法一致。
+"""
+
+import getpass
+import hashlib
+import os
+import re
+import subprocess
+import sys
+
+PSQL = "/www/server/pgsql/bin/psql"
+PW_MIN = 10
+
+
+def q(query, **params):
+    sets = "".join(f"\\set {k} '{str(v).replace(chr(92), chr(92) * 2).replace(chr(39), chr(92) + chr(39))}'\n"
+                   for k, v in params.items())  # fmt: skip
+    return subprocess.run(
+        [
+            PSQL,
+            "-h",
+            "localhost",
+            "-U",
+            "postgres",
+            "-d",
+            "sub2api",
+            "-qAt",
+            "-v",
+            "ON_ERROR_STOP=1",
+        ],
+        input=sets + query,
+        capture_output=True,
+        text=True,
+        check=True,
+        env=os.environ,
+    ).stdout.strip()
+
+
+def hash_password(pw):
+    salt = os.urandom(16)
+    dk = hashlib.scrypt(pw.encode(), salt=salt, n=2**14, r=8, p=1, dklen=32)
+    return f"scrypt$16384$8$1${salt.hex()}${dk.hex()}"
+
+
+def ask_password():
+    pw = getpass.getpass("新密码（至少 10 位，不显示）：")
+    if len(pw) < PW_MIN:
+        raise SystemExit(f"密码至少 {PW_MIN} 位")
+    if getpass.getpass("再输入一次：") != pw:
+        raise SystemExit("两次输入不一致")
+    return pw
+
+
+def exists(name):
+    return (
+        q("select count(*) from s2a_ops.refund_users where username = :'u';", u=name)
+        == "1"
+    )
+
+
+cmd = sys.argv[1] if len(sys.argv) > 1 else "list"
+name = sys.argv[2].strip() if len(sys.argv) > 2 else ""
+if cmd != "list" and not re.fullmatch(r"[A-Za-z0-9_.@-]{2,64}", name):
+    raise SystemExit(__doc__ + "\n账号只能用字母、数字和 _ . @ -，2–64 位")
+
+if cmd == "list":
+    out = q("""select username, case when enabled then '启用' else '停用' end,
+                 case when locked_until > now() then '锁定中' else '' end,
+                 coalesce(to_char(last_login_at at time zone 'Asia/Shanghai', 'YYYY-MM-DD HH24:MI'), '从未登录'),
+                 (select count(*) from s2a_ops.refund_sessions s where s.user_id = u.id and s.expires_at > now())
+               from s2a_ops.refund_users u order by id;""")
+    print("账号 | 状态 | 锁定 | 最近登录（北京时间） | 在线会话")
+    print(out or "（还没有账号，用 run refund-user add <账号> 新建）")
+elif cmd == "add":
+    if exists(name):
+        raise SystemExit(f"账号 {name} 已存在")
+    q("insert into s2a_ops.refund_users(username, pw_hash, must_change) values (:'u', :'h', false);",
+      u=name, h=hash_password(ask_password()))  # fmt: skip
+    print(f"已新建账号 {name}")
+elif cmd == "passwd":
+    if not exists(name):
+        raise SystemExit(f"账号 {name} 不存在")
+    q("""update s2a_ops.refund_users set pw_hash = :'h', must_change = false, failed = 0, locked_until = null
+         where username = :'u';
+         delete from s2a_ops.refund_sessions where user_id = (select id from s2a_ops.refund_users where username = :'u');""",
+      u=name, h=hash_password(ask_password()))  # fmt: skip
+    print(f"已重设 {name} 的密码，已解锁并踢下线所有会话")
+elif cmd in ("disable", "enable"):
+    if not exists(name):
+        raise SystemExit(f"账号 {name} 不存在")
+    q("update s2a_ops.refund_users set enabled = :'e'::boolean where username = :'u';"
+      + ("delete from s2a_ops.refund_sessions where user_id = (select id from s2a_ops.refund_users where username = :'u');"
+         if cmd == "disable" else ""),
+      u=name, e="true" if cmd == "enable" else "false")  # fmt: skip
+    print(f"已{'启用' if cmd == 'enable' else '停用并踢下线'} {name}")
+else:
+    raise SystemExit(__doc__)
diff --git a/relay/src/index.html b/relay/src/index.html
new file mode 100644
index 0000000..7e9812a
--- /dev/null
+++ b/relay/src/index.html
@@ -0,0 +1,1765 @@
+<!doctype html>
+<html lang="zh-CN" class="dark">
+  <head>
+    <meta charset="utf-8" />
+    <meta
+      name="viewport"
+      content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no"
+    />
+    <title>StarNexus - 余额查询</title>
+    <meta
+      name="description"
+      content="StarNexus：Key 余额用量查询、分组接入查看与一键复制"
+    />
+    <link
+      rel="icon"
+      type="image/svg+xml"
+      href="data:image/svg+xml,%3Csvg viewBox='0 0 48 48' xmlns='http://www.w3.org/2000/svg'%3E%3Cdefs%3E%3ClinearGradient id='snbg' x1='0' y1='0' x2='1' y2='1'%3E%3Cstop offset='0' stop-color='%236366f1'/%3E%3Cstop offset='1' stop-color='%238b5cf6'/%3E%3C/linearGradient%3E%3C/defs%3E%3Crect width='48' height='48' rx='12' fill='url(%23snbg)'/%3E%3Cpath d='M24 9.5l3.6 10.9L38.5 24l-10.9 3.6L24 38.5l-3.6-10.9L9.5 24l10.9-3.6z' fill='%23fff'/%3E%3Ccircle cx='35' cy='13' r='2.6' fill='%23fff' fill-opacity='.7'/%3E%3C/svg%3E"
+    />
+
+    <!-- 防止闪烁的主题初始化脚本 (立即执行) -->
+    <script>
+      (function () {
+        const mode = localStorage.getItem("theme_mode") || "system";
+        const dark =
+          mode === "dark" ||
+          (mode === "system" &&
+            window.matchMedia("(prefers-color-scheme: dark)").matches);
+        document.documentElement.classList.toggle("dark", dark);
+      })();
+    </script>
+
+    <!-- Tailwind v4 规范：必须带有 @import "tailwindcss" 以及声明自定义 dark variant -->
+
+    <!-- 引入本地预编译的 Tailwind CSS (零外部依赖、秒开) -->
+    <link rel="stylesheet" href="./tailwind.css" />
+  </head>
+  <body
+    class="min-h-screen selection:bg-indigo-500 selection:text-white transition-colors duration-200"
+  >
+    <div class="max-w-7xl mx-auto px-4 sm:px-6 py-6 pb-24">
+      <!-- 顶部居中导航栏 -->
+      <header
+        class="relative flex flex-col items-center justify-center text-center pb-6 mb-6 border-b-2 border-slate-200 dark:border-night-line"
+      >
+        <!-- 右上角主题切换下拉菜单 (支持白天模式、黑夜模式、跟随系统，带图标) -->
+        <div class="absolute right-0 top-0 z-40 group/theme">
+          <button
+            id="themeTriggerBtn"
+            class="w-10 h-10 rounded-xl border-2 border-slate-300 dark:border-night-line bg-white dark:bg-night-card text-slate-700 dark:text-slate-200 flex items-center justify-center shadow-sm transition-all cursor-pointer hv"
+          >
+            <span id="activeThemeIcon">
+              <!-- 动态填充当前模式图标 -->
+              <svg
+                class="w-5 h-5 text-indigo-400"
+                fill="none"
+                stroke="currentColor"
+                stroke-width="2"
+                viewBox="0 0 24 24"
+              >
+                <path
+                  d="M12 3v1m0 16v1m9-9h-1M4 12H3m15.364 6.364l-.707-.707M6.343 6.343l-.707-.707m12.728 0l-.707.707M6.343 17.657l-.707.707M16 12a4 4 0 11-8 0 4 4 0 018 0z"
+                />
+              </svg>
+            </span>
+          </button>
+
+          <!-- 下拉菜单：Hover 或点击显示 -->
+          <div
+            class="absolute right-0 top-full pt-2 hidden group-hover/theme:block hover:block z-50 animate-fadeIn"
+          >
+            <div
+              class="w-36 p-1.5 rounded-2xl border-2 border-slate-200 dark:border-night-line bg-white/95 dark:bg-night-card backdrop-blur-2xl shadow-2xl flex flex-col gap-1 text-xs"
+            >
+              <button
+                onclick="setThemeMode('light')"
+                id="itemThemeLight"
+                class="flex items-center justify-between w-full px-3 py-2 rounded-xl transition-colors hover:bg-indigo-50 dark:hover:bg-night-hover text-slate-700 dark:text-slate-300 cursor-pointer"
+              >
+                <span class="flex items-center gap-2">
+                  <svg
+                    class="w-4 h-4 text-amber-500"
+                    fill="none"
+                    stroke="currentColor"
+                    stroke-width="2"
+                    viewBox="0 0 24 24"
+                  >
+                    <circle cx="12" cy="12" r="5" />
+                    <path
+                      d="M12 1v2M12 21v2M4.22 4.22l1.42 1.42M18.36 18.36l1.42 1.42M1 12h2M21 12h2M4.22 19.78l1.42-1.42M18.36 5.64l1.42-1.42"
+                    />
+                  </svg>
+                  <span>白天模式</span>
+                </span>
+                <span class="check-mark hidden text-indigo-500 font-bold"
+                  >✓</span
+                >
+              </button>
+
+              <button
+                onclick="setThemeMode('dark')"
+                id="itemThemeDark"
+                class="flex items-center justify-between w-full px-3 py-2 rounded-xl transition-colors hover:bg-indigo-50 dark:hover:bg-night-hover text-slate-700 dark:text-slate-300 cursor-pointer"
+              >
+                <span class="flex items-center gap-2">
+                  <svg
+                    class="w-4 h-4 text-indigo-400"
+                    fill="none"
+                    stroke="currentColor"
+                    stroke-width="2"
+                    viewBox="0 0 24 24"
+                  >
+                    <path d="M21 12.79A9 9 0 1111.21 3 7 7 0 0021 12.79z" />
+                  </svg>
+                  <span>黑夜模式</span>
+                </span>
+                <span class="check-mark hidden text-indigo-500 font-bold"
+                  >✓</span
+                >
+              </button>
+
+              <button
+                onclick="setThemeMode('system')"
+                id="itemThemeSystem"
+                class="flex items-center justify-between w-full px-3 py-2 rounded-xl transition-colors hover:bg-indigo-50 dark:hover:bg-night-hover text-slate-700 dark:text-slate-300 cursor-pointer"
+              >
+                <span class="flex items-center gap-2">
+                  <svg
+                    class="w-4 h-4 text-slate-500 dark:text-slate-400"
+                    fill="none"
+                    stroke="currentColor"
+                    stroke-width="2"
+                    viewBox="0 0 24 24"
+                  >
+                    <rect width="20" height="14" x="2" y="3" rx="2" />
+                    <path d="M8 21h8M12 17v4" />
+                  </svg>
+                  <span>跟随系统</span>
+                </span>
+                <span class="check-mark hidden text-indigo-500 font-bold"
+                  >✓</span
+                >
+              </button>
+            </div>
+          </div>
+        </div>
+
+        <!-- 居中的 Brand：Logo + 标题 + 副标题 -->
+        <div
+          class="inline-flex flex-col items-center justify-center select-none"
+        >
+          <span
+            class="block w-14 h-14 mb-3 rounded-2xl ring-1 ring-black/5 dark:ring-white/15 shadow-lg shadow-indigo-500/30 overflow-hidden"
+            role="img"
+            aria-label="StarNexus"
+            ><svg
+              class="w-full h-full"
+              viewBox="0 0 48 48"
+              xmlns="http://www.w3.org/2000/svg"
+            >
+              <defs>
+                <linearGradient id="snbg" x1="0" y1="0" x2="1" y2="1">
+                  <stop offset="0" stop-color="#6366f1" />
+                  <stop offset="1" stop-color="#8b5cf6" />
+                </linearGradient>
+              </defs>
+              <rect width="48" height="48" rx="12" fill="url(#snbg)" />
+              <path
+                d="M24 9.5l3.6 10.9L38.5 24l-10.9 3.6L24 38.5l-3.6-10.9L9.5 24l10.9-3.6z"
+                fill="#fff"
+              />
+              <circle
+                cx="35"
+                cy="13"
+                r="2.6"
+                fill="#fff"
+                fill-opacity=".7"
+              /></svg
+          ></span>
+          <h1
+            class="text-2xl sm:text-3xl font-extrabold tracking-tight text-slate-900 dark:text-white"
+          >
+            StarNexus
+          </h1>
+          <p
+            class="text-xs sm:text-sm text-slate-500 dark:text-slate-400 mt-1 max-w-lg leading-relaxed"
+          >
+            一个 Key，接入全部 AI 模型
+          </p>
+        </div>
+        <!-- 右下角按钮组：退款登记（需登录）+ 公告（无公告时不显示） -->
+        <div
+          class="mt-3 flex items-center gap-2 sm:mt-0 sm:absolute sm:right-0 sm:bottom-6"
+        >
+          <a
+            href="/relay/refund.html"
+            class="flex h-9 px-3 rounded-xl border-2 border-slate-300 dark:border-night-line bg-white dark:bg-night-card text-slate-700 dark:text-slate-200 text-xs font-medium items-center gap-1.5 shadow-sm cursor-pointer hv"
+          >
+            <svg
+              class="w-4 h-4 text-amber-500"
+              fill="none"
+              stroke="currentColor"
+              stroke-width="2"
+              viewBox="0 0 24 24"
+            >
+              <path d="M3 12a9 9 0 1 0 3-6.7L3 8" />
+              <path d="M3 3v5h5" />
+            </svg>
+            <span>退款</span>
+          </a>
+          <button
+            id="annoToggleBtn"
+            type="button"
+            onclick="toggleAnnouncement()"
+            aria-haspopup="dialog"
+            class="hidden h-9 px-3 rounded-xl border-2 border-slate-300 dark:border-night-line bg-white dark:bg-night-card text-slate-700 dark:text-slate-200 text-xs font-medium items-center gap-1.5 shadow-sm cursor-pointer hv"
+          >
+            <svg
+              class="w-4 h-4 text-indigo-500 dark:text-indigo-400"
+              fill="none"
+              stroke="currentColor"
+              stroke-width="2"
+              viewBox="0 0 24 24"
+            >
+              <path
+                d="M11 5.882V19.24a1.76 1.76 0 01-3.417.592l-2.147-6.15M18 13a3 3 0 100-6M5.436 13.683A4.001 4.001 0 017 6h1.832c4.1 0 7.625-1.234 9.168-3v14c-1.543-1.766-5.067-3-9.168-3H7a3.988 3.988 0 01-1.564-.317z"
+              />
+            </svg>
+            <span>公告</span>
+          </button>
+        </div>
+      </header>
+      <!-- 公告：Markdown 渲染，全屏居中弹窗 -->
+      <div
+        id="announcementBox"
+        role="dialog"
+        aria-modal="true"
+        aria-label="公告"
+        onclick="if (event.target === this) setAnnouncementOpen(false);"
+        class="hidden fixed inset-0 z-[100] items-center justify-center p-4 bg-slate-900/50 backdrop-blur-sm animate-fadeIn"
+      >
+        <div
+          class="w-full max-w-2xl max-h-[85vh] flex flex-col rounded-2xl border-2 border-indigo-500/30 bg-white dark:bg-night-card shadow-2xl p-5 sm:p-6"
+        >
+          <div
+            class="flex items-center gap-2 mb-3 text-indigo-600 dark:text-indigo-400"
+          >
+            <svg
+              class="w-5 h-5 shrink-0"
+              fill="none"
+              stroke="currentColor"
+              stroke-width="2"
+              viewBox="0 0 24 24"
+            >
+              <path
+                d="M11 5.882V19.24a1.76 1.76 0 01-3.417.592l-2.147-6.15M18 13a3 3 0 100-6M5.436 13.683A4.001 4.001 0 017 6h1.832c4.1 0 7.625-1.234 9.168-3v14c-1.543-1.766-5.067-3-9.168-3H7a3.988 3.988 0 01-1.564-.317z"
+              />
+            </svg>
+            <span class="text-sm font-semibold">公告</span>
+            <span
+              id="annoDate"
+              class="ml-auto text-[11px] text-indigo-500 dark:text-indigo-400 font-mono"
+            ></span>
+            <button
+              type="button"
+              onclick="setAnnouncementOpen(false)"
+              aria-label="关闭公告"
+              class="w-8 h-8 -mr-1 rounded-lg flex items-center justify-center text-slate-400 hover:text-slate-700 dark:hover:text-slate-200 hover:bg-slate-100 dark:hover:bg-night-hover cursor-pointer"
+            >
+              <svg
+                class="w-4 h-4"
+                fill="none"
+                stroke="currentColor"
+                stroke-width="2.5"
+                viewBox="0 0 24 24"
+              >
+                <path d="M18 6 6 18M6 6l12 12" />
+              </svg>
+            </button>
+          </div>
+          <div
+            id="annoList"
+            class="flex-1 min-h-0 overflow-y-auto pr-1 divide-y divide-indigo-500/20"
+          ></div>
+        </div>
+      </div>
+
+      <!-- 线路展示与测速卡片 (推荐加速线路和 URL 并排显示，直连主线路并排显示) -->
+      <div class="grid grid-cols-1 md:grid-cols-2 gap-4 mb-6">
+        <!-- 推荐加速线路 -->
+        <div
+          class="rounded-2xl p-4 border-2 border-slate-200 dark:border-night-line bg-white/90 dark:bg-night-card backdrop-blur-xl flex flex-wrap items-center justify-between gap-3"
+        >
+          <div class="flex flex-wrap items-center gap-2.5">
+            <div
+              class="flex items-center gap-1.5 font-semibold text-sm text-slate-900 dark:text-slate-100 whitespace-nowrap"
+            >
+              <span>加速线路</span>
+              <span
+                class="text-[11px] px-2 py-0.5 rounded-full bg-indigo-500/15 text-indigo-600 dark:text-indigo-300 border-2 border-indigo-500/30 font-semibold"
+                >Cloudflare Anycast</span
+              >
+            </div>
+            <div
+              class="font-mono text-xs text-slate-700 dark:text-slate-300 bg-slate-100 dark:bg-night-inset px-2.5 py-1 rounded-lg border-2 border-slate-200 dark:border-night-line inline-block select-all whitespace-nowrap"
+            >
+              https://apiacc.itssx.com
+            </div>
+          </div>
+          <div
+            class="flex items-center gap-1.5 font-mono text-xs text-slate-600 dark:text-slate-300 shrink-0 ml-auto sm:ml-0 px-2 py-1"
+          >
+            <span
+              id="pingDotAcc"
+              class="w-2.5 h-2.5 rounded-full bg-slate-400 inline-block"
+            ></span>
+            <span id="pingValAcc">测速中…</span>
+            <span
+              id="pingBestAcc"
+              class="hidden text-[10px] px-1.5 py-0.5 rounded bg-emerald-500/10 text-emerald-600 dark:text-emerald-400 font-sans font-bold"
+              >最快</span
+            >
+          </div>
+        </div>
+
+        <!-- 直连主线路 -->
+        <div
+          class="rounded-2xl p-4 border-2 border-slate-200 dark:border-night-line bg-white/70 dark:bg-night-card backdrop-blur-xl flex flex-wrap items-center justify-between gap-3"
+        >
+          <div class="flex flex-wrap items-center gap-2.5">
+            <div
+              class="flex items-center gap-1.5 font-semibold text-sm text-slate-700 dark:text-slate-300 whitespace-nowrap"
+            >
+              <span>直连线路</span>
+              <span
+                class="text-[11px] px-2 py-0.5 rounded-full bg-slate-100 dark:bg-night-hover text-slate-600 dark:text-slate-400 border-2 border-slate-200 dark:border-night-line font-semibold"
+                >US West 直连</span
+              >
+            </div>
+            <div
+              class="font-mono text-xs text-slate-700 dark:text-slate-300 bg-slate-100 dark:bg-night-inset px-2.5 py-1 rounded-lg border-2 border-slate-200 dark:border-night-line inline-block select-all whitespace-nowrap"
+            >
+              https://api.itssx.com
+            </div>
+          </div>
+          <div
+            class="flex items-center gap-1.5 font-mono text-xs text-slate-600 dark:text-slate-300 shrink-0 ml-auto sm:ml-0 px-2 py-1"
+          >
+            <span
+              id="pingDotDirect"
+              class="w-2.5 h-2.5 rounded-full bg-slate-400 inline-block"
+            ></span>
+            <span id="pingValDirect">测速中…</span>
+            <span
+              id="pingBestDirect"
+              class="hidden text-[10px] px-1.5 py-0.5 rounded bg-emerald-500/10 text-emerald-600 dark:text-emerald-400 font-sans font-bold"
+              >最快</span
+            >
+          </div>
+        </div>
+      </div>
+
+      <!-- Key 查询核心区域 (border-2 边框体系) -->
+      <section
+        class="rounded-2xl border-2 border-slate-200 dark:border-night-line bg-white/90 dark:bg-night-card backdrop-blur-2xl p-6 sm:p-8 mb-8 shadow-xl shadow-slate-200/50"
+      >
+        <div class="mb-5">
+          <h2
+            class="text-xl font-bold text-slate-900 dark:text-white flex items-center gap-2.5"
+          >
+            <svg
+              class="w-6 h-6 text-indigo-600 dark:text-indigo-400"
+              fill="none"
+              stroke="currentColor"
+              stroke-width="2"
+              viewBox="0 0 24 24"
+            >
+              <circle cx="11" cy="11" r="8" />
+              <path d="m21 21-4.3-4.3" />
+            </svg>
+            查询 Key
+          </h2>
+          <p class="text-xs text-slate-500 dark:text-slate-400 mt-1">
+            余额、额度、用量与最近调用。
+          </p>
+        </div>
+
+        <!-- 输入栏 -->
+        <div
+          id="queryError"
+          role="alert"
+          class="hidden mb-2 items-center gap-2 text-xs font-medium text-rose-600 dark:text-rose-400"
+        >
+          <svg
+            class="w-4 h-4 shrink-0"
+            fill="none"
+            stroke="currentColor"
+            stroke-width="2.5"
+            viewBox="0 0 24 24"
+          >
+            <circle cx="12" cy="12" r="10" />
+            <path d="M12 8v4m0 4h.01" />
+          </svg>
+          <span id="queryErrorMsg"></span>
+        </div>
+        <div class="flex flex-col sm:flex-row gap-3 mb-3">
+          <div class="relative flex-1">
+            <input
+              type="text"
+              id="keyInput"
+              placeholder="输入 API Key (sk-...)"
+              autocomplete="off"
+              spellcheck="false"
+              aria-describedby="queryErrorMsg"
+              class="w-full h-12 px-4 rounded-xl border border-slate-300 dark:border-night-line bg-white dark:bg-night-inset text-slate-900 dark:text-slate-100 placeholder-slate-400 dark:placeholder-slate-500 font-mono text-sm shadow-sm transition-all outline-none hover:border-indigo-400 hover:ring-4 hover:ring-indigo-500/10 focus:border-indigo-500 focus:ring-4 focus:ring-indigo-500/20 dark:hover:border-indigo-400 dark:focus:border-indigo-400"
+            />
+            <div
+              id="keyHistory"
+              class="hidden absolute left-0 right-0 top-full mt-1.5 z-30 rounded-xl border border-slate-200 dark:border-night-line bg-white dark:bg-night-card shadow-xl shadow-slate-300/40 dark:shadow-black/40 py-1 max-h-72 overflow-y-auto"
+            ></div>
+          </div>
+          <div class="flex gap-2">
+            <button
+              id="queryBtn"
+              onclick="doQuery()"
+              class="h-12 px-6 rounded-xl bg-indigo-600 hover:bg-indigo-500 text-white font-medium text-sm flex items-center justify-center gap-2 shadow-lg shadow-indigo-600/25 active:scale-95 transition-all cursor-pointer"
+            >
+              <svg
+                class="w-4 h-4"
+                fill="none"
+                stroke="currentColor"
+                stroke-width="2"
+                viewBox="0 0 24 24"
+              >
+                <circle cx="11" cy="11" r="8" />
+                <path d="m21 21-4.3-4.3" />
+              </svg>
+              立即查询
+            </button>
+          </div>
+        </div>
+
+        <!-- 查询结果仪表盘 -->
+        <div
+          id="dashboard"
+          class="hidden mt-6 pt-6 border-t-2 border-dashed border-slate-200 dark:border-night-line animate-fadeIn"
+        >
+          <!-- 余额：已使用 / 总金额、剩余、累计充值 -->
+          <div
+            class="rounded-xl border-2 border-emerald-500/30 bg-emerald-50/50 dark:bg-night-inset p-5 mb-5"
+          >
+            <div class="flex items-center gap-2 text-xs mb-3">
+              <span
+                id="statScope"
+                class="px-2 py-0.5 rounded-full border-2 border-emerald-500/20 bg-emerald-500/10 text-emerald-600 dark:text-emerald-400 text-[11px] font-semibold"
+                >账户余额</span
+              >
+            </div>
+            <div class="grid grid-cols-1 sm:grid-cols-3 gap-4 text-center">
+              <div>
+                <div class="text-[11px] text-slate-500 dark:text-slate-400">
+                  已使用 / 总金额
+                </div>
+                <div
+                  class="mt-1 text-[22px] font-bold font-mono text-slate-800 dark:text-slate-100"
+                >
+                  <span id="statUsed">$0.0000</span>
+                  <span class="text-slate-400 dark:text-slate-500 font-medium"
+                    >/</span
+                  >
+                  <span
+                    id="statTotal"
+                    class="text-slate-500 dark:text-slate-400"
+                    >$0.0000</span
+                  >
+                </div>
+              </div>
+              <div>
+                <div class="text-[11px] text-slate-500 dark:text-slate-400">
+                  剩余金额
+                </div>
+                <div
+                  id="statRemain"
+                  class="mt-1 text-[22px] font-bold font-mono text-emerald-600 dark:text-emerald-400"
+                >
+                  $0.0000
+                </div>
+              </div>
+              <div>
+                <div class="text-[11px] text-slate-500 dark:text-slate-400">
+                  累计充值
+                </div>
+                <div
+                  id="statRecharged"
+                  class="mt-1 text-[22px] font-bold font-mono text-orange-500 dark:text-orange-400"
+                >
+                  $0.00
+                </div>
+              </div>
+            </div>
+            <!-- Key 信息 -->
+            <div
+              class="grid grid-cols-2 lg:grid-cols-4 gap-4 mt-4 pt-4 border-t-2 border-emerald-500/15"
+            >
+              <div class="min-w-0">
+                <div class="text-[11px] text-slate-500 dark:text-slate-400">
+                  Key 备注名称
+                </div>
+                <div
+                  id="valKeyName"
+                  class="mt-1 text-[20px] font-bold text-slate-800 dark:text-slate-100 truncate"
+                >
+                  -
+                </div>
+              </div>
+              <div>
+                <div class="text-[11px] text-slate-500 dark:text-slate-400">
+                  Key 状态
+                </div>
+                <div
+                  id="valKeyStatus"
+                  class="mt-1 text-[20px] font-bold text-emerald-600 dark:text-emerald-400"
+                >
+                  正常生效
+                </div>
+              </div>
+              <div>
+                <div class="text-[11px] text-slate-500 dark:text-slate-400">
+                  过期时间
+                </div>
+                <div
+                  id="valExpiresAt"
+                  class="mt-1 text-[20px] font-bold text-slate-800 dark:text-slate-100 font-mono"
+                >
+                  永久有效
+                </div>
+              </div>
+              <div>
+                <div class="text-[11px] text-slate-500 dark:text-slate-400">
+                  最后调用时间
+                </div>
+                <div
+                  id="valLastUsedAt"
+                  class="mt-1 text-[20px] font-bold text-slate-800 dark:text-slate-100 font-mono"
+                >
+                  从未调用
+                </div>
+              </div>
+            </div>
+          </div>
+
+          <!-- 最近调用流水 -->
+          <div
+            id="recentLogsBox"
+            class="rounded-xl border-2 border-slate-200 dark:border-night-line bg-white/70 dark:bg-night-inset p-4"
+          >
+            <div
+              class="flex items-center justify-between text-xs font-semibold text-slate-700 dark:text-slate-300 mb-3"
+            >
+              <span class="flex items-center gap-1.5">
+                <svg
+                  class="w-4 h-4 text-slate-400"
+                  fill="none"
+                  stroke="currentColor"
+                  stroke-width="2"
+                  viewBox="0 0 24 24"
+                >
+                  <path d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z" />
+                </svg>
+                最近调用
+              </span>
+              <span class="text-[11px] text-slate-400 dark:text-slate-500"
+                >最近 20 笔请求</span
+              >
+            </div>
+            <div class="overflow-x-auto">
+              <table
+                class="w-full text-left text-xs text-slate-700 dark:text-slate-300"
+              >
+                <thead>
+                  <tr
+                    class="border-b-2 border-slate-200 dark:border-night-line text-slate-400 dark:text-slate-500 text-[11px]"
+                  >
+                    <th class="pb-2 font-medium">时间</th>
+                    <th class="pb-2 font-medium">请求模型</th>
+                    <th class="pb-2 font-medium">调用分组</th>
+                    <th class="pb-2 font-medium">Tokens</th>
+                    <th class="pb-2 font-medium">耗时</th>
+                    <th class="pb-2 font-medium text-right">实际扣费</th>
+                  </tr>
+                </thead>
+                <tbody
+                  id="recentLogsTbody"
+                  class="divide-y divide-slate-100 dark:divide-night-line font-mono"
+                >
+                  <!-- 动态填充 -->
+                </tbody>
+              </table>
+            </div>
+          </div>
+        </div>
+      </section>
+
+      <!-- 客户端快速接入指引卡片 -->
+      <div class="flex items-center justify-between mb-4">
+        <h3
+          class="text-base font-bold text-slate-900 dark:text-white flex items-center gap-2"
+        >
+          <span>快速接入</span>
+          <span class="text-xs font-normal text-slate-500 dark:text-slate-400"
+            >点击复制 · 默认统一路由</span
+          >
+        </h3>
+      </div>
+      <div
+        class="rounded-2xl border-2 border-slate-200 dark:border-night-line bg-white/90 dark:bg-night-card backdrop-blur-xl p-5 mb-8 space-y-4 shadow-sm"
+      >
+        <div>
+          <div
+            class="text-xs font-semibold text-indigo-600 dark:text-indigo-400 mb-1.5"
+          >
+            Claude Code 终端环境变量配置
+          </div>
+          <div
+            onclick="
+              copyText(
+                document.getElementById('cmdClaudeCode').innerText,
+                '已复制 Claude Code 命令',
+                this,
+              )
+            "
+            class="group/url flex items-center justify-between bg-slate-100 dark:bg-night-inset border-2 border-slate-200 dark:border-night-line rounded-xl px-4 py-2.5 font-mono text-xs overflow-x-auto transition-all cursor-pointer hv"
+          >
+            <span
+              id="cmdClaudeCode"
+              class="text-slate-800 dark:text-slate-300 whitespace-nowrap mr-3 group-hover/url:text-indigo-600 dark:group-hover/url:text-indigo-300 transition-colors"
+              >export ANTHROPIC_BASE_URL=https://apiacc.itssx.com</span
+            >
+            <div
+              class="copy-icon-slot flex items-center gap-1.5 shrink-0 text-slate-400 group-hover/url:text-indigo-500 font-sans text-xs"
+            >
+              <svg
+                class="w-4 h-4"
+                fill="none"
+                stroke="currentColor"
+                stroke-width="2"
+                viewBox="0 0 24 24"
+              >
+                <path
+                  d="M8 16H6a2 2 0 01-2-2V6a2 2 0 012-2h8a2 2 0 012 2v2m-6 12h8a2 2 0 002-2v-8a2 2 0 00-2-2h-8a2 2 0 00-2 2v8a2 2 0 002 2z"
+                />
+              </svg>
+              <span>点击复制</span>
+            </div>
+          </div>
+        </div>
+        <div>
+          <div
+            class="text-xs font-semibold text-emerald-600 dark:text-emerald-400 mb-1.5"
+          >
+            NextChat / Cherry Studio / OpenAI 兼容端点 (/v1)
+          </div>
+          <div
+            onclick="
+              copyText(
+                document.getElementById('cmdOpenAI').innerText,
+                '已复制 OpenAI 端点',
+                this,
+              )
+            "
+            class="group/url flex items-center justify-between bg-slate-100 dark:bg-night-inset border-2 border-slate-200 dark:border-night-line rounded-xl px-4 py-2.5 font-mono text-xs overflow-x-auto transition-all cursor-pointer hv"
+          >
+            <span
+              id="cmdOpenAI"
+              class="text-slate-800 dark:text-slate-300 whitespace-nowrap mr-3 group-hover/url:text-indigo-600 dark:group-hover/url:text-indigo-300 transition-colors"
+              >https://apiacc.itssx.com/v1</span
+            >
+            <div
+              class="copy-icon-slot flex items-center gap-1.5 shrink-0 text-slate-400 group-hover/url:text-indigo-500 font-sans text-xs"
+            >
+              <svg
+                class="w-4 h-4"
+                fill="none"
+                stroke="currentColor"
+                stroke-width="2"
+                viewBox="0 0 24 24"
+              >
+                <path
+                  d="M8 16H6a2 2 0 01-2-2V6a2 2 0 012-2h8a2 2 0 012 2v2m-6 12h8a2 2 0 002-2v-8a2 2 0 00-2-2h-8a2 2 0 00-2 2v8a2 2 0 002 2z"
+                />
+              </svg>
+              <span>点击复制</span>
+            </div>
+          </div>
+        </div>
+      </div>
+
+      <!-- 分组接入列表与 URL 复制 (用户核心诉求) -->
+      <div
+        class="flex flex-col sm:flex-row sm:items-center justify-between gap-3 mb-4"
+      >
+        <div>
+          <h3
+            class="text-lg font-bold text-slate-900 dark:text-white flex items-center gap-2"
+          >
+            <span
+              >分组
+              <span id="groupsCount" class="text-slate-400 font-normal"
+                >16</span
+              ></span
+            >
+          </h3>
+          <p class="text-xs text-slate-500 dark:text-slate-400 mt-0.5">
+            点击地址即可复制。
+          </p>
+        </div>
+        <div class="flex items-center gap-2">
+          <input
+            type="text"
+            id="groupSearch"
+            placeholder="搜索分组名、协议或模型..."
+            oninput="renderGroups()"
+            class="h-9 px-3 text-xs rounded-xl border-2 border-slate-300 dark:border-night-line bg-white dark:bg-night-card text-slate-800 dark:text-slate-200 placeholder-slate-400 dark:placeholder-slate-500 hv"
+          />
+        </div>
+      </div>
+
+      <!-- 分组分类过滤 Tabs (border-2 状态按钮) -->
+      <div
+        class="flex gap-2 overflow-x-auto pb-3 mb-4 scrollbar-none"
+        id="filterTabs"
+      >
+        <!-- 由 renderFilterTabs() 按 Nexus 标签生成 -->
+      </div>
+
+      <!-- 分组网格列表 -->
+      <div
+        id="groupsGrid"
+        class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4"
+      >
+        <!-- 动态填充 -->
+      </div>
+    </div>
+
+    <!-- Toast 提示框 -->
+    <div
+      id="toast"
+      class="fixed bottom-6 right-6 hidden items-center gap-2.5 px-4 py-3 rounded-xl border-2 border-indigo-500/60 bg-slate-900/95 dark:bg-night-card text-white text-xs font-medium shadow-2xl shadow-black/80 z-50"
+    >
+      <svg
+        class="w-4 h-4 text-emerald-400 shrink-0"
+        fill="none"
+        stroke="currentColor"
+        stroke-width="2"
+        viewBox="0 0 24 24"
+      >
+        <path d="M20 6L9 17l-5-5" />
+      </svg>
+      <span id="toastMsg">已复制到剪贴板</span>
+    </div>
+
+    <script>
+      let allGroups = [];
+      let currentCategory = "all";
+      let allTags = [];
+      let currentRouteHost = "https://apiacc.itssx.com";
+      const selectedGroupProtocols = {};
+
+      // 主题切换函数 (支持 light / dark / system)
+      function setThemeMode(mode) {
+        localStorage.setItem("theme_mode", mode);
+        applyThemeFromStorage();
+      }
+
+      function applyThemeFromStorage() {
+        const mode = localStorage.getItem("theme_mode") || "system";
+        let isDark = false;
+        if (mode === "dark") {
+          isDark = true;
+        } else if (mode === "light") {
+          isDark = false;
+        } else {
+          isDark = window.matchMedia("(prefers-color-scheme: dark)").matches;
+        }
+
+        if (isDark) {
+          document.documentElement.classList.add("dark");
+        } else {
+          document.documentElement.classList.remove("dark");
+        }
+
+        // 更新按钮展示图标
+        const iconContainer = document.getElementById("activeThemeIcon");
+        if (iconContainer) {
+          if (mode === "light") {
+            iconContainer.innerHTML =
+              '<svg class="w-5 h-5 text-amber-500" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24"><circle cx="12" cy="12" r="5"/><path d="M12 1v2M12 21v2M4.22 4.22l1.42 1.42M18.36 18.36l1.42 1.42M1 12h2M21 12h2M4.22 19.78l1.42-1.42M18.36 5.64l1.42-1.42"/></svg>';
+          } else if (mode === "dark") {
+            iconContainer.innerHTML =
+              '<svg class="w-5 h-5 text-indigo-400" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24"><path d="M21 12.79A9 9 0 1111.21 3 7 7 0 0021 12.79z"/></svg>';
+          } else {
+            iconContainer.innerHTML =
+              '<svg class="w-5 h-5 text-slate-500 dark:text-slate-300" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24"><rect width="20" height="14" x="2" y="3" rx="2"/><path d="M8 21h8M12 17v4"/></svg>';
+          }
+        }
+
+        // 菜单项打勾状态
+        ["light", "dark", "system"].forEach((m) => {
+          const item = document.getElementById(
+            "itemTheme" + m.charAt(0).toUpperCase() + m.slice(1),
+          );
+          if (item) {
+            const check = item.querySelector(".check-mark");
+            if (check) {
+              check.className =
+                m === mode
+                  ? "check-mark text-indigo-500 font-bold"
+                  : "check-mark hidden";
+            }
+          }
+        });
+      }
+
+      // 全局居中气泡提示 (Toast)
+      function showToast(msg, type = "success") {
+        const toast = document.getElementById("toast");
+        const toastMsg = document.getElementById("toastMsg");
+        const toastIcon = document.getElementById("toastIcon");
+        if (!toast || !toastMsg) return;
+
+        toastMsg.innerText = msg;
+
+        // 样式分流：错误 (红粉) / 成功 (翡翠绿) / 提示 (靛蓝)
+        if (type === "error") {
+          toast.className =
+            "fixed top-8 left-1/2 -translate-x-1/2 flex items-center gap-2.5 px-5 py-3 rounded-2xl border-2 border-rose-500/50 bg-slate-900/95 dark:bg-night-card text-rose-300 shadow-2xl shadow-rose-950/40 text-xs sm:text-sm font-semibold z-[999] animate-fadeIn pointer-events-none";
+          if (toastIcon) {
+            toastIcon.innerHTML =
+              '<svg class="w-4 h-4 text-rose-400 shrink-0" fill="none" stroke="currentColor" stroke-width="2.5" viewBox="0 0 24 24"><circle cx="12" cy="12" r="10"/><path d="M12 8v4m0 4h.01"/></svg>';
+          }
+        } else if (type === "info") {
+          toast.className =
+            "fixed top-8 left-1/2 -translate-x-1/2 flex items-center gap-2.5 px-5 py-3 rounded-2xl border-2 border-indigo-500/50 bg-slate-900/95 dark:bg-night-card text-indigo-300 shadow-2xl shadow-indigo-950/40 text-xs sm:text-sm font-semibold z-[999] animate-fadeIn pointer-events-none";
+          if (toastIcon) {
+            toastIcon.innerHTML =
+              '<svg class="w-4 h-4 text-indigo-400 shrink-0" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24"><circle cx="12" cy="12" r="10"/><path d="M12 16v-4m0-4h.01"/></svg>';
+          }
+        } else {
+          toast.className =
+            "fixed top-8 left-1/2 -translate-x-1/2 flex items-center gap-2.5 px-5 py-3 rounded-2xl border-2 border-emerald-500/50 bg-slate-900/95 dark:bg-night-card text-emerald-300 shadow-2xl shadow-emerald-950/40 text-xs sm:text-sm font-semibold z-[999] animate-fadeIn pointer-events-none";
+          if (toastIcon) {
+            toastIcon.innerHTML =
+              '<svg class="w-4 h-4 text-emerald-400 shrink-0" fill="none" stroke="currentColor" stroke-width="2.5" viewBox="0 0 24 24"><path d="M20 6L9 17l-5-5"/></svg>';
+          }
+        }
+
+        clearTimeout(window._toastTimer);
+        window._toastTimer = setTimeout(() => {
+          toast.className = "fixed top-8 left-1/2 -translate-x-1/2 hidden";
+        }, 2400);
+      }
+
+      // 复制动效：仅右侧图标变绿打勾，不改变整体底色
+      function animateIconCheck(el) {
+        if (!el) return;
+        if (el._copyTimer) clearTimeout(el._copyTimer);
+
+        const slot = el.querySelector(".copy-icon-slot") || el;
+        if (!el._origSlotHtml) {
+          el._origSlotHtml = slot.innerHTML;
+        }
+
+        slot.innerHTML = `
+        <span class="inline-flex items-center gap-1 text-emerald-500 font-bold transition-all scale-105">
+          <svg class="w-4 h-4 text-emerald-500" fill="none" stroke="currentColor" stroke-width="2.5" viewBox="0 0 24 24"><path d="M20 6L9 17l-5-5"/></svg>
+          <span class="text-[11px] font-sans">已复制</span>
+        </span>
+      `;
+
+        el._copyTimer = setTimeout(() => {
+          slot.innerHTML = el._origSlotHtml;
+          el._origSlotHtml = null;
+          el._copyTimer = null;
+        }, 1500);
+      }
+
+      // 复制函数 (支持传入 triggerEl，仅右边打钩)
+      function copyText(text, successMsg, triggerEl) {
+        if (!text) return;
+        const el =
+          triggerEl || (window.event ? window.event.currentTarget : null);
+        if (el) animateIconCheck(el);
+
+        if (navigator.clipboard && navigator.clipboard.writeText) {
+          navigator.clipboard
+            .writeText(text)
+            .then(() => showToast(successMsg || "已复制到剪贴板"));
+        } else {
+          const ta = document.createElement("textarea");
+          ta.value = text;
+          ta.style.position = "fixed";
+          ta.style.opacity = "0";
+          document.body.appendChild(ta);
+          ta.select();
+          document.execCommand("copy");
+          document.body.removeChild(ta);
+          showToast(successMsg || "已复制到剪贴板");
+        }
+      }
+
+      function copyDynamic(elemId, msg, triggerEl) {
+        const elem = document.getElementById(elemId);
+        const el =
+          triggerEl || (window.event ? window.event.currentTarget : null);
+        if (elem) copyText(elem.innerText, msg, el);
+      }
+
+      // 线路切换联动 (纯数据联动，顶部卡片无任何边框切换)
+      function selectRoute(routeId) {
+        currentRouteHost =
+          routeId === "acc"
+            ? "https://apiacc.itssx.com"
+            : "https://api.itssx.com";
+        updateQuickCmds();
+        renderGroups();
+      }
+
+      function updateQuickCmds() {
+        const c1 = document.getElementById("cmdClaudeCode");
+        const c2 = document.getElementById("cmdOpenAI");
+        if (c1)
+          c1.innerText = `export ANTHROPIC_BASE_URL=${currentRouteHost}/api/claude_code/mixed_cc_pro_max`;
+        if (c2) c2.innerText = `${currentRouteHost}/api/codex_eco/v1`;
+      }
+
+      // 简易 Markdown 渲染（先整体转义再转换，不执行任何 HTML；链接仅允许 http/https）
+      function mdInline(t) {
+        return t
+          .replace(
+            /`([^`]+)`/g,
+            '<code class="px-1 py-0.5 rounded bg-white/70 dark:bg-night-inset font-mono text-[0.85em]">$1</code>',
+          )
+          .replace(
+            /\*\*([^*]+)\*\*/g,
+            '<strong class="font-semibold text-slate-900 dark:text-white">$1</strong>',
+          )
+          .replace(/(^|[^*])\*([^*\s][^*]*)\*/g, "$1<em>$2</em>")
+          .replace(/~~([^~]+)~~/g, "<del>$1</del>")
+          .replace(
+            /\[([^\]]+)\]\((https?:\/\/[^\s)]+)\)/g,
+            '<a href="$2" target="_blank" rel="noopener noreferrer" class="text-indigo-600 dark:text-indigo-300 underline underline-offset-2">$1</a>',
+          );
+      }
+      function renderMarkdown(md) {
+        const lines = esc(md).replace(/\r\n?/g, "\n").split("\n");
+        const out = [];
+        let para = [],
+          list = null,
+          code = null;
+        const flushPara = () => {
+          if (para.length)
+            out.push(`<p class="my-2">${mdInline(para.join("<br>"))}</p>`);
+          para = [];
+        };
+        const flushList = () => {
+          if (list)
+            out.push(
+              `<${list.tag} class="my-2 pl-5 space-y-1 ${list.tag === "ol" ? "list-decimal" : "list-disc"}">${list.items.map((i) => `<li>${mdInline(i)}</li>`).join("")}</${list.tag}>`,
+            );
+          list = null;
+        };
+        for (const line of lines) {
+          if (code) {
+            if (/^\s*```/.test(line)) {
+              out.push(
+                `<pre class="my-2 p-3 rounded-lg bg-white/70 dark:bg-night-inset font-mono text-xs overflow-x-auto">${code.join("\n")}</pre>`,
+              );
+              code = null;
+            } else code.push(line);
+            continue;
+          }
+          let m;
+          if (/^\s*```/.test(line)) {
+            flushPara();
+            flushList();
+            code = [];
+          } else if (!line.trim()) {
+            flushPara();
+            flushList();
+          } else if ((m = line.match(/^(#{1,6})\s+(.*)$/))) {
+            flushPara();
+            flushList();
+            const size =
+              m[1].length === 1
+                ? "text-lg"
+                : m[1].length === 2
+                  ? "text-base"
+                  : "text-sm";
+            out.push(
+              `<div class="${size} font-bold text-slate-900 dark:text-white mt-3 mb-1.5">${mdInline(m[2])}</div>`,
+            );
+          } else if (/^\s*([-*_])(\s*\1){2,}\s*$/.test(line)) {
+            flushPara();
+            flushList();
+            out.push('<hr class="my-3 border-indigo-500/20">');
+          } else if ((m = line.match(/^\s*(?:[-*+]|(\d+)\.)\s+(.*)$/))) {
+            flushPara();
+            const tag = m[1] ? "ol" : "ul";
+            if (!list || list.tag !== tag) {
+              flushList();
+              list = { tag, items: [] };
+            }
+            list.items.push(m[2]);
+          } else if ((m = line.match(/^\s*&gt;\s?(.*)$/))) {
+            flushPara();
+            flushList();
+            out.push(
+              `<blockquote class="my-2 pl-3 border-l-4 border-indigo-500/40 text-slate-500 dark:text-slate-400">${mdInline(m[1])}</blockquote>`,
+            );
+          } else {
+            flushList();
+            para.push(line.trim());
+          }
+        }
+        if (code)
+          out.push(
+            `<pre class="my-2 p-3 rounded-lg bg-white/70 dark:bg-night-inset font-mono text-xs overflow-x-auto">${code.join("\n")}</pre>`,
+          );
+        flushPara();
+        flushList();
+        return out.join("");
+      }
+      function setAnnouncementOpen(open) {
+        const box = document.getElementById("announcementBox");
+        box.classList.toggle("hidden", !open);
+        box.classList.toggle("flex", open);
+        document.body.classList.toggle("overflow-hidden", open); // 打开时锁定背景滚动
+      }
+      document.addEventListener("keydown", (e) => {
+        if (e.key === "Escape") setAnnouncementOpen(false);
+      });
+      function toggleAnnouncement() {
+        setAnnouncementOpen(
+          document
+            .getElementById("announcementBox")
+            .classList.contains("hidden"),
+        );
+      }
+      function renderAnnouncements(list) {
+        const box = document.getElementById("announcementBox");
+        const btn = document.getElementById("annoToggleBtn");
+        btn.classList.toggle("hidden", !list.length);
+        btn.classList.toggle("flex", !!list.length);
+        if (!list.length) setAnnouncementOpen(false);
+        // 最新一条的日期显示在「公告」那一行，其余公告的日期跟在各自标题右侧
+        document.getElementById("annoDate").innerText = list.length
+          ? list[0].created_at || ""
+          : "";
+        document.getElementById("annoList").innerHTML = list
+          .map((a, i) => {
+            // 正文以一级标题开头时，用该标题作为公告标题（避免重复），其余部分作为正文
+            const m = (a.content || "").match(/^\s*#\s+(.*)(?:\r?\n|$)/);
+            const title = m ? mdInline(esc(m[1])) : esc(a.title);
+            const body = renderMarkdown(
+              m ? a.content.slice(m[0].length) : a.content || "",
+            );
+            return `<article class="py-3 first:pt-0 last:pb-0">
+              <div class="flex items-center justify-between gap-3 mb-1">
+                <div class="text-lg font-bold text-slate-900 dark:text-white">${title}</div>
+                ${i ? `<span class="text-[11px] text-indigo-500 dark:text-indigo-400 font-mono shrink-0">${esc(a.created_at || "")}</span>` : ""}
+              </div>
+              <div class="text-sm text-slate-600 dark:text-slate-300 leading-relaxed">${body}</div>
+            </article>`;
+          })
+          .join("");
+      }
+
+      // 线路测速（参考 Nexus：请求各线路的 /api/common/healthz，由 nginx 直接返回、不经后端；
+      // 每条线路先预热 1 次建立连接，再测 3 次取中位数；单次 5 秒超时）
+      const SPEED_ROUTES = [
+        {
+          host: "https://apiacc.itssx.com",
+          dot: "pingDotAcc",
+          val: "pingValAcc",
+          best: "pingBestAcc",
+        },
+        {
+          host: "https://api.itssx.com",
+          dot: "pingDotDirect",
+          val: "pingValDirect",
+          best: "pingBestDirect",
+        },
+      ];
+      let speedRunning = false;
+      async function probeOnce(url) {
+        const ctl = new AbortController();
+        const timer = setTimeout(() => ctl.abort(), 5000);
+        const t0 = performance.now();
+        try {
+          const r = await fetch(url + "?_=" + Date.now() + Math.random(), {
+            cache: "no-store",
+            mode: "cors",
+            signal: ctl.signal,
+          });
+          await r.text();
+          return r.ok ? performance.now() - t0 : null;
+        } catch (_) {
+          return null;
+        } finally {
+          clearTimeout(timer);
+        }
+      }
+      async function measureRoute(route) {
+        const url = route.host + "/api/common/healthz";
+        await probeOnce(url);
+        const samples = [];
+        for (let i = 0; i < 3; i++) {
+          const ms = await probeOnce(url);
+          if (ms !== null) samples.push(ms);
+        }
+        samples.sort((a, b) => a - b);
+        return samples.length
+          ? Math.round(samples[Math.floor(samples.length / 2)])
+          : null;
+      }
+      async function runSpeedTest() {
+        if (speedRunning) return;
+        speedRunning = true;
+        SPEED_ROUTES.forEach((r) => {
+          document.getElementById(r.val).innerText = "测速中…";
+          document.getElementById(r.dot).className =
+            "w-2.5 h-2.5 rounded-full bg-slate-400 inline-block animate-pulse";
+          document.getElementById(r.best).classList.add("hidden");
+        });
+        const results = await Promise.all(SPEED_ROUTES.map(measureRoute));
+        results.forEach((ms, i) => {
+          const r = SPEED_ROUTES[i];
+          const color =
+            ms === null
+              ? "bg-rose-500"
+              : ms < 200
+                ? "bg-emerald-500"
+                : ms < 500
+                  ? "bg-amber-500"
+                  : "bg-rose-500";
+          document.getElementById(r.val).innerText =
+            ms === null ? "失败" : ms + "ms";
+          document.getElementById(r.dot).className =
+            "w-2.5 h-2.5 rounded-full inline-block " + color;
+        });
+        const ok = results.filter((ms) => ms !== null);
+        if (ok.length > 1) {
+          document
+            .getElementById(SPEED_ROUTES[results.indexOf(Math.min(...ok))].best)
+            .classList.remove("hidden");
+        }
+        speedRunning = false;
+      }
+
+      // HTML 转义：分组说明来自 Nexus、模型名来自用户请求，插入页面前一律转义
+      // 金额：千位分隔的财务格式，如 $12,345.6789
+      function usd(v, n = 4) {
+        return (
+          "$" +
+          Number(v || 0).toLocaleString("en-US", {
+            minimumFractionDigits: n,
+            maximumFractionDigits: n,
+          })
+        );
+      }
+      function esc(v) {
+        return String(v ?? "").replace(
+          /[&<>"']/g,
+          (c) =>
+            ({
+              "&": "&amp;",
+              "<": "&lt;",
+              ">": "&gt;",
+              '"': "&quot;",
+              "'": "&#39;",
+            })[c],
+        );
+      }
+      // 加载公共数据 (分组 + 公告)
+      async function loadPublicData() {
+        try {
+          const res = await fetch("/api/relay/public-info");
+          const json = await res.json();
+          if (json.code === 0 && json.data) {
+            allGroups = json.data.groups || [];
+            allTags = json.data.tags || [];
+            renderFilterTabs();
+            const countEl = document.getElementById("groupsCount");
+            if (countEl) countEl.innerText = allGroups.length;
+            renderGroups();
+
+            renderAnnouncements(json.data.announcements || []);
+          }
+        } catch (e) {
+          console.error("加载公共数据失败:", e);
+        }
+      }
+
+      // 切换卡片内激活的协议
+      function switchGroupProto(groupId, protoName) {
+        selectedGroupProtocols[groupId] = protoName;
+        renderGroups();
+      }
+
+      // 根据协议生成对应 URL 矩阵
+      function getProtoUrls(g, proto) {
+        const base = `${currentRouteHost}${g.path}`;
+        const v1 = `${currentRouteHost}${g.path}/v1`;
+
+        if (proto === "Claude") {
+          return [
+            {
+              label: "Claude Base URL",
+              val: base,
+              desc: "适用于常见支持自定义 Anthropic Base URL 的客户端",
+            },
+            {
+              label: "Claude Messages 端点",
+              val: `${base}/v1/messages`,
+              desc: "直接调用 Messages API",
+            },
+            {
+              label: "Claude Code 终端命令",
+              val: `export ANTHROPIC_BASE_URL=${base}`,
+              desc: "终端环境变量",
+            },
+          ];
+        } else if (proto === "OpenAI Chat") {
+          return [
+            {
+              label: "OpenAI Base URL (/v1)",
+              val: v1,
+              desc: "NextChat / Cherry Studio / SDK 基地址",
+            },
+            {
+              label: "Chat Completions 端点",
+              val: `${v1}/chat/completions`,
+              desc: "标准 OpenAI 聊天接口",
+            },
+            {
+              label: "终端环境变量",
+              val: `export OPENAI_BASE_URL=${v1}`,
+              desc: "OpenAI 客户端环境变量",
+            },
+          ];
+        } else if (proto === "Codex") {
+          return [
+            {
+              label: "Codex Base URL",
+              val: v1,
+              desc: "兼容 Responses / Codex CLI 基础端点",
+            },
+            {
+              label: "Responses 端点",
+              val: `${v1}/responses`,
+              desc: "Codex 新版 Responses 接口",
+            },
+            {
+              label: "终端环境变量",
+              val: `export OPENAI_BASE_URL=${v1}`,
+              desc: "Codex CLI 环境变量",
+            },
+          ];
+        } else if (proto === "Gemini") {
+          return [
+            {
+              label: "Gemini Base URL",
+              val: base,
+              desc: "Google Gemini 官方接入基地址",
+            },
+            {
+              label: "Gemini 端点前缀",
+              val: `${base}/v1beta`,
+              desc: "用于请求 generateContent",
+            },
+            {
+              label: "Gemini CLI 终端配置",
+              val: `export GOOGLE_GEMINI_BASE_URL=${base}`,
+              desc: "Gemini CLI 配置",
+            },
+          ];
+        } else if (proto === "生图") {
+          return [
+            {
+              label: "生图 Base URL (/v1)",
+              val: v1,
+              desc: "DALL-E / 图片生成服务基础地址",
+            },
+            {
+              label: "Images 端点",
+              val: `${v1}/images/generations`,
+              desc: "标准生成图片接口（按张计费）",
+            },
+            {
+              label: "终端环境变量",
+              val: `export OPENAI_BASE_URL=${v1}`,
+              desc: "图片客户端配置",
+            },
+          ];
+        }
+        return [{ label: "通用 Base URL", val: base, desc: "默认入口" }];
+      }
+
+      // 渲染分组卡片列表
+      function renderGroups() {
+        const container = document.getElementById("groupsGrid");
+        if (!container) return;
+        const search = (
+          document.getElementById("groupSearch")
+            ? document.getElementById("groupSearch").value
+            : ""
+        )
+          .trim()
+          .toLowerCase();
+
+        const filtered = allGroups.filter((g) => {
+          if (
+            currentCategory !== "all" &&
+            !(g.tags || []).some(
+              (t) => String(t.id) === String(currentCategory),
+            )
+          )
+            return false;
+          if (search) {
+            const matchName = (g.name || "").toLowerCase().includes(search);
+            const matchSlug = (g.slug || "").toLowerCase().includes(search);
+            const matchProto = (g.protocols || []).some((p) =>
+              p.toLowerCase().includes(search),
+            );
+            const matchNotice = (g.notice || "").toLowerCase().includes(search);
+            const matchModel = Object.values(g.models || {}).some((ms) =>
+              ms.some((m) => m.toLowerCase().includes(search)),
+            );
+            return (
+              matchName || matchSlug || matchProto || matchNotice || matchModel
+            );
+          }
+          return true;
+        });
+
+        if (filtered.length === 0) {
+          container.innerHTML =
+            '<div class="col-span-full text-center py-12 text-slate-500 text-xs">未找到符合条件的分组</div>';
+          return;
+        }
+
+        container.innerHTML = filtered
+          .map((g) => {
+            const protocols = g.protocols || ["OpenAI Chat"];
+            const activeProto = selectedGroupProtocols[g.id] || protocols[0];
+            const urls = getProtoUrls(g, activeProto);
+
+            const recBadge = g.is_recommended
+              ? '<span class="text-[10px] px-1.5 py-0.5 rounded bg-emerald-500/10 text-emerald-600 dark:text-emerald-400 border-2 border-emerald-500/20 font-bold">推荐</span>'
+              : "";
+
+            // 协议切换按钮 (点击展开该协议专属 URL)
+            const protoTabs = protocols
+              .map((p) => {
+                const isAct = p === activeProto;
+                const cls = isAct
+                  ? "px-2.5 py-1 rounded-lg border-2 border-indigo-500 bg-indigo-500/15 text-indigo-600 dark:text-indigo-400 font-bold text-xs shadow-sm cursor-pointer"
+                  : "px-2.5 py-1 rounded-lg border-2 border-slate-200 dark:border-night-line bg-slate-100 dark:bg-night-card text-slate-600 dark:text-slate-400 text-xs font-medium cursor-pointer transition-colors hv";
+                return `<button onclick="switchGroupProto(${g.id}, '${esc(p)}')" class="${cls}">${esc(p)}</button>`;
+              })
+              .join("");
+
+            // URL 列表：点击整行直接复制，右侧仅图标打钩，绝不变底色
+            const urlRows = urls
+              .map(
+                (u) => `
+          <div onclick="copyText('${u.val}', '已复制 ${u.label}', this)" class="group/url flex items-center justify-between p-2.5 rounded-xl border-2 border-slate-200 dark:border-night-line bg-slate-50/80 dark:bg-night-inset transition-all cursor-pointer hv">
+            <div class="flex-1 min-w-0 pr-3">
+              <div class="flex items-center gap-1.5 text-[11px] font-semibold text-slate-700 dark:text-slate-300 mb-0.5">
+                <span>${u.label}</span>
+              </div>
+              <div class="font-mono text-xs text-indigo-700 dark:text-sky-400 truncate select-all">
+                ${u.val}
+              </div>
+            </div>
+            <div class="copy-icon-slot shrink-0 flex items-center gap-1 text-slate-400 group-hover/url:text-indigo-500 text-xs font-sans transition-colors">
+              <svg class="w-3.5 h-3.5" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24"><path d="M8 16H6a2 2 0 01-2-2V6a2 2 0 012-2h8a2 2 0 012 2v2m-6 12h8a2 2 0 002-2v-8a2 2 0 00-2-2h-8a2 2 0 00-2 2v8a2 2 0 002 2z"/></svg>
+              <span class="text-[11px]">复制</span>
+            </div>
+          </div>
+        `,
+              )
+              .join("");
+
+            return `
+          <div class="rounded-2xl border-2 border-slate-200 dark:border-night-line bg-white/90 dark:bg-night-card backdrop-blur-xl p-5 transition-all flex flex-col justify-between hv">
+            <div>
+              <div class="flex items-start justify-between gap-2 mb-2">
+                <div class="flex items-center gap-1.5 font-bold text-sm text-slate-900 dark:text-slate-100">
+                  <span>${esc(g.display_name)}</span>
+                  ${(g.tags || []).map((t) => `<span class="text-[10px] px-1.5 py-0.5 rounded font-bold bg-slate-100 text-slate-600 dark:bg-night-hover dark:text-slate-200 dark:brightness-200" style="${tagStyle(t.color)}">${esc(t.name)}</span>`).join("")}${recBadge}${g.is_unified ? '<span class="text-[10px] px-1.5 py-0.5 rounded bg-indigo-500/10 text-indigo-600 dark:text-indigo-400 border-2 border-indigo-500/30 font-bold">默认 · 自动匹配</span>' : ""}${g.can_access === false ? '<span class="text-[10px] px-1.5 py-0.5 rounded bg-slate-100 dark:bg-night-card text-rose-500 border-2 border-slate-200 dark:border-night-line font-bold">无权限</span>' : ""}
+                </div>
+                <span class="text-xs font-mono font-bold px-2 py-0.5 rounded-lg bg-indigo-500/10 text-indigo-600 dark:text-indigo-400 border-2 border-indigo-500/30">
+                  ${g.is_unified ? "按命中分组" : g.user_rate_multiplier !== undefined ? esc(g.user_rate_multiplier) + "x（专属）" : esc(g.rate_multiplier) + "x"}
+                </span>
+              </div>
+
+              <!-- 分组说明 -->
+              <div class="text-xs text-slate-500 dark:text-slate-400 leading-relaxed mb-3">
+                ${esc(g.notice || "标准组合分组，支持多协议自动路由。")}
+              </div>
+              <details class="mb-3">
+                <summary class="text-[11px] font-semibold text-slate-400 cursor-pointer">可用模型 ${Number(g.model_count || 0)} 个（点击展开）</summary>
+                <div class="mt-1 text-[11px] font-mono text-slate-500 dark:text-slate-400 leading-relaxed">${Object.entries(
+                  g.models || {},
+                )
+                  .map(
+                    ([p, ms]) =>
+                      `<div><span class="font-semibold">${esc({ anthropic: "Claude", openai: "OpenAI/Codex", gemini: "Gemini" }[p] || p)}：</span>${ms.map(esc).join("、")}</div>`,
+                  )
+                  .join("")}</div>
+              </details>
+
+              <!-- 协议切换 Tabs (点击展开对应 URL) -->
+              <div class="mb-3">
+                <div class="text-[11px] font-semibold text-slate-400 mb-1.5 flex items-center justify-between">
+                  <span>支持协议 (点击切换对应 URL):</span>
+                  <span class="text-indigo-500 dark:text-indigo-400 font-bold">${activeProto}</span>
+                </div>
+                <div class="flex flex-wrap gap-1.5">
+                  ${protoTabs}
+                </div>
+              </div>
+
+              <!-- 对应协议的 URL 列表 (每一条点击直接复制，右侧仅打钩不改背景色) -->
+              <div class="space-y-2 mt-3 pt-3 border-t-2 border-slate-100 dark:border-night-line">
+                ${urlRows}
+              </div>
+            </div>
+          </div>
+        `;
+          })
+          .join("");
+      }
+
+      function tagStyle(c) {
+        const m = /^#([0-9a-f]{6})$/i.exec(c || "");
+        if (!m) return "";
+        const n = parseInt(m[1], 16),
+          lum =
+            (0.299 * (n >> 16) + 0.587 * ((n >> 8) & 255) + 0.114 * (n & 255)) /
+            255;
+        return lum < 0.08 ? "" : `color:${c};background:${c}1a`;
+      }
+      // 分组筛选：全部 + Nexus 标签（标签与颜色由后台同步入库），只显示有分组的标签
+      function renderFilterTabs() {
+        const box = document.getElementById("filterTabs");
+        if (!box) return;
+        const count = (id) =>
+          allGroups.filter((g) =>
+            (g.tags || []).some((t) => String(t.id) === String(id)),
+          ).length;
+        const items = [{ id: "all", name: "全部", n: allGroups.length }].concat(
+          allTags
+            .map((t) => ({
+              id: t.id,
+              name: t.name,
+              color: t.color,
+              n: count(t.id),
+            }))
+            .filter((t) => t.n > 0),
+        );
+        box.innerHTML = items
+          .map((t) => {
+            const act = String(t.id) === String(currentCategory);
+            const cls = act
+              ? "border-indigo-500 bg-indigo-600 text-white"
+              : "border-slate-200 dark:border-night-line bg-white dark:bg-night-card text-slate-600 dark:text-slate-300 hv";
+            const dot = t.color
+              ? `<span class="w-2 h-2 rounded-full inline-block ring-1 ring-slate-300 dark:ring-slate-500" style="background:${esc(t.color)}"></span>`
+              : "";
+            return `<button type="button" onclick="setCategory('${esc(t.id)}')" class="tab-btn flex items-center gap-1.5 px-3.5 py-1.5 rounded-full border-2 text-xs font-semibold whitespace-nowrap cursor-pointer ${cls}">${dot}${esc(t.name)}<span class="${act ? "text-white/70" : "text-slate-400"} font-normal">${t.n}</span></button>`;
+          })
+          .join("");
+      }
+      function setCategory(cat) {
+        currentCategory = cat;
+        renderFilterTabs();
+        renderGroups();
+      }
+
+      // 执行 Key 查询
+      async function doQuery() {
+        const input = document.getElementById("keyInput");
+        const key = (input.value || "").trim();
+        if (!key) {
+          showQueryError("请输入 API Key");
+          input.focus();
+          return;
+        }
+
+        showQueryError("");
+        hideKeyHistory();
+        const btn = document.getElementById("queryBtn");
+        const oldHtml = btn.innerHTML;
+        btn.innerHTML = "查询中...";
+        btn.disabled = true;
+
+        try {
+          const res = await fetch("/api/relay/key-query", {
+            headers: { Authorization: "Bearer " + key },
+            cache: "no-store",
+          });
+          const json = await res.json();
+
+          if (json.code !== 0 || !json.data) {
+            showQueryError(json.message || "API Key 不存在，请核对后再试");
+            return;
+          }
+
+          localStorage.setItem("s2a_saved_key", key);
+          saveKeyHistory(key);
+          const data = json.data;
+          const b = data.balance_info || {};
+          const k = data.key_info || {};
+          const r = data.rate_limits || {};
+          const logs = data.recent_logs || [];
+
+          // 1. 余额：Key 设了单独限额时按 Key 计算（剩余不超过账户余额），否则按账户计算
+          const fmt = usd;
+          const balance = Number(b.user_balance || 0);
+          let used, total, remain;
+          if (b.has_quota_limit && b.quota) {
+            used = Number(b.quota_used || 0);
+            total = Number(b.quota);
+            remain = Math.min(Number(b.quota_remain || 0), balance);
+            document.getElementById("statScope").innerText = "Key 限额";
+          } else {
+            used = Number(b.user_used || 0);
+            total = used + balance;
+            remain = balance;
+            document.getElementById("statScope").innerText = "账户余额";
+          }
+          document.getElementById("statUsed").innerText = fmt(used);
+          document.getElementById("statTotal").innerText = fmt(total);
+          document.getElementById("statRemain").innerText = fmt(remain);
+          document.getElementById("statRecharged").innerText = fmt(
+            b.total_recharged,
+            2,
+          );
+
+          // 3. Key 详细信息
+          document.getElementById("valKeyName").innerText = k.name || "-";
+          document.getElementById("valKeyStatus").innerText =
+            k.status_text || "正常生效";
+          document.getElementById("valKeyStatus").className =
+            k.status === "active"
+              ? "mt-1 text-[20px] font-bold text-emerald-600 dark:text-emerald-400"
+              : "mt-1 text-[20px] font-bold text-rose-500 dark:text-rose-400";
+          document.getElementById("valExpiresAt").innerText = k.expires_at
+            ? k.expires_at.split("T")[0]
+            : "永久有效";
+          document.getElementById("valLastUsedAt").innerText = k.last_used_at
+            ? k.last_used_at.replace("T", " ").split(".")[0]
+            : "从未调用";
+
+          // 4. 最近调用流水
+          const tbody = document.getElementById("recentLogsTbody");
+          if (logs.length > 0) {
+            tbody.innerHTML = logs
+              .map(
+                (l) => `
+            <tr class="hover:bg-slate-100/60 dark:hover:bg-night-hover transition-colors">
+              <td class="py-2.5 text-slate-500 dark:text-slate-400">${esc(l.time)}</td>
+              <td class="py-2.5 text-slate-800 dark:text-slate-200 font-semibold">${esc(l.model)}</td>
+              <td class="py-2.5 text-slate-600 dark:text-slate-400">${esc(l.group)}</td>
+              <td class="py-2.5 text-slate-600 dark:text-slate-400">${l.tokens}</td>
+              <td class="py-2.5 text-slate-600 dark:text-slate-400">${l.duration_ms}ms</td>
+              <td class="py-2.5 text-right font-semibold text-emerald-600 dark:text-emerald-400">${usd(l.cost, 5)}</td>
+            </tr>
+          `,
+              )
+              .join("");
+            document.getElementById("recentLogsBox").classList.remove("hidden");
+          } else {
+            tbody.innerHTML =
+              '<tr><td colspan="6" class="py-3 text-center text-slate-400 dark:text-slate-500">该 Key 暂无历史调用日志</td></tr>';
+          }
+
+          // 近 7 天用量统计
+          const old = document.getElementById("usageStatsBox");
+          if (old) old.remove();
+          const tbl = (title, heads, rows) => `
+          <div class="overflow-x-auto mt-3">
+            <div class="text-[11px] font-semibold text-slate-500 dark:text-slate-400 mb-1">${title}</div>
+            <table class="w-full text-left text-xs text-slate-700 dark:text-slate-300">
+              <thead><tr class="border-b-2 border-slate-200 dark:border-night-line text-slate-400 dark:text-slate-500 text-[11px]">${heads.map((h, i) => `<th class="pb-2 font-medium${i === heads.length - 1 ? " text-right" : ""}">${h}</th>`).join("")}</tr></thead>
+              <tbody class="divide-y divide-slate-100 dark:divide-night-line font-mono">${rows.length ? rows.map((r) => `<tr>${r.map((c, i) => `<td class="py-2 ${i === r.length - 1 ? "text-right font-semibold text-emerald-600 dark:text-emerald-400" : "text-slate-600 dark:text-slate-400"}">${c}</td>`).join("")}</tr>`).join("") : `<tr><td colspan="${heads.length}" class="py-3 text-center text-slate-400 dark:text-slate-500">暂无数据</td></tr>`}</tbody>
+            </table>
+          </div>`;
+          const money = (v) => usd(v, 5);
+          const statsHtml = `
+          <div id="usageStatsBox" class="rounded-xl border-2 border-slate-200 dark:border-night-line bg-white/70 dark:bg-night-inset p-4 mt-3">
+            <div class="flex items-center justify-between text-xs font-semibold text-slate-700 dark:text-slate-300">
+              <span>近 7 天用量</span>
+              <span class="text-[11px] text-slate-400 dark:text-slate-500">7 天共 ${Number(r.requests_7d || 0)} 次请求</span>
+            </div>
+            ${tbl(
+              "每日",
+              ["日期", "请求", "扣费"],
+              (data.daily || []).map((d) => [
+                esc(d.date),
+                d.requests,
+                money(d.cost),
+              ]),
+            )}
+            ${tbl(
+              "按分组",
+              ["分组", "请求", "Tokens", "扣费"],
+              (data.usage_by_group || []).map((x) => [
+                esc(x.group),
+                x.requests,
+                x.tokens,
+                money(x.cost),
+              ]),
+            )}
+            ${tbl(
+              "按模型（前 20）",
+              ["模型", "请求", "Tokens", "扣费"],
+              (data.usage_by_model || []).map((x) => [
+                esc(x.model),
+                x.requests,
+                x.tokens,
+                money(x.cost),
+              ]),
+            )}
+          </div>`;
+          document
+            .getElementById("recentLogsBox")
+            .insertAdjacentHTML("afterend", statsHtml);
+
+          document.getElementById("dashboard").classList.remove("hidden");
+
+          if (data.groups && data.groups.length) {
+            allGroups = data.groups;
+            renderFilterTabs();
+            renderGroups();
+          }
+        } catch (e) {
+          showQueryError("请求接口失败，请检查网络");
+        } finally {
+          btn.innerHTML = oldHtml;
+          btn.disabled = false;
+        }
+      }
+
+      // 查询错误提示（输入框上方）
+      function showQueryError(msg) {
+        document.getElementById("queryErrorMsg").innerText = msg;
+        const box = document.getElementById("queryError");
+        box.classList.toggle("hidden", !msg);
+        box.classList.toggle("flex", !!msg);
+      }
+
+      // 查询过的 Key 缓存在本机浏览器，聚焦输入框时列出（完整显示，最近的在前，最多 10 个）
+      const KEY_HISTORY = "s2a_key_history";
+      function loadKeyHistory() {
+        try {
+          const list = JSON.parse(localStorage.getItem(KEY_HISTORY) || "[]");
+          return Array.isArray(list)
+            ? list.filter((k) => typeof k === "string" && k)
+            : [];
+        } catch (_) {
+          return [];
+        }
+      }
+      function saveKeyHistory(key) {
+        const list = [key, ...loadKeyHistory().filter((k) => k !== key)].slice(
+          0,
+          10,
+        );
+        localStorage.setItem(KEY_HISTORY, JSON.stringify(list));
+      }
+      function removeKeyHistory(key) {
+        localStorage.setItem(
+          KEY_HISTORY,
+          JSON.stringify(loadKeyHistory().filter((k) => k !== key)),
+        );
+        if (localStorage.getItem("s2a_saved_key") === key)
+          localStorage.removeItem("s2a_saved_key");
+        showKeyHistory();
+      }
+      function hideKeyHistory() {
+        document.getElementById("keyHistory").classList.add("hidden");
+      }
+      function showKeyHistory() {
+        const box = document.getElementById("keyHistory");
+        const list = loadKeyHistory();
+        if (!list.length) return hideKeyHistory();
+        box.innerHTML =
+          '<div class="px-3 pt-1.5 pb-1 text-[11px] text-slate-400 dark:text-slate-500">查询过的 Key</div>' +
+          list
+            .map(
+              (k, i) => `
+        <div class="group flex items-center gap-2 px-3 py-2 hover:bg-indigo-50 dark:hover:bg-night-hover cursor-pointer" data-i="${i}">
+          <span class="flex-1 font-mono text-xs text-slate-700 dark:text-slate-200 break-all">${esc(k)}</span>
+          <button type="button" data-del="${i}" title="从记录中移除" class="shrink-0 w-6 h-6 rounded-md text-slate-400 hover:text-rose-500 hover:bg-rose-500/10 cursor-pointer">×</button>
+        </div>`,
+            )
+            .join("");
+        box.classList.remove("hidden");
+      }
+      document
+        .getElementById("keyHistory")
+        .addEventListener("mousedown", (e) => {
+          e.preventDefault(); // 保持输入框焦点
+          const list = loadKeyHistory();
+          const del = e.target.closest("[data-del]");
+          if (del) return removeKeyHistory(list[+del.dataset.del]);
+          const row = e.target.closest("[data-i]");
+          if (!row) return;
+          document.getElementById("keyInput").value = list[+row.dataset.i];
+          doQuery();
+        });
+
+      const keyInputEl = document.getElementById("keyInput");
+      keyInputEl.addEventListener("focus", showKeyHistory);
+      keyInputEl.addEventListener("blur", hideKeyHistory);
+      keyInputEl.addEventListener("input", () => showQueryError(""));
+      keyInputEl.addEventListener("keydown", (e) => {
+        if (e.key === "Enter") doQuery();
+        if (e.key === "Escape") hideKeyHistory();
+      });
+
+      window.addEventListener("DOMContentLoaded", () => {
+        // 初始化主题
+        applyThemeFromStorage();
+        window
+          .matchMedia("(prefers-color-scheme: dark)")
+          .addEventListener("change", () => {
+            const mode = localStorage.getItem("theme_mode") || "system";
+            if (mode === "system") applyThemeFromStorage();
+          });
+
+        const params = new URLSearchParams(window.location.search);
+        const urlKey = params.get("key");
+        if (urlKey) {
+          document.getElementById("keyInput").value = urlKey.trim();
+        } else {
+          const saved = localStorage.getItem("s2a_saved_key");
+          if (saved) {
+            document.getElementById("keyInput").value = saved;
+            if (!loadKeyHistory().includes(saved)) saveKeyHistory(saved);
+          }
+        }
+
+        loadPublicData();
+        runSpeedTest();
+
+        if (document.getElementById("keyInput").value) {
+          doQuery();
+        }
+      });
+    </script>
+  </body>
+</html>
diff --git a/relay/src/input.css b/relay/src/input.css
new file mode 100644
index 0000000..a30170c
--- /dev/null
+++ b/relay/src/input.css
@@ -0,0 +1,59 @@
+@import "tailwindcss";
+@custom-variant dark (&:where(.dark, .dark *));
+
+@theme {
+  --color-brand-50: #eef2ff;
+  --color-brand-100: #e0e7ff;
+  --color-brand-500: #6366f1;
+  --color-brand-600: #4f46e5;
+  /* 深色模式：深蓝灰（比纯黑更柔和），卡片比页面亮一档 */
+  --color-night-bg: #1c2638;
+  --color-night-inset: #1a2333;
+  --color-night-card: #243049;
+  --color-night-hover: #2d3b57;
+  --color-night-line: #3a4a68;
+}
+
+/* 统一悬停（参考 tailwindcss.com：悬停不加阴影、不改边框粗细，靠颜色变化）：
+   默认 2px 淡色边框；悬停时这圈 2px 边框变为主题色并轻微染底色。
+   不放进 @layer：未分层样式优先于 Tailwind 的 utilities 层，不会被元素自带的 border-* / bg-* 覆盖 */
+.hv {
+  transition: border-color 0.15s, background-color 0.15s, color 0.15s;
+}
+.hv:hover,
+.hv:focus-visible,
+input.hv:focus {
+  border-color: #6366f1;
+  background-color: rgba(99, 102, 241, 0.06);
+  box-shadow: none;
+  outline: none;
+}
+html.dark .hv:hover,
+html.dark .hv:focus-visible,
+html.dark input.hv:focus {
+  border-color: #818cf8;
+  background-color: rgba(129, 140, 248, 0.1);
+}
+
+html {
+  transition: background-color 0.25s ease, color 0.25s ease;
+}
+
+html.dark body {
+  background-color: var(--color-night-bg) !important;
+  color: #e2e8f0 !important;
+  background-image:
+    radial-gradient(at 0% 0%, rgba(99, 102, 241, 0.14) 0px, transparent 50%),
+    radial-gradient(at 100% 100%, rgba(56, 189, 248, 0.08) 0px, transparent 50%);
+  background-attachment: fixed;
+}
+
+html:not(.dark) body {
+  background-color: #f8fafc !important;
+  color: #0f172a !important;
+  background-image:
+    radial-gradient(at 0% 0%, rgba(99, 102, 241, 0.08) 0px, transparent 50%),
+    radial-gradient(at 100% 100%, rgba(16, 185, 129, 0.05) 0px, transparent 50%),
+    radial-gradient(at 50% 50%, rgba(139, 92, 246, 0.04) 0px, transparent 50%);
+  background-attachment: fixed;
+}
diff --git a/relay/src/refund.html b/relay/src/refund.html
new file mode 100644
index 0000000..affc423
--- /dev/null
+++ b/relay/src/refund.html
@@ -0,0 +1,1257 @@
+<!doctype html>
+<html lang="zh-CN" class="dark">
+  <head>
+    <meta charset="utf-8" />
+    <meta name="viewport" content="width=device-width, initial-scale=1" />
+    <meta name="robots" content="noindex, nofollow" />
+    <title>StarNexus - 退款登记</title>
+    <link
+      rel="icon"
+      type="image/svg+xml"
+      href="data:image/svg+xml,%3Csvg viewBox='0 0 48 48' xmlns='http://www.w3.org/2000/svg'%3E%3Cdefs%3E%3ClinearGradient id='snbg' x1='0' y1='0' x2='1' y2='1'%3E%3Cstop offset='0' stop-color='%236366f1'/%3E%3Cstop offset='1' stop-color='%238b5cf6'/%3E%3C/linearGradient%3E%3C/defs%3E%3Crect width='48' height='48' rx='12' fill='url(%23snbg)'/%3E%3Cpath d='M24 9.5l3.6 10.9L38.5 24l-10.9 3.6L24 38.5l-3.6-10.9L9.5 24l10.9-3.6z' fill='%23fff'/%3E%3Ccircle cx='35' cy='13' r='2.6' fill='%23fff' fill-opacity='.7'/%3E%3C/svg%3E"
+    />
+    <!-- 与查询页一致的主题初始化（读取同一个 theme_mode） -->
+    <script>
+      (function () {
+        const mode = localStorage.getItem("theme_mode") || "system";
+        const dark =
+          mode === "dark" ||
+          (mode === "system" &&
+            window.matchMedia("(prefers-color-scheme: dark)").matches);
+        document.documentElement.classList.toggle("dark", dark);
+      })();
+    </script>
+    <link rel="stylesheet" href="./tailwind.css" />
+  </head>
+  <body class="min-h-screen selection:bg-indigo-500 selection:text-white">
+    <div class="max-w-7xl mx-auto px-4 sm:px-6 py-6 pb-24">
+      <header
+        class="flex flex-wrap items-center justify-between gap-3 pb-5 mb-6 border-b-2 border-slate-200 dark:border-night-line"
+      >
+        <div class="flex items-center gap-3">
+          <a
+            href="/relay/key"
+            class="h-9 px-3 rounded-xl border-2 border-slate-300 dark:border-night-line bg-white dark:bg-night-card text-slate-700 dark:text-slate-200 text-xs font-medium flex items-center gap-1.5 hv"
+            >← 返回查询页</a
+          >
+          <h1
+            class="text-xl sm:text-2xl font-extrabold text-slate-900 dark:text-white"
+          >
+            退款登记
+          </h1>
+        </div>
+        <div class="flex items-center gap-2">
+          <div id="userBar" class="hidden items-center gap-2 text-xs">
+            <span class="text-slate-500 dark:text-slate-400">已登录：</span>
+            <span
+              id="userName"
+              class="font-semibold text-slate-800 dark:text-slate-100"
+            ></span>
+            <button
+              type="button"
+              onclick="showPassword(false)"
+              class="h-9 px-3 rounded-xl border-2 border-slate-300 dark:border-night-line bg-white dark:bg-night-card text-slate-700 dark:text-slate-200 font-medium cursor-pointer hv"
+            >
+              修改密码
+            </button>
+            <button
+              type="button"
+              onclick="logout()"
+              class="h-9 px-3 rounded-xl border-2 border-slate-300 dark:border-night-line bg-white dark:bg-night-card text-slate-700 dark:text-slate-200 font-medium cursor-pointer hv"
+            >
+              退出
+            </button>
+          </div>
+          <!-- 右上角主题切换下拉菜单 (支持白天模式、黑夜模式、跟随系统，带图标) -->
+          <div class="relative z-40 group/theme">
+            <button
+              id="themeTriggerBtn"
+              class="w-10 h-10 rounded-xl border-2 border-slate-300 dark:border-night-line bg-white dark:bg-night-card text-slate-700 dark:text-slate-200 flex items-center justify-center shadow-sm transition-all cursor-pointer hv"
+            >
+              <span id="activeThemeIcon">
+                <!-- 动态填充当前模式图标 -->
+                <svg
+                  class="w-5 h-5 text-indigo-400"
+                  fill="none"
+                  stroke="currentColor"
+                  stroke-width="2"
+                  viewBox="0 0 24 24"
+                >
+                  <path
+                    d="M12 3v1m0 16v1m9-9h-1M4 12H3m15.364 6.364l-.707-.707M6.343 6.343l-.707-.707m12.728 0l-.707.707M6.343 17.657l-.707.707M16 12a4 4 0 11-8 0 4 4 0 018 0z"
+                  />
+                </svg>
+              </span>
+            </button>
+
+            <!-- 下拉菜单：Hover 或点击显示 -->
+            <div
+              class="absolute right-0 top-full pt-2 hidden group-hover/theme:block hover:block z-50 animate-fadeIn"
+            >
+              <div
+                class="w-36 p-1.5 rounded-2xl border-2 border-slate-200 dark:border-night-line bg-white/95 dark:bg-night-card backdrop-blur-2xl shadow-2xl flex flex-col gap-1 text-xs"
+              >
+                <button
+                  onclick="setThemeMode('light')"
+                  id="itemThemeLight"
+                  class="flex items-center justify-between w-full px-3 py-2 rounded-xl transition-colors hover:bg-indigo-50 dark:hover:bg-night-hover text-slate-700 dark:text-slate-300 cursor-pointer"
+                >
+                  <span class="flex items-center gap-2">
+                    <svg
+                      class="w-4 h-4 text-amber-500"
+                      fill="none"
+                      stroke="currentColor"
+                      stroke-width="2"
+                      viewBox="0 0 24 24"
+                    >
+                      <circle cx="12" cy="12" r="5" />
+                      <path
+                        d="M12 1v2M12 21v2M4.22 4.22l1.42 1.42M18.36 18.36l1.42 1.42M1 12h2M21 12h2M4.22 19.78l1.42-1.42M18.36 5.64l1.42-1.42"
+                      />
+                    </svg>
+                    <span>白天模式</span>
+                  </span>
+                  <span class="check-mark hidden text-indigo-500 font-bold"
+                    >✓</span
+                  >
+                </button>
+
+                <button
+                  onclick="setThemeMode('dark')"
+                  id="itemThemeDark"
+                  class="flex items-center justify-between w-full px-3 py-2 rounded-xl transition-colors hover:bg-indigo-50 dark:hover:bg-night-hover text-slate-700 dark:text-slate-300 cursor-pointer"
+                >
+                  <span class="flex items-center gap-2">
+                    <svg
+                      class="w-4 h-4 text-indigo-400"
+                      fill="none"
+                      stroke="currentColor"
+                      stroke-width="2"
+                      viewBox="0 0 24 24"
+                    >
+                      <path d="M21 12.79A9 9 0 1111.21 3 7 7 0 0021 12.79z" />
+                    </svg>
+                    <span>黑夜模式</span>
+                  </span>
+                  <span class="check-mark hidden text-indigo-500 font-bold"
+                    >✓</span
+                  >
+                </button>
+
+                <button
+                  onclick="setThemeMode('system')"
+                  id="itemThemeSystem"
+                  class="flex items-center justify-between w-full px-3 py-2 rounded-xl transition-colors hover:bg-indigo-50 dark:hover:bg-night-hover text-slate-700 dark:text-slate-300 cursor-pointer"
+                >
+                  <span class="flex items-center gap-2">
+                    <svg
+                      class="w-4 h-4 text-slate-500 dark:text-slate-400"
+                      fill="none"
+                      stroke="currentColor"
+                      stroke-width="2"
+                      viewBox="0 0 24 24"
+                    >
+                      <rect width="20" height="14" x="2" y="3" rx="2" />
+                      <path d="M8 21h8M12 17v4" />
+                    </svg>
+                    <span>跟随系统</span>
+                  </span>
+                  <span class="check-mark hidden text-indigo-500 font-bold"
+                    >✓</span
+                  >
+                </button>
+              </div>
+            </div>
+          </div>
+        </div>
+      </header>
+
+      <!-- 登录 -->
+      <section
+        id="loginView"
+        class="hidden max-w-sm mx-auto rounded-2xl border-2 border-slate-200 dark:border-night-line bg-white/90 dark:bg-night-card p-6 sm:p-8 shadow-xl shadow-slate-200/50"
+      >
+        <h2 class="text-lg font-bold text-slate-900 dark:text-white mb-1">
+          登录
+        </h2>
+        <p class="text-xs text-slate-500 dark:text-slate-400 mb-5">
+          退款登记账号由服务器管理员创建，与 sub2api 后台账号无关。
+        </p>
+        <form
+          onsubmit="
+            event.preventDefault();
+            doLogin();
+          "
+          class="flex flex-col gap-3"
+        >
+          <input
+            id="loginUser"
+            autocomplete="username"
+            placeholder="账号"
+            class="h-11 px-4 rounded-xl border border-slate-300 dark:border-night-line bg-white dark:bg-night-inset text-slate-900 dark:text-slate-100 placeholder-slate-400 dark:placeholder-slate-500 text-sm outline-none hover:border-indigo-400 focus:border-indigo-500 focus:ring-4 focus:ring-indigo-500/20"
+          />
+          <input
+            id="loginPass"
+            type="password"
+            autocomplete="current-password"
+            placeholder="密码"
+            class="h-11 px-4 rounded-xl border border-slate-300 dark:border-night-line bg-white dark:bg-night-inset text-slate-900 dark:text-slate-100 placeholder-slate-400 dark:placeholder-slate-500 text-sm outline-none hover:border-indigo-400 focus:border-indigo-500 focus:ring-4 focus:ring-indigo-500/20"
+          />
+          <p
+            id="loginMsg"
+            role="alert"
+            class="min-h-4 text-xs font-medium text-rose-600 dark:text-rose-400"
+          ></p>
+          <button
+            id="loginBtn"
+            class="h-11 rounded-xl bg-indigo-600 hover:bg-indigo-500 text-white font-medium text-sm shadow-lg shadow-indigo-600/25 active:scale-95 transition-all cursor-pointer disabled:opacity-50 disabled:cursor-not-allowed"
+          >
+            登录
+          </button>
+        </form>
+      </section>
+
+      <!-- 修改密码（首次登录强制） -->
+      <section
+        id="pwView"
+        class="hidden max-w-sm mx-auto rounded-2xl border-2 border-indigo-500/40 bg-white/90 dark:bg-night-card p-6 sm:p-8 shadow-xl shadow-slate-200/50"
+      >
+        <h2 class="text-lg font-bold text-slate-900 dark:text-white mb-1">
+          修改密码
+        </h2>
+        <p id="pwHint" class="text-xs text-slate-500 dark:text-slate-400 mb-5">
+          新密码至少 10 位。
+        </p>
+        <form
+          onsubmit="
+            event.preventDefault();
+            doChangePassword();
+          "
+          class="flex flex-col gap-3"
+        >
+          <input
+            id="pwOld"
+            type="password"
+            autocomplete="current-password"
+            placeholder="原密码"
+            class="h-11 px-4 rounded-xl border border-slate-300 dark:border-night-line bg-white dark:bg-night-inset text-slate-900 dark:text-slate-100 placeholder-slate-400 dark:placeholder-slate-500 text-sm outline-none hover:border-indigo-400 focus:border-indigo-500 focus:ring-4 focus:ring-indigo-500/20"
+          />
+          <input
+            id="pwNew"
+            type="password"
+            autocomplete="new-password"
+            placeholder="新密码（至少 10 位）"
+            class="h-11 px-4 rounded-xl border border-slate-300 dark:border-night-line bg-white dark:bg-night-inset text-slate-900 dark:text-slate-100 placeholder-slate-400 dark:placeholder-slate-500 text-sm outline-none hover:border-indigo-400 focus:border-indigo-500 focus:ring-4 focus:ring-indigo-500/20"
+          />
+          <input
+            id="pwNew2"
+            type="password"
+            autocomplete="new-password"
+            placeholder="再输入一次新密码"
+            class="h-11 px-4 rounded-xl border border-slate-300 dark:border-night-line bg-white dark:bg-night-inset text-slate-900 dark:text-slate-100 placeholder-slate-400 dark:placeholder-slate-500 text-sm outline-none hover:border-indigo-400 focus:border-indigo-500 focus:ring-4 focus:ring-indigo-500/20"
+          />
+          <p
+            id="pwMsg"
+            role="alert"
+            class="min-h-4 text-xs font-medium text-rose-600 dark:text-rose-400"
+          ></p>
+          <div class="flex gap-2">
+            <button
+              id="pwBtn"
+              class="flex-1 h-11 rounded-xl bg-indigo-600 hover:bg-indigo-500 text-white font-medium text-sm active:scale-95 transition-all cursor-pointer disabled:opacity-50 disabled:cursor-not-allowed"
+            >
+              保存新密码
+            </button>
+            <button
+              id="pwCancel"
+              type="button"
+              onclick="showMain()"
+              class="h-11 px-5 rounded-xl border-2 border-slate-200 dark:border-night-line text-slate-600 dark:text-slate-300 text-sm cursor-pointer hv"
+            >
+              取消
+            </button>
+          </div>
+        </form>
+      </section>
+
+      <!-- 订单列表 -->
+      <section id="mainView" class="hidden">
+        <form
+          onsubmit="
+            event.preventDefault();
+            loadOrders(1);
+          "
+          class="grid grid-cols-2 md:grid-cols-4 lg:grid-cols-8 gap-2 mb-3"
+        >
+          <input
+            id="fQ"
+            placeholder="订单号 / 客户 ID / 邮箱 / 交易号"
+            class="col-span-2 h-10 px-3 rounded-xl border border-slate-300 dark:border-night-line bg-white dark:bg-night-inset text-slate-900 dark:text-slate-100 placeholder-slate-400 dark:placeholder-slate-500 text-sm outline-none hover:border-indigo-400 focus:border-indigo-500 focus:ring-4 focus:ring-indigo-500/20"
+          />
+          <select
+            id="fStatus"
+            class="h-10 px-3 rounded-xl border border-slate-300 dark:border-night-line bg-white dark:bg-night-inset text-slate-900 dark:text-slate-100 text-sm outline-none focus:border-indigo-500"
+          >
+            <option value="">全部状态</option>
+            <option
+              value="COMPLETED,PARTIALLY_REFUNDED,REFUND_REQUESTED,REFUND_FAILED"
+            >
+              可退款
+            </option>
+            <option value="COMPLETED">已完成</option>
+            <option value="PARTIALLY_REFUNDED">部分退款</option>
+            <option value="REFUNDED">已退款</option>
+            <option value="PENDING">待支付</option>
+            <option value="CANCELLED,EXPIRED">已取消/过期</option>
+            <option value="FAILED">失败</option>
+          </select>
+          <select
+            id="fPay"
+            class="h-10 px-3 rounded-xl border border-slate-300 dark:border-night-line bg-white dark:bg-night-inset text-slate-900 dark:text-slate-100 text-sm outline-none focus:border-indigo-500"
+          >
+            <option value="">全部支付方式</option>
+            <option value="wxpay">微信</option>
+            <option value="alipay">支付宝</option>
+          </select>
+          <select
+            id="fRefunded"
+            class="h-10 px-3 rounded-xl border border-slate-300 dark:border-night-line bg-white dark:bg-night-inset text-slate-900 dark:text-slate-100 text-sm outline-none focus:border-indigo-500"
+          >
+            <option value="">退款不限</option>
+            <option value="1">有退款</option>
+            <option value="0">无退款</option>
+          </select>
+          <input
+            id="fFrom"
+            type="date"
+            title="下单日期起"
+            class="h-10 px-3 rounded-xl border border-slate-300 dark:border-night-line bg-white dark:bg-night-inset text-slate-900 dark:text-slate-100 text-sm outline-none focus:border-indigo-500"
+          />
+          <input
+            id="fTo"
+            type="date"
+            title="下单日期止"
+            class="h-10 px-3 rounded-xl border border-slate-300 dark:border-night-line bg-white dark:bg-night-inset text-slate-900 dark:text-slate-100 text-sm outline-none focus:border-indigo-500"
+          />
+          <div class="col-span-2 md:col-span-4 lg:col-span-8 flex gap-2">
+            <button
+              class="h-10 px-5 rounded-xl bg-indigo-600 hover:bg-indigo-500 text-white font-medium text-sm active:scale-95 transition-all cursor-pointer"
+            >
+              查询
+            </button>
+            <button
+              type="button"
+              onclick="resetFilters()"
+              class="h-10 px-4 rounded-xl border-2 border-slate-200 dark:border-night-line text-slate-600 dark:text-slate-300 text-sm cursor-pointer hv"
+            >
+              重置
+            </button>
+            <button
+              type="button"
+              onclick="openNew()"
+              class="h-10 px-4 rounded-xl bg-amber-500 hover:bg-amber-400 text-white font-medium text-sm active:scale-95 transition-all cursor-pointer"
+            >
+              + 新增登记
+            </button>
+            <span
+              id="summary"
+              class="ml-auto self-center text-xs text-slate-500 dark:text-slate-400"
+            ></span>
+          </div>
+        </form>
+
+        <div
+          class="rounded-2xl border-2 border-slate-200 dark:border-night-line bg-white/90 dark:bg-night-card overflow-x-auto"
+        >
+          <table class="w-full text-xs whitespace-nowrap">
+            <thead
+              class="text-slate-500 dark:text-slate-400 bg-slate-50 dark:bg-night-inset"
+            >
+              <tr>
+                <th class="px-3 py-2.5 text-left font-medium">订单号</th>
+                <th class="px-3 py-2.5 text-left font-medium">下单时间</th>
+                <th class="px-3 py-2.5 text-left font-medium">客户</th>
+                <th class="px-3 py-2.5 text-left font-medium">支付</th>
+                <th class="px-3 py-2.5 text-right font-medium">实付</th>
+                <th class="px-3 py-2.5 text-right font-medium">到账余额</th>
+                <th class="px-3 py-2.5 text-left font-medium">状态</th>
+                <th class="px-3 py-2.5 text-right font-medium">已退</th>
+                <th class="px-3 py-2.5 text-right font-medium">操作</th>
+              </tr>
+            </thead>
+            <tbody
+              id="orderRows"
+              class="text-slate-700 dark:text-slate-200"
+            ></tbody>
+          </table>
+        </div>
+
+        <div
+          class="flex flex-wrap items-center justify-between gap-2 mt-3 text-xs text-slate-500 dark:text-slate-400"
+        >
+          <div class="flex items-center gap-2">
+            每页
+            <select
+              id="fSize"
+              onchange="loadOrders(1)"
+              class="h-8 px-2 rounded-lg border border-slate-300 dark:border-night-line bg-white dark:bg-night-inset text-slate-900 dark:text-slate-100"
+            >
+              <option>20</option>
+              <option>50</option>
+              <option>100</option>
+            </select>
+          </div>
+          <div class="flex items-center gap-2">
+            <button
+              id="prevBtn"
+              type="button"
+              onclick="loadOrders(page - 1)"
+              class="h-8 px-3 rounded-lg border-2 border-slate-200 dark:border-night-line cursor-pointer hv disabled:opacity-40 disabled:cursor-not-allowed"
+            >
+              上一页
+            </button>
+            <span id="pageInfo"></span>
+            <button
+              id="nextBtn"
+              type="button"
+              onclick="loadOrders(page + 1)"
+              class="h-8 px-3 rounded-lg border-2 border-slate-200 dark:border-night-line cursor-pointer hv disabled:opacity-40 disabled:cursor-not-allowed"
+            >
+              下一页
+            </button>
+          </div>
+        </div>
+      </section>
+    </div>
+
+    <!-- 订单详情与退款 -->
+    <div
+      id="orderModal"
+      role="dialog"
+      aria-modal="true"
+      onclick="if (event.target === this) closeOrder();"
+      class="hidden fixed inset-0 z-50 items-start sm:items-center justify-center p-4 bg-slate-900/50 backdrop-blur-sm overflow-y-auto"
+    >
+      <div
+        class="w-full max-w-4xl rounded-2xl border-2 border-slate-200 dark:border-night-line bg-white dark:bg-night-card p-5 sm:p-6 shadow-2xl"
+      >
+        <div class="flex items-center justify-between mb-4">
+          <h3
+            id="modalTitle"
+            class="text-lg font-bold text-slate-900 dark:text-white"
+          ></h3>
+          <button
+            type="button"
+            onclick="closeOrder()"
+            aria-label="关闭"
+            class="w-9 h-9 rounded-xl border-2 border-slate-200 dark:border-night-line text-slate-500 cursor-pointer hv"
+          >
+            ×
+          </button>
+        </div>
+        <div
+          id="modalFacts"
+          class="grid grid-cols-2 sm:grid-cols-4 gap-2 mb-4 text-xs"
+        ></div>
+        <div id="modalHistory" class="mb-4"></div>
+        <div
+          id="refundForm"
+          class="hidden pt-4 border-t-2 border-dashed border-slate-200 dark:border-night-line"
+        >
+          <div class="flex flex-col sm:flex-row gap-2 mb-2">
+            <div class="relative sm:w-56">
+              <span
+                class="absolute left-3 top-1/2 -translate-y-1/2 text-slate-400 text-sm"
+                >¥</span
+              >
+              <input
+                id="refundCny"
+                type="number"
+                min="0.01"
+                step="0.01"
+                placeholder="实际退款人民币"
+                class="w-full h-11 pl-7 pr-3 rounded-xl border border-slate-300 dark:border-night-line bg-white dark:bg-night-inset text-slate-900 dark:text-slate-100 placeholder-slate-400 dark:placeholder-slate-500 font-mono text-sm outline-none hover:border-indigo-400 focus:border-indigo-500 focus:ring-4 focus:ring-indigo-500/20"
+              />
+            </div>
+            <input
+              id="refundReason"
+              maxlength="200"
+              placeholder="原因（可选，如：易支付客服退款）"
+              class="flex-1 h-11 px-3 rounded-xl border border-slate-300 dark:border-night-line bg-white dark:bg-night-inset text-slate-900 dark:text-slate-100 placeholder-slate-400 dark:placeholder-slate-500 text-sm outline-none hover:border-indigo-400 focus:border-indigo-500 focus:ring-4 focus:ring-indigo-500/20"
+            />
+          </div>
+          <p
+            id="refundCalc"
+            class="min-h-5 text-xs text-slate-600 dark:text-slate-300 mb-3"
+          ></p>
+          <div class="flex flex-wrap items-center gap-2">
+            <button
+              id="refundBtn"
+              type="button"
+              onclick="submitRefund()"
+              disabled
+              class="h-11 px-5 rounded-xl bg-amber-500 hover:bg-amber-400 text-white font-medium text-sm active:scale-95 transition-all cursor-pointer disabled:opacity-50 disabled:cursor-not-allowed"
+            >
+              登记退款
+            </button>
+            <button
+              id="refundCancel"
+              type="button"
+              onclick="resetConfirm()"
+              class="hidden h-11 px-5 rounded-xl border-2 border-slate-200 dark:border-night-line text-slate-600 dark:text-slate-300 text-sm cursor-pointer hv"
+            >
+              取消
+            </button>
+            <span class="text-xs text-slate-400 dark:text-slate-500"
+              >先在支付平台退款成功，再在这里登记。</span
+            >
+          </div>
+        </div>
+        <p
+          id="refundBlocked"
+          class="hidden text-xs font-medium text-slate-500 dark:text-slate-400"
+        ></p>
+        <p
+          id="modalMsg"
+          role="alert"
+          class="hidden mt-3 text-xs font-medium"
+        ></p>
+      </div>
+    </div>
+
+    <!-- 新增登记：输入订单号 -->
+    <div
+      id="newDialog"
+      role="dialog"
+      aria-modal="true"
+      onclick="if (event.target === this) closeNew();"
+      class="hidden fixed inset-0 z-50 items-center justify-center p-4 bg-slate-900/50 backdrop-blur-sm"
+    >
+      <form
+        onsubmit="
+          event.preventDefault();
+          goNew();
+        "
+        class="w-full max-w-sm rounded-2xl border-2 border-indigo-500/40 bg-white dark:bg-night-card p-6 shadow-2xl flex flex-col gap-3"
+      >
+        <h3 class="text-lg font-bold text-slate-900 dark:text-white">
+          新增退款登记
+        </h3>
+        <p class="text-xs text-slate-500 dark:text-slate-400">
+          输入订单号（也可以直接在列表里点订单）。
+        </p>
+        <input
+          id="newOrderId"
+          inputmode="numeric"
+          placeholder="订单号"
+          autocomplete="off"
+          class="h-11 px-4 rounded-xl border border-slate-300 dark:border-night-line bg-white dark:bg-night-inset text-slate-900 dark:text-slate-100 placeholder-slate-400 dark:placeholder-slate-500 font-mono text-sm outline-none hover:border-indigo-400 focus:border-indigo-500 focus:ring-4 focus:ring-indigo-500/20"
+        />
+        <p
+          id="newMsg"
+          role="alert"
+          class="min-h-4 text-xs font-medium text-rose-600 dark:text-rose-400"
+        ></p>
+        <div class="flex gap-2">
+          <button
+            class="flex-1 h-11 rounded-xl bg-indigo-600 hover:bg-indigo-500 text-white font-medium text-sm active:scale-95 transition-all cursor-pointer"
+          >
+            下一步
+          </button>
+          <button
+            type="button"
+            onclick="closeNew()"
+            class="h-11 px-5 rounded-xl border-2 border-slate-200 dark:border-night-line text-slate-600 dark:text-slate-300 text-sm cursor-pointer hv"
+          >
+            取消
+          </button>
+        </div>
+      </form>
+    </div>
+
+    <script>
+      const API = "/api/relay/refund";
+      const STATUS = {
+        PENDING: "待支付",
+        PAID: "已支付",
+        RECHARGING: "充值中",
+        COMPLETED: "已完成",
+        CANCELLED: "已取消",
+        EXPIRED: "已过期",
+        FAILED: "失败",
+        REFUND_REQUESTED: "申请退款中",
+        REFUNDING: "退款中",
+        REFUND_PENDING: "退款处理中",
+        PARTIALLY_REFUNDED: "部分退款",
+        REFUNDED: "已退款",
+        REFUND_FAILED: "退款失败",
+      };
+      // 状态徽标颜色（完整类名，便于 Tailwind 扫描生成）
+      const STATUS_CLASS = {
+        COMPLETED: "bg-emerald-500/10 text-emerald-600 dark:text-emerald-400",
+        PARTIALLY_REFUNDED:
+          "bg-amber-500/10 text-amber-600 dark:text-amber-400",
+        REFUNDED: "bg-rose-500/10 text-rose-600 dark:text-rose-400",
+      };
+      const PAY = { wxpay: "微信", alipay: "支付宝" };
+      let page = 1;
+      let current = null;
+      let confirming = false;
+      let mustChange = false;
+
+      function esc(v) {
+        return String(v ?? "").replace(
+          /[&<>"']/g,
+          (c) =>
+            ({
+              "&": "&amp;",
+              "<": "&lt;",
+              ">": "&gt;",
+              '"': "&quot;",
+              "'": "&#39;",
+            })[c],
+        );
+      }
+      const yuan = (v) => "¥" + Number(v || 0).toFixed(2);
+      const usd = (v, n = 2) => "$" + Number(v || 0).toFixed(n);
+      const when = (t) =>
+        t ? new Date(t).toLocaleString("zh-CN", { hour12: false }) : "—";
+
+      async function api(path, opts = {}) {
+        const r = await fetch(API + path, {
+          credentials: "same-origin",
+          ...opts,
+          headers: {
+            "X-Requested-With": "s2a-refund",
+            ...(opts.body ? { "Content-Type": "application/json" } : {}),
+          },
+        }).catch(() => null);
+        if (!r)
+          return {
+            ok: false,
+            status: 0,
+            body: { message: "网络错误，请稍后再试" },
+          };
+        const body = await r.json().catch(() => ({}));
+        if (r.status === 401 && path !== "/login") showLogin();
+        if (r.status === 403 && body.code === "must_change") showPassword(true);
+        return { ok: r.ok, status: r.status, body };
+      }
+
+      function only(id) {
+        for (const v of ["loginView", "pwView", "mainView"]) {
+          document.getElementById(v).classList.toggle("hidden", v !== id);
+        }
+      }
+      function setUser(name) {
+        const bar = document.getElementById("userBar");
+        document.getElementById("userName").textContent = name || "";
+        bar.classList.toggle("hidden", !name);
+        bar.classList.toggle("flex", !!name);
+      }
+      function showLogin() {
+        setUser("");
+        closeOrder();
+        only("loginView");
+        document.getElementById("loginUser").focus();
+      }
+      function showPassword(forced) {
+        mustChange = forced;
+        closeOrder();
+        only("pwView");
+        document.getElementById("pwHint").textContent = forced
+          ? "首次登录请先设置新密码（至少 10 位）。"
+          : "新密码至少 10 位，修改后其他设备上的登录会失效。";
+        document.getElementById("pwCancel").classList.toggle("hidden", forced);
+        for (const id of ["pwOld", "pwNew", "pwNew2"])
+          document.getElementById(id).value = "";
+        document.getElementById("pwMsg").textContent = "";
+      }
+      function showMain() {
+        only("mainView");
+        loadOrders(page);
+      }
+
+      async function doLogin() {
+        const btn = document.getElementById("loginBtn");
+        const msg = document.getElementById("loginMsg");
+        msg.textContent = "";
+        btn.disabled = true;
+        const { ok, body } = await api("/login", {
+          method: "POST",
+          body: JSON.stringify({
+            username: document.getElementById("loginUser").value,
+            password: document.getElementById("loginPass").value,
+          }),
+        });
+        btn.disabled = false;
+        document.getElementById("loginPass").value = "";
+        if (!ok) return (msg.textContent = body.message || "登录失败");
+        setUser(body.data.username);
+        body.data.must_change ? showPassword(true) : showMain();
+      }
+
+      async function logout() {
+        await api("/logout", { method: "POST" });
+        showLogin();
+      }
+
+      async function doChangePassword() {
+        const msg = document.getElementById("pwMsg");
+        const n1 = document.getElementById("pwNew").value;
+        if (n1.length < 10) return (msg.textContent = "新密码至少 10 位");
+        if (n1 !== document.getElementById("pwNew2").value)
+          return (msg.textContent = "两次输入的新密码不一致");
+        const btn = document.getElementById("pwBtn");
+        btn.disabled = true;
+        const { ok, body } = await api("/password", {
+          method: "POST",
+          body: JSON.stringify({
+            old: document.getElementById("pwOld").value,
+            new: n1,
+          }),
+        });
+        btn.disabled = false;
+        if (!ok) return (msg.textContent = body.message || "修改失败");
+        mustChange = false;
+        showMain();
+      }
+
+      function resetFilters() {
+        for (const id of ["fQ", "fStatus", "fPay", "fRefunded", "fFrom", "fTo"])
+          document.getElementById(id).value = "";
+        loadOrders(1);
+      }
+
+      async function loadOrders(p) {
+        page = Math.max(1, p || 1);
+        const params = new URLSearchParams({
+          page,
+          size: document.getElementById("fSize").value,
+          q: document.getElementById("fQ").value.trim(),
+          status: document.getElementById("fStatus").value,
+          pay: document.getElementById("fPay").value,
+          refunded: document.getElementById("fRefunded").value,
+          from: document.getElementById("fFrom").value,
+          to: document.getElementById("fTo").value,
+        });
+        const rows = document.getElementById("orderRows");
+        const { ok, body } = await api("/orders?" + params);
+        if (!ok) {
+          rows.innerHTML = `<tr><td colspan="9" class="px-3 py-8 text-center text-rose-500">${esc(body.message || "加载失败")}</td></tr>`;
+          return;
+        }
+        const d = body.data;
+        const pages = Math.max(1, Math.ceil(d.total / d.size));
+        document.getElementById("summary").textContent =
+          `共 ${d.total} 笔 · 实付合计 ${yuan(d.paid_sum)} · 已退合计 ${yuan(d.refunded_sum)}`;
+        document.getElementById("pageInfo").textContent =
+          `第 ${d.page} / ${pages} 页`;
+        document.getElementById("prevBtn").disabled = d.page <= 1;
+        document.getElementById("nextBtn").disabled = d.page >= pages;
+        rows.innerHTML = d.items.length
+          ? d.items
+              .map(
+                (o) => `
+          <tr class="border-t border-slate-100 dark:border-night-line hover:bg-indigo-50/50 dark:hover:bg-night-hover cursor-pointer" onclick="openOrder(${Number(o.id)})">
+            <td class="px-3 py-2.5 font-mono">#${esc(o.id)}</td>
+            <td class="px-3 py-2.5">${esc(when(o.created_at))}</td>
+            <td class="px-3 py-2.5 max-w-56 truncate" title="${esc(o.email)}">${esc(o.email || "#" + o.user_id)}</td>
+            <td class="px-3 py-2.5">${esc(PAY[o.payment_type] || o.payment_type || "—")}</td>
+            <td class="px-3 py-2.5 text-right font-mono">${yuan(o.pay_amount)}</td>
+            <td class="px-3 py-2.5 text-right font-mono">${usd(o.amount)}</td>
+            <td class="px-3 py-2.5"><span class="px-2 py-0.5 rounded-md ${STATUS_CLASS[o.status] || "bg-slate-500/10 text-slate-500 dark:text-slate-400"}">${esc(STATUS[o.status] || o.status)}</span></td>
+            <td class="px-3 py-2.5 text-right font-mono">${o.refunded_cny ? yuan(o.refunded_cny) + (o.refund_count > 1 ? `（${o.refund_count} 次）` : "") : "—"}</td>
+            <td class="px-3 py-2.5 text-right"><span class="text-indigo-600 dark:text-indigo-400 font-medium">详情 / 退款</span></td>
+          </tr>`,
+              )
+              .join("")
+          : `<tr><td colspan="9" class="px-3 py-8 text-center text-slate-400">没有符合条件的订单</td></tr>`;
+      }
+
+      function fact(label, value) {
+        return `<div class="rounded-xl border-2 border-slate-200 dark:border-night-line bg-slate-50/70 dark:bg-night-inset px-3 py-2">
+          <div class="text-slate-400 dark:text-slate-500">${esc(label)}</div>
+          <div class="font-semibold text-slate-800 dark:text-slate-100 mt-0.5 break-all">${esc(value)}</div></div>`;
+      }
+
+      // 可点击复制的卡片（交易号、商户单号）
+      function factCopy(label, value) {
+        if (!value) return fact(label, "—");
+        return `<button type="button" data-copy="${esc(value)}" data-label="${esc(label)}" onclick="copyText(this.dataset.copy, this.dataset.label)"
+          title="点击复制" class="text-left rounded-xl border-2 border-slate-200 dark:border-night-line bg-slate-50/70 dark:bg-night-inset px-3 py-2 cursor-pointer hv">
+          <div class="flex items-center justify-between text-slate-400 dark:text-slate-500">${esc(label)}
+            <svg class="w-3.5 h-3.5" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24"><rect x="9" y="9" width="13" height="13" rx="2"/><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/></svg></div>
+          <div class="font-semibold font-mono text-slate-800 dark:text-slate-100 mt-0.5 break-all">${esc(value)}</div></button>`;
+      }
+
+      async function copyText(text, label) {
+        try {
+          await navigator.clipboard.writeText(text);
+        } catch {
+          const t = document.createElement("textarea");
+          t.value = text;
+          t.style.position = "fixed";
+          t.style.opacity = "0";
+          document.body.appendChild(t);
+          t.select();
+          document.execCommand("copy");
+          t.remove();
+        }
+        modalMsg(`已复制${label}：${text}`, false);
+      }
+
+      function modalMsg(text, error = true) {
+        const el = document.getElementById("modalMsg");
+        el.textContent = text || "";
+        el.className = text
+          ? error
+            ? "mt-3 text-xs font-medium text-rose-600 dark:text-rose-400"
+            : "mt-3 text-xs font-medium text-emerald-600 dark:text-emerald-400"
+          : "hidden mt-3 text-xs font-medium";
+      }
+
+      async function openOrder(id, keepMsg = false, showForm = false) {
+        if (!keepMsg) modalMsg("");
+        const { ok, body } = await api("/order?id=" + id);
+        if (!ok) return;
+        const o = (current = body.data);
+        document.getElementById("modalTitle").textContent = `订单 #${o.id}`;
+        document.getElementById("modalFacts").innerHTML = [
+          fact("客户", (o.email || "") + `（#${o.user_id}）`),
+          fact("状态", STATUS[o.status] || o.status),
+          fact("支付方式", PAY[o.payment_type] || o.payment_type || "—"),
+          fact("支付时间", when(o.paid_at)),
+          factCopy("交易号", o.payment_trade_no),
+          factCopy("商户单号", o.out_trade_no),
+          fact("实付", yuan(o.pay_amount)),
+          fact(
+            "到账余额",
+            usd(o.amount) +
+              (o.bonus_amount ? `（含赠送 ${usd(o.bonus_amount)}）` : ""),
+          ),
+          fact("购买单价", "¥" + (o.pay_amount / o.amount).toFixed(4) + " / $"),
+          fact("客户当前余额", usd(o.balance, 4)),
+          fact(
+            "已退",
+            `${yuan(o.refunded_cny)} · 扣回 ${usd(o.refund_amount)}`,
+          ),
+          fact(
+            "剩余可退",
+            `${yuan(o.remaining_cny)} · ${usd(o.remaining_usd)}`,
+          ),
+        ].join("");
+        revoking = null;
+        restoring = null;
+        renderHistory();
+        setFormOpen(!!showForm && o.refundable);
+        document.getElementById("refundCny").value = "";
+        document.getElementById("refundReason").value = "";
+        updateCalc();
+        const m = document.getElementById("orderModal");
+        m.classList.remove("hidden");
+        m.classList.add("flex");
+        if (await resolvePending(o.id)) {
+          const pend = getPending(o.id);
+          setFormOpen(true);
+          document.getElementById("refundCny").value = pend.cny;
+          document.getElementById("refundReason").value = pend.reason;
+          updateCalc();
+        }
+      }
+
+      // 退款记录：每条可删除（撤销），删除会退回当次扣回的余额；已删除的灰显留痕
+      let revoking = null;
+      function renderHistory() {
+        const o = current;
+        const head = `<div class="flex items-center justify-between mb-1.5">
+          <span class="text-xs font-semibold text-slate-700 dark:text-slate-200">退款记录</span>
+          ${
+            o.refundable
+              ? `<button type="button" onclick="setFormOpen(true)" class="h-8 px-3 rounded-lg bg-amber-500 hover:bg-amber-400 text-white text-xs font-medium cursor-pointer">+ 新增登记</button>`
+              : `<span class="text-xs text-slate-500 dark:text-slate-400">不能新增：${esc(o.not_refundable_reason)}</span>`
+          }</div>`;
+        const rows = o.history
+          .map((h) => {
+            const del = !!h.deleted_at;
+            const delTag = `<span class="px-2 py-0.5 rounded-md bg-slate-500/10 text-slate-500 dark:text-slate-400" title="${esc((h.deleted_by || "") + " · " + when(h.deleted_at) + (h.delete_reason ? " · " + h.delete_reason : ""))}">已删除</span>`;
+            const restoredTag = h.restored_at
+              ? `<span class="px-2 py-0.5 rounded-md bg-emerald-500/10 text-emerald-600 dark:text-emerald-400" title="${esc((h.restored_by || "") + " · " + when(h.restored_at))}">已恢复</span>`
+              : "";
+            const op = del
+              ? restoring === h.id
+                ? `${delTag}<button type="button" onclick="restore(${Number(h.id)})" class="h-7 px-2.5 rounded-lg bg-emerald-600 hover:bg-emerald-500 text-white cursor-pointer disabled:opacity-50" id="rs${Number(h.id)}" title="将再次扣回客户余额 ${usd(h.usd)}（余额不足时最多扣到 0）">确认恢复</button>
+                   <button type="button" onclick="setRestoring(null)" class="h-7 px-2.5 rounded-lg border-2 border-slate-200 dark:border-night-line cursor-pointer hv">取消</button>`
+                : `${delTag}<button type="button" onclick="setRestoring(${Number(h.id)})" class="h-7 px-2.5 rounded-lg border-2 border-slate-200 dark:border-night-line text-emerald-600 dark:text-emerald-400 cursor-pointer hv">恢复</button>`
+              : restoredTag +
+                (revoking === h.id
+                  ? `<button type="button" onclick="revoke(${Number(h.id)})" class="h-7 px-2.5 rounded-lg bg-rose-600 hover:bg-rose-500 text-white cursor-pointer disabled:opacity-50" id="rv${Number(h.id)}" title="将退回客户余额 ${usd(h.deducted, 4)}">确认删除</button>
+                   <button type="button" onclick="setRevoking(null)" class="h-7 px-2.5 rounded-lg border-2 border-slate-200 dark:border-night-line cursor-pointer hv">取消</button>`
+                  : `<button type="button" onclick="setRevoking(${Number(h.id)})" class="h-7 px-2.5 rounded-lg border-2 border-slate-200 dark:border-night-line text-rose-600 dark:text-rose-400 cursor-pointer hv">删除</button>`);
+            return `<tr class="border-t border-slate-100 dark:border-night-line ${del ? "line-through text-slate-400 dark:text-slate-500" : ""}">
+              <td class="px-3 py-2">${esc(when(h.created_at))}</td>
+              <td class="px-3 py-2 text-right font-mono">${yuan(h.cny)}</td>
+              <td class="px-3 py-2 text-right font-mono">${usd(h.deducted, 4)}</td>
+              <td class="px-3 py-2 max-w-32 truncate" title="${esc(h.reason)}">${esc(h.reason)}</td>
+              <td class="px-3 py-2">${esc(h.operator)}</td>
+              <td class="px-3 py-2 text-right"><div class="inline-flex items-center gap-1.5">${op}</div></td></tr>`;
+          })
+          .join("");
+        document.getElementById("modalHistory").innerHTML =
+          head +
+          (o.history.length
+            ? `<div class="overflow-x-auto rounded-xl border-2 border-slate-200 dark:border-night-line">
+               <table class="w-full text-xs whitespace-nowrap"><thead class="text-slate-500 dark:text-slate-400 bg-slate-50 dark:bg-night-inset"><tr>
+                 <th class="px-3 py-2 text-left font-medium">时间</th><th class="px-3 py-2 text-right font-medium">退款</th>
+                 <th class="px-3 py-2 text-right font-medium">扣回余额</th><th class="px-3 py-2 text-left font-medium">原因</th>
+                 <th class="px-3 py-2 text-left font-medium">操作人</th><th class="px-3 py-2 text-right font-medium">操作</th></tr></thead>
+               <tbody class="text-slate-700 dark:text-slate-200">${rows}</tbody></table></div>`
+            : `<div class="rounded-xl border-2 border-dashed border-slate-200 dark:border-night-line px-3 py-4 text-center text-xs text-slate-400">暂无退款记录</div>`);
+      }
+
+      let restoring = null;
+      function setRevoking(id) {
+        revoking = id;
+        restoring = null;
+        renderHistory();
+      }
+      function setRestoring(id) {
+        restoring = id;
+        revoking = null;
+        renderHistory();
+      }
+
+      async function restore(id) {
+        const btn = document.getElementById("rs" + id);
+        if (btn) btn.disabled = true;
+        const oid = current.id;
+        const { ok, body } = await api("/restore", {
+          method: "POST",
+          body: JSON.stringify({ ledger_id: id, confirm: true }),
+        });
+        if (!ok) {
+          setRestoring(null);
+          return modalMsg(body.message || "恢复失败");
+        }
+        const d = body.data;
+        await openOrder(oid, true);
+        modalMsg(
+          `已恢复该次退款：扣回余额 ${usd(d.deducted, 4)}（${usd(d.balance_before, 4)} → ${usd(d.balance_before - d.deducted, 4)}），订单「${STATUS[d.status] || d.status}」。` +
+            (d.cache_cleared ? "" : CACHE_WARN),
+          false,
+        );
+        loadOrders(page);
+      }
+
+      async function revoke(id) {
+        const btn = document.getElementById("rv" + id);
+        if (btn) btn.disabled = true;
+        const oid = current.id;
+        const { ok, body } = await api("/revoke", {
+          method: "POST",
+          body: JSON.stringify({ ledger_id: id, confirm: true }),
+        });
+        if (!ok) {
+          setRevoking(null);
+          return modalMsg(body.message || "删除失败");
+        }
+        const d = body.data;
+        await openOrder(oid, true);
+        modalMsg(
+          `已删除该次退款：客户余额 ${usd(d.balance_before, 4)} → ${usd(d.balance_after, 4)}，订单「${STATUS[d.status] || d.status}」。` +
+            (d.cache_cleared ? "" : CACHE_WARN),
+          false,
+        );
+        loadOrders(page);
+      }
+
+      function setFormOpen(open) {
+        document.getElementById("refundForm").classList.toggle("hidden", !open);
+        if (open) document.getElementById("refundCny").focus();
+      }
+
+      function openNew() {
+        const d = document.getElementById("newDialog");
+        document.getElementById("newOrderId").value = "";
+        document.getElementById("newMsg").textContent = "";
+        d.classList.remove("hidden");
+        d.classList.add("flex");
+        document.getElementById("newOrderId").focus();
+      }
+      function closeNew() {
+        const d = document.getElementById("newDialog");
+        d.classList.add("hidden");
+        d.classList.remove("flex");
+      }
+      async function goNew() {
+        const id = document.getElementById("newOrderId").value.trim();
+        if (!/^\d{1,18}$/.test(id))
+          return (document.getElementById("newMsg").textContent =
+            "请输入数字订单号");
+        const { ok, body } = await api("/order?id=" + id);
+        if (!ok)
+          return (document.getElementById("newMsg").textContent =
+            body.message || "订单不存在");
+        closeNew();
+        openOrder(id, false, true);
+      }
+
+      // 主题（与查询页共用 theme_mode：白天 / 黑夜 / 跟随系统）
+      function setThemeMode(mode) {
+        localStorage.setItem("theme_mode", mode);
+        applyThemeFromStorage();
+      }
+
+      function applyThemeFromStorage() {
+        const mode = localStorage.getItem("theme_mode") || "system";
+        let isDark = false;
+        if (mode === "dark") {
+          isDark = true;
+        } else if (mode === "light") {
+          isDark = false;
+        } else {
+          isDark = window.matchMedia("(prefers-color-scheme: dark)").matches;
+        }
+
+        if (isDark) {
+          document.documentElement.classList.add("dark");
+        } else {
+          document.documentElement.classList.remove("dark");
+        }
+
+        // 更新按钮展示图标
+        const iconContainer = document.getElementById("activeThemeIcon");
+        if (iconContainer) {
+          if (mode === "light") {
+            iconContainer.innerHTML =
+              '<svg class="w-5 h-5 text-amber-500" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24"><circle cx="12" cy="12" r="5"/><path d="M12 1v2M12 21v2M4.22 4.22l1.42 1.42M18.36 18.36l1.42 1.42M1 12h2M21 12h2M4.22 19.78l1.42-1.42M18.36 5.64l1.42-1.42"/></svg>';
+          } else if (mode === "dark") {
+            iconContainer.innerHTML =
+              '<svg class="w-5 h-5 text-indigo-400" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24"><path d="M21 12.79A9 9 0 1111.21 3 7 7 0 0021 12.79z"/></svg>';
+          } else {
+            iconContainer.innerHTML =
+              '<svg class="w-5 h-5 text-slate-500 dark:text-slate-300" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24"><rect width="20" height="14" x="2" y="3" rx="2"/><path d="M8 21h8M12 17v4"/></svg>';
+          }
+        }
+
+        // 菜单项打勾状态
+        ["light", "dark", "system"].forEach((m) => {
+          const item = document.getElementById(
+            "itemTheme" + m.charAt(0).toUpperCase() + m.slice(1),
+          );
+          if (item) {
+            const check = item.querySelector(".check-mark");
+            if (check) {
+              check.className =
+                m === mode
+                  ? "check-mark text-indigo-500 font-bold"
+                  : "check-mark hidden";
+            }
+          }
+        });
+      }
+
+      function closeOrder() {
+        const m = document.getElementById("orderModal");
+        m.classList.add("hidden");
+        m.classList.remove("flex");
+        current = null;
+        resetConfirm();
+      }
+
+      function planUsd(cny) {
+        // 与后端同公式：按订单 实付¥/到账$ 折算；退完剩余人民币时扣回全部剩余到账（含赠送）
+        const o = current;
+        if (!o || !(cny > 0) || cny - o.remaining_cny > 0.005) return null;
+        if (Math.abs(cny - o.remaining_cny) <= 0.005) return o.remaining_usd;
+        const v = Math.min(
+          Math.round(((cny * o.amount) / o.pay_amount) * 100) / 100,
+          o.remaining_usd,
+        );
+        return v > 0 ? v : null;
+      }
+
+      function updateCalc() {
+        resetConfirm();
+        const o = current;
+        if (!o) return;
+        const raw = document.getElementById("refundCny").value;
+        const cny = Math.round(parseFloat(raw) * 100) / 100;
+        const u = planUsd(cny);
+        const calc = document.getElementById("refundCalc");
+        document.getElementById("refundBtn").disabled = u === null;
+        if (!raw)
+          return (calc.textContent = `输入实际退款的人民币，最多 ${yuan(o.remaining_cny)}。`);
+        if (u === null)
+          return (calc.textContent = `退款金额需大于 0 且不超过剩余可退 ${yuan(o.remaining_cny)}。`);
+        const deduct = Math.min(u, Math.max(o.balance, 0));
+        const done = o.refund_amount + u >= o.amount - 0.005;
+        calc.textContent =
+          `退款 ${yuan(cny)} → 扣回余额 ${usd(u)}` +
+          (deduct < u ? `（余额不足，最多扣到 0：${usd(deduct, 4)}）` : "") +
+          `；客户余额 ${usd(o.balance, 4)} → ${usd(o.balance - deduct, 4)}；订单变为「${done ? "已退款" : "部分退款"}」。`;
+      }
+
+      function resetConfirm() {
+        confirming = false;
+        const btn = document.getElementById("refundBtn");
+        btn.textContent = "登记退款";
+        btn.className =
+          "h-11 px-5 rounded-xl bg-amber-500 hover:bg-amber-400 text-white font-medium text-sm active:scale-95 transition-all cursor-pointer disabled:opacity-50 disabled:cursor-not-allowed";
+        document.getElementById("refundCancel").classList.add("hidden");
+      }
+
+      async function submitRefund() {
+        const cny =
+          Math.round(
+            parseFloat(document.getElementById("refundCny").value) * 100,
+          ) / 100;
+        const u = planUsd(cny);
+        if (u === null || !current) return;
+        const btn = document.getElementById("refundBtn");
+        if (!confirming) {
+          confirming = true; // 第一次点击只进入确认态
+          btn.textContent = `确认登记：退 ${yuan(cny)}，扣 ${usd(u)}`;
+          btn.className =
+            "h-11 px-5 rounded-xl bg-rose-600 hover:bg-rose-500 text-white font-medium text-sm active:scale-95 transition-all cursor-pointer disabled:opacity-50 disabled:cursor-not-allowed";
+          document.getElementById("refundCancel").classList.remove("hidden");
+          return;
+        }
+        const id = current.id;
+        const reason = document.getElementById("refundReason").value;
+        // 结果未确认的登记存 localStorage（关窗/刷新不丢）：未核对前只能按原金额、原因用原 request_id 重试
+        const pend = getPending(id);
+        if (pend && (pend.cny !== cny || pend.reason !== reason)) {
+          resetConfirm();
+          return modalMsg(
+            `该订单有一笔结果未确认的登记（${yuan(pend.cny)}），请关闭后重新打开订单核对，或按原金额和原因重试。`,
+          );
+        }
+        btn.disabled = true;
+        const reqId = pend ? pend.id : newRequestId();
+        setPending(id, { cny, reason, id: reqId, at: Date.now() });
+        const { ok, status, body } = await api("/refund", {
+          method: "POST",
+          body: JSON.stringify({
+            order_id: id,
+            cny,
+            reason,
+            request_id: reqId,
+            confirm: true,
+          }),
+        });
+        btn.disabled = false;
+        resetConfirm();
+        if (!ok) {
+          // 网络错误 / 5xx 结果未确认，保留 request_id 供重试或下次打开订单时核对；4xx 明确未写入
+          if (status && status < 500) setPending(id, null);
+          return modalMsg(
+            status && status < 500
+              ? body.message || "登记失败"
+              : "登记结果未确认：可直接再次点击确认重试（同一次操作不会重复登记），或关闭后重新打开订单自动核对。",
+          );
+        }
+        setPending(id, null);
+        const d = body.data;
+        await openOrder(id, true, false);
+        modalMsg(
+          (d.duplicate
+            ? "这次登记此前已成功（重复提交未再扣回）："
+            : "已登记：") +
+            `退款 ${yuan(d.cny)}，扣回余额 ${usd(d.deducted, 4)}，订单「${d.status === "REFUNDED" ? "已退款" : "部分退款"}」。` +
+            (d.cache_cleared ? "" : CACHE_WARN),
+          false,
+        );
+        loadOrders(page);
+      }
+
+      const PENDING_KEY = "s2a_refund_pending";
+      function getPending(oid) {
+        try {
+          return (
+            JSON.parse(localStorage.getItem(PENDING_KEY) || "{}")[oid] || null
+          );
+        } catch {
+          return null;
+        }
+      }
+      function setPending(oid, v) {
+        let all = {};
+        try {
+          all = JSON.parse(localStorage.getItem(PENDING_KEY) || "{}");
+        } catch {}
+        if (v) all[oid] = v;
+        else delete all[oid];
+        localStorage.setItem(PENDING_KEY, JSON.stringify(all));
+      }
+      // 打开订单时处理上次结果未确认的登记：由服务器原子判定——已写入则返回结果，否则作废该 request_id
+      // （之后同 ID 的在途或重试写入都会失败），不依赖本机时间推断。返回 true 表示仍未确认（表单预填原值供重试）
+      async function resolvePending(oid) {
+        const pend = getPending(oid);
+        if (!pend) return false;
+        const { ok, body } = await api("/abandon", {
+          method: "POST",
+          body: JSON.stringify({ request_id: pend.id }),
+        });
+        if (!ok) {
+          modalMsg(
+            `上次登记（${yuan(pend.cny)}）结果仍未确认：核对失败，可按原金额和原因直接重试（不会重复登记），或稍后重新打开订单。`,
+          );
+          return true;
+        }
+        const r = body.data;
+        setPending(oid, null);
+        if (r.found) {
+          await openOrder(oid, true); // 写入可能在本次加载详情之后才提交，刷新一次
+          modalMsg(
+            r.deleted
+              ? `上次结果未确认的登记（${yuan(pend.cny)}）实际已写入，之后已被删除。`
+              : `上次结果未确认的登记已确认成功：退款 ${yuan(r.cny)}，扣回余额 ${usd(r.deducted, 4)}，无需重复登记。`,
+            false,
+          );
+        } else {
+          modalMsg(
+            `上次结果未确认的登记（${yuan(pend.cny)}）未写入，已在服务器作废（之后也不会再写入），可重新登记。`,
+            false,
+          );
+        }
+        return false;
+      }
+      const CACHE_WARN =
+        "余额缓存清除未成功，后台每分钟自动重试，客户端余额显示可能短暂滞后，无需重复操作。";
+      function newRequestId() {
+        if (crypto.randomUUID) return crypto.randomUUID();
+        const b = crypto.getRandomValues(new Uint8Array(16));
+        b[6] = (b[6] & 15) | 64;
+        b[8] = (b[8] & 63) | 128;
+        const h = [...b].map((x) => x.toString(16).padStart(2, "0")).join("");
+        return `${h.slice(0, 8)}-${h.slice(8, 12)}-${h.slice(12, 16)}-${h.slice(16, 20)}-${h.slice(20)}`;
+      }
+
+      document
+        .getElementById("refundCny")
+        .addEventListener("input", updateCalc);
+      document.addEventListener("keydown", (e) => {
+        if (e.key === "Escape") {
+          closeOrder();
+          closeNew();
+        }
+      });
+
+      applyThemeFromStorage();
+      window
+        .matchMedia("(prefers-color-scheme: dark)")
+        .addEventListener("change", () => {
+          if ((localStorage.getItem("theme_mode") || "system") === "system")
+            applyThemeFromStorage();
+        });
+
+      (async () => {
+        const { ok, body } = await api("/me");
+        if (!ok) return; // 401 已切到登录
+        setUser(body.data.username);
+        body.data.must_change ? showPassword(true) : showMain();
+      })();
+    </script>
+  </body>
+</html>
diff --git a/run b/run
new file mode 100755
index 0000000..4bff209
--- /dev/null
+++ b/run
@@ -0,0 +1,286 @@
+#!/usr/bin/env bash
+# ==============================================================================
+# StarNexus（sub2api）管理脚本 —— /opt/sub2api/run（项目唯一入口，需 root）
+#   ./run            菜单：按数字键立即执行（无需回车）
+#   ./run <命令>      直接执行，供宝塔计划任务与命令行使用：
+#     restart-sub2api | restart-relay | start | update [--check] | sync | status
+#     backup {all|files|db|r2|list|restore-files [目录]|check} | report [日期] | logs <名称>
+# 组成：sub2api 主程序 8080 · 分组路由鉴权 route_auth 8091 · relay 查询页后端 8092
+#       · 统一路由 auto_proxy 8093 · 运维程序 ops/ · relay 前端与后端 relay/
+# ==============================================================================
+set -uo pipefail
+export PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
+ROOT=/opt/sub2api
+OPS=$ROOT/ops
+RELAY=$ROOT/relay
+LOGDIR=/var/log/sub2api-ops
+REPO=Wei-Shaw/sub2api
+
+c_g="\033[32m" c_y="\033[33m" c_r="\033[31m" c_c="\033[36m" c_b="\033[1m" c_0="\033[0m"
+info() { echo -e "${c_c}[信息]${c_0} $*"; }
+ok() { echo -e "${c_g}[完成]${c_0} $*"; }
+warn() { echo -e "${c_y}[注意]${c_0} $*"; }
+err() { echo -e "${c_r}[失败]${c_0} $*"; }
+
+[ "$(id -u)" = 0 ] || {
+	err "请用 root 运行：sudo $0 $*"
+	exit 1
+}
+source "$OPS/lib.sh" # PGPASSWORD、Q、ops_lock 等
+
+# 健康检查（不用管道 grep -q，避免 pipefail 误判）
+healthy() { [[ "$(curl -s -m 5 "$1" 2>/dev/null)" == *'"ok"'* ]]; }
+wait_healthy() { # URL 秒数
+	local i
+	for i in $(seq 1 "$2"); do
+		healthy "$1" && return 0
+		sleep 1
+	done
+	return 1
+}
+current_version() { "$ROOT/sub2api" --version 2>&1 | grep -o 'Sub2API [0-9][0-9.]*' | head -1 | cut -d' ' -f2; }
+
+# ---------------- 1. 重启 sub2api（主程序 + 依赖它的分组路由/统一路由） ----------------
+restart_sub2api() {
+	info "重启 sub2api 主程序（约 3–5 秒中断）..."
+	systemctl reset-failed sub2api 2>/dev/null
+	systemctl restart sub2api
+	if wait_healthy http://127.0.0.1:8080/health 30; then ok "sub2api 已就绪（v$(current_version)，8080）"; else
+		err "sub2api 30 秒内未就绪：journalctl -u sub2api -n 30"
+		return 1
+	fi
+	info "重启分组路由与统一路由..."
+	"$OPS/svc-watchdog.sh" restart | grep -E 'route_auth|auto_proxy|守护' | sed 's/^/  /'
+}
+
+# ---------------- 2. 重启 relay 及相关服务 ----------------
+relay_build() {
+	info "构建 relay 前端产物..."
+	mkdir -p "$RELAY/dist"
+	# 宝塔「Node.js 版本管理器」安装的 node 不在系统 PATH，自动查找
+	command -v node >/dev/null || for d in $(ls -d /www/server/nodejs/v*/bin 2>/dev/null | sort -V -r); do
+		[ -x "$d/node" ] && export PATH="$d:$PATH" && break
+	done
+	if [ -x "$RELAY/node_modules/.bin/tailwindcss" ] && command -v node >/dev/null; then
+		(cd "$RELAY" && ./node_modules/.bin/tailwindcss -i src/input.css -o dist/tailwind.css --minify) || return 1
+	elif [ -f "$RELAY/dist/tailwind.css" ]; then
+		warn "服务器未安装 Node.js，沿用已编译的 tailwind.css（新用到的样式类可能缺失，可在本地编译后上传 dist/tailwind.css）"
+	else
+		err "缺少 Tailwind 编译器且无预编译 tailwind.css"
+		return 1
+	fi
+	cp "$RELAY/src/index.html" "$RELAY/dist/index.html"
+	ok "relay 前端已更新"
+}
+
+restart_relay() {
+	relay_build || return 1
+	info "重启 relay 后端（sub2api-key-query，8092）..."
+	systemctl reset-failed sub2api-key-query 2>/dev/null
+	systemctl restart sub2api-key-query
+	if wait_healthy http://127.0.0.1:8092/health 15; then ok "relay 后端已就绪"; else
+		err "relay 后端未就绪：journalctl -u sub2api-key-query -n 20"
+		return 1
+	fi
+	info "检查并重载 nginx..."
+	if nginx -t >/dev/null 2>&1; then nginx -s reload && ok "nginx 已重载"; else
+		err "nginx 配置有误（未重载）："
+		nginx -t
+		return 1
+	fi
+	local u code
+	for u in https://apiacc.itssx.com/relay/key https://api.itssx.com/relay/key; do
+		code=$(curl -s -m 15 -o /dev/null -w '%{http_code}' "$u")
+		[ "$code" = 200 ] && ok "$u → 200" || err "$u → $code"
+	done
+}
+
+# ---------------- 3. 一起启动 ----------------
+start_all() {
+	info "启动 sub2api..."
+	systemctl reset-failed sub2api 2>/dev/null
+	systemctl start sub2api
+	wait_healthy http://127.0.0.1:8080/health 30 && ok "sub2api 就绪（8080）" || err "sub2api 未就绪：journalctl -u sub2api -n 30"
+	info "启动分组路由、统一路由与全服务守护..."
+	"$OPS/svc-watchdog.sh" ensure >/dev/null
+	sleep 3
+	restart_relay
+	echo
+	"$OPS/svc-watchdog.sh" status | sed 's/^/  /'
+}
+
+# ---------------- 4. 更新 sub2api ----------------
+update_sub2api() {
+	local check_only=${1:-}
+	local cur latest arch tmp archive url sums want got
+	cur=$(current_version)
+	info "查询 GitHub 最新版本（$REPO）..."
+	latest=$(curl -s -m 30 "https://api.github.com/repos/$REPO/releases/latest" | python3 -c "import json,sys;print(json.load(sys.stdin).get('tag_name','').lstrip('v'))" 2>/dev/null)
+	[ -n "$latest" ] || {
+		err "无法获取最新版本（网络或 GitHub 限流）"
+		return 1
+	}
+	echo "  当前版本：v$cur    最新版本：v$latest"
+	if [ "$(printf '%s\n%s\n' "$cur" "$latest" | sort -V | tail -1)" = "$cur" ]; then
+		ok "已是最新版本，无需更新"
+		return 0
+	fi
+	[ "$check_only" = "--check" ] && return 0
+	case $(uname -m) in x86_64) arch=amd64 ;; aarch64 | arm64) arch=arm64 ;; *)
+		err "不支持的架构 $(uname -m)"
+		return 1
+		;;
+	esac
+	tmp=$(mktemp -d /root/sub2api-update.XXXX)
+	archive="sub2api_${latest}_linux_${arch}.tar.gz"
+	url="https://github.com/$REPO/releases/download/v$latest"
+	info "下载 $archive 与 checksums.txt..."
+	curl -fsSL -m 600 -o "$tmp/$archive" "$url/$archive" && curl -fsSL -m 60 -o "$tmp/checksums.txt" "$url/checksums.txt" || {
+		err "下载失败"
+		rm -rf -- "$tmp"
+		return 1
+	}
+	want=$(awk -v f="$archive" '$2==f{print $1}' "$tmp/checksums.txt")
+	got=$(sha256sum "$tmp/$archive" | cut -d' ' -f1)
+	[ -n "$want" ] && [ "$want" = "$got" ] || {
+		err "SHA256 校验失败（期望 ${want:-无} 实际 $got），已放弃"
+		rm -rf -- "$tmp"
+		return 1
+	}
+	ok "校验通过"
+	tar -xzf "$tmp/$archive" -C "$tmp" sub2api 2>/dev/null || tar -xzf "$tmp/$archive" -C "$tmp" --wildcards '*/sub2api' --strip-components=1 || {
+		err "解压失败"
+		rm -rf -- "$tmp"
+		return 1
+	}
+	"$tmp/sub2api" --version 2>&1 | grep -q "$latest" || warn "新程序版本号未能确认，继续"
+	info "更新前备份：文件入库 + 数据库本机备份 + 当前程序..."
+	backup_files >/dev/null && backup_db_local >/dev/null || warn "备份有失败项，请留意"
+	mkdir -p /root/backup/sub2api-bin
+	cp -p "$ROOT/sub2api" "/root/backup/sub2api-bin/sub2api-v$cur"
+	info "替换程序并重启..."
+	systemctl stop sub2api
+	install -o sub2api -g sub2api -m 755 "$tmp/sub2api" "$ROOT/sub2api"
+	systemctl reset-failed sub2api 2>/dev/null
+	systemctl start sub2api
+	if wait_healthy http://127.0.0.1:8080/health 60; then
+		ok "已更新到 v$(current_version)（旧程序备份：/root/backup/sub2api-bin/sub2api-v$cur）"
+		"$OPS/svc-watchdog.sh" restart >/dev/null
+		warn "充值页、Key 页的前端覆盖文件名随版本变化会自动失效，需按交接文档重新适配；建议执行一次「同步 Nexus 数据」核对配置"
+	else
+		err "新版本 60 秒内未就绪，回滚到 v$cur..."
+		systemctl stop sub2api
+		install -o sub2api -g sub2api -m 755 "/root/backup/sub2api-bin/sub2api-v$cur" "$ROOT/sub2api"
+		systemctl start sub2api
+		wait_healthy http://127.0.0.1:8080/health 30 && ok "已回滚到 v$cur" || err "回滚后仍未就绪，请人工处理：journalctl -u sub2api -n 50"
+	fi
+	rm -rf -- "$tmp"
+}
+
+# ---------------- 5. 同步 Nexus 数据 ----------------
+sync_nexus() {
+	info "对账 Nexus → 有差异则同步（写前自动备份）→ 再对账 → 邮件通知..."
+	"$OPS/nexus-auto-sync.sh"
+	grep -E '一致|发现差异|同步完成|对账失败|跳过' "$OPS/auto_sync.log" | tail -2 | sed 's/^/  /'
+}
+
+# ---------------- 备份（宝塔计划任务与命令行使用） ----------------
+backup_files() { python3 -I "$OPS/snapshot_files.py" save; }
+backup_db_local() { bash /www/server/panel/script/custom/backup-sub2api.sh 14 | tail -3; }
+backup_r2() {
+	source /root/.config/sub2api-r2.env
+	local f code
+	f=$(ls -t /www/backup/database/pgsql/sub2api/sub2api_db_*.dump 2>/dev/null | head -1)
+	[ -n "$f" ] || {
+		err "没有本机数据库备份可上传"
+		return 1
+	}
+	code=$(curl -sS -m 300 -o /dev/null -w "%{http_code}" --aws-sigv4 "aws:amz:auto:s3" \
+		-K <(printf 'user = "%s:%s"\n' "$R2_ACCESS_KEY_ID" "$R2_SECRET_ACCESS_KEY") -T "$f" "$R2_ENDPOINT/$R2_BUCKET/sub2api/manual/$(basename "$f")")
+	[ "$code" = 200 ] && ok "已上传 R2：sub2api/manual/$(basename "$f")" || err "上传 R2 失败 HTTP $code"
+	/usr/local/sbin/sub2api-config-backup.sh | tail -1
+}
+do_backup() {
+	case "${1:-all}" in
+	files) backup_files ;;
+	db) backup_db_local ;;
+	r2) backup_r2 ;;
+	all) backup_files && backup_db_local && backup_r2 ;;
+	list) python3 -I "$OPS/snapshot_files.py" list ;;
+	restore-files) python3 -I "$OPS/snapshot_files.py" restore "${2:-}" ;;
+	check) "$OPS/backup-restore-check.sh" && tail -14 "$OPS/backup_restore_check.log" ;;
+	*) echo "用法：$0 backup {all|files|db|r2|list|restore-files [目录]|check}" ;;
+	esac
+}
+
+do_logs() {
+	case "${1:-}" in
+	sub2api) journalctl -u sub2api -n 50 --no-pager ;;
+	relay) journalctl -u sub2api-key-query -n 50 --no-pager ;;
+	sync) tail -40 "$OPS/auto_sync.log" ;;
+	watchdog) tail -40 "$LOGDIR/watchdog.log" ;;
+	route) tail -40 "$LOGDIR/route_auth.log" ;;
+	auto) tail -40 "$LOGDIR/auto_proxy.log" ;;
+	*) echo "用法：$0 logs {sub2api|relay|sync|watchdog|route|auto}" ;;
+	esac
+}
+
+status_line() {
+	local s
+	for s in "sub2api:http://127.0.0.1:8080/health" "relay:http://127.0.0.1:8092/health" "统一路由:http://127.0.0.1:8093/__health"; do
+		healthy "${s#*:}" && printf "${c_g}●${c_0} %s  " "${s%%:*}" || printf "${c_r}●${c_0} %s  " "${s%%:*}"
+	done
+	[[ "$(curl -s -m 5 -o /dev/null -w '%{http_code}' http://127.0.0.1:8091/check)" == 200 ]] && printf "${c_g}●${c_0} 分组路由" || printf "${c_r}●${c_0} 分组路由"
+	echo "    v$(current_version)"
+}
+
+menu() {
+	local key
+	while true; do
+		echo -e "\n${c_b}========== StarNexus（sub2api）管理 ==========${c_0}"
+		status_line
+		cat <<EOF
+
+  1  重启 sub2api（含分组路由、统一路由）
+  2  重启 relay 及相关服务（Key 查询页后端、nginx）
+  3  一起启动（sub2api + relay + 路由服务与守护）
+  4  更新 sub2api（GitHub 最新版，校验、备份、失败自动回滚）
+  5  同步 Nexus 数据
+  0  退出
+EOF
+		printf "按数字键选择："
+		read -rsn1 key
+		echo "$key"
+		case $key in
+		1) restart_sub2api ;;
+		2) restart_relay ;;
+		3) start_all ;;
+		4) update_sub2api ;;
+		5) sync_nexus ;;
+		0 | q | Q) exit 0 ;;
+		*) continue ;;
+		esac
+		printf "\n按任意键返回菜单..."
+		read -rsn1 _
+		echo
+	done
+}
+
+cmd=${1:-menu}
+shift || true
+case $cmd in
+menu) menu ;;
+restart-sub2api | restart) restart_sub2api ;;
+restart-relay) restart_relay ;;
+start) start_all ;;
+update) update_sub2api "$@" ;;
+sync) sync_nexus ;;
+status) "$OPS/svc-watchdog.sh" status ;;
+backup) do_backup "$@" ;;
+report) "$OPS/daily-report.sh" "$@" ;;
+logs) do_logs "$@" ;;
+*)
+	sed -n '3,10p' "$0"
+	exit 1
+	;;
+esac
diff --git a/sub2api-datamanagementd.service b/sub2api-datamanagementd.service
new file mode 100644
index 0000000..b32733b
--- /dev/null
+++ b/sub2api-datamanagementd.service
@@ -0,0 +1,22 @@
+[Unit]
+Description=Sub2API Data Management Daemon
+After=network.target
+Wants=network.target
+
+[Service]
+Type=simple
+User=sub2api
+Group=sub2api
+WorkingDirectory=/opt/sub2api
+ExecStart=/opt/sub2api/datamanagementd \
+  -socket-path /tmp/sub2api-datamanagement.sock \
+  -sqlite-path /var/lib/sub2api/datamanagement/datamanagementd.db \
+  -version 1.0.0
+Restart=always
+RestartSec=5s
+LimitNOFILE=100000
+NoNewPrivileges=true
+PrivateTmp=false
+
+[Install]
+WantedBy=multi-user.target
diff --git a/sub2api.service b/sub2api.service
new file mode 100644
index 0000000..1a59ad0
--- /dev/null
+++ b/sub2api.service
@@ -0,0 +1,33 @@
+[Unit]
+Description=Sub2API - AI API Gateway Platform
+Documentation=https://github.com/Wei-Shaw/sub2api
+After=network.target postgresql.service redis.service
+Wants=postgresql.service redis.service
+
+[Service]
+Type=simple
+User=sub2api
+Group=sub2api
+WorkingDirectory=/opt/sub2api
+ExecStart=/opt/sub2api/sub2api
+Restart=always
+RestartSec=5
+StandardOutput=journal
+StandardError=journal
+SyslogIdentifier=sub2api
+
+# Security hardening
+NoNewPrivileges=true
+ProtectSystem=strict
+ProtectHome=true
+PrivateTmp=true
+ReadWritePaths=/opt/sub2api
+
+# Environment - Server configuration
+# Modify these values to change listen address and port
+Environment=GIN_MODE=release
+Environment=SERVER_HOST=0.0.0.0
+Environment=SERVER_PORT=8080
+
+[Install]
+WantedBy=multi-user.target
diff --git a/test-caddyfile-cache.sh b/test-caddyfile-cache.sh
new file mode 100755
index 0000000..41e5e25
--- /dev/null
+++ b/test-caddyfile-cache.sh
@@ -0,0 +1,85 @@
+#!/bin/sh
+set -eu
+
+repo_root=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)
+caddyfile="$repo_root/deploy/Caddyfile"
+active_config=$(sed 's/[[:space:]]*#.*$//' "$caddyfile")
+normalized_config=$(printf '%s\n' "$active_config" | awk '
+	NF > 0 {
+		for (field = 1; field <= NF; field++) {
+			token = $field
+			sub(/^["`]/, "", token)
+			sub(/["`]$/, "", token)
+			printf "%s%s", (field == 1 ? "" : " "), token
+		}
+		print ""
+	}
+')
+
+# Keep one canonical encode block instead of reimplementing Caddy matcher semantics.
+expected_encode_block=$(cat <<'EOF'
+encode {
+zstd
+gzip 6
+minimum_length 256
+match {
+header Content-Type text/css*
+header Content-Type text/csv*
+header Content-Type text/html*
+header Content-Type text/javascript*
+header Content-Type text/markdown*
+header Content-Type text/plain*
+header Content-Type text/xml*
+header Content-Type application/json*
+header Content-Type application/javascript*
+header Content-Type application/xml*
+header Content-Type application/rss+xml*
+header Content-Type image/svg+xml*
+}
+}
+EOF
+)
+
+if printf '%s\n' "$normalized_config" | grep -Eiq 'cache-control.*immutable'; then
+	echo "Caddyfile must not force immutable caching; the backend owns asset cache policy" >&2
+	exit 1
+fi
+
+if ! printf '%s\n' "$normalized_config" | grep -Eq '^reverse_proxy localhost:8080([[:space:]]|$)'; then
+	echo "Caddyfile must continue proxying all application routes to localhost:8080" >&2
+	exit 1
+fi
+
+if printf '%s\n' "$normalized_config" | grep -Eq '^import([[:space:]]|$)'; then
+	echo "Caddyfile must not import configuration outside this canonical policy check" >&2
+	exit 1
+fi
+
+if printf '%s\n' "$normalized_config" | grep -Eiq '^flush_interval([[:space:]]|$)'; then
+	echo "Caddyfile must leave flush_interval unset so SSE auto-flushing and client cancellation remain intact" >&2
+	exit 1
+fi
+
+encode_directive_count=$(printf '%s\n' "$normalized_config" | awk '$1 == "encode" { count++ } END { print count + 0 }')
+if [ "$encode_directive_count" -ne 1 ]; then
+	echo "Caddyfile must contain exactly one explicit encode block" >&2
+	exit 1
+fi
+
+actual_encode_block=$(printf '%s\n' "$normalized_config" | awk '
+	$1 == "encode" { in_block = 1 }
+	in_block {
+		print
+		for (field = 1; field <= NF; field++) {
+			if ($field == "{") depth++
+			if ($field == "}") depth--
+		}
+		if (depth == 0) exit
+	}
+')
+if [ "$actual_encode_block" != "$expected_encode_block" ]; then
+	echo "Caddyfile encode block must keep the canonical non-SSE compression policy" >&2
+	exit 1
+fi
+
+echo "Caddyfile preserves backend cache policy, SSE streaming, and non-SSE compression"
diff --git a/tests/apple-container-test.sh b/tests/apple-container-test.sh
new file mode 100755
index 0000000..f455111
--- /dev/null
+++ b/tests/apple-container-test.sh
@@ -0,0 +1,107 @@
+#!/bin/bash
+
+set -euo pipefail
+
+TEST_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
+DEPLOY_DIR="$(cd "${TEST_DIR}/.." && pwd)"
+SCRIPT="${DEPLOY_DIR}/apple-container.sh"
+TEST_ROOT="$(mktemp -d "${TMPDIR:-/tmp}/sub2api-apple-test.XXXXXX")"
+STATE_DIR="${TEST_ROOT}/state"
+ENV_FILE="${TEST_ROOT}/sub2api.env"
+
+cleanup() {
+    rm -rf "${TEST_ROOT}"
+}
+trap cleanup EXIT
+
+fail() {
+    printf 'FAIL: %s\n' "$*" >&2
+    exit 1
+}
+
+assert_exists() {
+    [[ -e "$1" ]] || fail "Expected path to exist: $1"
+}
+
+assert_missing() {
+    [[ ! -e "$1" ]] || fail "Expected path to be absent: $1"
+}
+
+export FAKE_CONTAINER_STATE="${STATE_DIR}"
+export PATH="${TEST_DIR}/fixtures/bin:${PATH}"
+export SUB2API_ENV_FILE="${ENV_FILE}"
+
+mkdir -p "${STATE_DIR}"
+
+"${SCRIPT}" init
+[[ "$(stat -f '%Lp' "${ENV_FILE}")" == "600" ]] || fail "init did not create a mode-600 env file"
+grep -q '^POSTGRES_PASSWORD=change_this_secure_password$' "${ENV_FILE}" && fail "init retained the placeholder password"
+
+chmod 644 "${ENV_FILE}"
+if "${SCRIPT}" up >/dev/null 2>&1; then
+    fail "up accepted an insecure env file"
+fi
+chmod 600 "${ENV_FILE}"
+
+"${SCRIPT}" up
+assert_exists "${STATE_DIR}/containers/sub2api-apple"
+assert_exists "${STATE_DIR}/containers/sub2api-apple-postgres"
+assert_exists "${STATE_DIR}/containers/sub2api-apple-redis"
+assert_exists "${STATE_DIR}/running/sub2api-apple"
+grep -q '^while true; do$' "${STATE_DIR}/create-arguments/sub2api-apple" || \
+    fail "app container does not supervise the Sub2API process"
+grep -q '^    su-exec sub2api "$runtime_binary" &$' "${STATE_DIR}/create-arguments/sub2api-apple" || \
+    fail "app supervisor does not launch the updatable Sub2API binary"
+grep -q '^trap stop TERM INT$' "${STATE_DIR}/create-arguments/sub2api-apple" || \
+    fail "app supervisor does not handle container stop signals"
+grep -q '^runtime_binary="$runtime_dir/sub2api"$' "${STATE_DIR}/create-arguments/sub2api-apple" || \
+    fail "app container does not run its updatable binary from persistent storage"
+grep -q '^APPLE_CONTAINER_SUB2API_IMAGE_ID=fake-image-id$' "${STATE_DIR}/env-files/sub2api-apple" || \
+    fail "app container did not receive the inspected base image ID"
+[[ ! -s "${STATE_DIR}/network-subnets/sub2api-apple" ]] || \
+    fail "up passed a subnet when APPLE_CONTAINER_NETWORK_SUBNET was unset"
+"${SCRIPT}" status >/dev/null
+
+"${SCRIPT}" up --recreate
+assert_exists "${STATE_DIR}/running/sub2api-apple"
+"${SCRIPT}" down
+assert_missing "${STATE_DIR}/running/sub2api-apple"
+assert_missing "${STATE_DIR}/running/sub2api-apple-postgres"
+assert_missing "${STATE_DIR}/running/sub2api-apple-redis"
+
+"${SCRIPT}" destroy --yes
+assert_missing "${STATE_DIR}/containers/sub2api-apple"
+assert_missing "${STATE_DIR}/networks/sub2api-apple"
+assert_exists "${STATE_DIR}/volumes/sub2api-apple-data"
+
+printf '\nAPPLE_CONTAINER_NETWORK_SUBNET=172.31.250.0/24\n' >>"${ENV_FILE}"
+"${SCRIPT}" up
+[[ "$(<"${STATE_DIR}/network-subnets/sub2api-apple")" == "172.31.250.0/24" ]] || \
+    fail "up did not pass APPLE_CONTAINER_NETWORK_SUBNET to network creation"
+
+printf 'APPLE_CONTAINER_NETWORK_SUBNET=172.31.251.0/24\n' >>"${ENV_FILE}"
+if mismatch_output="$("${SCRIPT}" up 2>&1)"; then
+    fail "up accepted a configured subnet that differs from the existing network"
+fi
+[[ "${mismatch_output}" == *"Existing network 'sub2api-apple' uses subnet '172.31.250.0/24'"* ]] || \
+    fail "up did not explain the existing network subnet mismatch"
+[[ "${mismatch_output}" == *"destroy --yes"* ]] || \
+    fail "up did not provide the network migration command"
+assert_exists "${STATE_DIR}/networks/sub2api-apple"
+assert_exists "${STATE_DIR}/containers/sub2api-apple"
+
+"${SCRIPT}" destroy --yes
+"${SCRIPT}" up
+"${SCRIPT}" destroy --volumes --yes
+assert_missing "${STATE_DIR}/volumes/sub2api-apple-data"
+assert_missing "${STATE_DIR}/volumes/sub2api-apple-postgres-data"
+assert_missing "${STATE_DIR}/volumes/sub2api-apple-redis-data"
+
+touch "${STATE_DIR}/system-running"
+touch "${STATE_DIR}/containers/sub2api-apple"
+touch "${STATE_DIR}/unowned/container/sub2api-apple"
+if "${SCRIPT}" status >/dev/null 2>&1; then
+    fail "status accepted an unowned same-name container"
+fi
+
+printf 'Apple container lifecycle tests passed.\n'
diff --git a/tests/docker-compose-gateway-env-test.sh b/tests/docker-compose-gateway-env-test.sh
new file mode 100644
index 0000000..f068410
--- /dev/null
+++ b/tests/docker-compose-gateway-env-test.sh
@@ -0,0 +1,47 @@
+#!/bin/sh
+set -eu
+
+repo_root=$(CDPATH= cd -- "$(dirname -- "$0")/../.." && pwd)
+cd "$repo_root"
+
+gateway_variables=$(mktemp "${TMPDIR:-/tmp}/sub2api-gateway-env.XXXXXX")
+cleanup() {
+  rm -f "$gateway_variables"
+}
+trap cleanup EXIT HUP INT TERM
+
+awk '
+  /^GATEWAY_[A-Z0-9_]+=/ {
+    separator = index($0, "=")
+    print substr($0, 1, separator - 1) "\t" substr($0, separator + 1)
+  }
+' deploy/.env.example > "$gateway_variables"
+
+for compose_file in \
+  deploy/docker-compose.yml \
+  deploy/docker-compose.local.yml \
+  deploy/docker-compose.standalone.yml \
+  deploy/docker-compose.dev.yml
+do
+  tab=$(printf '\t')
+  while IFS="$tab" read -r key value; do
+    # .env.example intentionally includes high-capacity tuning examples for
+    # these values. An unconfigured Compose deployment must retain the
+    # backend defaults instead of silently adopting the examples.
+    case "$key" in
+      GATEWAY_MAX_CONNS_PER_HOST) value=1024 ;;
+      GATEWAY_MAX_IDLE_CONNS) value=2560 ;;
+      GATEWAY_MAX_IDLE_CONNS_PER_HOST) value=120 ;;
+    esac
+
+    expected=$(printf '      - %s=${%s:-%s}' "$key" "$key" "$value")
+    expected_count=$(grep -Fxc "$expected" "$compose_file" || true)
+    key_count=$(grep -Ec "^[[:space:]]*-[[:space:]]*${key}([[:space:]]*=.*)?[[:space:]]*$" "$compose_file" || true)
+    if [ "$expected_count" -ne 1 ] || [ "$key_count" -ne 1 ]; then
+      printf '%s must pass %s with the expected fallback exactly once\n' "$compose_file" "$key" >&2
+      exit 1
+    fi
+  done < "$gateway_variables"
+done
+
+printf 'docker compose Gateway environment test passed\n'
diff --git a/tests/docker-compose-security-test.sh b/tests/docker-compose-security-test.sh
new file mode 100755
index 0000000..b6cfe76
--- /dev/null
+++ b/tests/docker-compose-security-test.sh
@@ -0,0 +1,44 @@
+#!/bin/sh
+set -eu
+
+repo_root=$(CDPATH= cd -- "$(dirname -- "$0")/../.." && pwd)
+cd "$repo_root"
+
+check_application_security_opt() {
+  file=$1
+  count=$(
+    awk '
+      $0 == "  sub2api:" {
+        in_application = 1
+        next
+      }
+      in_application && $0 ~ /^  [A-Za-z0-9_-]+:$/ {
+        in_application = 0
+      }
+      in_application && $0 == "    security_opt:" {
+        in_security_opt = 1
+        next
+      }
+      in_application && in_security_opt && $0 == "      - no-new-privileges:true" {
+        count++
+      }
+      END { print count + 0 }
+    ' "$file"
+  )
+
+  if [ "$count" -ne 1 ]; then
+    printf '%s must enable no-new-privileges exactly once for the sub2api service\n' "$file" >&2
+    exit 1
+  fi
+}
+
+for compose_file in \
+  deploy/docker-compose.yml \
+  deploy/docker-compose.local.yml \
+  deploy/docker-compose.standalone.yml \
+  deploy/docker-compose.dev.yml
+do
+  check_application_security_opt "$compose_file"
+done
+
+printf 'docker compose security test passed\n'
diff --git a/tests/docker-compose-simple-mode-env-test.sh b/tests/docker-compose-simple-mode-env-test.sh
new file mode 100644
index 0000000..28f4eec
--- /dev/null
+++ b/tests/docker-compose-simple-mode-env-test.sh
@@ -0,0 +1,46 @@
+#!/bin/sh
+set -eu
+
+repo_root=$(CDPATH= cd -- "$(dirname -- "$0")/../.." && pwd)
+cd "$repo_root"
+
+python3 - <<'PY'
+import json
+import os
+from pathlib import Path
+import subprocess
+
+key = "SIMPLE_MODE_AUTO_CREATE_DEFAULT_GROUPS"
+sample = Path("deploy/.env.example").read_text().splitlines()
+assert [line for line in sample if line.startswith(key + "=")] == [key + "="], \
+    ".env.example must preserve YAML configuration by leaving the override empty"
+
+for filename in (
+    "docker-compose.yml",
+    "docker-compose.local.yml",
+    "docker-compose.standalone.yml",
+    "docker-compose.dev.yml",
+):
+    path = Path("deploy") / filename
+    expected = "      - " + key + "=${" + key + ":-}"
+    assert path.read_text().splitlines().count(expected) == 1, \
+        f"{path} must pass the override with an empty fallback exactly once"
+    for value in (None, "", "true", "false"):
+        env = dict(
+            os.environ, POSTGRES_PASSWORD="compose-test-password",
+            DATABASE_HOST="postgres", DATABASE_PASSWORD="compose-test-password",
+            REDIS_HOST="redis",
+        )
+        env.pop(key, None)
+        if value is not None:
+            env[key] = value
+        result = subprocess.run(
+            ["docker", "compose", "--env-file", "/dev/null", "-f", str(path),
+             "config", "--format", "json"],
+            env=env, check=True, capture_output=True, text=True,
+        )
+        actual = json.loads(result.stdout)["services"]["sub2api"]["environment"][key]
+        assert actual == (value or ""), f"{path}: override {value!r} rendered as {actual!r}"
+
+print("docker compose simple mode environment test passed")
+PY
diff --git a/tests/docker-runtime-resources-test.sh b/tests/docker-runtime-resources-test.sh
new file mode 100755
index 0000000..4e7480d
--- /dev/null
+++ b/tests/docker-runtime-resources-test.sh
@@ -0,0 +1,34 @@
+#!/bin/sh
+set -eu
+
+repo_root=$(CDPATH= cd -- "$(dirname -- "$0")/../.." && pwd)
+cd "$repo_root"
+
+fail() {
+  printf 'docker runtime resources test failed: %s\n' "$1" >&2
+  exit 1
+}
+
+assert_line() {
+  file=$1
+  line=$2
+  grep -Fqx "$line" "$file" || fail "$file is missing: $line"
+}
+
+assert_count() {
+  file=$1
+  line=$2
+  expected=$3
+  actual=$(grep -Fxc "$line" "$file" || true)
+  [ "$actual" -eq "$expected" ] || fail "$file has $actual occurrences of '$line', expected $expected"
+}
+
+test -s backend/resources/model-pricing/model_prices_and_context_window.json || \
+  fail 'fallback pricing data is missing or empty'
+
+assert_line Dockerfile.goreleaser 'COPY --chown=sub2api:sub2api backend/resources /app/resources'
+assert_line deploy/Dockerfile 'COPY --from=backend-builder --chown=sub2api:sub2api /app/backend/resources /app/resources'
+assert_count .goreleaser.yaml '      - backend/resources' 4
+assert_count .goreleaser.simple.yaml '      - backend/resources' 1
+
+printf 'docker runtime resources test passed\n'
diff --git a/tests/fixtures/bin/container b/tests/fixtures/bin/container
new file mode 100755
index 0000000..62ae9f8
--- /dev/null
+++ b/tests/fixtures/bin/container
@@ -0,0 +1,204 @@
+#!/bin/bash
+
+set -eu
+
+STATE_DIR="${FAKE_CONTAINER_STATE:?FAKE_CONTAINER_STATE is required}"
+mkdir -p \
+    "${STATE_DIR}/containers" \
+    "${STATE_DIR}/running" \
+    "${STATE_DIR}/networks" \
+    "${STATE_DIR}/network-subnets" \
+    "${STATE_DIR}/volumes" \
+    "${STATE_DIR}/create-arguments" \
+    "${STATE_DIR}/env-files" \
+    "${STATE_DIR}/unowned/container" \
+    "${STATE_DIR}/unowned/network" \
+    "${STATE_DIR}/unowned/volume"
+
+list_names() {
+    local directory=$1
+    local path
+
+    for path in "${directory}"/*; do
+        [[ -e "${path}" ]] || continue
+        basename "${path}"
+    done
+}
+
+last_argument() {
+    local value=""
+
+    for value in "$@"; do :; done
+    printf '%s\n' "${value}"
+}
+
+inspect_resource() {
+    local resource_type=$1
+    local resource_name=$2
+    local label_value="apple-container"
+    local address="192.168.65.4/24"
+    local subnet="192.168.65.0/24"
+
+    if [[ -e "${STATE_DIR}/unowned/${resource_type}/${resource_name}" ]]; then
+        label_value="other"
+    fi
+    if [[ "${resource_type}" == "network" ]]; then
+        if [[ -s "${STATE_DIR}/network-subnets/${resource_name}" ]]; then
+            subnet="$(<"${STATE_DIR}/network-subnets/${resource_name}")"
+        fi
+        printf '[{"configuration":{"ipv4Subnet":"%s","labels":{"org.sub2api.stack":"%s"}}}]\n' \
+            "${subnet}" "${label_value}"
+        return
+    fi
+    case "${resource_name}" in
+        sub2api-apple-postgres) address="192.168.65.2/24" ;;
+        sub2api-apple-redis) address="192.168.65.3/24" ;;
+    esac
+
+    printf '[{"configuration":{"labels":{"org.sub2api.stack":"%s"}},"status":{"networks":[{"ipv4Address":"%s"}]}}]\n' \
+        "${label_value}" "${address}"
+}
+
+command=${1-}
+if [[ $# -gt 0 ]]; then shift; fi
+
+case "${command}" in
+    --version)
+        echo "container CLI version 1.1.0 (build: release, commit: fake)"
+        ;;
+    system)
+        subcommand=${1-}
+        case "${subcommand}" in
+            status) [[ -e "${STATE_DIR}/system-running" ]] ;;
+            start) touch "${STATE_DIR}/system-running" ;;
+            stop) rm -f "${STATE_DIR}/system-running" "${STATE_DIR}/running"/* ;;
+            *) exit 1 ;;
+        esac
+        ;;
+    list)
+        include_all=false
+        for argument in "$@"; do
+            [[ "${argument}" == "--all" || "${argument}" == "-a" ]] && include_all=true
+        done
+        if [[ "${include_all}" == true ]]; then
+            list_names "${STATE_DIR}/containers"
+        else
+            list_names "${STATE_DIR}/running"
+        fi
+        ;;
+    network)
+        subcommand=${1-}
+        shift || true
+        case "${subcommand}" in
+            list)
+                echo default
+                list_names "${STATE_DIR}/networks"
+                ;;
+            create)
+                network_name="$(last_argument "$@")"
+                subnet=""
+                while [[ $# -gt 0 ]]; do
+                    case "$1" in
+                        --subnet)
+                            subnet=$2
+                            shift 2
+                            ;;
+                        *) shift ;;
+                    esac
+                done
+                touch "${STATE_DIR}/networks/${network_name}"
+                printf '%s' "${subnet}" >"${STATE_DIR}/network-subnets/${network_name}"
+                ;;
+            inspect) inspect_resource network "${1}" ;;
+            delete)
+                rm -f "${STATE_DIR}/networks/${1}"
+                rm -f "${STATE_DIR}/network-subnets/${1}"
+                ;;
+            *) exit 1 ;;
+        esac
+        ;;
+    volume)
+        subcommand=${1-}
+        shift || true
+        case "${subcommand}" in
+            list) list_names "${STATE_DIR}/volumes" ;;
+            create) touch "${STATE_DIR}/volumes/$(last_argument "$@")" ;;
+            inspect) inspect_resource volume "${1}" ;;
+            delete) rm -f "${STATE_DIR}/volumes/${1}" ;;
+            *) exit 1 ;;
+        esac
+        ;;
+    image)
+        subcommand=${1-}
+        case "${subcommand}" in
+            inspect) printf '[{"id":"fake-image-id"}]\n' ;;
+            pull) exit 0 ;;
+            *) exit 1 ;;
+        esac
+        ;;
+    create)
+        create_arguments=("$@")
+        name=""
+        env_file=""
+        while [[ $# -gt 0 ]]; do
+            case "$1" in
+                --name)
+                    name=$2
+                    shift 2
+                    ;;
+                --env-file)
+                    env_file=$2
+                    shift 2
+                    ;;
+                --label|--network|--platform|--ulimit|--volume|--entrypoint|--publish)
+                    shift 2
+                    ;;
+                *)
+                    shift
+                    ;;
+            esac
+        done
+        [[ -n "${name}" ]]
+        printf '%s\n' "${create_arguments[@]}" >"${STATE_DIR}/create-arguments/${name}"
+        if [[ -n "${env_file}" ]]; then
+            cp "${env_file}" "${STATE_DIR}/env-files/${name}"
+        fi
+        touch "${STATE_DIR}/containers/${name}"
+        ;;
+    inspect)
+        inspect_resource container "${1}"
+        ;;
+    start)
+        touch "${STATE_DIR}/running/${1}"
+        ;;
+    stop)
+        for argument in "$@"; do
+            case "${argument}" in
+                --time|--signal) skip_next=true ;;
+                [0-9]*|SIG*) ;;
+                *) rm -f "${STATE_DIR}/running/${argument}" ;;
+            esac
+        done
+        ;;
+    delete)
+        for argument in "$@"; do
+            case "${argument}" in
+                --force|-f) ;;
+                *)
+                    rm -f "${STATE_DIR}/running/${argument}"
+                    rm -f "${STATE_DIR}/containers/${argument}"
+                    ;;
+            esac
+        done
+        ;;
+    exec)
+        echo 1
+        ;;
+    logs|copy)
+        exit 0
+        ;;
+    *)
+        echo "Unsupported fake container command: ${command} $*" >&2
+        exit 1
+        ;;
+esac
diff --git a/tests/fixtures/bin/curl b/tests/fixtures/bin/curl
new file mode 100755
index 0000000..5e611b4
--- /dev/null
+++ b/tests/fixtures/bin/curl
@@ -0,0 +1,4 @@
+#!/bin/bash
+
+set -eu
+printf '{"status":"ok"}\n'
diff --git a/tests/install-github-token-test.sh b/tests/install-github-token-test.sh
new file mode 100755
index 0000000..4bfdb5f
--- /dev/null
+++ b/tests/install-github-token-test.sh
@@ -0,0 +1,103 @@
+#!/bin/bash
+
+set -euo pipefail
+
+ROOT_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)
+TEMP_DIR=$(mktemp -d)
+trap 'rm -rf "$TEMP_DIR"' EXIT
+
+cat > "$TEMP_DIR/curl" <<'EOF'
+#!/bin/bash
+printf '%s\n' "$@" > "$CURL_ARGS_LOG"
+env > "${CURL_ARGS_LOG}.env"
+cat > "${CURL_ARGS_LOG}.stdin"
+EOF
+chmod +x "$TEMP_DIR/curl"
+
+mkdir "$TEMP_DIR/home"
+cat > "$TEMP_DIR/home/.curlrc" <<'EOF'
+url = "https://example.com/collect"
+header = "X-Leaked-From-Curlrc: yes"
+EOF
+
+run_api_curl() {
+    CURL_ARGS_LOG="$1" HOME="$TEMP_DIR/home" PATH="$TEMP_DIR:$PATH" UPDATE_GITHUB_TOKEN="${2:-}" \
+        GITHUB_TOKEN="github-fallback" GH_TOKEN="gh-fallback" \
+        bash -c 'source <(head -n -1 "$1"); github_api_curl -s "$2"' bash \
+        "$ROOT_DIR/deploy/install.sh" "https://api.github.com/repos/Wei-Shaw/sub2api/releases/latest"
+}
+
+run_api_curl "$TEMP_DIR/authenticated" "update-secret"
+test "$(head -n 1 "$TEMP_DIR/authenticated")" = '-q'
+grep -Fxq -- '--config' "$TEMP_DIR/authenticated"
+grep -Fxq -- '-' "$TEMP_DIR/authenticated"
+grep -Fxq -- '--globoff' "$TEMP_DIR/authenticated"
+grep -Fxq 'header = "Authorization: Bearer update-secret"' "$TEMP_DIR/authenticated.stdin"
+if grep -Fq 'update-secret' "$TEMP_DIR/authenticated"; then
+    echo "installer exposed the update token in curl argv" >&2
+    exit 1
+fi
+if grep -Eq 'update-secret|github-fallback|gh-fallback' "$TEMP_DIR/authenticated.env"; then
+    echo "installer exposed a token in curl environment" >&2
+    exit 1
+fi
+test "$(grep -Fxc 'https://api.github.com/repos/Wei-Shaw/sub2api/releases/latest' "$TEMP_DIR/authenticated")" -eq 1
+if grep -Fq 'example.com/collect' "$TEMP_DIR/authenticated" || grep -Fq 'X-Leaked-From-Curlrc' "$TEMP_DIR/authenticated" ||
+    grep -Fq 'example.com/collect' "$TEMP_DIR/authenticated.stdin" || grep -Fq 'X-Leaked-From-Curlrc' "$TEMP_DIR/authenticated.stdin"; then
+    echo "installer allowed hostile curl config into authenticated invocation" >&2
+    exit 1
+fi
+
+run_api_curl "$TEMP_DIR/anonymous"
+test "$(head -n 1 "$TEMP_DIR/anonymous")" = '-q'
+if grep -Eq 'github-fallback|gh-fallback' "$TEMP_DIR/anonymous.env"; then
+    echo "installer exposed a fallback token in anonymous curl environment" >&2
+    exit 1
+fi
+if grep -Fq 'Authorization:' "$TEMP_DIR/anonymous"; then
+    echo "installer unexpectedly used a fallback token" >&2
+    exit 1
+fi
+test ! -s "$TEMP_DIR/anonymous.stdin"
+test "$(grep -Fxc 'https://api.github.com/repos/Wei-Shaw/sub2api/releases/latest' "$TEMP_DIR/anonymous")" -eq 1
+if grep -Fq 'example.com/collect' "$TEMP_DIR/anonymous" || grep -Fq 'X-Leaked-From-Curlrc' "$TEMP_DIR/anonymous"; then
+    echo "installer allowed hostile curl config into anonymous invocation" >&2
+    exit 1
+fi
+
+assert_unsafe_invocation_rejected() {
+    local name=$1
+    shift
+    rm -f "$TEMP_DIR/$name" "$TEMP_DIR/$name.stdin"
+    if CURL_ARGS_LOG="$TEMP_DIR/$name" PATH="$TEMP_DIR:$PATH" UPDATE_GITHUB_TOKEN="update-secret" \
+        bash -c 'source <(head -n -1 "$1"); shift; github_api_curl "$@"' bash \
+        "$ROOT_DIR/deploy/install.sh" "$@" 2>/dev/null; then
+        echo "installer accepted unsafe curl invocation: $name" >&2
+        exit 1
+    fi
+    if [ -e "$TEMP_DIR/$name" ]; then
+        echo "installer invoked curl for unsafe request: $name" >&2
+        exit 1
+    fi
+}
+
+assert_unsafe_invocation_rejected non-api -s \
+    "https://github.com/Wei-Shaw/sub2api/releases/download/v1/asset"
+assert_unsafe_invocation_rejected mixed-host -s \
+    "https://api.github.com/repos/Wei-Shaw/sub2api/releases/latest" \
+    "https://example.com/collect"
+assert_unsafe_invocation_rejected multiple-api -s \
+    "https://api.github.com/repos/Wei-Shaw/sub2api/releases/latest" \
+    "https://api.github.com/repos/Wei-Shaw/sub2api/releases"
+assert_unsafe_invocation_rejected url-option -s --url \
+    "https://example.com/collect" \
+    "https://api.github.com/repos/Wei-Shaw/sub2api/releases/latest"
+
+# Every installer release API request must use the scoped helper.
+test "$(grep -c 'github_api_curl .*https://api.github.com/' "$ROOT_DIR/deploy/install.sh")" -eq 3
+
+# Asset and checksum downloads must continue to call curl directly.
+grep -Fq 'curl -sL "$download_url"' "$ROOT_DIR/deploy/install.sh"
+grep -Fq 'curl -sL "$checksum_url"' "$ROOT_DIR/deploy/install.sh"
+
+echo "install GitHub token checks passed"
