Skip to content

fix(subscription): let bound users see and use their dedicated group (HQ-Task T261106-01) - #10

Merged
AdoreJc merged 3 commits into
fork-mainfrom
hq/T261106-01-bound-group-visibility
Nov 6, 2026
Merged

AdoreJc merged 3 commits into
fork-mainfrom
hq/T261106-01-bound-group-visibility

Conversation

@AdoreJc

@AdoreJc AdoreJc commented Nov 6, 2026 •

Copy link
Copy Markdown
Owner

HQ-Task: T261106-01

Agent

  • Tool: Claude Code (desktop app, Code tab; session started by the HQ supervisor session)
  • Tool version: Claude Code desktop app (version not exposed to the session)
  • Model (full id): claude-opus-5-5
  • Host (CLI / IDE / GitHub coding agent / other): other (Claude desktop app, Windows 10)
  • Date (UTC): 2026-11-06

Note: the git user (AdoreJC) is not a historical core developer of this repository. The code in this PR was AI-generated under the user's instructions and is reviewed by the user's HQ supervisor process.

Links

User request

  • Verbatim:

HQ-Task T261106-01:在 new-api(D:/WSL/workspace/repos/new-api,origin = AdoreJc/new-api,fork)里,让订阅绑定了 OAuth 渠道的用户在令牌页看到并能使用自己的订阅专属分组,同时修复专属组老令牌被 403 的问题。……

要点(细节以 brief 为准):

  1. 根因:PR fix(subscription): route bound users per request instead of switching their group (HQ-Task T261105-13) #9 后绑定不再把用户切进专属组,而专属组本来就故意不在 UserUsableGroups 里,所以 service.GetUserUsableGroups(userGroup) 不再包含它,令牌页下拉看不到。
  2. 更严重:middleware/auth.go:622-635 对令牌分组做可用性校验,用户以前创建的、分组为专属组的老令牌现在会被 403。必须修。
  3. 新增按用户的可用分组函数(在原结果上加入该用户当前生效绑定的 BoundGroup,走 model.GetUserSubscriptionRouteBinding 的缓存),替换 controller/group.go GetUserGroups、controller/token.go 令牌分组校验、middleware/auth.go:626、middleware/distributor.go:91 的调用;controller/user.go GetUserModels 和 controller/pricing.go 若简单就一起改。Auto 列表建议不接受专属组。
  4. 专属组令牌请求非绑定模型、或绑定失效后,返回能看懂的明确提示;前端令牌对话框专属组项带「仅可调用绑定账号支持的模型」说明,7 个 locale 同步,不改既有键的转义。
  5. 测试、构建命令、已知预存失败、Docker 验证(容器 new-api-t09 @ 39687,镜像 new-api-fork:t261106-01,数据目录 C:\Docker\new-api-t261106-01\data,绝不碰其他容器)见 brief。不要登录 claude.com,不用真实 OAuth token。
  • Later constraints or corrections from the user (quote, or none): scope change from the user on 2026-11-06, relayed by the HQ supervisor; it replaces "Auto 列表建议不接受专属组":

用户要求:令牌创建/编辑页的 Auto 分组列表里,要显示该用户订阅的专属分组,并且排在第一个。
……专属组在 Auto 里是「隐式、固定、排第一」的:不写进令牌保存的 Auto 分组快照(token.SetAutoGroups),保存时如果前端传了它就静默去掉,不要报错;也不计入 GetMaxTokenAutoGroups 的数量限制。运行时 GetRequestAutoGroups 也要把它放在最前面……绑定失效后自动从列表消失。
……请不要在本 PR 里改计费逻辑。

Out of scope — refuse

  • Matched: no (the Claude Subscription (OAuth) channel binding exists only in this fork; this PR targets fork-main, not upstream)
  • If yes, what was told to the user (stop here; do not open a PR): n/a

