Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions PROPOSAL.md
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,7 @@ Provider 只管上游私有部分(发请求、解析事件、分类错误、
| 批量审计只记一条汇总 | 逐条审计 | 50 个号是一次操作、一个意图 |
| 窄屏表格卡片化改样式不改 DOM | 按视口渲染两套 JSX | 页面测试按 testid 断言,DOM 一变换语义就没了 |
| 凭证页一个渠道一个组,后端不拆行 | 每条 token 一行 | `refresh_token` 一次性且绑定 `client_id` + DPoP 私钥,拆行会二次刷新并烧票 |
| 登录后只对 officeAce 额外校验聊天凭据;`toggle enabled=true` 一并清硬禁用 | 所有渠道都在登录后探聊天 / 让启用与恢复严格分离 | officeAce 的额度/签到走控制面(临时 AK/SK)、聊天走不可续期的网关 Basic key,额度探测通过会掩盖网关 401;其他渠道登录下发的就是聊天凭据。硬禁用与软开关分两列易留 `enabled=1` 且 `disabled=1` 僵尸态,启用需让两列自洽(冷却仍归「恢复」) |
| 内置检索工具独立出口 | 只在 Responses 里映射 `web_search` | 先有可直连的出口,再谈把托管工具映射过来(未做) |

## 5. 安全边界(审查结论)
Expand Down
2 changes: 2 additions & 0 deletions README.en.md
Original file line number Diff line number Diff line change
Expand Up @@ -197,6 +197,7 @@ curl http://127.0.0.1:8000/v1/chat/completions \
- **Prerequisite**: the account must first sign in to the OfficeAce client and redeem an invite code, otherwise login "succeeds" but yields no model key → an explicit "account has not activated OfficeAce" error.
- **Two credential sets**: `Basic model_app_key:model_app_secret` (never expires, chat forwarding) and temporary AK/SK + `security_token` + `project_id` (~2 hours, quota queries / check-in). Mixing them yields `APIG.0303 app not found`. Temporary credentials are renewed by pre-refresh; `refresh_token` rotates once and is bound to `client_id=pdp5_for_agentarts` + the DPoP key (not interchangeable with CodeArts).
- **Re-login merges**: same `account_id` updates in place, clears "re-login required", preserves cooldowns, adds no duplicate.
- **`APIG.1009` cannot be fixed by re-login**: when the model gateway returns `401 AppKey or AppSecret is invalid`, the OAuth flow's `client-permission-validate` hands back the **same** `model_app_key/secret` already stored (measured 2026-12-01: three re-logins each returned the key the gateway was already rejecting). After saving a login, a read-only `list_models` check validates the chat credential; if upstream still classifies it DEAD, the credential is marked with "re-login is useless — re-attach the model in the OfficeAce client (Model → Attach model)" and that reason is returned to the UI (`warning`). The hard-disable reason is likewise no longer reported as a bare `session dead`.
- **Three protocol quirks**: rate limits arrive as fake 200 (`data:{"error":…}`, `81111/81114` cool only that credential × model); `81004` / `81009` are judged by business code before HTTP status → model-level negative cache (cleared on success); `max_tokens` is the total budget for reasoning + body (`≥16` adds 1024 then clamps to the model ceiling, `<16` passes through, absent stays absent).
- **Credits are the ledger**: unit `officeace_points`, each reward expires independently → "per-item expiry".
- **Check-in**: `POST /v1/subscription/bonus/claim` (a write; body must be `{}` with a JSON `Content-Type`; upstream is idempotent per day). Gains are computed from the remaining-balance delta and booked until the next Beijing midnight.
Expand Down Expand Up @@ -698,6 +699,7 @@ The table above marks only common hot-reloadable items; **89 items** in total (`
## Deployment notes

- **Platform: Linux / macOS only.** The single-instance lock (`src/instance_lock.py`) relies on `flock`; on Windows it exits with a readable Chinese message — use WSL2 / Docker. The `data/` `0700` trust boundary is enforced on Windows via `icacls` in `src/security/private_files.py`.
- **One writer per `DATA_DIR`**: never run a host process (`python -m src.main` / launchd) and a Docker container against the same `./data` at the same time. On macOS virtiofs, `flock` does not cross the host/container boundary: the container acquires the lock even while the host holds it, so the single-instance guard is void and two writers corrupt SQLite (observed as `database disk image is malformed`). When switching deployment modes, stop one side first (`launchctl bootout` or `docker compose stop`) and confirm the other is not running. Do not delete/modify `-wal`/`-shm` from the host while the container is running — that yields `disk I/O error`; stop the container for maintenance.
- **Mount ownership**: the container runs as uid 1001 (`appuser`) → `mkdir -p data secrets && sudo chown -R 1001:1001 data secrets`.
- **Time zone**: the image defaults to `TZ=Asia/Shanghai`; `TZ` from `.env` passes through. Check-in and quota periods key off "9am today", so it must match the host.
- **TRAE callback**: `PUBLIC_BASE_URL` is local-only by default; remote / container deployments must set a browser-reachable address. Forgetting it fails loudly: a loopback / `0.0.0.0` base falls back to the request origin and the *Add credential* dialog shows the effective address. If the callback is unreachable from the browser (common NAS / remote "network error"), paste the whole link from the address bar into the TRAE box — login works without the browser reaching this service.
Expand Down
6 changes: 4 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -200,6 +200,7 @@ curl http://127.0.0.1:8000/v1/chat/completions \
- **开通前提**:账号须先在 OfficeAce 客户端登录并兑换邀请码,否则登录「成功」但拿不到模型密钥 → 点名报「账号未开通 OfficeAce 服务」。
- **两套凭据**:`Basic model_app_key:model_app_secret`(不过期,聊天转发)与临时 AK/SK + `security_token` + `project_id`(约 2 小时,积分查询 / 签到)。混用得 `APIG.0303 app not found`。临时凭据由预刷新续期;`refresh_token` 一次性轮换,绑 `client_id=pdp5_for_agentarts` + DPoP 私钥(与 CodeArts 票不通用)。
- **重新登录合并**:同 `account_id` 就地更新并解除「需重新登录」,冷却保留,不新增重复账号。
- **`APIG.1009` 重登救不回来**:模型网关回 `401 AppKey or AppSecret is invalid` 时,OAuth 登录链路里的 `client-permission-validate` 原样下发**同一对** `model_app_key/secret`(实测 2026-12-01 连登三次、每次拿回的都是库里那把已在网关 401 的 key)。故登录落库后会额外用只读 `list_models` 校验聊天凭据:仍被上游判 DEAD 就写回「重登无效、需到 OfficeAce 客户端『模型 → 接入模型』重新接入」,并把该原因回给前端(`warning`)。硬禁用原因也据此区分,不再一律 `session dead`。
- **三处协议特例**:限流走伪 200(`data:{"error":…}`,`81111/81114` 只冷却「该凭据 × 该模型」);`81004` / `81009` 业务码先于状态码判定 → 模型级负缓存(成功即撤销);`max_tokens` = 推理 + 正文总预算(`≥16` 自动加 1024 余量再夹到硬上限,`<16` 原样,未给不补)。
- **积分即主账**:单位 `officeace_points`,每笔奖励独立到期不合并 → 「逐笔到期」。
- **签到**:`POST /v1/subscription/bonus/claim`(写操作,body 必须 `{}` 且带 JSON `Content-Type`;上游当日幂等)。收获按剩余量增量算,封账到下个北京时间 0 点。
Expand Down Expand Up @@ -386,11 +387,11 @@ curl -X POST http://127.0.0.1:8000/v1/fetch \

### 凭证暂停与批量运维

- **暂停** = 摘出对话 + 签到 / 预刷新跳过;其余后台任务(额度探测、成长、活跃上报)照常。适用「不接聊天、积分继续领」。≠「已禁用」(渠道判定会话失效后的系统禁用,需重登后「恢复」)。同一开关 `POST /api/credentials/{id}/toggle`。Zen / Kilo 是虚拟占位行,**暂停是永久停用的唯一方式**;暂停也会把该渠道从模型列表摘掉。
- **暂停** = 摘出对话 + 签到 / 预刷新跳过;其余后台任务(额度探测、成长、活跃上报)照常。适用「不接聊天、积分继续领」。≠「已禁用」(渠道判定会话失效后的系统禁用)。同一开关 `POST /api/credentials/{id}/toggle`;**`enabled=true` 会一并解除硬禁用**(否则留下 `enabled=1` 且 `disabled=1` 的僵尸态:点了「取消暂停」界面仍显示 session dead)。Zen / Kilo 是虚拟占位行,**暂停是永久停用的唯一方式**;暂停也会把该渠道从模型列表摘掉。
- **批量**:`POST /api/credentials/batch`,`{action: "probe"|"toggle"|"checkin"|"revive", ids: [...], enabled?, force?}`,一次 ≤200 条,重复 id 去重。
- **批量导入**:`POST /api/credentials/batch-import`,`{items: [{provider, credential, nickname?, tags?}]}`,一次 ≤100 条;坏条目进 `failed`(带 `index` 与原因),同渠道解密后内容一致进 `skipped`。支持粘贴 JSON 数组 / JSONL 或选文件。
- **单条导出**:`GET /api/credentials/{id}/export` 返回与导入同形的 JSON(含明文凭证,仅 admin / operator,落 `credential.export` 审计)。
- **「恢复」≠「取消暂停」**:`revive` 解系统硬禁用(需先重新登录),`toggle enabled=true` 才取消暂停。
- **「恢复」≠「取消暂停」**:`revive` 解系统硬禁用(需先重新登录),`toggle enabled=true` 才取消暂停(顺带清硬禁用,但不动冷却)。
- **`revive` 默认保留上游点名的冷却**(限流 / 余额 / 权益 / 风控):清掉只会立刻再撞一次。强制清除走 `force=true`(前端「强制恢复」)。签到失败回 `ok=false` + 可读 `message`,不 500。审计只记一条汇总,写失败只 warning。

### 凭证限额与在途
Expand Down Expand Up @@ -706,6 +707,7 @@ python3 scripts/restore_db.py data/backups/coding2api-20261014-030000.sqlite3 --
## 部署注意

- **平台范围:仅 Linux / macOS**。单实例锁(`src/instance_lock.py`)依赖 `flock`,Windows 直接跑会以可读中文退出;请用 WSL2 / Docker。`data/` 的 `0700` 信任边界在 Windows 下由 `src/security/private_files.py` 改用 `icacls` 收紧 ACL。
- **同一 `DATA_DIR` 只能一个写者**:宿主进程(`python -m src.main` / launchd)与 Docker 容器若共用 `./data`,**不要同时运行**。macOS virtiofs 挂载下 `flock` 不跨宿主/容器:宿主已持锁时容器照样拿到锁,单实例保护失效,两个进程双写 SQLite 会损坏库(实测 `database disk image is malformed`)。切换部署形态时先停一侧(`launchctl bootout` 或 `docker compose stop`),确认另一侧未运行再启动。容器运行时也不要在宿主删改 `-wal`/`-shm`,否则容器报 `disk I/O error`;维护前先停容器。
- **挂载属主**:容器内 uid 1001(`appuser`)→ `mkdir -p data secrets && sudo chown -R 1001:1001 data secrets`。
- **时区**:镜像默认 `TZ=Asia/Shanghai`;签到 / 额度周期按「今天 9 点」判断 → 必须与宿主一致。
- **TRAE 回调地址**:`PUBLIC_BASE_URL` 默认只在本机可用,远程 / 容器部署改成浏览器能开的地址。忘改也不会静默失败:基址落回环 / `0.0.0.0` → 回调改用当前请求 origin;「添加凭证」显示实际地址。浏览器侧打不开回调时(NAS / 远程常见「网络错误」),把地址栏整条链接粘回 TRAE 粘贴框即可完成登录。
Expand Down
23 changes: 20 additions & 3 deletions src/api/admin_auth.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@
from ..provider.trae.callback import login_trace_id
from ..webapp.security import session_cookie_secure
from .authorize import PENDING_CALLBACK_TTL_SECONDS
from .credential_login import save_login_credential
from .credential_login import save_login_credential, validate_login_credential
from .deps import (
SESSION_COOKIE,
Principal,
Expand Down Expand Up @@ -102,6 +102,19 @@ def _record_oauth_import(services: Services, principal: Principal, provider_id:
detail=f"上游 {provider_id};来源 OAuth {outcome}")


def _login_success(credential_id: str, merged: bool, warning: str) -> dict:
"""登录成功响应;`warning` 非空 = 上游仍拒绝该凭据(重登可能无效)。

单独成函数:poll / complete 两条登录路径必须同形,否则前端只能从其中
一条读到 `warning`。`warning` 为空时**不落键**,保持既有响应逐字节不变。
"""
body: dict = {"status": "success", "credential_id": credential_id,
"merged": merged}
if warning:
body["warning"] = warning
return body


def resolve_public_callback_url(settings: Settings,
request: Request | None = None) -> str:
"""回调基址 + /authorize。
Expand Down Expand Up @@ -363,7 +376,9 @@ async def upstream_auth_poll(payload: dict,
_record_oauth_import(services, principal, provider_id, credential_id,
merged=merged)
services.schedule_probe(credential_id)
return {"status": "success", "credential_id": credential_id, "merged": merged}
warning = await validate_login_credential(
services, credential_id, provider_id)
return _login_success(credential_id, merged, warning)

@router.post("/api/auth/upstream/cancel")
async def upstream_auth_cancel(request: Request, payload: dict,
Expand Down Expand Up @@ -424,6 +439,8 @@ async def upstream_auth_complete(request: Request, payload: dict,
_record_oauth_import(services, principal, provider_id, credential_id,
merged=merged)
services.schedule_probe(credential_id)
return {"status": "success", "credential_id": credential_id, "merged": merged}
warning = await validate_login_credential(
services, credential_id, provider_id)
return _login_success(credential_id, merged, warning)

return router
2 changes: 1 addition & 1 deletion src/api/admin_credentials.py
Original file line number Diff line number Diff line change
Expand Up @@ -233,7 +233,7 @@ async def probe_credential_once(credentials, provider, data, credential_id: str)
# DEAD(401)已经是确定性结论:和聊天路径一样硬禁用,管理台直接显示
#「重新粘贴 Cookie」,而不是停留在「未探测到额度」继续被调度。
login_reason = relogin_reason(
credentials.provider_of(credential_id) or "", error)
credentials.provider_of(credential_id) or "", error, provider)
if login_reason:
credentials.mark_relogin_required(credential_id, login_reason)
else:
Expand Down
52 changes: 52 additions & 0 deletions src/api/credential_login.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,11 +14,27 @@
from __future__ import annotations

import asyncio
import logging
from typing import Any

from ..provider.login_identity import login_identities_for
from ..provider.probe_failure import relogin_reason
from ..request_context import credential_scope
from .deps import Services

logger = logging.getLogger(__name__)

#: 登录后需要额外校验「聊天凭据」的渠道。
#:
#: 这些渠道的控制面(额度/签到,用临时 AK/SK)与模型网关(用不过期的
#: Basic app_key)是**两套凭据**:额度探测走控制面永远通过,会掩盖网关侧
#: Basic key 已失效。officeAce 尤其如此——APIG.1009 既可能是 key 真坏,也
#: 可能是积分耗尽,而 OAuth 重登从 `client-permission-validate` 拿回的是
#: **同一把** key,于是「登录成功 → 下次聊天 session dead」反复发生(实测
#: 2026-12-01 robbsluo 连登三次仍 401)。其余渠道登录下发的就是聊天凭据
#: 本身,无须重复探测。
_CHAT_CREDENTIAL_PROBES = frozenset({"officeace"})

#: 登录落库的渠道锁:单进程内同一渠道的「查 → 合并 → 新增」串行化。
#:
#: 为什么凭证级 `edit_lock` 不够:它按 `credential_id` 分键,而「第一次登录」
Expand Down Expand Up @@ -81,3 +97,39 @@ async def save_login_credential(
provider=provider_id, credential_data=credential_data,
nickname=nickname, added_by=added_by)
return credential_id, False


async def validate_login_credential(services: Services, credential_id: str,
provider_id: str) -> str:
"""登录落库后校验「聊天凭据」是否真被上游接受;返回空串=可用。

与 `schedule_probe`(只读额度、走控制面)互补:额度健康不代表聊天网关
认这把 key。仅对 `_CHAT_CREDENTIAL_PROBES` 里的渠道执行;用只读的
`list_models` 做校验(各渠道都是 GET)。

只在失败被上游明确判 **DEAD** 时写回「需重新登录」并返回原因;网络 /
限流 / 协议异常等瞬时问题一律视为通过,绝不因一次抖动阻断登录,也绝不
把登录本身弄失败(任何异常都吞掉)。
"""
if provider_id not in _CHAT_CREDENTIAL_PROBES:
return ""
provider = services.registry.get(provider_id)
lister = getattr(provider, "list_models", None)
if not callable(lister):
return ""
try:
data = services.credentials.credential_data(credential_id)
except Exception: # noqa: BLE001 - 解密失败等不阻断登录
logger.warning("登录后校验跳过 %s:取不到凭证明文", credential_id)
return ""
if data is None:
return ""
try:
with credential_scope(credential_id):
await lister(data)
except Exception as error: # noqa: BLE001 - 校验失败不影响登录结果
reason = relogin_reason(provider_id, error, provider)
if reason:
services.credentials.mark_relogin_required(credential_id, reason)
return reason
return ""
Loading