feat: 同步上游 320f5d4;扩展模型(多免费渠道/自定义映射/访问密钥/模型白名单)
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- .dockerignore +28 -28
- .gitattributes +12 -0
- .github/workflows/go-binaries.yml +0 -156
- .github/workflows/space-keepalive.yml +0 -78
- .gitignore +65 -58
- AGENTS.md +21 -0
- AutoBot.yml +164 -0
- Dockerfile +44 -42
- LICENSE +23 -22
- README.md +260 -160
- cmd/credit/main.go +300 -294
- cmd/credit/main_test.go +60 -0
- cmd/launcher/flags.go +1 -1
- cmd/launcher/main.go +1 -1
- cmd/login/main.go +461 -336
- cmd/login/realm_test.go +341 -169
- cmd/server/banner_test.go +57 -0
- cmd/server/cn_chat_base_test.go +49 -0
- cmd/server/config.go +0 -0
- cmd/server/config_example_test.go +48 -0
- cmd/server/config_save_test.go +211 -0
- cmd/server/config_test.go +1190 -861
- cmd/server/credit_floor_config_test.go +48 -48
- cmd/server/insecure_key_test.go +34 -0
- cmd/server/main.go +1124 -563
- cmd/server/upstream_port_config_test.go +21 -0
- cmd/server/wiring.go +40 -24
- cmd/signin/main.go +143 -140
- cmd/signin/main_test.go +31 -0
- cmd/sync/main.go +1 -1
- cmd/trial/classify_test.go +21 -0
- cmd/trial/main.go +133 -133
- config.default.json +154 -102
- config.example.json +206 -105
- credit.sh +14 -14
- docker-compose.yml +15 -15
- docker-entrypoint.sh +70 -69
- go.mod +19 -11
- go.sum +36 -12
- internal/alert/alert.go +366 -0
- internal/alert/alert_test.go +80 -0
- internal/auth/apikey_test.go +144 -0
- internal/auth/auth.go +628 -378
- internal/auth/auth_test.go +299 -266
- internal/auth/enterprise_test.go +39 -0
- internal/auth/expires_test.go +88 -0
- internal/auth/permhint_test.go +29 -29
- internal/auth/realm_test.go +284 -275
- internal/auth/recover_test.go +56 -0
- internal/auth/testdata/wbencrypted-auth.json +31 -0
.dockerignore
CHANGED
|
@@ -1,28 +1,28 @@
|
|
| 1 |
-
auths/
|
| 2 |
-
data/
|
| 3 |
-
storage/
|
| 4 |
-
*.tmp
|
| 5 |
-
.git/
|
| 6 |
-
.github/
|
| 7 |
-
.gitignore
|
| 8 |
-
docs/
|
| 9 |
-
scripts/__pycache__/
|
| 10 |
-
# 根目录已提交/未提交的二进制产物不进构建上下文(与 .gitignore 对齐)
|
| 11 |
-
/login
|
| 12 |
-
/credit
|
| 13 |
-
/wb2api
|
| 14 |
-
/wb2api-launcher
|
| 15 |
-
/wb2api-sync
|
| 16 |
-
/signin_bin
|
| 17 |
-
/wb2api.exe
|
| 18 |
-
/wb2api-launcher.exe
|
| 19 |
-
/wb2api-sync.exe
|
| 20 |
-
/login.exe
|
| 21 |
-
/credit.exe
|
| 22 |
-
# 真实配置不进镜像;镜像内模板是 config.default.json
|
| 23 |
-
config.json
|
| 24 |
-
PLAN.md
|
| 25 |
-
SPEC.md
|
| 26 |
-
LOOP.md
|
| 27 |
-
README.md
|
| 28 |
-
README.upstream.md
|
|
|
|
| 1 |
+
auths/
|
| 2 |
+
data/
|
| 3 |
+
storage/
|
| 4 |
+
*.tmp
|
| 5 |
+
.git/
|
| 6 |
+
.github/
|
| 7 |
+
.gitignore
|
| 8 |
+
docs/
|
| 9 |
+
scripts/__pycache__/
|
| 10 |
+
# 根目录已提交/未提交的二进制产物不进构建上下文(与 .gitignore 对齐)
|
| 11 |
+
/login
|
| 12 |
+
/credit
|
| 13 |
+
/wb2api
|
| 14 |
+
/wb2api-launcher
|
| 15 |
+
/wb2api-sync
|
| 16 |
+
/signin_bin
|
| 17 |
+
/wb2api.exe
|
| 18 |
+
/wb2api-launcher.exe
|
| 19 |
+
/wb2api-sync.exe
|
| 20 |
+
/login.exe
|
| 21 |
+
/credit.exe
|
| 22 |
+
# 真实配置不进镜像;镜像内模板是 config.default.json
|
| 23 |
+
config.json
|
| 24 |
+
PLAN.md
|
| 25 |
+
SPEC.md
|
| 26 |
+
LOOP.md
|
| 27 |
+
README.md
|
| 28 |
+
README.upstream.md
|
.gitattributes
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Go 源码与脚本一律 LF。
|
| 2 |
+
#
|
| 3 |
+
# 起因:internal/panel 的前端测试用 node 跑 app.js 里的真实函数,靠
|
| 4 |
+
# src.indexOf('\n}\n') 定位代码块边界。Windows 上 core.autocrlf=true 会把检出
|
| 5 |
+
# 写成 CRLF,这些匹配全部落空,本地必红而 Linux CI 常绿
|
| 6 |
+
# (TestAppJSEventsView / TestAppJSStoreRemarksReportsFailure)。
|
| 7 |
+
# 属性一旦写死,检出与规范化就与各人的 autocrlf 设置无关。
|
| 8 |
+
*.js text eol=lf
|
| 9 |
+
|
| 10 |
+
# 本文件自身也钉成 LF:否则 core.autocrlf=true 的机器下次检出会把它写成 CRLF,
|
| 11 |
+
# 提交时反复刷出 "LF will be replaced by CRLF" 警告(规则本身不受影响,只是噪音)。
|
| 12 |
+
.gitattributes text eol=lf
|
.github/workflows/go-binaries.yml
DELETED
|
@@ -1,156 +0,0 @@
|
|
| 1 |
-
name: go-binaries
|
| 2 |
-
|
| 3 |
-
# 可运行二进制构建/发布:
|
| 4 |
-
# - PR / push main → 测试 + 五平台编译验证(产物仅存 artifact,不发布)
|
| 5 |
-
# - push v* tag → 同上 + 打包上传到 GitHub Release(zip/tar.gz + checksums)
|
| 6 |
-
# 固化的发布纪律(曾两次人祸,见仓库 HANDOFF):-s -w 剥离、二进制版本串 == 源码
|
| 7 |
-
# appVersion、tag 版本 == 源码版本(-ci 后缀的测试 tag 豁免,用于演练发布线)。
|
| 8 |
-
on:
|
| 9 |
-
push:
|
| 10 |
-
branches: [main]
|
| 11 |
-
tags: ["v*"]
|
| 12 |
-
pull_request:
|
| 13 |
-
paths:
|
| 14 |
-
- "go.mod"
|
| 15 |
-
- "go.sum"
|
| 16 |
-
- "cmd/**"
|
| 17 |
-
- "internal/**"
|
| 18 |
-
- "config.example.json"
|
| 19 |
-
- ".github/workflows/go-binaries.yml"
|
| 20 |
-
workflow_dispatch:
|
| 21 |
-
|
| 22 |
-
concurrency:
|
| 23 |
-
group: ${{ github.workflow }}-${{ github.ref }}
|
| 24 |
-
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
|
| 25 |
-
|
| 26 |
-
permissions:
|
| 27 |
-
contents: read
|
| 28 |
-
|
| 29 |
-
jobs:
|
| 30 |
-
test:
|
| 31 |
-
runs-on: ubuntu-latest
|
| 32 |
-
steps:
|
| 33 |
-
- uses: actions/checkout@v4
|
| 34 |
-
- uses: actions/setup-go@v5
|
| 35 |
-
with:
|
| 36 |
-
go-version-file: go.mod
|
| 37 |
-
# ubuntu runner 自带 node → panel 包的 JS 运行时冒烟测试(TestAppJSTopLevelSmoke)会真实执行
|
| 38 |
-
- run: go test ./...
|
| 39 |
-
|
| 40 |
-
build:
|
| 41 |
-
needs: test
|
| 42 |
-
runs-on: ubuntu-latest
|
| 43 |
-
strategy:
|
| 44 |
-
fail-fast: false
|
| 45 |
-
matrix:
|
| 46 |
-
include:
|
| 47 |
-
- { goos: windows, goarch: amd64, ext: .zip }
|
| 48 |
-
- { goos: linux, goarch: amd64, ext: .tar.gz }
|
| 49 |
-
- { goos: linux, goarch: arm64, ext: .tar.gz }
|
| 50 |
-
- { goos: darwin, goarch: amd64, ext: .tar.gz }
|
| 51 |
-
- { goos: darwin, goarch: arm64, ext: .tar.gz }
|
| 52 |
-
steps:
|
| 53 |
-
- uses: actions/checkout@v4
|
| 54 |
-
- uses: actions/setup-go@v5
|
| 55 |
-
with:
|
| 56 |
-
go-version-file: go.mod
|
| 57 |
-
|
| 58 |
-
- name: 取源码版本号
|
| 59 |
-
id: ver
|
| 60 |
-
run: echo "v=$(grep -oP 'appVersion = "\K[^"]+' cmd/server/main.go)" >> "$GITHUB_OUTPUT"
|
| 61 |
-
|
| 62 |
-
- name: 构建(剥离符号,对齐本地发布口径)
|
| 63 |
-
env:
|
| 64 |
-
GOOS: ${{ matrix.goos }}
|
| 65 |
-
GOARCH: ${{ matrix.goarch }}
|
| 66 |
-
CGO_ENABLED: 0
|
| 67 |
-
run: go build -ldflags "-s -w" -o "wb2api${{ matrix.goos == 'windows' && '.exe' || '' }}" ./cmd/server
|
| 68 |
-
|
| 69 |
-
# 启动器单独构建:它是**独立程序**,作用是把新版的 wb2api 二进制换进去就能升级,
|
| 70 |
-
# 启动器本身不用动。所以刻意不参与上面的版本串断言(它有自己独立的版本号)。
|
| 71 |
-
- name: 构建启动器(独立,不参与网关版本串断言)
|
| 72 |
-
env:
|
| 73 |
-
GOOS: ${{ matrix.goos }}
|
| 74 |
-
GOARCH: ${{ matrix.goarch }}
|
| 75 |
-
CGO_ENABLED: 0
|
| 76 |
-
run: |
|
| 77 |
-
LEXT="${{ matrix.goos == 'windows' && '.exe' || '' }}"
|
| 78 |
-
go build -ldflags "-s -w" -o "wb2api-launcher${LEXT}" ./cmd/launcher
|
| 79 |
-
ls -la "wb2api-launcher${LEXT}"
|
| 80 |
-
|
| 81 |
-
# 版本串断言:二进制必须含源码 appVersion(防交叉编译矩阵里编错树/漏 ldflags)
|
| 82 |
-
- name: 断言二进制版本串
|
| 83 |
-
run: |
|
| 84 |
-
BIN="wb2api${{ matrix.goos == 'windows' && '.exe' || '' }}"
|
| 85 |
-
if ! grep -qa "${{ steps.ver.outputs.v }}" "$BIN"; then
|
| 86 |
-
echo "::error::binary missing version string ${{ steps.ver.outputs.v }}"
|
| 87 |
-
exit 1
|
| 88 |
-
fi
|
| 89 |
-
echo "version assert OK: ${{ steps.ver.outputs.v }}"
|
| 90 |
-
|
| 91 |
-
- name: 打包(windows=zip 三件套,其余=tar.gz)
|
| 92 |
-
run: |
|
| 93 |
-
V="${{ steps.ver.outputs.v }}"
|
| 94 |
-
V="${V%-panel}" # 文件名不带 -panel 后缀(wb2api-panel-v1.2.3-... 既有惯例)
|
| 95 |
-
case "${{ matrix.goos }}" in
|
| 96 |
-
windows)
|
| 97 |
-
NAME="wb2api-panel-v${V}-windows-amd64.zip"
|
| 98 |
-
zip -q "$NAME" wb2api.exe wb2api-launcher.exe config.example.json README.md
|
| 99 |
-
;;
|
| 100 |
-
*)
|
| 101 |
-
NAME="wb2api-panel-v${V}-${{ matrix.goos }}-${{ matrix.goarch }}.tar.gz"
|
| 102 |
-
tar czf "$NAME" wb2api wb2api-launcher config.example.json README.md
|
| 103 |
-
;;
|
| 104 |
-
esac
|
| 105 |
-
echo "name=$NAME" >> "$GITHUB_ENV"
|
| 106 |
-
|
| 107 |
-
- uses: actions/upload-artifact@v4
|
| 108 |
-
with:
|
| 109 |
-
name: ${{ env.name }}
|
| 110 |
-
path: ${{ env.name }}
|
| 111 |
-
retention-days: 7
|
| 112 |
-
|
| 113 |
-
# 仅 tag 触发:校验 tag == 源码版本(-ci 演练 tag 豁免)→ 汇总资产 → 建 Release
|
| 114 |
-
publish:
|
| 115 |
-
needs: build
|
| 116 |
-
if: startsWith(github.ref, 'refs/tags/v')
|
| 117 |
-
runs-on: ubuntu-latest
|
| 118 |
-
permissions:
|
| 119 |
-
contents: write
|
| 120 |
-
steps:
|
| 121 |
-
- uses: actions/checkout@v4
|
| 122 |
-
with:
|
| 123 |
-
fetch-depth: 0 # 取历史 tag 算 compare 链接
|
| 124 |
-
- name: tag 与源码版本一致性断言
|
| 125 |
-
run: |
|
| 126 |
-
SRC=$(grep -oP 'appVersion = "\K[^"]+' cmd/server/main.go)
|
| 127 |
-
SRC="${SRC%-panel}" # appVersion 带 -panel 后缀,比对前剥掉
|
| 128 |
-
TAG="${GITHUB_REF_NAME#v}"
|
| 129 |
-
if [[ "$GITHUB_REF_NAME" != *-ci ]]; then
|
| 130 |
-
if [[ "$TAG" != "$SRC" ]]; then
|
| 131 |
-
echo "::error::tag $GITHUB_REF_NAME 与源码 appVersion=$SRC 不一致(先提交版本号再打 tag)"
|
| 132 |
-
exit 1
|
| 133 |
-
fi
|
| 134 |
-
else
|
| 135 |
-
echo "演练 tag(-ci 后缀)跳过一致性断言:tag=$TAG src=$SRC"
|
| 136 |
-
fi
|
| 137 |
-
- uses: actions/download-artifact@v4
|
| 138 |
-
with:
|
| 139 |
-
path: dist
|
| 140 |
-
merge-multiple: true
|
| 141 |
-
- name: checksums
|
| 142 |
-
run: cd dist && sha256sum *.zip *.tar.gz > checksums.txt && ls -la
|
| 143 |
-
- name: 上一版 tag(compare 链接用)
|
| 144 |
-
id: prev
|
| 145 |
-
run: |
|
| 146 |
-
PREV=$(git describe --tags --abbrev=0 "${GITHUB_REF_NAME}^" 2>/dev/null || true)
|
| 147 |
-
echo "prev=${PREV}" >> "$GITHUB_OUTPUT"
|
| 148 |
-
- uses: softprops/action-gh-release@v2
|
| 149 |
-
with:
|
| 150 |
-
name: ${{ github.ref_name }}-panel
|
| 151 |
-
prerelease: ${{ contains(github.ref_name, '-') }}
|
| 152 |
-
body: |
|
| 153 |
-
CI 自动构建发布(五平台二进制 + checksums)。
|
| 154 |
-
|
| 155 |
-
完整变更:https://github.com/${{ github.repository }}/compare/${{ steps.prev.outputs.prev }}...${{ github.ref_name }}
|
| 156 |
-
files: dist/*
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
.github/workflows/space-keepalive.yml
DELETED
|
@@ -1,78 +0,0 @@
|
|
| 1 |
-
name: hf-space-keepalive
|
| 2 |
-
|
| 3 |
-
# 作用:定时给 Hugging Face Space 打一次 /healthz,阻止它因「48 小时无 HTTP 流量」被暂停。
|
| 4 |
-
# 为什么需要它:Space 一被暂停,它里面的定时任务(签到 / 活跃 / 保活)就全部停摆,
|
| 5 |
-
# 而唤醒要等 30~60 秒冷启动。
|
| 6 |
-
#
|
| 7 |
-
# 为什么用 GitHub Actions 而不是 Cloudflare Cron:
|
| 8 |
-
# Cloudflare 免费版**每个账号只有 5 个 cron 触发器**。如果那 5 个已经被别的 Worker 占了,
|
| 9 |
-
# 再给本 Worker 加 cron 会直接报 `code: 10072`(本仓库实测踩过)。GH Actions 没有这个限制。
|
| 10 |
-
#
|
| 11 |
-
# 为什么 6 小时一次就够:HF 的判定阈值是 **48 小时**,所以哪怕 GitHub 的定时任务
|
| 12 |
-
# 延迟几十分钟(高峰期常见)也毫无影响。刻意避开整点(:17)以减少排队。
|
| 13 |
-
#
|
| 14 |
-
# ⚠️⚠️ 必须打 Space 的**直连域名**(*.hf.space),**不要**改成公网入口
|
| 15 |
-
# cli.3216gemini.dpdns.org —— 实测那个入口的 `/healthz` 是 **Cloudflare 自己
|
| 16 |
-
# 应答的 `ok`**(响应带 cf-ray,但既没有网关的 `x-service`,也没有 HF 的
|
| 17 |
-
# `link: …/spaces/a3216/gcli2api` 头),请求根本没到 Space。拿它做保活
|
| 18 |
-
# 等于白 ping:返回 200 看着很健康,Space 却照样被暂停。
|
| 19 |
-
# (该入口只在 `/healthz` 上做了短路,`/status`、`/panel/*` 等仍是透传到 Space 的。)
|
| 20 |
-
#
|
| 21 |
-
# ⚠️ 两个 GitHub 侧的限制,知道一下就好:
|
| 22 |
-
# 1. 定时工作流只在**默认分支**上生效(所以这个文件要合进 main)。
|
| 23 |
-
# 2. 仓库连续 60 天没有任何提交/活动,GitHub 会自动停用定时工作流并给你发邮件;
|
| 24 |
-
# 到时在 Actions 页面点一下 "Enable workflow" 即可(或随便提交一次)。
|
| 25 |
-
|
| 26 |
-
on:
|
| 27 |
-
schedule:
|
| 28 |
-
- cron: "17 */6 * * *"
|
| 29 |
-
workflow_dispatch: # 也支持手动跑一次(Actions 页面 → Run workflow)
|
| 30 |
-
|
| 31 |
-
permissions: {}
|
| 32 |
-
|
| 33 |
-
concurrency:
|
| 34 |
-
group: hf-space-keepalive
|
| 35 |
-
cancel-in-progress: false
|
| 36 |
-
|
| 37 |
-
jobs:
|
| 38 |
-
ping:
|
| 39 |
-
runs-on: ubuntu-latest
|
| 40 |
-
timeout-minutes: 10
|
| 41 |
-
steps:
|
| 42 |
-
- name: 唤醒 / 保活 HF Space
|
| 43 |
-
run: |
|
| 44 |
-
set -uo pipefail
|
| 45 |
-
|
| 46 |
-
# 直连 Space 的域名(*.hf.space)。**不要**改成 cli.3216gemini.dpdns.org:
|
| 47 |
-
# 那个入口的 /healthz 由 Cloudflare 自己回 "ok",请求到不了 Space,
|
| 48 |
-
# 拿它保活是无效的(详见文件头注释)。
|
| 49 |
-
# 想顺带把公网入口也探一遍,可以加进来 —— 但它只证明边缘在,不证明 Space 醒着。
|
| 50 |
-
URLS=(
|
| 51 |
-
"https://a3216-gcli2api.hf.space/healthz"
|
| 52 |
-
)
|
| 53 |
-
|
| 54 |
-
fail=0
|
| 55 |
-
for url in "${URLS[@]}"; do
|
| 56 |
-
echo "::group::$url"
|
| 57 |
-
ok=0
|
| 58 |
-
# 冷启动可能要 30~60s,给足超时并重试三次。
|
| 59 |
-
for attempt in 1 2 3; do
|
| 60 |
-
code=$(curl -s -o /dev/null -w '%{http_code}' -m 90 "$url" || echo "000")
|
| 61 |
-
echo "第 ${attempt} 次: HTTP ${code}"
|
| 62 |
-
# 关键判据:只要拿到了**任何** HTTP 状态码,就说明 Space 是醒着的。
|
| 63 |
-
# 503 是网关「当前没有可用账号可服务」的业务语义,对保活而言完全正常。
|
| 64 |
-
# 只有 000(连不上/超时)才算这次没打到。
|
| 65 |
-
if [ "$code" != "000" ]; then
|
| 66 |
-
ok=1
|
| 67 |
-
break
|
| 68 |
-
fi
|
| 69 |
-
sleep 20
|
| 70 |
-
done
|
| 71 |
-
echo "::endgroup::"
|
| 72 |
-
if [ "$ok" -ne 1 ]; then
|
| 73 |
-
echo "::error::$url 三次都拿不到响应(Space 可能真的挂了,或正在长时间冷启动)"
|
| 74 |
-
fail=1
|
| 75 |
-
fi
|
| 76 |
-
done
|
| 77 |
-
|
| 78 |
-
exit "$fail"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
.gitignore
CHANGED
|
@@ -1,58 +1,65 @@
|
|
| 1 |
-
# Auth & secrets
|
| 2 |
-
auths/
|
| 3 |
-
data/
|
| 4 |
-
*.key
|
| 5 |
-
*.pem
|
| 6 |
-
*.env
|
| 7 |
-
.env
|
| 8 |
-
.env.*
|
| 9 |
-
# wrangler 本地变量(Cloudflare Worker 的 api_key 等,绝不进版本库)
|
| 10 |
-
.dev.vars
|
| 11 |
-
.dev.vars.*
|
| 12 |
-
# ……但模板必须能进版本库(里面只有占位符,没有真密钥)
|
| 13 |
-
!.dev.vars.example
|
| 14 |
-
.wrangler/
|
| 15 |
-
|
| 16 |
-
# Binaries (anchored to repo root only — bare "login"/"credit" would also ignore cmd/login/, cmd/credit/)
|
| 17 |
-
/login
|
| 18 |
-
/credit
|
| 19 |
-
/wb2api
|
| 20 |
-
/wb2api-launcher
|
| 21 |
-
/wb2api-sync
|
| 22 |
-
/signin_bin
|
| 23 |
-
|
| 24 |
-
# Config with secrets (use config.example.json)
|
| 25 |
-
config.json
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
.
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
!
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
/wb2api
|
| 51 |
-
/
|
| 52 |
-
/
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Auth & secrets
|
| 2 |
+
auths/
|
| 3 |
+
data/
|
| 4 |
+
*.key
|
| 5 |
+
*.pem
|
| 6 |
+
*.env
|
| 7 |
+
.env
|
| 8 |
+
.env.*
|
| 9 |
+
# wrangler 本地变量(Cloudflare Worker 的 api_key 等,绝不进版本库)
|
| 10 |
+
.dev.vars
|
| 11 |
+
.dev.vars.*
|
| 12 |
+
# ……但模板必须能进版本库(里面只有占位符,没有真密钥)
|
| 13 |
+
!.dev.vars.example
|
| 14 |
+
.wrangler/
|
| 15 |
+
|
| 16 |
+
# Binaries (anchored to repo root only — bare "login"/"credit" would also ignore cmd/login/, cmd/credit/)
|
| 17 |
+
/login
|
| 18 |
+
/credit
|
| 19 |
+
/wb2api
|
| 20 |
+
/wb2api-launcher
|
| 21 |
+
/wb2api-sync
|
| 22 |
+
/signin_bin
|
| 23 |
+
|
| 24 |
+
# Config with secrets (use config.example.json)
|
| 25 |
+
config.json
|
| 26 |
+
API_KEY.txt
|
| 27 |
+
|
| 28 |
+
# Build artifacts
|
| 29 |
+
*.tmp
|
| 30 |
+
__pycache__/
|
| 31 |
+
|
| 32 |
+
# Backups (contains auth tokens)
|
| 33 |
+
backups/
|
| 34 |
+
|
| 35 |
+
# IDE
|
| 36 |
+
.idea/
|
| 37 |
+
.vscode/
|
| 38 |
+
LOOP.md
|
| 39 |
+
PLAN.md
|
| 40 |
+
SPEC.md
|
| 41 |
+
docs/
|
| 42 |
+
|
| 43 |
+
# 设计/计划文档(但 README.md 与 go:embed 的内置提示词必须进版本库)
|
| 44 |
+
*.md
|
| 45 |
+
!README.md
|
| 46 |
+
!AGENTS.md
|
| 47 |
+
!internal/prompt/defaultprompt.md
|
| 48 |
+
|
| 49 |
+
# Windows binaries
|
| 50 |
+
/wb2api.exe
|
| 51 |
+
/wb2api-launcher.exe
|
| 52 |
+
/wb2api-sync.exe
|
| 53 |
+
/login.exe
|
| 54 |
+
/credit.exe
|
| 55 |
+
|
| 56 |
+
# 本地验证工具(判据逆向过程脚本,结论沉淀于 data/desktop-task-protocol.md)
|
| 57 |
+
/cmd/desktopverify*/
|
| 58 |
+
# 抓包取证脚本与原始报文(issue #51 等);结论写进 issue,不进仓库
|
| 59 |
+
/capture/
|
| 60 |
+
*.zip
|
| 61 |
+
server.exe
|
| 62 |
+
|
| 63 |
+
# 编译产物(16MB 误提交过一次,20261021)
|
| 64 |
+
/server
|
| 65 |
+
/app.toml
|
AGENTS.md
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# 版本发布
|
| 2 |
+
|
| 3 |
+
不跟上游 `1.x`。发版是打时间标签并推送,工作流看到 `v*` 才创建 Release。
|
| 4 |
+
|
| 5 |
+
版本号是上海时间,形如 `v2026.9.26.711`:
|
| 6 |
+
|
| 7 |
+
- `2026.9.26` 是日期,月和日不补零
|
| 8 |
+
- `711` 是 7:11,时不补零、分两位、不带秒
|
| 9 |
+
- 标签、Release、二进制用同一个号;二进制里不带 `v`,面板会自己加
|
| 10 |
+
- 不要打 `v1.x` 标签,也不要手改 `appVersion`
|
| 11 |
+
|
| 12 |
+
```bash
|
| 13 |
+
# 注意:本机(Windows / git-bash)没有 tzdata,`TZ=Asia/Shanghai date` 会**静默回落 UTC**,
|
| 14 |
+
# 打出来的标签整整早 8 小时。用显式加 8 小时,兼容有无 tzdata 两种环境:
|
| 15 |
+
VERSION=$(TZ=Asia/Shanghai date +%Y.%-m.%-d.%-H%M)
|
| 16 |
+
[ "$(TZ=UTC date +%H)" = "$(TZ=Asia/Shanghai date +%H)" ] && VERSION=$(date -u -d '+8 hours' +%Y.%-m.%-d.%-H%M)
|
| 17 |
+
git tag "v$VERSION"
|
| 18 |
+
git push origin "v$VERSION"
|
| 19 |
+
```
|
| 20 |
+
|
| 21 |
+
本地构建不注入,面板显示 `dev`。同一分钟再发才会撞号。
|
AutoBot.yml
ADDED
|
@@ -0,0 +1,164 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# AutoBot.yml —— 参考仓库清单与策略声明。
|
| 2 |
+
# 谁来读它见 .github/workflows/autobot.yml;改行为只改这里,不用改代码。
|
| 3 |
+
|
| 4 |
+
version: 2
|
| 5 |
+
|
| 6 |
+
upstream:
|
| 7 |
+
# 逐个 clone 下来交给 agent 分析的对象。
|
| 8 |
+
repos:
|
| 9 |
+
# 官方客户端行为的对照实现最全的一个:product.json 取值、每类请求的头/体形状、
|
| 10 |
+
# 备用入口与 HTTPDNS、业务码处置都有抓包依据,docs/official-client.md 是现成清单
|
| 11 |
+
- yreidev/workbuddy2api-panel
|
| 12 |
+
# 大仓(3.6k star),2026-11 恢复活跃推送后重新纳入:按行为吸收过的部分(11140
|
| 13 |
+
# 连坐、入站请求体上限)不重复提案,看的是它这之后新增的东西。
|
| 14 |
+
- ardeyouxipianyi/workbuddy2api-hub
|
| 15 |
+
- yuechuya/WorkBuddy2API-Gateway
|
| 16 |
+
- HUIdada1/AgentHub
|
| 17 |
+
- 3155498108/workbuddy-one
|
| 18 |
+
- OHCJ099/BuddyHub
|
| 19 |
+
- hj01857655/WorkBuddy2api
|
| 20 |
+
- JackAIStudio/dsh-workbuddy-dual
|
| 21 |
+
- smart-open/TraeWorkAssistant
|
| 22 |
+
- deltrivx/AutoBuddy
|
| 23 |
+
- techysy/CreditDaddy
|
| 24 |
+
- spdw666/multi-agent-checkin-dsh
|
| 25 |
+
- 1557335006/workbuddy-checkin-tool
|
| 26 |
+
- Yhx888/dsh-free-egg-credits
|
| 27 |
+
- Costben/workbuddy2api
|
| 28 |
+
- zr987459/workbuddy-app
|
| 29 |
+
- bhh3349/workbuddy2api-prime
|
| 30 |
+
- dhdbvcg/dsh-workbuddy-console
|
| 31 |
+
- chengzhi-c/pi-desktop-wtq-pool
|
| 32 |
+
- chengzhi-c/dsh-wtq-pool
|
| 33 |
+
- liberation8/hermes-workbuddy-provider
|
| 34 |
+
- Misaka10091/workbuddy2api-panel
|
| 35 |
+
- xibai6668/Android-AI-gateway
|
| 36 |
+
- pandarick916/workbuddy_checkin
|
| 37 |
+
- 2861292267/DSH-Official-WorkBuddy-Credit-Proxy
|
| 38 |
+
- ithtelab/workbuddy-manager
|
| 39 |
+
- caigee-cmd/cli2api
|
| 40 |
+
- FireOpalus/dsh-workbuddy2api
|
| 41 |
+
- NextAgentX/qoder-trae-workbuddy-switch
|
| 42 |
+
- sofs2005/w2a
|
| 43 |
+
- dingminhua/dsh-connect-workbuddy
|
| 44 |
+
- newtypepan12-svg/workbuddy-qiandao
|
| 45 |
+
- pkqzzt/workbuddy2api-panel-plus
|
| 46 |
+
- rcwowhoo/workbuddy-checkin
|
| 47 |
+
- lehuaner/SSHMonitor
|
| 48 |
+
- Faide-cyber/dsh-workbuddy
|
| 49 |
+
- wefewe/workbuddy2api
|
| 50 |
+
- ChaYeWuu/dsh-hyperworkbuddy
|
| 51 |
+
- wicm84266964/Buddy2api
|
| 52 |
+
- HXX-ita/workbuddy-checkin
|
| 53 |
+
- thintsing/agent-checkin
|
| 54 |
+
- stevenwang288/WorkBuddy-Daily
|
| 55 |
+
- study-yang/workbuddy2codex
|
| 56 |
+
- gray0128/pi-workbuddy-connect
|
| 57 |
+
- autumnsentiment/workbuddy-helper
|
| 58 |
+
- GeekFong/traework-checkin-assistant
|
| 59 |
+
- jerry9692/dsh-workbuddy2api-panel
|
| 60 |
+
- babygoton/WorkDaddy
|
| 61 |
+
- xbmaxx/cli2openai
|
| 62 |
+
- csszyft/wb2api
|
| 63 |
+
- PBY-CMYK/workbuddy-daily
|
| 64 |
+
- interli3/workbuddy-cloud-worker
|
| 65 |
+
- lxpkwwz/ql_scripts
|
| 66 |
+
- luoxh8/workbuddy-connect
|
| 67 |
+
- maiphucgiang/codebuddy2api
|
| 68 |
+
- a1007479270/aidaka
|
| 69 |
+
- fancylear/dsh-workbuddy-credits
|
| 70 |
+
- Libra1337/Reso2api
|
| 71 |
+
- jin66god/workbuddy2api-panel
|
| 72 |
+
- HanawaBanana/workbuddy2api
|
| 73 |
+
- CangShui/workbuddy-gateway
|
| 74 |
+
- Practice019/multi2api
|
| 75 |
+
- zhangdailin/API-Console
|
| 76 |
+
- aimod-cc/agent2api
|
| 77 |
+
- orangeboyChen/codebuddy2api
|
| 78 |
+
- Zhengyuuuui/workbuddy2api
|
| 79 |
+
- cty1735/wb-proxy
|
| 80 |
+
- mmqz/cpa-multi-plugins
|
| 81 |
+
- changexbc/workbuddy-switch
|
| 82 |
+
- 88lin/workbuddy-auto-signin
|
| 83 |
+
- baiyea/workbuddy2api-ui
|
| 84 |
+
- L0NE-6/WorkBuddy-Daily
|
| 85 |
+
- hawklithm/workbuddy2api
|
| 86 |
+
# 读本机桌面端登录态 + 设备风控头 X-Device-Token 的注入形态;敏感词二分查找工具可复用
|
| 87 |
+
- DistPub/workbuddy2api
|
| 88 |
+
# —— 多平台合集:Trae / Qoder / MiniMax / 豆包 的 IDE 账号池与签到池,看跨平台账号模型的抽象
|
| 89 |
+
- xu20060420fan-cell/workbuddy2api-panel
|
| 90 |
+
# 三协议 + 反检测头族 + 出站代理 + Prometheus 指标;mobile.css 与 /v1/search/messages 也回移自这里
|
| 91 |
+
- jiangwanying/wb2api-panel-plus
|
| 92 |
+
# 成长中心补登 / 连登兑换 / 盲盒的**实测接口契约**(方法分工、tier 字段、client_token、need_address)
|
| 93 |
+
- Ashfmit/workbuddy-scheduled-tasks
|
| 94 |
+
# Claude Code 指纹改写的实测对照表(哪几种写法被拦、哪种放行),含 [1m] 上下文后缀判定
|
| 95 |
+
- 9Ashwin/flow-one
|
| 96 |
+
# 管理密钥与网关 Key 分离 / HttpOnly 会话 Cookie / 登录限速,安全边界写得最清楚
|
| 97 |
+
- zhuweiyou/codearts2api
|
| 98 |
+
# ESP32 看板:接口只读内存快照(采集 2s、请求路径不查库),面板侧高频读取可借鉴
|
| 99 |
+
- kevinzgai/wd-hub
|
| 100 |
+
# 同类 DSH 插件:面板只读接口契约(/v1/balance-summary、/usage、/usage/analytics)
|
| 101 |
+
- HimA6652/dsh-workbuddy2api-hub
|
| 102 |
+
# 本地桥 + 指纹策略三档(defang / neutral / pass)+ 模型权限预检(11158 不写入目录)
|
| 103 |
+
- yang9582/workbuddy-connect
|
| 104 |
+
# 三协议本地桥 + 网页控制台(启停 / 诊断 / 体检 / 对话测试),诊断面做得最全
|
| 105 |
+
- Ianzhyh/workbuddy-to-dsh
|
| 106 |
+
# 少见的 /v2/embeddings 落地(bge-m3 1024 维,11351 未知模型),实验开关默认关
|
| 107 |
+
- EchoPing07/Buddy-2API-Go
|
| 108 |
+
# 九渠道合一:渠道内额度冷却与请求失败冷却分开记账,冷却期得分当 0 且路由硬剔除
|
| 109 |
+
- bluechonk/modelmux
|
| 110 |
+
# 组内加权轮询 + 虚拟模型组(客户端只点名组名,组内按权重分摊)+ 多 API Key
|
| 111 |
+
- RapidAI/RapidProxy
|
| 112 |
+
# 桌面���单 exe 形态:登录态管理 / 保活 / 猫猫旅行 / 本地网关的打包对照
|
| 113 |
+
- wbhubai/wb-desktop
|
| 114 |
+
# 35 项任务覆盖:对话类任务走免费模型省积分、新任务三路兜底(专家链 / 对话 / 通用激活)
|
| 115 |
+
- HonorC05/workbuddy-auto-checkin
|
| 116 |
+
# 多账号签到桌面端(Tauri):积分趋势与账号切换的交互参考
|
| 117 |
+
- onlyveyou/wb-checkin
|
| 118 |
+
# 四协议接入(Claude Code / Codex / pi)+ 313 条网关测试,测试面可对照
|
| 119 |
+
- 2439810550/buddy-deck
|
| 120 |
+
|
| 121 |
+
# 每片 4 个仓串行:串行是硬要求(免费档 10 RPM 共享一个池),
|
| 122 |
+
# 放大每片只为少付 setup 开销(每片一次 pip install ≈2 分钟)
|
| 123 |
+
shard_size: 4
|
| 124 |
+
# 每轮最多真正落地几条(每条要起 agent 写代码、跑测试、开 PR)。
|
| 125 |
+
# 每条最坏 60 分钟(方案 30 + diff 30)——抬到 3 就必须同步抬 implement 的
|
| 126 |
+
# job 超时,否则第 3 条落地到一半被 job 超时掐掉,前两条也白跑。
|
| 127 |
+
# 注意:值得度同分(本轮 60/89 都是 3)时排序退化成文件名字母序,选哪三条
|
| 128 |
+
# 没有语义,只是「同分里的三条」。
|
| 129 |
+
land_max: 3
|
| 130 |
+
|
| 131 |
+
policy:
|
| 132 |
+
base: main
|
| 133 |
+
branch_prefix: autobot/
|
| 134 |
+
label: autobot
|
| 135 |
+
|
| 136 |
+
# 硬禁项:这是给执行者的线,不是提示词里的软约束
|
| 137 |
+
never:
|
| 138 |
+
- push_main
|
| 139 |
+
- merge
|
| 140 |
+
- tag
|
| 141 |
+
- release
|
| 142 |
+
- deploy
|
| 143 |
+
- .github/workflows/**
|
| 144 |
+
- AGENTS.md
|
| 145 |
+
- config.example.json
|
| 146 |
+
|
| 147 |
+
# 「不做」清单:不是禁动作,是这个仓明确不要的能力。加一条只改这里。
|
| 148 |
+
# 三处都生效:分析提示词里带上(免得 agent 给 3 分)、报告命中的不落地(省掉 30 分钟实现)、
|
| 149 |
+
# 改动命中的在提交前驳回(报告写得干净、实现照做的也兜得住)。
|
| 150 |
+
# match 是不区分大小写的子串,会在报告正文和 diff 里各扫一遍。
|
| 151 |
+
off_limits:
|
| 152 |
+
- name: 多密钥 / 多人共用
|
| 153 |
+
why: 本仓只有一把管理员 api_key(httpauth.VerifyBearer 单串比对),不提供按人分发密钥、按人计量与限额。要多人用就自己搭一层反代。
|
| 154 |
+
match:
|
| 155 |
+
- client_keys
|
| 156 |
+
- clientkeys
|
| 157 |
+
- ClientKey
|
| 158 |
+
- api_keys
|
| 159 |
+
- admin_key_required
|
| 160 |
+
- 客户端密钥
|
| 161 |
+
- 多密钥
|
| 162 |
+
- 多 API Key
|
| 163 |
+
- 按人计量
|
| 164 |
+
- 按人限额
|
Dockerfile
CHANGED
|
@@ -1,42 +1,44 @@
|
|
| 1 |
-
# syntax=docker/dockerfile:1
|
| 2 |
-
# ---------------------------------------------------------------- build stage
|
| 3 |
-
|
| 4 |
-
|
| 5 |
-
|
| 6 |
-
|
| 7 |
-
COPY . .
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
&& CGO_ENABLED=0 go build -trimpath -ldflags="-s -w" -o /out/
|
| 13 |
-
&& CGO_ENABLED=0 go build -trimpath -ldflags="-s -w" -o /out/
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
#
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
COPY --from=build /out/wb2api
|
| 26 |
-
|
| 27 |
-
COPY --from=build /out/
|
| 28 |
-
COPY --from=build /out/
|
| 29 |
-
COPY login
|
| 30 |
-
COPY
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
|
|
|
|
|
|
|
|
| 1 |
+
# syntax=docker/dockerfile:1
|
| 2 |
+
# ---------------------------------------------------------------- build stage
|
| 3 |
+
# 必须跟 go.mod 的 `go` 指令一致(上游 1.26.0 起升到 1.26.10;低于它会在
|
| 4 |
+
# `go build` 时要求下载 toolchain,而构建阶段没有外网兜底)。
|
| 5 |
+
FROM golang:1.26.10-alpine AS build
|
| 6 |
+
WORKDIR /src
|
| 7 |
+
COPY go.mod go.sum ./
|
| 8 |
+
RUN go mod download
|
| 9 |
+
COPY . .
|
| 10 |
+
# 全静态二进制:镜像里直接跑脚本,无需 libc。
|
| 11 |
+
RUN CGO_ENABLED=0 go build -trimpath -ldflags="-s -w" -o /out/wb2api ./cmd/server \
|
| 12 |
+
&& CGO_ENABLED=0 go build -trimpath -ldflags="-s -w" -o /out/wb2api-launcher ./cmd/launcher \
|
| 13 |
+
&& CGO_ENABLED=0 go build -trimpath -ldflags="-s -w" -o /out/signin_bin ./cmd/signin \
|
| 14 |
+
&& CGO_ENABLED=0 go build -trimpath -ldflags="-s -w" -o /out/login ./cmd/login \
|
| 15 |
+
&& CGO_ENABLED=0 go build -trimpath -ldflags="-s -w" -o /out/credit ./cmd/credit
|
| 16 |
+
|
| 17 |
+
# -------------------------------------------------------------- runtime stage
|
| 18 |
+
FROM alpine:3.20
|
| 19 |
+
# python3:login.sh 的 JSON 解析 + 入口脚本的配置校验;tzdata:Asia/Shanghai。
|
| 20 |
+
RUN apk add --no-cache wget ca-certificates tzdata python3 bash \
|
| 21 |
+
&& mkdir -p /app/auths /app/data
|
| 22 |
+
ENV TZ=Asia/Shanghai
|
| 23 |
+
WORKDIR /app
|
| 24 |
+
|
| 25 |
+
COPY --from=build /out/wb2api /app/wb2api
|
| 26 |
+
# 独立启动器:本地/容器里都能「先同步凭证、再拉起网关」,且换 wb2api 版本时它不用重编。
|
| 27 |
+
COPY --from=build /out/wb2api-launcher /app/wb2api-launcher
|
| 28 |
+
COPY --from=build /out/signin_bin /app/signin_bin
|
| 29 |
+
COPY --from=build /out/login /app/login
|
| 30 |
+
COPY --from=build /out/credit /app/credit
|
| 31 |
+
COPY login.sh signin.sh credit.sh /app/
|
| 32 |
+
COPY scripts/probe_active.py /app/scripts/probe_active.py
|
| 33 |
+
# config.default.json 只是「镜像内模板」:仅当持久卷上还没有 config.json 时被拷过去一次。
|
| 34 |
+
# 真正的运行配置住在私有 Storage Bucket 上(见 docker-entrypoint.sh),公开仓库里不放 api_key。
|
| 35 |
+
COPY config.default.json /app/config.json
|
| 36 |
+
COPY docker-entrypoint.sh /app/docker-entrypoint.sh
|
| 37 |
+
RUN sed -i 's/\r$//' /app/login.sh /app/signin.sh /app/credit.sh /app/docker-entrypoint.sh \
|
| 38 |
+
&& chmod 755 /app/login.sh /app/signin.sh /app/credit.sh /app/docker-entrypoint.sh
|
| 39 |
+
|
| 40 |
+
# 以 root 运行:Storage Bucket 卷由挂载器创建,非 root 用户可能写不进去。
|
| 41 |
+
EXPOSE 7861
|
| 42 |
+
HEALTHCHECK --interval=30s --timeout=5s --start-period=10s \
|
| 43 |
+
CMD wget -qO- http://127.0.0.1:7861/healthz || exit 1
|
| 44 |
+
ENTRYPOINT ["/app/docker-entrypoint.sh"]
|
LICENSE
CHANGED
|
@@ -1,22 +1,23 @@
|
|
| 1 |
-
MIT License
|
| 2 |
-
|
| 3 |
-
Copyright (c) 2026 Sliverkiss (original project: https://github.com/Sliverkiss/workbuddy2api)
|
| 4 |
-
Copyright (c) 2026 linguo2625469 (
|
| 5 |
-
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
SOFTWARE
|
|
|
|
|
|
| 1 |
+
MIT License
|
| 2 |
+
|
| 3 |
+
Copyright (c) 2026 Sliverkiss (original project: https://github.com/Sliverkiss/workbuddy2api)
|
| 4 |
+
Copyright (c) 2026 linguo2625469 (fork: https://github.com/linguo2625469/workbuddy2api-panel)
|
| 5 |
+
Copyright (c) 2026 misakano7545 (this fork: https://github.com/misakano7545/workbuddy2api-panel)
|
| 6 |
+
|
| 7 |
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
| 8 |
+
of this software and associated documentation files (the "Software"), to deal
|
| 9 |
+
in the Software without restriction, including without limitation the rights
|
| 10 |
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
| 11 |
+
copies of the Software, and to permit persons to whom the Software is
|
| 12 |
+
furnished to do so, subject to the following conditions:
|
| 13 |
+
|
| 14 |
+
The above copyright notice and this permission notice shall be included in all
|
| 15 |
+
copies or substantial portions of the Software.
|
| 16 |
+
|
| 17 |
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
| 18 |
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
| 19 |
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
| 20 |
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
| 21 |
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
| 22 |
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
| 23 |
+
SOFTWARE.
|
README.md
CHANGED
|
@@ -1,160 +1,260 @@
|
|
| 1 |
-
---
|
| 2 |
-
title: WorkBuddy2API Panel
|
| 3 |
-
emoji: 🧩
|
| 4 |
-
colorFrom: indigo
|
| 5 |
-
colorTo: blue
|
| 6 |
-
sdk: docker
|
| 7 |
-
app_port: 7861
|
| 8 |
-
pinned: false
|
| 9 |
-
short_description: WorkBuddy 账号池网关,带面板,数据落私有存储桶
|
| 10 |
-
---
|
| 11 |
-
|
| 12 |
-
# WorkBuddy2API Panel — Hugging Face Spaces 部署
|
| 13 |
-
|
| 14 |
-
把腾讯 WorkBuddy 账号变成 OpenAI 兼容 API 的多账号网关(上游:
|
| 15 |
-
[
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
-
|
| 27 |
-
|
| 28 |
-
- `/app/storage/
|
| 29 |
-
- `/app/storage/
|
| 30 |
-
-
|
| 31 |
-
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
``
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
``
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
```
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
```
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
`
|
| 127 |
-
|
| 128 |
-
`
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
|
| 134 |
-
|
| 135 |
-
|
| 136 |
-
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
|
| 141 |
-
|
|
| 142 |
-
|
| 143 |
-
|
| 144 |
-
|
| 145 |
-
|
| 146 |
-
|
| 147 |
-
|
| 148 |
-
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
|
| 152 |
-
|
| 153 |
-
|
| 154 |
-
|
| 155 |
-
|
| 156 |
-
|
| 157 |
-
|
| 158 |
-
|
| 159 |
-
|
| 160 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
title: WorkBuddy2API Panel
|
| 3 |
+
emoji: 🧩
|
| 4 |
+
colorFrom: indigo
|
| 5 |
+
colorTo: blue
|
| 6 |
+
sdk: docker
|
| 7 |
+
app_port: 7861
|
| 8 |
+
pinned: false
|
| 9 |
+
short_description: WorkBuddy 账号池网关,带面板,数据落私有存储桶
|
| 10 |
+
---
|
| 11 |
+
|
| 12 |
+
# WorkBuddy2API Panel — Hugging Face Spaces 部署
|
| 13 |
+
|
| 14 |
+
把腾讯 WorkBuddy 账号变成 OpenAI 兼容 API 的多账号网关(上游:
|
| 15 |
+
[misakano7545/workbuddy2api-panel](https://github.com/misakano7545/workbuddy2api-panel);
|
| 16 |
+
原 [linguo2625469/workbuddy2api-panel](https://github.com/linguo2625469/workbuddy2api-panel) 已停止维护)。
|
| 17 |
+
本目录是**面向 HF Spaces 的部署分支**:唯一的改动是「持久化」。
|
| 18 |
+
|
| 19 |
+
## 这个分支改了什么
|
| 20 |
+
|
| 21 |
+
Spaces 的容器根文件系统是 ephemeral 的 —— 重启、��眠唤醒、重新构建都会清空。
|
| 22 |
+
原版把账号和状态放在容器内的 `./auths`、`./data`,在 Spaces 上等于每次重启都要重新登录账号。
|
| 23 |
+
|
| 24 |
+
本分支的做法:
|
| 25 |
+
|
| 26 |
+
- 一个**私有 Storage Bucket** 以卷的形式挂载到容器 `/app/storage`(读写);
|
| 27 |
+
- `docker-entrypoint.sh` 把运行配置指到卷上:
|
| 28 |
+
- `/app/storage/config.json` — 运行配置(含 `api_key`,私有卷上,公开仓库里没有)
|
| 29 |
+
- `/app/storage/auths/*.json` — 账号凭证
|
| 30 |
+
- `/app/storage/data/{state,usage,model,output_probes}.json`、`data/request-logs/` — 运行状态与请求归档
|
| 31 |
+
- `/app/storage/data/extensions.json` — 扩展模型配置(免费模型清单、自定义模型映射、访问密钥)
|
| 32 |
+
- 启动时做一次「写 + rename」自检(程序所有落盘都走 tmp+rename,FUSE 卷不支持 rename 的话持久化就是假的);
|
| 33 |
+
- **安全闸门**:`api_key` 为空等于完全关闭鉴权,入口脚本检测到空 key 会直接拒绝启动。
|
| 34 |
+
|
| 35 |
+
## 新增能力(本分支)
|
| 36 |
+
|
| 37 |
+
### 1. 免登录免费模型层
|
| 38 |
+
|
| 39 |
+
面板「扩展模型 → 免登录免费模型」把公共免费网关接进同一套 OpenAI 兼容接口。内置两个渠道,也可以自己加:
|
| 40 |
+
|
| 41 |
+
| 渠道 | 默认地址 | 说明 |
|
| 42 |
+
| --- | --- | --- |
|
| 43 |
+
| OpenCode Zen | `https://opencode.ai` | 免登录、免 Key;请求按官方 CLI 指纹整形(系统提示 / 13 工具集 / 会话与项目 id / uTLS Bun ClientHello)。上游按出口 IP 限量,429 会原样透传 |
|
| 44 |
+
| Kilo 免费池 | `https://ai-gateway.kilo.ai/api/v1` | 免登录、免 Key;只列 `isFree` 模型;提示词可能被上游记录,勿发敏感内容 |
|
| 45 |
+
| 自定义渠道 | 任意 OpenAI 兼容端点 | 面板填 Base URL、模型清单路径、对话路径、筛选方式(全部 / ID 含 free / `isFree=true`)与可选固定鉴权头即可 |
|
| 46 |
+
|
| 47 |
+
- 模型对外暴露为 `free:<渠道>/<id>`,`GET /v1/models` 会一并列出,并带 `channel=free`、`channel_label=<渠道显示名>`、`provider` 字段;
|
| 48 |
+
- 免费层不占 WorkBuddy 账号、不扣积分,也不受账号池熔断/预算限制;
|
| 49 |
+
- 面板可逐渠道启停、逐模型勾选;启动后自动刷新清单,之后每 6 小时一次,也可手动刷新;
|
| 50 |
+
- OpenCode 车道复刻了 [dsh-our-free-model](https://github.com/Ebony-Vinyl/dsh-our-free-model) 的请求整形层(官方提示、工具改名、会话/项目 id、Bun TLS 指纹),免费额度跟随上游出口 IP,换一个出口通常就能恢复。
|
| 51 |
+
|
| 52 |
+
模型列表里三类来源一眼可辨:WorkBuddy 账号池模型带 `WorkBuddy` 标签,免费渠道带绿色渠道名标签,自定义映射带 `自定义映射` 标签;面板「模型与档位」页也可按「免费通道 / 自定义映射」筛选。
|
| 53 |
+
|
| 54 |
+
### 2. 自定义模型映射
|
| 55 |
+
|
| 56 |
+
「扩展模型 → 自定义模型映射」添加 `模型名 → 目标模型 + 提示词`:
|
| 57 |
+
|
| 58 |
+
```json
|
| 59 |
+
{
|
| 60 |
+
"name": "my-assistant",
|
| 61 |
+
"target": "cn:deepseek-v4.1-flash",
|
| 62 |
+
"prompt": "回答不超过三句话。今天是 {{date}}。",
|
| 63 |
+
"mode": "append",
|
| 64 |
+
"description": "简洁中文助手",
|
| 65 |
+
"temperature": 0.3,
|
| 66 |
+
"max_tokens": 1024,
|
| 67 |
+
"enabled": true
|
| 68 |
+
}
|
| 69 |
+
```
|
| 70 |
+
|
| 71 |
+
- `mode`:`append`(默认,追加到 system 末尾)/ `prepend`(拼到首条 user 消息前)/ `replace`(替换 system 提示词);
|
| 72 |
+
- 提示词支持 `{{model}}`、`{{target}}`、`{{date}}`、`{{time}}`、`{{datetime}}` 占位符;
|
| 73 |
+
- `temperature` / `max_tokens` 可选覆盖客户端请求里的同名参数;
|
| 74 |
+
- 目标模型可以是 WorkBuddy 模型(`cn:` / `global:`)或免费模型(`free:*`);映射名同样出现在 `GET /v1/models`,响应里的 `model` 回显客户端请求名。
|
| 75 |
+
|
| 76 |
+
### 3. 访问密钥
|
| 77 |
+
|
| 78 |
+
「扩展模型 → 访问密钥」可生成多把 `sk-wb2api-…` 密钥,用于 `/v1/*` 与 `/status`(面板本身仍只认面板密钥)。
|
| 79 |
+
|
| 80 |
+
- **模型白名单 / 黑名单**:每行一个,支持 `*` 与 `?` 通配;黑名单优先。例如白名单 `free:opencode/*` + 黑名单 `cn:kimi-*`。被限制的模型不会出现在该密钥的 `/v1/models` 里,点名调用返回 403 `model_not_allowed`;
|
| 81 |
+
- 密钥可编辑备注、启停、删除,删除后立即 401;
|
| 82 |
+
- 主 `api_key` 不受限制;访问密钥与账号池共用同一个请求入口,不额外计费。
|
| 83 |
+
|
| 84 |
+
### 4. 面板密钥环境变量
|
| 85 |
+
|
| 86 |
+
`WB2A_PANEL_KEY` 存在时,面板登录密钥完全由该环境变量托管:面板里改 `api_key` 不会影响面板登录,适合把管理面板密钥与下游 API 密钥分开。未设置时沿用 `api_key`。
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
## 一次性配置(已经做完,此处仅为记录)
|
| 90 |
+
|
| 91 |
+
```python
|
| 92 |
+
from huggingface_hub import HfApi, Volume
|
| 93 |
+
api = HfApi()
|
| 94 |
+
api.create_bucket("a3216/wb2api-storage", private=True, exist_ok=True)
|
| 95 |
+
api.set_space_volumes(
|
| 96 |
+
"a3216/gcli2api",
|
| 97 |
+
volumes=[Volume(type="bucket", source="a3216/wb2api-storage", mount_path="/app/storage")],
|
| 98 |
+
)
|
| 99 |
+
```
|
| 100 |
+
|
| 101 |
+
`set_space_volumes` 是**替换**语义;要追加卷,先读 `get_space_runtime(...).volumes` 再一起传进去。
|
| 102 |
+
|
| 103 |
+
## 本地 ↔ 桶:凭证同步与独立启动器
|
| 104 |
+
|
| 105 |
+
**要解决的问题**:同一批账号常常要两处跑 —— 本地机器给工具提供低延迟 API,Space 负责定时签到。
|
| 106 |
+
两边各自维护 `auths/` 就会不同步:本地新加的号 Space 不知道(签到漏掉),
|
| 107 |
+
Space 刷新过的 token 本地还在用旧的;最糟的是两边**同时** refresh 同一个账号,
|
| 108 |
+
refreshToken 轮换后只有一方拿到新的,另一方直接掉线。
|
| 109 |
+
|
| 110 |
+
`wb2api-launcher` 就是为此而生:**先同步、后启动**。
|
| 111 |
+
|
| 112 |
+
```bash
|
| 113 |
+
# 独立 exe:不需要 Go / Python / PowerShell
|
| 114 |
+
wb2api-launcher # 同步 → 拉起网关 → 后台每 5 分钟对账
|
| 115 |
+
wb2api-launcher -status # 只看两边差异,不启动网关(有差异退出码 2)
|
| 116 |
+
wb2api-launcher -sync-only # 同步一次就退出
|
| 117 |
+
wb2api-launcher -no-sync # 离线启动(用本地已有凭证)
|
| 118 |
+
wb2api-launcher -h # 全部选项
|
| 119 |
+
```
|
| 120 |
+
|
| 121 |
+
它是个**独立程序**:与网关之间只有两个契约 ——「`wb2api -config <路径>` 能被拉起来」
|
| 122 |
+
和 `config.json` 里那几个键,不引用网关内部实现。所以**上游更新时你只需要换 `wb2api`,
|
| 123 |
+
启动器不用动**;同步引擎直接编在里面,也不需要第二个二进制。
|
| 124 |
+
`start.ps1` / `start.sh` 只是「没有二进制就 `go build`,然后 exec 启动器」的引导壳。
|
| 125 |
+
|
| 126 |
+
配置见 `config.example.json` 的 `sync` 段:
|
| 127 |
+
|
| 128 |
+
```json
|
| 129 |
+
"sync": {
|
| 130 |
+
"bucket": "a3216/wb2api-storage",
|
| 131 |
+
"token_file": "./data/hf_token.txt",
|
| 132 |
+
"writer": "auto"
|
| 133 |
+
}
|
| 134 |
+
```
|
| 135 |
+
|
| 136 |
+
两个方向的通道**刻意不同**(实测结论,不是设计偏好):
|
| 137 |
+
|
| 138 |
+
| 方向 | 通道 | 为什么 |
|
| 139 |
+
| --- | --- | --- |
|
| 140 |
+
| **读** | HF Hub REST(纯 HTTPS) | 不触发 Space 冷启动,它休眠/暂停时照样能拉 —— 启动那一次同步必须快 |
|
| 141 |
+
| **写** | 官方 `hf` CLI | Bucket 上传必须先做 **Xet 内容寻址上传**,拿文件 SHA-256 当 `xetHash` 会被服务端拒绝(`File not found in Xet storage`)。该协议不适合在 Go 里重造 |
|
| 142 |
+
|
| 143 |
+
冲突裁决(两端都有且内容不同时,按优先级):能被网关解析的一方赢 → **`expiresAt` 更晚的一方赢**
|
| 144 |
+
("谁刷新过用谁的",这条直接治凭证不同步)→ refreshToken 非空的一方赢 → mtime 更晚的一方赢 →
|
| 145 |
+
全平取本端(保证裁决确定性,否则两端会互相覆盖成无限拉锯)。
|
| 146 |
+
刻意**不做字段级合并**:accessToken 与 refreshToken 必须成对来自同一次刷新,拼起来只会造出永远刷不动的凭证。
|
| 147 |
+
也**不会删除账号** —— 删除只能在面板显式操作。
|
| 148 |
+
|
| 149 |
+
> ⚠️ **定时任务只能由一边跑。** 两边同时开签到/保活会互抢 refreshToken(轮换后只有一方拿到新的,
|
| 150 |
+
> 另一方直接掉线),这是同步工具救不了的**并发写冲突**。推荐分工:**Space 跑定时任务,本地只做 API** ——
|
| 151 |
+
> 把本地 `schedule.*_enabled` 全设 `false` 即可,网关处理请求时本来就会按需刷新 token,不影响可用性。
|
| 152 |
+
>
|
| 153 |
+
> ⚠️ **手动禁用 / 暂停不会被同步。** `disabled` / `paused` 是每端各自的运维意图,不属于凭证。
|
| 154 |
+
> 要两边一致请分别在两端面板里设置;也不要靠 `-include-data state.json` 去"抹平"它
|
| 155 |
+
> (那会把对端的冷却/熔断状态一起搬过来)。
|
| 156 |
+
|
| 157 |
+
## 保活:别让 Space 睡过去
|
| 158 |
+
|
| 159 |
+
cpu-basic 免费硬件**连续 48 小时没有任何 HTTP 流量就被暂停**,暂停期间网关的定时任务
|
| 160 |
+
(签到 / 领积分)不会执行。给它一个稳定的定时流量即可。
|
| 161 |
+
|
| 162 |
+
### 方案 A:GitHub Actions(推荐,不占 CF 配额)
|
| 163 |
+
|
| 164 |
+
仓库自带 `.github/workflows/space-keepalive.yml`:每 6 小时 ping 一次 Space 的 `/healthz`。
|
| 165 |
+
|
| 166 |
+
**为什么 6 小时就够**:HF 的判定阈值是 **48 小时**,所以有 8 倍余量;GitHub 定时任务
|
| 167 |
+
偶发延迟几十分钟毫无影响。它把**任何 HTTP 状态码都算成功**——`503` 是"当前没有可用账号"
|
| 168 |
+
的业务语义,但 Space 是醒着的,保活目的已经达到;只有连不上(`000`)才需要关注。
|
| 169 |
+
|
| 170 |
+
定时工作流只在**默认分支**生效;仓库连续 60 天无活动时 GitHub 会自动停用它
|
| 171 |
+
(Actions 页面点一下重新启用,或随便提交一次)。
|
| 172 |
+
|
| 173 |
+
> ⚠️ **保活必须打 Space 的直连域名(`*.hf.space`),不能打公网入口 `cli.3216gemini.dpdns.org`。**
|
| 174 |
+
> 实测那个入口的 `/healthz` 是 **Cloudflare 自己应答的 `ok`**
|
| 175 |
+
> (响应带 `cf-ray`,但既没有网关的 `x-service`,也没有 HF 的 `link: …/spaces/a3216/gcli2api` 头),
|
| 176 |
+
> **请求根本没到 Space** —— 拿它做保活会稳定返回 200、看着很健康,而 Space 照样被暂停。
|
| 177 |
+
> 该入口只在 `/healthz` 上短路,`/status`、`/panel/*` 仍是透传的。
|
| 178 |
+
> 工作流里因此写死直连域名并注明了原因,**别"顺手优化"掉**。
|
| 179 |
+
|
| 180 |
+
### 方案 B:Cloudflare Worker + Cron
|
| 181 |
+
|
| 182 |
+
`deploy/cloudflare-worker/` 是一份单文件 Worker:反代 `cli.3216gemini.dpdns.org/*`
|
| 183 |
+
(响应体流式回传,不破坏 SSE)+ `scheduled()` 保活。部��前可以先用
|
| 184 |
+
`node dev-server.mjs` 在本地把它验一遍(该脚本原样 import 同一个 `worker.js`,转发到真实 Space)。
|
| 185 |
+
|
| 186 |
+
> ⚠️ **Cloudflare 免费版的 cron 限制是「每个账号 5 个」,不是每个 Worker 5 个。**
|
| 187 |
+
> 名额满了 `wrangler deploy` 会给出**半成功**结果:`Uploaded` / `Deployed` 都成功,但紧接着
|
| 188 |
+
> `✘ [ERROR] ... reached the Workers Free limit of 5 cron triggers per account [code: 10072]`
|
| 189 |
+
> —— Worker 代码上线了、cron 没加上,于是它**空转,谁也唤不醒**。要么腾一个名额,要么用方案 A。
|
| 190 |
+
>
|
| 191 |
+
> 另外:`wrangler deploy` 打印的 `*.workers.dev` 地址在国内常因 DNS 污染而连不上,
|
| 192 |
+
> 这不代表部署失败;`wrangler tail` 若报 400,是它走的 WebSocket 被本地抓包代理挡了,
|
| 193 |
+
> 换 Dashboard → Worker → Logs 看即可。
|
| 194 |
+
|
| 195 |
+
## 环境变量
|
| 196 |
+
|
| 197 |
+
| 变量 | 作用 |
|
| 198 |
+
| --- | --- |
|
| 199 |
+
| `WB2A_API_KEY` | 覆盖配置文件里的 `api_key`(本项目默认不设,key 存在卷上的 config.json 里) |
|
| 200 |
+
| `WB2A_PANEL_KEY` | 单独托管管理面板的登录密钥(设置后面板不再认 `api_key`;`/v1/*` 仍用 `api_key` + 面板签发的访问密钥) |
|
| 201 |
+
| `WB2A_PERSIST_DIR` | 卷挂载点,默认 `/app/storage` |
|
| 202 |
+
| `WB2A_LISTEN` / `WB2A_AUTH_DIR` / `WB2A_STATE_FILE` … | 上游已有的同名覆盖,见上游 README |
|
| 203 |
+
|
| 204 |
+
## 运维
|
| 205 |
+
|
| 206 |
+
- **改 API 密钥**:面板「配置」页改完即热生效,并写回 `/app/storage/config.json`,重启不丢。
|
| 207 |
+
- **加账号**:面板里走 OAuth 添加,或把 `workbuddy-*.json` 丢进桶的 `auths/`。
|
| 208 |
+
- **备份**:桶本身就是备份。本地拉一份:
|
| 209 |
+
`hf buckets sync hf://buckets/a3216/wb2api-storage ./backup`
|
| 210 |
+
- **看日志**:`hf spaces logs a3216/gcli2api`(构建日志加 `--build`)。
|
| 211 |
+
- **部署新版本**:在能访问 `huggingface.co` 的机器上执行(网络受限环境里 HF 的 git/API 会被 DNS 污染,本机推不上去):
|
| 212 |
+
|
| 213 |
+
```bash
|
| 214 |
+
export HF_TOKEN=hf_xxx
|
| 215 |
+
python3 - <<'PY'
|
| 216 |
+
import os
|
| 217 |
+
from huggingface_hub import HfApi
|
| 218 |
+
api = HfApi(token=os.environ["HF_TOKEN"])
|
| 219 |
+
api.upload_folder(
|
| 220 |
+
repo_id="a3216/gcli2api", repo_type="space", folder_path=".",
|
| 221 |
+
commit_message="deploy: sync from GitHub main", delete_patterns=["*"],
|
| 222 |
+
ignore_patterns=[".git/*", ".git", ".github/*", "storage/*", "auths/*", "data/*", "dist/*", "**/__pycache__/*", "**/*.tmp"],
|
| 223 |
+
)
|
| 224 |
+
PY
|
| 225 |
+
```
|
| 226 |
+
|
| 227 |
+
仓库里的 `.github/workflows/deploy-hf.yml` 是同一件事的 Actions 版本(手动触发);
|
| 228 |
+
私有仓库需要先启用 Actions 计费,否则运行会停在 `startup_failure`。
|
| 229 |
+
本机也访问不了 `huggingface.co` 时,先开 [DevSidecar](https://github.com/docmirror/dev-sidecar)
|
| 230 |
+
或任意能访问 HF 的代理,再执行上面的命令。DevSidecar 本身需要一个可直连的出口;
|
| 231 |
+
纯内网/无直连的容器里它无法凭空打通。
|
| 232 |
+
- **免费硬件会自动休眠**:cpu-basic 上 48 小时没有 HTTP 流量就被暂停,下次有人访问自动唤醒。
|
| 233 |
+
唤醒后账号和状态从桶里恢复;网关的定时任务(签到/领积分)在暂停期间不会执行。
|
| 234 |
+
→ **保活方案见 [保活:别让 Space 睡过去](#保活别让-space-睡过去)。**
|
| 235 |
+
|
| 236 |
+
## 说明
|
| 237 |
+
|
| 238 |
+
上游项目与本文档的许可证见 `LICENSE`(上游为 MIT,本分支的部署脚本同样遵循)。
|
| 239 |
+
|
| 240 |
+
### 与上游的关系(同步口径)
|
| 241 |
+
|
| 242 |
+
- 本分支跟随 **misakano7545/workbuddy2api-panel**(模块路径同为
|
| 243 |
+
`github.com/misakano7545/workbuddy2api-panel`;老仓 `linguo2625469/*` 已归档)。
|
| 244 |
+
- 同步方式:**逐文件判定**。上游文件逐字节取上游版本;本分支只维护下面这批
|
| 245 |
+
「HF 专属」文件,冲突时以本分支为准:
|
| 246 |
+
`README.md`、`Dockerfile`、`docker-entrypoint.sh`、`docker-compose.yml`、
|
| 247 |
+
`config.default.json`、`config.example.json` 的 `sync` 段、`cmd/launcher/`、
|
| 248 |
+
`cmd/sync/`、`internal/syncer/`、`deploy/cloudflare-worker/`、
|
| 249 |
+
`start.ps1`、`start.sh`、`.github/workflows/space-keepalive.yml`、
|
| 250 |
+
`.github/workflows/deploy-hf.yml`、`binaries.yml` 里的启动器构建。
|
| 251 |
+
- 本分支新增、上游没有的扩展层:`internal/extstore/`、`internal/freemodel/`、
|
| 252 |
+
`internal/panel/extensions.go`、`internal/server/extensions.go`。
|
| 253 |
+
同步上游时这些文件整块保留;上游若新增同名路径,需按功能逐项合并。
|
| 254 |
+
- 上游的 `.github/workflows/autobot.yml`(每日自动开 PR 的机器人)**不进本分支**:
|
| 255 |
+
这里是部署分支,不需要自动改代码,留着只会每天刷 PR。
|
| 256 |
+
- Go 工具链跟随上游 `go.mod`(当前 `1.26.10`):Dockerfile 的构建阶段必须同步改版本,
|
| 257 |
+
否则 `go build` 会去下载 toolchain。
|
| 258 |
+
- 已知上游遗留:`internal/upstream` 的 `TestChatTimingObservation` 在上游 HEAD 上
|
| 259 |
+
本身就失败(Prep/Do 测不到)——纯观测路径,与签到/保活无关,故不阻塞本分支。
|
| 260 |
+
|
cmd/credit/main.go
CHANGED
|
@@ -1,294 +1,300 @@
|
|
| 1 |
-
// credit.go — WorkBuddy 积分查询(全部账号 + 总计),JSON 输出到 stdout。
|
| 2 |
-
//
|
| 3 |
-
// 用法:
|
| 4 |
-
//
|
| 5 |
-
// go run ./cmd/credit # 或编译后 ./credit
|
| 6 |
-
//
|
| 7 |
-
// 输出结构:
|
| 8 |
-
//
|
| 9 |
-
// {"service":"workbuddy","ts":N,
|
| 10 |
-
// "total":{"remain":N,"used":N,"size":N,"accounts":N,"ok":N,"failed":N},
|
| 11 |
-
// "accounts":[{"uid","nickname","remain","used","size","packages","ok","error?"}]}
|
| 12 |
-
//
|
| 13 |
-
// 接口与聚合逻辑:POST codebuddy.cn/v2/billing/meter/get-user-resource,聚合所有 package 的
|
| 14 |
-
// Cycle* 字段,TotalDosage 作 size 下限。
|
| 15 |
-
package main
|
| 16 |
-
|
| 17 |
-
import (
|
| 18 |
-
"bytes"
|
| 19 |
-
"encoding/json"
|
| 20 |
-
"fmt"
|
| 21 |
-
"
|
| 22 |
-
"
|
| 23 |
-
"
|
| 24 |
-
"
|
| 25 |
-
"
|
| 26 |
-
"time"
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
//
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
//
|
| 36 |
-
//
|
| 37 |
-
|
| 38 |
-
//
|
| 39 |
-
//
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
}
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
|
| 134 |
-
|
| 135 |
-
|
| 136 |
-
if
|
| 137 |
-
|
| 138 |
-
}
|
| 139 |
-
|
| 140 |
-
|
| 141 |
-
|
| 142 |
-
|
| 143 |
-
|
| 144 |
-
|
| 145 |
-
|
| 146 |
-
|
| 147 |
-
|
| 148 |
-
|
| 149 |
-
|
| 150 |
-
}
|
| 151 |
-
|
| 152 |
-
|
| 153 |
-
|
| 154 |
-
|
| 155 |
-
|
| 156 |
-
|
| 157 |
-
|
| 158 |
-
|
| 159 |
-
|
| 160 |
-
|
| 161 |
-
|
| 162 |
-
|
| 163 |
-
|
| 164 |
-
|
| 165 |
-
|
| 166 |
-
|
| 167 |
-
|
| 168 |
-
|
| 169 |
-
|
| 170 |
-
|
| 171 |
-
|
| 172 |
-
|
| 173 |
-
|
| 174 |
-
|
| 175 |
-
|
| 176 |
-
|
| 177 |
-
|
| 178 |
-
|
| 179 |
-
|
| 180 |
-
|
| 181 |
-
|
| 182 |
-
|
| 183 |
-
|
| 184 |
-
|
| 185 |
-
|
| 186 |
-
|
| 187 |
-
|
| 188 |
-
|
| 189 |
-
|
| 190 |
-
|
| 191 |
-
|
| 192 |
-
|
| 193 |
-
|
| 194 |
-
|
| 195 |
-
|
| 196 |
-
|
| 197 |
-
|
| 198 |
-
|
| 199 |
-
|
| 200 |
-
|
| 201 |
-
|
| 202 |
-
|
| 203 |
-
|
| 204 |
-
|
| 205 |
-
|
| 206 |
-
|
| 207 |
-
if
|
| 208 |
-
|
| 209 |
-
|
| 210 |
-
|
| 211 |
-
|
| 212 |
-
|
| 213 |
-
|
| 214 |
-
|
| 215 |
-
|
| 216 |
-
|
| 217 |
-
if
|
| 218 |
-
res.Error =
|
| 219 |
-
|
| 220 |
-
|
| 221 |
-
|
| 222 |
-
|
| 223 |
-
|
| 224 |
-
res.
|
| 225 |
-
}
|
| 226 |
-
|
| 227 |
-
|
| 228 |
-
|
| 229 |
-
|
| 230 |
-
|
| 231 |
-
|
| 232 |
-
|
| 233 |
-
|
| 234 |
-
|
| 235 |
-
|
| 236 |
-
|
| 237 |
-
|
| 238 |
-
|
| 239 |
-
|
| 240 |
-
|
| 241 |
-
if a.
|
| 242 |
-
|
| 243 |
-
}
|
| 244 |
-
|
| 245 |
-
|
| 246 |
-
|
| 247 |
-
|
| 248 |
-
|
| 249 |
-
|
| 250 |
-
|
| 251 |
-
|
| 252 |
-
|
| 253 |
-
|
| 254 |
-
|
| 255 |
-
|
| 256 |
-
|
| 257 |
-
|
| 258 |
-
|
| 259 |
-
|
| 260 |
-
|
| 261 |
-
|
| 262 |
-
|
| 263 |
-
|
| 264 |
-
|
| 265 |
-
|
| 266 |
-
|
| 267 |
-
|
| 268 |
-
|
| 269 |
-
|
| 270 |
-
|
| 271 |
-
|
| 272 |
-
|
| 273 |
-
|
| 274 |
-
|
| 275 |
-
|
| 276 |
-
|
| 277 |
-
|
| 278 |
-
|
| 279 |
-
|
| 280 |
-
|
| 281 |
-
|
| 282 |
-
|
| 283 |
-
|
| 284 |
-
|
| 285 |
-
|
| 286 |
-
|
| 287 |
-
|
| 288 |
-
|
| 289 |
-
|
| 290 |
-
|
| 291 |
-
|
| 292 |
-
|
| 293 |
-
|
| 294 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
// credit.go — WorkBuddy 积分查询(全部账号 + 总计),JSON 输出到 stdout。
|
| 2 |
+
//
|
| 3 |
+
// 用法:
|
| 4 |
+
//
|
| 5 |
+
// go run ./cmd/credit # 或编译后 ./credit
|
| 6 |
+
//
|
| 7 |
+
// 输出结构:
|
| 8 |
+
//
|
| 9 |
+
// {"service":"workbuddy","ts":N,
|
| 10 |
+
// "total":{"remain":N,"used":N,"size":N,"accounts":N,"ok":N,"failed":N},
|
| 11 |
+
// "accounts":[{"uid","nickname","remain","used","size","packages","ok","error?"}]}
|
| 12 |
+
//
|
| 13 |
+
// 接口与聚合逻辑:POST codebuddy.cn/v2/billing/meter/get-user-resource,聚合所有 package 的
|
| 14 |
+
// Cycle* 字段,TotalDosage 作 size 下限。
|
| 15 |
+
package main
|
| 16 |
+
|
| 17 |
+
import (
|
| 18 |
+
"bytes"
|
| 19 |
+
"encoding/json"
|
| 20 |
+
"fmt"
|
| 21 |
+
"log"
|
| 22 |
+
"net/http"
|
| 23 |
+
"os"
|
| 24 |
+
"path/filepath"
|
| 25 |
+
"sort"
|
| 26 |
+
"time"
|
| 27 |
+
|
| 28 |
+
"github.com/misakano7545/workbuddy2api-panel/internal/auth"
|
| 29 |
+
"github.com/misakano7545/workbuddy2api-panel/internal/upstream"
|
| 30 |
+
)
|
| 31 |
+
|
| 32 |
+
const billingBaseCN = "https://www.codebuddy.cn"
|
| 33 |
+
|
| 34 |
+
// billingBaseGlobal 国际版计费域。global 账号打 CN 域会得到 401:
|
| 35 |
+
// www.codebuddy.cn 不认 workbuddy.ai 的 token(实测 401,workbuddy.ai 同 token 为 code=0)。
|
| 36 |
+
const billingBaseGlobal = "https://www.workbuddy.ai"
|
| 37 |
+
|
| 38 |
+
// billingBaseFor 按账号 realm 选择计费域(判定收敛到 auth.IsGlobal,与主程序
|
| 39 |
+
// 同一口径;此前手抄的 realm/domain 推断靠人工同步)。cmd/credit 早先对所有
|
| 40 |
+
// 账号硬编码 CN 域,导致 global 账号余额查询恒返回 401。
|
| 41 |
+
func billingBaseFor(a *auth.Auth) string {
|
| 42 |
+
if a.IsGlobal() {
|
| 43 |
+
return billingBaseGlobal
|
| 44 |
+
}
|
| 45 |
+
return billingBaseCN
|
| 46 |
+
}
|
| 47 |
+
|
| 48 |
+
type accountResult struct {
|
| 49 |
+
UID string `json:"uid"`
|
| 50 |
+
Nickname string `json:"nickname"`
|
| 51 |
+
Remain *int64 `json:"remain"`
|
| 52 |
+
Used *int64 `json:"used"`
|
| 53 |
+
Size *int64 `json:"size"`
|
| 54 |
+
Packages int `json:"packages,omitempty"`
|
| 55 |
+
OK bool `json:"ok"`
|
| 56 |
+
Error string `json:"error,omitempty"`
|
| 57 |
+
}
|
| 58 |
+
|
| 59 |
+
type resourcePackage struct {
|
| 60 |
+
CapacityRemain int64 `json:"CapacityRemain"`
|
| 61 |
+
CapacityUsed int64 `json:"CapacityUsed"`
|
| 62 |
+
CapacitySize int64 `json:"CapacitySize"`
|
| 63 |
+
CycleCapacityRemain int64 `json:"CycleCapacityRemain"`
|
| 64 |
+
CycleCapacityUsed int64 `json:"CycleCapacityUsed"`
|
| 65 |
+
CycleCapacitySize int64 `json:"CycleCapacitySize"`
|
| 66 |
+
}
|
| 67 |
+
|
| 68 |
+
// packageRemainUsed 与 billing.go:203-258 一致
|
| 69 |
+
func packageRemainUsed(a resourcePackage) (remain, used, size int64) {
|
| 70 |
+
if a.CycleCapacitySize > 0 {
|
| 71 |
+
remain = a.CycleCapacityRemain
|
| 72 |
+
size = a.CycleCapacitySize
|
| 73 |
+
if remain < 0 {
|
| 74 |
+
remain = 0
|
| 75 |
+
}
|
| 76 |
+
if remain > size {
|
| 77 |
+
remain = size
|
| 78 |
+
}
|
| 79 |
+
used = size - remain
|
| 80 |
+
if a.CycleCapacityUsed > used {
|
| 81 |
+
used = a.CycleCapacityUsed
|
| 82 |
+
if size >= used {
|
| 83 |
+
remain = size - used
|
| 84 |
+
}
|
| 85 |
+
}
|
| 86 |
+
return remain, used, size
|
| 87 |
+
}
|
| 88 |
+
remain = a.CapacityRemain
|
| 89 |
+
used = a.CapacityUsed
|
| 90 |
+
size = a.CapacitySize
|
| 91 |
+
if used == 0 && size > remain {
|
| 92 |
+
used = size - remain
|
| 93 |
+
}
|
| 94 |
+
return remain, used, size
|
| 95 |
+
}
|
| 96 |
+
|
| 97 |
+
func fetchUserResource(a *auth.Auth) (remain, used, size int64, packs int, err error) {
|
| 98 |
+
now := time.Now()
|
| 99 |
+
body, _ := json.Marshal(map[string]any{
|
| 100 |
+
"PageNumber": 1,
|
| 101 |
+
"PageSize": 100,
|
| 102 |
+
"ProductCode": "p_tcaca",
|
| 103 |
+
"Status": []int{0, 3},
|
| 104 |
+
"PackageEndTimeRangeBegin": now.Format("2006-01-02 15:04:05"),
|
| 105 |
+
"PackageEndTimeRangeEnd": now.Add(365 * 101 * 24 * time.Hour).Format("2006-01-02 15:04:05"),
|
| 106 |
+
})
|
| 107 |
+
base := billingBaseFor(a)
|
| 108 |
+
// global 域无 /v2 前缀(与 internal/upstream 的 billingMeterPaths 同口径)。
|
| 109 |
+
path := "/v2/billing/meter/get-user-resource"
|
| 110 |
+
if base == billingBaseGlobal {
|
| 111 |
+
path = "/billing/meter/get-user-resource"
|
| 112 |
+
}
|
| 113 |
+
req, err := http.NewRequest(http.MethodPost, base+path, bytes.NewReader(body))
|
| 114 |
+
if err != nil {
|
| 115 |
+
return 0, 0, 0, 0, err
|
| 116 |
+
}
|
| 117 |
+
req.Header.Set("Authorization", "Bearer "+a.AccessToken)
|
| 118 |
+
req.Header.Set("Accept", "application/json")
|
| 119 |
+
req.Header.Set("Content-Type", "application/json")
|
| 120 |
+
if a.UID != "" {
|
| 121 |
+
req.Header.Set("X-User-Id", a.UID)
|
| 122 |
+
}
|
| 123 |
+
if a.EnterpriseID != "" {
|
| 124 |
+
req.Header.Set("X-Enterprise-Id", a.EnterpriseID)
|
| 125 |
+
req.Header.Set("X-Tenant-Id", a.EnterpriseID)
|
| 126 |
+
}
|
| 127 |
+
if a.Domain != "" {
|
| 128 |
+
req.Header.Set("X-Domain", a.Domain)
|
| 129 |
+
}
|
| 130 |
+
client := &http.Client{Timeout: 20 * time.Second}
|
| 131 |
+
resp, err := client.Do(req)
|
| 132 |
+
if err != nil {
|
| 133 |
+
return 0, 0, 0, 0, err
|
| 134 |
+
}
|
| 135 |
+
defer resp.Body.Close()
|
| 136 |
+
if resp.StatusCode >= 400 {
|
| 137 |
+
return 0, 0, 0, 0, fmt.Errorf("http %d", resp.StatusCode)
|
| 138 |
+
}
|
| 139 |
+
var env struct {
|
| 140 |
+
Code int `json:"code"`
|
| 141 |
+
Msg string `json:"msg"`
|
| 142 |
+
Data struct {
|
| 143 |
+
Response struct {
|
| 144 |
+
Data struct {
|
| 145 |
+
TotalDosage int64 `json:"TotalDosage"`
|
| 146 |
+
Accounts []resourcePackage `json:"Accounts"`
|
| 147 |
+
} `json:"Data"`
|
| 148 |
+
} `json:"Response"`
|
| 149 |
+
} `json:"data"`
|
| 150 |
+
}
|
| 151 |
+
if err := json.NewDecoder(resp.Body).Decode(&env); err != nil {
|
| 152 |
+
return 0, 0, 0, 0, err
|
| 153 |
+
}
|
| 154 |
+
if env.Code != 0 {
|
| 155 |
+
return 0, 0, 0, 0, fmt.Errorf("code=%d %s", env.Code, env.Msg)
|
| 156 |
+
}
|
| 157 |
+
for _, a := range env.Data.Response.Data.Accounts {
|
| 158 |
+
r, u, s := packageRemainUsed(a)
|
| 159 |
+
remain += r
|
| 160 |
+
used += u
|
| 161 |
+
size += s
|
| 162 |
+
}
|
| 163 |
+
packs = len(env.Data.Response.Data.Accounts)
|
| 164 |
+
if size > 0 {
|
| 165 |
+
if derived := size - remain; derived > used {
|
| 166 |
+
used = derived
|
| 167 |
+
}
|
| 168 |
+
}
|
| 169 |
+
if dosage := env.Data.Response.Data.TotalDosage; dosage > size {
|
| 170 |
+
size = dosage
|
| 171 |
+
if derived := size - remain; derived > used {
|
| 172 |
+
used = derived
|
| 173 |
+
}
|
| 174 |
+
}
|
| 175 |
+
return remain, used, size, packs, nil
|
| 176 |
+
}
|
| 177 |
+
|
| 178 |
+
func main() {
|
| 179 |
+
pretty := len(os.Args) > 1 && os.Args[1] == "-pretty"
|
| 180 |
+
authDir := "./auths"
|
| 181 |
+
if v := os.Getenv("WB2A_AUTH_DIR"); v != "" {
|
| 182 |
+
authDir = v
|
| 183 |
+
}
|
| 184 |
+
files, _ := filepath.Glob(filepath.Join(authDir, "workbuddy-*.json"))
|
| 185 |
+
sort.Strings(files)
|
| 186 |
+
|
| 187 |
+
up := upstream.New()
|
| 188 |
+
accounts := make([]accountResult, 0, len(files))
|
| 189 |
+
for _, f := range files {
|
| 190 |
+
// 坏文件不再静默跳过(跳过会让 total.accounts 与目录文件数对不上且无任何
|
| 191 |
+
// 线索):计入明细行,与 signin/trial 的 LOAD_ERR 口径一致。auth.Parse 同时
|
| 192 |
+
// 支持嵌套形与扁平形手写文件(此前自定义结构只认嵌套形,扁平形的 token
|
| 193 |
+
// 解析为空、报误导性的 no accessToken)。
|
| 194 |
+
raw, err := os.ReadFile(f)
|
| 195 |
+
var a *auth.Auth
|
| 196 |
+
if err == nil {
|
| 197 |
+
a, err = auth.Parse(raw)
|
| 198 |
+
}
|
| 199 |
+
if err != nil {
|
| 200 |
+
accounts = append(accounts, accountResult{UID: "", Nickname: filepath.Base(f), Error: "load: " + err.Error()})
|
| 201 |
+
continue
|
| 202 |
+
}
|
| 203 |
+
a.FilePath = f
|
| 204 |
+
res := accountResult{UID: a.UID, Nickname: a.Nickname}
|
| 205 |
+
// 过期 token 自动 refresh 并写回(与 signin 同款;此前 token 一过期全部
|
| 206 |
+
// 账号 failed,必须先跑一遍 signin 才能救回来)。
|
| 207 |
+
if a.NeedsRefresh(2 * time.Hour) {
|
| 208 |
+
if rerr := up.RefreshTokenIfNeeded(a, 2*time.Hour); rerr != nil {
|
| 209 |
+
res.Error = "refresh: " + rerr.Error()
|
| 210 |
+
accounts = append(accounts, res)
|
| 211 |
+
continue
|
| 212 |
+
}
|
| 213 |
+
if serr := a.SaveAtomicRetry(); serr != nil {
|
| 214 |
+
log.Printf("credit %s save: %v", a.UID, serr)
|
| 215 |
+
}
|
| 216 |
+
}
|
| 217 |
+
if a.AccessToken == "" {
|
| 218 |
+
res.Error = "no accessToken"
|
| 219 |
+
accounts = append(accounts, res)
|
| 220 |
+
continue
|
| 221 |
+
}
|
| 222 |
+
remain, used, size, packs, err := fetchUserResource(a)
|
| 223 |
+
if err != nil {
|
| 224 |
+
res.Error = err.Error()
|
| 225 |
+
} else {
|
| 226 |
+
res.Remain = &remain
|
| 227 |
+
res.Used = &used
|
| 228 |
+
res.Size = &size
|
| 229 |
+
res.Packages = packs
|
| 230 |
+
res.OK = true
|
| 231 |
+
}
|
| 232 |
+
accounts = append(accounts, res)
|
| 233 |
+
time.Sleep(200 * time.Millisecond)
|
| 234 |
+
}
|
| 235 |
+
|
| 236 |
+
var totalRemain, totalUsed, totalSize int64
|
| 237 |
+
okCount := 0
|
| 238 |
+
for _, a := range accounts {
|
| 239 |
+
if a.OK {
|
| 240 |
+
okCount++
|
| 241 |
+
if a.Remain != nil {
|
| 242 |
+
totalRemain += *a.Remain
|
| 243 |
+
}
|
| 244 |
+
if a.Used != nil {
|
| 245 |
+
totalUsed += *a.Used
|
| 246 |
+
}
|
| 247 |
+
if a.Size != nil {
|
| 248 |
+
totalSize += *a.Size
|
| 249 |
+
}
|
| 250 |
+
}
|
| 251 |
+
}
|
| 252 |
+
out := map[string]any{
|
| 253 |
+
"service": "workbuddy",
|
| 254 |
+
"ts": time.Now().Unix(),
|
| 255 |
+
"total": map[string]any{
|
| 256 |
+
"remain": totalRemain,
|
| 257 |
+
"used": totalUsed,
|
| 258 |
+
"size": totalSize,
|
| 259 |
+
"accounts": len(accounts),
|
| 260 |
+
"ok": okCount,
|
| 261 |
+
"failed": len(accounts) - okCount,
|
| 262 |
+
},
|
| 263 |
+
"accounts": accounts,
|
| 264 |
+
}
|
| 265 |
+
if pretty {
|
| 266 |
+
printPretty(accounts, totalRemain, totalUsed, totalSize, okCount)
|
| 267 |
+
return
|
| 268 |
+
}
|
| 269 |
+
raw, _ := json.Marshal(out)
|
| 270 |
+
fmt.Println(string(raw))
|
| 271 |
+
}
|
| 272 |
+
|
| 273 |
+
// printPretty 人类可读日报:四行汇总,无账号明细。
|
| 274 |
+
func printPretty(accounts []accountResult, totalRemain, totalUsed, totalSize int64, okCount int) {
|
| 275 |
+
withBalance := 0
|
| 276 |
+
var failed []string
|
| 277 |
+
for _, a := range accounts {
|
| 278 |
+
if a.OK && a.Remain != nil && *a.Remain > 0 {
|
| 279 |
+
withBalance++
|
| 280 |
+
}
|
| 281 |
+
if !a.OK {
|
| 282 |
+
name := a.Nickname
|
| 283 |
+
if name == "" && len(a.UID) >= 8 {
|
| 284 |
+
name = a.UID[:8]
|
| 285 |
+
}
|
| 286 |
+
failed = append(failed, name+" "+a.Error)
|
| 287 |
+
}
|
| 288 |
+
}
|
| 289 |
+
pct := int64(0)
|
| 290 |
+
if totalSize > 0 {
|
| 291 |
+
pct = totalRemain * 100 / totalSize
|
| 292 |
+
}
|
| 293 |
+
fmt.Printf("📊 WorkBuddy 积分日报\n")
|
| 294 |
+
fmt.Printf("账号: %d/%d\n", withBalance, len(accounts))
|
| 295 |
+
fmt.Printf("总计: %d/%d\n", totalRemain, totalSize)
|
| 296 |
+
fmt.Printf("剩余: %d%%\n", pct)
|
| 297 |
+
for _, f := range failed {
|
| 298 |
+
fmt.Printf("⚠️ %s\n", f)
|
| 299 |
+
}
|
| 300 |
+
}
|
cmd/credit/main_test.go
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
package main
|
| 2 |
+
|
| 3 |
+
import (
|
| 4 |
+
"os"
|
| 5 |
+
"path/filepath"
|
| 6 |
+
"testing"
|
| 7 |
+
|
| 8 |
+
"github.com/misakano7545/workbuddy2api-panel/internal/auth"
|
| 9 |
+
)
|
| 10 |
+
|
| 11 |
+
// TestBillingBaseForFollowsAuthRealm 计费域选择收敛到 auth.IsGlobal 口径
|
| 12 |
+
// (显式 realm=global 或 domain 落 workbuddy.ai 家族),不再手抄推断。
|
| 13 |
+
func TestBillingBaseForFollowsAuthRealm(t *testing.T) {
|
| 14 |
+
cases := []struct {
|
| 15 |
+
name string
|
| 16 |
+
a *auth.Auth
|
| 17 |
+
want string
|
| 18 |
+
}{
|
| 19 |
+
{"显式 global", parseAuth(t, `{"realm":"global","accessToken":"t"}`), billingBaseGlobal},
|
| 20 |
+
{"domain 家族", parseAuth(t, `{"accessToken":"t","domain":"www.workbuddy.ai"}`), billingBaseGlobal},
|
| 21 |
+
{"CN", parseAuth(t, `{"accessToken":"t","domain":"www.codebuddy.cn"}`), billingBaseCN},
|
| 22 |
+
{"缺省", parseAuth(t, `{"accessToken":"t"}`), billingBaseCN},
|
| 23 |
+
}
|
| 24 |
+
for _, c := range cases {
|
| 25 |
+
if got := billingBaseFor(c.a); got != c.want {
|
| 26 |
+
t.Errorf("%s: billingBaseFor = %s, want %s", c.name, got, c.want)
|
| 27 |
+
}
|
| 28 |
+
}
|
| 29 |
+
}
|
| 30 |
+
|
| 31 |
+
// TestCreditLoadsFlatAuthFile 扁平形手写 auth 文件(无 auth/account 嵌套)也
|
| 32 |
+
// 能解出 token——此前 credit 自定义结构只认嵌套形,扁平形 token 解析为空、
|
| 33 |
+
// 报误导性的 "no accessToken"。
|
| 34 |
+
func TestCreditLoadsFlatAuthFile(t *testing.T) {
|
| 35 |
+
dir := t.TempDir()
|
| 36 |
+
flat := filepath.Join(dir, "workbuddy-flat.json")
|
| 37 |
+
if err := os.WriteFile(flat, []byte(`{"accessToken":"at-1","refreshToken":"rt-1","uid":"u1","expiresAt":9999999999}`), 0o600); err != nil {
|
| 38 |
+
t.Fatal(err)
|
| 39 |
+
}
|
| 40 |
+
raw, err := os.ReadFile(flat)
|
| 41 |
+
if err != nil {
|
| 42 |
+
t.Fatal(err)
|
| 43 |
+
}
|
| 44 |
+
a, err := auth.Parse(raw)
|
| 45 |
+
if err != nil {
|
| 46 |
+
t.Fatalf("扁平形解析失败: %v", err)
|
| 47 |
+
}
|
| 48 |
+
if a.AccessToken != "at-1" || a.UID != "u1" {
|
| 49 |
+
t.Fatalf("flat parse: token=%q uid=%q", a.AccessToken, a.UID)
|
| 50 |
+
}
|
| 51 |
+
}
|
| 52 |
+
|
| 53 |
+
func parseAuth(t *testing.T, js string) *auth.Auth {
|
| 54 |
+
t.Helper()
|
| 55 |
+
a, err := auth.Parse([]byte(js))
|
| 56 |
+
if err != nil {
|
| 57 |
+
t.Fatal(err)
|
| 58 |
+
}
|
| 59 |
+
return a
|
| 60 |
+
}
|
cmd/launcher/flags.go
CHANGED
|
@@ -7,7 +7,7 @@ import (
|
|
| 7 |
"strings"
|
| 8 |
"time"
|
| 9 |
|
| 10 |
-
"github.com/
|
| 11 |
)
|
| 12 |
|
| 13 |
// usageHead 帮助文本前半段。
|
|
|
|
| 7 |
"strings"
|
| 8 |
"time"
|
| 9 |
|
| 10 |
+
"github.com/misakano7545/workbuddy2api-panel/internal/syncer"
|
| 11 |
)
|
| 12 |
|
| 13 |
// usageHead 帮助文本前半段。
|
cmd/launcher/main.go
CHANGED
|
@@ -36,7 +36,7 @@ import (
|
|
| 36 |
"syscall"
|
| 37 |
"time"
|
| 38 |
|
| 39 |
-
"github.com/
|
| 40 |
)
|
| 41 |
|
| 42 |
// version 版本号(-version)。做成变量便于 -ldflags 注入。
|
|
|
|
| 36 |
"syscall"
|
| 37 |
"time"
|
| 38 |
|
| 39 |
+
"github.com/misakano7545/workbuddy2api-panel/internal/syncer"
|
| 40 |
)
|
| 41 |
|
| 42 |
// version 版本号(-version)。做成变量便于 -ldflags 注入。
|
cmd/login/main.go
CHANGED
|
@@ -1,336 +1,461 @@
|
|
| 1 |
-
// login.go — WorkBuddy OAuth 登录(设备授权流程,CN realm;--realm=global 供国际版)。
|
| 2 |
-
//
|
| 3 |
-
// 两个子命令,由 login.sh 顺序驱动:
|
| 4 |
-
//
|
| 5 |
-
// login [--realm=cn|global] url → POST /v2/plugin/auth/state?platform=
|
| 6 |
-
// state 落 /tmp/wb2api-login-state.json,stdout 打印授权 URL
|
| 7 |
-
// login [--realm=cn|global] poll → 读 state,GET /v2/plugin/auth/token?state= 一次,
|
| 8 |
-
// 成功再 GET /v2/plugin/login/account?state= 拿 uid/nickname,
|
| 9 |
-
// stdout 打印完整 token+account JSON(含 realm 键)
|
| 10 |
-
//
|
| 11 |
-
// --realm 默认 cn。按 realm 切换上游端点与 Origin/Referer:
|
| 12 |
-
//
|
| 13 |
-
// cn → https://copilot.tencent.com(Origin: https://www.codebuddy.cn)
|
| 14 |
-
// global → https://www.workbuddy.ai(Origin: https://www.workbuddy.ai)
|
| 15 |
-
//
|
| 16 |
-
// state 落盘带 realm,poll 读回校验与命令行 --realm 一致(防混域)。
|
| 17 |
-
// 无 PKCE(workbuddy 设备流由服务端签发 state)。
|
| 18 |
-
package main
|
| 19 |
-
|
| 20 |
-
import (
|
| 21 |
-
"bufio"
|
| 22 |
-
"bytes"
|
| 23 |
-
"encoding/json"
|
| 24 |
-
"
|
| 25 |
-
"
|
| 26 |
-
"
|
| 27 |
-
"net/http
|
| 28 |
-
"
|
| 29 |
-
"
|
| 30 |
-
"
|
| 31 |
-
"
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
//
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
//
|
| 50 |
-
var
|
| 51 |
-
|
| 52 |
-
//
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
//
|
| 65 |
-
//
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
}
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
}
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
}
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
}
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
|
| 134 |
-
|
| 135 |
-
|
| 136 |
-
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
|
| 141 |
-
|
| 142 |
-
|
| 143 |
-
|
| 144 |
-
|
| 145 |
-
|
| 146 |
-
|
| 147 |
-
|
| 148 |
-
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
|
| 152 |
-
|
| 153 |
-
|
| 154 |
-
|
| 155 |
-
|
| 156 |
-
|
| 157 |
-
|
| 158 |
-
|
| 159 |
-
|
| 160 |
-
|
| 161 |
-
|
| 162 |
-
|
| 163 |
-
|
| 164 |
-
//
|
| 165 |
-
|
| 166 |
-
|
| 167 |
-
|
| 168 |
-
|
| 169 |
-
|
| 170 |
-
|
| 171 |
-
|
| 172 |
-
|
| 173 |
-
|
| 174 |
-
|
| 175 |
-
|
| 176 |
-
|
| 177 |
-
|
| 178 |
-
|
| 179 |
-
|
| 180 |
-
|
| 181 |
-
|
| 182 |
-
|
| 183 |
-
|
| 184 |
-
|
| 185 |
-
|
| 186 |
-
|
| 187 |
-
|
| 188 |
-
|
| 189 |
-
|
| 190 |
-
|
| 191 |
-
|
| 192 |
-
|
| 193 |
-
|
| 194 |
-
|
| 195 |
-
|
| 196 |
-
//
|
| 197 |
-
//
|
| 198 |
-
|
| 199 |
-
|
| 200 |
-
|
| 201 |
-
|
| 202 |
-
|
| 203 |
-
|
| 204 |
-
|
| 205 |
-
|
| 206 |
-
|
| 207 |
-
|
| 208 |
-
|
| 209 |
-
|
| 210 |
-
|
| 211 |
-
|
| 212 |
-
|
| 213 |
-
|
| 214 |
-
var
|
| 215 |
-
|
| 216 |
-
|
| 217 |
-
|
| 218 |
-
|
| 219 |
-
|
| 220 |
-
|
| 221 |
-
|
| 222 |
-
|
| 223 |
-
|
| 224 |
-
|
| 225 |
-
|
| 226 |
-
|
| 227 |
-
|
| 228 |
-
|
| 229 |
-
|
| 230 |
-
|
| 231 |
-
|
| 232 |
-
|
| 233 |
-
|
| 234 |
-
|
| 235 |
-
|
| 236 |
-
|
| 237 |
-
|
| 238 |
-
|
| 239 |
-
|
| 240 |
-
|
| 241 |
-
|
| 242 |
-
|
| 243 |
-
|
| 244 |
-
|
| 245 |
-
|
| 246 |
-
|
| 247 |
-
|
| 248 |
-
|
| 249 |
-
|
| 250 |
-
|
| 251 |
-
|
| 252 |
-
|
| 253 |
-
|
| 254 |
-
|
| 255 |
-
|
| 256 |
-
|
| 257 |
-
|
| 258 |
-
|
| 259 |
-
|
| 260 |
-
|
| 261 |
-
|
| 262 |
-
|
| 263 |
-
|
| 264 |
-
|
| 265 |
-
|
| 266 |
-
|
| 267 |
-
|
| 268 |
-
|
| 269 |
-
|
| 270 |
-
|
| 271 |
-
|
| 272 |
-
|
| 273 |
-
|
| 274 |
-
|
| 275 |
-
|
| 276 |
-
|
| 277 |
-
|
| 278 |
-
|
| 279 |
-
|
| 280 |
-
|
| 281 |
-
|
| 282 |
-
|
| 283 |
-
|
| 284 |
-
|
| 285 |
-
|
| 286 |
-
|
| 287 |
-
|
| 288 |
-
|
| 289 |
-
|
| 290 |
-
|
| 291 |
-
|
| 292 |
-
|
| 293 |
-
|
| 294 |
-
|
| 295 |
-
|
| 296 |
-
|
| 297 |
-
|
| 298 |
-
|
| 299 |
-
|
| 300 |
-
|
| 301 |
-
|
| 302 |
-
|
| 303 |
-
|
| 304 |
-
|
| 305 |
-
|
| 306 |
-
|
| 307 |
-
|
| 308 |
-
|
| 309 |
-
|
| 310 |
-
|
| 311 |
-
if
|
| 312 |
-
|
| 313 |
-
}
|
| 314 |
-
|
| 315 |
-
|
| 316 |
-
|
| 317 |
-
|
| 318 |
-
|
| 319 |
-
|
| 320 |
-
|
| 321 |
-
|
| 322 |
-
|
| 323 |
-
|
| 324 |
-
|
| 325 |
-
|
| 326 |
-
|
| 327 |
-
|
| 328 |
-
|
| 329 |
-
|
| 330 |
-
|
| 331 |
-
|
| 332 |
-
|
| 333 |
-
|
| 334 |
-
|
| 335 |
-
|
| 336 |
-
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
// login.go — WorkBuddy OAuth 登录(设备授权流程,CN realm;--realm=global 供国际版)。
|
| 2 |
+
//
|
| 3 |
+
// 两个子命令,由 login.sh 顺序驱动:
|
| 4 |
+
//
|
| 5 |
+
// login [--realm=cn|global] url → POST /v2/plugin/auth/state?platform=<站点 Platform> 拿 state+authUrl,
|
| 6 |
+
// state 落 /tmp/wb2api-login-state.json,stdout 打印授权 URL
|
| 7 |
+
// login [--realm=cn|global] poll → 读 state,GET /v2/plugin/auth/token?state= 一次,
|
| 8 |
+
// 成功再 GET /v2/plugin/login/account?state= 拿 uid/nickname,
|
| 9 |
+
// stdout 打印完整 token+account JSON(含 realm 键)
|
| 10 |
+
//
|
| 11 |
+
// --realm 默认 cn。按 realm 切换上游端点与 Origin/Referer:
|
| 12 |
+
//
|
| 13 |
+
// cn → https://copilot.tencent.com(Origin: https://www.codebuddy.cn)
|
| 14 |
+
// global → https://www.workbuddy.ai(Origin: https://www.workbuddy.ai)
|
| 15 |
+
//
|
| 16 |
+
// state 落盘带 realm,poll 读回校验与命令行 --realm 一致(防混域)。
|
| 17 |
+
// 无 PKCE(workbuddy 设备流由服务端签发 state)。
|
| 18 |
+
package main
|
| 19 |
+
|
| 20 |
+
import (
|
| 21 |
+
"bufio"
|
| 22 |
+
"bytes"
|
| 23 |
+
"encoding/json"
|
| 24 |
+
"errors"
|
| 25 |
+
"fmt"
|
| 26 |
+
"io"
|
| 27 |
+
"net/http"
|
| 28 |
+
"net/http/cookiejar"
|
| 29 |
+
"os"
|
| 30 |
+
"path/filepath"
|
| 31 |
+
"strings"
|
| 32 |
+
"time"
|
| 33 |
+
|
| 34 |
+
auth2 "github.com/misakano7545/workbuddy2api-panel/internal/auth"
|
| 35 |
+
"github.com/misakano7545/workbuddy2api-panel/internal/loginsite"
|
| 36 |
+
)
|
| 37 |
+
|
| 38 |
+
// 上游常量:站点表与 UA 统一来自 internal/loginsite(官方口径唯一来源)。
|
| 39 |
+
// CN → copilot.tencent.com;国际站两套主机名并存:
|
| 40 |
+
// intl → www.codebuddy.ai(官方 CLI externalDomain)、workbuddy → www.workbuddy.ai
|
| 41 |
+
// (旧桌面端)。UA 按站点取(loginsite.Site.UserAgent),不再有全局 CLI 串。
|
| 42 |
+
//
|
| 43 |
+
// 登录 state 落盘路径(var 便于测试替换临时文件)
|
| 44 |
+
// Portable across OSes: the upstream hardcoded "/tmp/...", which on
|
| 45 |
+
// Windows resolves to <drive>: mp\... and aborts the OAuth flow with
|
| 46 |
+
// "The system cannot find the path specified". os.TempDir() is /tmp on Linux.
|
| 47 |
+
var stateFile = filepath.Join(os.TempDir(), "wb2api-login-state.json")
|
| 48 |
+
|
| 49 |
+
// exitFunc 供测试替换(默认 os.Exit;测试持临时替换为 panic 以进程内捕获 fatal)。
|
| 50 |
+
var exitFunc = os.Exit
|
| 51 |
+
|
| 52 |
+
// realmConfig 按 realm 返回上游 base 与 Origin/Referer origin(兼容旧调用):
|
| 53 |
+
// global → 旧桌面端 workbuddy.ai;cn/非法/缺省 → copilot.tencent.com + codebuddy.cn。
|
| 54 |
+
// 新代码请直接用 loginsite.Site(要官方国际站用 SiteIntl)。
|
| 55 |
+
func realmConfig(realm string) (base, origin string) {
|
| 56 |
+
s := loginsite.ForRealm(realm)
|
| 57 |
+
return s.API, s.Origin
|
| 58 |
+
}
|
| 59 |
+
|
| 60 |
+
// commonHeaders 设备码端点的公共头族,直接取站点定义的真机头族
|
| 61 |
+
// (loginsite.Site.EndpointHeaders)。返回 func(*http.Request),由调用方按站点
|
| 62 |
+
// 构造一次后复用。
|
| 63 |
+
//
|
| 64 |
+
// 不再发 Origin / Referer / X-Requested-With:2026-10-30 双版本真机抓包显示这三条
|
| 65 |
+
// 端点由桌面端 node fetch 发出,恒无这三个头;浏览器的同源语义只属于「打开授权页」
|
| 66 |
+
// 那一步,不属于 API 调用。UA 也换成桌面端 RPC 族,不再是 CodeBuddy CLI 家族串。
|
| 67 |
+
//
|
| 68 |
+
// 端点差异头(x-device-token / x-no-* / Bearer)由 withExtra 叠加。
|
| 69 |
+
func commonHeaders(site loginsite.Site) func(*http.Request) {
|
| 70 |
+
hdrs := site.EndpointHeaders()
|
| 71 |
+
return func(req *http.Request) {
|
| 72 |
+
for k, v := range hdrs {
|
| 73 |
+
if v != "" {
|
| 74 |
+
req.Header.Set(k, v)
|
| 75 |
+
}
|
| 76 |
+
}
|
| 77 |
+
}
|
| 78 |
+
}
|
| 79 |
+
|
| 80 |
+
// withExtra 在基础头函数之上叠加端点差异头(空值跳过)。
|
| 81 |
+
func withExtra(base func(*http.Request), extra map[string]string) func(*http.Request) {
|
| 82 |
+
return func(req *http.Request) {
|
| 83 |
+
base(req)
|
| 84 |
+
for k, v := range extra {
|
| 85 |
+
if v != "" {
|
| 86 |
+
req.Header.Set(k, v)
|
| 87 |
+
}
|
| 88 |
+
}
|
| 89 |
+
}
|
| 90 |
+
}
|
| 91 |
+
|
| 92 |
+
// apiEnvelope 与 main.go:429-433 一致
|
| 93 |
+
type apiEnvelope struct {
|
| 94 |
+
Code int `json:"code"`
|
| 95 |
+
Msg string `json:"msg"`
|
| 96 |
+
Data json.RawMessage `json:"data"`
|
| 97 |
+
}
|
| 98 |
+
|
| 99 |
+
// envelopeError 上游业务码非 0 的结构化错误:调用方按官方码表区分
|
| 100 |
+
// 「继续轮询」(11217/12151)与「终态失败」(12005/11212/11216)。
|
| 101 |
+
type envelopeError struct {
|
| 102 |
+
Code int
|
| 103 |
+
Msg string
|
| 104 |
+
Status int
|
| 105 |
+
}
|
| 106 |
+
|
| 107 |
+
func (e *envelopeError) Error() string {
|
| 108 |
+
return fmt.Sprintf("code=%d msg=%s", e.Code, e.Msg)
|
| 109 |
+
}
|
| 110 |
+
|
| 111 |
+
// doJSON 与 oauth.go:33-66 一致:{code,msg,data} 信封,code!=0 → error
|
| 112 |
+
func doJSON(client *http.Client, method, fullURL string, headers func(*http.Request), body io.Reader) (json.RawMessage, int, error) {
|
| 113 |
+
req, err := http.NewRequest(method, fullURL, body)
|
| 114 |
+
if err != nil {
|
| 115 |
+
return nil, 0, err
|
| 116 |
+
}
|
| 117 |
+
if headers != nil {
|
| 118 |
+
headers(req)
|
| 119 |
+
} else {
|
| 120 |
+
// 缺省头:国内站(与原 commonHeaders() 行为一致,零回归)
|
| 121 |
+
commonHeaders(loginsite.For(""))(req)
|
| 122 |
+
}
|
| 123 |
+
resp, err := client.Do(req)
|
| 124 |
+
if err != nil {
|
| 125 |
+
return nil, 0, err
|
| 126 |
+
}
|
| 127 |
+
defer resp.Body.Close()
|
| 128 |
+
raw, _ := io.ReadAll(resp.Body)
|
| 129 |
+
if resp.StatusCode >= 400 {
|
| 130 |
+
return nil, resp.StatusCode, fmt.Errorf("http_error: upstream %d", resp.StatusCode)
|
| 131 |
+
}
|
| 132 |
+
if resp.StatusCode >= 300 {
|
| 133 |
+
return nil, resp.StatusCode, fmt.Errorf("http_error: upstream redirect %d", resp.StatusCode)
|
| 134 |
+
}
|
| 135 |
+
var env apiEnvelope
|
| 136 |
+
if err := json.Unmarshal(raw, &env); err != nil {
|
| 137 |
+
return nil, resp.StatusCode, fmt.Errorf("parse failed: %w", err)
|
| 138 |
+
}
|
| 139 |
+
if env.Code != 0 {
|
| 140 |
+
// 结构化:调用方按官方码表区分 pending / 终态。
|
| 141 |
+
return nil, resp.StatusCode, &envelopeError{Code: env.Code, Msg: env.Msg, Status: resp.StatusCode}
|
| 142 |
+
}
|
| 143 |
+
return env.Data, resp.StatusCode, nil
|
| 144 |
+
}
|
| 145 |
+
|
| 146 |
+
func fatal(format string, args ...any) {
|
| 147 |
+
fmt.Fprintf(os.Stderr, "login: "+format+"\n", args...)
|
| 148 |
+
exitFunc(1)
|
| 149 |
+
}
|
| 150 |
+
|
| 151 |
+
type loginState struct {
|
| 152 |
+
State string `json:"state"`
|
| 153 |
+
Realm string `json:"realm,omitempty"` // url 落盘时写回的 realm,poll 读回校验防混域
|
| 154 |
+
Site string `json:"site,omitempty"` // 站点标识(cn/intl/workbuddy),poll 读回校验防换站
|
| 155 |
+
}
|
| 156 |
+
|
| 157 |
+
// realm 取值枚举(与 internal/auth 的 Realm() 归一化输出一致)。
|
| 158 |
+
const (
|
| 159 |
+
realmCN = "cn"
|
| 160 |
+
realmGlobal = "global"
|
| 161 |
+
)
|
| 162 |
+
|
| 163 |
+
// parseRealmArgs 解析开头的 --realm=cn|global(或分离式 --realm <v>)flag,缺省 cn。
|
| 164 |
+
// 大小写不敏感归一化;非法值/缺值报错。桌椅剩余参数(子命令)顺序不变。
|
| 165 |
+
func parseRealmArgs(args []string) (realm string, rest []string, err error) {
|
| 166 |
+
realm = realmCN
|
| 167 |
+
for i := 0; i < len(args); i++ {
|
| 168 |
+
a := args[i]
|
| 169 |
+
switch {
|
| 170 |
+
case a == "--realm":
|
| 171 |
+
if i+1 >= len(args) {
|
| 172 |
+
return "", nil, fmt.Errorf("--realm requires a value")
|
| 173 |
+
}
|
| 174 |
+
v := strings.ToLower(strings.TrimSpace(args[i+1]))
|
| 175 |
+
if v != realmCN && v != realmGlobal {
|
| 176 |
+
return "", nil, fmt.Errorf("invalid --realm %q (want cn|global)", args[i+1])
|
| 177 |
+
}
|
| 178 |
+
realm = v
|
| 179 |
+
i++
|
| 180 |
+
case strings.HasPrefix(a, "--realm="):
|
| 181 |
+
v := strings.ToLower(strings.TrimSpace(strings.TrimPrefix(a, "--realm=")))
|
| 182 |
+
if v != realmCN && v != realmGlobal {
|
| 183 |
+
return "", nil, fmt.Errorf("invalid --realm %q (want cn|global)", v)
|
| 184 |
+
}
|
| 185 |
+
realm = v
|
| 186 |
+
default:
|
| 187 |
+
rest = append(rest, a)
|
| 188 |
+
}
|
| 189 |
+
}
|
| 190 |
+
return realm, rest, nil
|
| 191 |
+
}
|
| 192 |
+
|
| 193 |
+
// resolveRealmInput 把交互式选域的一行输入归一化为 realm(纯函数,login.sh 交互分支
|
| 194 |
+
// 的核心决策,可测)。规则:
|
| 195 |
+
//
|
| 196 |
+
// "1"/"cn"(大小写不敏感)/""(回车默认)→ cn
|
| 197 |
+
// "2"/"global" → global
|
| 198 |
+
// 其他 → ("", false)(调用方回默认 cn)
|
| 199 |
+
func resolveRealmInput(input string) (string, bool) {
|
| 200 |
+
switch strings.ToLower(strings.TrimSpace(input)) {
|
| 201 |
+
case "", "1", "cn":
|
| 202 |
+
return realmCN, true
|
| 203 |
+
case "2", "global":
|
| 204 |
+
return realmGlobal, true
|
| 205 |
+
}
|
| 206 |
+
return "", false
|
| 207 |
+
}
|
| 208 |
+
|
| 209 |
+
// parseSiteArgs 解析 --site=cn|intl|workbuddy(官方域表),并把剩余参数里的
|
| 210 |
+
// --realm 一并消化:显式 --site 优先;否则按 --realm 映射(cn → 国内站,
|
| 211 |
+
// global → 旧桌面端 workbuddy.ai,保持老脚本语义)。
|
| 212 |
+
func parseSiteArgs(args []string) (site loginsite.Site, rest []string, err error) {
|
| 213 |
+
var siteID string
|
| 214 |
+
var kept []string
|
| 215 |
+
for i := 0; i < len(args); i++ {
|
| 216 |
+
a := args[i]
|
| 217 |
+
switch {
|
| 218 |
+
case a == "--site":
|
| 219 |
+
if i+1 >= len(args) {
|
| 220 |
+
return loginsite.Site{}, nil, fmt.Errorf("--site requires a value")
|
| 221 |
+
}
|
| 222 |
+
siteID = args[i+1]
|
| 223 |
+
i++
|
| 224 |
+
case strings.HasPrefix(a, "--site="):
|
| 225 |
+
siteID = strings.TrimPrefix(a, "--site=")
|
| 226 |
+
default:
|
| 227 |
+
kept = append(kept, a)
|
| 228 |
+
}
|
| 229 |
+
}
|
| 230 |
+
if siteID != "" {
|
| 231 |
+
id := strings.ToLower(strings.TrimSpace(siteID))
|
| 232 |
+
if !loginsite.ValidID(id) {
|
| 233 |
+
return loginsite.Site{}, nil, fmt.Errorf("invalid --site %q (want cn|intl|workbuddy)", siteID)
|
| 234 |
+
}
|
| 235 |
+
// 仍消化 --realm(老脚本会同时传),但以 --site 为准。
|
| 236 |
+
_, kept, err = parseRealmArgs(kept)
|
| 237 |
+
if err != nil {
|
| 238 |
+
return loginsite.Site{}, nil, err
|
| 239 |
+
}
|
| 240 |
+
return loginsite.For(id), kept, nil
|
| 241 |
+
}
|
| 242 |
+
realm, kept, err := parseRealmArgs(kept)
|
| 243 |
+
if err != nil {
|
| 244 |
+
return loginsite.Site{}, nil, err
|
| 245 |
+
}
|
| 246 |
+
return loginsite.ForRealm(realm), kept, nil
|
| 247 |
+
}
|
| 248 |
+
|
| 249 |
+
// promptRealm 交互式选域:向 out 打印选项提示(out 接 stderr,stdout 留给 realm 本身),
|
| 250 |
+
// 从 in 读一行,返回归一化 realm。非法输入警告后回落 cn;EOF(非交互/管道)回落 cn。
|
| 251 |
+
func promptRealm(in io.Reader, out io.Writer) string {
|
| 252 |
+
fmt.Fprintln(out, "选择登录版本: 1) 国内版(cn) 2) 国际版(global) [默认 1/cn]: ")
|
| 253 |
+
line, err := bufio.NewReader(in).ReadString('\n')
|
| 254 |
+
if err != nil && line == "" {
|
| 255 |
+
// EOF/非交互 → 回落默认 cn
|
| 256 |
+
return realmCN
|
| 257 |
+
}
|
| 258 |
+
if realm, ok := resolveRealmInput(line); ok {
|
| 259 |
+
return realm
|
| 260 |
+
}
|
| 261 |
+
fmt.Fprintln(out, "无效选择,默认国内版 cn")
|
| 262 |
+
return realmCN
|
| 263 |
+
}
|
| 264 |
+
|
| 265 |
+
// validateRealmMatch 校验 state 文件 realm 与命令行 --realm 一致(防混域):
|
| 266 |
+
// state 无 realm(旧文件)放行;非空且不一致 → error。
|
| 267 |
+
func validateRealmMatch(stateRealm, cliRealm string) error {
|
| 268 |
+
if stateRealm != "" && stateRealm != cliRealm {
|
| 269 |
+
return fmt.Errorf("realm mismatch: state file realm=%q, command --realm=%q(url 与 poll 需同一 realm)", stateRealm, cliRealm)
|
| 270 |
+
}
|
| 271 |
+
return nil
|
| 272 |
+
}
|
| 273 |
+
|
| 274 |
+
// runURL 执行 url 子命令:向站点的 state 端点 POST 取授权 URL,state 落盘
|
| 275 |
+
// (带 realm+site),stdout 打印 authURL(已按官方补齐 version / ww_device_nonce)。
|
| 276 |
+
// out 接 stdout;statePath 为落盘路径(可注入临时文件便于测试)。
|
| 277 |
+
func runURL(site loginsite.Site, statePath string, client *http.Client, out io.Writer) {
|
| 278 |
+
stateURL, _, _, _ := site.Endpoints()
|
| 279 |
+
// auth/state 真机带 x-device-token(取到才发)+ x-custom-channel-id + 四个 x-no-*。
|
| 280 |
+
headers := withExtra(commonHeaders(site), site.HeadersForState(loginDeviceToken()))
|
| 281 |
+
data, _, err := doJSON(client, http.MethodPost, stateURL, headers, bytes.NewReader([]byte("{}")))
|
| 282 |
+
if err != nil {
|
| 283 |
+
fatal("auth state failed: %v", err)
|
| 284 |
+
}
|
| 285 |
+
var st struct {
|
| 286 |
+
State string `json:"state"`
|
| 287 |
+
AuthURL string `json:"authUrl"`
|
| 288 |
+
}
|
| 289 |
+
if err := json.Unmarshal(data, &st); err != nil || st.State == "" || st.AuthURL == "" {
|
| 290 |
+
fatal("auth state: missing state or authUrl")
|
| 291 |
+
}
|
| 292 |
+
raw, _ := json.Marshal(loginState{State: st.State, Realm: site.Realm, Site: site.ID})
|
| 293 |
+
if err := os.WriteFile(statePath, raw, 0o600); err != nil {
|
| 294 |
+
fatal("write state: %v", err)
|
| 295 |
+
}
|
| 296 |
+
fmt.Fprintln(out, loginsite.DecorateAuthURL(st.AuthURL, site, loginDeviceNonce(), loginsite.NewLoginSessionID()))
|
| 297 |
+
}
|
| 298 |
+
|
| 299 |
+
// loginDeviceNonce 官方 ww_device_nonce 的来源(桌面端 Turing 设备 SDK)。本仓无
|
| 300 |
+
// SDK,取部署侧环境变量;空 = 不加该参数(不伪造设备指纹)。
|
| 301 |
+
func loginDeviceNonce() string {
|
| 302 |
+
return strings.TrimSpace(os.Getenv("CODEBUDDY_LOGIN_DEVICE_NONCE"))
|
| 303 |
+
}
|
| 304 |
+
|
| 305 |
+
// loginDeviceToken 设备风控 token(X-Device-Token,auth/state 出站头)。
|
| 306 |
+
//
|
| 307 |
+
// 真机为 `v3:<base64…>`,由桌面端 qimei 组件本地生成,无法从 machineId 推导。
|
| 308 |
+
// 取不到就返回空串(调用方据此不发该头)——伪造比缺失更容易被判成非客户端。
|
| 309 |
+
// 来源:CODEBUDDY_LOGIN_DEVICE_TOKEN 环境变量,或 CODEBUDDY_LOGIN_DEVICE_TOKEN_FILE。
|
| 310 |
+
func loginDeviceToken() string {
|
| 311 |
+
if v := strings.TrimSpace(os.Getenv("CODEBUDDY_LOGIN_DEVICE_TOKEN")); v != "" {
|
| 312 |
+
return v
|
| 313 |
+
}
|
| 314 |
+
if p := strings.TrimSpace(os.Getenv("CODEBUDDY_LOGIN_DEVICE_TOKEN_FILE")); p != "" {
|
| 315 |
+
if b, err := os.ReadFile(p); err == nil {
|
| 316 |
+
return strings.TrimSpace(string(b))
|
| 317 |
+
}
|
| 318 |
+
}
|
| 319 |
+
return ""
|
| 320 |
+
}
|
| 321 |
+
|
| 322 |
+
// runPoll 执行 poll 子命令:读 state 文件(realm/site 校验),向站点 token 端点
|
| 323 |
+
// GET 一次,成功再 GET login/account(带 Bearer),stdout 打印完整 token+account JSON。
|
| 324 |
+
//
|
| 325 |
+
// 官方码表语义:11217(RetryFetchToken)/ 12151(RetryFetchAccount)是 pending,
|
| 326 |
+
// 12005/11212/11216 是终态许可错误——后者必须直接报错退出,否则 login.sh 的
|
| 327 |
+
// 「登录还没完成就按了 y」提示会把「席位满 / 许可证过期」误导成操作问题。
|
| 328 |
+
func runPoll(site loginsite.Site, statePath string, client *http.Client, out io.Writer) {
|
| 329 |
+
raw, err := os.ReadFile(statePath)
|
| 330 |
+
if err != nil {
|
| 331 |
+
fatal("read state: %v (先跑 login url)", err)
|
| 332 |
+
}
|
| 333 |
+
var ls loginState
|
| 334 |
+
if err := json.Unmarshal(raw, &ls); err != nil {
|
| 335 |
+
fatal("parse state: %v", err)
|
| 336 |
+
}
|
| 337 |
+
// 防混域/换站:state 落盘标识与本次站点不一致则拒绝(url 与 poll 必须同站)。
|
| 338 |
+
if err := validateRealmMatch(ls.Realm, site.Realm); err != nil {
|
| 339 |
+
fatal("%v", err)
|
| 340 |
+
}
|
| 341 |
+
if ls.Site != "" && ls.Site != site.ID {
|
| 342 |
+
fatal("site mismatch: state file site=%q, command site=%q(url 与 poll 需同一站点)", ls.Site, site.ID)
|
| 343 |
+
}
|
| 344 |
+
// auth/token 真机是唯一不带 x-domain 的端点(只有公共头 + 四个 x-no-*)。
|
| 345 |
+
tokenH := withExtra(commonHeaders(site), site.HeadersForToken())
|
| 346 |
+
// handlePollLogin (oauth.go:108-162):auth/token 是权威登录状态端点,
|
| 347 |
+
// pending 时业务码 11217,完成时 code=0 + token bundle
|
| 348 |
+
tokRaw, status, errTok := doJSON(client, http.MethodGet, site.API+"/v2/plugin/auth/token?state="+ls.State, tokenH, nil)
|
| 349 |
+
if errTok != nil {
|
| 350 |
+
var envErr *envelopeError
|
| 351 |
+
if errors.As(errTok, &envErr) {
|
| 352 |
+
if loginsite.CodeFatal(envErr.Code) {
|
| 353 |
+
fatal("登录被上游拒绝(code=%d):%s", envErr.Code, envErr.Msg)
|
| 354 |
+
}
|
| 355 |
+
if loginsite.CodePending(envErr.Code) {
|
| 356 |
+
fatal("登录未完成(waiting for login)。请确认已在浏览器完成登录再按 y")
|
| 357 |
+
}
|
| 358 |
+
}
|
| 359 |
+
if status == 0 || status >= 500 {
|
| 360 |
+
fatal("token endpoint error: %v", errTok)
|
| 361 |
+
}
|
| 362 |
+
// 走到这里的是「非信封 4xx」(HTML 错误页等):state 多半已过期/失效,
|
| 363 |
+
// 反复「确认浏览器登录 + 按 y」永远不会再成功——正确动作是重跑 login url,
|
| 364 |
+
// 不能与「还没登录完」共用同一句提示。
|
| 365 |
+
fatal("登录状态查询被拒(HTTP %d):%v\nstate 可能已过期,请重新运行 login url", status, errTok)
|
| 366 |
+
}
|
| 367 |
+
var tok struct {
|
| 368 |
+
AccessToken string `json:"accessToken"`
|
| 369 |
+
RefreshToken string `json:"refreshToken"`
|
| 370 |
+
ExpiresIn int64 `json:"expiresIn"`
|
| 371 |
+
Domain string `json:"domain"`
|
| 372 |
+
}
|
| 373 |
+
if err := json.Unmarshal(tokRaw, &tok); err != nil || tok.AccessToken == "" {
|
| 374 |
+
fatal("登录未完成(waiting for login)。请确认已在浏览器完成登录再按 y")
|
| 375 |
+
}
|
| 376 |
+
// login/account 拿 uid/nickname(带 Bearer)。12151 是「token 已发、账号信息还在
|
| 377 |
+
// 落库」的 pending 态,提示重试而不是当成失败。
|
| 378 |
+
var acct struct {
|
| 379 |
+
UID string `json:"uid"`
|
| 380 |
+
EnterpriseID string `json:"enterpriseId"`
|
| 381 |
+
Nickname string `json:"nickname"`
|
| 382 |
+
}
|
| 383 |
+
// login/account 真机带 x-domain + Bearer + 三个 x-no-*(无 x-no-authorization)。
|
| 384 |
+
acctHeaders := withExtra(commonHeaders(site), site.HeadersForAccount(tok.AccessToken))
|
| 385 |
+
acctRaw, _, errAcct := doJSON(client, http.MethodGet, site.API+"/v2/plugin/login/account?state="+ls.State, acctHeaders, nil)
|
| 386 |
+
if errAcct == nil {
|
| 387 |
+
_ = json.Unmarshal(acctRaw, &acct)
|
| 388 |
+
} else {
|
| 389 |
+
var envErr *envelopeError
|
| 390 |
+
if errors.As(errAcct, &envErr) {
|
| 391 |
+
if loginsite.CodeFatal(envErr.Code) {
|
| 392 |
+
fatal("登录被上游拒绝(code=%d):%s", envErr.Code, envErr.Msg)
|
| 393 |
+
}
|
| 394 |
+
if loginsite.CodePending(envErr.Code) {
|
| 395 |
+
fatal("账号信息尚未就绪(code=%d)。请稍等几秒再按 y 重试", envErr.Code)
|
| 396 |
+
}
|
| 397 |
+
}
|
| 398 |
+
}
|
| 399 |
+
raw, _ = json.Marshal(buildLoginOutput(tok, site.Realm, acct))
|
| 400 |
+
fmt.Fprintln(out, string(raw))
|
| 401 |
+
os.Remove(statePath)
|
| 402 |
+
}
|
| 403 |
+
|
| 404 |
+
// buildLoginOutput 组装 poll 输出的完整 JSON(login.sh 据此落盘 auth 文件)。
|
| 405 |
+
// realm 永不空:显式 --realm 优先(ResolveRealm 处理),否则按上游返回的 domain 推断——
|
| 406 |
+
// 保证登录落盘的 auth 文件恒带 realm 键。
|
| 407 |
+
func buildLoginOutput(tok struct {
|
| 408 |
+
AccessToken string `json:"accessToken"`
|
| 409 |
+
RefreshToken string `json:"refreshToken"`
|
| 410 |
+
ExpiresIn int64 `json:"expiresIn"`
|
| 411 |
+
Domain string `json:"domain"`
|
| 412 |
+
}, realm string, acct struct {
|
| 413 |
+
UID string `json:"uid"`
|
| 414 |
+
EnterpriseID string `json:"enterpriseId"`
|
| 415 |
+
Nickname string `json:"nickname"`
|
| 416 |
+
}) map[string]any {
|
| 417 |
+
return map[string]any{
|
| 418 |
+
"access_token": tok.AccessToken,
|
| 419 |
+
"refresh_token": tok.RefreshToken,
|
| 420 |
+
"expires_in": tok.ExpiresIn,
|
| 421 |
+
"domain": tok.Domain,
|
| 422 |
+
"realm": auth2.ResolveRealm(realm, tok.Domain),
|
| 423 |
+
"uid": acct.UID,
|
| 424 |
+
"enterprise_id": acct.EnterpriseID,
|
| 425 |
+
"nickname": acct.Nickname,
|
| 426 |
+
}
|
| 427 |
+
}
|
| 428 |
+
|
| 429 |
+
func main() {
|
| 430 |
+
site, rest, err := parseSiteArgs(os.Args[1:])
|
| 431 |
+
if err != nil {
|
| 432 |
+
fatal("%v (usage: login [--site=cn|intl|workbuddy] [--realm=cn|global] <url|poll|realm|site>)", err)
|
| 433 |
+
}
|
| 434 |
+
if len(rest) < 1 {
|
| 435 |
+
fatal("usage: login [--site=cn|intl|workbuddy] [--realm=cn|global] <url|poll|realm|site>")
|
| 436 |
+
}
|
| 437 |
+
// 每个流程独立 cookie jar(oauth.go:22-29:多账号登录互不串会话)
|
| 438 |
+
jar, _ := cookiejar.New(nil)
|
| 439 |
+
client := &http.Client{Timeout: 30 * time.Second, Jar: jar}
|
| 440 |
+
|
| 441 |
+
switch rest[0] {
|
| 442 |
+
case "url":
|
| 443 |
+
runURL(site, stateFile, client, os.Stdout)
|
| 444 |
+
|
| 445 |
+
case "poll":
|
| 446 |
+
runPoll(site, stateFile, client, os.Stdout)
|
| 447 |
+
|
| 448 |
+
case "realm":
|
| 449 |
+
// 交互式选域(login.sh 无 --realm 传参且 stdin 为 tty 时调用)。
|
| 450 |
+
// 提示打到 stderr,stdout 只输出归一化 realm,供 $( ) 捕获。
|
| 451 |
+
realm := promptRealm(os.Stdin, os.Stderr)
|
| 452 |
+
fmt.Println(realm)
|
| 453 |
+
|
| 454 |
+
case "site":
|
| 455 |
+
// 输出归一化站点标识(cn/intl/workbuddy),供脚本 $( ) 捕获。
|
| 456 |
+
fmt.Println(site.ID)
|
| 457 |
+
|
| 458 |
+
default:
|
| 459 |
+
fatal("unknown subcommand %q (want url|poll|realm|site)", rest[0])
|
| 460 |
+
}
|
| 461 |
+
}
|
cmd/login/realm_test.go
CHANGED
|
@@ -1,169 +1,341 @@
|
|
| 1 |
-
package main
|
| 2 |
-
|
| 3 |
-
import (
|
| 4 |
-
"bytes"
|
| 5 |
-
"
|
| 6 |
-
"
|
| 7 |
-
"
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
/
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
}
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
}
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
}
|
| 80 |
-
|
| 81 |
-
}
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
|
| 134 |
-
|
| 135 |
-
|
| 136 |
-
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
|
| 141 |
-
|
| 142 |
-
|
| 143 |
-
}
|
| 144 |
-
|
| 145 |
-
|
| 146 |
-
|
| 147 |
-
|
| 148 |
-
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
|
| 152 |
-
|
| 153 |
-
|
| 154 |
-
{
|
| 155 |
-
}
|
| 156 |
-
|
| 157 |
-
|
| 158 |
-
|
| 159 |
-
|
| 160 |
-
|
| 161 |
-
|
| 162 |
-
|
| 163 |
-
|
| 164 |
-
|
| 165 |
-
|
| 166 |
-
|
| 167 |
-
|
| 168 |
-
|
| 169 |
-
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
package main
|
| 2 |
+
|
| 3 |
+
import (
|
| 4 |
+
"bytes"
|
| 5 |
+
"encoding/json"
|
| 6 |
+
"fmt"
|
| 7 |
+
"io"
|
| 8 |
+
"net/http"
|
| 9 |
+
"net/http/httptest"
|
| 10 |
+
"net/url"
|
| 11 |
+
"os"
|
| 12 |
+
"path/filepath"
|
| 13 |
+
"reflect"
|
| 14 |
+
"strings"
|
| 15 |
+
"testing"
|
| 16 |
+
|
| 17 |
+
"github.com/misakano7545/workbuddy2api-panel/internal/loginsite"
|
| 18 |
+
)
|
| 19 |
+
|
| 20 |
+
// TestParseRealmArgs 覆盖 --realm 参数解析:缺省 cn、等号/分离式写法、
|
| 21 |
+
// 非法值/缺值报错、大小写归一、剥离 flag 后剩余参数保持相对顺序。
|
| 22 |
+
func TestParseRealmArgs(t *testing.T) {
|
| 23 |
+
cases := []struct {
|
| 24 |
+
name string
|
| 25 |
+
args []string
|
| 26 |
+
wantRealm string
|
| 27 |
+
wantRest []string
|
| 28 |
+
wantErr bool
|
| 29 |
+
}{
|
| 30 |
+
{name: "缺省 cn", args: []string{"url"}, wantRealm: "cn", wantRest: []string{"url"}},
|
| 31 |
+
{name: "等号 global 在前", args: []string{"--realm=global", "url"}, wantRealm: "global", wantRest: []string{"url"}},
|
| 32 |
+
{name: "等号 cn 在后", args: []string{"poll", "--realm=cn"}, wantRealm: "cn", wantRest: []string{"poll"}},
|
| 33 |
+
{name: "分离式 global", args: []string{"--realm", "global", "url"}, wantRealm: "global", wantRest: []string{"url"}},
|
| 34 |
+
{name: "非法值报错", args: []string{"--realm=foo", "url"}, wantErr: true},
|
| 35 |
+
{name: "分离式缺值报错", args: []string{"--realm", "url"}, wantErr: true},
|
| 36 |
+
{name: "大小写归一", args: []string{"--realm=GLOBAL", "url"}, wantRealm: "global", wantRest: []string{"url"}},
|
| 37 |
+
}
|
| 38 |
+
for _, c := range cases {
|
| 39 |
+
t.Run(c.name, func(t *testing.T) {
|
| 40 |
+
realm, rest, err := parseRealmArgs(c.args)
|
| 41 |
+
if c.wantErr {
|
| 42 |
+
if err == nil {
|
| 43 |
+
t.Fatalf("parseRealmArgs(%v) err=nil, want error", c.args)
|
| 44 |
+
}
|
| 45 |
+
return
|
| 46 |
+
}
|
| 47 |
+
if err != nil {
|
| 48 |
+
t.Fatalf("parseRealmArgs(%v) err=%v", c.args, err)
|
| 49 |
+
}
|
| 50 |
+
if realm != c.wantRealm {
|
| 51 |
+
t.Errorf("realm=%q want %q", realm, c.wantRealm)
|
| 52 |
+
}
|
| 53 |
+
if !reflect.DeepEqual(rest, c.wantRest) {
|
| 54 |
+
t.Errorf("rest=%v want %v", rest, c.wantRest)
|
| 55 |
+
}
|
| 56 |
+
})
|
| 57 |
+
}
|
| 58 |
+
}
|
| 59 |
+
|
| 60 |
+
// TestParseSiteArgs 覆盖 --site 解析:显式 --site 优先于 --realm,未知值报错,
|
| 61 |
+
// 缺省/无参回落国内站;同时确认 --site/--realm 都被剥离,子命令留在 rest。
|
| 62 |
+
func TestParseSiteArgs(t *testing.T) {
|
| 63 |
+
cases := []struct {
|
| 64 |
+
name string
|
| 65 |
+
args []string
|
| 66 |
+
wantID string
|
| 67 |
+
wantRest []string
|
| 68 |
+
wantErr bool
|
| 69 |
+
}{
|
| 70 |
+
{name: "缺省 cn", args: []string{"url"}, wantID: "cn", wantRest: []string{"url"}},
|
| 71 |
+
{name: "site=intl", args: []string{"--site=intl", "url"}, wantID: "intl", wantRest: []string{"url"}},
|
| 72 |
+
{name: "site=workbuddy 分离式", args: []string{"--site", "workbuddy", "poll"}, wantID: "workbuddy", wantRest: []string{"poll"}},
|
| 73 |
+
{name: "site 大小写归一", args: []string{"--site=INTL", "url"}, wantID: "intl", wantRest: []string{"url"}},
|
| 74 |
+
// --site 优先:老脚本同时传两个也不冲突。
|
| 75 |
+
{name: "site 优先于 realm", args: []string{"--site=intl", "--realm=cn", "url"}, wantID: "intl", wantRest: []string{"url"}},
|
| 76 |
+
// 只传 realm 时保持历史语义(global → workbuddy 旧桌面端)。
|
| 77 |
+
{name: "realm=global 映射旧桌面端", args: []string{"--realm=global", "url"}, wantID: "workbuddy", wantRest: []string{"url"}},
|
| 78 |
+
{name: "realm=cn", args: []string{"--realm=cn", "url"}, wantID: "cn", wantRest: []string{"url"}},
|
| 79 |
+
{name: "未知 site 报错", args: []string{"--site=global", "url"}, wantErr: true},
|
| 80 |
+
{name: "site 缺值报错", args: []string{"--site"}, wantErr: true},
|
| 81 |
+
}
|
| 82 |
+
for _, c := range cases {
|
| 83 |
+
t.Run(c.name, func(t *testing.T) {
|
| 84 |
+
site, rest, err := parseSiteArgs(c.args)
|
| 85 |
+
if c.wantErr {
|
| 86 |
+
if err == nil {
|
| 87 |
+
t.Fatalf("parseSiteArgs(%v) err=nil, want error", c.args)
|
| 88 |
+
}
|
| 89 |
+
return
|
| 90 |
+
}
|
| 91 |
+
if err != nil {
|
| 92 |
+
t.Fatalf("parseSiteArgs(%v) err=%v", c.args, err)
|
| 93 |
+
}
|
| 94 |
+
if site.ID != c.wantID {
|
| 95 |
+
t.Errorf("site.ID=%q want %q", site.ID, c.wantID)
|
| 96 |
+
}
|
| 97 |
+
if !reflect.DeepEqual(rest, c.wantRest) {
|
| 98 |
+
t.Errorf("rest=%v want %v", rest, c.wantRest)
|
| 99 |
+
}
|
| 100 |
+
})
|
| 101 |
+
}
|
| 102 |
+
}
|
| 103 |
+
|
| 104 |
+
// TestRunURLDecoratesAuthURL 覆盖 url 子命令的输出:授权链接必须带官方 version
|
| 105 |
+
// 参数(对齐 CLI appendAuthUrlParams),且 state 落盘带 realm+site 供 poll 校验。
|
| 106 |
+
func TestRunURLDecoratesAuthURL(t *testing.T) {
|
| 107 |
+
dir := t.TempDir()
|
| 108 |
+
statePath := filepath.Join(dir, "state.json")
|
| 109 |
+
|
| 110 |
+
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
| 111 |
+
if !strings.HasSuffix(r.URL.Path, "/v2/plugin/auth/state") {
|
| 112 |
+
t.Errorf("unexpected path %s", r.URL.Path)
|
| 113 |
+
}
|
| 114 |
+
if got := r.URL.Query().Get("platform"); got != "workbuddy-ai" {
|
| 115 |
+
t.Errorf("platform=%q want workbuddy-ai(intl 站点真机口径)", got)
|
| 116 |
+
}
|
| 117 |
+
// 授权 URL 用测试服务器自身地址,便于断言参数。
|
| 118 |
+
base := "http://" + r.Host
|
| 119 |
+
w.Header().Set("Content-Type", "application/json")
|
| 120 |
+
fmt.Fprintf(w, `{"code":0,"msg":"OK","data":{"state":"st-1","authUrl":"%s/login?platform=CLI&state=st-1"}}`, base)
|
| 121 |
+
}))
|
| 122 |
+
defer srv.Close()
|
| 123 |
+
|
| 124 |
+
// 用自定义站点指向测试服务器(真实站点表不便打外网)。
|
| 125 |
+
site := loginsite.For(loginsite.SiteIntl)
|
| 126 |
+
site.API = srv.URL
|
| 127 |
+
site.Origin = srv.URL
|
| 128 |
+
|
| 129 |
+
var out bytes.Buffer
|
| 130 |
+
runURL(site, statePath, srv.Client(), &out)
|
| 131 |
+
|
| 132 |
+
got := strings.TrimSpace(out.String())
|
| 133 |
+
u, err := url.Parse(got)
|
| 134 |
+
if err != nil {
|
| 135 |
+
t.Fatalf("解析授权 URL 失败 %q: %v", got, err)
|
| 136 |
+
}
|
| 137 |
+
// 授权 URL 不再补 version(授权页 bundle 只读 platform/fromSource)。
|
| 138 |
+
if v := u.Query().Get("version"); v != "" {
|
| 139 |
+
t.Errorf("授权 URL 不该带 version:%q", got)
|
| 140 |
+
}
|
| 141 |
+
if s := u.Query().Get("state"); s != "st-1" {
|
| 142 |
+
t.Errorf("state=%q want st-1", s)
|
| 143 |
+
}
|
| 144 |
+
|
| 145 |
+
raw, err := os.ReadFile(statePath)
|
| 146 |
+
if err != nil {
|
| 147 |
+
t.Fatalf("state 未落盘: %v", err)
|
| 148 |
+
}
|
| 149 |
+
var ls loginState
|
| 150 |
+
if err := json.Unmarshal(raw, &ls); err != nil {
|
| 151 |
+
t.Fatalf("state 解析失败: %v", err)
|
| 152 |
+
}
|
| 153 |
+
if ls.State != "st-1" || ls.Realm != "global" || ls.Site != "intl" {
|
| 154 |
+
t.Errorf("state={state:%s realm:%s site:%s} want {st-1 global intl}", ls.State, ls.Realm, ls.Site)
|
| 155 |
+
}
|
| 156 |
+
}
|
| 157 |
+
|
| 158 |
+
// TestRunPollFatalCode 覆盖 poll 的终态码处理:上游返回 12005(席位满)时必须
|
| 159 |
+
// 直接退出并给出上游 msg,而不是报「登录未完成」让用户反复重按 y。
|
| 160 |
+
func TestRunPollFatalCode(t *testing.T) {
|
| 161 |
+
dir := t.TempDir()
|
| 162 |
+
statePath := filepath.Join(dir, "state.json")
|
| 163 |
+
if err := os.WriteFile(statePath, []byte(`{"state":"st-1","realm":"cn","site":"cn"}`), 0o600); err != nil {
|
| 164 |
+
t.Fatal(err)
|
| 165 |
+
}
|
| 166 |
+
|
| 167 |
+
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
| 168 |
+
w.Header().Set("Content-Type", "application/json")
|
| 169 |
+
fmt.Fprint(w, `{"code":12005,"msg":"license seat limit reached"}`)
|
| 170 |
+
}))
|
| 171 |
+
defer srv.Close()
|
| 172 |
+
|
| 173 |
+
site := loginsite.For(loginsite.SiteCN)
|
| 174 |
+
site.API = srv.URL
|
| 175 |
+
site.Origin = srv.URL
|
| 176 |
+
|
| 177 |
+
// 捕获 fatal(exitFunc 换成 panic,与既有 realm_test 的用法一致)。
|
| 178 |
+
var msg string
|
| 179 |
+
oldExit := exitFunc
|
| 180 |
+
exitFunc = func(code int) { panic("exit") }
|
| 181 |
+
defer func() { exitFunc = oldExit }()
|
| 182 |
+
// fatal 写 stderr,这里只看 panic 是否发生。
|
| 183 |
+
func() {
|
| 184 |
+
defer func() {
|
| 185 |
+
if r := recover(); r != nil {
|
| 186 |
+
msg = "fatal"
|
| 187 |
+
}
|
| 188 |
+
}()
|
| 189 |
+
runPoll(site, statePath, srv.Client(), io.Discard)
|
| 190 |
+
}()
|
| 191 |
+
if msg != "fatal" {
|
| 192 |
+
t.Fatal("12005 应触发 fatal 退出,实际未退出(会被误当成「登录未完成」)")
|
| 193 |
+
}
|
| 194 |
+
}
|
| 195 |
+
|
| 196 |
+
// TestRunPollSiteMismatch 覆盖防换站:state 文件记录的站点与本次 --site 不一致时
|
| 197 |
+
// 必须拒绝(国际域两套主机名同后端,混用会把请求打到非签发域)。
|
| 198 |
+
func TestRunPollSiteMismatch(t *testing.T) {
|
| 199 |
+
dir := t.TempDir()
|
| 200 |
+
statePath := filepath.Join(dir, "state.json")
|
| 201 |
+
if err := os.WriteFile(statePath, []byte(`{"state":"st-1","realm":"global","site":"workbuddy"}`), 0o600); err != nil {
|
| 202 |
+
t.Fatal(err)
|
| 203 |
+
}
|
| 204 |
+
oldExit := exitFunc
|
| 205 |
+
exitFunc = func(code int) { panic("exit") }
|
| 206 |
+
defer func() { exitFunc = oldExit }()
|
| 207 |
+
|
| 208 |
+
var fatal bool
|
| 209 |
+
func() {
|
| 210 |
+
defer func() {
|
| 211 |
+
if r := recover(); r != nil {
|
| 212 |
+
fatal = true
|
| 213 |
+
}
|
| 214 |
+
}()
|
| 215 |
+
runPoll(loginsite.For(loginsite.SiteIntl), statePath, http.DefaultClient, io.Discard)
|
| 216 |
+
}()
|
| 217 |
+
if !fatal {
|
| 218 |
+
t.Fatal("site 不一致应拒绝,实际继续执行了")
|
| 219 |
+
}
|
| 220 |
+
}
|
| 221 |
+
|
| 222 |
+
// TestResolveRealmInput 覆盖交互式选域的输入→realm 映射(login.sh 交互分支的核心决策):
|
| 223 |
+
// "1"/"cn"/""(回车默认)→ cn;"2"/"global" → global;大小写不敏感;非法 → ("",false)。
|
| 224 |
+
func TestResolveRealmInput(t *testing.T) {
|
| 225 |
+
cases := []struct {
|
| 226 |
+
input string
|
| 227 |
+
want string
|
| 228 |
+
}{
|
| 229 |
+
{input: "1", want: "cn"},
|
| 230 |
+
{input: "cn", want: "cn"},
|
| 231 |
+
{input: "CN", want: "cn"},
|
| 232 |
+
{input: "", want: "cn"}, // 回车默认
|
| 233 |
+
{input: "2", want: "global"},
|
| 234 |
+
{input: "global", want: "global"},
|
| 235 |
+
{input: "GLOBAL", want: "global"},
|
| 236 |
+
}
|
| 237 |
+
for _, c := range cases {
|
| 238 |
+
got, ok := resolveRealmInput(c.input)
|
| 239 |
+
if !ok {
|
| 240 |
+
t.Errorf("resolveRealmInput(%q) ok=false want true", c.input)
|
| 241 |
+
continue
|
| 242 |
+
}
|
| 243 |
+
if got != c.want {
|
| 244 |
+
t.Errorf("resolveRealmInput(%q)=%q want %q", c.input, got, c.want)
|
| 245 |
+
}
|
| 246 |
+
}
|
| 247 |
+
// 非法输入 → (false)。
|
| 248 |
+
for _, bad := range []string{"3", "cnn", "globalx", "foo"} {
|
| 249 |
+
if got, ok := resolveRealmInput(bad); ok {
|
| 250 |
+
t.Errorf("resolveRealmInput(%q)=(%q,true) want (_,false)", bad, got)
|
| 251 |
+
}
|
| 252 |
+
}
|
| 253 |
+
}
|
| 254 |
+
|
| 255 |
+
// TestPromptRealm 覆盖 promptRealm 的 I/O 行为(out 将接 os.Stderr,stdout 只出 realm):
|
| 256 |
+
//
|
| 257 |
+
// 1 / 2 / 回车默认 → 分别输出来 cn / global / cn;均打印"选择登录版本"提示;
|
| 258 |
+
// 非法输入 → 警告并回落 cn;EOF(非交互直接管道)→ 回落 cn。
|
| 259 |
+
func TestPromptRealm(t *testing.T) {
|
| 260 |
+
cases := []struct {
|
| 261 |
+
name string
|
| 262 |
+
input string
|
| 263 |
+
want string
|
| 264 |
+
wantHint bool // 输出中出现"选择登录版本"提示
|
| 265 |
+
}{
|
| 266 |
+
{name: "选 cn", input: "1\n", want: "cn", wantHint: true},
|
| 267 |
+
{name: "选 global", input: "2\n", want: "global", wantHint: true},
|
| 268 |
+
{name: "回车默认 cn", input: "\n", want: "cn", wantHint: true},
|
| 269 |
+
{name: "非法回落 cn", input: "foo\n", want: "cn", wantHint: true},
|
| 270 |
+
{name: "EOF 回落 cn", input: "", want: "cn", wantHint: true},
|
| 271 |
+
}
|
| 272 |
+
for _, c := range cases {
|
| 273 |
+
t.Run(c.name, func(t *testing.T) {
|
| 274 |
+
var out bytes.Buffer
|
| 275 |
+
got := promptRealm(strings.NewReader(c.input), &out)
|
| 276 |
+
if got != c.want {
|
| 277 |
+
t.Errorf("promptRealm(%q)=%q want %q", c.input, got, c.want)
|
| 278 |
+
}
|
| 279 |
+
if c.wantHint && !strings.Contains(out.String(), "选择登录版本") {
|
| 280 |
+
t.Errorf("prompt should contain '选择登录版本', got %q", out.String())
|
| 281 |
+
}
|
| 282 |
+
})
|
| 283 |
+
}
|
| 284 |
+
}
|
| 285 |
+
|
| 286 |
+
// TestRealmSubcommandSelection 通过命令形式验证 realm 子命令(login.sh 交互分支调用):
|
| 287 |
+
// 子命令剥离 --realm,剩余参数为首个 "realm"。
|
| 288 |
+
func TestRealmSubcommandSelection(t *testing.T) {
|
| 289 |
+
realm, rest, err := parseRealmArgs([]string{"realm"})
|
| 290 |
+
if err != nil {
|
| 291 |
+
t.Fatalf("parseRealmArgs(realm) err=%v", err)
|
| 292 |
+
}
|
| 293 |
+
if realm != "cn" {
|
| 294 |
+
t.Errorf("realm default=%q want cn", realm)
|
| 295 |
+
}
|
| 296 |
+
if len(rest) != 1 || rest[0] != "realm" {
|
| 297 |
+
t.Errorf("rest=%v want [realm]", rest)
|
| 298 |
+
}
|
| 299 |
+
}
|
| 300 |
+
|
| 301 |
+
// TestBuildLoginOutputRealmAlwaysSet 登录产物(login.sh 据此落盘 auth 文件)恒含 realm 键:
|
| 302 |
+
// 显式 --realm 优先,缺省时按 domain 推断(echo 出的 global 账号即便未显式指定也带 global)。
|
| 303 |
+
// 这是「登录落盘永远带 realm 标识」契约的测试载体。
|
| 304 |
+
func TestBuildLoginOutputRealmAlwaysSet(t *testing.T) {
|
| 305 |
+
tok := struct {
|
| 306 |
+
AccessToken string `json:"accessToken"`
|
| 307 |
+
RefreshToken string `json:"refreshToken"`
|
| 308 |
+
ExpiresIn int64 `json:"expiresIn"`
|
| 309 |
+
Domain string `json:"domain"`
|
| 310 |
+
}{AccessToken: "at", RefreshToken: "rt", ExpiresIn: 3600, Domain: "www.codebuddy.cn"}
|
| 311 |
+
acct := struct {
|
| 312 |
+
UID string `json:"uid"`
|
| 313 |
+
EnterpriseID string `json:"enterpriseId"`
|
| 314 |
+
Nickname string `json:"nickname"`
|
| 315 |
+
}{UID: "u1", Nickname: "n1"}
|
| 316 |
+
|
| 317 |
+
cases := []struct {
|
| 318 |
+
name string
|
| 319 |
+
realm string
|
| 320 |
+
domain string
|
| 321 |
+
wantRealm string
|
| 322 |
+
}{
|
| 323 |
+
{name: "显式 global 优先", realm: "global", domain: "www.codebuddy.cn", wantRealm: "global"},
|
| 324 |
+
{name: "显式 cn 优先", realm: "cn", domain: "www.workbuddy.ai", wantRealm: "cn"},
|
| 325 |
+
{name: "缺省按 domain 推断 global", realm: "", domain: "www.workbuddy.ai", wantRealm: "global"},
|
| 326 |
+
{name: "缺省空 domain 回落 cn", realm: "", domain: "", wantRealm: "cn"},
|
| 327 |
+
}
|
| 328 |
+
for _, c := range cases {
|
| 329 |
+
t.Run(c.name, func(t *testing.T) {
|
| 330 |
+
tok.Domain = c.domain
|
| 331 |
+
out := buildLoginOutput(tok, c.realm, acct)
|
| 332 |
+
m, ok := out["realm"].(string)
|
| 333 |
+
if !ok {
|
| 334 |
+
t.Fatalf("missing realm key in login output: %v", out)
|
| 335 |
+
}
|
| 336 |
+
if m != c.wantRealm {
|
| 337 |
+
t.Errorf("realm=%q want %q", m, c.wantRealm)
|
| 338 |
+
}
|
| 339 |
+
})
|
| 340 |
+
}
|
| 341 |
+
}
|
cmd/server/banner_test.go
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
package main
|
| 2 |
+
|
| 3 |
+
import (
|
| 4 |
+
"strings"
|
| 5 |
+
"testing"
|
| 6 |
+
)
|
| 7 |
+
|
| 8 |
+
// 掩码只留首尾各两位,短密钥/空密钥整条隐去——横幅是写进 journal 的,不能出明文。
|
| 9 |
+
func TestMaskSecret(t *testing.T) {
|
| 10 |
+
const key = "gZb95oiQqT-A7VdssgI27FO"
|
| 11 |
+
cases := []struct{ in, want string }{
|
| 12 |
+
{"", "(未设置)"},
|
| 13 |
+
{"abc", "***"},
|
| 14 |
+
{key, "gZ" + strings.Repeat("*", len(key)-4) + "FO"},
|
| 15 |
+
{"密钥密钥密钥密钥密钥", "密钥" + strings.Repeat("*", 6) + "密钥"},
|
| 16 |
+
}
|
| 17 |
+
for _, c := range cases {
|
| 18 |
+
if got := maskSecret(c.in); got != c.want {
|
| 19 |
+
t.Errorf("maskSecret(%q)=%q want %q", c.in, got, c.want)
|
| 20 |
+
}
|
| 21 |
+
}
|
| 22 |
+
}
|
| 23 |
+
|
| 24 |
+
// issue #155:改了 config.json 却不生效时,旧横幅只写 api_key=true,看不出是
|
| 25 |
+
// WB2A_API_KEY 覆盖了文件,还是改错了文件。横幅必须报来源,且密钥只出掩码。
|
| 26 |
+
func TestListenBannerReportsKeySource(t *testing.T) {
|
| 27 |
+
const key = "gZb95oiQqT-A7VdssgI27FO"
|
| 28 |
+
t.Setenv("WB2A_API_KEY", "")
|
| 29 |
+
|
| 30 |
+
got := listenBanner("127.0.0.1:7863", "/etc/wb/config.json", key)
|
| 31 |
+
want := "workbuddy2api listening on 127.0.0.1:7863 (api_key=gZ" + strings.Repeat("*", len(key)-4) +
|
| 32 |
+
"FO, 来源 配置文件 /etc/wb/config.json),管理面板 http://127.0.0.1:7863/panel/"
|
| 33 |
+
if got != want {
|
| 34 |
+
t.Fatalf("横幅=%q want %q", got, want)
|
| 35 |
+
}
|
| 36 |
+
if strings.Contains(got, key) {
|
| 37 |
+
t.Fatalf("横幅泄露了明文 api_key:%q", got)
|
| 38 |
+
}
|
| 39 |
+
// 前缀不能动:面板「运行日志」按它归类(ring_test.go 的 ChSys 用例)。
|
| 40 |
+
if !strings.HasPrefix(got, "workbuddy2api listening on 127.0.0.1:7863") {
|
| 41 |
+
t.Fatalf("横幅前缀被改动,面板日志归类会失配:%q", got)
|
| 42 |
+
}
|
| 43 |
+
|
| 44 |
+
// env 非空即覆盖文件(同 applyEnv):来源必须改口。
|
| 45 |
+
t.Setenv("WB2A_API_KEY", "env-key-12345678")
|
| 46 |
+
got = listenBanner(":7863", "/etc/wb/config.json", "env-key-12345678")
|
| 47 |
+
if !strings.Contains(got, "来源 环境变量 WB2A_API_KEY") {
|
| 48 |
+
t.Fatalf("env 覆盖时来源仍报文件,issue #155 的困惑照旧:%q", got)
|
| 49 |
+
}
|
| 50 |
+
|
| 51 |
+
// 目录只读、自动生成失败 → 退回默认+env:来源不许继续写那份没读到的路径。
|
| 52 |
+
t.Setenv("WB2A_API_KEY", "")
|
| 53 |
+
got = listenBanner(":7863", "", "abc")
|
| 54 |
+
if !strings.Contains(got, "来源 内置默认值") || strings.Contains(got, "配置文件") {
|
| 55 |
+
t.Fatalf("退回默认时来源应报内置默认值、且不许再提配置文件:%q", got)
|
| 56 |
+
}
|
| 57 |
+
}
|
cmd/server/cn_chat_base_test.go
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
package main
|
| 2 |
+
|
| 3 |
+
import (
|
| 4 |
+
"slices"
|
| 5 |
+
"testing"
|
| 6 |
+
|
| 7 |
+
"github.com/misakano7545/workbuddy2api-panel/internal/upstream"
|
| 8 |
+
)
|
| 9 |
+
|
| 10 |
+
// 老配置(无 cn 段)必须保留内置 CN base,零回归。
|
| 11 |
+
func TestCNChatBaseDefaultKeepsBuiltin(t *testing.T) {
|
| 12 |
+
cfg, err := ParseConfig([]byte(`{}`))
|
| 13 |
+
if err != nil {
|
| 14 |
+
t.Fatalf("parse: %v", err)
|
| 15 |
+
}
|
| 16 |
+
up := upstream.New()
|
| 17 |
+
want := up.ChatBaseCN
|
| 18 |
+
applyCNChatBase(up, cfg)
|
| 19 |
+
if up.ChatBaseCN != want {
|
| 20 |
+
t.Fatalf("ChatBaseCN=%q want builtin %q", up.ChatBaseCN, want)
|
| 21 |
+
}
|
| 22 |
+
}
|
| 23 |
+
|
| 24 |
+
func TestCNChatBaseOverride(t *testing.T) {
|
| 25 |
+
cfg, err := ParseConfig([]byte(`{"cn":{"chat_base":"https://www.workbuddy.cn"}}`))
|
| 26 |
+
if err != nil {
|
| 27 |
+
t.Fatalf("parse: %v", err)
|
| 28 |
+
}
|
| 29 |
+
up := upstream.New()
|
| 30 |
+
applyCNChatBase(up, cfg)
|
| 31 |
+
if up.ChatBaseCN != "https://www.workbuddy.cn" {
|
| 32 |
+
t.Fatalf("ChatBaseCN=%q want override", up.ChatBaseCN)
|
| 33 |
+
}
|
| 34 |
+
// global base 不受 cn 覆盖影响。
|
| 35 |
+
if up.ChatBaseGlobal != "" {
|
| 36 |
+
t.Fatalf("ChatBaseGlobal=%q want untouched", up.ChatBaseGlobal)
|
| 37 |
+
}
|
| 38 |
+
}
|
| 39 |
+
|
| 40 |
+
// cn.chat_base 只在装配期生效,面板保存后须提示重启。
|
| 41 |
+
func TestCNChatBaseRequiresRestart(t *testing.T) {
|
| 42 |
+
cfg := Default()
|
| 43 |
+
// 本 fork 的 restartRequiredFields 比较「运行值 vs 新值」,故造一个差异。
|
| 44 |
+
next := Default()
|
| 45 |
+
next.CN.ChatBase = "https://example.invalid"
|
| 46 |
+
if !slices.Contains(restartRequiredFields(cfg, next), "cn.chat_base") {
|
| 47 |
+
t.Fatal("cn.chat_base missing from restart-required fields")
|
| 48 |
+
}
|
| 49 |
+
}
|
cmd/server/config.go
CHANGED
|
The diff for this file is too large to render.
See raw diff
|
|
|
cmd/server/config_example_test.go
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
package main
|
| 2 |
+
|
| 3 |
+
import (
|
| 4 |
+
"encoding/json"
|
| 5 |
+
"os"
|
| 6 |
+
"path/filepath"
|
| 7 |
+
"testing"
|
| 8 |
+
)
|
| 9 |
+
|
| 10 |
+
// TestConfigExampleIsValid 守卫仓库根目录的 config.example.json 是合法 JSON、
|
| 11 |
+
// 且能被 Config 结构解析(键名拼错/漏逗号都不会被编译期发现)。
|
| 12 |
+
//
|
| 13 |
+
// 来由:PR #55 加 features.sanitize_brand_scope 时漏了上一行的逗号,
|
| 14 |
+
// 文件变成非法 JSON 而 CI 全绿——因为它只在运行时被 `cp config.example.json
|
| 15 |
+
// config.json` 的人读到,报错现场离提交很远。这个测试把现场挪回 CI。
|
| 16 |
+
func TestConfigExampleIsValid(t *testing.T) {
|
| 17 |
+
path := filepath.Join("..", "..", "config.example.json")
|
| 18 |
+
raw, err := os.ReadFile(path)
|
| 19 |
+
if err != nil {
|
| 20 |
+
t.Fatalf("读不到 %s: %v", path, err)
|
| 21 |
+
}
|
| 22 |
+
if !json.Valid(raw) {
|
| 23 |
+
t.Fatalf("%s 不是合法 JSON", path)
|
| 24 |
+
}
|
| 25 |
+
var c Config
|
| 26 |
+
if err := json.Unmarshal(raw, &c); err != nil {
|
| 27 |
+
t.Fatalf("%s 无法解析为 Config: %v", path, err)
|
| 28 |
+
}
|
| 29 |
+
// 新增的对外配置项必须在示例里可见,否则用户只能从 README 反推。
|
| 30 |
+
if c.Features.SanitizeBrandScope != "all" {
|
| 31 |
+
t.Errorf("features.sanitize_brand_scope 示例值应为 all,得到 %q", c.Features.SanitizeBrandScope)
|
| 32 |
+
}
|
| 33 |
+
if !c.Features.SanitizeBlacklistFingerprints {
|
| 34 |
+
t.Error("features.sanitize_blacklist_fingerprints 示例值应为 true")
|
| 35 |
+
}
|
| 36 |
+
if c.Pool.ModelFallback == nil {
|
| 37 |
+
t.Error("pool.model_fallback 示例应存在(空对象即可),否则用户不知道有这张表")
|
| 38 |
+
}
|
| 39 |
+
// models.allowed(issue #68):示例必须是存在的数组(仿上方各项的「示例可见」
|
| 40 |
+
// 口径)。空数组解析为非 nil 空切片;nil = 键缺失,用户无从发现白名单配置。
|
| 41 |
+
if c.Models.Allowed == nil {
|
| 42 |
+
t.Error("models.allowed 示例应存在(空数组即可),否则用户不知道有白名单")
|
| 43 |
+
}
|
| 44 |
+
// 6020/6021 排队等待的默认值也要在示例里可见(PR #217)。
|
| 45 |
+
if !c.Features.BusyRetry || c.Features.BusyWaitSeconds != 60 {
|
| 46 |
+
t.Errorf("features.busy_retry / busy_wait_seconds 示例应为 true / 60: %+v", c.Features)
|
| 47 |
+
}
|
| 48 |
+
}
|
cmd/server/config_save_test.go
ADDED
|
@@ -0,0 +1,211 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
package main
|
| 2 |
+
|
| 3 |
+
import (
|
| 4 |
+
"encoding/json"
|
| 5 |
+
"os"
|
| 6 |
+
"path/filepath"
|
| 7 |
+
"reflect"
|
| 8 |
+
"testing"
|
| 9 |
+
|
| 10 |
+
"github.com/misakano7545/workbuddy2api-panel/internal/livecfg"
|
| 11 |
+
"github.com/misakano7545/workbuddy2api-panel/internal/pool"
|
| 12 |
+
"github.com/misakano7545/workbuddy2api-panel/internal/scheduler"
|
| 13 |
+
"github.com/misakano7545/workbuddy2api-panel/internal/upstream"
|
| 14 |
+
)
|
| 15 |
+
|
| 16 |
+
func TestSaveConfigPreservesAndUpdatesModelFallback(t *testing.T) {
|
| 17 |
+
cfg := Default()
|
| 18 |
+
cfg.Pool.ModelFallback = map[string]string{"model-a": "model-b"}
|
| 19 |
+
if err := cfg.normalize(); err != nil {
|
| 20 |
+
t.Fatal(err)
|
| 21 |
+
}
|
| 22 |
+
raw, _ := json.Marshal(cfg)
|
| 23 |
+
path := filepath.Join(t.TempDir(), "config.json")
|
| 24 |
+
if err := os.WriteFile(path, raw, 0600); err != nil {
|
| 25 |
+
t.Fatal(err)
|
| 26 |
+
}
|
| 27 |
+
live := livecfg.New(livecfg.Snapshot{ModelFallback: cfg.Pool.ModelFallback})
|
| 28 |
+
p := pool.New("")
|
| 29 |
+
defer p.Close()
|
| 30 |
+
up := upstream.New()
|
| 31 |
+
sch := scheduler.New(scheduler.Config{Pool: p, Upstream: up})
|
| 32 |
+
for _, tc := range []struct{ body, want string }{
|
| 33 |
+
{`{"api_key":"changed"}`, "model-b"},
|
| 34 |
+
{`{"pool":{"model_fallback":{"model-a":"model-c"}}}`, "model-c"},
|
| 35 |
+
{`{"pool":{"model_fallback":null}}`, ""},
|
| 36 |
+
} {
|
| 37 |
+
if _, err := saveConfig([]byte(tc.body), path, live, p, up, sch, nil, nil, cfg); err != nil {
|
| 38 |
+
t.Fatal(err)
|
| 39 |
+
}
|
| 40 |
+
if got := live.Load().ModelFallback["model-a"]; got != tc.want {
|
| 41 |
+
t.Errorf("save %s: fallback = %q, want %q", tc.body, got, tc.want)
|
| 42 |
+
}
|
| 43 |
+
}
|
| 44 |
+
}
|
| 45 |
+
|
| 46 |
+
// TestSaveConfigReportsActualAndPendingRestarts 重启清单 = 「运行中配置 vs 新配置」的
|
| 47 |
+
// 实际差异:改动即入列、第二处保存不丢上一处的待重启项、改回原值自动清除。
|
| 48 |
+
// 移植上游 PR #104(saveConfig 多传 running 基线;本 fork 多 gw/pn 两参传 nil)。
|
| 49 |
+
func TestSaveConfigReportsActualAndPendingRestarts(t *testing.T) {
|
| 50 |
+
cfg := Default()
|
| 51 |
+
if err := cfg.normalize(); err != nil {
|
| 52 |
+
t.Fatal(err)
|
| 53 |
+
}
|
| 54 |
+
raw, err := json.Marshal(cfg)
|
| 55 |
+
if err != nil {
|
| 56 |
+
t.Fatal(err)
|
| 57 |
+
}
|
| 58 |
+
path := filepath.Join(t.TempDir(), "config.json")
|
| 59 |
+
if err := os.WriteFile(path, raw, 0600); err != nil {
|
| 60 |
+
t.Fatal(err)
|
| 61 |
+
}
|
| 62 |
+
live := livecfg.New(livecfg.Snapshot{})
|
| 63 |
+
p := pool.New("")
|
| 64 |
+
defer p.Close()
|
| 65 |
+
up := upstream.New()
|
| 66 |
+
sch := scheduler.New(scheduler.Config{Pool: p, Upstream: up})
|
| 67 |
+
save := func(body string) []string {
|
| 68 |
+
t.Helper()
|
| 69 |
+
fields, err := saveConfig([]byte(body), path, live, p, up, sch, nil, nil, cfg)
|
| 70 |
+
if err != nil {
|
| 71 |
+
t.Fatal(err)
|
| 72 |
+
}
|
| 73 |
+
return fields
|
| 74 |
+
}
|
| 75 |
+
if fields := save(`{"api_key":"changed"}`); len(fields) != 0 {
|
| 76 |
+
t.Fatalf("hot save restart fields=%v", fields)
|
| 77 |
+
}
|
| 78 |
+
if live.Load().APIKey != "changed" {
|
| 79 |
+
t.Fatal("key was not applied immediately")
|
| 80 |
+
}
|
| 81 |
+
if fields := save(`{"listen":":9999"}`); !reflect.DeepEqual(fields, []string{"listen"}) {
|
| 82 |
+
t.Fatalf("changed fields=%v", fields)
|
| 83 |
+
}
|
| 84 |
+
if fields := save(`{"api_key":"second"}`); !reflect.DeepEqual(fields, []string{"listen"}) {
|
| 85 |
+
t.Fatalf("pending restart disappeared: %v", fields)
|
| 86 |
+
}
|
| 87 |
+
if fields := save(`{"listen":"127.0.0.1:7863"}`); len(fields) != 0 {
|
| 88 |
+
t.Fatalf("reverted pending fields=%v", fields)
|
| 89 |
+
}
|
| 90 |
+
}
|
| 91 |
+
|
| 92 |
+
// TestSaveConfigWhenDirNotWritable 目录不可写但 config.json 可写时仍要能保存:Docker 里
|
| 93 |
+
// /app 属主是镜像内的 app(10001),而 compose 让容器以 PUID 运行 —— 原子替换的 tmp 建不
|
| 94 |
+
// 出来(issue #134),必须退回原地重写。
|
| 95 |
+
//
|
| 96 |
+
// root 不受目录权限位约束(CAP_DAC_OVERRIDE),所以本机 root 下 skip;CI 以普通用户跑,
|
| 97 |
+
// 这条才真的会红/绿。
|
| 98 |
+
func TestSaveConfigWhenDirNotWritable(t *testing.T) {
|
| 99 |
+
if os.Geteuid() == 0 {
|
| 100 |
+
t.Skip("目录权限位对 root 无效,需非 root 运行才有牙齿(CI 生效)")
|
| 101 |
+
}
|
| 102 |
+
cfg := Default()
|
| 103 |
+
if err := cfg.normalize(); err != nil {
|
| 104 |
+
t.Fatal(err)
|
| 105 |
+
}
|
| 106 |
+
raw, _ := json.Marshal(cfg)
|
| 107 |
+
dir := t.TempDir()
|
| 108 |
+
path := filepath.Join(dir, "config.json")
|
| 109 |
+
if err := os.WriteFile(path, raw, 0600); err != nil {
|
| 110 |
+
t.Fatal(err)
|
| 111 |
+
}
|
| 112 |
+
if err := os.Chmod(dir, 0o555); err != nil { // 目录不可写:tmp 建不出来
|
| 113 |
+
t.Fatal(err)
|
| 114 |
+
}
|
| 115 |
+
defer os.Chmod(dir, 0o755)
|
| 116 |
+
|
| 117 |
+
live := livecfg.New(livecfg.Snapshot{})
|
| 118 |
+
p := pool.New("")
|
| 119 |
+
defer p.Close()
|
| 120 |
+
up := upstream.New()
|
| 121 |
+
sch := scheduler.New(scheduler.Config{Pool: p, Upstream: up})
|
| 122 |
+
if _, err := saveConfig([]byte(`{"api_key":"changed-in-place"}`), path, live, p, up, sch, nil, nil, cfg); err != nil {
|
| 123 |
+
t.Fatalf("目录不可写时应原地重写而不是报错: %v", err)
|
| 124 |
+
}
|
| 125 |
+
if live.Load().APIKey != "changed-in-place" {
|
| 126 |
+
t.Fatal("key was not applied immediately")
|
| 127 |
+
}
|
| 128 |
+
saved, err := os.ReadFile(path)
|
| 129 |
+
if err != nil {
|
| 130 |
+
t.Fatal(err)
|
| 131 |
+
}
|
| 132 |
+
var got map[string]any
|
| 133 |
+
if err := json.Unmarshal(saved, &got); err != nil {
|
| 134 |
+
t.Fatalf("落盘内容不是完整 JSON(原地重写写坏了?): %v", err)
|
| 135 |
+
}
|
| 136 |
+
if got["api_key"] != "changed-in-place" {
|
| 137 |
+
t.Fatalf("api_key=%v", got["api_key"])
|
| 138 |
+
}
|
| 139 |
+
if _, err := os.Stat(path + ".tmp"); !os.IsNotExist(err) {
|
| 140 |
+
t.Error("不应残留 config.json.tmp")
|
| 141 |
+
}
|
| 142 |
+
}
|
| 143 |
+
|
| 144 |
+
// TestRestartRequiredIncludesAllAssemblyFields 装配期字段(监听/身份/双域/提示词/
|
| 145 |
+
// 会话粘性/upstash)逐族抽查:变化必须被 restartRequiredFields 报告。
|
| 146 |
+
func TestRestartRequiredIncludesAllAssemblyFields(t *testing.T) {
|
| 147 |
+
current, err := ParseConfig([]byte(`{}`))
|
| 148 |
+
if err != nil {
|
| 149 |
+
t.Fatal(err)
|
| 150 |
+
}
|
| 151 |
+
next, err := ParseConfig([]byte(`{"global":{"enabled":false},"prompt":{"mode":"custom"},"upstream":{"user_agent":"new-agent"},"session_sticky":{"enabled":false},"server":{"read_timeout":"120s"},"upstash":{"url":"https://example.upstash.io","token":"sample"}}`))
|
| 152 |
+
if err != nil {
|
| 153 |
+
t.Fatal(err)
|
| 154 |
+
}
|
| 155 |
+
fields := restartRequiredFields(current, next)
|
| 156 |
+
for _, want := range []string{"global.enabled", "prompt.mode", "upstream.user_agent", "session_sticky.enabled", "server.read_timeout", "upstash.url", "upstash.token"} {
|
| 157 |
+
found := false
|
| 158 |
+
for _, field := range fields {
|
| 159 |
+
found = found || field == want
|
| 160 |
+
}
|
| 161 |
+
if !found {
|
| 162 |
+
t.Fatalf("missing %s in %v", want, fields)
|
| 163 |
+
}
|
| 164 |
+
}
|
| 165 |
+
}
|
| 166 |
+
|
| 167 |
+
// TestSaveConfigRetainsEnvironmentManagedKey WB2A_API_KEY 托管时:保存提交的文件值
|
| 168 |
+
// 不得抢班(运行值恒为 env 值),且不产生重启项。移植上游 PR #104。
|
| 169 |
+
func TestSaveConfigRetainsEnvironmentManagedKey(t *testing.T) {
|
| 170 |
+
t.Setenv("WB2A_API_KEY", "environment-key")
|
| 171 |
+
path := filepath.Join(t.TempDir(), "config.json")
|
| 172 |
+
if err := os.WriteFile(path, []byte(`{"api_key":"file-key"}`), 0600); err != nil {
|
| 173 |
+
t.Fatal(err)
|
| 174 |
+
}
|
| 175 |
+
cfg, err := Load(path)
|
| 176 |
+
if err != nil {
|
| 177 |
+
t.Fatal(err)
|
| 178 |
+
}
|
| 179 |
+
live := livecfg.New(livecfg.Snapshot{APIKey: cfg.APIKey})
|
| 180 |
+
p := pool.New("")
|
| 181 |
+
defer p.Close()
|
| 182 |
+
up := upstream.New()
|
| 183 |
+
sch := scheduler.New(scheduler.Config{Pool: p, Upstream: up})
|
| 184 |
+
fields, err := saveConfig([]byte(`{"api_key":"submitted-key"}`), path, live, p, up, sch, nil, nil, cfg)
|
| 185 |
+
if err != nil {
|
| 186 |
+
t.Fatal(err)
|
| 187 |
+
}
|
| 188 |
+
if len(fields) != 0 || live.Load().APIKey != "environment-key" {
|
| 189 |
+
t.Fatalf("fields=%v key changed=%v", fields, live.Load().APIKey != "environment-key")
|
| 190 |
+
}
|
| 191 |
+
}
|
| 192 |
+
|
| 193 |
+
// TestEnvironmentManagedFieldsMatchesValidOverrides 托管清单只收「值合法」的 env:
|
| 194 |
+
// 非法值(WB2A_TIMEOUT_SECONDS=invalid)等同未设置,不进清单。
|
| 195 |
+
func TestEnvironmentManagedFieldsMatchesValidOverrides(t *testing.T) {
|
| 196 |
+
t.Setenv("WB2A_API_KEY", "env-key")
|
| 197 |
+
t.Setenv("WB2A_SOFT_RATE", "30s")
|
| 198 |
+
t.Setenv("WB2A_TIMEOUT_SECONDS", "invalid")
|
| 199 |
+
fields := Default().EnvironmentManagedFields()
|
| 200 |
+
has := func(want string) bool {
|
| 201 |
+
for _, field := range fields {
|
| 202 |
+
if field == want {
|
| 203 |
+
return true
|
| 204 |
+
}
|
| 205 |
+
}
|
| 206 |
+
return false
|
| 207 |
+
}
|
| 208 |
+
if !has("api_key") || !has("cooldown.soft_rate") || has("upstream.timeout_seconds") {
|
| 209 |
+
t.Fatalf("managed=%v", fields)
|
| 210 |
+
}
|
| 211 |
+
}
|
cmd/server/config_test.go
CHANGED
|
@@ -1,861 +1,1190 @@
|
|
| 1 |
-
package main
|
| 2 |
-
|
| 3 |
-
import (
|
| 4 |
-
"encoding/json"
|
| 5 |
-
"os"
|
| 6 |
-
"path/filepath"
|
| 7 |
-
"strings"
|
| 8 |
-
"testing"
|
| 9 |
-
"time"
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
}
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
}
|
| 67 |
-
if
|
| 68 |
-
t.Fatalf("
|
| 69 |
-
}
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
}
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
c
|
| 103 |
-
if err != nil {
|
| 104 |
-
t.Fatal(err)
|
| 105 |
-
}
|
| 106 |
-
if c.
|
| 107 |
-
t.
|
| 108 |
-
}
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
|
| 134 |
-
|
| 135 |
-
|
| 136 |
-
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
|
| 141 |
-
|
| 142 |
-
|
| 143 |
-
|
| 144 |
-
|
| 145 |
-
|
| 146 |
-
|
| 147 |
-
|
| 148 |
-
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
|
| 152 |
-
|
| 153 |
-
|
| 154 |
-
|
| 155 |
-
|
| 156 |
-
|
| 157 |
-
|
| 158 |
-
|
| 159 |
-
|
| 160 |
-
|
| 161 |
-
|
| 162 |
-
|
| 163 |
-
|
| 164 |
-
|
| 165 |
-
|
| 166 |
-
|
| 167 |
-
|
| 168 |
-
|
| 169 |
-
|
| 170 |
-
|
| 171 |
-
|
| 172 |
-
dir := t.TempDir()
|
| 173 |
-
fp := filepath.Join(dir, "c.json")
|
| 174 |
-
os.WriteFile(fp, []byte(`{
|
| 175 |
-
|
| 176 |
-
|
| 177 |
-
|
| 178 |
-
|
| 179 |
-
|
| 180 |
-
|
| 181 |
-
|
| 182 |
-
|
| 183 |
-
|
| 184 |
-
|
| 185 |
-
|
| 186 |
-
|
| 187 |
-
|
| 188 |
-
|
| 189 |
-
if
|
| 190 |
-
t.
|
| 191 |
-
}
|
| 192 |
-
if c.
|
| 193 |
-
t.Errorf("
|
| 194 |
-
}
|
| 195 |
-
if c.
|
| 196 |
-
t.Errorf("
|
| 197 |
-
}
|
| 198 |
-
if c.
|
| 199 |
-
t.Errorf("
|
| 200 |
-
}
|
| 201 |
-
if c.Pool.IdleWeightPerHour != 0.
|
| 202 |
-
t.Errorf("idle weights=%v/%v", c.Pool.IdleWeightPerHour, c.Pool.IdleWeightMax)
|
| 203 |
-
}
|
| 204 |
-
if c.Pool.PreferExpiring || c.ExpiringSoonDur !=
|
| 205 |
-
t.Errorf("expiring
|
| 206 |
-
}
|
| 207 |
-
if c.
|
| 208 |
-
t.
|
| 209 |
-
}
|
| 210 |
-
if
|
| 211 |
-
t.
|
| 212 |
-
}
|
| 213 |
-
|
| 214 |
-
|
| 215 |
-
|
| 216 |
-
|
| 217 |
-
|
| 218 |
-
|
| 219 |
-
|
| 220 |
-
|
| 221 |
-
|
| 222 |
-
|
| 223 |
-
|
| 224 |
-
|
| 225 |
-
|
| 226 |
-
|
| 227 |
-
|
| 228 |
-
|
| 229 |
-
|
| 230 |
-
|
| 231 |
-
|
| 232 |
-
|
| 233 |
-
|
| 234 |
-
|
| 235 |
-
|
| 236 |
-
|
| 237 |
-
|
| 238 |
-
|
| 239 |
-
if !
|
| 240 |
-
t.Fatal(
|
| 241 |
-
}
|
| 242 |
-
|
| 243 |
-
|
| 244 |
-
|
| 245 |
-
|
| 246 |
-
|
| 247 |
-
|
| 248 |
-
c
|
| 249 |
-
|
| 250 |
-
|
| 251 |
-
|
| 252 |
-
|
| 253 |
-
|
| 254 |
-
|
| 255 |
-
|
| 256 |
-
|
| 257 |
-
|
| 258 |
-
|
| 259 |
-
|
| 260 |
-
|
| 261 |
-
|
| 262 |
-
|
| 263 |
-
|
| 264 |
-
|
| 265 |
-
|
| 266 |
-
|
| 267 |
-
|
| 268 |
-
}
|
| 269 |
-
|
| 270 |
-
|
| 271 |
-
|
| 272 |
-
|
| 273 |
-
|
| 274 |
-
|
| 275 |
-
|
| 276 |
-
|
| 277 |
-
|
| 278 |
-
}
|
| 279 |
-
|
| 280 |
-
|
| 281 |
-
|
| 282 |
-
|
| 283 |
-
|
| 284 |
-
|
| 285 |
-
|
| 286 |
-
|
| 287 |
-
|
| 288 |
-
|
| 289 |
-
|
| 290 |
-
|
| 291 |
-
|
| 292 |
-
|
| 293 |
-
|
| 294 |
-
|
| 295 |
-
|
| 296 |
-
|
| 297 |
-
}
|
| 298 |
-
|
| 299 |
-
|
| 300 |
-
|
| 301 |
-
|
| 302 |
-
|
| 303 |
-
|
| 304 |
-
}
|
| 305 |
-
|
| 306 |
-
|
| 307 |
-
|
| 308 |
-
|
| 309 |
-
|
| 310 |
-
|
| 311 |
-
|
| 312 |
-
|
| 313 |
-
|
| 314 |
-
|
| 315 |
-
|
| 316 |
-
|
| 317 |
-
|
| 318 |
-
|
| 319 |
-
|
| 320 |
-
|
| 321 |
-
|
| 322 |
-
|
| 323 |
-
|
| 324 |
-
|
| 325 |
-
|
| 326 |
-
|
| 327 |
-
|
| 328 |
-
|
| 329 |
-
|
| 330 |
-
|
| 331 |
-
|
| 332 |
-
|
| 333 |
-
}
|
| 334 |
-
if
|
| 335 |
-
t.
|
| 336 |
-
}
|
| 337 |
-
}
|
| 338 |
-
|
| 339 |
-
func
|
| 340 |
-
|
| 341 |
-
|
| 342 |
-
|
| 343 |
-
|
| 344 |
-
|
| 345 |
-
|
| 346 |
-
|
| 347 |
-
|
| 348 |
-
|
| 349 |
-
|
| 350 |
-
|
| 351 |
-
|
| 352 |
-
|
| 353 |
-
|
| 354 |
-
|
| 355 |
-
|
| 356 |
-
|
| 357 |
-
|
| 358 |
-
|
| 359 |
-
|
| 360 |
-
|
| 361 |
-
|
| 362 |
-
|
| 363 |
-
|
| 364 |
-
|
| 365 |
-
|
| 366 |
-
|
| 367 |
-
|
| 368 |
-
|
| 369 |
-
|
| 370 |
-
|
| 371 |
-
|
| 372 |
-
|
| 373 |
-
|
| 374 |
-
|
| 375 |
-
|
| 376 |
-
|
| 377 |
-
|
| 378 |
-
|
| 379 |
-
|
| 380 |
-
|
| 381 |
-
|
| 382 |
-
|
| 383 |
-
|
| 384 |
-
|
| 385 |
-
|
| 386 |
-
|
| 387 |
-
|
| 388 |
-
|
| 389 |
-
|
| 390 |
-
|
| 391 |
-
|
| 392 |
-
|
| 393 |
-
|
| 394 |
-
|
| 395 |
-
|
| 396 |
-
|
| 397 |
-
|
| 398 |
-
|
| 399 |
-
|
| 400 |
-
|
| 401 |
-
|
| 402 |
-
|
| 403 |
-
|
| 404 |
-
|
| 405 |
-
|
| 406 |
-
|
| 407 |
-
|
| 408 |
-
|
| 409 |
-
|
| 410 |
-
|
| 411 |
-
|
| 412 |
-
|
| 413 |
-
|
| 414 |
-
|
| 415 |
-
|
| 416 |
-
|
| 417 |
-
|
| 418 |
-
|
| 419 |
-
//
|
| 420 |
-
|
| 421 |
-
|
| 422 |
-
|
| 423 |
-
|
| 424 |
-
|
| 425 |
-
c
|
| 426 |
-
|
| 427 |
-
|
| 428 |
-
}
|
| 429 |
-
if c.Schedule.
|
| 430 |
-
t.Errorf("want
|
| 431 |
-
|
| 432 |
-
|
| 433 |
-
if len(c.Schedule.
|
| 434 |
-
t.Errorf("
|
| 435 |
-
}
|
| 436 |
-
if len(c.Schedule.
|
| 437 |
-
t.Errorf("
|
| 438 |
-
}
|
| 439 |
-
}
|
| 440 |
-
|
| 441 |
-
//
|
| 442 |
-
|
| 443 |
-
|
| 444 |
-
|
| 445 |
-
|
| 446 |
-
|
| 447 |
-
|
| 448 |
-
|
| 449 |
-
|
| 450 |
-
|
| 451 |
-
|
| 452 |
-
|
| 453 |
-
|
| 454 |
-
if !c.Schedule.
|
| 455 |
-
t.Errorf("
|
| 456 |
-
}
|
| 457 |
-
|
| 458 |
-
|
| 459 |
-
|
| 460 |
-
|
| 461 |
-
if len(c.Schedule.
|
| 462 |
-
t.Errorf("
|
| 463 |
-
}
|
| 464 |
-
|
| 465 |
-
|
| 466 |
-
|
| 467 |
-
|
| 468 |
-
|
| 469 |
-
|
| 470 |
-
|
| 471 |
-
|
| 472 |
-
|
| 473 |
-
|
| 474 |
-
|
| 475 |
-
|
| 476 |
-
|
| 477 |
-
|
| 478 |
-
|
| 479 |
-
|
| 480 |
-
|
| 481 |
-
|
| 482 |
-
|
| 483 |
-
|
| 484 |
-
|
| 485 |
-
}
|
| 486 |
-
|
| 487 |
-
|
| 488 |
-
|
| 489 |
-
|
| 490 |
-
|
| 491 |
-
|
| 492 |
-
|
| 493 |
-
|
| 494 |
-
|
| 495 |
-
|
| 496 |
-
|
| 497 |
-
if
|
| 498 |
-
t.
|
| 499 |
-
}
|
| 500 |
-
if
|
| 501 |
-
t.Errorf("
|
| 502 |
-
}
|
| 503 |
-
|
| 504 |
-
|
| 505 |
-
/
|
| 506 |
-
|
| 507 |
-
|
| 508 |
-
|
| 509 |
-
|
| 510 |
-
|
| 511 |
-
if
|
| 512 |
-
t.
|
| 513 |
-
}
|
| 514 |
-
|
| 515 |
-
|
| 516 |
-
|
| 517 |
-
|
| 518 |
-
|
| 519 |
-
|
| 520 |
-
}
|
| 521 |
-
|
| 522 |
-
|
| 523 |
-
|
| 524 |
-
|
| 525 |
-
|
| 526 |
-
|
| 527 |
-
|
| 528 |
-
|
| 529 |
-
|
| 530 |
-
|
| 531 |
-
|
| 532 |
-
|
| 533 |
-
|
| 534 |
-
|
| 535 |
-
|
| 536 |
-
|
| 537 |
-
|
| 538 |
-
|
| 539 |
-
|
| 540 |
-
|
| 541 |
-
|
| 542 |
-
|
| 543 |
-
|
| 544 |
-
|
| 545 |
-
|
| 546 |
-
|
| 547 |
-
|
| 548 |
-
|
| 549 |
-
|
| 550 |
-
|
| 551 |
-
|
| 552 |
-
|
| 553 |
-
|
| 554 |
-
|
| 555 |
-
|
| 556 |
-
|
| 557 |
-
|
| 558 |
-
|
| 559 |
-
}
|
| 560 |
-
|
| 561 |
-
|
| 562 |
-
|
| 563 |
-
|
| 564 |
-
|
| 565 |
-
|
| 566 |
-
|
| 567 |
-
|
| 568 |
-
|
| 569 |
-
|
| 570 |
-
|
| 571 |
-
|
| 572 |
-
|
| 573 |
-
|
| 574 |
-
|
| 575 |
-
|
| 576 |
-
}
|
| 577 |
-
|
| 578 |
-
|
| 579 |
-
|
| 580 |
-
|
| 581 |
-
|
| 582 |
-
|
| 583 |
-
|
| 584 |
-
|
| 585 |
-
|
| 586 |
-
|
| 587 |
-
|
| 588 |
-
|
| 589 |
-
|
| 590 |
-
|
| 591 |
-
|
| 592 |
-
|
| 593 |
-
|
| 594 |
-
|
| 595 |
-
|
| 596 |
-
|
| 597 |
-
|
| 598 |
-
|
| 599 |
-
|
| 600 |
-
|
| 601 |
-
|
| 602 |
-
|
| 603 |
-
|
| 604 |
-
|
| 605 |
-
|
| 606 |
-
|
| 607 |
-
|
| 608 |
-
|
| 609 |
-
|
| 610 |
-
|
| 611 |
-
|
| 612 |
-
|
| 613 |
-
|
| 614 |
-
|
| 615 |
-
|
| 616 |
-
|
| 617 |
-
|
| 618 |
-
|
| 619 |
-
|
| 620 |
-
|
| 621 |
-
|
| 622 |
-
|
| 623 |
-
|
| 624 |
-
|
| 625 |
-
|
| 626 |
-
|
| 627 |
-
|
| 628 |
-
|
| 629 |
-
|
| 630 |
-
|
| 631 |
-
|
| 632 |
-
|
| 633 |
-
|
| 634 |
-
|
| 635 |
-
|
| 636 |
-
|
| 637 |
-
|
| 638 |
-
|
| 639 |
-
|
| 640 |
-
|
| 641 |
-
|
| 642 |
-
|
| 643 |
-
|
| 644 |
-
|
| 645 |
-
|
| 646 |
-
|
| 647 |
-
|
| 648 |
-
|
| 649 |
-
|
| 650 |
-
|
| 651 |
-
|
| 652 |
-
|
| 653 |
-
|
| 654 |
-
|
| 655 |
-
|
| 656 |
-
|
| 657 |
-
|
| 658 |
-
if err != nil {
|
| 659 |
-
t.
|
| 660 |
-
}
|
| 661 |
-
if
|
| 662 |
-
t.Errorf("
|
| 663 |
-
}
|
| 664 |
-
|
| 665 |
-
|
| 666 |
-
|
| 667 |
-
|
| 668 |
-
|
| 669 |
-
|
| 670 |
-
|
| 671 |
-
|
| 672 |
-
|
| 673 |
-
|
| 674 |
-
|
| 675 |
-
|
| 676 |
-
|
| 677 |
-
|
| 678 |
-
|
| 679 |
-
|
| 680 |
-
|
| 681 |
-
|
| 682 |
-
|
| 683 |
-
|
| 684 |
-
|
| 685 |
-
|
| 686 |
-
|
| 687 |
-
|
| 688 |
-
|
| 689 |
-
|
| 690 |
-
|
| 691 |
-
|
| 692 |
-
|
| 693 |
-
|
| 694 |
-
|
| 695 |
-
|
| 696 |
-
|
| 697 |
-
|
| 698 |
-
|
| 699 |
-
|
| 700 |
-
|
| 701 |
-
if
|
| 702 |
-
t.
|
| 703 |
-
}
|
| 704 |
-
}
|
| 705 |
-
|
| 706 |
-
|
| 707 |
-
|
| 708 |
-
|
| 709 |
-
|
| 710 |
-
|
| 711 |
-
|
| 712 |
-
|
| 713 |
-
|
| 714 |
-
|
| 715 |
-
|
| 716 |
-
|
| 717 |
-
|
| 718 |
-
|
| 719 |
-
|
| 720 |
-
|
| 721 |
-
|
| 722 |
-
|
| 723 |
-
|
| 724 |
-
|
| 725 |
-
|
| 726 |
-
|
| 727 |
-
|
| 728 |
-
|
| 729 |
-
|
| 730 |
-
if err != nil {
|
| 731 |
-
t.Fatal(err)
|
| 732 |
-
}
|
| 733 |
-
if
|
| 734 |
-
t.
|
| 735 |
-
}
|
| 736 |
-
|
| 737 |
-
|
| 738 |
-
|
| 739 |
-
|
| 740 |
-
|
| 741 |
-
|
| 742 |
-
if err != nil {
|
| 743 |
-
t.
|
| 744 |
-
}
|
| 745 |
-
if
|
| 746 |
-
t.Errorf("
|
| 747 |
-
}
|
| 748 |
-
|
| 749 |
-
|
| 750 |
-
|
| 751 |
-
|
| 752 |
-
|
| 753 |
-
|
| 754 |
-
|
| 755 |
-
|
| 756 |
-
|
| 757 |
-
|
| 758 |
-
|
| 759 |
-
|
| 760 |
-
|
| 761 |
-
|
| 762 |
-
if c.
|
| 763 |
-
t.
|
| 764 |
-
}
|
| 765 |
-
|
| 766 |
-
|
| 767 |
-
|
| 768 |
-
//
|
| 769 |
-
|
| 770 |
-
|
| 771 |
-
|
| 772 |
-
|
| 773 |
-
|
| 774 |
-
|
| 775 |
-
|
| 776 |
-
|
| 777 |
-
|
| 778 |
-
|
| 779 |
-
|
| 780 |
-
}
|
| 781 |
-
|
| 782 |
-
if
|
| 783 |
-
t.
|
| 784 |
-
}
|
| 785 |
-
|
| 786 |
-
|
| 787 |
-
|
| 788 |
-
|
| 789 |
-
|
| 790 |
-
|
| 791 |
-
if
|
| 792 |
-
t.
|
| 793 |
-
}
|
| 794 |
-
|
| 795 |
-
|
| 796 |
-
|
| 797 |
-
|
| 798 |
-
|
| 799 |
-
|
| 800 |
-
|
| 801 |
-
|
| 802 |
-
|
| 803 |
-
|
| 804 |
-
|
| 805 |
-
|
| 806 |
-
if
|
| 807 |
-
t.
|
| 808 |
-
}
|
| 809 |
-
|
| 810 |
-
|
| 811 |
-
|
| 812 |
-
|
| 813 |
-
|
| 814 |
-
|
| 815 |
-
|
| 816 |
-
}
|
| 817 |
-
|
| 818 |
-
|
| 819 |
-
|
| 820 |
-
|
| 821 |
-
c
|
| 822 |
-
|
| 823 |
-
|
| 824 |
-
|
| 825 |
-
|
| 826 |
-
|
| 827 |
-
|
| 828 |
-
|
| 829 |
-
|
| 830 |
-
|
| 831 |
-
|
| 832 |
-
|
| 833 |
-
|
| 834 |
-
if err :=
|
| 835 |
-
t.
|
| 836 |
-
}
|
| 837 |
-
|
| 838 |
-
|
| 839 |
-
|
| 840 |
-
|
| 841 |
-
|
| 842 |
-
|
| 843 |
-
|
| 844 |
-
|
| 845 |
-
|
| 846 |
-
|
| 847 |
-
|
| 848 |
-
|
| 849 |
-
|
| 850 |
-
|
| 851 |
-
|
| 852 |
-
|
| 853 |
-
|
| 854 |
-
|
| 855 |
-
|
| 856 |
-
|
| 857 |
-
|
| 858 |
-
if err
|
| 859 |
-
t.
|
| 860 |
-
}
|
| 861 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
package main
|
| 2 |
+
|
| 3 |
+
import (
|
| 4 |
+
"encoding/json"
|
| 5 |
+
"os"
|
| 6 |
+
"path/filepath"
|
| 7 |
+
"strings"
|
| 8 |
+
"testing"
|
| 9 |
+
"time"
|
| 10 |
+
|
| 11 |
+
"github.com/misakano7545/workbuddy2api-panel/internal/upstream"
|
| 12 |
+
)
|
| 13 |
+
|
| 14 |
+
func TestDefault(t *testing.T) {
|
| 15 |
+
c := Default()
|
| 16 |
+
if c.Listen != "127.0.0.1:7863" {
|
| 17 |
+
t.Errorf("listen=%s", c.Listen)
|
| 18 |
+
}
|
| 19 |
+
if err := c.normalize(); err != nil {
|
| 20 |
+
t.Fatalf("normalize: %v", err)
|
| 21 |
+
}
|
| 22 |
+
if c.SoftRateDur.Seconds() != 600 {
|
| 23 |
+
t.Errorf("soft=%v want 600s", c.SoftRateDur)
|
| 24 |
+
}
|
| 25 |
+
if c.Update.AutoEnabled {
|
| 26 |
+
t.Error("update.auto_enabled default should be false")
|
| 27 |
+
}
|
| 28 |
+
if c.Update.AutoTime != "04:00" {
|
| 29 |
+
t.Errorf("update.auto_time=%q want 04:00", c.Update.AutoTime)
|
| 30 |
+
}
|
| 31 |
+
}
|
| 32 |
+
|
| 33 |
+
func TestUpdateAutoTimeValidation(t *testing.T) {
|
| 34 |
+
for _, value := range []string{"4:00", "+0:00", "24:00", "12:60", "noon"} {
|
| 35 |
+
if _, err := ParseConfig([]byte(`{"update":{"auto_time":"` + value + `"}}`)); err == nil {
|
| 36 |
+
t.Fatalf("auto_time %q should be rejected", value)
|
| 37 |
+
}
|
| 38 |
+
}
|
| 39 |
+
for _, value := range []string{"00:00", "04:00", "23:59"} {
|
| 40 |
+
c, err := ParseConfig([]byte(`{"update":{"auto_time":"` + value + `"}}`))
|
| 41 |
+
if err != nil || c.Update.AutoTime != value {
|
| 42 |
+
t.Fatalf("auto_time %q parse failed: cfg=%+v err=%v", value, c, err)
|
| 43 |
+
}
|
| 44 |
+
}
|
| 45 |
+
}
|
| 46 |
+
|
| 47 |
+
// TestPanelPollInterval 面板自动刷新间隔:0 = 缺省、负数 = 关闭自动刷新。
|
| 48 |
+
// normalize **不得**把负数回落成 0(那会把「关闭」变成「5 秒」)。
|
| 49 |
+
func TestPanelPollInterval(t *testing.T) {
|
| 50 |
+
c := Default()
|
| 51 |
+
if err := c.normalize(); err != nil {
|
| 52 |
+
t.Fatalf("normalize: %v", err)
|
| 53 |
+
}
|
| 54 |
+
if c.Panel.PollIntervalSec != 0 {
|
| 55 |
+
t.Fatalf("缺省 poll_interval_sec=%d want 0(= 前端缺省 5s)", c.Panel.PollIntervalSec)
|
| 56 |
+
}
|
| 57 |
+
|
| 58 |
+
off, err := ParseConfig([]byte(`{"panel":{"poll_interval_sec":-1}}`))
|
| 59 |
+
if err != nil {
|
| 60 |
+
t.Fatalf("parse off: %v", err)
|
| 61 |
+
}
|
| 62 |
+
if off.Panel.PollIntervalSec != -1 {
|
| 63 |
+
t.Fatalf("poll_interval_sec=%d want -1(关闭自动刷新,normalize 不得回落)", off.Panel.PollIntervalSec)
|
| 64 |
+
}
|
| 65 |
+
|
| 66 |
+
slow, err := ParseConfig([]byte(`{"panel":{"poll_interval_sec":60}}`))
|
| 67 |
+
if err != nil {
|
| 68 |
+
t.Fatalf("parse slow: %v", err)
|
| 69 |
+
}
|
| 70 |
+
if slow.Panel.PollIntervalSec != 60 {
|
| 71 |
+
t.Fatalf("poll_interval_sec=%d want 60", slow.Panel.PollIntervalSec)
|
| 72 |
+
}
|
| 73 |
+
}
|
| 74 |
+
|
| 75 |
+
func TestPanelPackageDetailLimit(t *testing.T) {
|
| 76 |
+
c := Default()
|
| 77 |
+
if err := c.normalize(); err != nil {
|
| 78 |
+
t.Fatalf("normalize: %v", err)
|
| 79 |
+
}
|
| 80 |
+
if c.Panel.PackageDetailLimit != 5 {
|
| 81 |
+
t.Fatalf("default package_detail_limit=%d want 5", c.Panel.PackageDetailLimit)
|
| 82 |
+
}
|
| 83 |
+
|
| 84 |
+
configured, err := ParseConfig([]byte(`{"panel":{"package_detail_limit":8}}`))
|
| 85 |
+
if err != nil {
|
| 86 |
+
t.Fatalf("parse configured limit: %v", err)
|
| 87 |
+
}
|
| 88 |
+
if configured.Panel.PackageDetailLimit != 8 {
|
| 89 |
+
t.Fatalf("configured package_detail_limit=%d want 8", configured.Panel.PackageDetailLimit)
|
| 90 |
+
}
|
| 91 |
+
|
| 92 |
+
fallback, err := ParseConfig([]byte(`{"panel":{"package_detail_limit":0}}`))
|
| 93 |
+
if err != nil {
|
| 94 |
+
t.Fatalf("parse fallback limit: %v", err)
|
| 95 |
+
}
|
| 96 |
+
if fallback.Panel.PackageDetailLimit != 5 {
|
| 97 |
+
t.Fatalf("fallback package_detail_limit=%d want 5", fallback.Panel.PackageDetailLimit)
|
| 98 |
+
}
|
| 99 |
+
}
|
| 100 |
+
|
| 101 |
+
func TestLoggingDefaults(t *testing.T) {
|
| 102 |
+
c := Default()
|
| 103 |
+
if err := c.normalize(); err != nil {
|
| 104 |
+
t.Fatal(err)
|
| 105 |
+
}
|
| 106 |
+
if !c.Logging.RequestArchiveEnabled || c.Logging.RequestRetentionDays != 7 || c.Logging.RequestArchiveMaxMB != 100 {
|
| 107 |
+
t.Fatalf("logging defaults = %+v", c.Logging)
|
| 108 |
+
}
|
| 109 |
+
// 来源记录(IP/UA)缺省开启:键缺席时必须保持 true,只有显式 false 才关闭。
|
| 110 |
+
if !c.Logging.RequestClientInfo {
|
| 111 |
+
t.Fatalf("request_client_info default = false, want true: %+v", c.Logging)
|
| 112 |
+
}
|
| 113 |
+
configured, err := ParseConfig([]byte(`{"logging":{"request_archive_enabled":false,"request_retention_days":30,"request_archive_max_mb":500}}`))
|
| 114 |
+
if err != nil {
|
| 115 |
+
t.Fatal(err)
|
| 116 |
+
}
|
| 117 |
+
if configured.Logging.RequestArchiveEnabled || configured.Logging.RequestRetentionDays != 30 || configured.Logging.RequestArchiveMaxMB != 500 {
|
| 118 |
+
t.Fatalf("configured logging = %+v", configured.Logging)
|
| 119 |
+
}
|
| 120 |
+
off, err := ParseConfig([]byte(`{"logging":{"request_client_info":false}}`))
|
| 121 |
+
if err != nil {
|
| 122 |
+
t.Fatal(err)
|
| 123 |
+
}
|
| 124 |
+
if off.Logging.RequestClientInfo {
|
| 125 |
+
t.Fatalf("explicit false ignored: %+v", off.Logging)
|
| 126 |
+
}
|
| 127 |
+
fallback, err := ParseConfig([]byte(`{"logging":{"request_retention_days":0,"request_archive_max_mb":0}}`))
|
| 128 |
+
if err != nil {
|
| 129 |
+
t.Fatal(err)
|
| 130 |
+
}
|
| 131 |
+
if fallback.Logging.RequestRetentionDays != 7 || fallback.Logging.RequestArchiveMaxMB != 100 {
|
| 132 |
+
t.Fatalf("logging fallback = %+v", fallback.Logging)
|
| 133 |
+
}
|
| 134 |
+
}
|
| 135 |
+
|
| 136 |
+
func TestLoadFile(t *testing.T) {
|
| 137 |
+
dir := t.TempDir()
|
| 138 |
+
fp := filepath.Join(dir, "c.json")
|
| 139 |
+
os.WriteFile(fp, []byte(`{"listen":":9999","api_key":"k"}`), 0o600)
|
| 140 |
+
c, err := Load(fp)
|
| 141 |
+
if err != nil {
|
| 142 |
+
t.Fatal(err)
|
| 143 |
+
}
|
| 144 |
+
if c.Listen != ":9999" || c.APIKey != "k" {
|
| 145 |
+
t.Errorf("c=%+v", c)
|
| 146 |
+
}
|
| 147 |
+
}
|
| 148 |
+
|
| 149 |
+
func TestEnvOverride(t *testing.T) {
|
| 150 |
+
t.Setenv("WB2A_LISTEN", ":7777")
|
| 151 |
+
t.Setenv("WB2A_API_KEY", "envkey")
|
| 152 |
+
c, err := Load("")
|
| 153 |
+
if err != nil {
|
| 154 |
+
t.Fatal(err)
|
| 155 |
+
}
|
| 156 |
+
if c.Listen != ":7777" || c.APIKey != "envkey" {
|
| 157 |
+
t.Errorf("c=%+v", c)
|
| 158 |
+
}
|
| 159 |
+
}
|
| 160 |
+
|
| 161 |
+
func TestBadDuration(t *testing.T) {
|
| 162 |
+
dir := t.TempDir()
|
| 163 |
+
fp := filepath.Join(dir, "c.json")
|
| 164 |
+
os.WriteFile(fp, []byte(`{"cooldown":{"soft_rate":"not-a-duration"}}`), 0o600)
|
| 165 |
+
if _, err := Load(fp); err == nil {
|
| 166 |
+
t.Fatal("want error for bad duration")
|
| 167 |
+
}
|
| 168 |
+
}
|
| 169 |
+
|
| 170 |
+
func TestHardCreditKeyIgnored(t *testing.T) {
|
| 171 |
+
// 退役的 hard_credit 键作为 JSON 未知字段被自然忽略,不报错。
|
| 172 |
+
dir := t.TempDir()
|
| 173 |
+
fp := filepath.Join(dir, "c.json")
|
| 174 |
+
os.WriteFile(fp, []byte(`{"cooldown":{"hard_credit":"not-a-duration","soft_rate":"30s"}}`), 0o600)
|
| 175 |
+
c, err := Load(fp)
|
| 176 |
+
if err != nil {
|
| 177 |
+
t.Fatalf("hard_credit must be ignored (not validated): %v", err)
|
| 178 |
+
}
|
| 179 |
+
if c.SoftRateDur.Seconds() != 30 {
|
| 180 |
+
t.Errorf("soft_rate=%v want 30s", c.SoftRateDur)
|
| 181 |
+
}
|
| 182 |
+
}
|
| 183 |
+
|
| 184 |
+
func TestNewPoolConfigDefaults(t *testing.T) {
|
| 185 |
+
c := Default()
|
| 186 |
+
if err := c.normalize(); err != nil {
|
| 187 |
+
t.Fatalf("normalize: %v", err)
|
| 188 |
+
}
|
| 189 |
+
if c.Pool.MaxInFlight != 3 {
|
| 190 |
+
t.Errorf("max_in_flight=%d want 3", c.Pool.MaxInFlight)
|
| 191 |
+
}
|
| 192 |
+
if c.Pool.BreakerThreshold != 3 {
|
| 193 |
+
t.Errorf("breaker_threshold=%d want 3", c.Pool.BreakerThreshold)
|
| 194 |
+
}
|
| 195 |
+
if c.BreakerCooldownDur.Minutes() != 30 {
|
| 196 |
+
t.Errorf("breaker_cooldown=%v want 30m", c.BreakerCooldownDur)
|
| 197 |
+
}
|
| 198 |
+
if c.BreakerCooldownMaxD.Hours() != 6 {
|
| 199 |
+
t.Errorf("breaker_cooldown_max=%v want 6h", c.BreakerCooldownMaxD)
|
| 200 |
+
}
|
| 201 |
+
if c.Pool.IdleWeightPerHour != 0.5 || c.Pool.IdleWeightMax != 5.0 {
|
| 202 |
+
t.Errorf("idle weights=%v/%v", c.Pool.IdleWeightPerHour, c.Pool.IdleWeightMax)
|
| 203 |
+
}
|
| 204 |
+
if !c.Pool.PreferExpiring || c.ExpiringSoonDur != 30*24*time.Hour {
|
| 205 |
+
t.Errorf("expiring defaults: enabled=%v window=%v", c.Pool.PreferExpiring, c.ExpiringSoonDur)
|
| 206 |
+
}
|
| 207 |
+
if c.SoftRateMaxDur.Hours() != 2 {
|
| 208 |
+
t.Errorf("soft_rate_max=%v want 2h", c.SoftRateMaxDur)
|
| 209 |
+
}
|
| 210 |
+
if !c.SessionSticky.Enabled {
|
| 211 |
+
t.Error("session_sticky.enabled want true")
|
| 212 |
+
}
|
| 213 |
+
if c.SessionTTL.Minutes() != 30 || c.SessionGCInterval.Minutes() != 5 {
|
| 214 |
+
t.Errorf("session durations=%v/%v", c.SessionTTL, c.SessionGCInterval)
|
| 215 |
+
}
|
| 216 |
+
if c.Upstash.URL != "" || c.Upstash.Token != "" {
|
| 217 |
+
t.Errorf("upstash default should be empty: %+v", c.Upstash)
|
| 218 |
+
}
|
| 219 |
+
}
|
| 220 |
+
|
| 221 |
+
func TestPoolConfigParsedFromFile(t *testing.T) {
|
| 222 |
+
dir := t.TempDir()
|
| 223 |
+
fp := filepath.Join(dir, "c.json")
|
| 224 |
+
os.WriteFile(fp, []byte(`{
|
| 225 |
+
"upstash":{"url":"https://foo.upstash.io","token":"tok"},
|
| 226 |
+
"pool":{
|
| 227 |
+
"max_in_flight":5,
|
| 228 |
+
"breaker_threshold":4,
|
| 229 |
+
"breaker_cooldown":"10m",
|
| 230 |
+
"breaker_cooldown_max":"2h",
|
| 231 |
+
"idle_weight_per_hour":0.7,
|
| 232 |
+
"idle_weight_max":8.0,
|
| 233 |
+
"prefer_expiring":false,
|
| 234 |
+
"expiring_soon":"72h"
|
| 235 |
+
},
|
| 236 |
+
"session_sticky":{"enabled":false,"ttl":"1h","gc_interval":"2m"}
|
| 237 |
+
}`), 0o600)
|
| 238 |
+
c, err := Load(fp)
|
| 239 |
+
if err != nil {
|
| 240 |
+
t.Fatal(err)
|
| 241 |
+
}
|
| 242 |
+
if c.Upstash.URL != "https://foo.upstash.io" || c.Upstash.Token != "tok" {
|
| 243 |
+
t.Errorf("upstash=%+v", c.Upstash)
|
| 244 |
+
}
|
| 245 |
+
if c.Pool.MaxInFlight != 5 || c.Pool.BreakerThreshold != 4 {
|
| 246 |
+
t.Errorf("pool=%+v", c.Pool)
|
| 247 |
+
}
|
| 248 |
+
if c.BreakerCooldownDur.Minutes() != 10 || c.BreakerCooldownMaxD.Hours() != 2 {
|
| 249 |
+
t.Errorf("breaker durations=%v/%v", c.BreakerCooldownDur, c.BreakerCooldownMaxD)
|
| 250 |
+
}
|
| 251 |
+
if c.Pool.IdleWeightPerHour != 0.7 || c.Pool.IdleWeightMax != 8.0 {
|
| 252 |
+
t.Errorf("idle weights=%v/%v", c.Pool.IdleWeightPerHour, c.Pool.IdleWeightMax)
|
| 253 |
+
}
|
| 254 |
+
if c.Pool.PreferExpiring || c.ExpiringSoonDur != 72*time.Hour {
|
| 255 |
+
t.Errorf("expiring override: enabled=%v window=%v", c.Pool.PreferExpiring, c.ExpiringSoonDur)
|
| 256 |
+
}
|
| 257 |
+
if c.SessionSticky.Enabled {
|
| 258 |
+
t.Error("session_sticky.enabled want false from file")
|
| 259 |
+
}
|
| 260 |
+
if c.SessionTTL.Hours() != 1 || c.SessionGCInterval.Minutes() != 2 {
|
| 261 |
+
t.Errorf("session durations=%v/%v", c.SessionTTL, c.SessionGCInterval)
|
| 262 |
+
}
|
| 263 |
+
}
|
| 264 |
+
|
| 265 |
+
func TestSoftRateMaxParsedFromFile(t *testing.T) {
|
| 266 |
+
dir := t.TempDir()
|
| 267 |
+
fp := filepath.Join(dir, "c.json")
|
| 268 |
+
os.WriteFile(fp, []byte(`{"cooldown":{"soft_rate":"5m","soft_rate_max":"45m"}}`), 0o600)
|
| 269 |
+
c, err := Load(fp)
|
| 270 |
+
if err != nil {
|
| 271 |
+
t.Fatal(err)
|
| 272 |
+
}
|
| 273 |
+
if c.SoftRateDur.Minutes() != 5 {
|
| 274 |
+
t.Errorf("soft_rate=%v want 5m", c.SoftRateDur)
|
| 275 |
+
}
|
| 276 |
+
if c.SoftRateMaxDur.Minutes() != 45 {
|
| 277 |
+
t.Errorf("soft_rate_max=%v want 45m", c.SoftRateMaxDur)
|
| 278 |
+
}
|
| 279 |
+
}
|
| 280 |
+
|
| 281 |
+
func TestLegacyConfigKeepsPreferExpiringEnabled(t *testing.T) {
|
| 282 |
+
dir := t.TempDir()
|
| 283 |
+
fp := filepath.Join(dir, "c.json")
|
| 284 |
+
os.WriteFile(fp, []byte(`{"pool":{"idle_weight_max":3}}`), 0o600)
|
| 285 |
+
c, err := Load(fp)
|
| 286 |
+
if err != nil {
|
| 287 |
+
t.Fatal(err)
|
| 288 |
+
}
|
| 289 |
+
if !c.Pool.PreferExpiring {
|
| 290 |
+
t.Fatal("missing prefer_expiring must preserve default true")
|
| 291 |
+
}
|
| 292 |
+
}
|
| 293 |
+
|
| 294 |
+
func TestNegativeExpiringSoonClampsToDisabled(t *testing.T) {
|
| 295 |
+
dir := t.TempDir()
|
| 296 |
+
fp := filepath.Join(dir, "c.json")
|
| 297 |
+
os.WriteFile(fp, []byte(`{"pool":{"expiring_soon":"-1h"}}`), 0o600)
|
| 298 |
+
c, err := Load(fp)
|
| 299 |
+
if err != nil {
|
| 300 |
+
t.Fatal(err)
|
| 301 |
+
}
|
| 302 |
+
if c.ExpiringSoonDur != 0 || c.Pool.ExpiringSoon != "0" {
|
| 303 |
+
t.Fatalf("negative window=%v/%q want 0/0", c.ExpiringSoonDur, c.Pool.ExpiringSoon)
|
| 304 |
+
}
|
| 305 |
+
}
|
| 306 |
+
|
| 307 |
+
func TestSoftRateMaxEmptyFallsBackToDefault(t *testing.T) {
|
| 308 |
+
// 键缺席 → Default() 的 2h 保留(空串无法 ParseDuration)。
|
| 309 |
+
dir := t.TempDir()
|
| 310 |
+
fp := filepath.Join(dir, "c.json")
|
| 311 |
+
os.WriteFile(fp, []byte(`{"cooldown":{"soft_rate":"90s"}}`), 0o600)
|
| 312 |
+
c, err := Load(fp)
|
| 313 |
+
if err != nil {
|
| 314 |
+
t.Fatal(err)
|
| 315 |
+
}
|
| 316 |
+
if c.SoftRateMaxDur.Hours() != 2 {
|
| 317 |
+
t.Errorf("soft_rate_max=%v want 2h fallback", c.SoftRateMaxDur)
|
| 318 |
+
}
|
| 319 |
+
}
|
| 320 |
+
|
| 321 |
+
func TestBadSoftRateMax(t *testing.T) {
|
| 322 |
+
dir := t.TempDir()
|
| 323 |
+
fp := filepath.Join(dir, "c.json")
|
| 324 |
+
os.WriteFile(fp, []byte(`{"cooldown":{"soft_rate_max":"oops"}}`), 0o600)
|
| 325 |
+
if _, err := Load(fp); err == nil {
|
| 326 |
+
t.Fatal("want error for bad soft_rate_max")
|
| 327 |
+
}
|
| 328 |
+
}
|
| 329 |
+
|
| 330 |
+
func TestBadBreakerCooldown(t *testing.T) {
|
| 331 |
+
dir := t.TempDir()
|
| 332 |
+
fp := filepath.Join(dir, "c.json")
|
| 333 |
+
os.WriteFile(fp, []byte(`{"pool":{"breaker_cooldown":"oops"}}`), 0o600)
|
| 334 |
+
if _, err := Load(fp); err == nil {
|
| 335 |
+
t.Fatal("want error for bad breaker_cooldown")
|
| 336 |
+
}
|
| 337 |
+
}
|
| 338 |
+
|
| 339 |
+
func TestUpstreamTimeoutDefaults(t *testing.T) {
|
| 340 |
+
// 默认:header 回落 timeout,idle 回落 300。
|
| 341 |
+
c := Default()
|
| 342 |
+
if err := c.normalize(); err != nil {
|
| 343 |
+
t.Fatalf("normalize: %v", err)
|
| 344 |
+
}
|
| 345 |
+
if c.Upstream.TimeoutSeconds != 120 {
|
| 346 |
+
t.Errorf("timeout_seconds=%d want 120", c.Upstream.TimeoutSeconds)
|
| 347 |
+
}
|
| 348 |
+
if c.Upstream.HeaderTimeoutSeconds != 120 {
|
| 349 |
+
t.Errorf("header_timeout_seconds=%d want fallback 120", c.Upstream.HeaderTimeoutSeconds)
|
| 350 |
+
}
|
| 351 |
+
if c.Upstream.IdleTimeoutSeconds != 300 {
|
| 352 |
+
t.Errorf("idle_timeout_seconds=%d want fallback 300", c.Upstream.IdleTimeoutSeconds)
|
| 353 |
+
}
|
| 354 |
+
}
|
| 355 |
+
|
| 356 |
+
func TestUpstreamHeaderFallsBackToTimeout(t *testing.T) {
|
| 357 |
+
// 只设 timeout_seconds:header 回落同值,idle 回落 300。
|
| 358 |
+
dir := t.TempDir()
|
| 359 |
+
fp := filepath.Join(dir, "c.json")
|
| 360 |
+
os.WriteFile(fp, []byte(`{"upstream":{"timeout_seconds":60}}`), 0o600)
|
| 361 |
+
c, err := Load(fp)
|
| 362 |
+
if err != nil {
|
| 363 |
+
t.Fatal(err)
|
| 364 |
+
}
|
| 365 |
+
if c.Upstream.HeaderTimeoutSeconds != 60 {
|
| 366 |
+
t.Errorf("header_timeout_seconds=%d want fallback 60", c.Upstream.HeaderTimeoutSeconds)
|
| 367 |
+
}
|
| 368 |
+
if c.Upstream.IdleTimeoutSeconds != 300 {
|
| 369 |
+
t.Errorf("idle_timeout_seconds=%d want fallback 300", c.Upstream.IdleTimeoutSeconds)
|
| 370 |
+
}
|
| 371 |
+
}
|
| 372 |
+
|
| 373 |
+
func TestUpstreamExplicitHeaderIdle(t *testing.T) {
|
| 374 |
+
dir := t.TempDir()
|
| 375 |
+
fp := filepath.Join(dir, "c.json")
|
| 376 |
+
os.WriteFile(fp, []byte(`{"upstream":{"timeout_seconds":120,"header_timeout_seconds":30,"idle_timeout_seconds":600}}`), 0o600)
|
| 377 |
+
c, err := Load(fp)
|
| 378 |
+
if err != nil {
|
| 379 |
+
t.Fatal(err)
|
| 380 |
+
}
|
| 381 |
+
if c.Upstream.HeaderTimeoutSeconds != 30 {
|
| 382 |
+
t.Errorf("header_timeout_seconds=%d want 30", c.Upstream.HeaderTimeoutSeconds)
|
| 383 |
+
}
|
| 384 |
+
if c.Upstream.IdleTimeoutSeconds != 600 {
|
| 385 |
+
t.Errorf("idle_timeout_seconds=%d want 600", c.Upstream.IdleTimeoutSeconds)
|
| 386 |
+
}
|
| 387 |
+
}
|
| 388 |
+
|
| 389 |
+
func TestUpstreamEnvOverride(t *testing.T) {
|
| 390 |
+
t.Setenv("WB2A_HEADER_TIMEOUT_SECONDS", "45")
|
| 391 |
+
t.Setenv("WB2A_IDLE_TIMEOUT_SECONDS", "900")
|
| 392 |
+
c, err := Load("")
|
| 393 |
+
if err != nil {
|
| 394 |
+
t.Fatal(err)
|
| 395 |
+
}
|
| 396 |
+
if c.Upstream.HeaderTimeoutSeconds != 45 {
|
| 397 |
+
t.Errorf("header_timeout_seconds=%d want env 45", c.Upstream.HeaderTimeoutSeconds)
|
| 398 |
+
}
|
| 399 |
+
if c.Upstream.IdleTimeoutSeconds != 900 {
|
| 400 |
+
t.Errorf("idle_timeout_seconds=%d want env 900", c.Upstream.IdleTimeoutSeconds)
|
| 401 |
+
}
|
| 402 |
+
}
|
| 403 |
+
|
| 404 |
+
// TestRetiredTravelIntervalKeyIgnored 退役的 travel_interval_minutes 键按未知字段忽略,不报错。
|
| 405 |
+
func TestRetiredTravelIntervalKeyIgnored(t *testing.T) {
|
| 406 |
+
dir := t.TempDir()
|
| 407 |
+
fp := filepath.Join(dir, "c.json")
|
| 408 |
+
os.WriteFile(fp, []byte(`{"schedule":{"travel_interval_minutes":15,"checkin_hours":[9]}}`), 0o600)
|
| 409 |
+
c, err := Load(fp)
|
| 410 |
+
if err != nil {
|
| 411 |
+
t.Fatalf("retired key should not fail load: %v", err)
|
| 412 |
+
}
|
| 413 |
+
if len(c.Schedule.CheckinHours) != 1 || c.Schedule.CheckinHours[0] != 9 {
|
| 414 |
+
t.Errorf("checkin_hours=%v want [9](同段其余键照常生效)", c.Schedule.CheckinHours)
|
| 415 |
+
}
|
| 416 |
+
}
|
| 417 |
+
|
| 418 |
+
// TestScheduleEnabledByDefault 四个任务的 enabled 开关默认均为 true:
|
| 419 |
+
// 老 config 不写这些键,行为必须与从前完全一致。
|
| 420 |
+
func TestScheduleEnabledByDefault(t *testing.T) {
|
| 421 |
+
c := Default()
|
| 422 |
+
if err := c.normalize(); err != nil {
|
| 423 |
+
t.Fatalf("normalize: %v", err)
|
| 424 |
+
}
|
| 425 |
+
if !c.Schedule.CheckinEnabled || !c.Schedule.KeepaliveEnabled {
|
| 426 |
+
t.Errorf("enabled defaults want true/true, got %v/%v",
|
| 427 |
+
c.Schedule.CheckinEnabled, c.Schedule.KeepaliveEnabled)
|
| 428 |
+
}
|
| 429 |
+
if !c.Schedule.TravelEnabled || !c.Schedule.ActivityEnabled {
|
| 430 |
+
t.Errorf("travel/activity enabled defaults want true/true, got %v/%v",
|
| 431 |
+
c.Schedule.TravelEnabled, c.Schedule.ActivityEnabled)
|
| 432 |
+
}
|
| 433 |
+
if len(c.Schedule.TravelHours) != 2 || c.Schedule.TravelHours[0] != 9 || c.Schedule.TravelHours[1] != 21 {
|
| 434 |
+
t.Errorf("travel_hours=%v want [9,21]", c.Schedule.TravelHours)
|
| 435 |
+
}
|
| 436 |
+
if len(c.Schedule.ActivityHours) != 1 || c.Schedule.ActivityHours[0] != 10 {
|
| 437 |
+
t.Errorf("activity_hours=%v want [10]", c.Schedule.ActivityHours)
|
| 438 |
+
}
|
| 439 |
+
}
|
| 440 |
+
|
| 441 |
+
// TestScheduleLegacyConfigKeepsRunning 老 config(只写签到/保活小时数组,无新键)加载后仍是启用态,
|
| 442 |
+
// 新开关缺省 true、新 hours 回落默认——对老配置零影响。
|
| 443 |
+
func TestScheduleLegacyConfigKeepsRunning(t *testing.T) {
|
| 444 |
+
dir := t.TempDir()
|
| 445 |
+
fp := filepath.Join(dir, "c.json")
|
| 446 |
+
os.WriteFile(fp, []byte(`{"schedule":{"checkin_hours":[9,21],"keepalive_hours":[22]}}`), 0o600)
|
| 447 |
+
c, err := Load(fp)
|
| 448 |
+
if err != nil {
|
| 449 |
+
t.Fatal(err)
|
| 450 |
+
}
|
| 451 |
+
if !c.Schedule.CheckinEnabled || !c.Schedule.KeepaliveEnabled {
|
| 452 |
+
t.Errorf("legacy config must stay enabled: %+v", c.Schedule)
|
| 453 |
+
}
|
| 454 |
+
if !c.Schedule.TravelEnabled || !c.Schedule.ActivityEnabled {
|
| 455 |
+
t.Errorf("new switches must default true on legacy config: %+v", c.Schedule)
|
| 456 |
+
}
|
| 457 |
+
if len(c.Schedule.CheckinHours) != 2 {
|
| 458 |
+
t.Errorf("checkin_hours=%v", c.Schedule.CheckinHours)
|
| 459 |
+
}
|
| 460 |
+
// 新 hours 缺省 → 回落默认(非空)。
|
| 461 |
+
if len(c.Schedule.TravelHours) != 2 || c.Schedule.TravelHours[0] != 9 || c.Schedule.TravelHours[1] != 21 {
|
| 462 |
+
t.Errorf("travel_hours=%v want default [9,21]", c.Schedule.TravelHours)
|
| 463 |
+
}
|
| 464 |
+
if len(c.Schedule.ActivityHours) != 1 || c.Schedule.ActivityHours[0] != 10 {
|
| 465 |
+
t.Errorf("activity_hours=%v want default [10]", c.Schedule.ActivityHours)
|
| 466 |
+
}
|
| 467 |
+
}
|
| 468 |
+
|
| 469 |
+
// TestScheduleExplicitDisable 显式 checkin_enabled=false 即可真正关掉签到
|
| 470 |
+
// (issue #27 边界:此前无论怎么配小时都关不掉)。
|
| 471 |
+
func TestScheduleExplicitDisable(t *testing.T) {
|
| 472 |
+
dir := t.TempDir()
|
| 473 |
+
fp := filepath.Join(dir, "c.json")
|
| 474 |
+
os.WriteFile(fp, []byte(`{"schedule":{"checkin_enabled":false,"keepalive_enabled":false}}`), 0o600)
|
| 475 |
+
c, err := Load(fp)
|
| 476 |
+
if err != nil {
|
| 477 |
+
t.Fatal(err)
|
| 478 |
+
}
|
| 479 |
+
if c.Schedule.CheckinEnabled || c.Schedule.KeepaliveEnabled {
|
| 480 |
+
t.Errorf("want both disabled: %+v", c.Schedule)
|
| 481 |
+
}
|
| 482 |
+
// 小时数组仍回落默认值(禁用与默认值互不干扰:重新启用无需补配小时)。
|
| 483 |
+
if len(c.Schedule.CheckinHours) != 2 || c.Schedule.CheckinHours[0] != 9 || c.Schedule.CheckinHours[1] != 21 {
|
| 484 |
+
t.Errorf("checkin_hours=%v want default [9 21] even when disabled", c.Schedule.CheckinHours)
|
| 485 |
+
}
|
| 486 |
+
if len(c.Schedule.KeepaliveHours) != 1 || c.Schedule.KeepaliveHours[0] != 22 {
|
| 487 |
+
t.Errorf("keepalive_hours=%v want default [22] even when disabled", c.Schedule.KeepaliveHours)
|
| 488 |
+
}
|
| 489 |
+
}
|
| 490 |
+
|
| 491 |
+
// TestScheduleTravelActivityExplicitDisable 显式关闭旅行/活跃上报开关。
|
| 492 |
+
func TestScheduleTravelActivityExplicitDisable(t *testing.T) {
|
| 493 |
+
dir := t.TempDir()
|
| 494 |
+
fp := filepath.Join(dir, "c.json")
|
| 495 |
+
os.WriteFile(fp, []byte(`{"schedule":{"travel_enabled":false,"activity_enabled":false}}`), 0o600)
|
| 496 |
+
c, err := Load(fp)
|
| 497 |
+
if err != nil {
|
| 498 |
+
t.Fatal(err)
|
| 499 |
+
}
|
| 500 |
+
if c.Schedule.TravelEnabled || c.Schedule.ActivityEnabled {
|
| 501 |
+
t.Errorf("want travel/activity disabled: %+v", c.Schedule)
|
| 502 |
+
}
|
| 503 |
+
// 签到/保活开关缺省 true(互不干扰)。
|
| 504 |
+
if !c.Schedule.CheckinEnabled || !c.Schedule.KeepaliveEnabled {
|
| 505 |
+
t.Errorf("checkin/keepalive should stay enabled: %+v", c.Schedule)
|
| 506 |
+
}
|
| 507 |
+
// hours 仍回落默认。
|
| 508 |
+
if len(c.Schedule.TravelHours) != 2 || c.Schedule.TravelHours[0] != 9 || c.Schedule.TravelHours[1] != 21 {
|
| 509 |
+
t.Errorf("travel_hours=%v want default [9,21] even when disabled", c.Schedule.TravelHours)
|
| 510 |
+
}
|
| 511 |
+
if len(c.Schedule.ActivityHours) != 1 || c.Schedule.ActivityHours[0] != 10 {
|
| 512 |
+
t.Errorf("activity_hours=%v want default [10] even when disabled", c.Schedule.ActivityHours)
|
| 513 |
+
}
|
| 514 |
+
}
|
| 515 |
+
|
| 516 |
+
// TestScheduleTravelActivityInvalidHoursRejected 旅行/活跃非法小时报错并指向正确开关。
|
| 517 |
+
func TestScheduleTravelActivityInvalidHoursRejected(t *testing.T) {
|
| 518 |
+
cases := []struct{ body, wantSwitch string }{
|
| 519 |
+
{`{"schedule":{"travel_hours":[25]}}`, "travel_enabled"},
|
| 520 |
+
{`{"schedule":{"travel_hours":[-1]}}`, "travel_enabled"},
|
| 521 |
+
{`{"schedule":{"activity_hours":[24]}}`, "activity_enabled"},
|
| 522 |
+
{`{"schedule":{"activity_hours":[-1]}}`, "activity_enabled"},
|
| 523 |
+
}
|
| 524 |
+
for _, tc := range cases {
|
| 525 |
+
dir := t.TempDir()
|
| 526 |
+
fp := filepath.Join(dir, "c.json")
|
| 527 |
+
os.WriteFile(fp, []byte(tc.body), 0o600)
|
| 528 |
+
_, err := Load(fp)
|
| 529 |
+
if err == nil {
|
| 530 |
+
t.Fatalf("want error for %s", tc.body)
|
| 531 |
+
}
|
| 532 |
+
if !strings.Contains(err.Error(), tc.wantSwitch) {
|
| 533 |
+
t.Errorf("error for %s should point at schedule.%s: %v", tc.body, tc.wantSwitch, err)
|
| 534 |
+
}
|
| 535 |
+
}
|
| 536 |
+
}
|
| 537 |
+
|
| 538 |
+
// TestScheduleTravelActivityExplicitHours 显式配置旅行/活跃小时。
|
| 539 |
+
func TestScheduleTravelActivityExplicitHours(t *testing.T) {
|
| 540 |
+
dir := t.TempDir()
|
| 541 |
+
fp := filepath.Join(dir, "c.json")
|
| 542 |
+
os.WriteFile(fp, []byte(`{"schedule":{"travel_hours":[9,21],"activity_hours":[11]}}`), 0o600)
|
| 543 |
+
c, err := Load(fp)
|
| 544 |
+
if err != nil {
|
| 545 |
+
t.Fatal(err)
|
| 546 |
+
}
|
| 547 |
+
if len(c.Schedule.TravelHours) != 2 || c.Schedule.TravelHours[0] != 9 || c.Schedule.TravelHours[1] != 21 {
|
| 548 |
+
t.Errorf("travel_hours=%v want [9 21]", c.Schedule.TravelHours)
|
| 549 |
+
}
|
| 550 |
+
if len(c.Schedule.ActivityHours) != 1 || c.Schedule.ActivityHours[0] != 11 {
|
| 551 |
+
t.Errorf("activity_hours=%v want [11]", c.Schedule.ActivityHours)
|
| 552 |
+
}
|
| 553 |
+
}
|
| 554 |
+
|
| 555 |
+
// TestScheduleDisableKeepsExplicitHours 禁用不擦除用户配置的小时(便于原样恢复)。
|
| 556 |
+
func TestScheduleDisableKeepsExplicitHours(t *testing.T) {
|
| 557 |
+
dir := t.TempDir()
|
| 558 |
+
fp := filepath.Join(dir, "c.json")
|
| 559 |
+
os.WriteFile(fp, []byte(`{"schedule":{"checkin_enabled":false,"checkin_hours":[10,14]}}`), 0o600)
|
| 560 |
+
c, err := Load(fp)
|
| 561 |
+
if err != nil {
|
| 562 |
+
t.Fatal(err)
|
| 563 |
+
}
|
| 564 |
+
if c.Schedule.CheckinEnabled {
|
| 565 |
+
t.Error("checkin should be disabled")
|
| 566 |
+
}
|
| 567 |
+
if len(c.Schedule.CheckinHours) != 2 || c.Schedule.CheckinHours[0] != 10 || c.Schedule.CheckinHours[1] != 14 {
|
| 568 |
+
t.Errorf("explicit hours must be preserved: %v", c.Schedule.CheckinHours)
|
| 569 |
+
}
|
| 570 |
+
}
|
| 571 |
+
|
| 572 |
+
// TestScheduleEmptyHoursFallsBackToDefault 空数组 / null / 缺省都视同「未配置」→ 回落默认。
|
| 573 |
+
func TestScheduleEmptyHoursFallsBackToDefault(t *testing.T) {
|
| 574 |
+
cases := map[string]string{
|
| 575 |
+
"absent": `{}`,
|
| 576 |
+
"empty": `{"schedule":{}}`,
|
| 577 |
+
"null": `{"schedule":{"checkin_hours":null,"keepalive_hours":null,"travel_hours":null,"activity_hours":null}}`,
|
| 578 |
+
"emptyarr": `{"schedule":{"checkin_hours":[],"keepalive_hours":[],"travel_hours":[],"activity_hours":[]}}`,
|
| 579 |
+
}
|
| 580 |
+
for name, body := range cases {
|
| 581 |
+
t.Run(name, func(t *testing.T) {
|
| 582 |
+
dir := t.TempDir()
|
| 583 |
+
fp := filepath.Join(dir, "c.json")
|
| 584 |
+
os.WriteFile(fp, []byte(body), 0o600)
|
| 585 |
+
c, err := Load(fp)
|
| 586 |
+
if err != nil {
|
| 587 |
+
t.Fatal(err)
|
| 588 |
+
}
|
| 589 |
+
if len(c.Schedule.CheckinHours) != 2 || c.Schedule.CheckinHours[0] != 9 || c.Schedule.CheckinHours[1] != 21 {
|
| 590 |
+
t.Errorf("checkin_hours=%v want default [9 21]", c.Schedule.CheckinHours)
|
| 591 |
+
}
|
| 592 |
+
if len(c.Schedule.KeepaliveHours) != 1 || c.Schedule.KeepaliveHours[0] != 22 {
|
| 593 |
+
t.Errorf("keepalive_hours=%v want default [22]", c.Schedule.KeepaliveHours)
|
| 594 |
+
}
|
| 595 |
+
if len(c.Schedule.TravelHours) != 2 || c.Schedule.TravelHours[0] != 9 || c.Schedule.TravelHours[1] != 21 {
|
| 596 |
+
t.Errorf("travel_hours=%v want default [9 21]", c.Schedule.TravelHours)
|
| 597 |
+
}
|
| 598 |
+
if len(c.Schedule.ActivityHours) != 1 || c.Schedule.ActivityHours[0] != 10 {
|
| 599 |
+
t.Errorf("activity_hours=%v want default [10]", c.Schedule.ActivityHours)
|
| 600 |
+
}
|
| 601 |
+
if !c.Schedule.CheckinEnabled || !c.Schedule.KeepaliveEnabled {
|
| 602 |
+
t.Errorf("empty hours must not imply disabled: %+v", c.Schedule)
|
| 603 |
+
}
|
| 604 |
+
if !c.Schedule.TravelEnabled || !c.Schedule.ActivityEnabled {
|
| 605 |
+
t.Errorf("empty hours must not imply disabled: %+v", c.Schedule)
|
| 606 |
+
}
|
| 607 |
+
})
|
| 608 |
+
}
|
| 609 |
+
}
|
| 610 |
+
|
| 611 |
+
// TestScheduleInvalidHourRejected 非法小时快速失败:指向正确的禁用开关,避免用户
|
| 612 |
+
// 猜测哨兵值([-1] 之类)被静默当成"改到别的整点"。
|
| 613 |
+
func TestScheduleInvalidHourRejected(t *testing.T) {
|
| 614 |
+
cases := []struct{ body, wantSwitch string }{
|
| 615 |
+
{`{"schedule":{"checkin_hours":[25]}}`, "checkin_enabled"},
|
| 616 |
+
{`{"schedule":{"checkin_hours":[-1]}}`, "checkin_enabled"},
|
| 617 |
+
{`{"schedule":{"keepalive_hours":[-1]}}`, "keepalive_enabled"},
|
| 618 |
+
}
|
| 619 |
+
for _, tc := range cases {
|
| 620 |
+
dir := t.TempDir()
|
| 621 |
+
fp := filepath.Join(dir, "c.json")
|
| 622 |
+
os.WriteFile(fp, []byte(tc.body), 0o600)
|
| 623 |
+
_, err := Load(fp)
|
| 624 |
+
if err == nil {
|
| 625 |
+
t.Fatalf("want error for %s", tc.body)
|
| 626 |
+
}
|
| 627 |
+
if !strings.Contains(err.Error(), tc.wantSwitch) {
|
| 628 |
+
t.Errorf("error for %s should point at schedule.%s: %v", tc.body, tc.wantSwitch, err)
|
| 629 |
+
}
|
| 630 |
+
}
|
| 631 |
+
}
|
| 632 |
+
|
| 633 |
+
func TestBadSessionTTL(t *testing.T) {
|
| 634 |
+
dir := t.TempDir()
|
| 635 |
+
fp := filepath.Join(dir, "c.json")
|
| 636 |
+
os.WriteFile(fp, []byte(`{"session_sticky":{"ttl":"oops"}}`), 0o600)
|
| 637 |
+
if _, err := Load(fp); err == nil {
|
| 638 |
+
t.Fatal("want error for bad session_sticky.ttl")
|
| 639 |
+
}
|
| 640 |
+
}
|
| 641 |
+
|
| 642 |
+
func TestWriteDefault(t *testing.T) {
|
| 643 |
+
dir := t.TempDir()
|
| 644 |
+
fp := filepath.Join(dir, "sub", "config.json") // 顺带验证父目录自动创建
|
| 645 |
+
key, err := WriteDefault(fp)
|
| 646 |
+
if err != nil {
|
| 647 |
+
t.Fatal(err)
|
| 648 |
+
}
|
| 649 |
+
// key 形如 sk-<24字符随机串>,两次生成不重复
|
| 650 |
+
if !strings.HasPrefix(key, "sk-") || len(key) < 20 {
|
| 651 |
+
t.Errorf("key=%q want sk-<random>", key)
|
| 652 |
+
}
|
| 653 |
+
if key2, _ := WriteDefault(filepath.Join(dir, "another.json")); key2 == key {
|
| 654 |
+
t.Errorf("two generated keys identical: %q", key)
|
| 655 |
+
}
|
| 656 |
+
// 落盘文件可被 Load 正常加载,推荐值齐备且 api_key 生效
|
| 657 |
+
c, err := Load(fp)
|
| 658 |
+
if err != nil {
|
| 659 |
+
t.Fatalf("load generated config: %v", err)
|
| 660 |
+
}
|
| 661 |
+
if c.APIKey != key {
|
| 662 |
+
t.Errorf("api_key=%q want %q", c.APIKey, key)
|
| 663 |
+
}
|
| 664 |
+
if c.Listen != "127.0.0.1:7863" || c.AuthDir != "./auths" || c.StateFile != "./data/state.json" {
|
| 665 |
+
t.Errorf("generated defaults off: %+v", c)
|
| 666 |
+
}
|
| 667 |
+
if len(c.Schedule.CheckinHours) == 0 || !c.Schedule.CheckinEnabled {
|
| 668 |
+
t.Errorf("generated schedule off: %+v", c.Schedule)
|
| 669 |
+
}
|
| 670 |
+
// 已存在的文件不覆盖:二次写入同一路径必须报错
|
| 671 |
+
if _, err := WriteDefault(fp); err == nil {
|
| 672 |
+
t.Error("WriteDefault must refuse to overwrite existing file")
|
| 673 |
+
}
|
| 674 |
+
}
|
| 675 |
+
|
| 676 |
+
// 补领清扫(issue #174):缺省启用 + 15 分钟;显式关闭时 interval 归零(不启动);
|
| 677 |
+
// minutes<=0 回落 15。
|
| 678 |
+
func TestTaskSweepDefaults(t *testing.T) {
|
| 679 |
+
c := Default()
|
| 680 |
+
if err := c.normalize(); err != nil {
|
| 681 |
+
t.Fatal(err)
|
| 682 |
+
}
|
| 683 |
+
if !c.Schedule.TaskSweepEnabled || c.TaskSweepInterval != 15*time.Minute {
|
| 684 |
+
t.Errorf("default task sweep: enabled=%v interval=%v", c.Schedule.TaskSweepEnabled, c.TaskSweepInterval)
|
| 685 |
+
}
|
| 686 |
+
dir := t.TempDir()
|
| 687 |
+
fp := filepath.Join(dir, "c.json")
|
| 688 |
+
os.WriteFile(fp, []byte(`{"schedule":{"task_sweep_minutes":3}}`), 0o600)
|
| 689 |
+
c2, err := Load(fp)
|
| 690 |
+
if err != nil {
|
| 691 |
+
t.Fatal(err)
|
| 692 |
+
}
|
| 693 |
+
if c2.TaskSweepInterval != 3*time.Minute {
|
| 694 |
+
t.Errorf("interval=%v want 3m", c2.TaskSweepInterval)
|
| 695 |
+
}
|
| 696 |
+
os.WriteFile(fp, []byte(`{"schedule":{"task_sweep_enabled":false}}`), 0o600)
|
| 697 |
+
c3, err := Load(fp)
|
| 698 |
+
if err != nil {
|
| 699 |
+
t.Fatal(err)
|
| 700 |
+
}
|
| 701 |
+
if c3.TaskSweepInterval != 0 {
|
| 702 |
+
t.Errorf("disabled interval=%v want 0", c3.TaskSweepInterval)
|
| 703 |
+
}
|
| 704 |
+
os.WriteFile(fp, []byte(`{"schedule":{"task_sweep_minutes":-5}}`), 0o600)
|
| 705 |
+
c4, err := Load(fp)
|
| 706 |
+
if err != nil {
|
| 707 |
+
t.Fatal(err)
|
| 708 |
+
}
|
| 709 |
+
if c4.TaskSweepInterval != 15*time.Minute {
|
| 710 |
+
t.Errorf("negative minutes interval=%v want 15m", c4.TaskSweepInterval)
|
| 711 |
+
}
|
| 712 |
+
}
|
| 713 |
+
|
| 714 |
+
// TestKeepaliveRefreshWindow checks defaults, explicit durations, and invalid values.
|
| 715 |
+
func TestKeepaliveRefreshWindow(t *testing.T) {
|
| 716 |
+
c := Default()
|
| 717 |
+
if err := c.normalize(); err != nil {
|
| 718 |
+
t.Fatal(err)
|
| 719 |
+
}
|
| 720 |
+
if c.Schedule.KeepaliveRefreshWindow != "168h" || c.KeepaliveRefreshWindowDur != 168*time.Hour {
|
| 721 |
+
t.Fatalf("default keepalive window=%q/%v want 168h", c.Schedule.KeepaliveRefreshWindow, c.KeepaliveRefreshWindowDur)
|
| 722 |
+
}
|
| 723 |
+
|
| 724 |
+
dir := t.TempDir()
|
| 725 |
+
fp := filepath.Join(dir, "c.json")
|
| 726 |
+
if err := os.WriteFile(fp, []byte(`{"schedule":{"keepalive_refresh_window":"24h"}}`), 0o600); err != nil {
|
| 727 |
+
t.Fatal(err)
|
| 728 |
+
}
|
| 729 |
+
c2, err := Load(fp)
|
| 730 |
+
if err != nil {
|
| 731 |
+
t.Fatal(err)
|
| 732 |
+
}
|
| 733 |
+
if c2.KeepaliveRefreshWindowDur != 24*time.Hour {
|
| 734 |
+
t.Fatalf("explicit keepalive window=%v want 24h", c2.KeepaliveRefreshWindowDur)
|
| 735 |
+
}
|
| 736 |
+
|
| 737 |
+
// 老 config 没这个键:缺键必须回落到默认,不能报错。
|
| 738 |
+
if err := os.WriteFile(fp, []byte(`{"schedule":{"keepalive_hours":[22]}}`), 0o600); err != nil {
|
| 739 |
+
t.Fatal(err)
|
| 740 |
+
}
|
| 741 |
+
c3, err := Load(fp)
|
| 742 |
+
if err != nil {
|
| 743 |
+
t.Fatalf("缺键不应报错: %v", err)
|
| 744 |
+
}
|
| 745 |
+
if c3.KeepaliveRefreshWindowDur != 168*time.Hour {
|
| 746 |
+
t.Errorf("缺键窗口=%v want 168h", c3.KeepaliveRefreshWindowDur)
|
| 747 |
+
}
|
| 748 |
+
|
| 749 |
+
for _, raw := range []string{"0s", "-1h", "not-a-duration"} {
|
| 750 |
+
if err := os.WriteFile(fp, []byte(`{"schedule":{"keepalive_refresh_window":"`+raw+`"}}`), 0o600); err != nil {
|
| 751 |
+
t.Fatal(err)
|
| 752 |
+
}
|
| 753 |
+
if _, err := Load(fp); err == nil {
|
| 754 |
+
t.Errorf("keepalive_refresh_window=%q should be rejected", raw)
|
| 755 |
+
}
|
| 756 |
+
}
|
| 757 |
+
}
|
| 758 |
+
|
| 759 |
+
func TestBalanceRefreshDefaults(t *testing.T) {
|
| 760 |
+
// 缺省:启用 + 30 分钟
|
| 761 |
+
c := Default()
|
| 762 |
+
if err := c.normalize(); err != nil {
|
| 763 |
+
t.Fatal(err)
|
| 764 |
+
}
|
| 765 |
+
if !c.Schedule.BalanceRefreshEnabled || c.BalanceRefreshInterval != 5*time.Minute {
|
| 766 |
+
t.Errorf("default balance refresh: enabled=%v interval=%v", c.Schedule.BalanceRefreshEnabled, c.BalanceRefreshInterval)
|
| 767 |
+
}
|
| 768 |
+
// 显式配置 10 分钟
|
| 769 |
+
dir := t.TempDir()
|
| 770 |
+
fp := filepath.Join(dir, "c.json")
|
| 771 |
+
os.WriteFile(fp, []byte(`{"schedule":{"balance_refresh_minutes":10}}`), 0o600)
|
| 772 |
+
c2, err := Load(fp)
|
| 773 |
+
if err != nil {
|
| 774 |
+
t.Fatal(err)
|
| 775 |
+
}
|
| 776 |
+
if c2.BalanceRefreshInterval != 10*time.Minute {
|
| 777 |
+
t.Errorf("interval=%v want 10m", c2.BalanceRefreshInterval)
|
| 778 |
+
}
|
| 779 |
+
// 显式关闭:interval 归零(不启动)
|
| 780 |
+
os.WriteFile(fp, []byte(`{"schedule":{"balance_refresh_enabled":false}}`), 0o600)
|
| 781 |
+
c3, err := Load(fp)
|
| 782 |
+
if err != nil {
|
| 783 |
+
t.Fatal(err)
|
| 784 |
+
}
|
| 785 |
+
if c3.BalanceRefreshInterval != 0 {
|
| 786 |
+
t.Errorf("disabled interval=%v want 0", c3.BalanceRefreshInterval)
|
| 787 |
+
}
|
| 788 |
+
// 启用但 minutes<=0 → 回落默认 30
|
| 789 |
+
os.WriteFile(fp, []byte(`{"schedule":{"balance_refresh_minutes":-5}}`), 0o600)
|
| 790 |
+
c4, err := Load(fp)
|
| 791 |
+
if err != nil {
|
| 792 |
+
t.Fatal(err)
|
| 793 |
+
}
|
| 794 |
+
if c4.BalanceRefreshInterval != 5*time.Minute {
|
| 795 |
+
t.Errorf("fallback interval=%v want 30m", c4.BalanceRefreshInterval)
|
| 796 |
+
}
|
| 797 |
+
}
|
| 798 |
+
|
| 799 |
+
// TestPromptDefaultPassthrough 默认 prompt.mode=passthrough(对齐上游:透传客户端
|
| 800 |
+
// 原始 system 是更保守的缺省);custom 由用户显式选择,此时 PromptText 为内置默认(非空)。
|
| 801 |
+
func TestPromptDefaultPassthrough(t *testing.T) {
|
| 802 |
+
c, err := Load("")
|
| 803 |
+
if err != nil {
|
| 804 |
+
t.Fatal(err)
|
| 805 |
+
}
|
| 806 |
+
if c.Prompt.Mode != "passthrough" {
|
| 807 |
+
t.Errorf("prompt.mode=%q want passthrough", c.Prompt.Mode)
|
| 808 |
+
}
|
| 809 |
+
// passthrough 不加载提示词文本(透传客户端 system);切 custom 时 normalize 会加载。
|
| 810 |
+
}
|
| 811 |
+
|
| 812 |
+
// TestPromptExplicitPassthrough passthrough 模式不加载文本(透传客户端原始 system)。
|
| 813 |
+
func TestPromptExplicitPassthrough(t *testing.T) {
|
| 814 |
+
dir := t.TempDir()
|
| 815 |
+
fp := filepath.Join(dir, "c.json")
|
| 816 |
+
os.WriteFile(fp, []byte(`{"prompt":{"mode":"passthrough"}}`), 0o600)
|
| 817 |
+
c, err := Load(fp)
|
| 818 |
+
if err != nil {
|
| 819 |
+
t.Fatal(err)
|
| 820 |
+
}
|
| 821 |
+
if c.Prompt.Mode != "passthrough" {
|
| 822 |
+
t.Errorf("mode=%q want passthrough", c.Prompt.Mode)
|
| 823 |
+
}
|
| 824 |
+
if c.PromptText != "" {
|
| 825 |
+
t.Errorf("passthrough should not load PromptText, got len=%d", len(c.PromptText))
|
| 826 |
+
}
|
| 827 |
+
}
|
| 828 |
+
|
| 829 |
+
// TestPromptInvalidMode 非法 mode 启动报错。
|
| 830 |
+
func TestPromptInvalidMode(t *testing.T) {
|
| 831 |
+
dir := t.TempDir()
|
| 832 |
+
fp := filepath.Join(dir, "c.json")
|
| 833 |
+
os.WriteFile(fp, []byte(`{"prompt":{"mode":"bogus"}}`), 0o600)
|
| 834 |
+
if _, err := Load(fp); err == nil {
|
| 835 |
+
t.Fatal("want error for invalid prompt.mode")
|
| 836 |
+
}
|
| 837 |
+
}
|
| 838 |
+
|
| 839 |
+
// TestPromptFileMissing 文件路径非空但不存在 → 启动报错(fail fast)。
|
| 840 |
+
func TestPromptFileMissing(t *testing.T) {
|
| 841 |
+
dir := t.TempDir()
|
| 842 |
+
fp := filepath.Join(dir, "c.json")
|
| 843 |
+
os.WriteFile(fp, []byte(`{"prompt":{"mode":"custom","file":"/nonexistent/p.md"}}`), 0o600)
|
| 844 |
+
if _, err := Load(fp); err == nil {
|
| 845 |
+
t.Fatal("want error for missing prompt file")
|
| 846 |
+
}
|
| 847 |
+
}
|
| 848 |
+
|
| 849 |
+
// TestPromptFileOverride 自定义 file 覆盖内置默认。
|
| 850 |
+
func TestPromptFileOverride(t *testing.T) {
|
| 851 |
+
dir := t.TempDir()
|
| 852 |
+
pf := filepath.Join(dir, "my.md")
|
| 853 |
+
want := "我的自定义人格入口"
|
| 854 |
+
os.WriteFile(pf, []byte(want), 0o600)
|
| 855 |
+
cf := filepath.Join(dir, "c.json")
|
| 856 |
+
// 用 json.Marshal 拼路径:Windows 反斜杠必须转义,手工字符串拼接会产出非法 JSON。
|
| 857 |
+
cfgJSON, err := json.Marshal(map[string]any{"prompt": map[string]any{"mode": "custom", "file": pf}})
|
| 858 |
+
if err != nil {
|
| 859 |
+
t.Fatal(err)
|
| 860 |
+
}
|
| 861 |
+
os.WriteFile(cf, cfgJSON, 0o600)
|
| 862 |
+
c, err := Load(cf)
|
| 863 |
+
if err != nil {
|
| 864 |
+
t.Fatal(err)
|
| 865 |
+
}
|
| 866 |
+
if c.PromptText != want {
|
| 867 |
+
t.Errorf("PromptText=%q want %q", c.PromptText, want)
|
| 868 |
+
}
|
| 869 |
+
}
|
| 870 |
+
|
| 871 |
+
// TestPromptEnvOverride env 覆盖 prompt.mode 与 prompt.file。
|
| 872 |
+
func TestPromptEnvOverride(t *testing.T) {
|
| 873 |
+
t.Setenv("WB2A_PROMPT_MODE", "passthrough")
|
| 874 |
+
c, err := Load("")
|
| 875 |
+
if err != nil {
|
| 876 |
+
t.Fatal(err)
|
| 877 |
+
}
|
| 878 |
+
if c.Prompt.Mode != "passthrough" {
|
| 879 |
+
t.Errorf("mode=%q want passthrough", c.Prompt.Mode)
|
| 880 |
+
}
|
| 881 |
+
}
|
| 882 |
+
|
| 883 |
+
// TestPromptLegacyConfigNoImpact 旧 config(无 prompt 段)零影响:mode 缺省 passthrough。
|
| 884 |
+
func TestPromptLegacyConfigNoImpact(t *testing.T) {
|
| 885 |
+
dir := t.TempDir()
|
| 886 |
+
fp := filepath.Join(dir, "c.json")
|
| 887 |
+
os.WriteFile(fp, []byte(`{"listen":":9999","api_key":"k"}`), 0o600)
|
| 888 |
+
c, err := Load(fp)
|
| 889 |
+
if err != nil {
|
| 890 |
+
t.Fatal(err)
|
| 891 |
+
}
|
| 892 |
+
if c.Prompt.Mode != "passthrough" {
|
| 893 |
+
t.Errorf("legacy config should default to passthrough, got %q", c.Prompt.Mode)
|
| 894 |
+
}
|
| 895 |
+
if c.Listen != ":9999" {
|
| 896 |
+
t.Errorf("listen=%q", c.Listen)
|
| 897 |
+
}
|
| 898 |
+
}
|
| 899 |
+
|
| 900 |
+
// TestUpstreamUserAgentConfig 配置 upstream.user_agent 与 env WB2A_USER_AGENT 均生效,
|
| 901 |
+
// 缺省空串保持现状(headers 层回落到 clientUA)。
|
| 902 |
+
func TestUpstreamUserAgentConfig(t *testing.T) {
|
| 903 |
+
// JSON 配置
|
| 904 |
+
dir := t.TempDir()
|
| 905 |
+
fp := filepath.Join(dir, "c.json")
|
| 906 |
+
os.WriteFile(fp, []byte(`{"upstream":{"user_agent":"WorkBuddy/1.2.3"}}`), 0o600)
|
| 907 |
+
c, err := Load(fp)
|
| 908 |
+
if err != nil {
|
| 909 |
+
t.Fatal(err)
|
| 910 |
+
}
|
| 911 |
+
if c.Upstream.UserAgent != "WorkBuddy/1.2.3" {
|
| 912 |
+
t.Errorf("user_agent=%q want WorkBuddy/1.2.3", c.Upstream.UserAgent)
|
| 913 |
+
}
|
| 914 |
+
// 缺省为空
|
| 915 |
+
if c2, err := Load(""); err != nil || c2.Upstream.UserAgent != "" {
|
| 916 |
+
t.Errorf("default user_agent=%q want empty (err=%v)", c2.Upstream.UserAgent, err)
|
| 917 |
+
}
|
| 918 |
+
// env 覆盖
|
| 919 |
+
t.Setenv("WB2A_USER_AGENT", "EnvAgent/9")
|
| 920 |
+
c3, err := Load("")
|
| 921 |
+
if err != nil {
|
| 922 |
+
t.Fatal(err)
|
| 923 |
+
}
|
| 924 |
+
if c3.Upstream.UserAgent != "EnvAgent/9" {
|
| 925 |
+
t.Errorf("env user_agent=%q want EnvAgent/9", c3.Upstream.UserAgent)
|
| 926 |
+
}
|
| 927 |
+
}
|
| 928 |
+
|
| 929 |
+
// TestLoadConfigPathIsDirectory config 路径是目录时给出可操作提示(Docker bind mount 陷阱)。
|
| 930 |
+
// 复现:compose 挂载 ./config.json 但宿主机缺该文件 → Docker 创建同名目录 → 启动失败。
|
| 931 |
+
// 旧行为只报 "read config: ... Incorrect function" 之类晦涩错误,无从排查。
|
| 932 |
+
func TestLoadConfigPathIsDirectory(t *testing.T) {
|
| 933 |
+
dir := t.TempDir()
|
| 934 |
+
asDir := filepath.Join(dir, "config.json")
|
| 935 |
+
if err := os.Mkdir(asDir, 0o755); err != nil {
|
| 936 |
+
t.Fatal(err)
|
| 937 |
+
}
|
| 938 |
+
_, err := Load(asDir)
|
| 939 |
+
if err == nil {
|
| 940 |
+
t.Fatal("want error when config path is a directory")
|
| 941 |
+
}
|
| 942 |
+
msg := err.Error()
|
| 943 |
+
if !strings.Contains(msg, "是目录") {
|
| 944 |
+
t.Errorf("error should explain it is a directory: %v", err)
|
| 945 |
+
}
|
| 946 |
+
if !strings.Contains(msg, "config.example.json") {
|
| 947 |
+
t.Errorf("error should suggest the fix (cp config.example.json): %v", err)
|
| 948 |
+
}
|
| 949 |
+
}
|
| 950 |
+
|
| 951 |
+
// TestReserveCreditsDefaultAndOff 保留积分默认值语义:
|
| 952 |
+
// 键缺席 → 10(默认留一线);显式 0 → 关闭;显式值 → 原样。
|
| 953 |
+
func TestReserveCreditsDefaultAndOff(t *testing.T) {
|
| 954 |
+
dir := t.TempDir()
|
| 955 |
+
load := func(t *testing.T, body string) *int64 {
|
| 956 |
+
t.Helper()
|
| 957 |
+
fp := filepath.Join(dir, strings.ReplaceAll(t.Name(), "/", "_")+".json")
|
| 958 |
+
if err := os.WriteFile(fp, []byte(body), 0o600); err != nil {
|
| 959 |
+
t.Fatal(err)
|
| 960 |
+
}
|
| 961 |
+
c, err := Load(fp)
|
| 962 |
+
if err != nil {
|
| 963 |
+
t.Fatalf("load: %v", err)
|
| 964 |
+
}
|
| 965 |
+
return c.Pool.ReserveCredits
|
| 966 |
+
}
|
| 967 |
+
if v := load(t, `{}`); v == nil || *v != 10 {
|
| 968 |
+
t.Errorf("键缺席 reserve_credits=%v want 10(默认)", v)
|
| 969 |
+
}
|
| 970 |
+
if v := load(t, `{"pool":{"reserve_credits":0}}`); v == nil || *v != 0 {
|
| 971 |
+
t.Errorf("显式 0 reserve_credits=%v want 0(关闭���", v)
|
| 972 |
+
}
|
| 973 |
+
if v := load(t, `{"pool":{"reserve_credits":5000}}`); v == nil || *v != 5000 {
|
| 974 |
+
t.Errorf("显式值 reserve_credits=%v want 5000", v)
|
| 975 |
+
}
|
| 976 |
+
if v := load(t, `{"pool":{"reserve_credits":-5}}`); v == nil || *v != 0 {
|
| 977 |
+
t.Errorf("负值 reserve_credits=%v want 0(归零)", v)
|
| 978 |
+
}
|
| 979 |
+
}
|
| 980 |
+
|
| 981 |
+
// TestServerReadTimeout 入站读取上限(issue #100):空值回落默认 300s;
|
| 982 |
+
// "0" = 显式不限制(0 是合法值不回落);负值 fail fast(静默钳 0 会把保护悄悄关掉)。
|
| 983 |
+
func TestServerReadTimeout(t *testing.T) {
|
| 984 |
+
c := Default()
|
| 985 |
+
if c.Server.ReadTimeout != "300s" {
|
| 986 |
+
t.Errorf("default read_timeout=%q want 300s", c.Server.ReadTimeout)
|
| 987 |
+
}
|
| 988 |
+
if err := c.normalize(); err != nil {
|
| 989 |
+
t.Fatalf("normalize: %v", err)
|
| 990 |
+
}
|
| 991 |
+
if c.ServerReadTimeoutDur != 300*time.Second {
|
| 992 |
+
t.Errorf("default dur=%v want 300s", c.ServerReadTimeoutDur)
|
| 993 |
+
}
|
| 994 |
+
|
| 995 |
+
c = Default()
|
| 996 |
+
c.Server.ReadTimeout = "" // 显式清空 = 未配置 → 回落默认
|
| 997 |
+
if err := c.normalize(); err != nil {
|
| 998 |
+
t.Fatalf("normalize empty: %v", err)
|
| 999 |
+
}
|
| 1000 |
+
if c.ServerReadTimeoutDur != 300*time.Second {
|
| 1001 |
+
t.Errorf("empty dur=%v want 300s", c.ServerReadTimeoutDur)
|
| 1002 |
+
}
|
| 1003 |
+
|
| 1004 |
+
c = Default()
|
| 1005 |
+
c.Server.ReadTimeout = "0" // 显式 0 = 不限制(http.Server ReadTimeout 0 即无超时)
|
| 1006 |
+
if err := c.normalize(); err != nil {
|
| 1007 |
+
t.Fatalf("normalize zero: %v", err)
|
| 1008 |
+
}
|
| 1009 |
+
if c.ServerReadTimeoutDur != 0 {
|
| 1010 |
+
t.Errorf("zero dur=%v want 0", c.ServerReadTimeoutDur)
|
| 1011 |
+
}
|
| 1012 |
+
|
| 1013 |
+
c = Default()
|
| 1014 |
+
c.Server.ReadTimeout = "-5s"
|
| 1015 |
+
if err := c.normalize(); err == nil {
|
| 1016 |
+
t.Error("negative read_timeout should fail fast")
|
| 1017 |
+
}
|
| 1018 |
+
|
| 1019 |
+
c = Default()
|
| 1020 |
+
c.Server.ReadTimeout = "bogus"
|
| 1021 |
+
if err := c.normalize(); err == nil {
|
| 1022 |
+
t.Error("unparsable read_timeout should fail fast")
|
| 1023 |
+
}
|
| 1024 |
+
}
|
| 1025 |
+
|
| 1026 |
+
// TestDNSServersConfigAndEnv dns_servers 两种来源:配置文件数组原样保留;
|
| 1027 |
+
// WB2A_DNS 逗号分隔覆盖(去空白、丢空项)。空 = 系统解析器,不得塞空串进去。
|
| 1028 |
+
func TestDNSServersConfigAndEnv(t *testing.T) {
|
| 1029 |
+
c, err := ParseConfig([]byte(`{"dns_servers":["223.5.5.5","1.1.1.1:5353"]}`))
|
| 1030 |
+
if err != nil {
|
| 1031 |
+
t.Fatal(err)
|
| 1032 |
+
}
|
| 1033 |
+
if got := strings.Join(c.DNSServers, ","); got != "223.5.5.5,1.1.1.1:5353" {
|
| 1034 |
+
t.Fatalf("文件配置 dns_servers=%v", c.DNSServers)
|
| 1035 |
+
}
|
| 1036 |
+
|
| 1037 |
+
t.Setenv("WB2A_DNS", " 119.29.29.29 , ,8.8.8.8")
|
| 1038 |
+
c2, err := Load("")
|
| 1039 |
+
if err != nil {
|
| 1040 |
+
t.Fatal(err)
|
| 1041 |
+
}
|
| 1042 |
+
if got := strings.Join(c2.DNSServers, ","); got != "119.29.29.29,8.8.8.8" {
|
| 1043 |
+
t.Fatalf("WB2A_DNS 覆盖结果=%v", c2.DNSServers)
|
| 1044 |
+
}
|
| 1045 |
+
|
| 1046 |
+
// 面板/环境变量管理的字段清单要认它,否则面板会让人以为改了配置能生效。
|
| 1047 |
+
managed := c2.EnvironmentManagedFields()
|
| 1048 |
+
found := false
|
| 1049 |
+
for _, f := range managed {
|
| 1050 |
+
if f == "dns_servers" {
|
| 1051 |
+
found = true
|
| 1052 |
+
}
|
| 1053 |
+
}
|
| 1054 |
+
if !found {
|
| 1055 |
+
t.Fatalf("dns_servers 应出现在环境变量管理字段里:%v", managed)
|
| 1056 |
+
}
|
| 1057 |
+
|
| 1058 |
+
c3, err := ParseConfig([]byte(`{}`))
|
| 1059 |
+
if err != nil {
|
| 1060 |
+
t.Fatal(err)
|
| 1061 |
+
}
|
| 1062 |
+
if len(c3.DNSServers) != 0 {
|
| 1063 |
+
t.Fatalf("缺省应为空(系统解析器):%v", c3.DNSServers)
|
| 1064 |
+
}
|
| 1065 |
+
}
|
| 1066 |
+
|
| 1067 |
+
func TestPeriodicJitterPermillConfig(t *testing.T) {
|
| 1068 |
+
dir := t.TempDir()
|
| 1069 |
+
fp := filepath.Join(dir, "c.json")
|
| 1070 |
+
os.WriteFile(fp, []byte(`{"listen":":9999","api_key":"k","schedule":{"balance_refresh_jitter_permill":200,"task_sweep_jitter_permill":300}}`), 0o600)
|
| 1071 |
+
c, err := Load(fp)
|
| 1072 |
+
if err != nil {
|
| 1073 |
+
t.Fatal(err)
|
| 1074 |
+
}
|
| 1075 |
+
if c.Schedule.BalanceRefreshJitterPermill != 200 || c.Schedule.TaskSweepJitterPermill != 300 {
|
| 1076 |
+
t.Fatalf("c.Schedule=%+v", c.Schedule)
|
| 1077 |
+
}
|
| 1078 |
+
|
| 1079 |
+
// 超上限拒绝(上限 500 = 50%)。
|
| 1080 |
+
os.WriteFile(fp, []byte(`{"listen":":9999","api_key":"k","schedule":{"balance_refresh_jitter_permill":501}}`), 0o600)
|
| 1081 |
+
if _, err := Load(fp); err == nil {
|
| 1082 |
+
t.Fatal("want error for jitter_permill > 500")
|
| 1083 |
+
}
|
| 1084 |
+
|
| 1085 |
+
// 负数拒绝。
|
| 1086 |
+
os.WriteFile(fp, []byte(`{"listen":":9999","api_key":"k","schedule":{"task_sweep_jitter_permill":-1}}`), 0o600)
|
| 1087 |
+
if _, err := Load(fp); err == nil {
|
| 1088 |
+
t.Fatal("want error for negative jitter_permill")
|
| 1089 |
+
}
|
| 1090 |
+
|
| 1091 |
+
// env 覆盖。
|
| 1092 |
+
t.Setenv("WB2A_SCHEDULE_BALANCE_REFRESH_JITTER_PERMILL", "250")
|
| 1093 |
+
t.Setenv("WB2A_SCHEDULE_TASK_SWEEP_JITTER_PERMILL", "100")
|
| 1094 |
+
c2, err := Load("")
|
| 1095 |
+
if err != nil {
|
| 1096 |
+
t.Fatal(err)
|
| 1097 |
+
}
|
| 1098 |
+
if c2.Schedule.BalanceRefreshJitterPermill != 250 || c2.Schedule.TaskSweepJitterPermill != 100 {
|
| 1099 |
+
t.Fatalf("env override: %+v", c2.Schedule)
|
| 1100 |
+
}
|
| 1101 |
+
}
|
| 1102 |
+
|
| 1103 |
+
func TestThinkingDefaults(t *testing.T) {
|
| 1104 |
+
c := Default()
|
| 1105 |
+
if !c.Thinking.Enabled {
|
| 1106 |
+
t.Error("thinking.enabled default should be true")
|
| 1107 |
+
}
|
| 1108 |
+
// 缺省 high(upstream.DefaultGatewayEffort),不是 max:思考与正文共用一份输出
|
| 1109 |
+
// 额度,max 会把预算烧在思考上、正文只剩半句。
|
| 1110 |
+
if c.Thinking.DefaultEffort != upstream.DefaultGatewayEffort {
|
| 1111 |
+
t.Errorf("thinking.default_effort=%q want %q", c.Thinking.DefaultEffort, upstream.DefaultGatewayEffort)
|
| 1112 |
+
}
|
| 1113 |
+
if !c.Thinking.ClientPriority {
|
| 1114 |
+
t.Error("thinking.client_priority default should be true")
|
| 1115 |
+
}
|
| 1116 |
+
if c.Thinking.OverrideScope != "level" {
|
| 1117 |
+
t.Errorf("thinking.override_scope=%q want level", c.Thinking.OverrideScope)
|
| 1118 |
+
}
|
| 1119 |
+
}
|
| 1120 |
+
|
| 1121 |
+
func TestThinkingRejectsInvalid(t *testing.T) {
|
| 1122 |
+
for _, raw := range []string{
|
| 1123 |
+
`{"thinking":{"default_effort":"turbo"}}`,
|
| 1124 |
+
`{"thinking":{"default_effort":"off"}}`,
|
| 1125 |
+
`{"thinking":{"override_scope":"everything"}}`,
|
| 1126 |
+
`{"thinking":{"model_defaults":{"glm-5.2":"ultra"}}}`,
|
| 1127 |
+
} {
|
| 1128 |
+
if _, err := ParseConfig([]byte(raw)); err == nil {
|
| 1129 |
+
t.Fatalf("%s should be rejected", raw)
|
| 1130 |
+
}
|
| 1131 |
+
}
|
| 1132 |
+
}
|
| 1133 |
+
|
| 1134 |
+
func TestThinkingNormalize(t *testing.T) {
|
| 1135 |
+
c, err := ParseConfig([]byte(`{"thinking":{"default_effort":" HIGH ","override_scope":"ALL",` +
|
| 1136 |
+
`"model_defaults":{" glm-5.2 ":"Max","legacy":"inherit","":"high","blank":" ","glm-5.3":"Off"}}}`))
|
| 1137 |
+
if err != nil {
|
| 1138 |
+
t.Fatalf("parse: %v", err)
|
| 1139 |
+
}
|
| 1140 |
+
if c.Thinking.DefaultEffort != "high" {
|
| 1141 |
+
t.Errorf("default_effort=%q want high", c.Thinking.DefaultEffort)
|
| 1142 |
+
}
|
| 1143 |
+
if c.Thinking.OverrideScope != "all" {
|
| 1144 |
+
t.Errorf("override_scope=%q want all", c.Thinking.OverrideScope)
|
| 1145 |
+
}
|
| 1146 |
+
if got := c.Thinking.ModelDefaults; len(got) != 2 || got["glm-5.2"] != "max" || got["glm-5.3"] != "off" {
|
| 1147 |
+
t.Fatalf("model_defaults=%v(inherit/空键/空值应被剔除,off 是合法的按模型关闭)", got)
|
| 1148 |
+
}
|
| 1149 |
+
}
|
| 1150 |
+
|
| 1151 |
+
func TestThinkingEnvOverride(t *testing.T) {
|
| 1152 |
+
t.Setenv("WB2A_THINKING_ENABLED", "false")
|
| 1153 |
+
t.Setenv("WB2A_THINKING_DEFAULT_EFFORT", "xhigh")
|
| 1154 |
+
t.Setenv("WB2A_THINKING_CLIENT_PRIORITY", "false")
|
| 1155 |
+
t.Setenv("WB2A_THINKING_OVERRIDE_SCOPE", "all")
|
| 1156 |
+
c := Default()
|
| 1157 |
+
applyEnv(c)
|
| 1158 |
+
if err := c.normalize(); err != nil {
|
| 1159 |
+
t.Fatalf("normalize: %v", err)
|
| 1160 |
+
}
|
| 1161 |
+
if c.Thinking.Enabled || c.Thinking.ClientPriority {
|
| 1162 |
+
t.Fatalf("bool env override failed: %+v", c.Thinking)
|
| 1163 |
+
}
|
| 1164 |
+
if c.Thinking.DefaultEffort != "xhigh" || c.Thinking.OverrideScope != "all" {
|
| 1165 |
+
t.Fatalf("string env override failed: %+v", c.Thinking)
|
| 1166 |
+
}
|
| 1167 |
+
if fields := c.EnvironmentManagedFields(); len(fields) == 0 {
|
| 1168 |
+
t.Error("thinking env vars should be reported as managed")
|
| 1169 |
+
}
|
| 1170 |
+
}
|
| 1171 |
+
|
| 1172 |
+
func TestConfigExampleParses(t *testing.T) {
|
| 1173 |
+
raw, err := os.ReadFile(filepath.Join("..", "..", "config.example.json"))
|
| 1174 |
+
if err != nil {
|
| 1175 |
+
t.Fatalf("read example: %v", err)
|
| 1176 |
+
}
|
| 1177 |
+
var cfg Config
|
| 1178 |
+
if err := json.Unmarshal(raw, &cfg); err != nil {
|
| 1179 |
+
t.Fatalf("parse example: %v", err)
|
| 1180 |
+
}
|
| 1181 |
+
if err := cfg.normalizeThinking(); err != nil {
|
| 1182 |
+
t.Fatalf("normalize example thinking: %v", err)
|
| 1183 |
+
}
|
| 1184 |
+
// default_effort 期望 high 而不是 max:思考与正文共用一份输出额度,max 会把预算
|
| 1185 |
+
// 烧在思考上、正文只剩半句(实测 max 正文 1906 token vs high 3236 token)。
|
| 1186 |
+
// 与 hub 的 WB_DEFAULT_REASONING_EFFORT 默认值同口径(issue #508)。
|
| 1187 |
+
if !cfg.Thinking.Enabled || !cfg.Thinking.ClientPriority || cfg.Thinking.OverrideScope != "level" || cfg.Thinking.DefaultEffort != "high" {
|
| 1188 |
+
t.Fatalf("unexpected example thinking defaults: %+v", cfg.Thinking)
|
| 1189 |
+
}
|
| 1190 |
+
}
|
cmd/server/credit_floor_config_test.go
CHANGED
|
@@ -1,48 +1,48 @@
|
|
| 1 |
-
// credit_floor_config_test.go pool.credit_floor 配置测试:
|
| 2 |
-
// 默认 0(关闭,零回归)/ 文件覆盖 / 负值钳 0 / 大值合法。
|
| 3 |
-
package main
|
| 4 |
-
|
| 5 |
-
import (
|
| 6 |
-
"os"
|
| 7 |
-
"path/filepath"
|
| 8 |
-
"testing"
|
| 9 |
-
)
|
| 10 |
-
|
| 11 |
-
// TestCreditFloorDefault 键缺席 → 默认 0(保底关闭,行为与引入前一致)。
|
| 12 |
-
func TestCreditFloorDefault(t *testing.T) {
|
| 13 |
-
c := Default()
|
| 14 |
-
if err := c.normalize(); err != nil {
|
| 15 |
-
t.Fatalf("normalize: %v", err)
|
| 16 |
-
}
|
| 17 |
-
if c.Pool.CreditFloor != 0 {
|
| 18 |
-
t.Errorf("credit_floor=%d want 0 (default off)", c.Pool.CreditFloor)
|
| 19 |
-
}
|
| 20 |
-
}
|
| 21 |
-
|
| 22 |
-
// TestCreditFloorParsedFromFile 显式配置覆盖默认。
|
| 23 |
-
func TestCreditFloorParsedFromFile(t *testing.T) {
|
| 24 |
-
dir := t.TempDir()
|
| 25 |
-
fp := filepath.Join(dir, "c.json")
|
| 26 |
-
os.WriteFile(fp, []byte(`{"pool":{"credit_floor":100}}`), 0o600)
|
| 27 |
-
c, err := Load(fp)
|
| 28 |
-
if err != nil {
|
| 29 |
-
t.Fatal(err)
|
| 30 |
-
}
|
| 31 |
-
if c.Pool.CreditFloor != 100 {
|
| 32 |
-
t.Errorf("credit_floor=%d want 100", c.Pool.CreditFloor)
|
| 33 |
-
}
|
| 34 |
-
}
|
| 35 |
-
|
| 36 |
-
// TestCreditFloorNegativeClamped 负值钳 0(非法即关闭,不报错:老配置误写不炸启动)。
|
| 37 |
-
func TestCreditFloorNegativeClamped(t *testing.T) {
|
| 38 |
-
dir := t.TempDir()
|
| 39 |
-
fp := filepath.Join(dir, "c.json")
|
| 40 |
-
os.WriteFile(fp, []byte(`{"pool":{"credit_floor":-5}}`), 0o600)
|
| 41 |
-
c, err := Load(fp)
|
| 42 |
-
if err != nil {
|
| 43 |
-
t.Fatal(err)
|
| 44 |
-
}
|
| 45 |
-
if c.Pool.CreditFloor != 0 {
|
| 46 |
-
t.Errorf("credit_floor=%d want 0 (negative clamped)", c.Pool.CreditFloor)
|
| 47 |
-
}
|
| 48 |
-
}
|
|
|
|
| 1 |
+
// credit_floor_config_test.go pool.credit_floor 配置测试:
|
| 2 |
+
// 默认 0(关闭,零回归)/ 文件覆盖 / 负值钳 0 / 大值合法。
|
| 3 |
+
package main
|
| 4 |
+
|
| 5 |
+
import (
|
| 6 |
+
"os"
|
| 7 |
+
"path/filepath"
|
| 8 |
+
"testing"
|
| 9 |
+
)
|
| 10 |
+
|
| 11 |
+
// TestCreditFloorDefault 键缺席 → 默认 0(保底关闭,行为与引入前一致)。
|
| 12 |
+
func TestCreditFloorDefault(t *testing.T) {
|
| 13 |
+
c := Default()
|
| 14 |
+
if err := c.normalize(); err != nil {
|
| 15 |
+
t.Fatalf("normalize: %v", err)
|
| 16 |
+
}
|
| 17 |
+
if c.Pool.CreditFloor != 0 {
|
| 18 |
+
t.Errorf("credit_floor=%d want 0 (default off)", c.Pool.CreditFloor)
|
| 19 |
+
}
|
| 20 |
+
}
|
| 21 |
+
|
| 22 |
+
// TestCreditFloorParsedFromFile 显式配置覆盖默认。
|
| 23 |
+
func TestCreditFloorParsedFromFile(t *testing.T) {
|
| 24 |
+
dir := t.TempDir()
|
| 25 |
+
fp := filepath.Join(dir, "c.json")
|
| 26 |
+
os.WriteFile(fp, []byte(`{"pool":{"credit_floor":100}}`), 0o600)
|
| 27 |
+
c, err := Load(fp)
|
| 28 |
+
if err != nil {
|
| 29 |
+
t.Fatal(err)
|
| 30 |
+
}
|
| 31 |
+
if c.Pool.CreditFloor != 100 {
|
| 32 |
+
t.Errorf("credit_floor=%d want 100", c.Pool.CreditFloor)
|
| 33 |
+
}
|
| 34 |
+
}
|
| 35 |
+
|
| 36 |
+
// TestCreditFloorNegativeClamped 负值钳 0(非法即关闭,不报错:老配置误写不炸启动)。
|
| 37 |
+
func TestCreditFloorNegativeClamped(t *testing.T) {
|
| 38 |
+
dir := t.TempDir()
|
| 39 |
+
fp := filepath.Join(dir, "c.json")
|
| 40 |
+
os.WriteFile(fp, []byte(`{"pool":{"credit_floor":-5}}`), 0o600)
|
| 41 |
+
c, err := Load(fp)
|
| 42 |
+
if err != nil {
|
| 43 |
+
t.Fatal(err)
|
| 44 |
+
}
|
| 45 |
+
if c.Pool.CreditFloor != 0 {
|
| 46 |
+
t.Errorf("credit_floor=%d want 0 (negative clamped)", c.Pool.CreditFloor)
|
| 47 |
+
}
|
| 48 |
+
}
|
cmd/server/insecure_key_test.go
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
package main
|
| 2 |
+
|
| 3 |
+
import "testing"
|
| 4 |
+
|
| 5 |
+
// TestInsecureKeyWarning 空 api_key(完全不鉴权)与样例占位符 test_key 叠加
|
| 6 |
+
// 非回环监听时的启动告警;强 key 或只听回环不告警。
|
| 7 |
+
func TestInsecureKeyWarning(t *testing.T) {
|
| 8 |
+
cases := []struct {
|
| 9 |
+
listen, apiKey string
|
| 10 |
+
want bool
|
| 11 |
+
}{
|
| 12 |
+
{":7863", "", true}, // 缺省监听绑所有网卡 + 不鉴权
|
| 13 |
+
{":7863", "test_key", true}, // 照抄样例占位符
|
| 14 |
+
{"0.0.0.0:7863", "", true}, // 显式全网卡
|
| 15 |
+
{"192.168.1.5:7863", "test_key", true}, // 具体内网地址
|
| 16 |
+
{"127.0.0.1:7863", "", false}, // 只听回环
|
| 17 |
+
{"[::1]:7863", "", false}, // IPv6 回环
|
| 18 |
+
{"localhost:7863", "", false}, // localhost
|
| 19 |
+
{":7863", "strong-key-xyz", false}, // 有有效 key
|
| 20 |
+
}
|
| 21 |
+
for _, c := range cases {
|
| 22 |
+
got := insecureKeyWarning(c.listen, c.apiKey)
|
| 23 |
+
if (got != "") != c.want {
|
| 24 |
+
t.Errorf("insecureKeyWarning(%q, %q) = %q, want 告警=%v", c.listen, redact(c.apiKey), got, c.want)
|
| 25 |
+
}
|
| 26 |
+
}
|
| 27 |
+
}
|
| 28 |
+
|
| 29 |
+
func redact(key string) string {
|
| 30 |
+
if key == "" {
|
| 31 |
+
return "<empty>"
|
| 32 |
+
}
|
| 33 |
+
return "<set>"
|
| 34 |
+
}
|
cmd/server/main.go
CHANGED
|
@@ -1,563 +1,1124 @@
|
|
| 1 |
-
// main.go workbuddy2api 入口:加载配置、构建 pool、起调度器与 HTTP 服务。
|
| 2 |
-
package main
|
| 3 |
-
|
| 4 |
-
import (
|
| 5 |
-
"context"
|
| 6 |
-
"encoding/json"
|
| 7 |
-
"errors"
|
| 8 |
-
"flag"
|
| 9 |
-
"fmt"
|
| 10 |
-
"io"
|
| 11 |
-
"io/fs"
|
| 12 |
-
"log"
|
| 13 |
-
"net
|
| 14 |
-
"
|
| 15 |
-
"
|
| 16 |
-
"
|
| 17 |
-
"
|
| 18 |
-
"
|
| 19 |
-
|
| 20 |
-
"
|
| 21 |
-
"
|
| 22 |
-
"
|
| 23 |
-
"
|
| 24 |
-
|
| 25 |
-
"github.com/
|
| 26 |
-
"github.com/
|
| 27 |
-
"github.com/
|
| 28 |
-
"github.com/
|
| 29 |
-
"github.com/
|
| 30 |
-
"github.com/
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
//
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
//
|
| 37 |
-
//
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
//
|
| 41 |
-
//
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
}
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
}
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
}
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
|
| 134 |
-
|
| 135 |
-
|
| 136 |
-
|
| 137 |
-
|
| 138 |
-
//
|
| 139 |
-
//
|
| 140 |
-
|
| 141 |
-
|
| 142 |
-
|
| 143 |
-
|
| 144 |
-
|
| 145 |
-
|
| 146 |
-
|
| 147 |
-
|
| 148 |
-
|
| 149 |
-
//
|
| 150 |
-
|
| 151 |
-
|
| 152 |
-
//
|
| 153 |
-
|
| 154 |
-
//
|
| 155 |
-
|
| 156 |
-
|
| 157 |
-
|
| 158 |
-
|
| 159 |
-
|
| 160 |
-
|
| 161 |
-
|
| 162 |
-
|
| 163 |
-
//
|
| 164 |
-
|
| 165 |
-
|
| 166 |
-
|
| 167 |
-
|
| 168 |
-
//
|
| 169 |
-
|
| 170 |
-
|
| 171 |
-
|
| 172 |
-
|
| 173 |
-
|
| 174 |
-
|
| 175 |
-
|
| 176 |
-
|
| 177 |
-
|
| 178 |
-
|
| 179 |
-
|
| 180 |
-
|
| 181 |
-
|
| 182 |
-
|
| 183 |
-
|
| 184 |
-
|
| 185 |
-
|
| 186 |
-
|
| 187 |
-
|
| 188 |
-
|
| 189 |
-
|
| 190 |
-
|
| 191 |
-
|
| 192 |
-
|
| 193 |
-
|
| 194 |
-
|
| 195 |
-
|
| 196 |
-
|
| 197 |
-
|
| 198 |
-
|
| 199 |
-
|
| 200 |
-
|
| 201 |
-
|
| 202 |
-
|
| 203 |
-
log.Printf("
|
| 204 |
-
|
| 205 |
-
|
| 206 |
-
|
| 207 |
-
|
| 208 |
-
|
| 209 |
-
|
| 210 |
-
|
| 211 |
-
|
| 212 |
-
|
| 213 |
-
|
| 214 |
-
|
| 215 |
-
|
| 216 |
-
|
| 217 |
-
|
| 218 |
-
|
| 219 |
-
|
| 220 |
-
|
| 221 |
-
|
| 222 |
-
|
| 223 |
-
|
| 224 |
-
|
| 225 |
-
|
| 226 |
-
|
| 227 |
-
|
| 228 |
-
if
|
| 229 |
-
|
| 230 |
-
}
|
| 231 |
-
|
| 232 |
-
|
| 233 |
-
|
| 234 |
-
|
| 235 |
-
|
| 236 |
-
|
| 237 |
-
|
| 238 |
-
|
| 239 |
-
|
| 240 |
-
|
| 241 |
-
|
| 242 |
-
|
| 243 |
-
|
| 244 |
-
|
| 245 |
-
|
| 246 |
-
|
| 247 |
-
|
| 248 |
-
|
| 249 |
-
|
| 250 |
-
|
| 251 |
-
|
| 252 |
-
|
| 253 |
-
|
| 254 |
-
|
| 255 |
-
|
| 256 |
-
|
| 257 |
-
|
| 258 |
-
|
| 259 |
-
|
| 260 |
-
|
| 261 |
-
|
| 262 |
-
|
| 263 |
-
|
| 264 |
-
|
| 265 |
-
|
| 266 |
-
|
| 267 |
-
|
| 268 |
-
|
| 269 |
-
|
| 270 |
-
|
| 271 |
-
|
| 272 |
-
|
| 273 |
-
|
| 274 |
-
|
| 275 |
-
|
| 276 |
-
|
| 277 |
-
|
| 278 |
-
|
| 279 |
-
|
| 280 |
-
|
| 281 |
-
|
| 282 |
-
|
| 283 |
-
|
| 284 |
-
|
| 285 |
-
|
| 286 |
-
|
| 287 |
-
|
| 288 |
-
//
|
| 289 |
-
|
| 290 |
-
|
| 291 |
-
|
| 292 |
-
|
| 293 |
-
|
| 294 |
-
|
| 295 |
-
|
| 296 |
-
|
| 297 |
-
|
| 298 |
-
|
| 299 |
-
|
| 300 |
-
|
| 301 |
-
|
| 302 |
-
|
| 303 |
-
|
| 304 |
-
|
| 305 |
-
|
| 306 |
-
|
| 307 |
-
|
| 308 |
-
|
| 309 |
-
//
|
| 310 |
-
|
| 311 |
-
|
| 312 |
-
|
| 313 |
-
|
| 314 |
-
|
| 315 |
-
|
| 316 |
-
|
| 317 |
-
|
| 318 |
-
|
| 319 |
-
|
| 320 |
-
|
| 321 |
-
|
| 322 |
-
|
| 323 |
-
|
| 324 |
-
|
| 325 |
-
|
| 326 |
-
|
| 327 |
-
|
| 328 |
-
|
| 329 |
-
|
| 330 |
-
|
| 331 |
-
|
| 332 |
-
|
| 333 |
-
|
| 334 |
-
|
| 335 |
-
|
| 336 |
-
|
| 337 |
-
|
| 338 |
-
|
| 339 |
-
|
| 340 |
-
|
| 341 |
-
|
| 342 |
-
|
| 343 |
-
|
| 344 |
-
|
| 345 |
-
|
| 346 |
-
|
| 347 |
-
|
| 348 |
-
|
| 349 |
-
|
| 350 |
-
|
| 351 |
-
|
| 352 |
-
|
| 353 |
-
log.
|
| 354 |
-
|
| 355 |
-
|
| 356 |
-
|
| 357 |
-
|
| 358 |
-
|
| 359 |
-
|
| 360 |
-
|
| 361 |
-
|
| 362 |
-
|
| 363 |
-
|
| 364 |
-
|
| 365 |
-
|
| 366 |
-
|
| 367 |
-
|
| 368 |
-
|
| 369 |
-
|
| 370 |
-
|
| 371 |
-
|
| 372 |
-
|
| 373 |
-
|
| 374 |
-
|
| 375 |
-
|
| 376 |
-
|
| 377 |
-
|
| 378 |
-
|
| 379 |
-
|
| 380 |
-
|
| 381 |
-
|
| 382 |
-
|
| 383 |
-
|
| 384 |
-
|
| 385 |
-
|
| 386 |
-
|
| 387 |
-
|
| 388 |
-
|
| 389 |
-
|
| 390 |
-
|
| 391 |
-
|
| 392 |
-
|
| 393 |
-
|
| 394 |
-
|
| 395 |
-
|
| 396 |
-
|
| 397 |
-
|
| 398 |
-
|
| 399 |
-
|
| 400 |
-
|
| 401 |
-
|
| 402 |
-
|
| 403 |
-
|
| 404 |
-
|
| 405 |
-
|
| 406 |
-
|
| 407 |
-
|
| 408 |
-
|
| 409 |
-
|
| 410 |
-
|
| 411 |
-
|
| 412 |
-
|
| 413 |
-
|
| 414 |
-
|
| 415 |
-
//
|
| 416 |
-
//
|
| 417 |
-
|
| 418 |
-
|
| 419 |
-
|
| 420 |
-
|
| 421 |
-
|
| 422 |
-
|
| 423 |
-
//
|
| 424 |
-
|
| 425 |
-
|
| 426 |
-
|
| 427 |
-
|
| 428 |
-
|
| 429 |
-
|
| 430 |
-
|
| 431 |
-
|
| 432 |
-
if
|
| 433 |
-
|
| 434 |
-
|
| 435 |
-
|
| 436 |
-
|
| 437 |
-
|
| 438 |
-
|
| 439 |
-
|
| 440 |
-
|
| 441 |
-
|
| 442 |
-
|
| 443 |
-
//
|
| 444 |
-
|
| 445 |
-
|
| 446 |
-
|
| 447 |
-
|
| 448 |
-
|
| 449 |
-
|
| 450 |
-
|
| 451 |
-
|
| 452 |
-
|
| 453 |
-
|
| 454 |
-
|
| 455 |
-
|
| 456 |
-
|
| 457 |
-
|
| 458 |
-
|
| 459 |
-
|
| 460 |
-
|
| 461 |
-
|
| 462 |
-
|
| 463 |
-
|
| 464 |
-
|
| 465 |
-
|
| 466 |
-
|
| 467 |
-
|
| 468 |
-
|
| 469 |
-
|
| 470 |
-
|
| 471 |
-
|
| 472 |
-
|
| 473 |
-
|
| 474 |
-
|
| 475 |
-
|
| 476 |
-
|
| 477 |
-
|
| 478 |
-
|
| 479 |
-
|
| 480 |
-
|
| 481 |
-
|
| 482 |
-
|
| 483 |
-
|
| 484 |
-
|
| 485 |
-
|
| 486 |
-
|
| 487 |
-
|
| 488 |
-
|
| 489 |
-
|
| 490 |
-
|
| 491 |
-
|
| 492 |
-
|
| 493 |
-
|
| 494 |
-
|
| 495 |
-
|
| 496 |
-
|
| 497 |
-
|
| 498 |
-
|
| 499 |
-
|
| 500 |
-
|
| 501 |
-
|
| 502 |
-
|
| 503 |
-
|
| 504 |
-
|
| 505 |
-
|
| 506 |
-
|
| 507 |
-
|
| 508 |
-
|
| 509 |
-
|
| 510 |
-
|
| 511 |
-
|
| 512 |
-
//
|
| 513 |
-
|
| 514 |
-
|
| 515 |
-
|
| 516 |
-
//
|
| 517 |
-
|
| 518 |
-
|
| 519 |
-
|
| 520 |
-
if
|
| 521 |
-
|
| 522 |
-
|
| 523 |
-
|
| 524 |
-
|
| 525 |
-
|
| 526 |
-
|
| 527 |
-
|
| 528 |
-
|
| 529 |
-
|
| 530 |
-
|
| 531 |
-
|
| 532 |
-
|
| 533 |
-
}
|
| 534 |
-
|
| 535 |
-
|
| 536 |
-
|
| 537 |
-
|
| 538 |
-
}
|
| 539 |
-
|
| 540 |
-
|
| 541 |
-
|
| 542 |
-
//
|
| 543 |
-
|
| 544 |
-
|
| 545 |
-
|
| 546 |
-
|
| 547 |
-
|
| 548 |
-
|
| 549 |
-
|
| 550 |
-
|
| 551 |
-
|
| 552 |
-
|
| 553 |
-
|
| 554 |
-
|
| 555 |
-
|
| 556 |
-
|
| 557 |
-
|
| 558 |
-
|
| 559 |
-
|
| 560 |
-
|
| 561 |
-
|
| 562 |
-
|
| 563 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
// main.go workbuddy2api 入口:加载配置、构建 pool、起调度器与 HTTP 服务。
|
| 2 |
+
package main
|
| 3 |
+
|
| 4 |
+
import (
|
| 5 |
+
"context"
|
| 6 |
+
"encoding/json"
|
| 7 |
+
"errors"
|
| 8 |
+
"flag"
|
| 9 |
+
"fmt"
|
| 10 |
+
"io"
|
| 11 |
+
"io/fs"
|
| 12 |
+
"log"
|
| 13 |
+
"net"
|
| 14 |
+
"net/http"
|
| 15 |
+
_ "net/http/pprof" // WB2API_PPROF 打开时提供 /debug/pprof(默认无监听)
|
| 16 |
+
"os"
|
| 17 |
+
"os/signal"
|
| 18 |
+
"path/filepath"
|
| 19 |
+
"reflect"
|
| 20 |
+
"strings"
|
| 21 |
+
"sync"
|
| 22 |
+
"syscall"
|
| 23 |
+
"time"
|
| 24 |
+
|
| 25 |
+
"github.com/misakano7545/workbuddy2api-panel/internal/alert"
|
| 26 |
+
"github.com/misakano7545/workbuddy2api-panel/internal/auth"
|
| 27 |
+
"github.com/misakano7545/workbuddy2api-panel/internal/balance"
|
| 28 |
+
"github.com/misakano7545/workbuddy2api-panel/internal/credithist"
|
| 29 |
+
"github.com/misakano7545/workbuddy2api-panel/internal/extstore"
|
| 30 |
+
"github.com/misakano7545/workbuddy2api-panel/internal/freemodel"
|
| 31 |
+
"github.com/misakano7545/workbuddy2api-panel/internal/livecfg"
|
| 32 |
+
"github.com/misakano7545/workbuddy2api-panel/internal/panel"
|
| 33 |
+
"github.com/misakano7545/workbuddy2api-panel/internal/pool"
|
| 34 |
+
"github.com/misakano7545/workbuddy2api-panel/internal/proxypool"
|
| 35 |
+
"github.com/misakano7545/workbuddy2api-panel/internal/redisstore"
|
| 36 |
+
"github.com/misakano7545/workbuddy2api-panel/internal/reqlog"
|
| 37 |
+
"github.com/misakano7545/workbuddy2api-panel/internal/safefile"
|
| 38 |
+
"github.com/misakano7545/workbuddy2api-panel/internal/scheduler"
|
| 39 |
+
"github.com/misakano7545/workbuddy2api-panel/internal/server"
|
| 40 |
+
"github.com/misakano7545/workbuddy2api-panel/internal/session"
|
| 41 |
+
"github.com/misakano7545/workbuddy2api-panel/internal/updater"
|
| 42 |
+
"github.com/misakano7545/workbuddy2api-panel/internal/upstream"
|
| 43 |
+
"github.com/misakano7545/workbuddy2api-panel/internal/usage"
|
| 44 |
+
)
|
| 45 |
+
|
| 46 |
+
// appVersion 面板版本,透出到 /panel/api/overview。
|
| 47 |
+
// 本地构建保持 dev。发布构建由 CI 用 -X 注入上海时间(2026.9.26.711),不跟上游 1.x。
|
| 48 |
+
var appVersion = "dev"
|
| 49 |
+
var appRepository = "misakano7545/workbuddy2api-panel"
|
| 50 |
+
|
| 51 |
+
// insecureKeyWarning 空 api_key = 完全不鉴权(httpauth.VerifyBearer 对空 key 恒放
|
| 52 |
+
// 行),样例占位符 test_key = 人尽皆知的弱密钥;叠加非回环监听(显式配成
|
| 53 |
+
// "0.0.0.0:7863" 或 ":7863")等于把网关与面板 API 暴露给整个内网/公网。返回非空告警文本供启动日志
|
| 54 |
+
// 打印,安全状态返回空串。首启自动生成的随机 key 不会命中——这是给「照抄样例 /
|
| 55 |
+
// 显式清空」的最后提醒,不阻塞启动。
|
| 56 |
+
func insecureKeyWarning(listen, apiKey string) string {
|
| 57 |
+
if apiKey != "" && apiKey != "test_key" {
|
| 58 |
+
return ""
|
| 59 |
+
}
|
| 60 |
+
host, _, err := net.SplitHostPort(listen)
|
| 61 |
+
if err != nil {
|
| 62 |
+
host = listen // 非 host:port 形态:按具名地址保守处理(继续告警)
|
| 63 |
+
}
|
| 64 |
+
switch {
|
| 65 |
+
case host == "", host == "0.0.0.0", host == "::":
|
| 66 |
+
// 空 host = 所有网卡,维持告警
|
| 67 |
+
case host == "127.0.0.1", host == "::1", strings.EqualFold(host, "localhost"):
|
| 68 |
+
return "" // 只听回环:暴露面有限,不打扰
|
| 69 |
+
}
|
| 70 |
+
what := "为空(网关与面板完全不鉴权)"
|
| 71 |
+
if apiKey != "" {
|
| 72 |
+
what = "为样例占位符 test_key"
|
| 73 |
+
}
|
| 74 |
+
return fmt.Sprintf("api_key %s,且监听 %s 非回环地址——对外无有效鉴权,请尽快修改配置里的 api_key", what, listen)
|
| 75 |
+
}
|
| 76 |
+
|
| 77 |
+
// usagePathFor 由 state 文件路径推出用量文件路径:同目录、文件名 usage.json。
|
| 78 |
+
// 这样 config 里改 state_file 时用量数据跟着走,不需要额外配置项。
|
| 79 |
+
func usagePathFor(stateFile string) string { return stateSibling(stateFile, "usage.json") }
|
| 80 |
+
|
| 81 |
+
// stateSibling 返回与 state 文件同目录的指定文件名路径(相对路径场景回落当前目录)。
|
| 82 |
+
// usage.json(用量记录)与 output_probes.json(模型上限探测)共用本规则。
|
| 83 |
+
func stateSibling(stateFile, name string) string {
|
| 84 |
+
dir := filepath.Dir(stateFile)
|
| 85 |
+
if dir == "" || dir == "." {
|
| 86 |
+
return name
|
| 87 |
+
}
|
| 88 |
+
return filepath.Join(dir, name)
|
| 89 |
+
}
|
| 90 |
+
|
| 91 |
+
func main() {
|
| 92 |
+
if handled, err := updater.HandleSelfUpdate(os.Args); handled {
|
| 93 |
+
if err != nil {
|
| 94 |
+
log.Printf("[updater] %v", err)
|
| 95 |
+
os.Exit(1)
|
| 96 |
+
}
|
| 97 |
+
return
|
| 98 |
+
}
|
| 99 |
+
cfgPath := flag.String("config", "config.json", "配置文件路径(默认当前目录 config.json;不存在时自动生成推荐配置)")
|
| 100 |
+
flag.Parse()
|
| 101 |
+
// 实际生效的配置路径。必须在 flag.Parse() **之后**取值:flag.String 返回的指针
|
| 102 |
+
// 在 Parse 时才写入命令行值,此前取到的是默认值拷贝,-config 自定义路径时横幅
|
| 103 |
+
// 会报一份根本没读的文件。下面退回「默认+env」时清空,同理(issue #155)。
|
| 104 |
+
loadedFrom := *cfgPath
|
| 105 |
+
|
| 106 |
+
cfg, err := Load(*cfgPath)
|
| 107 |
+
if err != nil {
|
| 108 |
+
// errors.Is 才能看穿 Load 里 fmt.Errorf("%w") 的包装;os.IsNotExist 不行。
|
| 109 |
+
if errors.Is(err, fs.ErrNotExist) {
|
| 110 |
+
// 首次运行:目录下没有配置 → 自动落一份推荐配置(含随机 api_key)再加载。
|
| 111 |
+
// 双击 exe / 裸跑 docker 即开,无需先手工复制样例。
|
| 112 |
+
if key, werr := WriteDefault(*cfgPath); werr == nil {
|
| 113 |
+
log.Printf("config %s 不存在,已生成推荐配置(api_key=%s,记录在该文件里,可自行修改)", *cfgPath, key)
|
| 114 |
+
cfg, err = Load(*cfgPath)
|
| 115 |
+
}
|
| 116 |
+
if err != nil {
|
| 117 |
+
// 生成失败(目录只读等):退回纯默认 + env(旧行为兜底),不阻塞启动。
|
| 118 |
+
log.Printf("config %s not found (auto-generate failed), using defaults+env: %v", *cfgPath, err)
|
| 119 |
+
loadedFrom = ""
|
| 120 |
+
cfg, err = Load("")
|
| 121 |
+
}
|
| 122 |
+
}
|
| 123 |
+
if err != nil {
|
| 124 |
+
log.Fatalf("load config: %v", err)
|
| 125 |
+
}
|
| 126 |
+
}
|
| 127 |
+
|
| 128 |
+
auths, err := auth.LoadDir(cfg.AuthDir)
|
| 129 |
+
if err != nil {
|
| 130 |
+
log.Fatalf("load auths: %v", err)
|
| 131 |
+
}
|
| 132 |
+
log.Printf("loaded %d account(s) from %s", len(auths), cfg.AuthDir)
|
| 133 |
+
|
| 134 |
+
// redisstore:未配置/连接失败 → Noop(纯内存模式,一切功能照常)。
|
| 135 |
+
store := redisstore.New(cfg.Upstash.URL, cfg.Upstash.Token)
|
| 136 |
+
|
| 137 |
+
p := pool.New(cfg.StateFile)
|
| 138 |
+
// 停机序:先 pool.Close()(最后一次 Flush → SaveState 已提交到 store),
|
| 139 |
+
// 再 store.Close() 排空在途异步写(最后一笔 Redis 镜像必须写完才关连接)。
|
| 140 |
+
defer func() {
|
| 141 |
+
p.Close()
|
| 142 |
+
_ = store.Close()
|
| 143 |
+
}()
|
| 144 |
+
p.SetStore(store)
|
| 145 |
+
p.RestoreFromSnapshot() // 择新恢复:Redis 快照比本地新才采用,否则本地优先
|
| 146 |
+
p.SyncToDir(auths) // 与 auths 目录对齐:新账号加入、已删除文件账号剔除(状态保留)
|
| 147 |
+
|
| 148 |
+
// 熔断器 + 在途上限(含 global 分档)+ 连败降权 + 闲置补偿调优(从 config 注入,
|
| 149 |
+
// 非正值回退默认)。
|
| 150 |
+
p.SetBreaker(cfg.Pool.BreakerThreshold, cfg.BreakerCooldownDur, cfg.BreakerCooldownMaxD)
|
| 151 |
+
p.SetMaxInFlight(cfg.Pool.MaxInFlight)
|
| 152 |
+
p.SetMaxInFlightGlobal(cfg.Pool.MaxInFlightGlobal) // global 域 WAF 风控分档(P1-1)
|
| 153 |
+
p.SetDegrade(cfg.Pool.DegradeThreshold, cfg.DegradeCooldownDur, cfg.DegradeCooldownMaxD)
|
| 154 |
+
p.SetSoftRateMax(cfg.SoftRateMaxDur) // 软冷却指数退避封顶(soft_rate_max,默认 2h)
|
| 155 |
+
p.SetCostExploreInterval(cfg.CostExploreIntervalDur) // costTier 探索窗口(issue #136,默认 30m;0 关停)
|
| 156 |
+
p.SetBalanceWindow(cfg.BalanceWindowDur) // 窗口用量调度(issue #112,默认 1h;0 关停)
|
| 157 |
+
p.SetCreditFloor(cfg.Pool.CreditFloor) // 积分保底(默认 0 = 关闭)
|
| 158 |
+
p.SetCreditFloorMaxRate(cfg.Pool.CreditFloorMaxRate) // 保底兜底的目录倍率上限(0 = 严格模式)
|
| 159 |
+
p.SetWeights(cfg.Pool.IdleWeightPerHour, cfg.Pool.IdleWeightMax)
|
| 160 |
+
p.SetReserveCredits(*cfg.Pool.ReserveCredits) // 保留积分:余额低于阈值停止接单(0 = 关闭,缺省 10)
|
| 161 |
+
p.SetReserveCreditsByRealm(cfg.Pool.ReserveCreditsByRealm)
|
| 162 |
+
p.SetPreferExpiring(cfg.Pool.PreferExpiring, cfg.ExpiringSoonDur)
|
| 163 |
+
p.SetAccountPriority(cfg.Pool.AccountPriority) // 账号优先级/占比(issue #62):空表 = 不启用
|
| 164 |
+
p.SetAccountShare(cfg.Pool.AccountShare)
|
| 165 |
+
// 选号策略(pool.selection_strategy):weighted 缺省 / round_robin / sequential。
|
| 166 |
+
p.SetStrategy(cfg.Pool.SelectionStrategy)
|
| 167 |
+
|
| 168 |
+
// 会话粘性路由(可配关闭)。
|
| 169 |
+
var sessRouter *session.Router
|
| 170 |
+
redisMode := "noop"
|
| 171 |
+
if _, ok := store.(redisstore.Noop); !ok {
|
| 172 |
+
redisMode = "upstash"
|
| 173 |
+
}
|
| 174 |
+
if cfg.SessionSticky.Enabled {
|
| 175 |
+
sessRouter = session.New(session.Config{
|
| 176 |
+
TTL: cfg.SessionTTL,
|
| 177 |
+
GCInterval: cfg.SessionGCInterval,
|
| 178 |
+
Store: store,
|
| 179 |
+
Available: p.AvailableUIDs,
|
| 180 |
+
// realm 感知闭包:带前缀模型名按 realm 过滤可用账号(跨 realm 不泄漏);
|
| 181 |
+
// 裸名走 cn(现状零回归)。闭包内部 resolveModel 剥前缀,再按 realm 过滤。
|
| 182 |
+
AvailableForModel: realmAwareAvailableForModel(p),
|
| 183 |
+
})
|
| 184 |
+
sessRouter.LoadFromStore() // 启动时从 Redis 恢复粘性(读操作仅此处)
|
| 185 |
+
sessRouter.StartGC()
|
| 186 |
+
defer sessRouter.StopGC()
|
| 187 |
+
}
|
| 188 |
+
sessCount := func() int {
|
| 189 |
+
if sessRouter != nil {
|
| 190 |
+
return sessRouter.Count()
|
| 191 |
+
}
|
| 192 |
+
return 0
|
| 193 |
+
}
|
| 194 |
+
|
| 195 |
+
up := upstream.New()
|
| 196 |
+
|
| 197 |
+
// 出站 ClientHello 指纹档位:默认 node(复刻官方 Node/OpenSSL 的 JA3/JA4)。
|
| 198 |
+
// 配 go 才退回 crypto/tls 原生形态——唯一用途是指纹导致握手异常���紧急回滚。
|
| 199 |
+
if err := up.SetTLSFingerprint(cfg.Upstream.TLSFingerprint); err != nil {
|
| 200 |
+
log.Fatalf("CONFIG: %v", err)
|
| 201 |
+
}
|
| 202 |
+
if up.TLSFingerprint == upstream.TLSFingerprintNode {
|
| 203 |
+
log.Printf("[upstream] TLS 指纹复刻已启用(JA3 %s / JA4 %s)",
|
| 204 |
+
upstream.OfficialJA3MD5, upstream.OfficialJA4)
|
| 205 |
+
} else {
|
| 206 |
+
log.Printf("[upstream] TLS 指纹为原生 Go 形态(JA3/JA4 与官方客户端不一致)")
|
| 207 |
+
}
|
| 208 |
+
|
| 209 |
+
// 出站 DNS(config dns_servers / WB2A_DNS):显式指定解析器,绕开系统配置。
|
| 210 |
+
// 典型场景是 Android(无 /etc/resolv.conf,Go 解析器退回 [::1]:53 全域名失败)
|
| 211 |
+
// 与本地 DNS 被污染。未配置时保持系统解析器,行为零变化。
|
| 212 |
+
if len(cfg.DNSServers) > 0 {
|
| 213 |
+
up.SetDNSDialer(upstream.NewDNSDialer(cfg.DNSServers))
|
| 214 |
+
}
|
| 215 |
+
|
| 216 |
+
// 积分保底的「收费」兜底判据:接上游模型目录的积分倍率表。本地实测台账无观测
|
| 217 |
+
// 时用它判收费——否则「没学过」恒等于「放行」,高价新模型会把触底号一笔打穿
|
| 218 |
+
// (kimi-k3-1 实案:全池无观测 → 保底全放行 → 两笔打穿并硬冷却到次日 04:00)。
|
| 219 |
+
// 位于 up 装配之后:倍率表由探测下发,闭包每次调用读实时快照。
|
| 220 |
+
p.SetModelRateOf(func(realm, model string) string { return up.ModelRate(realm, model) })
|
| 221 |
+
// 「免费号调不通」的模型(modelTiers accessMode=exclusive):知道账号免费就不派给它。
|
| 222 |
+
// 付费状态来自 billing summary 的 IsPaidUser(顺手记在 upstream 里),没观测过就放行。
|
| 223 |
+
p.SetExclusiveModels(up.ModelExclusive, up.PaidUser)
|
| 224 |
+
// 短 RPC 总时长上限(refresh/checkin/balance/FetchModels),语义不变。
|
| 225 |
+
up.HTTP.Timeout = time.Duration(cfg.Upstream.TimeoutSeconds) * time.Second
|
| 226 |
+
// 聊天 SSE 首字节前(响应头)上限:cfg 已 normalize(缺省回落 timeout_seconds)。
|
| 227 |
+
up.HeaderTimeout = time.Duration(cfg.Upstream.HeaderTimeoutSeconds) * time.Second
|
| 228 |
+
if tr, ok := up.ChatHTTP.Transport.(*http.Transport); ok {
|
| 229 |
+
tr.ResponseHeaderTimeout = up.HeaderTimeout
|
| 230 |
+
}
|
| 231 |
+
// 聊天 SSE 流中空闲上限(S3 空闲监控读取)。
|
| 232 |
+
up.IdleTimeout = time.Duration(cfg.Upstream.IdleTimeoutSeconds) * time.Second
|
| 233 |
+
proxies, err := proxypool.New(stateSibling(cfg.StateFile, "proxy-pool.json"),
|
| 234 |
+
up.HTTP.Transport.(*http.Transport), upstream.NewDNSDialer(cfg.DNSServers))
|
| 235 |
+
if err != nil {
|
| 236 |
+
log.Fatalf("proxy pool: %v", err)
|
| 237 |
+
}
|
| 238 |
+
defer proxies.Close()
|
| 239 |
+
proxies.SetTLSOver(up.TLSOver) // 经代理的 HTTPS 与直连同一指纹、同一请求头顺序
|
| 240 |
+
// 出口画像(国家 / 住宅或机房 / ISP):随健康探测顺手查,查不到就空着,不参与选号。
|
| 241 |
+
proxies.EnableExitLookup()
|
| 242 |
+
up.ProxyPool = proxies
|
| 243 |
+
up.SanitizeFingerprints.Store(cfg.Features.SanitizeBlacklistFingerprints)
|
| 244 |
+
up.SanitizeBrandScope.Store(cfg.Features.SanitizeBrandScope)
|
| 245 |
+
up.KeepRecentRounds.Store(int64(cfg.Prompt.KeepRecentRounds))
|
| 246 |
+
// 思考档位策略(thinking 节):启动装载,面板保存配置时经 saveConfig 热更新。
|
| 247 |
+
up.SetEffortPolicy(effortPolicyOf(cfg))
|
| 248 |
+
if cfg.Thinking.Enabled {
|
| 249 |
+
priority := "客户端优先(只在缺档时补默认档)"
|
| 250 |
+
if !cfg.Thinking.ClientPriority {
|
| 251 |
+
priority = "网关优先(改写客户端档位)"
|
| 252 |
+
if cfg.Thinking.OverrideScope == "all" {
|
| 253 |
+
priority = "网关优先(档位与关闭意图一起覆盖)"
|
| 254 |
+
}
|
| 255 |
+
}
|
| 256 |
+
log.Printf("思考档位策略:默认档 %s;%s", cfg.Thinking.DefaultEffort, priority)
|
| 257 |
+
} else {
|
| 258 |
+
log.Printf("思考档位策略已关闭(不补档、不改写客户端档位)")
|
| 259 |
+
}
|
| 260 |
+
if cfg.Features.SanitizeBlacklistFingerprints {
|
| 261 |
+
if cfg.Features.SanitizeBrandScope == "identity" {
|
| 262 |
+
log.Printf("指纹脱敏已启用;品牌词规则仅作用于 system/developer(features.sanitize_brand_scope=identity)")
|
| 263 |
+
} else {
|
| 264 |
+
log.Printf("指纹脱敏已启用;品牌词规则作用于所有消息角色(features.sanitize_brand_scope=all)")
|
| 265 |
+
}
|
| 266 |
+
}
|
| 267 |
+
// 出站 UA 与归属头(issue #42 + 上游同步):
|
| 268 |
+
// UserAgent 非空则完全覆盖;ClientVersion/CliVersion 缺省对齐官方形态;
|
| 269 |
+
// ClientName 非空时 chat 路径注入 X-IDE-* 四头(用量归因对齐官方桌面端)。
|
| 270 |
+
up.UserAgent = cfg.Upstream.UserAgent
|
| 271 |
+
up.ClientVersion = cfg.Upstream.ClientVersion
|
| 272 |
+
up.CliVersion = cfg.Upstream.CliVersion
|
| 273 |
+
up.ClientName = cfg.Upstream.ClientName
|
| 274 |
+
up.DeviceToken = cfg.Upstream.DeviceToken
|
| 275 |
+
up.DeviceTokenFile = cfg.Upstream.DeviceTokenFile
|
| 276 |
+
up.DumpDir = cfg.Upstream.DumpDir
|
| 277 |
+
up.DumpRequestMax = cfg.Upstream.DumpMaxBytes
|
| 278 |
+
up.PassthroughIP = cfg.Upstream.PassthroughIP
|
| 279 |
+
// global realm 路由(config global 段):上游侧开关(第一道闸)+ base 覆盖;
|
| 280 |
+
// auth 侧开关(auth.SetGlobalEnabled)是第二道闸,两者同 config global.enabled。
|
| 281 |
+
up.GlobalEnabled = cfg.Global.Enabled
|
| 282 |
+
up.ChatBaseGlobal = cfg.Global.ChatBase
|
| 283 |
+
up.BillingBaseGlobal = cfg.Global.BillingBase
|
| 284 |
+
applyCNChatBase(up, cfg)
|
| 285 |
+
auth.SetGlobalEnabled(cfg.Global.Enabled)
|
| 286 |
+
// model.json 本地缓存接线(context_length/max_output_tokens 四级查找链第 3 级):
|
| 287 |
+
// 数据目录与 state.json 同风格(Docker volume 持久化路径)。首次缺失/损坏自动
|
| 288 |
+
// 回落仓库内嵌种子;models.dev 按需拉取成功后原子写回。
|
| 289 |
+
upstream.SetModelCatalogPath(stateSibling(cfg.StateFile, "model.json"))
|
| 290 |
+
|
| 291 |
+
// 余额采样记录器:与 state 文件同目录(路径由 state 推出,不加配置项)。
|
| 292 |
+
// 采样动作挂在余额刷新之后(见 internal/scheduler),这里只管装配与落盘生命周期。
|
| 293 |
+
balPath := stateSibling(cfg.StateFile, "balance_history.json")
|
| 294 |
+
bal := balance.New(balPath)
|
| 295 |
+
bal.Start()
|
| 296 |
+
defer bal.Stop()
|
| 297 |
+
log.Printf("[balance] 余额趋势采样已启用: %s 每 %v 一点(%s)", balPath, balance.Interval(), bal.Describe())
|
| 298 |
+
|
| 299 |
+
sch := scheduler.New(scheduler.Config{
|
| 300 |
+
Pool: p,
|
| 301 |
+
Upstream: up,
|
| 302 |
+
CheckinHours: cfg.Schedule.CheckinHours,
|
| 303 |
+
TravelHours: cfg.Schedule.TravelHours,
|
| 304 |
+
ActivityHours: cfg.Schedule.ActivityHours,
|
| 305 |
+
KeepaliveHours: cfg.Schedule.KeepaliveHours,
|
| 306 |
+
GrowthHours: cfg.Schedule.GrowthHours,
|
| 307 |
+
// 余额采样记录器:挂在余额刷新之后(scheduler 内),nil = 不采样。
|
| 308 |
+
Balance: bal,
|
| 309 |
+
// 快过期积分优先消耗:签到/余额刷新按此窗口分桶(issue:积分过期)。
|
| 310 |
+
ExpiringSoonWindow: cfg.ExpiringSoonDur,
|
| 311 |
+
CheckinDisabled: !cfg.Schedule.CheckinEnabled,
|
| 312 |
+
TravelDisabled: !cfg.Schedule.TravelEnabled,
|
| 313 |
+
ActivityDisabled: !cfg.Schedule.ActivityEnabled,
|
| 314 |
+
WebActivityDisabled: !cfg.Schedule.WebActivityEnabled,
|
| 315 |
+
KeepaliveDisabled: !cfg.Schedule.KeepaliveEnabled,
|
| 316 |
+
GrowthDisabled: !cfg.Schedule.GrowthEnabled,
|
| 317 |
+
// 周期保活只刷新临期凭证(默认 7 天窗口);面板手动全量保活不受影响。
|
| 318 |
+
KeepaliveRefreshWindow: cfg.KeepaliveRefreshWindowDur,
|
| 319 |
+
// 保号类四任务是否覆盖禁用账号(缺省 false = 禁用即跳过,保持既有行为)。
|
| 320 |
+
IncludeDisabledInTasks: cfg.Schedule.IncludeDisabledInTasks,
|
| 321 |
+
JitterMinutes: cfg.Schedule.JitterMinutes,
|
| 322 |
+
// 账号级摊开(issue #45):默认 0/0 = 关闭,同一秒打全池。
|
| 323 |
+
AccountSpreadMinutes: cfg.Schedule.AccountSpreadMinutes,
|
| 324 |
+
AccountSpreadMinGapSeconds: cfg.Schedule.AccountSpreadMinGapSeconds,
|
| 325 |
+
// 启动补跑去重:与 state.json 同目录,重启多次只在当天补一轮。
|
| 326 |
+
RunStampFile: filepath.Join(filepath.Dir(cfg.StateFile), "task-runs.json"),
|
| 327 |
+
})
|
| 328 |
+
switch {
|
| 329 |
+
case !cfg.Schedule.CheckinEnabled:
|
| 330 |
+
log.Printf("签到已禁用(schedule.checkin_enabled=false)")
|
| 331 |
+
default:
|
| 332 |
+
log.Printf("签到已启用:%v 点(签到 + 余额查询解冻)", cfg.Schedule.CheckinHours)
|
| 333 |
+
}
|
| 334 |
+
switch {
|
| 335 |
+
case !cfg.Schedule.TravelEnabled:
|
| 336 |
+
log.Printf("猫猫旅行已禁用(schedule.travel_enabled=false)")
|
| 337 |
+
default:
|
| 338 |
+
log.Printf("猫猫旅行已启用:%v 点(独立排程:领养 / 派出 / 领奖)", cfg.Schedule.TravelHours)
|
| 339 |
+
}
|
| 340 |
+
switch {
|
| 341 |
+
case !cfg.Schedule.ActivityEnabled:
|
| 342 |
+
log.Printf("活跃上报已禁用(schedule.activity_enabled=false)")
|
| 343 |
+
default:
|
| 344 |
+
log.Printf("活跃上报已启用:%v 点(每日 1 次,点亮连登 + 解锁 first_buddy)", cfg.Schedule.ActivityHours)
|
| 345 |
+
}
|
| 346 |
+
if !cfg.Schedule.KeepaliveEnabled {
|
| 347 |
+
log.Printf("token 保活已禁用(schedule.keepalive_enabled=false)")
|
| 348 |
+
} else {
|
| 349 |
+
log.Printf("token 保活已启用:%v 点", cfg.Schedule.KeepaliveHours)
|
| 350 |
+
}
|
| 351 |
+
switch {
|
| 352 |
+
case !cfg.Schedule.GrowthEnabled:
|
| 353 |
+
log.Printf("成长任务队列已禁用(schedule.growth_enabled=false)")
|
| 354 |
+
default:
|
| 355 |
+
log.Printf("成长任务队列已启用:%v 点(每日自动跑一遍任务中心待办,账号间并发 %d)",
|
| 356 |
+
cfg.Schedule.GrowthHours, cfg.Schedule.GrowthConcurrency)
|
| 357 |
+
}
|
| 358 |
+
if cfg.Schedule.JitterMinutes > 0 {
|
| 359 |
+
log.Printf("排程抖动:各任务在名义整点后 0-%d 分钟(schedule.jitter_minutes)", cfg.Schedule.JitterMinutes)
|
| 360 |
+
}
|
| 361 |
+
if cfg.Schedule.AccountSpreadMinutes > 0 {
|
| 362 |
+
log.Printf("账号摊开:账号遍历型任务在 %d 分钟内按账号错开,最小间隔 %d 秒(schedule.account_spread_minutes)",
|
| 363 |
+
cfg.Schedule.AccountSpreadMinutes, cfg.Schedule.AccountSpreadMinGapSeconds)
|
| 364 |
+
}
|
| 365 |
+
switch {
|
| 366 |
+
case !cfg.Schedule.BalanceRefreshEnabled:
|
| 367 |
+
log.Printf("余额后台刷新已禁用(schedule.balance_refresh_enabled=false)")
|
| 368 |
+
case cfg.BalanceRefreshInterval > 0:
|
| 369 |
+
log.Printf("余额后台刷新:每 %s(签到时点照常额外刷新)", cfg.BalanceRefreshInterval)
|
| 370 |
+
}
|
| 371 |
+
switch {
|
| 372 |
+
case !cfg.Schedule.TaskSweepEnabled:
|
| 373 |
+
log.Printf("补领清扫已禁用(schedule.task_sweep_enabled=false)")
|
| 374 |
+
case cfg.TaskSweepInterval > 0:
|
| 375 |
+
log.Printf("补领清扫:每 %s(只 accept 待接受的、只 claim 已达标未领的)", cfg.TaskSweepInterval)
|
| 376 |
+
}
|
| 377 |
+
if !cfg.Schedule.WindowProbeEnabled {
|
| 378 |
+
log.Printf("额度窗口探针已禁用(schedule.window_probe_enabled=false)")
|
| 379 |
+
}
|
| 380 |
+
if cfg.Schedule.BalanceRefreshJitterPermill > 0 {
|
| 381 |
+
log.Printf("周期抖动(人味化):余额刷新 ±%d‰(账号遍历同步摊开)、补领清扫 ±%d‰,不再精确固定间隔(schedule.*_jitter_permill)",
|
| 382 |
+
cfg.Schedule.BalanceRefreshJitterPermill, cfg.Schedule.TaskSweepJitterPermill)
|
| 383 |
+
}
|
| 384 |
+
if cfg.Schedule.IncludeDisabledInTasks {
|
| 385 |
+
log.Printf("保号任务覆盖禁用账号(schedule.include_disabled_in_tasks=true):禁用号仍签到 / 活跃 / 保活 / 刷新余额,但不参与选号")
|
| 386 |
+
}
|
| 387 |
+
|
| 388 |
+
// 管理面板日志镜像:标准 log(stderr)与 chat 表格日志(stdout)双路复制进
|
| 389 |
+
// 面板环形缓冲,供 /panel/api/logs 读取;控制台输出行为完全不变。
|
| 390 |
+
// live 承载可热改字段(api_key/soft_rate/脱敏开关),面板保存配置时在线替换。
|
| 391 |
+
// 模型白名单(issue #68):启动时归一化一次,快照只读持有。
|
| 392 |
+
allowedModels, allowlistEnabled := livecfg.NormalizeAllowedModels(cfg.Models.Allowed)
|
| 393 |
+
live := livecfg.New(livecfg.Snapshot{
|
| 394 |
+
APIKey: cfg.APIKey,
|
| 395 |
+
SoftCooldown: cfg.SoftRateDur,
|
| 396 |
+
SanitizeFingerprints: cfg.Features.SanitizeBlacklistFingerprints,
|
| 397 |
+
EmbeddingsEnabled: cfg.Features.EmbeddingsEnabled,
|
| 398 |
+
WatermarkStripEnabled: cfg.Features.WatermarkStripEnabled,
|
| 399 |
+
RecordClientInfo: cfg.Logging.RequestClientInfo,
|
| 400 |
+
RecordContext: cfg.Logging.RequestArchiveContext,
|
| 401 |
+
HiddenModels: livecfg.NormalizeHiddenModels(cfg.Models.Hidden),
|
| 402 |
+
// 模型白名单(issue #68):归一化集合 + 启用标志;空配置 = 不启用。
|
| 403 |
+
AllowedModels: allowedModels,
|
| 404 |
+
AllowlistEnabled: allowlistEnabled,
|
| 405 |
+
ModelAliases: livecfg.NormalizeModelAliases(cfg.Models.Aliases),
|
| 406 |
+
// 模型降级路由表(pool.model_fallback):6004 限流时同账号改用等价模型。
|
| 407 |
+
ModelFallback: cfg.Pool.ModelFallback,
|
| 408 |
+
// 思考档位策略镜像:面板「模型与档位」页的「网关档位」列据此显示当前生效值。
|
| 409 |
+
ThinkingEnabled: cfg.Thinking.Enabled,
|
| 410 |
+
ThinkingDefaultEffort: cfg.Thinking.DefaultEffort,
|
| 411 |
+
ThinkingClientPriority: cfg.Thinking.ClientPriority,
|
| 412 |
+
ThinkingOverrideScope: cfg.Thinking.OverrideScope,
|
| 413 |
+
ThinkingModelDefaults: cfg.Thinking.ModelDefaults,
|
| 414 |
+
})
|
| 415 |
+
// 用量记录器:与 state 文件同目录,随 state_file 配置一起搬移。
|
| 416 |
+
// datapath 由 state 文件路径推出,避免再加一个配置项。
|
| 417 |
+
usagePath := usagePathFor(cfg.StateFile)
|
| 418 |
+
rec := usage.New(usagePath)
|
| 419 |
+
rec.Start()
|
| 420 |
+
defer rec.Stop()
|
| 421 |
+
log.Printf("[usage] 逐请求用量记录已启用: %s (%s)", usagePath, rec.Describe())
|
| 422 |
+
|
| 423 |
+
// 请求指标始终启用;JSONL 归档只写脱敏元数据,写盘失败不影响聊天请求。
|
| 424 |
+
requestLog := reqlog.New(reqlog.Config{
|
| 425 |
+
Dir: stateSibling(cfg.StateFile, "request-logs"),
|
| 426 |
+
Enabled: cfg.Logging.RequestArchiveEnabled,
|
| 427 |
+
RetentionDays: cfg.Logging.RequestRetentionDays,
|
| 428 |
+
MaxBytes: int64(cfg.Logging.RequestArchiveMaxMB) << 20,
|
| 429 |
+
})
|
| 430 |
+
defer requestLog.Close()
|
| 431 |
+
rs := requestLog.Snapshot().Archive
|
| 432 |
+
if rs.Enabled {
|
| 433 |
+
log.Printf("[reqlog] 请求指标已启用;JSONL 归档 %s(保留 %d 天,上限 %d MiB)",
|
| 434 |
+
rs.Dir, cfg.Logging.RequestRetentionDays, cfg.Logging.RequestArchiveMaxMB)
|
| 435 |
+
} else {
|
| 436 |
+
log.Printf("[reqlog] 请求指标已启用;JSONL 归档已关闭")
|
| 437 |
+
}
|
| 438 |
+
|
| 439 |
+
var gw *server.Handler
|
| 440 |
+
// configSaveMu 串行化面板配置保存(并发两次保存会在读-改-写文件与热应用之间互踩)。
|
| 441 |
+
var configSaveMu sync.Mutex
|
| 442 |
+
// pn 先声明再赋值:SaveConfig 闭包要在同一条语句里捕获它(:= 的作用域从语句结束才开始)。
|
| 443 |
+
// 积分历史:把每次真实查到的余额与上一次比对,变动即留痕(新账号首次只建
|
| 444 |
+
// 基线)。挂载在余额查询路径上(upstream 的余额观察者),签到 / 活跃上报 /
|
| 445 |
+
// 旅行 / 保活 / 面板手动刷新全覆盖——上游只在少数渠道落金额日志,比对余额
|
| 446 |
+
// 是唯一可靠的口径。与 state/usage/request-logs 同目录,随 state_file 搬移。
|
| 447 |
+
creditHist := credithist.New(stateSibling(cfg.StateFile, "credit-history.json"), 2000)
|
| 448 |
+
up.SetCreditObserver(creditHist.Observe)
|
| 449 |
+
log.Printf("[credithist] 积分历史已启用: %s", stateSibling(cfg.StateFile, "credit-history.json"))
|
| 450 |
+
|
| 451 |
+
// 扩展层:免费模型 / 自定义模型 / 访问密钥。与 state 同目录(HF 上在存储桶卷里)。
|
| 452 |
+
extStore := extstore.Open(stateSibling(cfg.StateFile, "extensions.json"))
|
| 453 |
+
freeClient := freemodel.New(extStore)
|
| 454 |
+
extSnap := extStore.Snapshot()
|
| 455 |
+
labels := make([]string, 0, len(extSnap.Free.Providers))
|
| 456 |
+
for _, p := range extSnap.Free.Providers {
|
| 457 |
+
state := "off"
|
| 458 |
+
if p.Enabled {
|
| 459 |
+
state = "on"
|
| 460 |
+
}
|
| 461 |
+
labels = append(labels, p.Name+"="+state)
|
| 462 |
+
}
|
| 463 |
+
log.Printf("[extensions] 扩展配置已加载: %s(免费模型总开关=%v,渠道: %s)",
|
| 464 |
+
extStore.Path(), extSnap.Free.Enabled, strings.Join(labels, ", "))
|
| 465 |
+
|
| 466 |
+
updateManager := updater.New(appVersion, appRepository, *cfgPath, updateSettingsFrom(cfg))
|
| 467 |
+
var pn *panel.Panel
|
| 468 |
+
pn = panel.New(panel.Config{
|
| 469 |
+
Pool: p,
|
| 470 |
+
ProxyPool: proxies,
|
| 471 |
+
Usage: rec,
|
| 472 |
+
RequestLog: requestLog,
|
| 473 |
+
Upstream: up,
|
| 474 |
+
Scheduler: sch,
|
| 475 |
+
// 降级路由表:面板据此在��流提示里标注「已路由至 <等价模型>」。
|
| 476 |
+
ModelFallback: func() map[string]string { return live.Load().ModelFallback },
|
| 477 |
+
// 余额趋势采样记录器:nil 时该视图返回 501。
|
| 478 |
+
Balance: bal,
|
| 479 |
+
// 后台任务的自动触发开关与成长任务排程共用热配置(schedule.growth_enabled)。
|
| 480 |
+
AutoTasksEnabled: sch.GrowthEnabled,
|
| 481 |
+
AuthDir: cfg.AuthDir,
|
| 482 |
+
APIKey: cfg.APIKey,
|
| 483 |
+
RedisMode: redisMode,
|
| 484 |
+
StickyCount: sessCount,
|
| 485 |
+
Version: appVersion,
|
| 486 |
+
Updater: updateManager,
|
| 487 |
+
PollIntervalSec: cfg.Panel.PollIntervalSec,
|
| 488 |
+
Live: live,
|
| 489 |
+
// 模型上限探测数据(scripts/probe_max_tokens.py --panel-out 写入):
|
| 490 |
+
// 与 state 文件同目录,缺省 data/output_probes.json。
|
| 491 |
+
ProbeFile: stateSibling(cfg.StateFile, "output_probes.json"),
|
| 492 |
+
ConfigPath: *cfgPath,
|
| 493 |
+
LoadConfig: func() (any, error) {
|
| 494 |
+
return Load(*cfgPath)
|
| 495 |
+
},
|
| 496 |
+
SaveConfig: func(raw []byte) ([]string, error) {
|
| 497 |
+
configSaveMu.Lock()
|
| 498 |
+
defer configSaveMu.Unlock()
|
| 499 |
+
fields, err := saveConfig(raw, *cfgPath, live, p, up, sch, gw, pn, cfg)
|
| 500 |
+
if err != nil {
|
| 501 |
+
return nil, err
|
| 502 |
+
}
|
| 503 |
+
if saved, loadErr := Load(*cfgPath); loadErr == nil {
|
| 504 |
+
updateManager.Configure(updateSettingsFrom(saved))
|
| 505 |
+
} else if loadErr != nil {
|
| 506 |
+
log.Printf("WARN: reload update settings: %v", loadErr)
|
| 507 |
+
}
|
| 508 |
+
return fields, nil
|
| 509 |
+
},
|
| 510 |
+
// 积分历史账本(只读展示;写入由上面的余额观察者完成)。
|
| 511 |
+
CreditHistory: creditHist,
|
| 512 |
+
// 扩展模型页:免登录免费模型 / 自定义模型映射 / 访问密钥。
|
| 513 |
+
Extensions: extStore,
|
| 514 |
+
FreeModels: freeClient,
|
| 515 |
+
})
|
| 516 |
+
// 面板运行日志全频道按天落盘(logging.panel_log_*):重启后回填、支持按区间导出。
|
| 517 |
+
// 装配顺序必须在 log.SetOutput 之前——回填完再把实时输出接上,否则启动期的
|
| 518 |
+
// 那几行会先入环、再被回填的历史插到前面,时间序就乱了。
|
| 519 |
+
var panelLogs *panel.LogStore
|
| 520 |
+
if cfg.Logging.PanelLogEnabled {
|
| 521 |
+
panelLogs = panel.NewLogStore(stateSibling(cfg.StateFile, "panel-logs"),
|
| 522 |
+
cfg.Logging.PanelLogRetentionDays, cfg.Logging.PanelLogMaxMB)
|
| 523 |
+
if panelLogs == nil {
|
| 524 |
+
log.Printf("WARN: 面板日志落盘不可用(数据目录建不出来),退回纯内存环")
|
| 525 |
+
} else {
|
| 526 |
+
if err := pn.Logs().SetLogStore(panelLogs); err != nil {
|
| 527 |
+
log.Printf("WARN: 面板日志回填失败(不影响新日志): %v", err)
|
| 528 |
+
}
|
| 529 |
+
defer panelLogs.Close()
|
| 530 |
+
log.Printf("[panel] 运行日志落盘 %s(保留 %d 天,上限 %d MiB)",
|
| 531 |
+
panelLogs.Dir(), cfg.Logging.PanelLogRetentionDays, cfg.Logging.PanelLogMaxMB)
|
| 532 |
+
}
|
| 533 |
+
}
|
| 534 |
+
// 兜底:落盘关掉或不可用时,仍用任务频道那份 JSON 快照回填(旧行为)。
|
| 535 |
+
if panelLogs == nil {
|
| 536 |
+
if err := pn.Logs().SetTaskArchive(stateSibling(cfg.StateFile, "task-logs.json")); err != nil {
|
| 537 |
+
log.Printf("WARN: task log archive: %v", err)
|
| 538 |
+
}
|
| 539 |
+
}
|
| 540 |
+
log.SetOutput(io.MultiWriter(os.Stderr, pn.Logs()))
|
| 541 |
+
server.SetChatLogOutput(io.MultiWriter(os.Stdout, pn.Logs()))
|
| 542 |
+
// 成长任务队列排程的执行体在面板(队列逻辑唯一实现):注入回调,避免 scheduler → panel 循环依赖。
|
| 543 |
+
sch.SetGrowthRunner(pn.RunGrowthQueueNow)
|
| 544 |
+
sch.SetSweepRunner(pn.RunTaskSweepNow)
|
| 545 |
+
pn.SetGrowthConcurrency(cfg.Schedule.GrowthConcurrency)
|
| 546 |
+
|
| 547 |
+
var auditLog *server.AuditLog
|
| 548 |
+
if cfg.Admin.AuditEnabled {
|
| 549 |
+
al, aerr := server.NewAuditLog(cfg.Admin.AuditFile, cfg.APIKey)
|
| 550 |
+
if aerr != nil {
|
| 551 |
+
p.Flush() // Fatal 绕过 defer:至少把池状态落盘再退,否则丢整轮运行状态
|
| 552 |
+
log.Fatalf("admin audit: %v", aerr)
|
| 553 |
+
}
|
| 554 |
+
auditLog = al
|
| 555 |
+
log.Printf("admin audit: %s", al.Path())
|
| 556 |
+
}
|
| 557 |
+
// MCP serverInfo.version 与面板 /status 用同一个版本串(本地构建是 dev)。
|
| 558 |
+
server.BuildVersion = appVersion
|
| 559 |
+
gw = server.NewHandler(server.Config{
|
| 560 |
+
Pool: p,
|
| 561 |
+
Upstream: up,
|
| 562 |
+
APIKey: cfg.APIKey,
|
| 563 |
+
Session: sessRouter,
|
| 564 |
+
StickyCount: sessCount,
|
| 565 |
+
RedisMode: redisMode,
|
| 566 |
+
SoftCooldown: cfg.SoftRateDur,
|
| 567 |
+
Panel: pn,
|
| 568 |
+
Live: live,
|
| 569 |
+
Usage: rec,
|
| 570 |
+
RequestLog: requestLog,
|
| 571 |
+
PromptMode: cfg.Prompt.Mode,
|
| 572 |
+
// 模型降级路由表:读 live 快照(支持面板热更,改完即生效、无需重启)。
|
| 573 |
+
ModelFallback: func() map[string]string { return live.Load().ModelFallback },
|
| 574 |
+
PromptText: cfg.PromptText,
|
| 575 |
+
// 来源记录开关经 livecfg 热生效;此处同时填静态字段,供 Live 为 nil 的
|
| 576 |
+
// 裸用/测试路径拿到同一缺省值。
|
| 577 |
+
RecordClientInfo: cfg.Logging.RequestClientInfo,
|
| 578 |
+
RecordContext: cfg.Logging.RequestArchiveContext,
|
| 579 |
+
// handler 侧第三道闸(global realm):false(显式逃生门)时不列 global: 模型名。
|
| 580 |
+
GlobalEnabled: cfg.Global.Enabled,
|
| 581 |
+
// 模型黑名单原始条目;运行期以 livecfg 快照为准(热生效),此处供
|
| 582 |
+
// Live 为 nil 的裸用/测试路径。
|
| 583 |
+
ModelsHidden: cfg.Models.Hidden,
|
| 584 |
+
// 模型白名单原始条目(issue #68);同上,运行期以 livecfg 快照为准。
|
| 585 |
+
ModelsAllowed: cfg.Models.Allowed,
|
| 586 |
+
// 模型映射原始条目(issue #30);同上,运行期以 livecfg 快照为准。
|
| 587 |
+
ModelsAliases: cfg.Models.Aliases,
|
| 588 |
+
AdminEnabled: cfg.Admin.Enabled,
|
| 589 |
+
MetricsEnabled: cfg.Metrics.Enabled,
|
| 590 |
+
Tasks: sch,
|
| 591 |
+
Audit: auditLog,
|
| 592 |
+
BudgetLimit: cfg.Budget.DailyCreditLimit,
|
| 593 |
+
BurstCreditLimit: cfg.Budget.BurstCreditLimit,
|
| 594 |
+
CacheLowRate: cfg.Budget.CacheLowRate,
|
| 595 |
+
// 入站请求体 OOM 护栏 + 11140 连坐暂停(两处都只在启动时读,改完需重启)。
|
| 596 |
+
MaxPayloadBytes: cfg.Server.MaxPayloadBytes,
|
| 597 |
+
RestrictionHold: time.Duration(cfg.Upstream.RestrictionHoldSeconds) * time.Second,
|
| 598 |
+
// 等上游首帧期间的 SSE 注释帧间隔(server.head_keepalive,缺省 1.5s)。
|
| 599 |
+
HeadKeepalive: cfg.HeadKeepaliveDur,
|
| 600 |
+
// 6020/6021 渠道排队:网关内先等一轮(features.busy_retry / busy_wait_seconds)。
|
| 601 |
+
BusyRetry: cfg.Features.BusyRetry,
|
| 602 |
+
BusyWaitMax: time.Duration(cfg.Features.BusyWaitSeconds) * time.Second,
|
| 603 |
+
// 扩展层:免费模型直连与自定义模型映射(访问密钥鉴权也走同一个 store)。
|
| 604 |
+
Extensions: extStore,
|
| 605 |
+
FreeModels: freeClient,
|
| 606 |
+
})
|
| 607 |
+
|
| 608 |
+
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
|
| 609 |
+
defer stop()
|
| 610 |
+
// 免费模型清单后台刷新(3 秒后首次,之后每 6 小时)。
|
| 611 |
+
go freeClient.RunRefresh(ctx)
|
| 612 |
+
proxyCtx, stopProxies := context.WithCancel(ctx)
|
| 613 |
+
proxyDone := make(chan struct{})
|
| 614 |
+
go func() {
|
| 615 |
+
defer close(proxyDone)
|
| 616 |
+
proxies.Run(proxyCtx)
|
| 617 |
+
}()
|
| 618 |
+
defer func() { stopProxies(); <-proxyDone }()
|
| 619 |
+
updateManager.SetRestart(stop)
|
| 620 |
+
go updateManager.Run(ctx)
|
| 621 |
+
// 账号目录热重载(issue #199):外部同步进来的 auths/*.json 不必重启进程即可入池,
|
| 622 |
+
// 删文件也会在连续 N 次扫描确认后出池。面板「刷新」按钮之外还提供
|
| 623 |
+
// POST /panel/api/accounts/reload 给脚本用;间隔 0s 时只保留手动接口。
|
| 624 |
+
pn.SetReloadConfig(cfg.ReloadIntervalDur, cfg.Accounts.ReloadDeleteConfirm)
|
| 625 |
+
go pn.ReloadLoop(ctx.Done())
|
| 626 |
+
// 账号后台任务(taskjobs):状态与主 state 同目录,重启后自动恢复未完成作业。
|
| 627 |
+
if err := pn.StartTaskJobs(ctx, stateSibling(cfg.StateFile, "task-jobs.json")); err != nil {
|
| 628 |
+
p.Flush() // Fatal 绕过 defer:至少把池状态落盘再退
|
| 629 |
+
log.Fatalf("task jobs: %v", err)
|
| 630 |
+
}
|
| 631 |
+
defer pn.StopTaskJobs()
|
| 632 |
+
pn.ResumeTaskJobs()
|
| 633 |
+
go sch.Run(ctx)
|
| 634 |
+
sch.SetJitter(cfg.Schedule.BalanceRefreshJitterPermill, cfg.Schedule.TaskSweepJitterPermill)
|
| 635 |
+
sch.SetMakeupCardsPerRound(cfg.Schedule.MakeupCardsPerRound)
|
| 636 |
+
sch.StartBalanceRefresh(ctx, cfg.BalanceRefreshInterval)
|
| 637 |
+
sch.StartTaskSweep(ctx, cfg.TaskSweepInterval)
|
| 638 |
+
// 额度窗口探针:上游按首次请求起算额度窗口,429 重置时刻到了没人发请求窗口就
|
| 639 |
+
// 不开始(额度空转)。到点主动发一个最小请求把起点钉住。开关见
|
| 640 |
+
// schedule.window_probe_enabled(缺省开)。
|
| 641 |
+
if cfg.Schedule.WindowProbeEnabled {
|
| 642 |
+
sch.StartModelWindowProbe(ctx)
|
| 643 |
+
}
|
| 644 |
+
if cfg.Alerting.Enabled {
|
| 645 |
+
mon := alert.New(alert.Config{
|
| 646 |
+
Enabled: true,
|
| 647 |
+
WebhookURL: cfg.Alerting.WebhookURL,
|
| 648 |
+
Secret: cfg.Alerting.Secret,
|
| 649 |
+
Interval: time.Duration(cfg.Alerting.IntervalSeconds) * time.Second,
|
| 650 |
+
Timeout: time.Duration(cfg.Alerting.TimeoutSeconds) * time.Second,
|
| 651 |
+
StartupGrace: time.Duration(cfg.Alerting.StartupGraceSeconds) * time.Second,
|
| 652 |
+
MinHealthyCN: cfg.Alerting.MinHealthyCN,
|
| 653 |
+
MinHealthyGlobal: cfg.Alerting.MinHealthyGlobal,
|
| 654 |
+
RecoverHealthy: cfg.Alerting.RecoverHealthy,
|
| 655 |
+
BreakerThreshold: cfg.Alerting.BreakerThreshold,
|
| 656 |
+
ForTicks: cfg.Alerting.ForTicks,
|
| 657 |
+
ClearTicks: cfg.Alerting.ClearTicks,
|
| 658 |
+
SendResolve: cfg.Alerting.SendResolve,
|
| 659 |
+
}, alertSource{pool: p, h: gw})
|
| 660 |
+
go mon.Run(ctx)
|
| 661 |
+
// 排程轮次结果汇总的推送出口(告警 webhook 同一条管道;未启用则只落面板日志)。
|
| 662 |
+
pn.SetNotifier(mon.Notify)
|
| 663 |
+
log.Printf("alerting: webhook on, every %ds", cfg.Alerting.IntervalSeconds)
|
| 664 |
+
// 上游目录改版监控也走这条管道(未启用告警时只写日志,见下方 watchdog 段)。
|
| 665 |
+
if cfg.Watchdog.Enabled {
|
| 666 |
+
go gw.WatchCatalog(ctx, time.Duration(cfg.Watchdog.IntervalSeconds)*time.Second, mon.Notify)
|
| 667 |
+
log.Printf("watchdog: 上游目录监控开,每 %ds", cfg.Watchdog.IntervalSeconds)
|
| 668 |
+
}
|
| 669 |
+
} else if cfg.Watchdog.Enabled {
|
| 670 |
+
// 没有 webhook 也要能开:变化只写日志(面板任务日志里能翻到)。
|
| 671 |
+
go gw.WatchCatalog(ctx, time.Duration(cfg.Watchdog.IntervalSeconds)*time.Second, nil)
|
| 672 |
+
log.Printf("watchdog: 上游目录监控开(未配置 alerting,仅写日志),每 %ds", cfg.Watchdog.IntervalSeconds)
|
| 673 |
+
}
|
| 674 |
+
|
| 675 |
+
// 启动即预热模型积分倍率表:倍率只在 FetchModels/FetchGlobalModelInfos 成功时
|
| 676 |
+
// 填充(两者均懒触发),重启后到首次 /v1/models 或面板模型页被访问之前,
|
| 677 |
+
// ModelRate 恒返回空串——积分保底的目录兜底在这段空窗期内形同虚设,触底号
|
| 678 |
+
// 会被当成「收费未知」放行并打穿(实测:重启后 2 分钟,97 分的账号打收费
|
| 679 |
+
// 模型归零;倍率表当时尚未建立)。
|
| 680 |
+
// 异步执行:不阻塞监听启动;失败仅记日志(下一轮懒触发或本轮重试仍可补上)。
|
| 681 |
+
go warmModelRates(ctx, up, p)
|
| 682 |
+
|
| 683 |
+
// 诊断用:WB2API_PPROF=127.0.0.1:6060 时另起一个只跑 pprof 的监听。
|
| 684 |
+
// 默认不开启(不设环境变量就完全没有这个监听),供「并发一高就降速」这类
|
| 685 |
+
// 只能靠真实负载定位的 CPU 问题取 profile(取完即关容器,不常驻生产)。
|
| 686 |
+
if addr := os.Getenv("WB2API_PPROF"); addr != "" {
|
| 687 |
+
go func() {
|
| 688 |
+
log.Printf("[pprof] 诊断监听开启 %s(CPU: /debug/pprof/profile?seconds=30)", addr)
|
| 689 |
+
if err := http.ListenAndServe(addr, nil); err != nil {
|
| 690 |
+
log.Printf("WARN: [pprof] 监听失败 %v", err)
|
| 691 |
+
}
|
| 692 |
+
}()
|
| 693 |
+
}
|
| 694 |
+
|
| 695 |
+
srv := &http.Server{
|
| 696 |
+
Addr: cfg.Listen,
|
| 697 |
+
Handler: gw,
|
| 698 |
+
ReadHeaderTimeout: 30 * time.Second,
|
| 699 |
+
// ReadTimeout 覆盖整个请求读取(含 body 上传):防慢速 body 拖死连接。
|
| 700 |
+
// 请求体已无网关侧上限(max_body_mb 移除)。缺省 300s(issue #100:旧固定
|
| 701 |
+
// 60s 会掐掉大上下文/文件块经反代链的慢速上传,客户端收到
|
| 702 |
+
// 400 "read body: ... i/o timeout");server.read_timeout="0" 显式关闭。
|
| 703 |
+
// 改动需重启进程。
|
| 704 |
+
ReadTimeout: cfg.ServerReadTimeoutDur,
|
| 705 |
+
// IdleTimeout keep-alive 空闲连接回收:配合 chat 出站 ctx 传播防连接泄漏堆积。
|
| 706 |
+
// 注意:SSE 流式响应期间连接非空闲,不受此项掐断;不设全局 WriteTimeout
|
| 707 |
+
// (长流式生成合法时长可达数分钟,全局 WriteTimeout 会误杀在途 SSE)。
|
| 708 |
+
IdleTimeout: 120 * time.Second,
|
| 709 |
+
}
|
| 710 |
+
shutdownDone := make(chan struct{})
|
| 711 |
+
go func() {
|
| 712 |
+
defer close(shutdownDone)
|
| 713 |
+
<-ctx.Done()
|
| 714 |
+
p.Flush() // 信号触发:先落盘再做优雅停机
|
| 715 |
+
// 在途请求排干窗口可配(server.shutdown_timeout,缺省 30s):长流式 SSE
|
| 716 |
+
// 合法时长可达分钟级,固定 5s 必然把在途请求掐成连接重置;超时不再静默。
|
| 717 |
+
shutdownTimeout := cfg.ShutdownTimeoutDur
|
| 718 |
+
if shutdownTimeout <= 0 {
|
| 719 |
+
shutdownTimeout = 5 * time.Second
|
| 720 |
+
}
|
| 721 |
+
shutdownCtx, cancel := context.WithTimeout(context.Background(), shutdownTimeout)
|
| 722 |
+
defer cancel()
|
| 723 |
+
if err := srv.Shutdown(shutdownCtx); err != nil {
|
| 724 |
+
log.Printf("WARN: 优雅关停未在 %s 内完成,在途请求被放弃: %v", shutdownTimeout, err)
|
| 725 |
+
}
|
| 726 |
+
}()
|
| 727 |
+
|
| 728 |
+
if warn := insecureKeyWarning(cfg.Listen, cfg.APIKey); warn != "" {
|
| 729 |
+
log.Printf("WARN: %s", warn)
|
| 730 |
+
}
|
| 731 |
+
log.Print(listenBanner(cfg.Listen, loadedFrom, cfg.APIKey))
|
| 732 |
+
if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
|
| 733 |
+
p.Flush() // 监听失败时信号路径不会跑:这里同样兜底落盘再退
|
| 734 |
+
log.Fatalf("http: %v", err)
|
| 735 |
+
}
|
| 736 |
+
if ctx.Err() != nil {
|
| 737 |
+
<-shutdownDone
|
| 738 |
+
}
|
| 739 |
+
log.Printf("bye")
|
| 740 |
+
}
|
| 741 |
+
|
| 742 |
+
// warmModelRates 启动预热各域模型积分倍率表(供积分保底的目录兜底判定)。
|
| 743 |
+
//
|
| 744 |
+
// 为什么需要:倍率表只在 FetchModels(CN)/ FetchGlobalModelInfos(global)成功时
|
| 745 |
+
// 填充,两者都是懒触发(被 /v1/models 或面板模型页访问才跑)。重启后到首次触发
|
| 746 |
+
// 之间的空窗期里 ModelRate 恒返回空串,保底的目录兜底判不出收费,触底号会被
|
| 747 |
+
// 当成「收费未知」放行并打穿(实测:重启后 2 分钟,97 分的账号打收费模型归零)。
|
| 748 |
+
//
|
| 749 |
+
// 失败处理:单域失败只记 WARN(不阻塞、不致命——后续懒触发仍会补上);global 域
|
| 750 |
+
// 仅在其路由开关开启时预热(逃生门关锁时按 CN 处理,无需探测)。
|
| 751 |
+
func warmModelRates(ctx context.Context, up *upstream.Client, p *pool.Pool) {
|
| 752 |
+
// 预热不得拖住进程退出:ctx 取消(SIGINT/SIGTERM)时立刻放弃剩余域。
|
| 753 |
+
if ctx.Err() != nil {
|
| 754 |
+
return
|
| 755 |
+
}
|
| 756 |
+
// CN:有可用 CN 账号才拉(与面板 models 同口径,避免无谓上游调用)。
|
| 757 |
+
if uids := p.AvailableUIDsForRealm("cn"); len(uids) > 0 {
|
| 758 |
+
if a := p.AuthByUID(uids[0]); a != nil {
|
| 759 |
+
if _, err := up.FetchModels(a); err != nil {
|
| 760 |
+
log.Printf("WARN: [upstream] warm model rates (cn): %v", err)
|
| 761 |
+
} else {
|
| 762 |
+
log.Printf("[upstream] warm model rates: cn ok")
|
| 763 |
+
}
|
| 764 |
+
}
|
| 765 |
+
}
|
| 766 |
+
// global:独立目录端点(workbuddy.ai),倍率按 "global" 域键存储。
|
| 767 |
+
if up.GlobalEnabled && ctx.Err() == nil {
|
| 768 |
+
if uids := p.AvailableUIDsForRealm("global"); len(uids) > 0 {
|
| 769 |
+
if a := p.AuthByUID(uids[0]); a != nil {
|
| 770 |
+
// FetchGlobalModelInfos 无错误返回(内部负缓存自行节流),
|
| 771 |
+
// 仅按结果条数判断是否拿到目录。
|
| 772 |
+
if infos := up.FetchGlobalModelInfos(a); len(infos) == 0 {
|
| 773 |
+
log.Printf("WARN: [upstream] warm model rates (global): empty model list")
|
| 774 |
+
} else {
|
| 775 |
+
log.Printf("[upstream] warm model rates: global ok (%d models)", len(infos))
|
| 776 |
+
}
|
| 777 |
+
}
|
| 778 |
+
}
|
| 779 |
+
}
|
| 780 |
+
}
|
| 781 |
+
|
| 782 |
+
// listenBanner 组装启动横幅。api_key 的来源必须写明(issue #155:改了 config.json 却不
|
| 783 |
+
// 生效,旧日志只写 api_key=true,看不出是 WB2A_API_KEY 覆盖了文件还是改错了文件),
|
| 784 |
+
// 密钥本身只出掩码。path 传「实际加载的那份」,退回默认时传空。
|
| 785 |
+
func listenBanner(listen, path, key string) string {
|
| 786 |
+
return fmt.Sprintf("workbuddy2api listening on %s (api_key=%s, 来源 %s),管理面板 http://127.0.0.1%s/panel/",
|
| 787 |
+
listen, maskSecret(key), apiKeySource(path), panelListenPath(listen))
|
| 788 |
+
}
|
| 789 |
+
|
| 790 |
+
// apiKeySource 报生效的 api_key 来自哪里,顺序同 applyEnv:env 非空即覆盖文件。
|
| 791 |
+
func apiKeySource(path string) string {
|
| 792 |
+
if os.Getenv("WB2A_API_KEY") != "" {
|
| 793 |
+
return "环境变量 WB2A_API_KEY"
|
| 794 |
+
}
|
| 795 |
+
if path == "" {
|
| 796 |
+
return "内置默认值"
|
| 797 |
+
}
|
| 798 |
+
return "配置文件 " + path
|
| 799 |
+
}
|
| 800 |
+
|
| 801 |
+
// maskSecret 只留首尾各两位便于对号入座;不足 8 位或未设置则整条隐去。
|
| 802 |
+
func maskSecret(s string) string {
|
| 803 |
+
if s == "" {
|
| 804 |
+
return "(未设置)"
|
| 805 |
+
}
|
| 806 |
+
r := []rune(s)
|
| 807 |
+
if len(r) < 8 {
|
| 808 |
+
return strings.Repeat("*", len(r))
|
| 809 |
+
}
|
| 810 |
+
return string(r[:2]) + strings.Repeat("*", len(r)-4) + string(r[len(r)-2:])
|
| 811 |
+
}
|
| 812 |
+
|
| 813 |
+
// panelListenPath 从 listen 地址提取 ":port" 形式,用于启动日志拼面板 URL
|
| 814 |
+
// (":7863" 或 "0.0.0.0:7863" → ":7863";异常输入原样返回)。
|
| 815 |
+
func panelListenPath(listen string) string {
|
| 816 |
+
for i := len(listen) - 1; i >= 0; i-- {
|
| 817 |
+
if listen[i] == ':' {
|
| 818 |
+
return listen[i:]
|
| 819 |
+
}
|
| 820 |
+
}
|
| 821 |
+
return listen
|
| 822 |
+
}
|
| 823 |
+
|
| 824 |
+
// saveConfig 面板保存配置:校验 → 落盘 → 热应用 → 返回需重启的字段列表。
|
| 825 |
+
//
|
| 826 |
+
// 热生效范围(设计取舍):
|
| 827 |
+
// - api_key / cooldown.soft_rate / features.sanitize_blacklist_fingerprints → livecfg 快照
|
| 828 |
+
// - pool.* → pool.SetBreaker/SetMaxInFlight/SetSoftRateMax/SetWeights/SetCostExploreInterval/SetPreferExpiring(含快过期窗口)/SetAccountPriority/SetAccountShare/SetCreditFloor
|
| 829 |
+
// - schedule.* → scheduler.Reconfigure/SetBalanceInterval/SetExpiringSoonWindow
|
| 830 |
+
//
|
| 831 |
+
// 需重启(涉及监听地址、HTTP client 超时、auth_dir 等装配期依赖):
|
| 832 |
+
// - listen / auth_dir / state_file / upstream.* / upstash.* / session_sticky.*(TTL 类)
|
| 833 |
+
//
|
| 834 |
+
// 落盘用"先写 tmp 再 rename"原子替换,且优先保留磁盘上的原始 JSON 结构(只改
|
| 835 |
+
// 面板表单覆盖到的键),避免把用户手写的注释性字段/未知键洗掉——这里直接整体
|
| 836 |
+
// 序列化校验后的配置,未知键在 json.Unmarshal 时已丢失,故先合并原始 map。
|
| 837 |
+
// writeConfigInPlace 原地重写配置(O_TRUNC),给两种「原子替换做不到」的部署形态复用:
|
| 838 |
+
// 单文件 bind mount 不能被 rename 覆盖(EBUSY);配置目录不可写但文件可写(EACCES,
|
| 839 |
+
// Docker 以 PUID 运行而 /app 属主是镜像内的 app,见 issue #134)。代价是失去原子性:
|
| 840 |
+
// 写失败时文件可能只剩半截 —— 这两种形态下本来也没有可用 tmp 的目录。
|
| 841 |
+
func writeConfigInPlace(path string, out []byte) error {
|
| 842 |
+
f, err := os.OpenFile(path, os.O_WRONLY|os.O_TRUNC, 0o600)
|
| 843 |
+
if err != nil {
|
| 844 |
+
return err
|
| 845 |
+
}
|
| 846 |
+
_, werr := f.Write(out)
|
| 847 |
+
if werr == nil {
|
| 848 |
+
werr = f.Sync()
|
| 849 |
+
}
|
| 850 |
+
if cerr := f.Close(); werr == nil {
|
| 851 |
+
werr = cerr
|
| 852 |
+
}
|
| 853 |
+
return werr
|
| 854 |
+
}
|
| 855 |
+
|
| 856 |
+
// effortPolicyOf 把 config thinking 节转成 upstream 运行时策略。nil 配置/
|
| 857 |
+
// 未启用时返回的策略由 Client.SetEffortPolicy 统一处理(Enabled=false 即不生效)。
|
| 858 |
+
func effortPolicyOf(cfg *Config) *upstream.EffortPolicy {
|
| 859 |
+
if cfg == nil {
|
| 860 |
+
return nil
|
| 861 |
+
}
|
| 862 |
+
return &upstream.EffortPolicy{
|
| 863 |
+
Enabled: cfg.Thinking.Enabled,
|
| 864 |
+
DefaultEffort: cfg.Thinking.DefaultEffort,
|
| 865 |
+
ClientPriority: cfg.Thinking.ClientPriority,
|
| 866 |
+
OverrideScope: cfg.Thinking.OverrideScope,
|
| 867 |
+
ModelDefaults: cfg.Thinking.ModelDefaults,
|
| 868 |
+
}
|
| 869 |
+
}
|
| 870 |
+
|
| 871 |
+
// updateSettingsFrom 把 config 的 update 段翻成 updater.Settings(issue #198)。
|
| 872 |
+
//
|
| 873 |
+
// 单独抽成函数是因为「启动装配」与「配置保存后热更新」两处必须用同一口 IO——
|
| 874 |
+
// 各写一份字面量时,新增字段必然只接一处(热更新丢了 proxy/mirror,面板看着
|
| 875 |
+
// 保存成功、实际还是旧通道)。
|
| 876 |
+
//
|
| 877 |
+
// proxy_from_env 在 config 里是 *bool:JSON 缺键 = 未表态 → 沿用环境变量(历史
|
| 878 |
+
// 行为,也是绝大多数部署的实际形态);显式 false 才完全不读环境。
|
| 879 |
+
func updateSettingsFrom(u *Config) updater.Settings {
|
| 880 |
+
fromEnv := true
|
| 881 |
+
if u.Update.ProxyFromEnv != nil {
|
| 882 |
+
fromEnv = *u.Update.ProxyFromEnv
|
| 883 |
+
}
|
| 884 |
+
return updater.Settings{
|
| 885 |
+
AutoEnabled: u.Update.AutoEnabled,
|
| 886 |
+
AutoTime: u.Update.AutoTime,
|
| 887 |
+
Proxy: u.Update.Proxy,
|
| 888 |
+
ProxyFromEnv: fromEnv,
|
| 889 |
+
Mirror: u.Update.Mirror,
|
| 890 |
+
}
|
| 891 |
+
}
|
| 892 |
+
|
| 893 |
+
func saveConfig(raw []byte, path string, live *livecfg.Holder, p *pool.Pool, up *upstream.Client, sch *scheduler.Scheduler, gw *server.Handler, pn *panel.Panel, running ...*Config) ([]string, error) {
|
| 894 |
+
// 1) 解析原始 JSON 为 map(保留用户手写的未知键),再叠加面板提交的键。
|
| 895 |
+
oldRaw, err := os.ReadFile(path)
|
| 896 |
+
if err != nil {
|
| 897 |
+
return nil, fmt.Errorf("read current config: %w", err)
|
| 898 |
+
}
|
| 899 |
+
// 重启清单的比较基线:优先用「运行中配置」(含 env 覆盖与启动归一化);
|
| 900 |
+
// 未传入(测试/旧调用)时退化为磁盘旧值。见 restartRequiredFields。
|
| 901 |
+
previous, err := ParseConfig(oldRaw)
|
| 902 |
+
if err != nil {
|
| 903 |
+
return nil, fmt.Errorf("parse current config: %w", err)
|
| 904 |
+
}
|
| 905 |
+
baseline := previous
|
| 906 |
+
if len(running) > 0 && running[0] != nil {
|
| 907 |
+
baseline = running[0]
|
| 908 |
+
}
|
| 909 |
+
var cur, incoming map[string]any
|
| 910 |
+
if err := json.Unmarshal(oldRaw, &cur); err != nil {
|
| 911 |
+
cur = map[string]any{}
|
| 912 |
+
}
|
| 913 |
+
if err := json.Unmarshal(raw, &incoming); err != nil {
|
| 914 |
+
return nil, fmt.Errorf("parse submitted config: %w", err)
|
| 915 |
+
}
|
| 916 |
+
merged := mergeConfigMaps(cur, incoming)
|
| 917 |
+
|
| 918 |
+
// 2) 校验(与启动同一套 Default+normalize),失败直接返回、不落盘。
|
| 919 |
+
newCfg, err := ParseConfig(mergedJSON(merged))
|
| 920 |
+
if err != nil {
|
| 921 |
+
return nil, err
|
| 922 |
+
}
|
| 923 |
+
// 环境变量覆盖与启动同优先级:保存路径同样应用(否则 env 托管字段会被文件值
|
| 924 |
+
// 抢班——面板显示 env 值、运行却按文件值)。移植上游 PR #104。
|
| 925 |
+
applyEnv(newCfg)
|
| 926 |
+
if err := newCfg.normalize(); err != nil {
|
| 927 |
+
return nil, err
|
| 928 |
+
}
|
| 929 |
+
|
| 930 |
+
// 3) 落盘(原子替换)。
|
| 931 |
+
out, err := json.MarshalIndent(merged, "", " ")
|
| 932 |
+
if err != nil {
|
| 933 |
+
return nil, fmt.Errorf("marshal config: %w", err)
|
| 934 |
+
}
|
| 935 |
+
// safefile:tmp fsync 后才 rename,并把上一份有效配置留成 config.json.bak
|
| 936 |
+
// —— 掉电把 config.json 留成半截时,下次启动能捡回上一份。
|
| 937 |
+
if err := safefile.WriteKeep(path, out, 0o600); err != nil {
|
| 938 |
+
switch {
|
| 939 |
+
case errors.Is(err, fs.ErrPermission):
|
| 940 |
+
// 配置所在目录不可写:Docker 里 /app 属主是镜像内的 app(10001),而 compose 让
|
| 941 |
+
// 容器以 PUID(如 1000) 运行 —— 挂载进去的 config.json 可写、目录不行,于是原子
|
| 942 |
+
// 替换连 tmp 都建不出来(issue #134:write config: open /app/config.json.tmp:
|
| 943 |
+
// permission denied)。文件本身可写就退回原地重写,不再要求目录可写。
|
| 944 |
+
if inPlaceErr := writeConfigInPlace(path, out); inPlaceErr != nil {
|
| 945 |
+
return nil, fmt.Errorf("write config (目录不可写,原地重写也失败): %w", inPlaceErr)
|
| 946 |
+
}
|
| 947 |
+
case errors.Is(err, syscall.EBUSY):
|
| 948 |
+
// A single-file Docker bind mount cannot be renamed over its mount
|
| 949 |
+
// target (Linux returns EBUSY / "device or resource busy"). Keep the
|
| 950 |
+
// atomic path for regular files, but update the mounted file in place
|
| 951 |
+
// for this specific deployment shape.
|
| 952 |
+
if inPlaceErr := writeConfigInPlace(path, out); inPlaceErr != nil {
|
| 953 |
+
return nil, fmt.Errorf("replace config (bind mount fallback): %w", inPlaceErr)
|
| 954 |
+
}
|
| 955 |
+
default:
|
| 956 |
+
return nil, fmt.Errorf("write config: %w", err)
|
| 957 |
+
}
|
| 958 |
+
}
|
| 959 |
+
|
| 960 |
+
// 4) 热应用:能立即生效的字段全部应用,并列出仍需重启的字段。
|
| 961 |
+
// 白名单同步重建(issue #68):面板保存 models.allowed 后即时生效。
|
| 962 |
+
newAllowedModels, newAllowlistEnabled := livecfg.NormalizeAllowedModels(newCfg.Models.Allowed)
|
| 963 |
+
live.Store(livecfg.Snapshot{
|
| 964 |
+
APIKey: newCfg.APIKey,
|
| 965 |
+
SoftCooldown: newCfg.SoftRateDur,
|
| 966 |
+
SanitizeFingerprints: newCfg.Features.SanitizeBlacklistFingerprints,
|
| 967 |
+
EmbeddingsEnabled: newCfg.Features.EmbeddingsEnabled,
|
| 968 |
+
WatermarkStripEnabled: newCfg.Features.WatermarkStripEnabled,
|
| 969 |
+
RecordClientInfo: newCfg.Logging.RequestClientInfo,
|
| 970 |
+
RecordContext: newCfg.Logging.RequestArchiveContext,
|
| 971 |
+
HiddenModels: livecfg.NormalizeHiddenModels(newCfg.Models.Hidden),
|
| 972 |
+
// 白名单热生效:与 HiddenModels 同一条快照重建通路(issue #68)。
|
| 973 |
+
AllowedModels: newAllowedModels,
|
| 974 |
+
AllowlistEnabled: newAllowlistEnabled,
|
| 975 |
+
ModelAliases: livecfg.NormalizeModelAliases(newCfg.Models.Aliases),
|
| 976 |
+
// 思考档位策略镜像:与 up.SetEffortPolicy 同批热更新,面板立即回显新生效值。
|
| 977 |
+
ThinkingEnabled: newCfg.Thinking.Enabled,
|
| 978 |
+
ThinkingDefaultEffort: newCfg.Thinking.DefaultEffort,
|
| 979 |
+
ThinkingClientPriority: newCfg.Thinking.ClientPriority,
|
| 980 |
+
ThinkingOverrideScope: newCfg.Thinking.OverrideScope,
|
| 981 |
+
ThinkingModelDefaults: newCfg.Thinking.ModelDefaults,
|
| 982 |
+
ModelFallback: newCfg.Pool.ModelFallback,
|
| 983 |
+
})
|
| 984 |
+
up.SanitizeFingerprints.Store(newCfg.Features.SanitizeBlacklistFingerprints)
|
| 985 |
+
up.SanitizeBrandScope.Store(newCfg.Features.SanitizeBrandScope)
|
| 986 |
+
up.KeepRecentRounds.Store(int64(newCfg.Prompt.KeepRecentRounds))
|
| 987 |
+
// 思考档位策略热生效:改默认档 / 切换客户端优先或作用域后,下一次 chat 即按新策略。
|
| 988 |
+
up.SetEffortPolicy(effortPolicyOf(newCfg))
|
| 989 |
+
p.SetBreaker(newCfg.Pool.BreakerThreshold, newCfg.BreakerCooldownDur, newCfg.BreakerCooldownMaxD)
|
| 990 |
+
p.SetMaxInFlight(newCfg.Pool.MaxInFlight)
|
| 991 |
+
p.SetMaxInFlightGlobal(newCfg.Pool.MaxInFlightGlobal)
|
| 992 |
+
p.SetDegrade(newCfg.Pool.DegradeThreshold, newCfg.DegradeCooldownDur, newCfg.DegradeCooldownMaxD)
|
| 993 |
+
p.SetSoftRateMax(newCfg.SoftRateMaxDur)
|
| 994 |
+
p.SetCostExploreInterval(newCfg.CostExploreIntervalDur) // costTier 探索窗口热生效(0 关停)
|
| 995 |
+
p.SetBalanceWindow(newCfg.BalanceWindowDur) // 窗口用量调度热生效(0 关停)
|
| 996 |
+
p.SetCreditFloor(newCfg.Pool.CreditFloor) // 积分保底热生效(0 = 关闭)
|
| 997 |
+
p.SetCreditFloorMaxRate(newCfg.Pool.CreditFloorMaxRate) // 保底倍率上限热生效(0 = 严格模式)
|
| 998 |
+
p.SetWeights(newCfg.Pool.IdleWeightPerHour, newCfg.Pool.IdleWeightMax)
|
| 999 |
+
p.SetPreferExpiring(newCfg.Pool.PreferExpiring, newCfg.ExpiringSoonDur)
|
| 1000 |
+
sch.SetExpiringSoonWindow(newCfg.ExpiringSoonDur)
|
| 1001 |
+
sch.SetKeepaliveRefreshWindow(newCfg.KeepaliveRefreshWindowDur)
|
| 1002 |
+
p.SetReserveCredits(*newCfg.Pool.ReserveCredits) // 保留积分热生效(0 = 关闭,缺省 10)
|
| 1003 |
+
p.SetReserveCreditsByRealm(newCfg.Pool.ReserveCreditsByRealm) // 按域覆盖热生效(issue #147)
|
| 1004 |
+
p.SetAccountPriority(newCfg.Pool.AccountPriority) // 账号优先级/占比热生效(issue #62)
|
| 1005 |
+
p.SetAccountShare(newCfg.Pool.AccountShare)
|
| 1006 |
+
p.SetStrategy(newCfg.Pool.SelectionStrategy) // 选号策略热生效
|
| 1007 |
+
sch.Reconfigure(scheduler.ScheduleParams{
|
| 1008 |
+
CheckinHours: newCfg.Schedule.CheckinHours,
|
| 1009 |
+
TravelHours: newCfg.Schedule.TravelHours,
|
| 1010 |
+
ActivityHours: newCfg.Schedule.ActivityHours,
|
| 1011 |
+
KeepaliveHours: newCfg.Schedule.KeepaliveHours,
|
| 1012 |
+
GrowthHours: newCfg.Schedule.GrowthHours,
|
| 1013 |
+
|
| 1014 |
+
CheckinDisabled: !newCfg.Schedule.CheckinEnabled,
|
| 1015 |
+
TravelDisabled: !newCfg.Schedule.TravelEnabled,
|
| 1016 |
+
ActivityDisabled: !newCfg.Schedule.ActivityEnabled,
|
| 1017 |
+
WebActivityDisabled: !newCfg.Schedule.WebActivityEnabled,
|
| 1018 |
+
KeepaliveDisabled: !newCfg.Schedule.KeepaliveEnabled,
|
| 1019 |
+
GrowthDisabled: !newCfg.Schedule.GrowthEnabled,
|
| 1020 |
+
IncludeDisabledInTasks: newCfg.Schedule.IncludeDisabledInTasks,
|
| 1021 |
+
|
| 1022 |
+
JitterMinutes: newCfg.Schedule.JitterMinutes,
|
| 1023 |
+
AccountSpreadMinutes: newCfg.Schedule.AccountSpreadMinutes,
|
| 1024 |
+
AccountSpreadMinGapSeconds: newCfg.Schedule.AccountSpreadMinGapSeconds,
|
| 1025 |
+
})
|
| 1026 |
+
sch.SetBalanceInterval(newCfg.BalanceRefreshInterval)
|
| 1027 |
+
sch.SetTaskSweepInterval(newCfg.TaskSweepInterval)
|
| 1028 |
+
sch.SetJitter(newCfg.Schedule.BalanceRefreshJitterPermill, newCfg.Schedule.TaskSweepJitterPermill)
|
| 1029 |
+
sch.SetMakeupCardsPerRound(newCfg.Schedule.MakeupCardsPerRound)
|
| 1030 |
+
if pn != nil {
|
| 1031 |
+
pn.SetGrowthConcurrency(newCfg.Schedule.GrowthConcurrency) // 排程轮次并发热生效
|
| 1032 |
+
}
|
| 1033 |
+
if gw != nil {
|
| 1034 |
+
gw.SetBudgetLimit(newCfg.Budget.DailyCreditLimit)
|
| 1035 |
+
gw.SetBudgetGuards(newCfg.Budget.BurstCreditLimit, newCfg.Budget.CacheLowRate)
|
| 1036 |
+
}
|
| 1037 |
+
|
| 1038 |
+
return restartRequiredFields(baseline, newCfg), nil
|
| 1039 |
+
}
|
| 1040 |
+
|
| 1041 |
+
// applyCNChatBase 把 config cn.chat_base / cn.billing_base 装配进上游 client;
|
| 1042 |
+
// 空则保留内置默认,老配置(无 cn 段)行为不变。
|
| 1043 |
+
func applyCNChatBase(up *upstream.Client, cfg *Config) {
|
| 1044 |
+
if cfg.CN.ChatBase != "" {
|
| 1045 |
+
up.ChatBaseCN = cfg.CN.ChatBase
|
| 1046 |
+
}
|
| 1047 |
+
if cfg.CN.BillingBase != "" {
|
| 1048 |
+
up.BillingBaseCN = cfg.CN.BillingBase
|
| 1049 |
+
}
|
| 1050 |
+
}
|
| 1051 |
+
|
| 1052 |
+
// restartRequiredFields 比较运行中装配值与新配置(有运行配置时以它为准,否则退化
|
| 1053 |
+
// 为磁盘旧值),只报告「确实变化且无法热生效」的字段——第二次保存不再重复携带上
|
| 1054 |
+
// 一处的待重启项、改回原值即自动清除(无独立的 pending 集合)。移植上游 PR #104;
|
| 1055 |
+
// 字段集保留本 fork 自有项(admin/metrics/alerting 整块)。
|
| 1056 |
+
func restartRequiredFields(current, next *Config) []string {
|
| 1057 |
+
var out []string
|
| 1058 |
+
changed := func(name string, before, after any) {
|
| 1059 |
+
if !reflect.DeepEqual(before, after) {
|
| 1060 |
+
out = append(out, name)
|
| 1061 |
+
}
|
| 1062 |
+
}
|
| 1063 |
+
changed("listen", current.Listen, next.Listen)
|
| 1064 |
+
changed("auth_dir", current.AuthDir, next.AuthDir)
|
| 1065 |
+
changed("state_file", current.StateFile, next.StateFile)
|
| 1066 |
+
changed("upstream.timeout_seconds", current.Upstream.TimeoutSeconds, next.Upstream.TimeoutSeconds)
|
| 1067 |
+
changed("upstream.header_timeout_seconds", current.Upstream.HeaderTimeoutSeconds, next.Upstream.HeaderTimeoutSeconds)
|
| 1068 |
+
changed("upstream.idle_timeout_seconds", current.Upstream.IdleTimeoutSeconds, next.Upstream.IdleTimeoutSeconds)
|
| 1069 |
+
changed("upstream.user_agent", current.Upstream.UserAgent, next.Upstream.UserAgent)
|
| 1070 |
+
changed("upstream.client_version", current.Upstream.ClientVersion, next.Upstream.ClientVersion)
|
| 1071 |
+
changed("upstream.cli_version", current.Upstream.CliVersion, next.Upstream.CliVersion)
|
| 1072 |
+
changed("upstream.client_name", current.Upstream.ClientName, next.Upstream.ClientName)
|
| 1073 |
+
changed("upstream.device_token", current.Upstream.DeviceToken, next.Upstream.DeviceToken)
|
| 1074 |
+
changed("upstream.device_token_file", current.Upstream.DeviceTokenFile, next.Upstream.DeviceTokenFile)
|
| 1075 |
+
changed("upstream.passthrough_ip", current.Upstream.PassthroughIP, next.Upstream.PassthroughIP)
|
| 1076 |
+
// cn.chat_base / cn.billing_base 同样只在装配期写进上游 client(请求路径并发读取,不做热改)。
|
| 1077 |
+
changed("cn.chat_base", current.CN.ChatBase, next.CN.ChatBase)
|
| 1078 |
+
changed("cn.billing_base", current.CN.BillingBase, next.CN.BillingBase)
|
| 1079 |
+
changed("global.enabled", current.Global.Enabled, next.Global.Enabled)
|
| 1080 |
+
changed("global.chat_base", current.Global.ChatBase, next.Global.ChatBase)
|
| 1081 |
+
changed("global.billing_base", current.Global.BillingBase, next.Global.BillingBase)
|
| 1082 |
+
changed("prompt.mode", current.Prompt.Mode, next.Prompt.Mode)
|
| 1083 |
+
changed("prompt.file", current.Prompt.File, next.Prompt.File)
|
| 1084 |
+
changed("prompt.text", current.PromptText, next.PromptText)
|
| 1085 |
+
changed("upstash.url", current.Upstash.URL, next.Upstash.URL)
|
| 1086 |
+
changed("upstash.token", current.Upstash.Token, next.Upstash.Token)
|
| 1087 |
+
changed("session_sticky.enabled", current.SessionSticky.Enabled, next.SessionSticky.Enabled)
|
| 1088 |
+
changed("session_sticky.ttl", current.SessionTTL, next.SessionTTL)
|
| 1089 |
+
changed("session_sticky.gc_interval", current.SessionGCInterval, next.SessionGCInterval)
|
| 1090 |
+
changed("admin", current.Admin, next.Admin)
|
| 1091 |
+
changed("metrics", current.Metrics, next.Metrics)
|
| 1092 |
+
changed("alerting", current.Alerting, next.Alerting)
|
| 1093 |
+
changed("logging.request_archive_enabled", current.Logging.RequestArchiveEnabled, next.Logging.RequestArchiveEnabled)
|
| 1094 |
+
changed("logging.request_retention_days", current.Logging.RequestRetentionDays, next.Logging.RequestRetentionDays)
|
| 1095 |
+
changed("logging.request_archive_max_mb", current.Logging.RequestArchiveMaxMB, next.Logging.RequestArchiveMaxMB)
|
| 1096 |
+
changed("server.read_timeout", current.Server.ReadTimeout, next.Server.ReadTimeout)
|
| 1097 |
+
changed("server.shutdown_timeout", current.Server.ShutdownTimeout, next.Server.ShutdownTimeout)
|
| 1098 |
+
return out
|
| 1099 |
+
}
|
| 1100 |
+
|
| 1101 |
+
// mergeConfigMaps 把 incoming 深合并进 cur(原地),返回 cur。
|
| 1102 |
+
// 对嵌套对象逐键覆盖而不是整体替换:面板表单只提交它管理的键,
|
| 1103 |
+
// 未提交的兄弟键(含用户手写的未知键)保持原样。
|
| 1104 |
+
func mergeConfigMaps(cur, incoming map[string]any) map[string]any {
|
| 1105 |
+
for k, v := range incoming {
|
| 1106 |
+
if inMap, ok := v.(map[string]any); ok {
|
| 1107 |
+
if curMap, ok := cur[k].(map[string]any); ok {
|
| 1108 |
+
cur[k] = mergeConfigMaps(curMap, inMap)
|
| 1109 |
+
continue
|
| 1110 |
+
}
|
| 1111 |
+
}
|
| 1112 |
+
cur[k] = v
|
| 1113 |
+
}
|
| 1114 |
+
return cur
|
| 1115 |
+
}
|
| 1116 |
+
|
| 1117 |
+
// mergedJSON 把合并后的 map 序列化回 JSON(供 ParseConfig 校验)。
|
| 1118 |
+
func mergedJSON(m map[string]any) []byte {
|
| 1119 |
+
b, err := json.Marshal(m)
|
| 1120 |
+
if err != nil {
|
| 1121 |
+
return []byte("{}")
|
| 1122 |
+
}
|
| 1123 |
+
return b
|
| 1124 |
+
}
|
cmd/server/upstream_port_config_test.go
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
package main
|
| 2 |
+
|
| 3 |
+
import "testing"
|
| 4 |
+
|
| 5 |
+
func TestBudgetAndJitterRejectBadValues(t *testing.T) {
|
| 6 |
+
c := Default()
|
| 7 |
+
c.Budget.DailyCreditLimit = -1
|
| 8 |
+
if err := c.normalize(); err == nil {
|
| 9 |
+
t.Fatal("negative budget should fail")
|
| 10 |
+
}
|
| 11 |
+
c = Default()
|
| 12 |
+
c.Schedule.JitterMinutes = 1441
|
| 13 |
+
if err := c.normalize(); err == nil {
|
| 14 |
+
t.Fatal("jitter over a day should fail")
|
| 15 |
+
}
|
| 16 |
+
c = Default()
|
| 17 |
+
c.Alerting.Enabled = true
|
| 18 |
+
if err := c.normalize(); err == nil {
|
| 19 |
+
t.Fatal("alerting without webhook should fail")
|
| 20 |
+
}
|
| 21 |
+
}
|
cmd/server/wiring.go
CHANGED
|
@@ -1,24 +1,40 @@
|
|
| 1 |
-
package main
|
| 2 |
-
|
| 3 |
-
import (
|
| 4 |
-
"github.com/
|
| 5 |
-
"github.com/
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
//
|
| 10 |
-
//
|
| 11 |
-
//
|
| 12 |
-
//
|
| 13 |
-
//
|
| 14 |
-
//
|
| 15 |
-
//
|
| 16 |
-
//
|
| 17 |
-
//
|
| 18 |
-
//
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
package main
|
| 2 |
+
|
| 3 |
+
import (
|
| 4 |
+
"github.com/misakano7545/workbuddy2api-panel/internal/alert"
|
| 5 |
+
"github.com/misakano7545/workbuddy2api-panel/internal/pool"
|
| 6 |
+
"github.com/misakano7545/workbuddy2api-panel/internal/server"
|
| 7 |
+
)
|
| 8 |
+
|
| 9 |
+
// realmAwareAvailableForModel 构造会话粘性路由按模型可用口径的 realm 感知闭包。
|
| 10 |
+
//
|
| 11 |
+
// 粘性分配的模型名可能带 realm 前缀("global:gpt-5.4" / "cn:glm-5.2"):必须按前缀剥出
|
| 12 |
+
// realm + bareModel,再交给分池选号域过滤——否则裸名取池子全集,global 号会被粘性分配给
|
| 13 |
+
// CN 前缀请求(跨 realm 泄漏)。裸名/显式 cn → cn 集合;global: → global 集合。
|
| 14 |
+
//
|
| 15 |
+
// realm 为空串时 pool.WeightedAvailableUIDsForModelRealm 退化为现状
|
| 16 |
+
// (AvailableUIDsForModel),老调用(无前缀模型名)语义零改动。
|
| 17 |
+
//
|
| 18 |
+
// 返回列表可能对快过期账号重复同一 UID,作为虚拟实例权重;会话哈希分配无需感知
|
| 19 |
+
// 权重细节,已有绑定的快路径仍直接返回原账号,不做迁移。
|
| 20 |
+
func realmAwareAvailableForModel(p *pool.Pool) func(model string) []string {
|
| 21 |
+
return func(model string) []string {
|
| 22 |
+
realm, bare := server.ResolveModel(model)
|
| 23 |
+
return p.WeightedAvailableUIDsForModelRealm(bare, realm)
|
| 24 |
+
}
|
| 25 |
+
}
|
| 26 |
+
|
| 27 |
+
type alertSource struct {
|
| 28 |
+
pool *pool.Pool
|
| 29 |
+
h *server.Handler
|
| 30 |
+
}
|
| 31 |
+
|
| 32 |
+
func (s alertSource) Health(realm string) alert.Health {
|
| 33 |
+
h := s.pool.RealmHealth(realm)
|
| 34 |
+
return alert.Health{
|
| 35 |
+
Total: h.Total, Healthy: h.Healthy, Cooling: h.Cooling, Disabled: h.Disabled,
|
| 36 |
+
Breaker: h.Breaker, Degraded: h.Degraded, InFlight: h.InFlight,
|
| 37 |
+
}
|
| 38 |
+
}
|
| 39 |
+
|
| 40 |
+
func (s alertSource) WAFActive() bool { return s.h.WAFActive() }
|
cmd/signin/main.go
CHANGED
|
@@ -1,140 +1,143 @@
|
|
| 1 |
-
// signin 一次性批量签到工具:遍历 ./auths/workbuddy-*.json 全部账号,
|
| 2 |
-
// 自动 RefreshToken(过期时),逐个调 daily-checkin,顺手查余额。
|
| 3 |
-
package main
|
| 4 |
-
|
| 5 |
-
import (
|
| 6 |
-
"fmt"
|
| 7 |
-
"log"
|
| 8 |
-
"os"
|
| 9 |
-
"path/filepath"
|
| 10 |
-
"sort"
|
| 11 |
-
"strings"
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
"github.com/
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
r.
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
r.
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
fmt.Printf("
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
|
| 134 |
-
|
| 135 |
-
|
| 136 |
-
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
// signin 一次性批量签到工具:遍历 ./auths/workbuddy-*.json 全部账号,
|
| 2 |
+
// 自动 RefreshToken(过期时),逐个调 daily-checkin,顺手查余额。
|
| 3 |
+
package main
|
| 4 |
+
|
| 5 |
+
import (
|
| 6 |
+
"fmt"
|
| 7 |
+
"log"
|
| 8 |
+
"os"
|
| 9 |
+
"path/filepath"
|
| 10 |
+
"sort"
|
| 11 |
+
"strings"
|
| 12 |
+
"time"
|
| 13 |
+
|
| 14 |
+
"github.com/misakano7545/workbuddy2api-panel/internal/auth"
|
| 15 |
+
"github.com/misakano7545/workbuddy2api-panel/internal/upstream"
|
| 16 |
+
)
|
| 17 |
+
|
| 18 |
+
type row struct {
|
| 19 |
+
file string
|
| 20 |
+
uid string
|
| 21 |
+
nick string
|
| 22 |
+
status string // OK | ALREADY | FAIL | AUTH_INVALID | LOAD_ERR
|
| 23 |
+
detail string
|
| 24 |
+
remain int64
|
| 25 |
+
hasQuota bool
|
| 26 |
+
}
|
| 27 |
+
|
| 28 |
+
func main() {
|
| 29 |
+
dir := "auths"
|
| 30 |
+
if len(os.Args) > 1 {
|
| 31 |
+
dir = os.Args[1]
|
| 32 |
+
}
|
| 33 |
+
files, err := filepath.Glob(filepath.Join(dir, "workbuddy-*.json"))
|
| 34 |
+
if err != nil || len(files) == 0 {
|
| 35 |
+
fmt.Fprintf(os.Stderr, "no auth files in %s\n", dir)
|
| 36 |
+
os.Exit(1)
|
| 37 |
+
}
|
| 38 |
+
sort.Strings(files)
|
| 39 |
+
up := upstream.New()
|
| 40 |
+
|
| 41 |
+
var rows []row
|
| 42 |
+
okN, alreadyN, failN := 0, 0, 0
|
| 43 |
+
for _, f := range files {
|
| 44 |
+
r := row{file: filepath.Base(f)}
|
| 45 |
+
raw, err := os.ReadFile(f)
|
| 46 |
+
if err != nil {
|
| 47 |
+
r.status, r.detail = "LOAD_ERR", err.Error()
|
| 48 |
+
rows = append(rows, r)
|
| 49 |
+
failN++
|
| 50 |
+
continue
|
| 51 |
+
}
|
| 52 |
+
a, err := auth.Parse(raw)
|
| 53 |
+
if err != nil {
|
| 54 |
+
r.status, r.detail = "LOAD_ERR", err.Error()
|
| 55 |
+
rows = append(rows, r)
|
| 56 |
+
failN++
|
| 57 |
+
continue
|
| 58 |
+
}
|
| 59 |
+
a.FilePath = f
|
| 60 |
+
r.uid, r.nick = a.UID, a.Nickname
|
| 61 |
+
|
| 62 |
+
// refresh 过期 token
|
| 63 |
+
if a.NeedsRefresh(2 * time.Hour) {
|
| 64 |
+
if err := up.RefreshTokenIfNeeded(a, 2*time.Hour); err != nil {
|
| 65 |
+
if ue, ok := err.(*upstream.Error); ok && ue.Kind == upstream.ErrSessionDead {
|
| 66 |
+
r.status = "AUTH_INVALID"
|
| 67 |
+
} else {
|
| 68 |
+
r.status = "FAIL"
|
| 69 |
+
}
|
| 70 |
+
r.detail = "refresh: " + short(err.Error())
|
| 71 |
+
rows = append(rows, r)
|
| 72 |
+
failN++
|
| 73 |
+
continue
|
| 74 |
+
}
|
| 75 |
+
// refresh 后写回文件(权限问题已修复);落盘失败必须暴露,否则重启回旧 token
|
| 76 |
+
if err := a.SaveAtomicRetry(); err != nil {
|
| 77 |
+
log.Printf("signin %s save: %v", a.UID, err)
|
| 78 |
+
}
|
| 79 |
+
}
|
| 80 |
+
|
| 81 |
+
err = up.DailyCheckin(a)
|
| 82 |
+
switch {
|
| 83 |
+
case err == nil:
|
| 84 |
+
r.status = "OK"
|
| 85 |
+
okN++
|
| 86 |
+
default:
|
| 87 |
+
// DailyCheckin 已签到返回 code!=0 错误
|
| 88 |
+
if isAlready(err.Error()) {
|
| 89 |
+
r.status = "ALREADY"
|
| 90 |
+
r.detail = short(err.Error())
|
| 91 |
+
alreadyN++
|
| 92 |
+
} else {
|
| 93 |
+
r.status = "FAIL"
|
| 94 |
+
r.detail = short(err.Error())
|
| 95 |
+
failN++
|
| 96 |
+
}
|
| 97 |
+
}
|
| 98 |
+
// 顺手查余额
|
| 99 |
+
if remain, _, qerr := up.UserResource(a); qerr == nil {
|
| 100 |
+
r.remain, r.hasQuota = remain, true
|
| 101 |
+
}
|
| 102 |
+
rows = append(rows, r)
|
| 103 |
+
}
|
| 104 |
+
|
| 105 |
+
// 报告
|
| 106 |
+
fmt.Printf("uid | nick | status | remain | detail\n")
|
| 107 |
+
fmt.Printf("-------------------------------------+-------------+--------------+--------+------------------------------\n")
|
| 108 |
+
for _, r := range rows {
|
| 109 |
+
remain := "-"
|
| 110 |
+
if r.hasQuota {
|
| 111 |
+
remain = fmt.Sprintf("%d", r.remain)
|
| 112 |
+
}
|
| 113 |
+
fmt.Printf("%-36s | %-11s | %-12s | %-6s | %s\n",
|
| 114 |
+
trunc(r.uid, 36), trunc(r.nick, 11), r.status, remain, r.detail)
|
| 115 |
+
}
|
| 116 |
+
fmt.Printf("\ntotal=%d ok=%d already=%d fail=%d\n", len(rows), okN, alreadyN, failN)
|
| 117 |
+
}
|
| 118 |
+
|
| 119 |
+
// isAlready 已签到幂等判定。判据必须窄:上游业务错误统一是 HTTP 400 + code=%d
|
| 120 |
+
// msg=%s——早期版本宽匹配 "code=400" 甚至裸 "checkin",任何 400(参数缺失/风控/
|
| 121 |
+
// 活动未开启)都会被误判成 ALREADY,把真实失败静默掩盖成「已签到」。实测幂等码
|
| 122 |
+
// 是 code=10001(「今天已签到」),与文案判定并列兜底。
|
| 123 |
+
func isAlready(msg string) bool {
|
| 124 |
+
s := strings.ToLower(msg)
|
| 125 |
+
return strings.Contains(s, "已签到") ||
|
| 126 |
+
strings.Contains(s, "already") ||
|
| 127 |
+
strings.Contains(s, "code=10001")
|
| 128 |
+
}
|
| 129 |
+
|
| 130 |
+
func trunc(s string, n int) string {
|
| 131 |
+
if len(s) > n {
|
| 132 |
+
return s[:n]
|
| 133 |
+
}
|
| 134 |
+
return s
|
| 135 |
+
}
|
| 136 |
+
|
| 137 |
+
func short(s string) string {
|
| 138 |
+
s = strings.ReplaceAll(s, "\n", " ")
|
| 139 |
+
if len(s) > 60 {
|
| 140 |
+
return s[:60]
|
| 141 |
+
}
|
| 142 |
+
return s
|
| 143 |
+
}
|
cmd/signin/main_test.go
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
package main
|
| 2 |
+
|
| 3 |
+
import "testing"
|
| 4 |
+
|
| 5 |
+
// TestIsAlreadyNarrowMatching 已签到判定必须窄匹配:上游业务错误统一是
|
| 6 |
+
// HTTP 400 + code=%d,宽匹配 code=400 / 裸 "checkin" 会把参数缺失、风控、
|
| 7 |
+
// 「活动未开启」等真实失败全部误判成 ALREADY,静默掩盖失败。
|
| 8 |
+
func TestIsAlreadyNarrowMatching(t *testing.T) {
|
| 9 |
+
already := []string{
|
| 10 |
+
"upstream error: code=10001 今天已签到",
|
| 11 |
+
"code=10001 msg=already checked in today",
|
| 12 |
+
"今日已签到,明天再来吧",
|
| 13 |
+
"already claimed",
|
| 14 |
+
}
|
| 15 |
+
for _, m := range already {
|
| 16 |
+
if !isAlready(m) {
|
| 17 |
+
t.Errorf("isAlready(%q) = false, want true", m)
|
| 18 |
+
}
|
| 19 |
+
}
|
| 20 |
+
failures := []string{
|
| 21 |
+
"upstream error: code=400 msg=活动未开启", // 400 但非幂等码
|
| 22 |
+
"upstream error: code=400 msg=request illegal", // 风控/参数错误
|
| 23 |
+
"checkin activity not started", // 裸 checkin 字样不再误判
|
| 24 |
+
"http 500",
|
| 25 |
+
}
|
| 26 |
+
for _, m := range failures {
|
| 27 |
+
if isAlready(m) {
|
| 28 |
+
t.Errorf("isAlready(%q) = true, want false(真实失败被误判成已签到)", m)
|
| 29 |
+
}
|
| 30 |
+
}
|
| 31 |
+
}
|
cmd/sync/main.go
CHANGED
|
@@ -25,7 +25,7 @@ import (
|
|
| 25 |
"syscall"
|
| 26 |
"time"
|
| 27 |
|
| 28 |
-
"github.com/
|
| 29 |
)
|
| 30 |
|
| 31 |
// 退出码:0 一切就绪/已对齐;1 出错;2 有差异但未应用(status 模式,供脚本判分支)。
|
|
|
|
| 25 |
"syscall"
|
| 26 |
"time"
|
| 27 |
|
| 28 |
+
"github.com/misakano7545/workbuddy2api-panel/internal/syncer"
|
| 29 |
)
|
| 30 |
|
| 31 |
// 退出码:0 一切就绪/已对齐;1 出错;2 有差异但未应用(status 模式,供脚本判分支)。
|
cmd/trial/classify_test.go
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
package main
|
| 2 |
+
|
| 3 |
+
import (
|
| 4 |
+
"errors"
|
| 5 |
+
"testing"
|
| 6 |
+
)
|
| 7 |
+
|
| 8 |
+
// TestClassifyTrial 领取结果三态分类(纯函数,注释一直声称「供测试直接断言」,
|
| 9 |
+
// 此前没有这个测试)。
|
| 10 |
+
func TestClassifyTrial(t *testing.T) {
|
| 11 |
+
if st, msg := classifyTrial(true, nil); st != trialOK || msg != "trial granted" {
|
| 12 |
+
t.Errorf("claimed: %q %q", st, msg)
|
| 13 |
+
}
|
| 14 |
+
if st, _ := classifyTrial(false, nil); st != trialAlready {
|
| 15 |
+
t.Errorf("idempotent: %q", st)
|
| 16 |
+
}
|
| 17 |
+
wrapped := errors.New("code=14051 already claimed")
|
| 18 |
+
if st, msg := classifyTrial(false, wrapped); st != trialFailed || msg != wrapped.Error() {
|
| 19 |
+
t.Errorf("error: %q %q", st, msg)
|
| 20 |
+
}
|
| 21 |
+
}
|
cmd/trial/main.go
CHANGED
|
@@ -1,133 +1,133 @@
|
|
| 1 |
-
// trial 一次性批量领取 global trial 加油包:遍历 auths 下全部账号,
|
| 2 |
-
// 仅对 global 账号执行 /billing/ide/trial(CN 无此端点,明确提示不适用)。
|
| 3 |
-
//
|
| 4 |
-
// 用法:
|
| 5 |
-
//
|
| 6 |
-
// # 本地:在项目根目录(需 config.json + auths/ + data/)直接 run
|
| 7 |
-
// go run ./cmd/trial
|
| 8 |
-
//
|
| 9 |
-
// # 容器内:先 cp 进去再 exec
|
| 10 |
-
// docker cp trial workbuddy2api:/tmp/trial
|
| 11 |
-
// docker exec -w /app workbuddy2api /tmp/trial
|
| 12 |
-
//
|
| 13 |
-
// 结果逐账号输出到 stdout:
|
| 14 |
-
//
|
| 15 |
-
// uid | nick | status | detail
|
| 16 |
-
// ----+------+--------+-------
|
| 17 |
-
// ... | GLOBAL | OK | trial granted
|
| 18 |
-
// ... | GLOBAL | ALREADY | 已领取过(幂等,不算失败)
|
| 19 |
-
// ... | CN | N/A | not applicable
|
| 20 |
-
package main
|
| 21 |
-
|
| 22 |
-
import (
|
| 23 |
-
"fmt"
|
| 24 |
-
"os"
|
| 25 |
-
"path/filepath"
|
| 26 |
-
"sort"
|
| 27 |
-
|
| 28 |
-
"github.com/
|
| 29 |
-
"github.com/
|
| 30 |
-
)
|
| 31 |
-
|
| 32 |
-
// classifyTrial 归一化 ClaimTrial 结果(纯函数,供 main 循环与测试直接断言):
|
| 33 |
-
// err → FAIL;claimed → OK;否则(幂等码已领)→ ALREADY。
|
| 34 |
-
func classifyTrial(claimed bool, err error) (trialStatus, string) {
|
| 35 |
-
switch {
|
| 36 |
-
case err != nil:
|
| 37 |
-
return trialFailed, err.Error()
|
| 38 |
-
case claimed:
|
| 39 |
-
return trialOK, "trial granted"
|
| 40 |
-
default:
|
| 41 |
-
return trialAlready, "already claimed (idempotent)"
|
| 42 |
-
}
|
| 43 |
-
}
|
| 44 |
-
|
| 45 |
-
// trialStatus 单账号 trial 领取结果状态。
|
| 46 |
-
type trialStatus string
|
| 47 |
-
|
| 48 |
-
const (
|
| 49 |
-
trialOK trialStatus = "OK"
|
| 50 |
-
trialAlready trialStatus = "ALREADY"
|
| 51 |
-
trialNotApp trialStatus = "N/A" // CN 账号不适用
|
| 52 |
-
trialFailed trialStatus = "FAIL"
|
| 53 |
-
)
|
| 54 |
-
|
| 55 |
-
type trialRow struct {
|
| 56 |
-
uid string
|
| 57 |
-
nick string
|
| 58 |
-
status trialStatus
|
| 59 |
-
detail string
|
| 60 |
-
}
|
| 61 |
-
|
| 62 |
-
func main() {
|
| 63 |
-
authDir := "auths"
|
| 64 |
-
if len(os.Args) > 1 {
|
| 65 |
-
authDir = os.Args[1]
|
| 66 |
-
}
|
| 67 |
-
files, err := filepath.Glob(filepath.Join(authDir, "workbuddy-*.json"))
|
| 68 |
-
if err != nil || len(files) == 0 {
|
| 69 |
-
fmt.Fprintf(os.Stderr, "no auth files in %s\n", authDir)
|
| 70 |
-
os.Exit(1)
|
| 71 |
-
}
|
| 72 |
-
sort.Strings(files)
|
| 73 |
-
|
| 74 |
-
up := upstream.New()
|
| 75 |
-
// trial 是 global 专属端点:必须开启 global realm 路由,否则 upstream.New() 的
|
| 76 |
-
// GlobalEnabled 零值 false 会把请求路由到 CN base(codebuddy.cn)而必然失败。
|
| 77 |
-
up.GlobalEnabled = true
|
| 78 |
-
var rows []trialRow
|
| 79 |
-
for _, f := range files {
|
| 80 |
-
r := trialRow{uid: filepath.Base(f)}
|
| 81 |
-
raw, err := os.ReadFile(f)
|
| 82 |
-
if err != nil {
|
| 83 |
-
r.status, r.detail = trialFailed, "load: "+err.Error()
|
| 84 |
-
rows = append(rows, r)
|
| 85 |
-
continue
|
| 86 |
-
}
|
| 87 |
-
a, err := auth.Parse(raw)
|
| 88 |
-
if err != nil {
|
| 89 |
-
r.status, r.detail = trialFailed, "parse: "+err.Error()
|
| 90 |
-
rows = append(rows, r)
|
| 91 |
-
continue
|
| 92 |
-
}
|
| 93 |
-
a.FilePath = f
|
| 94 |
-
r.uid, r.nick = a.UID, a.Nickname
|
| 95 |
-
|
| 96 |
-
// 仅 global 账号适用:CN 明确提示不适用,不发任何请求。
|
| 97 |
-
if !a.IsGlobal() {
|
| 98 |
-
r.status, r.detail = trialNotApp, "CN account not applicable"
|
| 99 |
-
rows = append(rows, r)
|
| 100 |
-
continue
|
| 101 |
-
}
|
| 102 |
-
|
| 103 |
-
r.status, r.detail = classifyTrial(up.ClaimTrial(a))
|
| 104 |
-
rows = append(rows, r)
|
| 105 |
-
}
|
| 106 |
-
|
| 107 |
-
var okN, alreadyN, notAppN, failN int
|
| 108 |
-
fmt.Printf("uid | nick | status | detail\n")
|
| 109 |
-
fmt.Printf("-------------------------------------+-------------+---------+------------------------------\n")
|
| 110 |
-
for _, r := range rows {
|
| 111 |
-
fmt.Printf("%-36s | %-11s | %-7s | %s\n",
|
| 112 |
-
trunc(r.uid, 36), trunc(r.nick, 11), r.status, r.detail)
|
| 113 |
-
switch r.status {
|
| 114 |
-
case trialOK:
|
| 115 |
-
okN++
|
| 116 |
-
case trialAlready:
|
| 117 |
-
alreadyN++
|
| 118 |
-
case trialNotApp:
|
| 119 |
-
notAppN++
|
| 120 |
-
default:
|
| 121 |
-
failN++
|
| 122 |
-
}
|
| 123 |
-
}
|
| 124 |
-
fmt.Printf("\ntotal=%d ok=%d already=%d na=%d fail=%d\n",
|
| 125 |
-
len(rows), okN, alreadyN, notAppN, failN)
|
| 126 |
-
}
|
| 127 |
-
|
| 128 |
-
func trunc(s string, n int) string {
|
| 129 |
-
if len(s) > n {
|
| 130 |
-
return s[:n]
|
| 131 |
-
}
|
| 132 |
-
return s
|
| 133 |
-
}
|
|
|
|
| 1 |
+
// trial 一次性批量领取 global trial 加油包:遍历 auths 下全部账号,
|
| 2 |
+
// 仅对 global 账号执行 /billing/ide/trial(CN 无此端点,明确提示不适用)。
|
| 3 |
+
//
|
| 4 |
+
// 用法:
|
| 5 |
+
//
|
| 6 |
+
// # 本地:在项目根目录(需 config.json + auths/ + data/)直接 run
|
| 7 |
+
// go run ./cmd/trial
|
| 8 |
+
//
|
| 9 |
+
// # 容器内:先 cp 进去再 exec
|
| 10 |
+
// docker cp trial workbuddy2api:/tmp/trial
|
| 11 |
+
// docker exec -w /app workbuddy2api /tmp/trial
|
| 12 |
+
//
|
| 13 |
+
// 结果逐账号输出到 stdout:
|
| 14 |
+
//
|
| 15 |
+
// uid | nick | status | detail
|
| 16 |
+
// ----+------+--------+-------
|
| 17 |
+
// ... | GLOBAL | OK | trial granted
|
| 18 |
+
// ... | GLOBAL | ALREADY | 已领取过(幂等,不算失败)
|
| 19 |
+
// ... | CN | N/A | not applicable
|
| 20 |
+
package main
|
| 21 |
+
|
| 22 |
+
import (
|
| 23 |
+
"fmt"
|
| 24 |
+
"os"
|
| 25 |
+
"path/filepath"
|
| 26 |
+
"sort"
|
| 27 |
+
|
| 28 |
+
"github.com/misakano7545/workbuddy2api-panel/internal/auth"
|
| 29 |
+
"github.com/misakano7545/workbuddy2api-panel/internal/upstream"
|
| 30 |
+
)
|
| 31 |
+
|
| 32 |
+
// classifyTrial 归一化 ClaimTrial 结果(纯函数,供 main 循环与测试直接断言):
|
| 33 |
+
// err → FAIL;claimed → OK;否则(幂等码已领)→ ALREADY。
|
| 34 |
+
func classifyTrial(claimed bool, err error) (trialStatus, string) {
|
| 35 |
+
switch {
|
| 36 |
+
case err != nil:
|
| 37 |
+
return trialFailed, err.Error()
|
| 38 |
+
case claimed:
|
| 39 |
+
return trialOK, "trial granted"
|
| 40 |
+
default:
|
| 41 |
+
return trialAlready, "already claimed (idempotent)"
|
| 42 |
+
}
|
| 43 |
+
}
|
| 44 |
+
|
| 45 |
+
// trialStatus 单账号 trial 领取结果状态。
|
| 46 |
+
type trialStatus string
|
| 47 |
+
|
| 48 |
+
const (
|
| 49 |
+
trialOK trialStatus = "OK"
|
| 50 |
+
trialAlready trialStatus = "ALREADY"
|
| 51 |
+
trialNotApp trialStatus = "N/A" // CN 账号不适用
|
| 52 |
+
trialFailed trialStatus = "FAIL"
|
| 53 |
+
)
|
| 54 |
+
|
| 55 |
+
type trialRow struct {
|
| 56 |
+
uid string
|
| 57 |
+
nick string
|
| 58 |
+
status trialStatus
|
| 59 |
+
detail string
|
| 60 |
+
}
|
| 61 |
+
|
| 62 |
+
func main() {
|
| 63 |
+
authDir := "auths"
|
| 64 |
+
if len(os.Args) > 1 {
|
| 65 |
+
authDir = os.Args[1]
|
| 66 |
+
}
|
| 67 |
+
files, err := filepath.Glob(filepath.Join(authDir, "workbuddy-*.json"))
|
| 68 |
+
if err != nil || len(files) == 0 {
|
| 69 |
+
fmt.Fprintf(os.Stderr, "no auth files in %s\n", authDir)
|
| 70 |
+
os.Exit(1)
|
| 71 |
+
}
|
| 72 |
+
sort.Strings(files)
|
| 73 |
+
|
| 74 |
+
up := upstream.New()
|
| 75 |
+
// trial 是 global 专属端点:必须开启 global realm 路由,否则 upstream.New() 的
|
| 76 |
+
// GlobalEnabled 零值 false 会把请求路由到 CN base(codebuddy.cn)而必然失败。
|
| 77 |
+
up.GlobalEnabled = true
|
| 78 |
+
var rows []trialRow
|
| 79 |
+
for _, f := range files {
|
| 80 |
+
r := trialRow{uid: filepath.Base(f)}
|
| 81 |
+
raw, err := os.ReadFile(f)
|
| 82 |
+
if err != nil {
|
| 83 |
+
r.status, r.detail = trialFailed, "load: "+err.Error()
|
| 84 |
+
rows = append(rows, r)
|
| 85 |
+
continue
|
| 86 |
+
}
|
| 87 |
+
a, err := auth.Parse(raw)
|
| 88 |
+
if err != nil {
|
| 89 |
+
r.status, r.detail = trialFailed, "parse: "+err.Error()
|
| 90 |
+
rows = append(rows, r)
|
| 91 |
+
continue
|
| 92 |
+
}
|
| 93 |
+
a.FilePath = f
|
| 94 |
+
r.uid, r.nick = a.UID, a.Nickname
|
| 95 |
+
|
| 96 |
+
// 仅 global 账号适用:CN 明确提示不适用,不发任何请求。
|
| 97 |
+
if !a.IsGlobal() {
|
| 98 |
+
r.status, r.detail = trialNotApp, "CN account not applicable"
|
| 99 |
+
rows = append(rows, r)
|
| 100 |
+
continue
|
| 101 |
+
}
|
| 102 |
+
|
| 103 |
+
r.status, r.detail = classifyTrial(up.ClaimTrial(a))
|
| 104 |
+
rows = append(rows, r)
|
| 105 |
+
}
|
| 106 |
+
|
| 107 |
+
var okN, alreadyN, notAppN, failN int
|
| 108 |
+
fmt.Printf("uid | nick | status | detail\n")
|
| 109 |
+
fmt.Printf("-------------------------------------+-------------+---------+------------------------------\n")
|
| 110 |
+
for _, r := range rows {
|
| 111 |
+
fmt.Printf("%-36s | %-11s | %-7s | %s\n",
|
| 112 |
+
trunc(r.uid, 36), trunc(r.nick, 11), r.status, r.detail)
|
| 113 |
+
switch r.status {
|
| 114 |
+
case trialOK:
|
| 115 |
+
okN++
|
| 116 |
+
case trialAlready:
|
| 117 |
+
alreadyN++
|
| 118 |
+
case trialNotApp:
|
| 119 |
+
notAppN++
|
| 120 |
+
default:
|
| 121 |
+
failN++
|
| 122 |
+
}
|
| 123 |
+
}
|
| 124 |
+
fmt.Printf("\ntotal=%d ok=%d already=%d na=%d fail=%d\n",
|
| 125 |
+
len(rows), okN, alreadyN, notAppN, failN)
|
| 126 |
+
}
|
| 127 |
+
|
| 128 |
+
func trunc(s string, n int) string {
|
| 129 |
+
if len(s) > n {
|
| 130 |
+
return s[:n]
|
| 131 |
+
}
|
| 132 |
+
return s
|
| 133 |
+
}
|
config.default.json
CHANGED
|
@@ -1,102 +1,154 @@
|
|
| 1 |
-
{
|
| 2 |
-
"listen": ":7861",
|
| 3 |
-
"api_key": "",
|
| 4 |
-
"auth_dir": "/app/storage/auths",
|
| 5 |
-
"state_file": "/app/storage/data/state.json",
|
| 6 |
-
"
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
"
|
| 15 |
-
"
|
| 16 |
-
"
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
"
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
"
|
| 44 |
-
"
|
| 45 |
-
"
|
| 46 |
-
"
|
| 47 |
-
"
|
| 48 |
-
"
|
| 49 |
-
"
|
| 50 |
-
"
|
| 51 |
-
"
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
"
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
"
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
"
|
| 65 |
-
"
|
| 66 |
-
"
|
| 67 |
-
"
|
| 68 |
-
"
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
"
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
"
|
| 75 |
-
"
|
| 76 |
-
},
|
| 77 |
-
"
|
| 78 |
-
"
|
| 79 |
-
"
|
| 80 |
-
},
|
| 81 |
-
"
|
| 82 |
-
"
|
| 83 |
-
"
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
"
|
| 87 |
-
"
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
"
|
| 91 |
-
"
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
"
|
| 95 |
-
"
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
"
|
| 99 |
-
"
|
| 100 |
-
"
|
| 101 |
-
|
| 102 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"listen": ":7861",
|
| 3 |
+
"api_key": "",
|
| 4 |
+
"auth_dir": "/app/storage/auths",
|
| 5 |
+
"state_file": "/app/storage/data/state.json",
|
| 6 |
+
"dns_servers": [],
|
| 7 |
+
"server": {
|
| 8 |
+
"read_timeout": "300s"
|
| 9 |
+
},
|
| 10 |
+
"panel": {
|
| 11 |
+
"package_detail_limit": 5
|
| 12 |
+
},
|
| 13 |
+
"logging": {
|
| 14 |
+
"request_archive_enabled": true,
|
| 15 |
+
"request_retention_days": 7,
|
| 16 |
+
"request_archive_max_mb": 100,
|
| 17 |
+
"request_client_info": true
|
| 18 |
+
},
|
| 19 |
+
"cooldown": {
|
| 20 |
+
"soft_rate": "600s",
|
| 21 |
+
"soft_rate_max": "2h"
|
| 22 |
+
},
|
| 23 |
+
"schedule": {
|
| 24 |
+
"checkin_hours": [
|
| 25 |
+
9,
|
| 26 |
+
21
|
| 27 |
+
],
|
| 28 |
+
"travel_hours": [
|
| 29 |
+
9,
|
| 30 |
+
21
|
| 31 |
+
],
|
| 32 |
+
"activity_hours": [
|
| 33 |
+
10
|
| 34 |
+
],
|
| 35 |
+
"keepalive_hours": [
|
| 36 |
+
22
|
| 37 |
+
],
|
| 38 |
+
"keepalive_refresh_window": "168h",
|
| 39 |
+
"growth_hours": [
|
| 40 |
+
11
|
| 41 |
+
],
|
| 42 |
+
"checkin_enabled": true,
|
| 43 |
+
"travel_enabled": true,
|
| 44 |
+
"activity_enabled": true,
|
| 45 |
+
"keepalive_enabled": true,
|
| 46 |
+
"growth_enabled": true,
|
| 47 |
+
"growth_concurrency": 1,
|
| 48 |
+
"jitter_minutes": 0,
|
| 49 |
+
"account_spread_minutes": 0,
|
| 50 |
+
"account_spread_min_gap_seconds": 0,
|
| 51 |
+
"balance_refresh_enabled": true,
|
| 52 |
+
"balance_refresh_minutes": 5,
|
| 53 |
+
"include_disabled_in_tasks": false
|
| 54 |
+
},
|
| 55 |
+
"global": {
|
| 56 |
+
"enabled": true,
|
| 57 |
+
"chat_base": "",
|
| 58 |
+
"billing_base": ""
|
| 59 |
+
},
|
| 60 |
+
"cn": {
|
| 61 |
+
"chat_base": ""
|
| 62 |
+
},
|
| 63 |
+
"upstream": {
|
| 64 |
+
"timeout_seconds": 120,
|
| 65 |
+
"header_timeout_seconds": 120,
|
| 66 |
+
"idle_timeout_seconds": 300,
|
| 67 |
+
"user_agent": "",
|
| 68 |
+
"client_version": "",
|
| 69 |
+
"cli_version": "",
|
| 70 |
+
"client_name": "",
|
| 71 |
+
"device_token": "",
|
| 72 |
+
"device_token_file": "",
|
| 73 |
+
"passthrough_ip": false,
|
| 74 |
+
"dump_dir": "",
|
| 75 |
+
"dump_max_bytes": 0
|
| 76 |
+
},
|
| 77 |
+
"features": {
|
| 78 |
+
"sanitize_blacklist_fingerprints": true,
|
| 79 |
+
"sanitize_brand_scope": "all"
|
| 80 |
+
},
|
| 81 |
+
"models": {
|
| 82 |
+
"_comment": "hidden: 不对外暴露的模型黑名单。裸名=两域都藏;\"cn:xxx\"/\"global:xxx\"=只藏该域。/v1/models 列表过滤 + chat 点名拒绝,面板保存后热生效。",
|
| 83 |
+
"hidden": []
|
| 84 |
+
},
|
| 85 |
+
"prompt": {
|
| 86 |
+
"mode": "passthrough",
|
| 87 |
+
"file": ""
|
| 88 |
+
},
|
| 89 |
+
"upstash": {
|
| 90 |
+
"url": "",
|
| 91 |
+
"token": ""
|
| 92 |
+
},
|
| 93 |
+
"pool": {
|
| 94 |
+
"max_in_flight": 3,
|
| 95 |
+
"max_in_flight_global": 2,
|
| 96 |
+
"breaker_threshold": 3,
|
| 97 |
+
"breaker_cooldown": "30m",
|
| 98 |
+
"breaker_cooldown_max": "6h",
|
| 99 |
+
"degrade_threshold": 5,
|
| 100 |
+
"degrade_cooldown": "10m",
|
| 101 |
+
"degrade_cooldown_max": "2h",
|
| 102 |
+
"idle_weight_per_hour": 0.5,
|
| 103 |
+
"idle_weight_max": 5.0,
|
| 104 |
+
"prefer_expiring": true,
|
| 105 |
+
"expiring_soon": "168h",
|
| 106 |
+
"account_priority": {},
|
| 107 |
+
"account_share": {},
|
| 108 |
+
"cost_explore_interval": "30m",
|
| 109 |
+
"credit_floor": 0,
|
| 110 |
+
"reserve_credits": 10,
|
| 111 |
+
"model_fallback": {}
|
| 112 |
+
},
|
| 113 |
+
"session_sticky": {
|
| 114 |
+
"enabled": true,
|
| 115 |
+
"ttl": "30m",
|
| 116 |
+
"gc_interval": "5m"
|
| 117 |
+
},
|
| 118 |
+
"admin": {
|
| 119 |
+
"enabled": false,
|
| 120 |
+
"audit_enabled": false,
|
| 121 |
+
"audit_file": "./data/admin_audit.log"
|
| 122 |
+
},
|
| 123 |
+
"metrics": {
|
| 124 |
+
"enabled": false
|
| 125 |
+
},
|
| 126 |
+
"budget": {
|
| 127 |
+
"daily_credit_limit": 0,
|
| 128 |
+
"burst_credit_limit": 0,
|
| 129 |
+
"cache_low_rate": 0
|
| 130 |
+
},
|
| 131 |
+
"alerting": {
|
| 132 |
+
"enabled": false,
|
| 133 |
+
"webhook_url": "",
|
| 134 |
+
"min_healthy_cn": 1,
|
| 135 |
+
"min_healthy_global": 0
|
| 136 |
+
},
|
| 137 |
+
"sync": {
|
| 138 |
+
"bucket": "",
|
| 139 |
+
"token": "",
|
| 140 |
+
"token_file": "",
|
| 141 |
+
"endpoint": "https://huggingface.co",
|
| 142 |
+
"auth_dir": "",
|
| 143 |
+
"data_dir": "",
|
| 144 |
+
"include_data": [],
|
| 145 |
+
"writer": "auto",
|
| 146 |
+
"hf_bin": "hf",
|
| 147 |
+
"relay_url": "",
|
| 148 |
+
"relay_key": "",
|
| 149 |
+
"restart_space": "",
|
| 150 |
+
"ca_bundle": "",
|
| 151 |
+
"timeout": "60s",
|
| 152 |
+
"insecure_skip_verify": false
|
| 153 |
+
}
|
| 154 |
+
}
|
config.example.json
CHANGED
|
@@ -1,105 +1,206 @@
|
|
| 1 |
-
{
|
| 2 |
-
"listen": ":7863",
|
| 3 |
-
"api_key": "test_key",
|
| 4 |
-
"auth_dir": "./auths",
|
| 5 |
-
"state_file": "./data/state.json",
|
| 6 |
-
"
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
"
|
| 11 |
-
},
|
| 12 |
-
"
|
| 13 |
-
"
|
| 14 |
-
"
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
"
|
| 20 |
-
"
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
"
|
| 24 |
-
"
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
"
|
| 28 |
-
"
|
| 29 |
-
"
|
| 30 |
-
"
|
| 31 |
-
"
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
"
|
| 35 |
-
"
|
| 36 |
-
"
|
| 37 |
-
"
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
"
|
| 41 |
-
"
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
"
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
"
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
"
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
"
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
"
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
"
|
| 69 |
-
"
|
| 70 |
-
"
|
| 71 |
-
"
|
| 72 |
-
"
|
| 73 |
-
"
|
| 74 |
-
"
|
| 75 |
-
"
|
| 76 |
-
"
|
| 77 |
-
"
|
| 78 |
-
"
|
| 79 |
-
"
|
| 80 |
-
"
|
| 81 |
-
"
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
"
|
| 86 |
-
"
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
"
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
"
|
| 94 |
-
"
|
| 95 |
-
"
|
| 96 |
-
"
|
| 97 |
-
"
|
| 98 |
-
"
|
| 99 |
-
"
|
| 100 |
-
"
|
| 101 |
-
"
|
| 102 |
-
"
|
| 103 |
-
"
|
| 104 |
-
|
| 105 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"listen": "127.0.0.1:7863",
|
| 3 |
+
"api_key": "test_key",
|
| 4 |
+
"auth_dir": "./auths",
|
| 5 |
+
"state_file": "./data/state.json",
|
| 6 |
+
"dns_servers": [],
|
| 7 |
+
"server": {
|
| 8 |
+
"read_timeout": "300s",
|
| 9 |
+
"shutdown_timeout": "30s",
|
| 10 |
+
"max_payload_bytes": 67108864
|
| 11 |
+
},
|
| 12 |
+
"panel": {
|
| 13 |
+
"package_detail_limit": 5,
|
| 14 |
+
"poll_interval_sec": 0
|
| 15 |
+
},
|
| 16 |
+
"update": {
|
| 17 |
+
"auto_enabled": false,
|
| 18 |
+
"auto_time": "04:00",
|
| 19 |
+
"_proxy_comment": "更新走哪个出口(issue #198)。空 = 不显式设置。支持 http:// https:// socks5://。典型场景:api.github.com 通、但 release-assets.githubusercontent.com 被出站拦住(群晖/NAS/内网),此时填 socks5://127.0.0.1:1080 之类即可。可热生效,不用重启。",
|
| 20 |
+
"proxy": "",
|
| 21 |
+
"_proxy_from_env_comment": "是否沿用进程环境变量里的 HTTP_PROXY/HTTPS_PROXY(缺省 true,保持历史行为)。显式 false 则完全不读环境,只认上面的 proxy。",
|
| 22 |
+
"proxy_from_env": true,
|
| 23 |
+
"_mirror_comment": "资产下载镜像前缀(issue #198),如 https://ghfast.top/ 。只作用于资产下载:Release 元数据(tag/digest/size)永远直连 api.github.com,落盘后照旧校验 sha256——镜像只能搬字节,改不了「应该是什么」。空 = 直连。",
|
| 24 |
+
"mirror": ""
|
| 25 |
+
},
|
| 26 |
+
"accounts": {
|
| 27 |
+
"_comment": "账号目录热重载(issue #199):外部脚本/另一台机器往 auths/ 同步文件,不必重启进程即可入池;删文件在连续 N 次扫描确认后出池。",
|
| 28 |
+
"reload_interval": "10s",
|
| 29 |
+
"_reload_interval_comment": "轮询间隔;\"0s\" = 关闭轮询(手动接口 POST /panel/api/accounts/reload 仍可用)。",
|
| 30 |
+
"reload_delete_confirm": 2,
|
| 31 |
+
"_reload_delete_confirm_comment": "文件消失后要连续几轮扫描确认才移出账号池。半写文件、临时移走文件都只让账号「这一轮看不见」;剔除会写进 state.json 且下次启动不复活,所以要连续确认。1 = 立即删(不建议)。"
|
| 32 |
+
},
|
| 33 |
+
"logging": {
|
| 34 |
+
"request_archive_enabled": true,
|
| 35 |
+
"request_retention_days": 7,
|
| 36 |
+
"request_archive_max_mb": 100,
|
| 37 |
+
"request_client_info": true,
|
| 38 |
+
"request_archive_context": false,
|
| 39 |
+
"panel_log_enabled": true,
|
| 40 |
+
"panel_log_retention_days": 7,
|
| 41 |
+
"panel_log_max_mb": 50
|
| 42 |
+
},
|
| 43 |
+
"cooldown": {
|
| 44 |
+
"soft_rate": "600s",
|
| 45 |
+
"soft_rate_max": "2h"
|
| 46 |
+
},
|
| 47 |
+
"schedule": {
|
| 48 |
+
"checkin_hours": [
|
| 49 |
+
9,
|
| 50 |
+
21
|
| 51 |
+
],
|
| 52 |
+
"travel_hours": [
|
| 53 |
+
9,
|
| 54 |
+
21
|
| 55 |
+
],
|
| 56 |
+
"activity_hours": [
|
| 57 |
+
10
|
| 58 |
+
],
|
| 59 |
+
"web_activity_enabled": false,
|
| 60 |
+
"keepalive_hours": [
|
| 61 |
+
22
|
| 62 |
+
],
|
| 63 |
+
"keepalive_refresh_window": "168h",
|
| 64 |
+
"growth_hours": [
|
| 65 |
+
11
|
| 66 |
+
],
|
| 67 |
+
"checkin_enabled": true,
|
| 68 |
+
"travel_enabled": true,
|
| 69 |
+
"activity_enabled": true,
|
| 70 |
+
"keepalive_enabled": true,
|
| 71 |
+
"growth_enabled": true,
|
| 72 |
+
"growth_concurrency": 1,
|
| 73 |
+
"jitter_minutes": 0,
|
| 74 |
+
"account_spread_minutes": 0,
|
| 75 |
+
"account_spread_min_gap_seconds": 0,
|
| 76 |
+
"balance_refresh_enabled": true,
|
| 77 |
+
"balance_refresh_minutes": 5,
|
| 78 |
+
"include_disabled_in_tasks": false,
|
| 79 |
+
"balance_refresh_jitter_permill": 0,
|
| 80 |
+
"task_sweep_jitter_permill": 0,
|
| 81 |
+
"makeup_cards_per_round": 0,
|
| 82 |
+
"window_probe_enabled": true
|
| 83 |
+
},
|
| 84 |
+
"global": {
|
| 85 |
+
"enabled": true,
|
| 86 |
+
"chat_base": "",
|
| 87 |
+
"billing_base": ""
|
| 88 |
+
},
|
| 89 |
+
"cn": {
|
| 90 |
+
"chat_base": ""
|
| 91 |
+
},
|
| 92 |
+
"upstream": {
|
| 93 |
+
"timeout_seconds": 120,
|
| 94 |
+
"tls_fingerprint": "node",
|
| 95 |
+
"header_timeout_seconds": 120,
|
| 96 |
+
"idle_timeout_seconds": 300,
|
| 97 |
+
"user_agent": "",
|
| 98 |
+
"client_version": "",
|
| 99 |
+
"cli_version": "",
|
| 100 |
+
"client_name": "",
|
| 101 |
+
"device_token": "",
|
| 102 |
+
"device_token_file": "",
|
| 103 |
+
"passthrough_ip": false,
|
| 104 |
+
"dump_dir": "",
|
| 105 |
+
"dump_max_bytes": 0,
|
| 106 |
+
"restriction_hold_seconds": 1800
|
| 107 |
+
},
|
| 108 |
+
"features": {
|
| 109 |
+
"sanitize_blacklist_fingerprints": true,
|
| 110 |
+
"sanitize_brand_scope": "all",
|
| 111 |
+
"embeddings_enabled": false,
|
| 112 |
+
"busy_retry": true,
|
| 113 |
+
"busy_wait_seconds": 60,
|
| 114 |
+
"watermark_strip_enabled": false
|
| 115 |
+
},
|
| 116 |
+
"models": {
|
| 117 |
+
"_comment": "hidden: 不对外暴露的模型黑名单。裸名=两域都藏;\"cn:xxx\"/\"global:xxx\"=只藏该域。/v1/models 列表过滤 + chat 点名拒绝,面板保存后热生效。allowed: 模型白名单(issue #68),条目语法同 hidden;空数组 = 不启用(默认放行全部);非空时仅白名单内模型可列出与调用,与 hidden 共存取交集。",
|
| 118 |
+
"hidden": [],
|
| 119 |
+
"allowed": []
|
| 120 |
+
},
|
| 121 |
+
"thinking": {
|
| 122 |
+
"_comment": "网关思考档位策略。enabled=false 完全不碰档位;client_priority=true 客户端优先:客户端传了档位就照单全收(含关闭思考),只在缺档时补 default_effort;false 网关优先,按 override_scope 改写客户端档位(level=只改档位、尊重客户端关闭思考;all=连关闭也改写为开启)。default_effort 缺省 high:max 取模型支持的最高档,但思考与正文共用一份输出额度,max 会把预算烧在思考上、正文只剩半句(实测 max 正文 1906 token vs high 3236 token),只有确实要最深推理时才改回 max。也可写 xhigh/medium/low/minimal(模型不支持时落到不高于它的最高支持档)。model_defaults 按模型覆盖目标档:\"cn:xxx\"/\"global:xxx\" 精确到域,裸名两域共用;\"inherit\" 表示不覆盖。面板「模型与档位」页每行的「网关档位」下拉直接写本表(域精确键),配置页仅保留总开关与优先级三选一;保存后热生效。",
|
| 123 |
+
"enabled": true,
|
| 124 |
+
"default_effort": "high",
|
| 125 |
+
"client_priority": true,
|
| 126 |
+
"override_scope": "level",
|
| 127 |
+
"model_defaults": {}
|
| 128 |
+
},
|
| 129 |
+
"prompt": {
|
| 130 |
+
"mode": "passthrough",
|
| 131 |
+
"file": "",
|
| 132 |
+
"keep_recent_rounds": 0
|
| 133 |
+
},
|
| 134 |
+
"upstash": {
|
| 135 |
+
"url": "",
|
| 136 |
+
"token": ""
|
| 137 |
+
},
|
| 138 |
+
"pool": {
|
| 139 |
+
"max_in_flight": 3,
|
| 140 |
+
"max_in_flight_global": 2,
|
| 141 |
+
"breaker_threshold": 3,
|
| 142 |
+
"breaker_cooldown": "30m",
|
| 143 |
+
"breaker_cooldown_max": "6h",
|
| 144 |
+
"degrade_threshold": 5,
|
| 145 |
+
"degrade_cooldown": "10m",
|
| 146 |
+
"degrade_cooldown_max": "2h",
|
| 147 |
+
"selection_strategy": "weighted",
|
| 148 |
+
"idle_weight_per_hour": 0.5,
|
| 149 |
+
"idle_weight_max": 5.0,
|
| 150 |
+
"prefer_expiring": true,
|
| 151 |
+
"expiring_soon": "168h",
|
| 152 |
+
"account_priority": {},
|
| 153 |
+
"account_share": {},
|
| 154 |
+
"cost_explore_interval": "30m",
|
| 155 |
+
"balance_window": "1h",
|
| 156 |
+
"credit_floor": 100,
|
| 157 |
+
"reserve_credits": 10,
|
| 158 |
+
"model_fallback": {}
|
| 159 |
+
},
|
| 160 |
+
"session_sticky": {
|
| 161 |
+
"enabled": true,
|
| 162 |
+
"ttl": "30m",
|
| 163 |
+
"gc_interval": "5m"
|
| 164 |
+
},
|
| 165 |
+
"admin": {
|
| 166 |
+
"enabled": false,
|
| 167 |
+
"audit_enabled": false,
|
| 168 |
+
"audit_file": "./data/admin_audit.log"
|
| 169 |
+
},
|
| 170 |
+
"metrics": {
|
| 171 |
+
"enabled": false
|
| 172 |
+
},
|
| 173 |
+
"budget": {
|
| 174 |
+
"daily_credit_limit": 0,
|
| 175 |
+
"burst_credit_limit": 0,
|
| 176 |
+
"cache_low_rate": 0
|
| 177 |
+
},
|
| 178 |
+
"alerting": {
|
| 179 |
+
"enabled": false,
|
| 180 |
+
"webhook_url": "",
|
| 181 |
+
"min_healthy_cn": 1,
|
| 182 |
+
"min_healthy_global": 0
|
| 183 |
+
},
|
| 184 |
+
"watchdog": {
|
| 185 |
+
"_comment": "上游目录改版监控:定期对 /v1/models 结果取指纹,模型新增/下线或能力字段变动时经 alerting.webhook_url 通知。默认关闭——只在想第一时间知道上游改了目录时开。",
|
| 186 |
+
"enabled": false,
|
| 187 |
+
"interval_seconds": 3600
|
| 188 |
+
},
|
| 189 |
+
"sync": {
|
| 190 |
+
"bucket": "",
|
| 191 |
+
"token": "",
|
| 192 |
+
"token_file": "",
|
| 193 |
+
"endpoint": "https://huggingface.co",
|
| 194 |
+
"auth_dir": "",
|
| 195 |
+
"data_dir": "",
|
| 196 |
+
"include_data": [],
|
| 197 |
+
"writer": "auto",
|
| 198 |
+
"hf_bin": "hf",
|
| 199 |
+
"relay_url": "",
|
| 200 |
+
"relay_key": "",
|
| 201 |
+
"restart_space": "",
|
| 202 |
+
"ca_bundle": "",
|
| 203 |
+
"timeout": "60s",
|
| 204 |
+
"insecure_skip_verify": false
|
| 205 |
+
}
|
| 206 |
+
}
|
credit.sh
CHANGED
|
@@ -1,14 +1,14 @@
|
|
| 1 |
-
#!/usr/bin/env bash
|
| 2 |
-
# credit.sh — WorkBuddy 积分日报(默认美化输出)
|
| 3 |
-
#
|
| 4 |
-
# 用法:
|
| 5 |
-
# ./credit.sh # 人类可读日报
|
| 6 |
-
# ./credit.sh -json # 原始 JSON
|
| 7 |
-
#
|
| 8 |
-
# 二进制升级: go build -o credit ./cmd/credit
|
| 9 |
-
set -euo pipefail
|
| 10 |
-
cd "$(dirname "$0")"
|
| 11 |
-
if [[ "${1:-}" == "-json" ]]; then
|
| 12 |
-
exec ./credit
|
| 13 |
-
fi
|
| 14 |
-
exec ./credit -pretty
|
|
|
|
| 1 |
+
#!/usr/bin/env bash
|
| 2 |
+
# credit.sh — WorkBuddy 积分日报(默认美化输出)
|
| 3 |
+
#
|
| 4 |
+
# 用法:
|
| 5 |
+
# ./credit.sh # 人类可读日报
|
| 6 |
+
# ./credit.sh -json # 原始 JSON
|
| 7 |
+
#
|
| 8 |
+
# 二进制升级: go build -o credit ./cmd/credit
|
| 9 |
+
set -euo pipefail
|
| 10 |
+
cd "$(dirname "$0")"
|
| 11 |
+
if [[ "${1:-}" == "-json" ]]; then
|
| 12 |
+
exec ./credit
|
| 13 |
+
fi
|
| 14 |
+
exec ./credit -pretty
|
docker-compose.yml
CHANGED
|
@@ -1,15 +1,15 @@
|
|
| 1 |
-
# 本地 / 自建服务器跑法(不用 HF 时)。HF Spaces 上不需要这个文件。
|
| 2 |
-
services:
|
| 3 |
-
wb2api:
|
| 4 |
-
build: .
|
| 5 |
-
container_name: workbuddy2api
|
| 6 |
-
restart: unless-stopped
|
| 7 |
-
environment:
|
| 8 |
-
- TZ=Asia/Shanghai
|
| 9 |
-
ports:
|
| 10 |
-
- "7861:7861"
|
| 11 |
-
volumes:
|
| 12 |
-
# 一个目录装下全部持久化状态,和 HF 上挂桶的布局保持一致:
|
| 13 |
-
# storage/config.json、storage/auths/、storage/data/
|
| 14 |
-
- ./storage:/app/storage
|
| 15 |
-
- ./storage/config.json:/app/config.json
|
|
|
|
| 1 |
+
# 本地 / 自建服务器跑法(不用 HF 时)。HF Spaces 上不需要这个文件。
|
| 2 |
+
services:
|
| 3 |
+
wb2api:
|
| 4 |
+
build: .
|
| 5 |
+
container_name: workbuddy2api
|
| 6 |
+
restart: unless-stopped
|
| 7 |
+
environment:
|
| 8 |
+
- TZ=Asia/Shanghai
|
| 9 |
+
ports:
|
| 10 |
+
- "7861:7861"
|
| 11 |
+
volumes:
|
| 12 |
+
# 一个目录装下全部持久化状态,和 HF 上挂桶的布局保持一致:
|
| 13 |
+
# storage/config.json、storage/auths/、storage/data/
|
| 14 |
+
- ./storage:/app/storage
|
| 15 |
+
- ./storage/config.json:/app/config.json
|
docker-entrypoint.sh
CHANGED
|
@@ -1,69 +1,70 @@
|
|
| 1 |
-
#!/bin/sh
|
| 2 |
-
# WorkBuddy2API Panel — Hugging Face Spaces 入口脚本
|
| 3 |
-
#
|
| 4 |
-
# 持久化模型:
|
| 5 |
-
# HF Storage Bucket(私有) -> 挂载到容器 /app/storage
|
| 6 |
-
# /app/storage/config.json 运行配置(含 api_key,私有卷上,不进公开仓库)
|
| 7 |
-
# /app/storage/auths/*.json 账号凭证
|
| 8 |
-
# /app/storage/data/*.json 水位/用量/模型探测/请求归档
|
| 9 |
-
#
|
| 10 |
-
#
|
| 11 |
-
#
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
&&
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
# 空
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
echo "[entrypoint]
|
| 61 |
-
echo "[entrypoint]
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
echo "[entrypoint]
|
| 69 |
-
|
|
|
|
|
|
| 1 |
+
#!/bin/sh
|
| 2 |
+
# WorkBuddy2API Panel — Hugging Face Spaces 入口脚本
|
| 3 |
+
#
|
| 4 |
+
# 持久化模型:
|
| 5 |
+
# HF Storage Bucket(私有) -> 挂载到容器 /app/storage
|
| 6 |
+
# /app/storage/config.json 运行配置(含 api_key,私有卷上,不进公开仓库)
|
| 7 |
+
# /app/storage/auths/*.json 账号凭证
|
| 8 |
+
# /app/storage/data/*.json 水位/用量/模型探测/请求归档
|
| 9 |
+
# /app/storage/data/extensions.json 免费模型 / 自定义模型 / 访问密钥
|
| 10 |
+
#
|
| 11 |
+
# 容器根文件系统是 ephemeral 的:重启、休眠唤醒、重新构建都会重置。
|
| 12 |
+
# 所以配置和账号必须待在卷上,否则每次重启都要重新登录账号。
|
| 13 |
+
set -eu
|
| 14 |
+
|
| 15 |
+
PERSIST="${WB2A_PERSIST_DIR:-/app/storage}"
|
| 16 |
+
TEMPLATE=/app/config.json
|
| 17 |
+
CFG="$TEMPLATE"
|
| 18 |
+
|
| 19 |
+
echo "[entrypoint] boot at $(date -u '+%Y-%m-%dT%H:%M:%SZ')"
|
| 20 |
+
|
| 21 |
+
if [ -d "$PERSIST" ]; then
|
| 22 |
+
echo "[entrypoint] persistent volume detected at $PERSIST"
|
| 23 |
+
mkdir -p "$PERSIST/auths" "$PERSIST/data"
|
| 24 |
+
|
| 25 |
+
# 落盘自检:程序全部走「写 .tmp 再 rename」,rename 不可用的话持久化是假的
|
| 26 |
+
if echo probe > "$PERSIST/.wb2a-write-probe" 2>/dev/null \
|
| 27 |
+
&& mv "$PERSIST/.wb2a-write-probe" "$PERSIST/.wb2a-rename-probe" 2>/dev/null \
|
| 28 |
+
&& rm -f "$PERSIST/.wb2a-rename-probe"; then
|
| 29 |
+
echo "[entrypoint] storage self-test: write+rename OK"
|
| 30 |
+
else
|
| 31 |
+
echo "[entrypoint] storage self-test: FAILED — write or rename unsupported on $PERSIST" >&2
|
| 32 |
+
rm -f "$PERSIST/.wb2a-write-probe" "$PERSIST/.wb2a-rename-probe" 2>/dev/null || true
|
| 33 |
+
fi
|
| 34 |
+
|
| 35 |
+
if [ ! -f "$PERSIST/config.json" ]; then
|
| 36 |
+
if [ -f "$TEMPLATE" ]; then
|
| 37 |
+
echo "[entrypoint] no config.json on the volume -> seeding from image template"
|
| 38 |
+
cp "$TEMPLATE" "$PERSIST/config.json"
|
| 39 |
+
else
|
| 40 |
+
echo "[entrypoint] no config.json on the volume and no image template" >&2
|
| 41 |
+
fi
|
| 42 |
+
fi
|
| 43 |
+
[ -f "$PERSIST/config.json" ] && CFG="$PERSIST/config.json"
|
| 44 |
+
else
|
| 45 |
+
echo "[entrypoint] WARNING: no persistent volume at $PERSIST — everything written will be LOST on restart" >&2
|
| 46 |
+
mkdir -p /app/auths /app/data
|
| 47 |
+
fi
|
| 48 |
+
|
| 49 |
+
# 安全闸门:api_key 为空 == 完全不鉴权(httpauth.VerifyBearer 语义)。
|
| 50 |
+
# 空间是公网可达的,绝不允许以裸奔状态启动。
|
| 51 |
+
if [ -n "${WB2A_API_KEY:-}" ]; then
|
| 52 |
+
echo "[entrypoint] api_key supplied via WB2A_API_KEY env"
|
| 53 |
+
else
|
| 54 |
+
KEY=$(python3 -c 'import json,sys
|
| 55 |
+
try:
|
| 56 |
+
print(json.load(open(sys.argv[1])).get("api_key") or "")
|
| 57 |
+
except Exception:
|
| 58 |
+
print("")' "$CFG" 2>/dev/null || true)
|
| 59 |
+
if [ -z "$KEY" ]; then
|
| 60 |
+
echo "[entrypoint] FATAL: api_key is empty in $CFG and WB2A_API_KEY is not set." >&2
|
| 61 |
+
echo "[entrypoint] Refusing to start: an empty api_key disables authentication on a public Space." >&2
|
| 62 |
+
echo "[entrypoint] Fix: write a config.json containing an api_key onto the bucket, or set the WB2A_API_KEY secret." >&2
|
| 63 |
+
exit 1
|
| 64 |
+
fi
|
| 65 |
+
echo "[entrypoint] api_key loaded from config file"
|
| 66 |
+
fi
|
| 67 |
+
|
| 68 |
+
echo "[entrypoint] config: $CFG"
|
| 69 |
+
echo "[entrypoint] auth_dir: $(dirname "$CFG")/auths (see config)"
|
| 70 |
+
exec /app/wb2api -config "$CFG"
|
go.mod
CHANGED
|
@@ -1,11 +1,19 @@
|
|
| 1 |
-
module github.com/
|
| 2 |
-
|
| 3 |
-
go 1.
|
| 4 |
-
|
| 5 |
-
require (
|
| 6 |
-
github.com/
|
| 7 |
-
github.com/
|
| 8 |
-
github.com/
|
| 9 |
-
|
| 10 |
-
golang.org/x/sys v0.
|
| 11 |
-
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
module github.com/misakano7545/workbuddy2api-panel
|
| 2 |
+
|
| 3 |
+
go 1.26.10
|
| 4 |
+
|
| 5 |
+
require (
|
| 6 |
+
github.com/andybalholm/brotli v1.2.7
|
| 7 |
+
github.com/redis/go-redis/v9 v9.18.0
|
| 8 |
+
github.com/refraction-networking/utls v1.8.2
|
| 9 |
+
golang.org/x/net v0.52.0
|
| 10 |
+
golang.org/x/sys v0.42.0
|
| 11 |
+
)
|
| 12 |
+
|
| 13 |
+
require (
|
| 14 |
+
github.com/cespare/xxhash/v2 v2.3.0 // indirect
|
| 15 |
+
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f // indirect
|
| 16 |
+
github.com/klauspost/compress v1.20.2 // indirect
|
| 17 |
+
go.uber.org/atomic v1.11.0 // indirect
|
| 18 |
+
golang.org/x/crypto v0.49.0 // indirect
|
| 19 |
+
)
|
go.sum
CHANGED
|
@@ -1,12 +1,36 @@
|
|
| 1 |
-
github.com/
|
| 2 |
-
github.com/
|
| 3 |
-
github.com/
|
| 4 |
-
github.com/
|
| 5 |
-
github.com/
|
| 6 |
-
github.com/
|
| 7 |
-
github.com/
|
| 8 |
-
github.com/
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
github.com/andybalholm/brotli v1.2.7 h1:UgafRPGMam5ySHfRkhthMqOFA6IFoeF3D7mWIDLjG5A=
|
| 2 |
+
github.com/andybalholm/brotli v1.2.7/go.mod h1:rzTDkvFWvIrjDXZHkuS16NPggd91W3kUSvPlQ1pLaKY=
|
| 3 |
+
github.com/bsm/ginkgo/v2 v2.12.0 h1:Ny8MWAHyOepLGlLKYmXG4IEkioBysk6GpaRTLC8zwWs=
|
| 4 |
+
github.com/bsm/ginkgo/v2 v2.12.0/go.mod h1:SwYbGRRDovPVboqFv0tPTcG1sN61LM1Z4ARdbAV9g4c=
|
| 5 |
+
github.com/bsm/gomega v1.27.10 h1:yeMWxP2pV2fG3FgAODIY8EiRE3dy0aeFYt4l7wh6yKA=
|
| 6 |
+
github.com/bsm/gomega v1.27.10/go.mod h1:JyEr/xRbxbtgWNi8tIEVPUYZ5Dzef52k01W3YH0H+O0=
|
| 7 |
+
github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=
|
| 8 |
+
github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
|
| 9 |
+
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
|
| 10 |
+
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
| 11 |
+
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f h1:lO4WD4F/rVNCu3HqELle0jiPLLBs70cWOduZpkS1E78=
|
| 12 |
+
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f/go.mod h1:cuUVRXasLTGF7a8hSLbxyZXjz+1KgoB3wDUb6vlszIc=
|
| 13 |
+
github.com/klauspost/compress v1.20.2 h1:v5tiZvm1KGLyg5d5oXdXe3lsSPrbEUiKoXGia//I7Qo=
|
| 14 |
+
github.com/klauspost/compress v1.20.2/go.mod h1:LUdAzn7YLVvxLpc7y3V1m40wESHTgc1422pwwBSKYuI=
|
| 15 |
+
github.com/klauspost/cpuid/v2 v2.0.9 h1:lgaqFMSdTdQYdZ04uHyN2d/eKdOMyi2YLSvlQIBFYa4=
|
| 16 |
+
github.com/klauspost/cpuid/v2 v2.0.9/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg=
|
| 17 |
+
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
| 18 |
+
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
| 19 |
+
github.com/redis/go-redis/v9 v9.18.0 h1:pMkxYPkEbMPwRdenAzUNyFNrDgHx9U+DrBabWNfSRQs=
|
| 20 |
+
github.com/redis/go-redis/v9 v9.18.0/go.mod h1:k3ufPphLU5YXwNTUcCRXGxUoF1fqxnhFQmscfkCoDA0=
|
| 21 |
+
github.com/refraction-networking/utls v1.8.2 h1:j4Q1gJj0xngdeH+Ox/qND11aEfhpgoEvV+S9iJ2IdQo=
|
| 22 |
+
github.com/refraction-networking/utls v1.8.2/go.mod h1:jkSOEkLqn+S/jtpEHPOsVv/4V4EVnelwbMQl4vCWXAM=
|
| 23 |
+
github.com/stretchr/testify v1.3.0 h1:TivCn/peBQ7UY8ooIcPgZFpTNSz0Q2U6UrFlUfqbe0Q=
|
| 24 |
+
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
|
| 25 |
+
github.com/xyproto/randomstring v1.0.5 h1:YtlWPoRdgMu3NZtP45drfy1GKoojuR7hmRcnhZqKjWU=
|
| 26 |
+
github.com/xyproto/randomstring v1.0.5/go.mod h1:rgmS5DeNXLivK7YprL0pY+lTuhNQW3iGxZ18UQApw/E=
|
| 27 |
+
github.com/zeebo/xxh3 v1.0.2 h1:xZmwmqxHZA8AI603jOQ0tMqmBr9lPeFwGg6d+xy9DC0=
|
| 28 |
+
github.com/zeebo/xxh3 v1.0.2/go.mod h1:5NWz9Sef7zIDm2JHfFlcQvNekmcEl9ekUZQQKCYaDcA=
|
| 29 |
+
go.uber.org/atomic v1.11.0 h1:ZvwS0R+56ePWxUNi+Atn9dWONBPp/AUETXlHW0DxSjE=
|
| 30 |
+
go.uber.org/atomic v1.11.0/go.mod h1:LUxbIzbOniOlMKjJjyPfpl4v+PKK2cNJn91OQbhoJI0=
|
| 31 |
+
golang.org/x/crypto v0.49.0 h1:+Ng2ULVvLHnJ/ZFEq4KdcDd/cfjrrjjNSXNzxg0Y4U4=
|
| 32 |
+
golang.org/x/crypto v0.49.0/go.mod h1:ErX4dUh2UM+CFYiXZRTcMpEcN8b/1gxEuv3nODoYtCA=
|
| 33 |
+
golang.org/x/net v0.52.0 h1:He/TN1l0e4mmR3QqHMT2Xab3Aj3L9qjbhRm78/6jrW0=
|
| 34 |
+
golang.org/x/net v0.52.0/go.mod h1:R1MAz7uMZxVMualyPXb+VaqGSa3LIaUqk0eEt3w36Sw=
|
| 35 |
+
golang.org/x/sys v0.42.0 h1:omrd2nAlyT5ESRdCLYdm3+fMfNFE/+Rf4bDIQImRJeo=
|
| 36 |
+
golang.org/x/sys v0.42.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
|
internal/alert/alert.go
ADDED
|
@@ -0,0 +1,366 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
// Package alert 账号池可用性阈值告警。Enabled=false 时 Run 直接返回。
|
| 2 |
+
package alert
|
| 3 |
+
|
| 4 |
+
import (
|
| 5 |
+
"bytes"
|
| 6 |
+
"context"
|
| 7 |
+
"crypto/hmac"
|
| 8 |
+
"crypto/sha256"
|
| 9 |
+
"encoding/hex"
|
| 10 |
+
"encoding/json"
|
| 11 |
+
"fmt"
|
| 12 |
+
"io"
|
| 13 |
+
"log"
|
| 14 |
+
"net/http"
|
| 15 |
+
"sync"
|
| 16 |
+
"time"
|
| 17 |
+
)
|
| 18 |
+
|
| 19 |
+
const (
|
| 20 |
+
defaultInterval = 30 * time.Second
|
| 21 |
+
defaultTimeout = 5 * time.Second
|
| 22 |
+
defaultForTicks = 2
|
| 23 |
+
defaultClearTicks = 2
|
| 24 |
+
defaultStartupGrace = 30 * time.Second
|
| 25 |
+
defaultRecover = 1
|
| 26 |
+
defaultServiceName = "workbuddy2api"
|
| 27 |
+
)
|
| 28 |
+
|
| 29 |
+
type Health struct {
|
| 30 |
+
Total, Healthy, Cooling, Disabled, Breaker, Degraded, InFlight int
|
| 31 |
+
}
|
| 32 |
+
|
| 33 |
+
type Source interface {
|
| 34 |
+
Health(realm string) Health
|
| 35 |
+
WAFActive() bool
|
| 36 |
+
}
|
| 37 |
+
|
| 38 |
+
type Config struct {
|
| 39 |
+
Enabled bool
|
| 40 |
+
WebhookURL string
|
| 41 |
+
Secret string
|
| 42 |
+
Interval time.Duration
|
| 43 |
+
Timeout time.Duration
|
| 44 |
+
StartupGrace time.Duration
|
| 45 |
+
MinHealthyCN int
|
| 46 |
+
MinHealthyGlobal int
|
| 47 |
+
RecoverHealthy int
|
| 48 |
+
BreakerThreshold int
|
| 49 |
+
ForTicks int
|
| 50 |
+
ClearTicks int
|
| 51 |
+
SendResolve bool
|
| 52 |
+
ServiceName string
|
| 53 |
+
}
|
| 54 |
+
|
| 55 |
+
func (c *Config) normalize() {
|
| 56 |
+
if c.Interval <= 0 {
|
| 57 |
+
c.Interval = defaultInterval
|
| 58 |
+
}
|
| 59 |
+
if c.Timeout <= 0 {
|
| 60 |
+
c.Timeout = defaultTimeout
|
| 61 |
+
}
|
| 62 |
+
if c.StartupGrace <= 0 {
|
| 63 |
+
c.StartupGrace = defaultStartupGrace
|
| 64 |
+
}
|
| 65 |
+
if c.ForTicks <= 0 {
|
| 66 |
+
c.ForTicks = defaultForTicks
|
| 67 |
+
}
|
| 68 |
+
if c.ClearTicks <= 0 {
|
| 69 |
+
c.ClearTicks = defaultClearTicks
|
| 70 |
+
}
|
| 71 |
+
if c.RecoverHealthy <= 0 {
|
| 72 |
+
c.RecoverHealthy = defaultRecover
|
| 73 |
+
}
|
| 74 |
+
if c.ServiceName == "" {
|
| 75 |
+
c.ServiceName = defaultServiceName
|
| 76 |
+
}
|
| 77 |
+
}
|
| 78 |
+
|
| 79 |
+
type ruleState int
|
| 80 |
+
|
| 81 |
+
const (
|
| 82 |
+
stateOK ruleState = iota
|
| 83 |
+
statePending
|
| 84 |
+
stateFiring
|
| 85 |
+
)
|
| 86 |
+
|
| 87 |
+
type rule struct {
|
| 88 |
+
id, severity, realm string
|
| 89 |
+
sample func(Source) (value float64, bad, recovered bool, threshold float64, msg string)
|
| 90 |
+
state ruleState
|
| 91 |
+
badTicks int
|
| 92 |
+
clearCount int
|
| 93 |
+
since time.Time
|
| 94 |
+
}
|
| 95 |
+
|
| 96 |
+
type event int
|
| 97 |
+
|
| 98 |
+
const (
|
| 99 |
+
eventNone event = iota
|
| 100 |
+
eventAlert
|
| 101 |
+
eventResolve
|
| 102 |
+
)
|
| 103 |
+
|
| 104 |
+
func (r *rule) step(now time.Time, src Source, forTicks, clearTicks int) (event, float64, float64, string) {
|
| 105 |
+
v, bad, recovered, th, msg := r.sample(src)
|
| 106 |
+
switch r.state {
|
| 107 |
+
case stateOK:
|
| 108 |
+
if !bad {
|
| 109 |
+
return eventNone, 0, 0, ""
|
| 110 |
+
}
|
| 111 |
+
r.state = statePending
|
| 112 |
+
r.badTicks = 0
|
| 113 |
+
fallthrough
|
| 114 |
+
case statePending:
|
| 115 |
+
if !bad {
|
| 116 |
+
r.state = stateOK
|
| 117 |
+
r.badTicks = 0
|
| 118 |
+
return eventNone, 0, 0, ""
|
| 119 |
+
}
|
| 120 |
+
r.badTicks++
|
| 121 |
+
if r.badTicks >= forTicks {
|
| 122 |
+
r.state = stateFiring
|
| 123 |
+
r.since = now
|
| 124 |
+
r.clearCount = 0
|
| 125 |
+
return eventAlert, v, th, msg
|
| 126 |
+
}
|
| 127 |
+
case stateFiring:
|
| 128 |
+
if recovered {
|
| 129 |
+
r.clearCount++
|
| 130 |
+
if r.clearCount >= clearTicks {
|
| 131 |
+
r.state = stateOK
|
| 132 |
+
r.badTicks = 0
|
| 133 |
+
r.clearCount = 0
|
| 134 |
+
return eventResolve, v, th, msg
|
| 135 |
+
}
|
| 136 |
+
} else {
|
| 137 |
+
r.clearCount = 0
|
| 138 |
+
}
|
| 139 |
+
}
|
| 140 |
+
return eventNone, 0, 0, ""
|
| 141 |
+
}
|
| 142 |
+
|
| 143 |
+
func newRules(cfg Config) []*rule {
|
| 144 |
+
var rs []*rule
|
| 145 |
+
for _, rc := range []struct {
|
| 146 |
+
realm string
|
| 147 |
+
min int
|
| 148 |
+
}{{"cn", cfg.MinHealthyCN}, {"global", cfg.MinHealthyGlobal}} {
|
| 149 |
+
if rc.min <= 0 {
|
| 150 |
+
continue
|
| 151 |
+
}
|
| 152 |
+
realm, min := rc.realm, rc.min
|
| 153 |
+
rs = append(rs, &rule{
|
| 154 |
+
id: "realm_healthy_low", severity: "critical", realm: realm,
|
| 155 |
+
sample: func(src Source) (float64, bool, bool, float64, string) {
|
| 156 |
+
v := float64(src.Health(realm).Healthy)
|
| 157 |
+
bad := v < float64(min)
|
| 158 |
+
return v, bad, v >= float64(cfg.RecoverHealthy), float64(min),
|
| 159 |
+
fmt.Sprintf("%s realm healthy accounts (%d) below threshold (%d)", realm, int(v), min)
|
| 160 |
+
},
|
| 161 |
+
})
|
| 162 |
+
}
|
| 163 |
+
if cfg.BreakerThreshold > 0 {
|
| 164 |
+
th := cfg.BreakerThreshold
|
| 165 |
+
rs = append(rs, &rule{
|
| 166 |
+
id: "breaker_high", severity: "warning",
|
| 167 |
+
sample: func(src Source) (float64, bool, bool, float64, string) {
|
| 168 |
+
v := float64(src.Health("cn").Breaker + src.Health("global").Breaker)
|
| 169 |
+
return v, v >= float64(th), v < float64(th), float64(th),
|
| 170 |
+
fmt.Sprintf("accounts in circuit-breaker (%d) reached threshold (%d)", int(v), th)
|
| 171 |
+
},
|
| 172 |
+
})
|
| 173 |
+
}
|
| 174 |
+
rs = append(rs, &rule{
|
| 175 |
+
id: "waf_ip_block", severity: "warning",
|
| 176 |
+
sample: func(src Source) (float64, bool, bool, float64, string) {
|
| 177 |
+
active := src.WAFActive()
|
| 178 |
+
v := 0.0
|
| 179 |
+
if active {
|
| 180 |
+
v = 1
|
| 181 |
+
}
|
| 182 |
+
return v, active, !active, 1, "IP-level WAF block is active"
|
| 183 |
+
},
|
| 184 |
+
})
|
| 185 |
+
return rs
|
| 186 |
+
}
|
| 187 |
+
|
| 188 |
+
type Snapshot struct {
|
| 189 |
+
CN RealmSnapshot `json:"cn"`
|
| 190 |
+
Global RealmSnapshot `json:"global"`
|
| 191 |
+
WAFActive bool `json:"waf_active"`
|
| 192 |
+
}
|
| 193 |
+
|
| 194 |
+
type RealmSnapshot struct {
|
| 195 |
+
Total int `json:"total"`
|
| 196 |
+
Healthy int `json:"healthy"`
|
| 197 |
+
Cooling int `json:"cooling"`
|
| 198 |
+
Disabled int `json:"disabled"`
|
| 199 |
+
Breaker int `json:"breaker"`
|
| 200 |
+
// Degraded 连败降权中的账号数。alert.Health 一直有这个观测,但快照转换时
|
| 201 |
+
// 被丢弃——webhook 接收方永远看不到「有一批号在连败降权」,只能等它恶化成
|
| 202 |
+
// healthy 不足才被 realm_healthy_low 告警。
|
| 203 |
+
Degraded int `json:"degraded"`
|
| 204 |
+
InFlight int `json:"in_flight"`
|
| 205 |
+
}
|
| 206 |
+
|
| 207 |
+
type Payload struct {
|
| 208 |
+
Version int `json:"version"`
|
| 209 |
+
Event string `json:"event"`
|
| 210 |
+
Service string `json:"service"`
|
| 211 |
+
Rule string `json:"rule"`
|
| 212 |
+
Severity string `json:"severity"`
|
| 213 |
+
Realm string `json:"realm,omitempty"`
|
| 214 |
+
Value float64 `json:"value"`
|
| 215 |
+
Threshold float64 `json:"threshold"`
|
| 216 |
+
Message string `json:"message"`
|
| 217 |
+
Since time.Time `json:"since"`
|
| 218 |
+
FiredAt time.Time `json:"fired_at"`
|
| 219 |
+
Snapshot Snapshot `json:"snapshot"`
|
| 220 |
+
}
|
| 221 |
+
|
| 222 |
+
type Monitor struct {
|
| 223 |
+
cfg Config
|
| 224 |
+
src Source
|
| 225 |
+
rules []*rule
|
| 226 |
+
client *http.Client
|
| 227 |
+
startedAt time.Time
|
| 228 |
+
mu sync.Mutex
|
| 229 |
+
stop chan struct{}
|
| 230 |
+
stopOnce sync.Once
|
| 231 |
+
}
|
| 232 |
+
|
| 233 |
+
func New(cfg Config, src Source) *Monitor {
|
| 234 |
+
cfg.normalize()
|
| 235 |
+
return &Monitor{
|
| 236 |
+
cfg: cfg, src: src, rules: newRules(cfg), startedAt: time.Now(),
|
| 237 |
+
client: &http.Client{
|
| 238 |
+
Timeout: cfg.Timeout,
|
| 239 |
+
CheckRedirect: func(req *http.Request, via []*http.Request) error {
|
| 240 |
+
if len(via) >= 2 {
|
| 241 |
+
return fmt.Errorf("too many redirects")
|
| 242 |
+
}
|
| 243 |
+
if req.URL.Host != via[0].URL.Host {
|
| 244 |
+
return fmt.Errorf("cross-host redirect refused")
|
| 245 |
+
}
|
| 246 |
+
return nil
|
| 247 |
+
},
|
| 248 |
+
},
|
| 249 |
+
}
|
| 250 |
+
}
|
| 251 |
+
|
| 252 |
+
func (m *Monitor) Run(ctx context.Context) {
|
| 253 |
+
if !m.cfg.Enabled || m.src == nil {
|
| 254 |
+
return
|
| 255 |
+
}
|
| 256 |
+
m.mu.Lock()
|
| 257 |
+
if m.stop != nil {
|
| 258 |
+
m.mu.Unlock()
|
| 259 |
+
return
|
| 260 |
+
}
|
| 261 |
+
stop := make(chan struct{})
|
| 262 |
+
m.stop = stop
|
| 263 |
+
m.mu.Unlock()
|
| 264 |
+
t := time.NewTicker(m.cfg.Interval)
|
| 265 |
+
defer t.Stop()
|
| 266 |
+
m.Tick(time.Now())
|
| 267 |
+
for {
|
| 268 |
+
select {
|
| 269 |
+
case <-ctx.Done():
|
| 270 |
+
return
|
| 271 |
+
case <-stop:
|
| 272 |
+
return
|
| 273 |
+
case <-t.C:
|
| 274 |
+
m.Tick(time.Now())
|
| 275 |
+
}
|
| 276 |
+
}
|
| 277 |
+
}
|
| 278 |
+
|
| 279 |
+
func (m *Monitor) Stop() {
|
| 280 |
+
m.stopOnce.Do(func() {
|
| 281 |
+
m.mu.Lock()
|
| 282 |
+
defer m.mu.Unlock()
|
| 283 |
+
if m.stop != nil {
|
| 284 |
+
close(m.stop)
|
| 285 |
+
m.stop = nil
|
| 286 |
+
}
|
| 287 |
+
})
|
| 288 |
+
}
|
| 289 |
+
|
| 290 |
+
func (m *Monitor) Tick(now time.Time) {
|
| 291 |
+
if !m.cfg.Enabled || m.src == nil {
|
| 292 |
+
return
|
| 293 |
+
}
|
| 294 |
+
if now.Sub(m.startedAt) < m.cfg.StartupGrace {
|
| 295 |
+
return
|
| 296 |
+
}
|
| 297 |
+
for _, r := range m.rules {
|
| 298 |
+
ev, value, threshold, msg := r.step(now, m.src, m.cfg.ForTicks, m.cfg.ClearTicks)
|
| 299 |
+
switch ev {
|
| 300 |
+
case eventAlert:
|
| 301 |
+
m.send("alert", r, now, value, threshold, msg)
|
| 302 |
+
case eventResolve:
|
| 303 |
+
if m.cfg.SendResolve {
|
| 304 |
+
m.send("resolve", r, now, value, threshold, msg)
|
| 305 |
+
}
|
| 306 |
+
}
|
| 307 |
+
}
|
| 308 |
+
}
|
| 309 |
+
|
| 310 |
+
func (m *Monitor) snapshot() Snapshot {
|
| 311 |
+
to := func(h Health) RealmSnapshot {
|
| 312 |
+
return RealmSnapshot{Total: h.Total, Healthy: h.Healthy, Cooling: h.Cooling, Disabled: h.Disabled, Breaker: h.Breaker, Degraded: h.Degraded, InFlight: h.InFlight}
|
| 313 |
+
}
|
| 314 |
+
return Snapshot{CN: to(m.src.Health("cn")), Global: to(m.src.Health("global")), WAFActive: m.src.WAFActive()}
|
| 315 |
+
}
|
| 316 |
+
|
| 317 |
+
func (m *Monitor) send(eventName string, r *rule, now time.Time, value, threshold float64, msg string) {
|
| 318 |
+
m.post(Payload{
|
| 319 |
+
Version: 1, Event: eventName, Service: m.cfg.ServiceName, Rule: r.id, Severity: r.severity,
|
| 320 |
+
Realm: r.realm, Value: value, Threshold: threshold, Message: msg, Since: r.since, FiredAt: now,
|
| 321 |
+
Snapshot: m.snapshot(),
|
| 322 |
+
}, r.id)
|
| 323 |
+
}
|
| 324 |
+
|
| 325 |
+
// Notify 推送一条通知(无阈值语义的事件型消息,如排程轮次结果汇总)。
|
| 326 |
+
// 未启用或无 webhook 时静默——通知是旁路,不该影响调用方主流程。
|
| 327 |
+
func (m *Monitor) Notify(message string) {
|
| 328 |
+
if !m.cfg.Enabled || m.cfg.WebhookURL == "" {
|
| 329 |
+
return
|
| 330 |
+
}
|
| 331 |
+
m.post(Payload{
|
| 332 |
+
Version: 1, Event: "notify", Service: m.cfg.ServiceName, Severity: "info",
|
| 333 |
+
Message: message, FiredAt: time.Now(), Snapshot: m.snapshot(),
|
| 334 |
+
}, "notify")
|
| 335 |
+
}
|
| 336 |
+
|
| 337 |
+
// post 发 payload 到 webhook(HMAC 签名同规则事件;失败只记日志,不重试)。
|
| 338 |
+
func (m *Monitor) post(p Payload, tag string) {
|
| 339 |
+
body, err := json.Marshal(p)
|
| 340 |
+
if err != nil {
|
| 341 |
+
log.Printf("WARN: [alert] marshal payload rule=%s: %v", tag, err)
|
| 342 |
+
return
|
| 343 |
+
}
|
| 344 |
+
req, err := http.NewRequest(http.MethodPost, m.cfg.WebhookURL, bytes.NewReader(body))
|
| 345 |
+
if err != nil {
|
| 346 |
+
log.Printf("WARN: [alert] build request rule=%s: %v", tag, err)
|
| 347 |
+
return
|
| 348 |
+
}
|
| 349 |
+
req.Header.Set("Content-Type", "application/json")
|
| 350 |
+
req.Header.Set("User-Agent", "workbuddy2api-alert/1")
|
| 351 |
+
if m.cfg.Secret != "" {
|
| 352 |
+
mac := hmac.New(sha256.New, []byte(m.cfg.Secret))
|
| 353 |
+
mac.Write(body)
|
| 354 |
+
req.Header.Set("X-WB2A-Signature", "sha256="+hex.EncodeToString(mac.Sum(nil)))
|
| 355 |
+
}
|
| 356 |
+
resp, err := m.client.Do(req)
|
| 357 |
+
if err != nil {
|
| 358 |
+
log.Printf("WARN: [alert] webhook post failed rule=%s: %v", tag, err)
|
| 359 |
+
return
|
| 360 |
+
}
|
| 361 |
+
_, _ = io.Copy(io.Discard, io.LimitReader(resp.Body, 4<<10))
|
| 362 |
+
_ = resp.Body.Close()
|
| 363 |
+
if resp.StatusCode < 200 || resp.StatusCode > 299 {
|
| 364 |
+
log.Printf("WARN: [alert] webhook returned %d rule=%s", resp.StatusCode, tag)
|
| 365 |
+
}
|
| 366 |
+
}
|
internal/alert/alert_test.go
ADDED
|
@@ -0,0 +1,80 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
package alert
|
| 2 |
+
|
| 3 |
+
import (
|
| 4 |
+
"crypto/hmac"
|
| 5 |
+
"crypto/sha256"
|
| 6 |
+
"encoding/hex"
|
| 7 |
+
"io"
|
| 8 |
+
"net/http"
|
| 9 |
+
"net/http/httptest"
|
| 10 |
+
"strings"
|
| 11 |
+
"testing"
|
| 12 |
+
"time"
|
| 13 |
+
)
|
| 14 |
+
|
| 15 |
+
type fakeSrc struct{ healthy int }
|
| 16 |
+
|
| 17 |
+
func (f fakeSrc) Health(realm string) Health {
|
| 18 |
+
if realm == "cn" {
|
| 19 |
+
return Health{Total: 2, Healthy: f.healthy}
|
| 20 |
+
}
|
| 21 |
+
return Health{}
|
| 22 |
+
}
|
| 23 |
+
func (f fakeSrc) WAFActive() bool { return false }
|
| 24 |
+
|
| 25 |
+
func TestAlertFiresOnce(t *testing.T) {
|
| 26 |
+
var n int
|
| 27 |
+
var gotSig string
|
| 28 |
+
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
| 29 |
+
n++
|
| 30 |
+
body, _ := io.ReadAll(r.Body)
|
| 31 |
+
gotSig = r.Header.Get("X-WB2A-Signature")
|
| 32 |
+
mac := hmac.New(sha256.New, []byte("s3"))
|
| 33 |
+
mac.Write(body)
|
| 34 |
+
want := "sha256=" + hex.EncodeToString(mac.Sum(nil))
|
| 35 |
+
if gotSig != want {
|
| 36 |
+
t.Errorf("sig %s want %s", gotSig, want)
|
| 37 |
+
}
|
| 38 |
+
w.WriteHeader(204)
|
| 39 |
+
}))
|
| 40 |
+
defer srv.Close()
|
| 41 |
+
m := New(Config{
|
| 42 |
+
Enabled: true, WebhookURL: srv.URL, Secret: "s3",
|
| 43 |
+
StartupGrace: time.Nanosecond, ForTicks: 1, ClearTicks: 1,
|
| 44 |
+
MinHealthyCN: 1, Interval: time.Hour, Timeout: time.Second,
|
| 45 |
+
}, fakeSrc{})
|
| 46 |
+
now := m.startedAt.Add(time.Second)
|
| 47 |
+
m.Tick(now)
|
| 48 |
+
m.Tick(now.Add(time.Second))
|
| 49 |
+
if n != 1 {
|
| 50 |
+
t.Fatalf("posts=%d want 1 (edge trigger, no repeat)", n)
|
| 51 |
+
}
|
| 52 |
+
}
|
| 53 |
+
|
| 54 |
+
// TestNotifyPosts 汇总通知走同一条 webhook 管道:enabled + URL 才发;关闭时静默。
|
| 55 |
+
func TestNotifyPosts(t *testing.T) {
|
| 56 |
+
var n int
|
| 57 |
+
var got string
|
| 58 |
+
var sig string
|
| 59 |
+
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
| 60 |
+
n++
|
| 61 |
+
body, _ := io.ReadAll(r.Body)
|
| 62 |
+
got, sig = string(body), r.Header.Get("X-WB2A-Signature")
|
| 63 |
+
w.WriteHeader(204)
|
| 64 |
+
}))
|
| 65 |
+
defer srv.Close()
|
| 66 |
+
m := New(Config{Enabled: true, WebhookURL: srv.URL, Secret: "s3", Interval: time.Hour, Timeout: time.Second}, fakeSrc{})
|
| 67 |
+
m.Notify("growth 队列 第 1 轮 2 项:完成 2 / 跳过 0 / 失败 0")
|
| 68 |
+
if n != 1 || !strings.Contains(got, `"event":"notify"`) || !strings.Contains(got, "growth 队列 第 1 轮") {
|
| 69 |
+
t.Fatalf("posts=%d body=%s want 1 条 event=notify", n, got)
|
| 70 |
+
}
|
| 71 |
+
mac := hmac.New(sha256.New, []byte("s3"))
|
| 72 |
+
mac.Write([]byte(got))
|
| 73 |
+
if want := "sha256=" + hex.EncodeToString(mac.Sum(nil)); sig != want {
|
| 74 |
+
t.Fatalf("sig %s want %s", sig, want)
|
| 75 |
+
}
|
| 76 |
+
New(Config{Interval: time.Hour, Timeout: time.Second}, fakeSrc{}).Notify("x") // 未启用:静默不 panic
|
| 77 |
+
if n != 1 {
|
| 78 |
+
t.Fatalf("posts=%d want 1(未启用不应发)", n)
|
| 79 |
+
}
|
| 80 |
+
}
|
internal/auth/apikey_test.go
ADDED
|
@@ -0,0 +1,144 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
package auth
|
| 2 |
+
|
| 3 |
+
import (
|
| 4 |
+
"os"
|
| 5 |
+
"testing"
|
| 6 |
+
"time"
|
| 7 |
+
)
|
| 8 |
+
|
| 9 |
+
// TestIsAPIKey 静态 API Key 判定:只看 accessToken 前缀(ck_/pt_)。
|
| 10 |
+
//
|
| 11 |
+
// 为什么必须在前缀上判:auth 文件不持久化 tokenType(refresh 只认 OAuth 设备流,
|
| 12 |
+
// 静态 Key 无法刷新),前缀是落盘形态里唯一稳定、跨进程一致的判据。误判两个方向
|
| 13 |
+
// 都有实代价:判成普通号 → 每日对签到/成长端点空发请求、refresh 必然失败把好号冷却;
|
| 14 |
+
// 判太宽(比如把 ck 之后的任意串都算)→ 真实 OAuth token 被当成 Key,额度查询走错端点。
|
| 15 |
+
func TestIsAPIKey(t *testing.T) {
|
| 16 |
+
cases := []struct {
|
| 17 |
+
name string
|
| 18 |
+
token string
|
| 19 |
+
want bool
|
| 20 |
+
}{
|
| 21 |
+
{"ck_ 前缀(CodeBuddy 控制台签发)", "ck_abcd1234.secretpart", true},
|
| 22 |
+
{"pt_ 前缀(官方 CLI 形态)", "pt_abcd1234.secretpart", true},
|
| 23 |
+
{"裸 ck 无下划线", "ckabcd1234", false},
|
| 24 |
+
{"大写前缀", "CK_abcd1234", false},
|
| 25 |
+
{"JWT 形式 OAuth token", "eyJhbGciOiJSUzI1NiJ9.eyJ1aWQiOiJ1MSJ9.sig", false},
|
| 26 |
+
{"空 token", "", false},
|
| 27 |
+
{"前缀在中间", "Bearer ck_abcd", false},
|
| 28 |
+
}
|
| 29 |
+
for _, c := range cases {
|
| 30 |
+
t.Run(c.name, func(t *testing.T) {
|
| 31 |
+
a := &Auth{UID: "u1", AccessToken: c.token}
|
| 32 |
+
if got := a.IsAPIKey(); got != c.want {
|
| 33 |
+
t.Fatalf("token=%q IsAPIKey()=%v want %v", c.token, got, c.want)
|
| 34 |
+
}
|
| 35 |
+
})
|
| 36 |
+
}
|
| 37 |
+
|
| 38 |
+
// nil 接收者不得 panic:panel 侧会用临时 Auth 走判定,防御路径也可能传 nil。
|
| 39 |
+
var nilAuth *Auth
|
| 40 |
+
if nilAuth.IsAPIKey() {
|
| 41 |
+
t.Fatal("nil Auth 不该被判为 API Key")
|
| 42 |
+
}
|
| 43 |
+
}
|
| 44 |
+
|
| 45 |
+
// TestUsesEnterpriseBilling 额度查询分流判据:企业版与静态 API Key 都要走企业口径,
|
| 46 |
+
// 因为个人 get-user-resource 对二者恒返回空 Accounts。若这里的判据漏了 API Key,
|
| 47 |
+
// 静态 Key 账号的余额会恒为 0,积分保底把它当成耗尽号挡出选号。
|
| 48 |
+
func TestUsesEnterpriseBilling(t *testing.T) {
|
| 49 |
+
cases := []struct {
|
| 50 |
+
name string
|
| 51 |
+
a *Auth
|
| 52 |
+
want bool
|
| 53 |
+
}{
|
| 54 |
+
{"个人 OAuth 号", &Auth{UID: "u1", AccessToken: "eyJ.x.y"}, false},
|
| 55 |
+
{"企业版", &Auth{UID: "u1", AccessToken: "eyJ.x.y", EnterpriseID: "fn7x"}, true},
|
| 56 |
+
{"静态 API Key", &Auth{UID: "u1", AccessToken: "ck_abc.def"}, true},
|
| 57 |
+
{"企业版 + API Key", &Auth{UID: "u1", AccessToken: "pt_abc.def", EnterpriseID: "fn7x"}, true},
|
| 58 |
+
}
|
| 59 |
+
for _, c := range cases {
|
| 60 |
+
t.Run(c.name, func(t *testing.T) {
|
| 61 |
+
if got := c.a.UsesEnterpriseBilling(); got != c.want {
|
| 62 |
+
t.Fatalf("UsesEnterpriseBilling()=%v want %v", got, c.want)
|
| 63 |
+
}
|
| 64 |
+
})
|
| 65 |
+
}
|
| 66 |
+
}
|
| 67 |
+
|
| 68 |
+
// TestSupportsPersonalGrowth 个人成长体系门控:企业版与静态 API Key 都不具备,
|
| 69 |
+
// scheduler 五类任务与 panel 成长入口据此跳过(否则每日空发一堆注定失败的请求)。
|
| 70 |
+
func TestSupportsPersonalGrowth(t *testing.T) {
|
| 71 |
+
cases := []struct {
|
| 72 |
+
name string
|
| 73 |
+
a *Auth
|
| 74 |
+
want bool
|
| 75 |
+
}{
|
| 76 |
+
{"个人号", &Auth{UID: "u1", AccessToken: "eyJ.x.y"}, true},
|
| 77 |
+
{"企业版", &Auth{UID: "u1", AccessToken: "eyJ.x.y", EnterpriseID: "fn7x"}, false},
|
| 78 |
+
{"静态 API Key", &Auth{UID: "u1", AccessToken: "ck_abc.def"}, false},
|
| 79 |
+
}
|
| 80 |
+
for _, c := range cases {
|
| 81 |
+
t.Run(c.name, func(t *testing.T) {
|
| 82 |
+
if got := c.a.SupportsPersonalGrowth(); got != c.want {
|
| 83 |
+
t.Fatalf("SupportsPersonalGrowth()=%v want %v", got, c.want)
|
| 84 |
+
}
|
| 85 |
+
// 执行类门控与读类门控在本项目当前口径下必须一致(两者分开命名只为将来
|
| 86 |
+
// 出现「读得见、记不上账」的账号类型时能单独改一处)。
|
| 87 |
+
if got := c.a.SupportsPersonalEndpoints(); got != c.want {
|
| 88 |
+
t.Fatalf("SupportsPersonalEndpoints()=%v want %v(应与 SupportsPersonalGrowth 同口径)", got, c.want)
|
| 89 |
+
}
|
| 90 |
+
})
|
| 91 |
+
}
|
| 92 |
+
}
|
| 93 |
+
|
| 94 |
+
// TestNeedsRefreshAPIAKeyNever 静态 API Key 永不刷新。
|
| 95 |
+
//
|
| 96 |
+
// 这是整个接入里最容易踩的一处:Key 没有 expiresAt,若 NeedsRefresh 按「无过期即
|
| 97 |
+
// 需刷新」返回 true,请求路径会在每次发请求前先打 refresh 端点——而 refresh 只认
|
| 98 |
+
// OAuth 设备流,必然失败,于是这个完全健康的号会被当成坏号冷却/轮换。
|
| 99 |
+
func TestNeedsRefreshAPIAKeyNever(t *testing.T) {
|
| 100 |
+
a := &Auth{UID: "u1", AccessToken: "ck_abc.def"} // ExpiresAt 零值
|
| 101 |
+
if a.NeedsRefresh(time.Hour) {
|
| 102 |
+
t.Fatal("静态 API Key 不该需要刷新(refresh 端点只认 OAuth 设备流)")
|
| 103 |
+
}
|
| 104 |
+
if a.NeedsRefresh(0) {
|
| 105 |
+
t.Fatal("静态 API Key 在任何窗口下都不该需要刷新")
|
| 106 |
+
}
|
| 107 |
+
|
| 108 |
+
// 反例:普通 OAuth 号无 expiresAt 时仍要刷新(既有语义不能被这次改动带偏)。
|
| 109 |
+
b := &Auth{UID: "u2", AccessToken: "eyJ.x.y"}
|
| 110 |
+
if !b.NeedsRefresh(time.Hour) {
|
| 111 |
+
t.Fatal("无 expiresAt 的 OAuth 账号仍应需要刷新")
|
| 112 |
+
}
|
| 113 |
+
}
|
| 114 |
+
|
| 115 |
+
// TestAPIKeySavedAndReloaded 静态 Key 落盘/重载后判定不变:前缀判据只看 token 本身,
|
| 116 |
+
// 不依赖 Parse 时补齐的任何字段——否则重启后账号会「变回」普通号。
|
| 117 |
+
func TestAPIKeySavedAndReloaded(t *testing.T) {
|
| 118 |
+
dir := t.TempDir()
|
| 119 |
+
orig := &Auth{UID: "apikey-abc", AccessToken: "ck_abc.secret", Nickname: "key-1"}
|
| 120 |
+
orig.FilePath = dir + "/workbuddy-apikey-abc.json"
|
| 121 |
+
if _, realm := orig.BackfillRealm(); realm == "" {
|
| 122 |
+
t.Fatal("realm 应被补全(静态 Key 恒 CN)")
|
| 123 |
+
}
|
| 124 |
+
if err := orig.SaveAtomic(); err != nil {
|
| 125 |
+
t.Fatalf("save: %v", err)
|
| 126 |
+
}
|
| 127 |
+
raw, err := os.ReadFile(orig.FilePath)
|
| 128 |
+
if err != nil {
|
| 129 |
+
t.Fatalf("read: %v", err)
|
| 130 |
+
}
|
| 131 |
+
parsed, err := Parse(raw)
|
| 132 |
+
if err != nil {
|
| 133 |
+
t.Fatalf("parse: %v", err)
|
| 134 |
+
}
|
| 135 |
+
if !parsed.IsAPIKey() {
|
| 136 |
+
t.Fatalf("重载后应仍判为 API Key:%+v", parsed)
|
| 137 |
+
}
|
| 138 |
+
if parsed.RefreshTokenValue() != "" {
|
| 139 |
+
t.Fatalf("静态 Key 不该带 refreshToken:%q", parsed.RefreshTokenValue())
|
| 140 |
+
}
|
| 141 |
+
if parsed.NeedsRefresh(time.Hour) {
|
| 142 |
+
t.Fatal("重载后仍不该需要刷新")
|
| 143 |
+
}
|
| 144 |
+
}
|
internal/auth/auth.go
CHANGED
|
@@ -1,378 +1,628 @@
|
|
| 1 |
-
// Package auth 解析 WorkBuddy auth 文件(嵌套形/扁平形双形态),
|
| 2 |
-
// 提供 refresh 后的原子写回。
|
| 3 |
-
package auth
|
| 4 |
-
|
| 5 |
-
import (
|
| 6 |
-
"encoding/
|
| 7 |
-
"
|
| 8 |
-
"
|
| 9 |
-
"
|
| 10 |
-
"
|
| 11 |
-
"
|
| 12 |
-
"
|
| 13 |
-
"
|
| 14 |
-
"
|
| 15 |
-
"
|
| 16 |
-
"
|
| 17 |
-
|
| 18 |
-
"
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
//
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
//
|
| 32 |
-
|
| 33 |
-
//
|
| 34 |
-
//
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
//
|
| 43 |
-
|
| 44 |
-
//
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
//
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
//
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
//
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
//
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
a.
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
//
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
//
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
//
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
//
|
| 120 |
-
//
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
|
| 134 |
-
|
| 135 |
-
|
| 136 |
-
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
|
| 141 |
-
|
| 142 |
-
|
| 143 |
-
|
| 144 |
-
|
| 145 |
-
|
| 146 |
-
|
| 147 |
-
|
| 148 |
-
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
|
| 152 |
-
|
| 153 |
-
|
| 154 |
-
|
| 155 |
-
|
| 156 |
-
|
| 157 |
-
|
| 158 |
-
|
| 159 |
-
|
| 160 |
-
|
| 161 |
-
|
| 162 |
-
|
| 163 |
-
|
| 164 |
-
|
| 165 |
-
|
| 166 |
-
|
| 167 |
-
|
| 168 |
-
|
| 169 |
-
|
| 170 |
-
//
|
| 171 |
-
|
| 172 |
-
|
| 173 |
-
|
| 174 |
-
|
| 175 |
-
|
| 176 |
-
|
| 177 |
-
|
| 178 |
-
|
| 179 |
-
|
| 180 |
-
|
| 181 |
-
a
|
| 182 |
-
|
| 183 |
-
|
| 184 |
-
|
| 185 |
-
|
| 186 |
-
|
| 187 |
-
|
| 188 |
-
}
|
| 189 |
-
|
| 190 |
-
|
| 191 |
-
|
| 192 |
-
|
| 193 |
-
|
| 194 |
-
|
| 195 |
-
|
| 196 |
-
|
| 197 |
-
|
| 198 |
-
|
| 199 |
-
|
| 200 |
-
|
| 201 |
-
|
| 202 |
-
|
| 203 |
-
|
| 204 |
-
|
| 205 |
-
|
| 206 |
-
|
| 207 |
-
|
| 208 |
-
|
| 209 |
-
|
| 210 |
-
//
|
| 211 |
-
//
|
| 212 |
-
//
|
| 213 |
-
//
|
| 214 |
-
|
| 215 |
-
|
| 216 |
-
|
| 217 |
-
|
| 218 |
-
|
| 219 |
-
|
| 220 |
-
|
| 221 |
-
|
| 222 |
-
|
| 223 |
-
|
| 224 |
-
|
| 225 |
-
|
| 226 |
-
|
| 227 |
-
|
| 228 |
-
|
| 229 |
-
|
| 230 |
-
|
| 231 |
-
|
| 232 |
-
|
| 233 |
-
|
| 234 |
-
|
| 235 |
-
|
| 236 |
-
|
| 237 |
-
|
| 238 |
-
|
| 239 |
-
|
| 240 |
-
|
| 241 |
-
|
| 242 |
-
|
| 243 |
-
|
| 244 |
-
|
| 245 |
-
|
| 246 |
-
|
| 247 |
-
|
| 248 |
-
|
| 249 |
-
|
| 250 |
-
|
| 251 |
-
|
| 252 |
-
|
| 253 |
-
|
| 254 |
-
|
| 255 |
-
|
| 256 |
-
|
| 257 |
-
|
| 258 |
-
|
| 259 |
-
|
| 260 |
-
|
| 261 |
-
|
| 262 |
-
|
| 263 |
-
|
| 264 |
-
|
| 265 |
-
|
| 266 |
-
|
| 267 |
-
|
| 268 |
-
|
| 269 |
-
|
| 270 |
-
|
| 271 |
-
|
| 272 |
-
|
| 273 |
-
|
| 274 |
-
|
| 275 |
-
|
| 276 |
-
|
| 277 |
-
|
| 278 |
-
|
| 279 |
-
|
| 280 |
-
|
| 281 |
-
|
| 282 |
-
|
| 283 |
-
|
| 284 |
-
|
| 285 |
-
|
| 286 |
-
|
| 287 |
-
|
| 288 |
-
|
| 289 |
-
|
| 290 |
-
|
| 291 |
-
|
| 292 |
-
|
| 293 |
-
|
| 294 |
-
|
| 295 |
-
|
| 296 |
-
|
| 297 |
-
|
| 298 |
-
|
| 299 |
-
|
| 300 |
-
|
| 301 |
-
"
|
| 302 |
-
|
| 303 |
-
|
| 304 |
-
|
| 305 |
-
|
| 306 |
-
|
| 307 |
-
|
| 308 |
-
|
| 309 |
-
|
| 310 |
-
|
| 311 |
-
|
| 312 |
-
|
| 313 |
-
|
| 314 |
-
|
| 315 |
-
|
| 316 |
-
|
| 317 |
-
|
| 318 |
-
|
| 319 |
-
|
| 320 |
-
|
| 321 |
-
|
| 322 |
-
|
| 323 |
-
|
| 324 |
-
|
| 325 |
-
|
| 326 |
-
|
| 327 |
-
|
| 328 |
-
|
| 329 |
-
|
| 330 |
-
|
| 331 |
-
|
| 332 |
-
|
| 333 |
-
|
| 334 |
-
|
| 335 |
-
|
| 336 |
-
}
|
| 337 |
-
|
| 338 |
-
//
|
| 339 |
-
//
|
| 340 |
-
|
| 341 |
-
|
| 342 |
-
|
| 343 |
-
|
| 344 |
-
|
| 345 |
-
|
| 346 |
-
|
| 347 |
-
//
|
| 348 |
-
//
|
| 349 |
-
|
| 350 |
-
|
| 351 |
-
|
| 352 |
-
|
| 353 |
-
|
| 354 |
-
|
| 355 |
-
|
| 356 |
-
|
| 357 |
-
|
| 358 |
-
|
| 359 |
-
|
| 360 |
-
|
| 361 |
-
|
| 362 |
-
|
| 363 |
-
|
| 364 |
-
|
| 365 |
-
|
| 366 |
-
|
| 367 |
-
|
| 368 |
-
|
| 369 |
-
|
| 370 |
-
|
| 371 |
-
|
| 372 |
-
|
| 373 |
-
|
| 374 |
-
|
| 375 |
-
|
| 376 |
-
}
|
| 377 |
-
|
| 378 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
// Package auth 解析 WorkBuddy auth 文件(嵌套形/扁平形双形态),
|
| 2 |
+
// 提供 refresh 后的原子写回。
|
| 3 |
+
package auth
|
| 4 |
+
|
| 5 |
+
import (
|
| 6 |
+
"encoding/base64"
|
| 7 |
+
"encoding/json"
|
| 8 |
+
"errors"
|
| 9 |
+
"fmt"
|
| 10 |
+
"io/fs"
|
| 11 |
+
"log"
|
| 12 |
+
"os"
|
| 13 |
+
"path/filepath"
|
| 14 |
+
"sort"
|
| 15 |
+
"strings"
|
| 16 |
+
"sync"
|
| 17 |
+
"sync/atomic"
|
| 18 |
+
"time"
|
| 19 |
+
|
| 20 |
+
"github.com/misakano7545/workbuddy2api-panel/internal/logfmt"
|
| 21 |
+
"github.com/misakano7545/workbuddy2api-panel/internal/safefile"
|
| 22 |
+
)
|
| 23 |
+
|
| 24 |
+
// Auth 是归一化后��账号凭证(来源可以是插件 OAuth 嵌套形或手写扁平形)。
|
| 25 |
+
type Auth struct {
|
| 26 |
+
// mu 串行化 RefreshToken 写与 SaveAtomic 读,防止并发写回半更新 token。
|
| 27 |
+
mu sync.Mutex
|
| 28 |
+
|
| 29 |
+
AccessToken string
|
| 30 |
+
RefreshToken string
|
| 31 |
+
ExpiresAt int64 // Unix 秒
|
| 32 |
+
Domain string
|
| 33 |
+
// realm 账号域("cn" / "global"),落盘于 auth.realm(嵌套形)或顶层 realm(扁平形)。
|
| 34 |
+
// 空 = 缺省:Realm() 按 domain 后缀回落,最终恒非空。
|
| 35 |
+
//
|
| 36 |
+
// 命名注记:Go 不允许字段与方法同名,持久化字段用未导出 realm,计算访问器用
|
| 37 |
+
// 导出的 Realm()(跨包调用全部走方法)。Parse/SaveAtomic/login 在包内读写字段。
|
| 38 |
+
realm string
|
| 39 |
+
UID string
|
| 40 |
+
EnterpriseID string
|
| 41 |
+
Nickname string
|
| 42 |
+
FilePath string // 来源文件;refresh 后原子写回此处
|
| 43 |
+
|
| 44 |
+
// DeviceToken 设备风控 Token(X-Device-Token 头),来源 auth 文件的 device_token 键。
|
| 45 |
+
// 缺省为空 = 不注入该头(容器内无桌面端 Turing SDK 的常见部署)。
|
| 46 |
+
// 手写扁平形 auth 文件可直接写 "device_token": "...";插件 OAuth 嵌套形
|
| 47 |
+
// 顶层 device_token 也会被解析(与桌面端共用状态文件的部署方式)。
|
| 48 |
+
DeviceToken string
|
| 49 |
+
|
| 50 |
+
// wbSealed 源文件里原本是 $wbEncrypted 信封的字段("auth.accessToken" 形态):
|
| 51 |
+
// SaveAtomic 回写时必须逐个复原成信封,否则刷新后的 token 会以明文覆盖掉
|
| 52 |
+
// 桌面端的加密文件。nil = 来源文件没加密。
|
| 53 |
+
wbSealed map[string]bool
|
| 54 |
+
}
|
| 55 |
+
|
| 56 |
+
// Lock 供同进程内其他包(upstream.RefreshToken)在改写 Auth 字段期间加锁。
|
| 57 |
+
func (a *Auth) Lock() { a.mu.Lock() }
|
| 58 |
+
|
| 59 |
+
// Unlock 释放 a.Lock 获取的锁。
|
| 60 |
+
func (a *Auth) Unlock() { a.mu.Unlock() }
|
| 61 |
+
|
| 62 |
+
// AccessTokenValue 加锁读取 AccessToken(出站请求头一律经此取值,勿直读字段)。
|
| 63 |
+
//
|
| 64 |
+
// 为什么必须加锁:RefreshToken 在 a.mu 内改写 AccessToken/RefreshToken/Domain/ExpiresAt
|
| 65 |
+
// (client.go「第 2 段(锁内):校验快照一致后写回」),而所有出站请求头构造
|
| 66 |
+
// (ChatHeaders / BillingHeaders / fetchEnterpriseModels / fetchV3Models /
|
| 67 |
+
// global_models)与调度器的 token 检查都在锁外直读这些字段。生产上两侧真会并发:
|
| 68 |
+
// Scheduler.RunKeepaliveNow 定时对**每个**非禁用账号刷新(与是否有在途请求无关),
|
| 69 |
+
// 而 handler 正基于**同一个** *auth.Auth 指针构造请求头(Pool.AuthByUID/List 返回的
|
| 70 |
+
// 就是池内同一个对象)。无同步直读构成数据竞争(go test -race 实证)。
|
| 71 |
+
func (a *Auth) AccessTokenValue() string {
|
| 72 |
+
if a == nil {
|
| 73 |
+
return ""
|
| 74 |
+
}
|
| 75 |
+
a.mu.Lock()
|
| 76 |
+
defer a.mu.Unlock()
|
| 77 |
+
return a.AccessToken
|
| 78 |
+
}
|
| 79 |
+
|
| 80 |
+
// DomainValue 加锁读取 Domain(同 AccessTokenValue:RefreshToken 在锁内改写它)。
|
| 81 |
+
func (a *Auth) DomainValue() string {
|
| 82 |
+
if a == nil {
|
| 83 |
+
return ""
|
| 84 |
+
}
|
| 85 |
+
a.mu.Lock()
|
| 86 |
+
defer a.mu.Unlock()
|
| 87 |
+
return a.Domain
|
| 88 |
+
}
|
| 89 |
+
|
| 90 |
+
// RefreshTokenValue 加锁读取 RefreshToken(同 AccessTokenValue:RefreshToken 在锁内
|
| 91 |
+
// 改写它)。调度器的「有无凭证」前置守卫(checkin/keepalive/travel 的
|
| 92 |
+
// `a.RefreshToken == ""`)必须经此取值,勿直读字段。
|
| 93 |
+
func (a *Auth) RefreshTokenValue() string {
|
| 94 |
+
if a == nil {
|
| 95 |
+
return ""
|
| 96 |
+
}
|
| 97 |
+
a.mu.Lock()
|
| 98 |
+
defer a.mu.Unlock()
|
| 99 |
+
return a.RefreshToken
|
| 100 |
+
}
|
| 101 |
+
|
| 102 |
+
// globalEnabled 全局开关:global realm 是否路由(D5 双保险)。
|
| 103 |
+
// 默认开启(与 config global.enabled 缺省 true 一致):Realm() 正常按显式 realm/
|
| 104 |
+
// domain 判定 global/cn。显式 SetGlobalEnabled(false)(config "enabled": false)关闭
|
| 105 |
+
// → 逃生门:纯 CN 部署,即便 auth 文件写了 realm=global 或 domain 为 .workbuddy.ai
|
| 106 |
+
// 也恒判 cn——「关了才锁死」的单一闸口集中收敛在 Realm()/IsGlobal() 里。
|
| 107 |
+
var globalEnabled atomic.Bool
|
| 108 |
+
|
| 109 |
+
func init() { globalEnabled.Store(true) }
|
| 110 |
+
|
| 111 |
+
// SetGlobalEnabled 注入 global realm 路由开关(false = 锁死纯 CN,逃生门)。
|
| 112 |
+
func SetGlobalEnabled(enabled bool) { globalEnabled.Store(enabled) }
|
| 113 |
+
|
| 114 |
+
// GlobalEnabled 报告 global realm 路由开关当前状态(测试/运维观测)。
|
| 115 |
+
func GlobalEnabled() bool { return globalEnabled.Load() }
|
| 116 |
+
|
| 117 |
+
// Realm 返回账号的归一化域:显式 Realm=="global" 或 domain 后缀 .workbuddy.ai → "global",
|
| 118 |
+
// 否则 "cn"。显式 global 优先于 domain 回落(D1)。
|
| 119 |
+
// 全局开关 SetGlobalEnabled(false) 时恒 "cn"(逃生门:纯 CN 锁定,不影响默认行为)。
|
| 120 |
+
// 空 realm + 空 domain → "cn"(老 CN 凭证零回归)。
|
| 121 |
+
func (a *Auth) Realm() string {
|
| 122 |
+
a.mu.Lock()
|
| 123 |
+
defer a.mu.Unlock()
|
| 124 |
+
return a.realmLocked()
|
| 125 |
+
}
|
| 126 |
+
|
| 127 |
+
// realmLocked Realm 的无锁内部实现:仅限**已持 a.mu** 的调用方使用(sync.Mutex 不可重入,
|
| 128 |
+
// 锁内再调 Realm() 会自锁)。realm 由 BackfillRealm 改写、Domain 由 RefreshToken 在锁内
|
| 129 |
+
// 改写,故读取必须与写方同锁(理由见 AccessTokenValue 注释)。
|
| 130 |
+
func (a *Auth) realmLocked() string {
|
| 131 |
+
if !globalEnabled.Load() {
|
| 132 |
+
return "cn"
|
| 133 |
+
}
|
| 134 |
+
if strings.TrimSpace(a.realm) == "global" || isGlobalDomain(a.Domain) {
|
| 135 |
+
return "global"
|
| 136 |
+
}
|
| 137 |
+
return "cn"
|
| 138 |
+
}
|
| 139 |
+
|
| 140 |
+
// ResolveRealm 归一化 realm(cn/global):显式非空优先,否则按原始 domain 推断
|
| 141 |
+
// (isGlobalDomain)。不受逃生门影响(逃生门是路由锁,不应影响标识判定);
|
| 142 |
+
// domain 也为空 → "cn"(老 CN 凭证零回归)。
|
| 143 |
+
func ResolveRealm(explicit, domain string) string {
|
| 144 |
+
if r := strings.TrimSpace(explicit); r != "" {
|
| 145 |
+
return r
|
| 146 |
+
}
|
| 147 |
+
if isGlobalDomain(domain) {
|
| 148 |
+
return "global"
|
| 149 |
+
}
|
| 150 |
+
return "cn"
|
| 151 |
+
}
|
| 152 |
+
|
| 153 |
+
// BackfillRealm 为缺省 realm 标识的账号持久化补标识:a.realm 为空时按「原始 domain 推断」
|
| 154 |
+
// 写回(cn/global),返回 (是否有变更, 归一化后的 realm)。已有标识不动(幂等)。
|
| 155 |
+
//
|
| 156 |
+
// 注意用 isGlobalDomain(a.Domain) 直接推断,而非 Realm()——Realm() 在逃生门
|
| 157 |
+
// (SetGlobalEnabled(false))下恒降级 cn,把 global 账号写死成 cn 会永久污染凭证
|
| 158 |
+
// (逃生门是纯 CN 部署的临时锁,不应改写落盘数据)。domain 也为空时写 "cn"(老 CN 凭证)。
|
| 159 |
+
func (a *Auth) BackfillRealm() (bool, string) {
|
| 160 |
+
a.mu.Lock()
|
| 161 |
+
defer a.mu.Unlock()
|
| 162 |
+
if strings.TrimSpace(a.realm) != "" {
|
| 163 |
+
return false, a.realm
|
| 164 |
+
}
|
| 165 |
+
r := ResolveRealm("", a.Domain)
|
| 166 |
+
a.realm = r
|
| 167 |
+
return true, r
|
| 168 |
+
}
|
| 169 |
+
|
| 170 |
+
// RealmStored 直读持久化的 realm 标识(可能为空 = 未 backfill 的旧文件,Realm() 会 fallback)。
|
| 171 |
+
func (a *Auth) RealmStored() string {
|
| 172 |
+
a.mu.Lock()
|
| 173 |
+
defer a.mu.Unlock()
|
| 174 |
+
return a.realm
|
| 175 |
+
}
|
| 176 |
+
|
| 177 |
+
// BackfillRealmFor 显式写入 realm 标识(包外登录路径使用:panel login 已知用户选了
|
| 178 |
+
// global,直接落盘 realm=global,不依赖 domain 后缀推断)。realm 需为 cn/global,
|
| 179 |
+
// 非法值报错(防写脏)。返回是否发生变更。
|
| 180 |
+
func BackfillRealmFor(a *Auth, realm string) (bool, error) {
|
| 181 |
+
if a == nil {
|
| 182 |
+
return false, fmt.Errorf("nil auth")
|
| 183 |
+
}
|
| 184 |
+
switch strings.TrimSpace(realm) {
|
| 185 |
+
case "cn", "global":
|
| 186 |
+
default:
|
| 187 |
+
return false, fmt.Errorf("realm must be cn/global, got %q", realm)
|
| 188 |
+
}
|
| 189 |
+
a.mu.Lock()
|
| 190 |
+
defer a.mu.Unlock()
|
| 191 |
+
if a.realm == realm {
|
| 192 |
+
return false, nil
|
| 193 |
+
}
|
| 194 |
+
a.realm = realm
|
| 195 |
+
return true, nil
|
| 196 |
+
}
|
| 197 |
+
|
| 198 |
+
// IsGlobal 报告账号是否属于 global realm(= Realm() == "global")。
|
| 199 |
+
func (a *Auth) IsGlobal() bool { return a.Realm() == "global" }
|
| 200 |
+
|
| 201 |
+
// IsEnterprise 报告账号是否为企业版(auth 文件带非空 enterpriseId)。
|
| 202 |
+
//
|
| 203 |
+
// 企业版**没有个人成长体系**:签到 / 成长任务 / 连登管家 / 猫猫旅行 / 夜猫子
|
| 204 |
+
// 在上游一律被拒——实测(2026-10-07,同一时刻 A/B 对照):
|
| 205 |
+
// - POST /v2/billing/meter/daily-checkin → 400 code 10001「企业账号不支持该操作」
|
| 206 |
+
// - POST /billing/meter/claim-gift / claim-compensation → 400 code 10001 同上
|
| 207 |
+
// - GET /activity/growth/{streak,buddy/info,heatmap,lottery/summary}
|
| 208 |
+
// 与 GET /v2/activity/growth/tasks → 403「growth system is only available for personal users」
|
| 209 |
+
//
|
| 210 |
+
// 因此引用处(scheduler 五类任务 + panel 成长任务/签到入口)必须与 IsGlobal 门控
|
| 211 |
+
// 并列跳过,避免每日对注定失败的端点空发请求、面板按钮必然报错。
|
| 212 |
+
//
|
| 213 |
+
// 不受影响的能力:选号派发、保活(token 刷新)、额度查询(企业额度改走
|
| 214 |
+
// /v2/billing/meter/get-enterprise-user-usage,见 upstream.enterpriseResource)。
|
| 215 |
+
//
|
| 216 |
+
// 直读字段(EnterpriseID 自 Parse 后不再改写,与 upstream 读取方式一致),
|
| 217 |
+
// 无需加锁——Realm() 加锁是因为 realm/Domain 会被 RefreshToken 在锁内改写。
|
| 218 |
+
func (a *Auth) IsEnterprise() bool { return strings.TrimSpace(a.EnterpriseID) != "" }
|
| 219 |
+
|
| 220 |
+
// apiTokenPrefixes 静态 API Key 的前缀集合:ck_(CodeBuddy 控制台签发)与
|
| 221 |
+
// pt_(官方 CLI @tencent-ai/codebuddy-code 另有该前缀)。
|
| 222 |
+
//
|
| 223 |
+
// 官方 CLI 的判据是 tokenType === "ApiKey" 且 token 以这两个前缀之一开头;auth
|
| 224 |
+
// 文件不持久化 tokenType(refresh 只认 OAuth 设备流,静态 Key 无法刷新),前缀是
|
| 225 |
+
// 落盘形态里唯一稳定、跨进程一致的判据。
|
| 226 |
+
var apiTokenPrefixes = []string{"ck_", "pt_"}
|
| 227 |
+
|
| 228 |
+
// isAPIKeyToken 判 token 是否以静态 API Key 前缀开头。
|
| 229 |
+
func isAPIKeyToken(at string) bool {
|
| 230 |
+
for _, p := range apiTokenPrefixes {
|
| 231 |
+
if strings.HasPrefix(at, p) {
|
| 232 |
+
return true
|
| 233 |
+
}
|
| 234 |
+
}
|
| 235 |
+
return false
|
| 236 |
+
}
|
| 237 |
+
|
| 238 |
+
// isAPIKeyLocked IsAPIKey 的无锁内部实现:仅限**已持 a.mu** 的调用方使用
|
| 239 |
+
// (sync.Mutex 不可重入,锁内再调 AccessTokenValue 会自锁)。
|
| 240 |
+
func (a *Auth) isAPIKeyLocked() bool { return isAPIKeyToken(a.AccessToken) }
|
| 241 |
+
|
| 242 |
+
// IsAPIKey 报告账号是否为静态 API Key 账号(AccessToken 以 ck_/pt_ 开头)。
|
| 243 |
+
//
|
| 244 |
+
// 静态 Key 直接可用(Authorization: Bearer <key>,官方 CLI 同时发 X-API-Key),
|
| 245 |
+
// 但它**没有**个人账号身份:签到 / 成长任务 / 连登 / 旅行 / 夜猫子一律不适用,
|
| 246 |
+
// 额度只能走企业口径端点(个人 get-user-resource 对静态 Key ��回空 Accounts),
|
| 247 |
+
// 见 UsesEnterpriseBilling。
|
| 248 |
+
//
|
| 249 |
+
// 经 AccessTokenValue() 加锁读取:RefreshToken 会在锁内改写 AccessToken。
|
| 250 |
+
func (a *Auth) IsAPIKey() bool {
|
| 251 |
+
if a == nil {
|
| 252 |
+
return false
|
| 253 |
+
}
|
| 254 |
+
return isAPIKeyToken(a.AccessTokenValue())
|
| 255 |
+
}
|
| 256 |
+
|
| 257 |
+
// UsesEnterpriseBilling 报告账号的额度查询是否该走企业口径端点
|
| 258 |
+
// (/v2/billing/meter/get-enterprise-user-usage)。
|
| 259 |
+
//
|
| 260 |
+
// 企业版与静态 API Key 账号同属此列:个人 get-user-resource 对二者均返回空
|
| 261 |
+
// Accounts(企业账号无个人资源包;静态 Key 无个人账号身份),额度必须走企业口径,
|
| 262 |
+
// 否则余额恒为 0 → 积分保底把可用号当成耗尽号挡掉。
|
| 263 |
+
func (a *Auth) UsesEnterpriseBilling() bool { return a.IsEnterprise() || a.IsAPIKey() }
|
| 264 |
+
|
| 265 |
+
// TokenSource 从 AccessToken 的 JWT payload 里读 token_source 声明(官方客户端用它
|
| 266 |
+
// 填出站 X-Auth-Method 与 X-Userinfo.token_source)。非 JWT / 无该声明 / 解码失败一律
|
| 267 |
+
// 返回空串——空表示「这个账号没有该维度」,调用方随之不发对应头(不伪造)。
|
| 268 |
+
//
|
| 269 |
+
// 每次现解码而不缓存:RefreshToken 会整体换发 token,token_source 可能随重新授权翻转。
|
| 270 |
+
// 成本是一次 base64 + 小 JSON,相对一次上游请求可忽略。
|
| 271 |
+
func (a *Auth) TokenSource() string {
|
| 272 |
+
if a == nil {
|
| 273 |
+
return ""
|
| 274 |
+
}
|
| 275 |
+
return jwtClaim(a.AccessTokenValue(), "token_source")
|
| 276 |
+
}
|
| 277 |
+
|
| 278 |
+
// IdSource 从 AccessToken 的 JWT payload 里读 `id_source` 声明(官方客户端据此填
|
| 279 |
+
// 出站 X-Id-Source 头与 X-Userinfo.id_source 段)。
|
| 280 |
+
//
|
| 281 |
+
// 与 TokenSource 的差别很重要:token_source 描述「这次授权走了哪条流程」(企业切换等,
|
| 282 |
+
// 个人号也有),id_source 描述「身份来源」——两者在真机 runIdentityHeaders() 里是
|
| 283 |
+
// 各自独立触发的条件维度。同样现解码不缓存:换发 token 后声明可能变。
|
| 284 |
+
func (a *Auth) IdSource() string {
|
| 285 |
+
if a == nil {
|
| 286 |
+
return ""
|
| 287 |
+
}
|
| 288 |
+
return jwtClaim(a.AccessTokenValue(), "id_source")
|
| 289 |
+
}
|
| 290 |
+
|
| 291 |
+
// jwtClaim 解出 JWT payload 里的指定字符串声明;非 JWT / 解码失败返回空。
|
| 292 |
+
// 先按无填充 base64url 解(JWT 标准),失败再试带填充形态(兼容非标准签发方)。
|
| 293 |
+
func jwtClaim(token, name string) string {
|
| 294 |
+
parts := strings.Split(token, ".")
|
| 295 |
+
if len(parts) < 2 {
|
| 296 |
+
return ""
|
| 297 |
+
}
|
| 298 |
+
raw, err := base64.RawURLEncoding.DecodeString(parts[1])
|
| 299 |
+
if err != nil {
|
| 300 |
+
if raw, err = base64.URLEncoding.DecodeString(parts[1]); err != nil {
|
| 301 |
+
return ""
|
| 302 |
+
}
|
| 303 |
+
}
|
| 304 |
+
var payload map[string]any
|
| 305 |
+
if json.Unmarshal(raw, &payload) != nil {
|
| 306 |
+
return ""
|
| 307 |
+
}
|
| 308 |
+
v, _ := payload[name].(string)
|
| 309 |
+
return strings.TrimSpace(v)
|
| 310 |
+
}
|
| 311 |
+
|
| 312 |
+
// SupportsPersonalGrowth 报告账号是否具备个人成长体系(签到 / 成长任务 / 连登管家 /
|
| 313 |
+
// 猫猫旅行 / 夜猫子)。企业版与静态 API Key 都没有该体系:
|
| 314 |
+
// - 企业版:上游一律拒绝(400 code 10001 / 403 growth-only,见 IsEnterprise);
|
| 315 |
+
// - 静态 API Key:根本没有个人账号身份。
|
| 316 |
+
//
|
| 317 |
+
// scheduler 各任务与 panel 成长入口统一用本方法门控,避免对注定失败的端点空发请求、
|
| 318 |
+
// 把本可正常对话的号攒出一串上游报错。
|
| 319 |
+
func (a *Auth) SupportsPersonalGrowth() bool { return !a.IsEnterprise() && !a.IsAPIKey() }
|
| 320 |
+
|
| 321 |
+
// SupportsPersonalEndpoints 报告账号是否可调用「签到 / 任务列表」这类显式报错的个人端点。
|
| 322 |
+
// 与 SupportsPersonalGrowth(执行类门控)刻意分开命名:两者当前的判据相同,但语义不同
|
| 323 |
+
// ——将来若某类账号「读得到、记不上账」,只需改这一处而不影响执行类门控。
|
| 324 |
+
func (a *Auth) SupportsPersonalEndpoints() bool { return !a.IsEnterprise() && !a.IsAPIKey() }
|
| 325 |
+
|
| 326 |
+
// 不要再用 AccessToken 的 token_source=enterprise_switch 判定「企业上下文」:
|
| 327 |
+
// 实测两个只带该章的**个人版**号(enterpriseId 空)成长任务全部 claimed、行为事件
|
| 328 |
+
// 照常计分——该章只记本次授权走了哪条流程。企业形态一律以 enterpriseId 为准。
|
| 329 |
+
|
| 330 |
+
// isGlobalDomain 判定 domain 是否指向 www.workbuddy.ai 家族。
|
| 331 |
+
// 同时接受裸域 workbuddy.ai 与任意子域(HasSuffix("www.workbuddy.ai") 或裸域本身)。
|
| 332 |
+
func isGlobalDomain(d string) bool {
|
| 333 |
+
d = strings.ToLower(strings.TrimSpace(d))
|
| 334 |
+
if d == "workbuddy.ai" || strings.HasSuffix(d, ".workbuddy.ai") {
|
| 335 |
+
return true
|
| 336 |
+
}
|
| 337 |
+
// 官方 CLI 国际站域(product.json externalDomain: www.codebuddy.ai)。与 workbuddy.ai
|
| 338 |
+
// 同后端不同主机名,但 domain 落盘值不同,不认它会把国际站账号误判成 cn
|
| 339 |
+
// (显式 realm 键可兜住面板登录的账号,手写 auth 文件则直接错域路由)。
|
| 340 |
+
return d == "codebuddy.ai" || strings.HasSuffix(d, ".codebuddy.ai")
|
| 341 |
+
}
|
| 342 |
+
|
| 343 |
+
// NeedsRefresh 报告 token 是否将在 within 内过期(或已过期/无 expiry)。
|
| 344 |
+
func (a *Auth) NeedsRefresh(within time.Duration) bool {
|
| 345 |
+
a.mu.Lock()
|
| 346 |
+
defer a.mu.Unlock()
|
| 347 |
+
// 静态 API Key 永不刷新(refresh 端点只认 OAuth 设备流):恒 false,否则请求
|
| 348 |
+
// 路径会先 refresh、失败后把该号当坏号冷却换号——Key 本身是好的。
|
| 349 |
+
if a.isAPIKeyLocked() {
|
| 350 |
+
return false
|
| 351 |
+
}
|
| 352 |
+
if a.ExpiresAt <= 0 {
|
| 353 |
+
return true
|
| 354 |
+
}
|
| 355 |
+
return time.Now().Add(within).Unix() >= a.ExpiresAt
|
| 356 |
+
}
|
| 357 |
+
|
| 358 |
+
// Parse 兼容两种磁盘形态:
|
| 359 |
+
//
|
| 360 |
+
// 嵌套形 {"auth":{...},"account":{...}} (插件 OAuth 输出)
|
| 361 |
+
// 扁平形 {"accessToken":...,"uid":...} (手写/旧版)
|
| 362 |
+
func Parse(raw []byte) (*Auth, error) {
|
| 363 |
+
if len(raw) == 0 {
|
| 364 |
+
return nil, fmt.Errorf("empty auth storage")
|
| 365 |
+
}
|
| 366 |
+
// 新版桌面端把 auth 字段换成 $wbEncrypted 信封(见 wbencrypted.go)。
|
| 367 |
+
// 解密后再按原两形态解析;未加密文件原样返回,不吃这条路径。
|
| 368 |
+
dec, sealed, err := decryptWBEncrypted(raw)
|
| 369 |
+
if err != nil {
|
| 370 |
+
return nil, err
|
| 371 |
+
}
|
| 372 |
+
raw = dec
|
| 373 |
+
var probe map[string]json.RawMessage
|
| 374 |
+
if err := json.Unmarshal(raw, &probe); err != nil {
|
| 375 |
+
return nil, fmt.Errorf("storage_parse_error: %w", err)
|
| 376 |
+
}
|
| 377 |
+
var a Auth
|
| 378 |
+
if _, nested := probe["auth"]; nested {
|
| 379 |
+
var n struct {
|
| 380 |
+
Auth struct {
|
| 381 |
+
AccessToken string `json:"accessToken"`
|
| 382 |
+
RefreshToken string `json:"refreshToken"`
|
| 383 |
+
ExpiresAt int64 `json:"expiresAt"`
|
| 384 |
+
Domain string `json:"domain"`
|
| 385 |
+
Realm string `json:"realm"`
|
| 386 |
+
} `json:"auth"`
|
| 387 |
+
Account struct {
|
| 388 |
+
UID string `json:"uid"`
|
| 389 |
+
EnterpriseID string `json:"enterpriseId"`
|
| 390 |
+
Nickname string `json:"nickname"`
|
| 391 |
+
} `json:"account"`
|
| 392 |
+
// DeviceToken 顶层 device_token(嵌套形与扁平形共用;手写时无需嵌进 auth 对象)。
|
| 393 |
+
DeviceToken string `json:"device_token"`
|
| 394 |
+
}
|
| 395 |
+
if err := json.Unmarshal(raw, &n); err != nil {
|
| 396 |
+
return nil, fmt.Errorf("storage_parse_error: %w", err)
|
| 397 |
+
}
|
| 398 |
+
a = Auth{
|
| 399 |
+
AccessToken: n.Auth.AccessToken,
|
| 400 |
+
RefreshToken: n.Auth.RefreshToken,
|
| 401 |
+
ExpiresAt: n.Auth.ExpiresAt,
|
| 402 |
+
Domain: n.Auth.Domain,
|
| 403 |
+
realm: n.Auth.Realm,
|
| 404 |
+
UID: n.Account.UID,
|
| 405 |
+
EnterpriseID: n.Account.EnterpriseID,
|
| 406 |
+
Nickname: n.Account.Nickname,
|
| 407 |
+
DeviceToken: n.DeviceToken,
|
| 408 |
+
}
|
| 409 |
+
} else {
|
| 410 |
+
var f struct {
|
| 411 |
+
AccessToken string `json:"accessToken"`
|
| 412 |
+
RefreshToken string `json:"refreshToken"`
|
| 413 |
+
ExpiresAt int64 `json:"expiresAt"`
|
| 414 |
+
Domain string `json:"domain"`
|
| 415 |
+
Realm string `json:"realm"`
|
| 416 |
+
UID string `json:"uid"`
|
| 417 |
+
EnterpriseID string `json:"enterpriseId"`
|
| 418 |
+
Nickname string `json:"nickname"`
|
| 419 |
+
DeviceToken string `json:"device_token"`
|
| 420 |
+
}
|
| 421 |
+
if err := json.Unmarshal(raw, &f); err != nil {
|
| 422 |
+
return nil, fmt.Errorf("storage_parse_error: %w", err)
|
| 423 |
+
}
|
| 424 |
+
a = Auth{
|
| 425 |
+
AccessToken: f.AccessToken,
|
| 426 |
+
RefreshToken: f.RefreshToken,
|
| 427 |
+
ExpiresAt: f.ExpiresAt,
|
| 428 |
+
Domain: f.Domain,
|
| 429 |
+
realm: f.Realm,
|
| 430 |
+
UID: f.UID,
|
| 431 |
+
EnterpriseID: f.EnterpriseID,
|
| 432 |
+
Nickname: f.Nickname,
|
| 433 |
+
DeviceToken: f.DeviceToken,
|
| 434 |
+
}
|
| 435 |
+
}
|
| 436 |
+
if strings.TrimSpace(a.AccessToken) == "" {
|
| 437 |
+
return nil, fmt.Errorf("parse_error: missing accessToken")
|
| 438 |
+
}
|
| 439 |
+
a.ExpiresAt = normalizeExpiresAt(a.ExpiresAt)
|
| 440 |
+
a.wbSealed = sealed
|
| 441 |
+
return &a, nil
|
| 442 |
+
}
|
| 443 |
+
|
| 444 |
+
// expiresAtMillisThreshold 区分「秒」与「毫秒」时间戳的分界(1e11)。
|
| 445 |
+
//
|
| 446 |
+
// 单位到 1e11 秒已是公元 5138 年,真实凭证不可能;而 1e11 毫秒 = 1973 年,
|
| 447 |
+
// 毫秒制当前值(~1.8e12)远在其上。阈值取在两者之间不会误判任一侧。
|
| 448 |
+
const expiresAtMillisThreshold = 100_000_000_000
|
| 449 |
+
|
| 450 |
+
// normalizeExpiresAt 把上游凭据的 expiresAt 归一到 Unix 秒。
|
| 451 |
+
//
|
| 452 |
+
// 为什么需要:官方 CodeBuddy CLI 的凭据文件
|
| 453 |
+
// (%LOCALAPPDATA%\CodeBuddyExtension\Data\Public\auth\*.info)写的是**毫秒**
|
| 454 |
+
// (实测 1795254516410),而本仓与旧插件 OAuth 落盘的是**秒**。直接按秒解释毫秒
|
| 455 |
+
// 会把到期时间推到公元 58800 年 → NeedsRefresh 恒 false → token 永不刷新 →
|
| 456 |
+
// 到期后账号静默失效(表现为「用了一个月突然全部 401」)。导入官方凭据是本仓
|
| 457 |
+
// 支持的用法,所以解析入口必须归一,而不是靠使用者手改文件。
|
| 458 |
+
func normalizeExpiresAt(v int64) int64 {
|
| 459 |
+
if v > expiresAtMillisThreshold {
|
| 460 |
+
return v / 1000
|
| 461 |
+
}
|
| 462 |
+
return v
|
| 463 |
+
}
|
| 464 |
+
|
| 465 |
+
// SaveAtomic 以嵌套形原子写回 FilePath(tmp + rename),保持嵌套形(插件可读)格式。
|
| 466 |
+
// 全程持 a.mu:防止与 RefreshToken 修改 token 字段并发,杜绝写回半更新。
|
| 467 |
+
// 防御:accessToken 为空时拒绝写回,避免误用空凭证覆盖有效文件。
|
| 468 |
+
func (a *Auth) SaveAtomic() error {
|
| 469 |
+
a.mu.Lock()
|
| 470 |
+
defer a.mu.Unlock()
|
| 471 |
+
if strings.TrimSpace(a.AccessToken) == "" {
|
| 472 |
+
return fmt.Errorf("save refused: empty accessToken (uid=%s)", a.UID)
|
| 473 |
+
}
|
| 474 |
+
if a.FilePath == "" {
|
| 475 |
+
return fmt.Errorf("no FilePath set")
|
| 476 |
+
}
|
| 477 |
+
doc := map[string]any{
|
| 478 |
+
"auth": map[string]any{
|
| 479 |
+
"accessToken": a.AccessToken,
|
| 480 |
+
"refreshToken": a.RefreshToken,
|
| 481 |
+
"expiresAt": a.ExpiresAt,
|
| 482 |
+
"domain": a.Domain,
|
| 483 |
+
"realm": a.realm,
|
| 484 |
+
},
|
| 485 |
+
"account": map[string]any{
|
| 486 |
+
"uid": a.UID,
|
| 487 |
+
"enterpriseId": a.EnterpriseID,
|
| 488 |
+
"nickname": a.Nickname,
|
| 489 |
+
},
|
| 490 |
+
}
|
| 491 |
+
// DeviceToken 非空才写回顶层 device_token:避免在无该字段的旧文件里引入空键
|
| 492 |
+
// (保持与插件 OAuth 输出形状一致,插件读取忽略未知键)。
|
| 493 |
+
if a.DeviceToken != "" {
|
| 494 |
+
doc["device_token"] = a.DeviceToken
|
| 495 |
+
}
|
| 496 |
+
// 来源文件加密的,回写也保持加密:按读入时的信封清单复原(见 sealForSave)。
|
| 497 |
+
// 封装失败就拒绝落盘——明文降级覆盖加密文件比写不进去更糟。
|
| 498 |
+
if err := sealForSave(doc, a.wbSealed); err != nil {
|
| 499 |
+
return err
|
| 500 |
+
}
|
| 501 |
+
raw, err := json.MarshalIndent(doc, "", " ")
|
| 502 |
+
if err != nil {
|
| 503 |
+
return err
|
| 504 |
+
}
|
| 505 |
+
// 落盘走 safefile:tmp fsync 后才 rename(掉电不会留下长度正确、内容全 0 的
|
| 506 |
+
// 凭证文件),并把上一份有效内容留成 <file>.bak —— LoadDir 读到坏文件时用它。
|
| 507 |
+
if err := safefile.WriteKeep(a.FilePath, raw, 0o600); err != nil {
|
| 508 |
+
// Docker bind-mount 权限问题的典型现场:容器内 app 用户(uid 10001)
|
| 509 |
+
// 对宿主机挂载目录无写权限。给出可操作指引而不是裸 syscall 错误。
|
| 510 |
+
msg := fmt.Sprintf("写入 %s 失败: %v", a.FilePath, err)
|
| 511 |
+
if errors.Is(err, fs.ErrPermission) {
|
| 512 |
+
msg += "\n(Docker 部署:容器内用户对宿主机挂载目录无写权限。解法任选:" +
|
| 513 |
+
"1) 以本机 uid 运行容器:PUID=$(id -u) PGID=$(id -g) docker compose up -d;" +
|
| 514 |
+
"2) sudo chown -R 10001:10001 ./auths ./data ./config.json;" +
|
| 515 |
+
"3) compose 设 user: \"0:0\" 以 root 运行)"
|
| 516 |
+
}
|
| 517 |
+
return errors.New(msg)
|
| 518 |
+
}
|
| 519 |
+
return nil
|
| 520 |
+
}
|
| 521 |
+
|
| 522 |
+
// SaveAtomicRetry 在 SaveAtomic 基础上做有界重试(0/100ms/300ms)。
|
| 523 |
+
//
|
| 524 |
+
// 为什么需要:refresh 成功后上游已经轮换了 RT,新 token 只在内存里;如果这一次
|
| 525 |
+
// 落盘失败(磁盘瞬时满、bind-mount 抖动),进程重启会拿旧 RT 去刷新——旧 RT 可能
|
| 526 |
+
// 已被消费,账号直接进入「需要重新登录」。重试把瞬时失败挡掉;仍失败由调用方
|
| 527 |
+
// 打 ERR(错误汇总可见),至少不让问题静默。
|
| 528 |
+
func (a *Auth) SaveAtomicRetry() error {
|
| 529 |
+
var err error
|
| 530 |
+
for i, delay := range []time.Duration{0, 100 * time.Millisecond, 300 * time.Millisecond} {
|
| 531 |
+
if i > 0 {
|
| 532 |
+
time.Sleep(delay)
|
| 533 |
+
}
|
| 534 |
+
if err = a.SaveAtomic(); err == nil {
|
| 535 |
+
return nil
|
| 536 |
+
}
|
| 537 |
+
}
|
| 538 |
+
return err
|
| 539 |
+
}
|
| 540 |
+
|
| 541 |
+
// LoadReport 一次账号目录扫描的结果。
|
| 542 |
+
//
|
| 543 |
+
// Errors 非空表示「本次有文件读不动/解析不了」:账号可能**还在**,只是这一轮看不见。
|
| 544 |
+
// 热重载必须据此放弃删除(见 panel/reload.go)——半写文件被当成「文件已删」会把
|
| 545 |
+
// 在池账号踢掉,而且剔除结果会持久化,下次启动也不复活。
|
| 546 |
+
type LoadReport struct {
|
| 547 |
+
Auths []*Auth
|
| 548 |
+
Files int
|
| 549 |
+
ParseError []string // "文件名: 原因",已按文件粒度去重
|
| 550 |
+
}
|
| 551 |
+
|
| 552 |
+
// LoadDir 扫描并解析 dir 下 workbuddy*.json;解析失败的文件静默跳过(启动日志由调用方统计)。
|
| 553 |
+
// 顺带做 realm 标识存量迁移:对空 realm 的 auth 自动 backfill(原始 domain 推断)并 SaveAtomic
|
| 554 |
+
// 落盘,一次性把旧文件补上 realm 键。单个文件写失败不阻断启动(log WARN 继续),
|
| 555 |
+
// 避免历史 auth 目录个别文件不可写时整个服务起不来。
|
| 556 |
+
func LoadDir(dir string) ([]*Auth, error) {
|
| 557 |
+
r, err := LoadDirReport(dir)
|
| 558 |
+
if err != nil {
|
| 559 |
+
return nil, err
|
| 560 |
+
}
|
| 561 |
+
return r.Auths, nil
|
| 562 |
+
}
|
| 563 |
+
|
| 564 |
+
// LoadDirReport 同 LoadDir,另外回报文件数与解析失败的条目(热重载用来判断能否删号)。
|
| 565 |
+
func LoadDirReport(dir string) (LoadReport, error) {
|
| 566 |
+
files, err := filepath.Glob(filepath.Join(dir, "workbuddy*.json"))
|
| 567 |
+
if err != nil {
|
| 568 |
+
return LoadReport{}, err
|
| 569 |
+
}
|
| 570 |
+
report := LoadReport{Files: len(files)}
|
| 571 |
+
// 按 mtime 升序:同一个号的轮转备份并存时(客户端会写 <name>.<ts>.<pid>.<uuid>.info),
|
| 572 |
+
// 池里「后载入者胜出」才等于「最新凭证胜出」。不排序的话 glob 顺序(字典序)可能让
|
| 573 |
+
// 陈旧备份胜出——那账号在面板上表现为 token 失效。取不到 mtime 的文件排最前(先被覆盖)。
|
| 574 |
+
sort.SliceStable(files, func(i, j int) bool {
|
| 575 |
+
fi, erri := os.Stat(files[i])
|
| 576 |
+
fj, errj := os.Stat(files[j])
|
| 577 |
+
if erri != nil || errj != nil {
|
| 578 |
+
return erri != nil && errj == nil
|
| 579 |
+
}
|
| 580 |
+
return fi.ModTime().Before(fj.ModTime())
|
| 581 |
+
})
|
| 582 |
+
// seenUID 重复 UID 检测:同一个号的**个人版与企业版 uid 完全相同**(企业版只是
|
| 583 |
+
// type→ultimate + 多一个 enterpriseId,实测如此),两份凭证在池里只有一个槽位,
|
| 584 |
+
// 后载入者胜出。这里打 WARN 并点出两个文件与各自 enterpriseId——否则用户只看到
|
| 585 |
+
// 「我导了两个号,面板只有一个」。
|
| 586 |
+
type dupUID struct{ file, eid string }
|
| 587 |
+
seenUID := make(map[string]dupUID, len(files))
|
| 588 |
+
var out []*Auth
|
| 589 |
+
for _, f := range files {
|
| 590 |
+
// 坏文件不再静默跳过:safefile.Read 在正文损坏时回退到 .bak(掉电留下的
|
| 591 |
+
// 全 0 文件因此还能救回账号),两边都坏才放弃��并且说清是哪个文件、坏在哪
|
| 592 |
+
// ——「账号凭空少了一个」比多打一行 ERROR 难查得多。
|
| 593 |
+
raw, err := safefile.Read(f, func(b []byte) bool {
|
| 594 |
+
_, perr := Parse(b)
|
| 595 |
+
return perr == nil
|
| 596 |
+
})
|
| 597 |
+
if err != nil {
|
| 598 |
+
log.Printf("ERROR: auth 文件 %s 无法读取: %v —— 该账号本次不在池里,修好文件或重新登录", f, err)
|
| 599 |
+
report.ParseError = append(report.ParseError, filepath.Base(f)+": "+err.Error())
|
| 600 |
+
continue
|
| 601 |
+
}
|
| 602 |
+
a, err := Parse(raw)
|
| 603 |
+
if err != nil {
|
| 604 |
+
log.Printf("ERROR: auth 文件 %s 解析失败: %v —— 该账号本次不在池里", f, err)
|
| 605 |
+
report.ParseError = append(report.ParseError, filepath.Base(f)+": "+err.Error())
|
| 606 |
+
continue
|
| 607 |
+
}
|
| 608 |
+
a.FilePath = f
|
| 609 |
+
if prev, ok := seenUID[a.UID]; ok {
|
| 610 |
+
log.Printf("WARN: uid %s 在 %s(enterpriseId=%q)与 %s(enterpriseId=%q)重复 —— "+
|
| 611 |
+
"同一账号的个人版/企业版 uid 相同,池里只保留后载入的一份;不用的那份删掉",
|
| 612 |
+
logfmt.Label(a.UID, a.Nickname), prev.file, prev.eid, f, a.EnterpriseID)
|
| 613 |
+
}
|
| 614 |
+
seenUID[a.UID] = dupUID{file: f, eid: a.EnterpriseID}
|
| 615 |
+
if a.RealmStored() == "" {
|
| 616 |
+
if changed, r := a.BackfillRealm(); changed {
|
| 617 |
+
if err := a.SaveAtomic(); err != nil {
|
| 618 |
+
log.Printf("WARN: auth %s realm backfill save: %v", logfmt.Label(a.UID, a.Nickname), err)
|
| 619 |
+
} else if r == "global" {
|
| 620 |
+
log.Printf("auth %s 存量迁移: 补 realm=global(domain=%s)", logfmt.Label(a.UID, a.Nickname), a.Domain)
|
| 621 |
+
}
|
| 622 |
+
}
|
| 623 |
+
}
|
| 624 |
+
out = append(out, a)
|
| 625 |
+
}
|
| 626 |
+
report.Auths = out
|
| 627 |
+
return report, nil
|
| 628 |
+
}
|
internal/auth/auth_test.go
CHANGED
|
@@ -1,266 +1,299 @@
|
|
| 1 |
-
package auth
|
| 2 |
-
|
| 3 |
-
import (
|
| 4 |
-
"
|
| 5 |
-
"
|
| 6 |
-
"
|
| 7 |
-
"
|
| 8 |
-
"
|
| 9 |
-
"
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
}
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
os.WriteFile(filepath.Join(dir, "workbuddy-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
}
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
|
| 134 |
-
|
| 135 |
-
|
| 136 |
-
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
|
| 141 |
-
|
| 142 |
-
|
| 143 |
-
|
| 144 |
-
|
| 145 |
-
|
| 146 |
-
|
| 147 |
-
|
| 148 |
-
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
|
| 152 |
-
"workbuddy-
|
| 153 |
-
|
| 154 |
-
|
| 155 |
-
|
| 156 |
-
|
| 157 |
-
|
| 158 |
-
|
| 159 |
-
|
| 160 |
-
|
| 161 |
-
|
| 162 |
-
|
| 163 |
-
|
| 164 |
-
|
| 165 |
-
|
| 166 |
-
|
| 167 |
-
|
| 168 |
-
|
| 169 |
-
|
| 170 |
-
|
| 171 |
-
|
| 172 |
-
|
| 173 |
-
|
| 174 |
-
|
| 175 |
-
|
| 176 |
-
|
| 177 |
-
|
| 178 |
-
|
| 179 |
-
|
| 180 |
-
|
| 181 |
-
|
| 182 |
-
|
| 183 |
-
|
| 184 |
-
|
| 185 |
-
|
| 186 |
-
}
|
| 187 |
-
|
| 188 |
-
|
| 189 |
-
|
| 190 |
-
//
|
| 191 |
-
|
| 192 |
-
|
| 193 |
-
|
| 194 |
-
|
| 195 |
-
|
| 196 |
-
|
| 197 |
-
|
| 198 |
-
|
| 199 |
-
|
| 200 |
-
|
| 201 |
-
|
| 202 |
-
|
| 203 |
-
|
| 204 |
-
|
| 205 |
-
|
| 206 |
-
|
| 207 |
-
|
| 208 |
-
|
| 209 |
-
|
| 210 |
-
|
| 211 |
-
|
| 212 |
-
|
| 213 |
-
|
| 214 |
-
|
| 215 |
-
|
| 216 |
-
|
| 217 |
-
|
| 218 |
-
|
| 219 |
-
|
| 220 |
-
|
| 221 |
-
|
| 222 |
-
|
| 223 |
-
|
| 224 |
-
//
|
| 225 |
-
|
| 226 |
-
|
| 227 |
-
|
| 228 |
-
|
| 229 |
-
|
| 230 |
-
|
| 231 |
-
|
| 232 |
-
|
| 233 |
-
|
| 234 |
-
|
| 235 |
-
|
| 236 |
-
|
| 237 |
-
|
| 238 |
-
|
| 239 |
-
|
| 240 |
-
|
| 241 |
-
|
| 242 |
-
|
| 243 |
-
|
| 244 |
-
|
| 245 |
-
|
| 246 |
-
|
| 247 |
-
|
| 248 |
-
|
| 249 |
-
|
| 250 |
-
|
| 251 |
-
|
| 252 |
-
|
| 253 |
-
|
| 254 |
-
|
| 255 |
-
|
| 256 |
-
|
| 257 |
-
|
| 258 |
-
|
| 259 |
-
|
| 260 |
-
|
| 261 |
-
|
| 262 |
-
|
| 263 |
-
|
| 264 |
-
|
| 265 |
-
|
| 266 |
-
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
package auth
|
| 2 |
+
|
| 3 |
+
import (
|
| 4 |
+
"fmt"
|
| 5 |
+
"io"
|
| 6 |
+
"log"
|
| 7 |
+
"os"
|
| 8 |
+
"path/filepath"
|
| 9 |
+
"strings"
|
| 10 |
+
"testing"
|
| 11 |
+
"time"
|
| 12 |
+
)
|
| 13 |
+
|
| 14 |
+
func TestParseNested(t *testing.T) {
|
| 15 |
+
raw := []byte(`{"auth":{"accessToken":"at","refreshToken":"rt","expiresAt":1753600000,"domain":""},"account":{"uid":"u1","enterpriseId":"e1","nickname":"n1"}}`)
|
| 16 |
+
sa, err := Parse(raw)
|
| 17 |
+
if err != nil {
|
| 18 |
+
t.Fatalf("nested parse err: %v", err)
|
| 19 |
+
}
|
| 20 |
+
if sa.AccessToken != "at" || sa.RefreshToken != "rt" || sa.ExpiresAt != 1753600000 {
|
| 21 |
+
t.Errorf("tokens: %+v", sa)
|
| 22 |
+
}
|
| 23 |
+
if sa.UID != "u1" || sa.EnterpriseID != "e1" || sa.Nickname != "n1" {
|
| 24 |
+
t.Errorf("account: %+v", sa)
|
| 25 |
+
}
|
| 26 |
+
}
|
| 27 |
+
|
| 28 |
+
func TestParseFlat(t *testing.T) {
|
| 29 |
+
raw := []byte(`{"accessToken":"at","refreshToken":"rt","expiresAt":1753600000,"uid":"u2","nickname":"n2"}`)
|
| 30 |
+
sa, err := Parse(raw)
|
| 31 |
+
if err != nil || sa.UID != "u2" || sa.AccessToken != "at" {
|
| 32 |
+
t.Fatalf("flat: %+v %v", sa, err)
|
| 33 |
+
}
|
| 34 |
+
}
|
| 35 |
+
|
| 36 |
+
func TestParseMissingToken(t *testing.T) {
|
| 37 |
+
if _, err := Parse([]byte(`{"uid":"u3"}`)); err == nil {
|
| 38 |
+
t.Fatal("want error for missing accessToken")
|
| 39 |
+
}
|
| 40 |
+
}
|
| 41 |
+
|
| 42 |
+
func TestSaveAtomicRoundtrip(t *testing.T) {
|
| 43 |
+
dir := t.TempDir()
|
| 44 |
+
fp := filepath.Join(dir, "workbuddy-u1.json")
|
| 45 |
+
a := &Auth{AccessToken: "at", RefreshToken: "rt", ExpiresAt: 1753600000,
|
| 46 |
+
UID: "u1", EnterpriseID: "e1", Nickname: "n1", FilePath: fp}
|
| 47 |
+
if err := a.SaveAtomic(); err != nil {
|
| 48 |
+
t.Fatalf("save: %v", err)
|
| 49 |
+
}
|
| 50 |
+
if _, err := os.Stat(fp + ".tmp"); !os.IsNotExist(err) {
|
| 51 |
+
t.Error("tmp file should not remain")
|
| 52 |
+
}
|
| 53 |
+
raw, err := os.ReadFile(fp)
|
| 54 |
+
if err != nil {
|
| 55 |
+
t.Fatalf("read: %v", err)
|
| 56 |
+
}
|
| 57 |
+
b, err := Parse(raw)
|
| 58 |
+
if err != nil {
|
| 59 |
+
t.Fatalf("reparse: %v", err)
|
| 60 |
+
}
|
| 61 |
+
if b.AccessToken != "at" || b.UID != "u1" || b.EnterpriseID != "e1" {
|
| 62 |
+
t.Errorf("roundtrip: %+v", b)
|
| 63 |
+
}
|
| 64 |
+
}
|
| 65 |
+
|
| 66 |
+
// TestLoadDirLoadsAllValid 不再按 region 过滤:所有可解析的 auth 文件都被加载,
|
| 67 |
+
// 解析失败的文件静默跳过。
|
| 68 |
+
func TestLoadDirLoadsAllValid(t *testing.T) {
|
| 69 |
+
dir := t.TempDir()
|
| 70 |
+
cn := `{"auth":{"accessToken":"at1","refreshToken":"r","expiresAt":1,"domain":""},"account":{"uid":"cn1"}}`
|
| 71 |
+
other := `{"auth":{"accessToken":"at2","refreshToken":"r","expiresAt":1,"domain":"example.com"},"account":{"uid":"u2"}}`
|
| 72 |
+
bad := `not json`
|
| 73 |
+
os.WriteFile(filepath.Join(dir, "workbuddy-cn1.json"), []byte(cn), 0o600)
|
| 74 |
+
os.WriteFile(filepath.Join(dir, "workbuddy-u2.json"), []byte(other), 0o600)
|
| 75 |
+
os.WriteFile(filepath.Join(dir, "workbuddy-bad.json"), []byte(bad), 0o600)
|
| 76 |
+
|
| 77 |
+
list, err := LoadDir(dir)
|
| 78 |
+
if err != nil {
|
| 79 |
+
t.Fatalf("load: %v", err)
|
| 80 |
+
}
|
| 81 |
+
if len(list) != 2 {
|
| 82 |
+
t.Fatalf("want 2 valid accounts, got %+v", list)
|
| 83 |
+
}
|
| 84 |
+
for _, a := range list {
|
| 85 |
+
if a.FilePath == "" {
|
| 86 |
+
t.Error("FilePath not set")
|
| 87 |
+
}
|
| 88 |
+
}
|
| 89 |
+
}
|
| 90 |
+
|
| 91 |
+
func TestNeedsRefresh(t *testing.T) {
|
| 92 |
+
a := &Auth{ExpiresAt: 0}
|
| 93 |
+
if !a.NeedsRefresh(0) {
|
| 94 |
+
t.Error("zero expiry should need refresh")
|
| 95 |
+
}
|
| 96 |
+
a.ExpiresAt = 9999999999
|
| 97 |
+
if a.NeedsRefresh(0) {
|
| 98 |
+
t.Error("far future should not need refresh")
|
| 99 |
+
}
|
| 100 |
+
}
|
| 101 |
+
|
| 102 |
+
// TestParseDeviceToken 嵌套形与扁平形 auth 文件的顶层 device_token 键均被解析。
|
| 103 |
+
func TestParseDeviceToken(t *testing.T) {
|
| 104 |
+
nested := []byte(`{"auth":{"accessToken":"at","refreshToken":"rt","expiresAt":1,"domain":""},"account":{"uid":"u1"},"device_token":"dev-tok-nested"}`)
|
| 105 |
+
sa, err := Parse(nested)
|
| 106 |
+
if err != nil {
|
| 107 |
+
t.Fatalf("nested parse: %v", err)
|
| 108 |
+
}
|
| 109 |
+
if sa.DeviceToken != "dev-tok-nested" {
|
| 110 |
+
t.Errorf("nested DeviceToken = %q want %q", sa.DeviceToken, "dev-tok-nested")
|
| 111 |
+
}
|
| 112 |
+
|
| 113 |
+
flat := []byte(`{"accessToken":"at","refreshToken":"rt","expiresAt":1,"uid":"u2","device_token":"dev-tok-flat"}`)
|
| 114 |
+
fa, err := Parse(flat)
|
| 115 |
+
if err != nil {
|
| 116 |
+
t.Fatalf("flat parse: %v", err)
|
| 117 |
+
}
|
| 118 |
+
if fa.DeviceToken != "dev-tok-flat" {
|
| 119 |
+
t.Errorf("flat DeviceToken = %q want %q", fa.DeviceToken, "dev-tok-flat")
|
| 120 |
+
}
|
| 121 |
+
}
|
| 122 |
+
|
| 123 |
+
// TestSaveAtomicPreservesDeviceToken SaveAtomic 写回后顶层 device_token 被保留并重新解析回来。
|
| 124 |
+
func TestSaveAtomicPreservesDeviceToken(t *testing.T) {
|
| 125 |
+
dir := t.TempDir()
|
| 126 |
+
fp := filepath.Join(dir, "workbuddy-dt.json")
|
| 127 |
+
a := &Auth{AccessToken: "at", RefreshToken: "rt", ExpiresAt: 1,
|
| 128 |
+
UID: "u1", DeviceToken: "persisted-tok", FilePath: fp}
|
| 129 |
+
if err := a.SaveAtomic(); err != nil {
|
| 130 |
+
t.Fatalf("save: %v", err)
|
| 131 |
+
}
|
| 132 |
+
raw, err := os.ReadFile(fp)
|
| 133 |
+
if err != nil {
|
| 134 |
+
t.Fatalf("read: %v", err)
|
| 135 |
+
}
|
| 136 |
+
b, err := Parse(raw)
|
| 137 |
+
if err != nil {
|
| 138 |
+
t.Fatalf("reparse: %v", err)
|
| 139 |
+
}
|
| 140 |
+
if b.DeviceToken != "persisted-tok" {
|
| 141 |
+
t.Errorf("roundtrip DeviceToken = %q want %q", b.DeviceToken, "persisted-tok")
|
| 142 |
+
}
|
| 143 |
+
}
|
| 144 |
+
|
| 145 |
+
// TestLoadDirBackfillsRealm 存量迁移:LoadDir 加载目录时对空 realm 的 auth 自动
|
| 146 |
+
// backfill + SaveAtomic;已有 realm 的保持原值(不被 domain 覆盖);文件全部带标识。
|
| 147 |
+
func TestLoadDirBackfillsRealm(t *testing.T) {
|
| 148 |
+
t.Parallel()
|
| 149 |
+
dir := t.TempDir()
|
| 150 |
+
fixtures := map[string]string{
|
| 151 |
+
"workbuddy-g1.json": `{"auth":{"accessToken":"at","refreshToken":"r","expiresAt":1,"domain":"www.workbuddy.ai"},"account":{"uid":"g1"}}`,
|
| 152 |
+
"workbuddy-c1.json": `{"auth":{"accessToken":"at","refreshToken":"r","expiresAt":1,"domain":""},"account":{"uid":"c1"}}`,
|
| 153 |
+
// 已有 realm 的不因 domain 变化被覆��:global domain + 显式 cn → 保持 cn
|
| 154 |
+
"workbuddy-c2.json": `{"auth":{"accessToken":"at","refreshToken":"r","expiresAt":1,"domain":"www.workbuddy.ai","realm":"cn"},"account":{"uid":"c2"}}`,
|
| 155 |
+
}
|
| 156 |
+
for name, body := range fixtures {
|
| 157 |
+
if err := os.WriteFile(filepath.Join(dir, name), []byte(body), 0o600); err != nil {
|
| 158 |
+
t.Fatal(err)
|
| 159 |
+
}
|
| 160 |
+
}
|
| 161 |
+
|
| 162 |
+
list, err := LoadDir(dir)
|
| 163 |
+
if err != nil {
|
| 164 |
+
t.Fatalf("load: %v", err)
|
| 165 |
+
}
|
| 166 |
+
if len(list) != 3 {
|
| 167 |
+
t.Fatalf("want 3 accounts, got %d", len(list))
|
| 168 |
+
}
|
| 169 |
+
want := map[string]string{"g1": "global", "c1": "cn", "c2": "cn"}
|
| 170 |
+
for _, a := range list {
|
| 171 |
+
// 内存态已补标识
|
| 172 |
+
if got := a.RealmStored(); got != want[a.UID] {
|
| 173 |
+
t.Errorf("uid=%s in-memory realm=%q want %q", a.UID, got, want[a.UID])
|
| 174 |
+
}
|
| 175 |
+
// 落盘文件也带 realm 键
|
| 176 |
+
raw, err := os.ReadFile(a.FilePath)
|
| 177 |
+
if err != nil {
|
| 178 |
+
t.Fatalf("read %s: %v", a.FilePath, err)
|
| 179 |
+
}
|
| 180 |
+
b, err := Parse(raw)
|
| 181 |
+
if err != nil {
|
| 182 |
+
t.Fatalf("reparse %s: %v", a.FilePath, err)
|
| 183 |
+
}
|
| 184 |
+
if got := b.RealmStored(); got != want[a.UID] {
|
| 185 |
+
t.Errorf("uid=%s on-disk realm=%q want %q", a.UID, got, want[a.UID])
|
| 186 |
+
}
|
| 187 |
+
}
|
| 188 |
+
}
|
| 189 |
+
|
| 190 |
+
// TestLoadDirBackfillWriteFailureDoesNotBlock 单个文件 backfill 落盘失败(tmp 预置目录
|
| 191 |
+
// 使 WriteFile 失败)不阻断启动:其他文件照常迁移,LoadDir 不向上抛错。
|
| 192 |
+
// (历史纯 CN auth 目录一次性迁移时,个别文件不可写不应让整个服务起不来。)
|
| 193 |
+
func TestLoadDirBackfillWriteFailureDoesNotBlock(t *testing.T) {
|
| 194 |
+
t.Parallel()
|
| 195 |
+
dir := t.TempDir()
|
| 196 |
+
good := `{"auth":{"accessToken":"at","refreshToken":"r","expiresAt":1,"domain":"www.workbuddy.ai"},"account":{"uid":"g1"}}`
|
| 197 |
+
if err := os.WriteFile(filepath.Join(dir, "workbuddy-g1.json"), []byte(good), 0o600); err != nil {
|
| 198 |
+
t.Fatal(err)
|
| 199 |
+
}
|
| 200 |
+
// 预置同名 .tmp 目录 → SaveAtomic 的 os.WriteFile(".tmp") 报 is a directory。
|
| 201 |
+
if err := os.Mkdir(filepath.Join(dir, "workbuddy-c1.json.tmp"), 0o700); err != nil {
|
| 202 |
+
t.Fatal(err)
|
| 203 |
+
}
|
| 204 |
+
bad := `{"auth":{"accessToken":"at","refreshToken":"r","expiresAt":1},"account":{"uid":"c1"}}`
|
| 205 |
+
if err := os.WriteFile(filepath.Join(dir, "workbuddy-c1.json"), []byte(bad), 0o600); err != nil {
|
| 206 |
+
t.Fatal(err)
|
| 207 |
+
}
|
| 208 |
+
|
| 209 |
+
list, err := LoadDir(dir)
|
| 210 |
+
if err != nil {
|
| 211 |
+
t.Fatalf("load err=%v want nil (write failure must not block startup)", err)
|
| 212 |
+
}
|
| 213 |
+
if len(list) != 2 {
|
| 214 |
+
t.Fatalf("want 2 accounts loaded, got %d", len(list))
|
| 215 |
+
}
|
| 216 |
+
// 好文件迁移成功
|
| 217 |
+
raw, _ := os.ReadFile(filepath.Join(dir, "workbuddy-g1.json"))
|
| 218 |
+
b, _ := Parse(raw)
|
| 219 |
+
if b.RealmStored() != "global" {
|
| 220 |
+
t.Errorf("good file realm=%q want global (migration should succeed)", b.RealmStored())
|
| 221 |
+
}
|
| 222 |
+
}
|
| 223 |
+
|
| 224 |
+
// TestLoadDirNewestFileWinsForDuplicateUID 同一 uid 多份文件时,最后一项必须是 mtime 最新的那份
|
| 225 |
+
// ——pool.SyncToDir 的 upsert 是「后载入者胜出」,所以 LoadDir 的顺序决定了哪个凭证活下来。
|
| 226 |
+
// 客户端会写 <name>.<ts>.<pid>.<uuid>.info 这类轮转备份,字典序可能让陈旧备份排在后面。
|
| 227 |
+
func TestLoadDirNewestFileWinsForDuplicateUID(t *testing.T) {
|
| 228 |
+
dir := t.TempDir()
|
| 229 |
+
write := func(name, at string, mt time.Time) {
|
| 230 |
+
body := fmt.Sprintf(`{"auth":{"accessToken":%q,"refreshToken":"r","expiresAt":1800000000,"domain":"www.codebuddy.cn"},"account":{"uid":"u7"}}`, at)
|
| 231 |
+
p := filepath.Join(dir, name)
|
| 232 |
+
if err := os.WriteFile(p, []byte(body), 0o600); err != nil {
|
| 233 |
+
t.Fatal(err)
|
| 234 |
+
}
|
| 235 |
+
if err := os.Chtimes(p, mt, mt); err != nil {
|
| 236 |
+
t.Fatal(err)
|
| 237 |
+
}
|
| 238 |
+
}
|
| 239 |
+
// 字典序在后、但内容陈旧的那份故意命名 workbuddy-z-,mtime 设为 2020。
|
| 240 |
+
write("workbuddy-z-stale.json", "at-stale", time.Date(2020, 1, 1, 0, 0, 0, 0, time.UTC))
|
| 241 |
+
write("workbuddy-a-fresh.json", "at-fresh", time.Date(2026, 1, 1, 0, 0, 0, 0, time.UTC))
|
| 242 |
+
|
| 243 |
+
list, err := LoadDir(dir)
|
| 244 |
+
if err != nil {
|
| 245 |
+
t.Fatalf("load err=%v", err)
|
| 246 |
+
}
|
| 247 |
+
if len(list) != 2 {
|
| 248 |
+
t.Fatalf("want 2 files loaded, got %d", len(list))
|
| 249 |
+
}
|
| 250 |
+
if got := list[len(list)-1].AccessToken; got != "at-fresh" {
|
| 251 |
+
t.Fatalf("最后一项应是 mtime 最新的凭证(pool 按后载入者胜出),实际 %q", got)
|
| 252 |
+
}
|
| 253 |
+
}
|
| 254 |
+
|
| 255 |
+
// TestLoadDirDuplicateUIDWarning 同 UID 双 realm auth 文件(概率近零的 EDGE):LoadDir
|
| 256 |
+
// 检测到重复 UID 时打 WARN(含两文件路径),且不改变加载行为——后载入者胜出(返回 1 个、
|
| 257 |
+
// 不 panic、realm 为后载入者值)。LoadDir 现在有额外 seenUID 副作用,逐字验证 WARN。
|
| 258 |
+
func TestLoadDirDuplicateUIDWarning(t *testing.T) {
|
| 259 |
+
dir := t.TempDir()
|
| 260 |
+
// 同一 UID u9 的两个文件:cn realm 文件按文件名排序在前(workbuddy-a-...),
|
| 261 |
+
// global realm 文件在后 → 后载入者(global)胜出。
|
| 262 |
+
cn := `{"auth":{"accessToken":"at1","refreshToken":"r","expiresAt":1,"domain":"www.codebuddy.cn"},"account":{"uid":"u9"}}`
|
| 263 |
+
gl := `{"auth":{"accessToken":"at2","refreshToken":"r","expiresAt":1,"domain":"www.workbuddy.ai"},"account":{"uid":"u9"}}`
|
| 264 |
+
if err := os.WriteFile(filepath.Join(dir, "workbuddy-a-cn.json"), []byte(cn), 0o600); err != nil {
|
| 265 |
+
t.Fatal(err)
|
| 266 |
+
}
|
| 267 |
+
if err := os.WriteFile(filepath.Join(dir, "workbuddy-z-global.json"), []byte(gl), 0o600); err != nil {
|
| 268 |
+
t.Fatal(err)
|
| 269 |
+
}
|
| 270 |
+
|
| 271 |
+
// 捕获 log 输出(本测试不 t.Parallel:log.SetOutput 是进程级全局,需串行)。
|
| 272 |
+
old := log.Writer()
|
| 273 |
+
r, w, err := os.Pipe()
|
| 274 |
+
if err != nil {
|
| 275 |
+
t.Fatal(err)
|
| 276 |
+
}
|
| 277 |
+
log.SetOutput(w)
|
| 278 |
+
|
| 279 |
+
list, err := LoadDir(dir)
|
| 280 |
+
_ = w.Close()
|
| 281 |
+
raw, _ := io.ReadAll(r)
|
| 282 |
+
log.SetOutput(old)
|
| 283 |
+
|
| 284 |
+
if err != nil {
|
| 285 |
+
t.Fatalf("load err=%v", err)
|
| 286 |
+
}
|
| 287 |
+
// 行为稳定(不改加载结果):LoadDir 返回全部可解析文件(去重发生在 pool.SyncToDir
|
| 288 |
+
// 的 UID 键 upsert),不 panic。
|
| 289 |
+
if len(list) != 2 {
|
| 290 |
+
t.Fatalf("want 2 accounts loaded (dedup later in pool), got %d", len(list))
|
| 291 |
+
}
|
| 292 |
+
// WARN 已触发,含两文件路径,并点明真实成因(同一账号的个人版/企业版 uid 相同)。
|
| 293 |
+
if !strings.Contains(string(raw), "WARN: uid") ||
|
| 294 |
+
!strings.Contains(string(raw), "个人版/企业版") ||
|
| 295 |
+
!strings.Contains(string(raw), "workbuddy-a-cn.json") ||
|
| 296 |
+
!strings.Contains(string(raw), "workbuddy-z-global.json") {
|
| 297 |
+
t.Errorf("expected WARN with both paths, got output: %s", string(raw))
|
| 298 |
+
}
|
| 299 |
+
}
|
internal/auth/enterprise_test.go
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
package auth
|
| 2 |
+
|
| 3 |
+
import "testing"
|
| 4 |
+
|
| 5 |
+
// TestIsEnterprise 企业版判定:enterpriseId 非空即企业版(纯空白视为非企业)。
|
| 6 |
+
// 该判定驱动 scheduler 五类任务与 panel 成长任务/签到入口的门控——企业版在这些
|
| 7 |
+
// 端点上被上游一律拒绝(400 code 10001 / 403 growth-only),误判为个人号会导致
|
| 8 |
+
// 每日对注定失败的端点空发请求。
|
| 9 |
+
func TestIsEnterprise(t *testing.T) {
|
| 10 |
+
cases := []struct {
|
| 11 |
+
name string
|
| 12 |
+
ent string
|
| 13 |
+
want bool
|
| 14 |
+
}{
|
| 15 |
+
{"个人号(空)", "", false},
|
| 16 |
+
{"纯空白", " ", false},
|
| 17 |
+
{"企业号", "fn7xvyc51dkw", true},
|
| 18 |
+
}
|
| 19 |
+
for _, c := range cases {
|
| 20 |
+
t.Run(c.name, func(t *testing.T) {
|
| 21 |
+
a := &Auth{UID: "u1", EnterpriseID: c.ent}
|
| 22 |
+
if got := a.IsEnterprise(); got != c.want {
|
| 23 |
+
t.Errorf("EnterpriseID=%q IsEnterprise()=%v want %v", c.ent, got, c.want)
|
| 24 |
+
}
|
| 25 |
+
})
|
| 26 |
+
}
|
| 27 |
+
}
|
| 28 |
+
|
| 29 |
+
// TestIsEnterpriseAndIsGlobalIndependent 企业标识与 realm 是正交维度:
|
| 30 |
+
// 企业号恒为 CN realm,但两者判定互不干扰(门控引用处并列书写)。
|
| 31 |
+
func TestIsEnterpriseAndIsGlobalIndependent(t *testing.T) {
|
| 32 |
+
a := &Auth{UID: "u1", EnterpriseID: "ent-1"}
|
| 33 |
+
if !a.IsEnterprise() {
|
| 34 |
+
t.Error("应判为企业版")
|
| 35 |
+
}
|
| 36 |
+
if a.IsGlobal() {
|
| 37 |
+
t.Error("企业号不应被判为 global")
|
| 38 |
+
}
|
| 39 |
+
}
|
internal/auth/expires_test.go
ADDED
|
@@ -0,0 +1,88 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
package auth
|
| 2 |
+
|
| 3 |
+
import (
|
| 4 |
+
"testing"
|
| 5 |
+
"time"
|
| 6 |
+
)
|
| 7 |
+
|
| 8 |
+
// TestParseNormalizesOfficialCLIExpiresAt 覆盖官方 CLI 凭据文件的导入:
|
| 9 |
+
// 官方写 expiresAt 为**毫秒**,本仓内部按 Unix 秒。不归一会让到期时间落到公元
|
| 10 |
+
// 58800 年 → NeedsRefresh 恒 false → token 永不刷新 → 到期后账号静默 401。
|
| 11 |
+
func TestParseNormalizesOfficialCLIExpiresAt(t *testing.T) {
|
| 12 |
+
// 取自真实官方凭据文件(2026-10-24,www.codebuddy.ai)。
|
| 13 |
+
const cliMillis = 1795254516410
|
| 14 |
+
wantSec := int64(cliMillis / 1000)
|
| 15 |
+
|
| 16 |
+
raw := []byte(`{
|
| 17 |
+
"account": {"uid":"00000000-0000-4000-8000-000000000001","nickname":"misakano7545","uin":"000000000000"},
|
| 18 |
+
"auth": {"accessToken":"at","refreshToken":"rt","expiresAt":1795254516410,
|
| 19 |
+
"domain":"www.codebuddy.ai","tokenType":"Bearer","expiresIn":2418995}
|
| 20 |
+
}`)
|
| 21 |
+
a, err := Parse(raw)
|
| 22 |
+
if err != nil {
|
| 23 |
+
t.Fatalf("Parse: %v", err)
|
| 24 |
+
}
|
| 25 |
+
if a.ExpiresAt != wantSec {
|
| 26 |
+
t.Errorf("ExpiresAt=%d want %d(毫秒未归一)", a.ExpiresAt, wantSec)
|
| 27 |
+
}
|
| 28 |
+
// 归一后必须落在合理区间:距今不到 1 年(官方 expiresIn 约 28 天)。
|
| 29 |
+
if d := time.Until(time.Unix(a.ExpiresAt, 0)); d <= 0 || d > 400*24*time.Hour {
|
| 30 |
+
t.Errorf("归一后到期时间不合理:%v(now+%v)", time.Unix(a.ExpiresAt, 0), d)
|
| 31 |
+
}
|
| 32 |
+
// 官方国际站域必须判 global(否则错域路由)。
|
| 33 |
+
if got := a.Realm(); got != "global" {
|
| 34 |
+
t.Errorf("Realm()=%q want global", got)
|
| 35 |
+
}
|
| 36 |
+
// NeedsRefresh:28 天后到期的 token 现在不该被要求刷新。
|
| 37 |
+
if a.NeedsRefresh(time.Hour) {
|
| 38 |
+
t.Error("NeedsRefresh=true,说明到期时间仍被当成毫秒(未来过远)或已过期")
|
| 39 |
+
}
|
| 40 |
+
}
|
| 41 |
+
|
| 42 |
+
// TestParseKeepsSeconds 覆盖旧格式:秒制 expiresAt 必须原样保留(不能被误除以 1000)。
|
| 43 |
+
func TestParseKeepsSeconds(t *testing.T) {
|
| 44 |
+
const sec = int64(1795254516)
|
| 45 |
+
raw := []byte(`{"auth":{"accessToken":"at","refreshToken":"rt","expiresAt":1795254516,"domain":"www.codebuddy.cn"}}`)
|
| 46 |
+
a, err := Parse(raw)
|
| 47 |
+
if err != nil {
|
| 48 |
+
t.Fatalf("Parse: %v", err)
|
| 49 |
+
}
|
| 50 |
+
if a.ExpiresAt != sec {
|
| 51 |
+
t.Errorf("ExpiresAt=%d want %d(秒制被误改)", a.ExpiresAt, sec)
|
| 52 |
+
}
|
| 53 |
+
}
|
| 54 |
+
|
| 55 |
+
// TestParseFlatFormNormalizesToo 覆盖扁平形(手写 auth 文件):两条解析分支都必须归一。
|
| 56 |
+
func TestParseFlatFormNormalizesToo(t *testing.T) {
|
| 57 |
+
raw := []byte(`{"uid":"u1","accessToken":"at","refreshToken":"rt","expiresAt":1795254516410,"domain":"www.workbuddy.ai"}`)
|
| 58 |
+
a, err := Parse(raw)
|
| 59 |
+
if err != nil {
|
| 60 |
+
t.Fatalf("Parse: %v", err)
|
| 61 |
+
}
|
| 62 |
+
if a.ExpiresAt != 1795254516 {
|
| 63 |
+
t.Errorf("ExpiresAt=%d want 1795254516", a.ExpiresAt)
|
| 64 |
+
}
|
| 65 |
+
if got := a.Realm(); got != "global" {
|
| 66 |
+
t.Errorf("Realm()=%q want global", got)
|
| 67 |
+
}
|
| 68 |
+
}
|
| 69 |
+
|
| 70 |
+
// TestNormalizeExpiresAt 覆盖阈值边界:秒制最大合理值不动,毫秒制一律 /1000。
|
| 71 |
+
func TestNormalizeExpiresAt(t *testing.T) {
|
| 72 |
+
cases := []struct {
|
| 73 |
+
in int64
|
| 74 |
+
want int64
|
| 75 |
+
}{
|
| 76 |
+
{in: 0, want: 0},
|
| 77 |
+
{in: 1, want: 1},
|
| 78 |
+
{in: 1795254516, want: 1795254516}, // 秒制当前值
|
| 79 |
+
{in: expiresAtMillisThreshold, want: expiresAtMillisThreshold}, // 恰在阈值上:按秒(不越过才换算)
|
| 80 |
+
{in: expiresAtMillisThreshold + 1, want: (expiresAtMillisThreshold + 1) / 1000},
|
| 81 |
+
{in: 1795254516410, want: 1795254516}, // 毫秒制当前值
|
| 82 |
+
}
|
| 83 |
+
for _, c := range cases {
|
| 84 |
+
if got := normalizeExpiresAt(c.in); got != c.want {
|
| 85 |
+
t.Errorf("normalizeExpiresAt(%d)=%d want %d", c.in, got, c.want)
|
| 86 |
+
}
|
| 87 |
+
}
|
| 88 |
+
}
|
internal/auth/permhint_test.go
CHANGED
|
@@ -1,29 +1,29 @@
|
|
| 1 |
-
package auth
|
| 2 |
-
|
| 3 |
-
import (
|
| 4 |
-
"os"
|
| 5 |
-
"path/filepath"
|
| 6 |
-
"runtime"
|
| 7 |
-
"strings"
|
| 8 |
-
"testing"
|
| 9 |
-
)
|
| 10 |
-
|
| 11 |
-
// TestSaveAtomicPermissionHint 无写权限目录下保存,错误应包含 Docker chown 指引。
|
| 12 |
-
func TestSaveAtomicPermissionHint(t *testing.T) {
|
| 13 |
-
if runtime.GOOS == "windows" || os.Geteuid() == 0 {
|
| 14 |
-
t.Skip("Windows 无 POSIX 权限语义 / root 无权限限制,跳过")
|
| 15 |
-
}
|
| 16 |
-
dir := t.TempDir()
|
| 17 |
-
ro := filepath.Join(dir, "ro")
|
| 18 |
-
os.MkdirAll(ro, 0o555) // 只读目录
|
| 19 |
-
defer os.Chmod(ro, 0o755)
|
| 20 |
-
a := &Auth{AccessToken: "at", RefreshToken: "rt", ExpiresAt: 1,
|
| 21 |
-
UID: "u1", FilePath: filepath.Join(ro, "workbuddy-u1.json")}
|
| 22 |
-
err := a.SaveAtomic()
|
| 23 |
-
if err == nil {
|
| 24 |
-
t.Fatal("只读目录保存应失败")
|
| 25 |
-
}
|
| 26 |
-
if !strings.Contains(err.Error(), "chown") || !strings.Contains(err.Error(), "10001") {
|
| 27 |
-
t.Errorf("权限错误应包含 Docker 指引,实际: %v", err)
|
| 28 |
-
}
|
| 29 |
-
}
|
|
|
|
| 1 |
+
package auth
|
| 2 |
+
|
| 3 |
+
import (
|
| 4 |
+
"os"
|
| 5 |
+
"path/filepath"
|
| 6 |
+
"runtime"
|
| 7 |
+
"strings"
|
| 8 |
+
"testing"
|
| 9 |
+
)
|
| 10 |
+
|
| 11 |
+
// TestSaveAtomicPermissionHint 无写权限目录下保存,错误应包含 Docker chown 指引。
|
| 12 |
+
func TestSaveAtomicPermissionHint(t *testing.T) {
|
| 13 |
+
if runtime.GOOS == "windows" || os.Geteuid() == 0 {
|
| 14 |
+
t.Skip("Windows 无 POSIX 权限语义 / root 无权限限制,跳过")
|
| 15 |
+
}
|
| 16 |
+
dir := t.TempDir()
|
| 17 |
+
ro := filepath.Join(dir, "ro")
|
| 18 |
+
os.MkdirAll(ro, 0o555) // 只读目录
|
| 19 |
+
defer os.Chmod(ro, 0o755)
|
| 20 |
+
a := &Auth{AccessToken: "at", RefreshToken: "rt", ExpiresAt: 1,
|
| 21 |
+
UID: "u1", FilePath: filepath.Join(ro, "workbuddy-u1.json")}
|
| 22 |
+
err := a.SaveAtomic()
|
| 23 |
+
if err == nil {
|
| 24 |
+
t.Fatal("只读目录保存应失败")
|
| 25 |
+
}
|
| 26 |
+
if !strings.Contains(err.Error(), "chown") || !strings.Contains(err.Error(), "10001") {
|
| 27 |
+
t.Errorf("权限错误应包含 Docker 指引,实际: %v", err)
|
| 28 |
+
}
|
| 29 |
+
}
|
internal/auth/realm_test.go
CHANGED
|
@@ -1,275 +1,284 @@
|
|
| 1 |
-
package auth
|
| 2 |
-
|
| 3 |
-
import (
|
| 4 |
-
"os"
|
| 5 |
-
"path/filepath"
|
| 6 |
-
"testing"
|
| 7 |
-
)
|
| 8 |
-
|
| 9 |
-
// withGlobalEnabled 临时打开 global realm 开关(生产缺省即开,此辅助仅显式确保),
|
| 10 |
-
// 测试结束复位为开启态(缺省)。
|
| 11 |
-
func withGlobalEnabled(t *testing.T) {
|
| 12 |
-
t.Helper()
|
| 13 |
-
globalEnabled.Store(true)
|
| 14 |
-
t.Cleanup(func() { globalEnabled.Store(true) })
|
| 15 |
-
}
|
| 16 |
-
|
| 17 |
-
// withGlobalDisabled 临时关闭 global realm 开关(逃生门),测试结束复位为开启态(缺省)。
|
| 18 |
-
func withGlobalDisabled(t *testing.T) {
|
| 19 |
-
t.Helper()
|
| 20 |
-
globalEnabled.Store(false)
|
| 21 |
-
t.Cleanup(func() { globalEnabled.Store(true) })
|
| 22 |
-
}
|
| 23 |
-
|
| 24 |
-
func TestRealmExplicitGlobal(t *testing.T) {
|
| 25 |
-
withGlobalEnabled(t)
|
| 26 |
-
a := &Auth{realm: "global"}
|
| 27 |
-
if got := a.Realm(); got != "global" {
|
| 28 |
-
t.Errorf("Realm()=%q want global", got)
|
| 29 |
-
}
|
| 30 |
-
if !a.IsGlobal() {
|
| 31 |
-
t.Error("IsGlobal()=false want true")
|
| 32 |
-
}
|
| 33 |
-
}
|
| 34 |
-
|
| 35 |
-
func TestRealmExplicitCN(t *testing.T) {
|
| 36 |
-
a := &Auth{realm: "cn"}
|
| 37 |
-
if got := a.Realm(); got != "cn" {
|
| 38 |
-
t.Errorf("Realm()=%q want cn", got)
|
| 39 |
-
}
|
| 40 |
-
if a.IsGlobal() {
|
| 41 |
-
t.Error("IsGlobal()=true want false")
|
| 42 |
-
}
|
| 43 |
-
}
|
| 44 |
-
|
| 45 |
-
func TestRealmDomainFallback(t *testing.T) {
|
| 46 |
-
withGlobalEnabled(t)
|
| 47 |
-
cases := []struct{ domain, want string }{
|
| 48 |
-
{"www.workbuddy.ai", "global"},
|
| 49 |
-
{"workbuddy.ai", "global"},
|
| 50 |
-
{"sub.workbuddy.ai", "global"},
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
}
|
| 59 |
-
|
| 60 |
-
}
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
}
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
}
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
}
|
| 98 |
-
|
| 99 |
-
}
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
}
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
}
|
| 119 |
-
|
| 120 |
-
}
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
|
| 134 |
-
if err != nil {
|
| 135 |
-
t.Fatalf("nested
|
| 136 |
-
}
|
| 137 |
-
if
|
| 138 |
-
t.Errorf("nested
|
| 139 |
-
}
|
| 140 |
-
|
| 141 |
-
|
| 142 |
-
|
| 143 |
-
|
| 144 |
-
|
| 145 |
-
|
| 146 |
-
if
|
| 147 |
-
t.
|
| 148 |
-
}
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
|
| 152 |
-
|
| 153 |
-
|
| 154 |
-
|
| 155 |
-
|
| 156 |
-
|
| 157 |
-
|
| 158 |
-
if
|
| 159 |
-
t.
|
| 160 |
-
}
|
| 161 |
-
if
|
| 162 |
-
t.
|
| 163 |
-
}
|
| 164 |
-
|
| 165 |
-
|
| 166 |
-
|
| 167 |
-
|
| 168 |
-
|
| 169 |
-
|
| 170 |
-
|
| 171 |
-
|
| 172 |
-
|
| 173 |
-
|
| 174 |
-
|
| 175 |
-
|
| 176 |
-
|
| 177 |
-
|
| 178 |
-
|
| 179 |
-
|
| 180 |
-
|
| 181 |
-
|
| 182 |
-
|
| 183 |
-
|
| 184 |
-
|
| 185 |
-
|
| 186 |
-
|
| 187 |
-
|
| 188 |
-
|
| 189 |
-
|
| 190 |
-
|
| 191 |
-
|
| 192 |
-
|
| 193 |
-
|
| 194 |
-
|
| 195 |
-
|
| 196 |
-
|
| 197 |
-
}
|
| 198 |
-
|
| 199 |
-
|
| 200 |
-
|
| 201 |
-
|
| 202 |
-
|
| 203 |
-
|
| 204 |
-
|
| 205 |
-
|
| 206 |
-
|
| 207 |
-
|
| 208 |
-
|
| 209 |
-
|
| 210 |
-
}
|
| 211 |
-
|
| 212 |
-
|
| 213 |
-
|
| 214 |
-
|
| 215 |
-
|
| 216 |
-
|
| 217 |
-
|
| 218 |
-
|
| 219 |
-
|
| 220 |
-
|
| 221 |
-
|
| 222 |
-
|
| 223 |
-
|
| 224 |
-
}
|
| 225 |
-
|
| 226 |
-
|
| 227 |
-
|
| 228 |
-
|
| 229 |
-
|
| 230 |
-
|
| 231 |
-
|
| 232 |
-
|
| 233 |
-
}
|
| 234 |
-
|
| 235 |
-
|
| 236 |
-
|
| 237 |
-
|
| 238 |
-
a
|
| 239 |
-
|
| 240 |
-
|
| 241 |
-
|
| 242 |
-
|
| 243 |
-
|
| 244 |
-
|
| 245 |
-
|
| 246 |
-
|
| 247 |
-
}
|
| 248 |
-
|
| 249 |
-
|
| 250 |
-
|
| 251 |
-
|
| 252 |
-
|
| 253 |
-
|
| 254 |
-
}
|
| 255 |
-
|
| 256 |
-
|
| 257 |
-
|
| 258 |
-
func
|
| 259 |
-
t.
|
| 260 |
-
|
| 261 |
-
|
| 262 |
-
}
|
| 263 |
-
|
| 264 |
-
|
| 265 |
-
|
| 266 |
-
|
| 267 |
-
|
| 268 |
-
|
| 269 |
-
|
| 270 |
-
|
| 271 |
-
|
| 272 |
-
|
| 273 |
-
}
|
| 274 |
-
|
| 275 |
-
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
package auth
|
| 2 |
+
|
| 3 |
+
import (
|
| 4 |
+
"os"
|
| 5 |
+
"path/filepath"
|
| 6 |
+
"testing"
|
| 7 |
+
)
|
| 8 |
+
|
| 9 |
+
// withGlobalEnabled 临时打开 global realm 开关(生产缺省即开,此辅助仅显式确保),
|
| 10 |
+
// 测试结束复位为开启态(缺省)。
|
| 11 |
+
func withGlobalEnabled(t *testing.T) {
|
| 12 |
+
t.Helper()
|
| 13 |
+
globalEnabled.Store(true)
|
| 14 |
+
t.Cleanup(func() { globalEnabled.Store(true) })
|
| 15 |
+
}
|
| 16 |
+
|
| 17 |
+
// withGlobalDisabled 临时关闭 global realm 开关(逃生门),测试结束复位为开启态(缺省)。
|
| 18 |
+
func withGlobalDisabled(t *testing.T) {
|
| 19 |
+
t.Helper()
|
| 20 |
+
globalEnabled.Store(false)
|
| 21 |
+
t.Cleanup(func() { globalEnabled.Store(true) })
|
| 22 |
+
}
|
| 23 |
+
|
| 24 |
+
func TestRealmExplicitGlobal(t *testing.T) {
|
| 25 |
+
withGlobalEnabled(t)
|
| 26 |
+
a := &Auth{realm: "global"}
|
| 27 |
+
if got := a.Realm(); got != "global" {
|
| 28 |
+
t.Errorf("Realm()=%q want global", got)
|
| 29 |
+
}
|
| 30 |
+
if !a.IsGlobal() {
|
| 31 |
+
t.Error("IsGlobal()=false want true")
|
| 32 |
+
}
|
| 33 |
+
}
|
| 34 |
+
|
| 35 |
+
func TestRealmExplicitCN(t *testing.T) {
|
| 36 |
+
a := &Auth{realm: "cn"}
|
| 37 |
+
if got := a.Realm(); got != "cn" {
|
| 38 |
+
t.Errorf("Realm()=%q want cn", got)
|
| 39 |
+
}
|
| 40 |
+
if a.IsGlobal() {
|
| 41 |
+
t.Error("IsGlobal()=true want false")
|
| 42 |
+
}
|
| 43 |
+
}
|
| 44 |
+
|
| 45 |
+
func TestRealmDomainFallback(t *testing.T) {
|
| 46 |
+
withGlobalEnabled(t)
|
| 47 |
+
cases := []struct{ domain, want string }{
|
| 48 |
+
{"www.workbuddy.ai", "global"},
|
| 49 |
+
{"workbuddy.ai", "global"},
|
| 50 |
+
{"sub.workbuddy.ai", "global"},
|
| 51 |
+
// 官方 CLI 国际站域(product.json externalDomain):不认它会把国际站账号
|
| 52 |
+
// 误判成 cn,手写 auth 文件(无显式 realm 键)直接错域路由。
|
| 53 |
+
{"www.codebuddy.ai", "global"},
|
| 54 |
+
{"codebuddy.ai", "global"},
|
| 55 |
+
{"api.codebuddy.ai", "global"},
|
| 56 |
+
{"WWW.CODEBUDDY.AI", "global"},
|
| 57 |
+
{"www.codebuddy.cn", "cn"},
|
| 58 |
+
{"", "cn"},
|
| 59 |
+
// 相似后缀不能误吞(HasSuffix 必须带点)。
|
| 60 |
+
{"evilcodebuddy.ai", "cn"},
|
| 61 |
+
{"codebuddy.ai.evil.com", "cn"},
|
| 62 |
+
}
|
| 63 |
+
for _, c := range cases {
|
| 64 |
+
a := &Auth{Domain: c.domain}
|
| 65 |
+
if got := a.Realm(); got != c.want {
|
| 66 |
+
t.Errorf("Domain=%q Realm()=%q want %q", c.domain, got, c.want)
|
| 67 |
+
}
|
| 68 |
+
}
|
| 69 |
+
}
|
| 70 |
+
|
| 71 |
+
func TestRealmEmptyFallsBackToCN(t *testing.T) {
|
| 72 |
+
// 开关缺省开启(零回归前提):空 realm + 空 domain → cn(老 CN 凭证的核心)。
|
| 73 |
+
a := &Auth{}
|
| 74 |
+
if got := a.Realm(); got != "cn" {
|
| 75 |
+
t.Errorf("Realm()=%q want cn", got)
|
| 76 |
+
}
|
| 77 |
+
// 显式 global → global(缺省开启,Realm() 不再因"未配置"而恒 cn)。
|
| 78 |
+
ag := &Auth{realm: "global"}
|
| 79 |
+
if got := ag.Realm(); got != "global" {
|
| 80 |
+
t.Errorf("Realm()=%q want global", got)
|
| 81 |
+
}
|
| 82 |
+
// domain 回落照常(缺省开启识别 workbuddy.ai)。
|
| 83 |
+
ad := &Auth{Domain: "www.workbuddy.ai"}
|
| 84 |
+
if got := ad.Realm(); got != "global" {
|
| 85 |
+
t.Errorf("Realm()=%q want global", got)
|
| 86 |
+
}
|
| 87 |
+
}
|
| 88 |
+
|
| 89 |
+
// TestRealmDefaultOnForCNZeroRegression 开关缺省开启时,老 CN 凭证(无 realm、无 domain)
|
| 90 |
+
// Realm() 恒为 cn——「默认开启」不影响纯 CN 部署行为。
|
| 91 |
+
func TestRealmDefaultOnForCNZeroRegression(t *testing.T) {
|
| 92 |
+
withGlobalEnabled(t)
|
| 93 |
+
cases := []*Auth{
|
| 94 |
+
{},
|
| 95 |
+
{Domain: "www.codebuddy.cn"},
|
| 96 |
+
{Domain: "codebuddy.cn"},
|
| 97 |
+
{realm: "cn"},
|
| 98 |
+
{realm: "cn", Domain: "www.codebuddy.cn"},
|
| 99 |
+
}
|
| 100 |
+
for _, a := range cases {
|
| 101 |
+
if got := a.Realm(); got != "cn" {
|
| 102 |
+
t.Errorf("%+v Realm()=%q want cn", a, got)
|
| 103 |
+
}
|
| 104 |
+
if a.IsGlobal() {
|
| 105 |
+
t.Errorf("%+v IsGlobal()=true want false", a)
|
| 106 |
+
}
|
| 107 |
+
}
|
| 108 |
+
}
|
| 109 |
+
|
| 110 |
+
// TestRealmExplicitOffEscapeHatch 逃生门:SetGlobalEnabled(false) 后恒 cn,
|
| 111 |
+
// 即便 realm=global / domain=workbuddy.ai(纯 CN 锁定,与旧缺省行为等价)。
|
| 112 |
+
func TestRealmExplicitOffEscapeHatch(t *testing.T) {
|
| 113 |
+
withGlobalDisabled(t)
|
| 114 |
+
cases := []struct {
|
| 115 |
+
auth *Auth
|
| 116 |
+
}{
|
| 117 |
+
{&Auth{realm: "global"}},
|
| 118 |
+
{&Auth{realm: "global", Domain: "www.workbuddy.ai"}},
|
| 119 |
+
{&Auth{Domain: "www.workbuddy.ai"}},
|
| 120 |
+
}
|
| 121 |
+
for _, tc := range cases {
|
| 122 |
+
if got := tc.auth.Realm(); got != "cn" {
|
| 123 |
+
t.Errorf("%+v Realm()=%q want cn (switch off)", tc.auth, got)
|
| 124 |
+
}
|
| 125 |
+
if tc.auth.IsGlobal() {
|
| 126 |
+
t.Errorf("%+v IsGlobal()=true want false (switch off)", tc.auth)
|
| 127 |
+
}
|
| 128 |
+
}
|
| 129 |
+
}
|
| 130 |
+
|
| 131 |
+
func TestParseNestedRealm(t *testing.T) {
|
| 132 |
+
raw := []byte(`{"auth":{"accessToken":"at","refreshToken":"rt","expiresAt":1,"domain":"www.workbuddy.ai","realm":"global"},"account":{"uid":"u1"}}`)
|
| 133 |
+
sa, err := Parse(raw)
|
| 134 |
+
if err != nil {
|
| 135 |
+
t.Fatalf("nested parse err: %v", err)
|
| 136 |
+
}
|
| 137 |
+
if sa.realm != "global" {
|
| 138 |
+
t.Errorf("nested realm=%q want global", sa.realm)
|
| 139 |
+
}
|
| 140 |
+
// 嵌套形显式 realm 空 → 读不到,靠 domain 回落。
|
| 141 |
+
raw2 := []byte(`{"auth":{"accessToken":"at","refreshToken":"rt","expiresAt":1},"account":{"uid":"u1"}}`)
|
| 142 |
+
sa2, err := Parse(raw2)
|
| 143 |
+
if err != nil {
|
| 144 |
+
t.Fatalf("nested no-realm parse err: %v", err)
|
| 145 |
+
}
|
| 146 |
+
if sa2.realm != "" {
|
| 147 |
+
t.Errorf("nested missing realm key should be zero, got %q", sa2.realm)
|
| 148 |
+
}
|
| 149 |
+
}
|
| 150 |
+
|
| 151 |
+
func TestParseFlatRealm(t *testing.T) {
|
| 152 |
+
withGlobalEnabled(t)
|
| 153 |
+
raw := []byte(`{"accessToken":"at","refreshToken":"rt","expiresAt":1,"uid":"u2","realm":"global"}`)
|
| 154 |
+
fa, err := Parse(raw)
|
| 155 |
+
if err != nil {
|
| 156 |
+
t.Fatalf("flat parse err: %v", err)
|
| 157 |
+
}
|
| 158 |
+
if fa.realm != "global" {
|
| 159 |
+
t.Errorf("flat realm=%q want global", fa.realm)
|
| 160 |
+
}
|
| 161 |
+
if !fa.IsGlobal() {
|
| 162 |
+
t.Error("flat global account IsGlobal()=false want true")
|
| 163 |
+
}
|
| 164 |
+
// 扁平形缺 realm 键 → 零值 → CN。
|
| 165 |
+
flatCN := []byte(`{"accessToken":"at","refreshToken":"rt","expiresAt":1,"uid":"u3"}`)
|
| 166 |
+
fc, err := Parse(flatCN)
|
| 167 |
+
if err != nil {
|
| 168 |
+
t.Fatalf("flat cn parse err: %v", err)
|
| 169 |
+
}
|
| 170 |
+
if fc.realm != "" {
|
| 171 |
+
t.Errorf("flat missing realm should be zero, got %q", fc.realm)
|
| 172 |
+
}
|
| 173 |
+
}
|
| 174 |
+
|
| 175 |
+
func TestSaveAtomicWritesRealm(t *testing.T) {
|
| 176 |
+
withGlobalEnabled(t)
|
| 177 |
+
dir := t.TempDir()
|
| 178 |
+
fp := filepath.Join(dir, "workbuddy-global.json")
|
| 179 |
+
a := &Auth{AccessToken: "at", RefreshToken: "rt", ExpiresAt: 1,
|
| 180 |
+
UID: "g1", realm: "global", FilePath: fp}
|
| 181 |
+
if err := a.SaveAtomic(); err != nil {
|
| 182 |
+
t.Fatalf("save: %v", err)
|
| 183 |
+
}
|
| 184 |
+
raw, err := os.ReadFile(fp)
|
| 185 |
+
if err != nil {
|
| 186 |
+
t.Fatalf("read: %v", err)
|
| 187 |
+
}
|
| 188 |
+
b, err := Parse(raw)
|
| 189 |
+
if err != nil {
|
| 190 |
+
t.Fatalf("reparse: %v", err)
|
| 191 |
+
}
|
| 192 |
+
if b.realm != "global" {
|
| 193 |
+
t.Errorf("roundtrip realm=%q want global", b.realm)
|
| 194 |
+
}
|
| 195 |
+
if !b.IsGlobal() {
|
| 196 |
+
t.Error("roundtrip global account IsGlobal()=false")
|
| 197 |
+
}
|
| 198 |
+
}
|
| 199 |
+
|
| 200 |
+
// TestBackfillRealmDomain CN/global 按原始 domain 推断(backfill 为导出空 realm 字段服务)。
|
| 201 |
+
func TestBackfillRealmDomain(t *testing.T) {
|
| 202 |
+
t.Parallel() // 不触碰全局开关
|
| 203 |
+
cases := []struct {
|
| 204 |
+
domain string
|
| 205 |
+
want string
|
| 206 |
+
}{
|
| 207 |
+
{"www.workbuddy.ai", "global"},
|
| 208 |
+
{"workbuddy.ai", "global"},
|
| 209 |
+
{"sub.workbuddy.ai", "global"},
|
| 210 |
+
{"www.codebuddy.cn", "cn"},
|
| 211 |
+
{"codebuddy.cn", "cn"},
|
| 212 |
+
{"", "cn"}, // 空 domain + 空 realm → cn(老 CN 凭证核心)
|
| 213 |
+
}
|
| 214 |
+
for _, c := range cases {
|
| 215 |
+
a := &Auth{Domain: c.domain}
|
| 216 |
+
changed, got := a.BackfillRealm()
|
| 217 |
+
if !changed {
|
| 218 |
+
t.Errorf("Domain=%q backfill changed=false want true", c.domain)
|
| 219 |
+
}
|
| 220 |
+
assertRealmStored(a, c.want, t)
|
| 221 |
+
if got != c.want {
|
| 222 |
+
t.Errorf("Domain=%q backfill got realm=%q want %q", c.domain, got, c.want)
|
| 223 |
+
}
|
| 224 |
+
}
|
| 225 |
+
}
|
| 226 |
+
|
| 227 |
+
// TestBackfillRealmEscapeHatchFree 逃生门关闭时 backfill 仍按原始 domain 推断(不受 Realm() 降级影响)。
|
| 228 |
+
func TestBackfillRealmEscapeHatchFree(t *testing.T) {
|
| 229 |
+
withGlobalDisabled(t) // 逃生门关闭:Realm() 恒 cn,但 backfill 不得被污染
|
| 230 |
+
a := &Auth{Domain: "www.workbuddy.ai"}
|
| 231 |
+
if g := a.Realm(); g != "cn" {
|
| 232 |
+
t.Fatalf("precondition Realm()=%q want cn (escape hatch on)", g)
|
| 233 |
+
}
|
| 234 |
+
changed, got := a.BackfillRealm()
|
| 235 |
+
if !changed {
|
| 236 |
+
t.Fatal("backfill changed=false want true (escape hatch free)")
|
| 237 |
+
}
|
| 238 |
+
assertRealmStored(a, "global", t)
|
| 239 |
+
if got != "global" {
|
| 240 |
+
t.Errorf("backfill got=%q want global (escape hatch must not corrupt backfill)", got)
|
| 241 |
+
}
|
| 242 |
+
}
|
| 243 |
+
|
| 244 |
+
// TestBackfillRealmIdempotent 已有 realm 标识的文件不做修改(幂等)。
|
| 245 |
+
func TestBackfillRealmIdempotent(t *testing.T) {
|
| 246 |
+
t.Parallel()
|
| 247 |
+
a := &Auth{Domain: "www.workbuddy.ai", realm: "cn"} // 已有 cn,domain 会推断 global——绝不覆盖
|
| 248 |
+
changed, got := a.BackfillRealm()
|
| 249 |
+
if changed {
|
| 250 |
+
t.Errorf("backfill changed=true want false (existing realm must win)")
|
| 251 |
+
}
|
| 252 |
+
if got != "cn" {
|
| 253 |
+
t.Errorf("backfill got=%q want cn (existing realm preserved)", got)
|
| 254 |
+
}
|
| 255 |
+
assertRealmStored(a, "cn", t)
|
| 256 |
+
}
|
| 257 |
+
|
| 258 |
+
func assertRealmStored(a *Auth, want string, t *testing.T) {
|
| 259 |
+
t.Helper()
|
| 260 |
+
if a.realm != want {
|
| 261 |
+
t.Errorf("stored realm field=%q want %q", a.realm, want)
|
| 262 |
+
}
|
| 263 |
+
}
|
| 264 |
+
|
| 265 |
+
// TestResolveRealm 纯函数归一化显式 realm,缺失时按 domain 推断(与 BackfillRealm
|
| 266 |
+
// 共用同一来源;不受逃生门影响)。显式值优先于 domain 推断。
|
| 267 |
+
func TestResolveRealm(t *testing.T) {
|
| 268 |
+
t.Parallel() // 纯函数:不触碰全局开关
|
| 269 |
+
cases := []struct {
|
| 270 |
+
explicit, domain, want string
|
| 271 |
+
}{
|
| 272 |
+
{"global", "www.codebuddy.cn", "global"}, // 显式优先:cn domain 也写 global
|
| 273 |
+
{"cn", "www.workbuddy.ai", "cn"}, // 显式优先:global domain 也写 cn
|
| 274 |
+
{"", "www.workbuddy.ai", "global"}, // 缺省按 domain 推断
|
| 275 |
+
{"", "workbuddy.ai", "global"},
|
| 276 |
+
{"", "codebuddy.cn", "cn"},
|
| 277 |
+
{"", "", "cn"}, // 空 domain → cn(老 CN 凭证零回归)
|
| 278 |
+
}
|
| 279 |
+
for _, c := range cases {
|
| 280 |
+
if got := ResolveRealm(c.explicit, c.domain); got != c.want {
|
| 281 |
+
t.Errorf("ResolveRealm(%q,%q)=%q want %q", c.explicit, c.domain, got, c.want)
|
| 282 |
+
}
|
| 283 |
+
}
|
| 284 |
+
}
|
internal/auth/recover_test.go
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
package auth
|
| 2 |
+
|
| 3 |
+
import (
|
| 4 |
+
"os"
|
| 5 |
+
"path/filepath"
|
| 6 |
+
"testing"
|
| 7 |
+
)
|
| 8 |
+
|
| 9 |
+
// 掉电把凭证文件留成全 0(长度不变、内容全空)时,账号不能凭空消失:
|
| 10 |
+
// 上一次写入留下的 .bak 顶上,该账号照常在池里。
|
| 11 |
+
func TestLoadDirRecoversZeroedAuthFile(t *testing.T) {
|
| 12 |
+
dir := t.TempDir()
|
| 13 |
+
fp := filepath.Join(dir, "workbuddy-u1.json")
|
| 14 |
+
a := &Auth{AccessToken: "at1", RefreshToken: "rt1", ExpiresAt: 1753600000, UID: "u1", FilePath: fp}
|
| 15 |
+
if err := a.SaveAtomic(); err != nil {
|
| 16 |
+
t.Fatalf("save: %v", err)
|
| 17 |
+
}
|
| 18 |
+
a.AccessToken = "at2" // 第二次写入 → .bak 里是 at1 那份
|
| 19 |
+
if err := a.SaveAtomic(); err != nil {
|
| 20 |
+
t.Fatalf("save: %v", err)
|
| 21 |
+
}
|
| 22 |
+
st, err := os.Stat(fp)
|
| 23 |
+
if err != nil {
|
| 24 |
+
t.Fatal(err)
|
| 25 |
+
}
|
| 26 |
+
if err := os.WriteFile(fp, make([]byte, st.Size()), 0o600); err != nil {
|
| 27 |
+
t.Fatal(err)
|
| 28 |
+
}
|
| 29 |
+
|
| 30 |
+
list, err := LoadDir(dir)
|
| 31 |
+
if err != nil {
|
| 32 |
+
t.Fatalf("load: %v", err)
|
| 33 |
+
}
|
| 34 |
+
if len(list) != 1 || list[0].UID != "u1" || list[0].AccessToken != "at1" {
|
| 35 |
+
t.Fatalf("want u1 recovered from .bak with at1, got %+v", list)
|
| 36 |
+
}
|
| 37 |
+
}
|
| 38 |
+
|
| 39 |
+
// 正文坏且没有 .bak:不静默跳过也不行,只能放弃这个文件——但不能影响别的账号。
|
| 40 |
+
func TestLoadDirSkipsUnrecoverableFile(t *testing.T) {
|
| 41 |
+
dir := t.TempDir()
|
| 42 |
+
good := filepath.Join(dir, "workbuddy-ok.json")
|
| 43 |
+
if err := os.WriteFile(good, []byte(`{"auth":{"accessToken":"at","refreshToken":"r","expiresAt":1},"account":{"uid":"ok"}}`), 0o600); err != nil {
|
| 44 |
+
t.Fatal(err)
|
| 45 |
+
}
|
| 46 |
+
if err := os.WriteFile(filepath.Join(dir, "workbuddy-bad.json"), []byte(`{"auth":`), 0o600); err != nil {
|
| 47 |
+
t.Fatal(err)
|
| 48 |
+
}
|
| 49 |
+
list, err := LoadDir(dir)
|
| 50 |
+
if err != nil {
|
| 51 |
+
t.Fatalf("load: %v", err)
|
| 52 |
+
}
|
| 53 |
+
if len(list) != 1 || list[0].UID != "ok" {
|
| 54 |
+
t.Fatalf("got %+v", list)
|
| 55 |
+
}
|
| 56 |
+
}
|
internal/auth/testdata/wbencrypted-auth.json
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"account": {
|
| 3 |
+
"uid": "uid-wb-1",
|
| 4 |
+
"uin": "10001",
|
| 5 |
+
"nickname": {
|
| 6 |
+
"$wbEncrypted": 1,
|
| 7 |
+
"envelope": "eyJzdWl0ZSI6MSwia2V5SWQiOiI5MTI3ZGVhMWI0NDAyMGE3Iiwibm9uY2UiOiJBQkVpTTBSVlpuZUltYXE3IiwiYXV0aFRhZyI6IkdaSTVGQ21wK1NiSmFISGk5bjZxRHc9PSIsImNpcGhlcnRleHQiOiJmRTJTKzJUd3p2TTN0NkZpT2NXZ1VLV2NleGtqRUk0TjF2Nkw0L1V5QURibFNFUzNlNEd6RGpZMjN4YXZ3NDhNQ3YwPSJ9"
|
| 8 |
+
},
|
| 9 |
+
"phoneNumber": {
|
| 10 |
+
"$wbEncrypted": 1,
|
| 11 |
+
"envelope": "eyJzdWl0ZSI6MSwia2V5SWQiOiI5MTI3ZGVhMWI0NDAyMGE3Iiwibm9uY2UiOiJBQkVpTTBSVlpuZUltYXE4IiwiYXV0aFRhZyI6Im52a1RZZTNHODZraUMvVzZ2SFdEU0E9PSIsImNpcGhlcnRleHQiOiIyNmtIT3haSTM3ejJrQzVsZU8zUHE4Z2ZEQkxkSFh3Y2FwTHRDZ2dzS0tSRWllWXJQaHNmM25zUHZhQ2Z0TnRpVmcrNCtPVHBRa0NmRHBJPSJ9"
|
| 12 |
+
}
|
| 13 |
+
},
|
| 14 |
+
"auth": {
|
| 15 |
+
"accessToken": {
|
| 16 |
+
"$wbEncrypted": 1,
|
| 17 |
+
"envelope": "eyJzdWl0ZSI6MSwia2V5SWQiOiI5MTI3ZGVhMWI0NDAyMGE3Iiwibm9uY2UiOiJBQkVpTTBSVlpuZUltYXE5IiwiYXV0aFRhZyI6ImJJQzJ1blJXVGdZMkxjN2JoUjBnUVE9PSIsImNpcGhlcnRleHQiOiJuWDRaYW8xLyttYndYT2xwRWZWRVIrcWlVUT09In0="
|
| 18 |
+
},
|
| 19 |
+
"refreshToken": {
|
| 20 |
+
"$wbEncrypted": 1,
|
| 21 |
+
"envelope": "eyJzdWl0ZSI6MSwia2V5SWQiOiI5MTI3ZGVhMWI0NDAyMGE3Iiwibm9uY2UiOiJBQkVpTTBSVlpuZUltYXErIiwiYXV0aFRhZyI6ImY5TjdMbjN5OEtpSzRhTVRmQk84UWc9PSIsImNpcGhlcnRleHQiOiJnQ2tnOWtmM1BYeWdjZVFnOUw1dXM0MmNEUT09In0="
|
| 22 |
+
},
|
| 23 |
+
"expiresAt": {
|
| 24 |
+
"$wbEncrypted": 1,
|
| 25 |
+
"envelope": "eyJzdWl0ZSI6MSwia2V5SWQiOiI5MTI3ZGVhMWI0NDAyMGE3Iiwibm9uY2UiOiJBQkVpTTBSVlpuZUltYXEvIiwiYXV0aFRhZyI6IlRDaStDN3BHSXpMZjQ1T0NUck1YS0E9PSIsImNpcGhlcnRleHQiOiJPN0RhR1ozemVCSWF5Rm9JQnc9PSJ9"
|
| 26 |
+
},
|
| 27 |
+
"domain": "workbuddy.cn",
|
| 28 |
+
"realm": "cn"
|
| 29 |
+
},
|
| 30 |
+
"device_token": "v3:test-device-token"
|
| 31 |
+
}
|