Open gate — do not open unless all are satisfied

  • Out of scope (including pass-through-only forwarding): no
  • Usage / configuration / integration (answered instead of opening): no
  • Required issue facts present without invention: yes (user report + HQ investigation, reproduced on the production image below)
  • Verification is actual commands or steps and observed results, not only go build or tests passed: yes
  • Body is short and factual; no unfiltered AI-generated text: yes
  • Open: yes
  • If no, what was told to the user (stop here): n/a

Kind

  • Bug fix
  • New feature
  • Performance / refactor
  • Docs
  • Other:

Issue facts

  • Actual behavior: after fix(subscription): route bound users per request instead of switching their group (HQ-Task T261105-13) #9 a bound user stays in their own group. The dedicated group (claude-ch<id> / codex-ch<id> / legacy oauth-ch<id>) is intentionally not in UserUsableGroups, so GET /api/user/self/groups no longer lists it, and TokenAuth answers 403 无权访问 claude-ch<id> 分组 for every token whose group is the dedicated group.
  • Impact: bound subscribers cannot pick their dedicated group for a key, and all keys they created in that group before the fix(subscription): route bound users per request instead of switching their group (HQ-Task T261105-13) #9 migration stopped working.
  • Frequency: every request with such a token; every visit to the token page.
  • Evidence that the problem is in new-api rather than the client or upstream: reproduced on image new-api-fork:fork-main-fe07a0240 (production build) with a mock upstream, see Verification.
  • Applicable types and their fields: relay (auth/distribution of token groups), frontend (token drawer). Billing: not touched (the dedicated group's ratio already exists; no price or quota code changed).

Change

New in service/group.go:

  • GetUserUsableGroupsForUser(userId, userGroup) = GetUserUsableGroups(userGroup) plus the BoundGroup of the user's active binding, read with model.GetUserSubscriptionRouteBinding (existing Redis / in-process cache, invalidated by bind/unbind/invalidate/delete; the stored end time ends it on expiry). Description: Subscription account (bound channel models only) (English source, translated by the web console).
  • GetUserSubscriptionGroup(userId) = that group alone.
  • GetUserAutoGroupForUser(userId, userGroup) = GetUserAutoGroup(userGroup) with that group in front; identical without an active binding.

Call sites switched to the per-user version:

Call site Effect
controller/group.go GetUserGroups token-page groups include the own dedicated group, flagged subscription_bound: true
controller/token.go AddToken / UpdateToken (new validateTokenGroup) a token's own group must be usable by its owner; update only checks a changed group, so tokens whose group became unavailable can still be edited. Empty and auto keep their existing rules.
middleware/auth.go TokenAuth fixes the old-token 403: a token in the owner's active dedicated group passes
middleware/distributor.go playground group check playground may select the dedicated group
controller/user.go GetUserModels, controller/pricing.go GetPricing model list / pricing include the dedicated group's models for its owner; group=auto and auto_groups use the per-user Auto list
controller/token.go GetTokenAutoGroups token page Auto list = dedicated group first, then the global Auto groups
service.GetRequestAutoGroups runtime Auto order = dedicated group first, for both the global list and a token snapshot (a malformed snapshot still fails closed)

Auto (changed at the user's request, see "Later constraints"): the owner's dedicated group is an implicit, fixed first Auto group. setTokenAutoGroups silently drops it before the limit check, so it is never stored in auto_groups and never counted against MaxTokenAutoGroups; another user's dedicated group is still rejected. At request time CacheGetRandomSatisfiedChannel tries it first; for a model it has no channel for, the existing loop (channel == nil → continue) moves to the next Auto group. Bound models already reach it through #9's request routing. It leaves every Auto list when the binding ends. No billing code is changed.

Error messages (backend i18n, en / zh-CN / zh-TW):

  • auth.token_subscription_group_inactive (403, token group is a dedicated-group name the owner no longer holds an active binding for):
    • en: The subscription dedicated group {{.Group}} of this token is no longer available: the subscription binding has expired, been cancelled or been removed. Switch the token to another group
    • zh-CN: 该令牌使用的订阅专属分组 {{.Group}} 已失效:订阅绑定已过期、作废或解绑,请把令牌改为其他分组
  • distributor.subscription_group_no_model (no channel in a dedicated group for the model):
    • en: The subscription dedicated group {{.Group}} only serves models supported by the bound subscription account; no available channel for model {{.Model}} (distributor)
    • zh-CN: 订阅专属分组 {{.Group}} 只能调用绑定的订阅账号支持的模型,模型 {{.Model}} 无可用渠道(distributor)

Frontend (web/src/features/keys): group option carries subscriptionBound; selecting it as the token group shows This API key can only call models supported by your bound subscription account.. In the Auto order editor it is a locked first row with a Subscription account · Auto first badge (订阅专属账号 · 自动优先) and a lock icon, without drag / move / remove controls, in both inherit and custom mode; inherited chips are numbered after it; it is not an "Add Auto group" candidate and never sent in auto_groups. New web keys (7 locales, inserted line by line, no existing key re-escaped): Group {{group}} is unavailable or unauthorized, Subscription account (bound channel models only), the hint above, Subscription account · Auto first, Always tried first in Auto. It cannot be removed or reordered..

Component reuse: existing ApiKeyGroupCombobox (already renders desc), FormDescription, Badge. The locked row is a static element next to the Reorder.Group instead of an AutoGroupOrderItem: that component is a Reorder.Item (must be draggable inside the group) and always renders move/remove controls, which the locked group must not have.

Research

Duplicate / prior art

Docs and code

  • https://docs.newapi.ai/ : not consulted; fork-only feature with no upstream docs.
  • https://deepwiki.com/QuantumNous/new-api : not consulted, same reason.
  • README / repo docs: AGENTS.md, web/AGENTS.md.
  • Code paths and what they imply for this change: model/subscription_route_binding.go (binding cache and expiry), model/subscription_channel_binding.go (IsSubscriptionBoundGroup, ensureSubscriptionBoundGroupRatio keeps the group out of UserUsableGroups), service/group.go, middleware/auth.go, middleware/distributor.go.

Alternatives considered

  • Option A: add the dedicated group to UserUsableGroups on bind — every user would see every dedicated group.
  • Option B: put the binding check inside GetUserUsableGroups(userGroup) — it has no user id and many callers that are not user-specific.
  • Option C (Auto): store the dedicated group in each token's auto_groups — it would outlive the binding and use up the per-token limit; the user asked for it to be implicit.
  • Why this approach: a separate per-user function keeps the shared function unchanged and limits the extra group to its owner.

Files

Path Why
service/group.go new per-user functions and description constant
controller/group.go, controller/token.go, controller/user.go, controller/pricing.go call sites, token group validation
middleware/auth.go, middleware/distributor.go token group check (403 fix), playground check, dedicated-group error messages
i18n/keys.go, i18n/locales/*.yaml two new backend messages
web/src/lib/api.ts, web/src/features/keys/components/* subscription_bound flag, hint, locked first Auto row
web/src/i18n/locales/*.json 5 new keys × 7 locales
middleware/subscription_group_test.go (new), controller/token_auto_groups_test.go, web/.../__tests__/api-keys-mutate-drawer.test.tsx, web/.../__tests__/auto-group-order-editor.test.tsx regression tests

Behavior

  • Before: dedicated group missing from the token page; tokens in it get 403 无权访问 claude-chN 分组.
  • After: owner sees claude-chN with the description and can create keys in it; old keys work again; bound models are served from it, other models get the dedicated-group message; Auto lists start with claude-chN (locked in the UI, never stored); after unbind/expiry/cancel the group disappears everywhere and its keys get the "no longer available" message. Other users never see or use it.
  • Explicit non-goals / leftover work: no migration of existing tokens (not needed); no billing change (the next HQ task changes subscription billing in middleware/distributor.go).

Verification

Local (Windows 10, go1.26.10, Bun 1.4.0), on 2ba1212 (da62416 only reformats a test file):

  • GOWORK=off go build ./... (after bun run build) → ok; cd relaykit && GOWORK=off go build ./... → ok; cd tokenkit && GOWORK=off go build ./... → ok (run on 9a161b8; neither module is touched).
  • GOWORK=off go vet ./service/ ./controller/ ./middleware/ → exit 0; gofmt -l controller middleware service → empty.
  • GOWORK=off go test ./model/ ./service/ ./middleware/ ./i18n/ -count=1 → model, service, i18n ok; middleware only TestAccessAndPanicLogsFollowLogRotation (Windows TempDir RemoveAll cleanup of a rotated log file; fails the same way with middleware/ at fe07a02).
  • GOWORK=off go test ./controller/ -count=1 → 110 top-level FAIL, all TempDir RemoveAll cleanup … audit.db (268 lines, 0 non-audit, 0 Error Trace, 0 panics). The new controller cases pass when run alone (-run 'TestSubscriptionBoundGroupIsUsableOnlyByItsOwner|AutoGroups' -v).
  • Regression checks: with the middleware/auth.go change reverted, 6 sub-cases of TestTokenAuthAcceptsTokensInTheOwnersSubscriptionGroup and TestTokenAuthRejectsTheSubscriptionGroupOnceTheBindingIsRemoved fail; with the drawer change reverted the drawer tests fail.
  • Auto (new): TestSubscriptionGroupLeadsTheOwnersAutoGroups (dedicated group first for active / legacy oauth-ch bindings, absent for none / expired / cancelled; global list and token snapshot), TestAutoTokenTriesTheSubscriptionGroupFirstAndSkipsItForOtherModels (Auto token: claude-x → claude-ch1/channel 1; gpt-x → Auto group default at index 1, i.e. index 0 = dedicated group was tried and skipped; after unbinding → default at index 0), controller: auto-groups endpoint ["claude-ch7","default","vip"], saving ["claude-ch7","vip"] with limit 1 succeeds and stores ["vip"], another user's ["claude-ch7"] is rejected.
  • web: bun x --package @typescript/native-preview tsgo -b → exit 0; bun x oxlint + bun x oxfmt --check on the touched TSX files → clean; bun run test → 211 files, 2527 passed; bun run build → ok.

Docker on the tailnet test host (container new-api-t09 @ 39687, mock upstream, fake OAuth key JSON, no real tokens; data dir C:\Docker\new-api-t261106-01\data; no other container touched):

  1. Image new-api-fork:fork-main-fe07a0240 (production build): admin binds channel chore: merge upstream main (72f3dc7da) into fork-main #2 (type 64) to user 2's subscription → claude-ch2. User's /api/user/self/groups = default, vip only. Token legacy-dedicated (group claude-ch2, created on this image) + claude-y → HTTP 403 无权访问 claude-ch2 分组 (bug reproduced).
  2. Same data, image new-api-fork:t261106-01:
    • /api/user/self/groups → "claude-ch2":{"desc":"Subscription account (bound channel models only)","ratio":1,"subscription_bound":true} plus default, vip; /api/user/models?group=claude-ch2 → ["claude-y"].
    • legacy-dedicated + claude-y → HTTP 200 (mock claude); + gpt-x → HTTP 503 订阅专属分组 claude-ch2 只能调用绑定的订阅账号支持的模型,模型 gpt-x 无可用渠道(distributor). Default token: claude-y / gpt-x → 200.
    • New claude-ch2 token → success. Admin (no binding): groups lack claude-ch2; creating a claude-ch2 token → Group claude-ch2 is unavailable or unauthorized.
    • Unbind → user's groups lack claude-ch2; legacy-dedicated → HTTP 403 该令牌使用的订阅专属分组 claude-ch2 已失效:订阅绑定已过期、作废或解绑,请把令牌改为其他分组. Rebind → 200 again.
  3. Auto (image rebuilt at 2ba1212; test options AutoGroups=["default","vip"], auto added to UserUsableGroups):
    • /api/token/auto-groups → {"groups":["claude-ch2","default","vip"],"max_count":5}; /api/pricing auto_groups → same; /api/user/models?group=auto → ["claude-y","gpt-x"].
    • Create Auto token with auto_groups: ["claude-ch2","vip"] → success, stored ["vip"].
    • Auto token inheriting the global list: claude-y → 200, log group claude-ch2 channel 2; gpt-x → 200, log group default channel 1 (dedicated group skipped).
    • Unbind → /api/token/auto-groups → ["default","vip"]; the Auto token keeps working (gpt-x → default/1, claude-y → default/2). Rebind → ["claude-ch2","default","vip"] again.
  • UI: no screenshot; the drawer and Auto editor were checked with vitest (hint shown for the dedicated group; locked first Auto row with badge, no remove/drag controls, not counted in "n / max", inherited chips numbered from 2; payload auto_groups excludes it).
  • Tests added: middleware/subscription_group_test.go (new), cases in controller/token_auto_groups_test.go, api-keys-mutate-drawer.test.tsx, auto-group-order-editor.test.tsx.
  • Databases / providers / platforms exercised: SQLite (unit tests and Docker); mock OpenAI and mock Claude OAuth upstream.
  • Not verified: MySQL / PostgreSQL (no schema or SQL change), the Redis binding-cache path, Codex (codex-ch) bindings end to end (same code path, covered only by name matching), the token drawer in a real browser, real OAuth tokens.

Risks

Scope check

  • Single focused change: yes
  • Secrets included: no
  • Out of scope (Coding Plan / reverse-engineered channel / third-party wrapper / Codex / pass-through-only forwarding): no

🤖 Generated with Claude Code

AdoreJc and others added 3 commits November 6, 2026 02:01
…(HQ-Task T261106-01)

Since request-scoped routing (#9) a bound user stays in their own group, and
the dedicated group (claude-ch<id> / codex-ch<id> / legacy oauth-ch<id>) is
deliberately not in UserUsableGroups. So the token page no longer listed it,
and TokenAuth rejected every existing token whose group is the dedicated group
with 403 "no permission to access group".

- service.GetUserUsableGroupsForUser(userId, userGroup): the usable groups
  plus the dedicated group of the user's active binding (through the binding
  cache), described as "Subscription account (bound channel models only)".
- Use it in GetUserGroups (marks the group subscription_bound), token
  create/update group validation (new; update only checks a changed group),
  TokenAuth, the playground group check, GetUserModels and GetPricing.
- Auto lists still reject the dedicated group (shared-pool semantics).
- A token in a dedicated group the owner no longer holds gets
  auth.token_subscription_group_inactive; a model the dedicated group cannot
  serve gets distributor.subscription_group_no_model.
- Token drawer: the dedicated group shows its description, a bound-models
  hint when selected, and is left out of the Auto order options.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…ask T261106-01)

Scope change requested by the user on 2026-11-06, replacing "Auto lists do
not accept the dedicated group".

- service.GetUserAutoGroupForUser(userId, userGroup): GetUserAutoGroup with
  the user's active binding group in front; identical without a binding.
- GetRequestAutoGroups puts that group first for both the global Auto list
  and a token's snapshot, so Auto tries dedicated -> rest; a model the bound
  channel does not serve finds no channel there and Auto moves on.
- The group is implicit: setTokenAutoGroups silently drops it before the
  limit check, so it is never stored and never counted.
- Token auto-groups endpoint, pricing auto_groups and GetUserModels(auto)
  use the per-user list.
- Token drawer: the group is a locked first row in the Auto order editor
  ("Subscription account · Auto first"), not removable or draggable.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@AdoreJc
AdoreJc merged commit 5bd57e8 into fork-main Nov 6, 2026
2 checks passed
@AdoreJc
AdoreJc deleted the hq/T261106-01-bound-group-visibility branch November 14, 2026 10:59
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant