Skip to content

feat(subscription): bind an OAuth channel account to a user subscription (HQ-Task T261105-02) - #3

Merged
AdoreJc merged 1 commit into
fork-mainfrom
hq/T261105-02-subscription-oauth-binding
Nov 5, 2026
Merged

AdoreJc merged 1 commit into
fork-mainfrom
hq/T261105-02-subscription-oauth-binding

Conversation

@AdoreJc

@AdoreJc AdoreJc commented Nov 5, 2026

Copy link
Copy Markdown
Owner

HQ-Task: T261105-02

This code was AI-generated (Claude Code implementer session dispatched by Project HQ); the git user AdoreJC is not a historical core developer of upstream new-api. Fork-only feature: base branch is fork-main, not main.

Agent

  • Tool: Claude Code (desktop app, implementer session)
  • Tool version: Claude Code desktop
  • Model (full id): claude-fable-5-1
  • Host (CLI / IDE / GitHub coding agent / other): desktop app, Windows 10
  • Date (UTC): 2026-11-05

Links

User request

  • Verbatim (from the HQ brief, 2026-11-05):

    在现有订阅套餐系统上加「订阅绑定 OAuth 渠道账户」:复用现有订阅(SubscriptionPlan / UserSubscription);管理员在用户订阅上手动绑定一个 OAuth 渠道账户(Claude Subscription (OAuth) type 64 和 Codex),可换绑、解绑,也可以在一个入口里同时设置订阅和绑定渠道;固定路由通过专属分组实现,优先复用 UpgradeGroup / PrevUserGroup 的升降组机制,到期/作废/解绑时用户组按现有逻辑恢复;该渠道只服务绑定的用户;新分组需要的倍率等配置自动补齐;一个渠道同一时间只能绑定一个有效订阅;用户在自己的订阅页面能看到绑定账户的 5 小时和周额度,用户端接口只能查自己订阅绑定的渠道,返回裁剪后的用量字段;重置仅管理员可用;管理员端订阅列表显示绑定的渠道并可查看额度。

  • Later constraints or corrections from the user (quote, or none): none

Out of scope — refuse

  • Matched: no (fork-only PR against fork-main; the Codex/Claude OAuth channel types already live only in this fork)
  • 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 (feature brief)
  • 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

Kind

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

Issue facts

  • Actual behavior: a subscription cannot be tied to one OAuth account; OAuth channels are shared by everyone in their group and subscribers cannot see the account's rate-limit windows.
  • Impact: dedicated-account subscriptions cannot be sold / operated.
  • Frequency: always.
  • Evidence that the problem is in new-api rather than the client or upstream: feature gap in the fork's subscription model.
  • Applicable types and their fields: frontend (wallet subscription card, admin user-subscription drawer), deployment (AutoMigrate adds 4 columns to user_subscriptions); relay unchanged except Auto-group resolution; billing untouched.

Change

Design

  • Binding model (model/subscription.go, model/subscription_channel_binding.go): UserSubscription gains bound_channel_id, bound_group, bound_channel_prev_group, bound_prev_upgrade_group (plus non-stored bound_channel_type/name/status projections). Binding is only allowed on an active subscription and only for channel types 64 (Claude OAuth) / 57 (Codex), single-key.
  • Dedicated group / pinned routing: binding sets the channel's group to oauth-ch<channelId> (abilities rebuilt in the same transaction, the previous group string is remembered), switches the user to that group and writes it into UpgradeGroup (snapshotting the plan's upgrade group in bound_prev_upgrade_group, and PrevUserGroup if it was empty). Because the dedicated group lives in UpgradeGroup, the existing expiry (ExpireDueSubscriptions), invalidate and delete paths restore the user's group without modification. service.GetRequestAutoGroups pins Auto tokens of a user whose group is a binding group to that group only (no fallback to shared pools; empty list when the group has no ratio). The group ratio is provisioned via UpdateOption("GroupRatio") (copied from the user's group, else 1). The group is deliberately not added to UserUsableGroups: the owner can use it because it is their own group; nobody else can select it.
  • Uniqueness: a channel can be bound to one active subscription at a time (bound_channel_id + active + end_time > now). Ended subscriptions that still reference the channel are detached when it is rebound.
  • Restore semantics: unbind, invalidate and delete return the channel to its previous group (only if it is still in the dedicated group) and, for unbind on an active subscription, move the user back to the plan's upgrade group or the pre-subscription group. Expiry does not release the channel: the user is reverted by the existing logic, the channel stays parked in its private group (idle, nobody can use it) until an administrator rebinds or unbinds it, so a renewal does not leak the account into a shared pool.
  • Admin API: GET /api/subscription/admin/bindable_channels, POST /api/subscription/admin/user_subscriptions/:id/bind_channel, POST .../unbind_channel; POST /api/subscription/admin/users/:id/subscriptions accepts an optional channel_id (create + bind in one transaction). Audit actions subscription.channel_bind / subscription.channel_unbind.
  • User API: GET /api/subscription/self/usage/:id checks ownership and activity, then returns {provider, channel_type, windows{...utilization, resets_at, window_seconds}, plan_type, limit_reached}. Claude: five_hour, seven_day, seven_day_sonnet, seven_day_overage_included from /api/oauth/usage; Codex: primary, secondary from /backend-api/wham/usage. Email, user id, organization, extra-usage and reset-credit data are dropped; upstream errors return only the status code. Reset credits remain on the admin channel endpoints. The channel key / token refresh-and-retry logic of controller/claude_usage.go and controller/codex_usage.go was extracted into claudeChannelOAuthFetch / codexChannelWhamFetch and reused.
  • Frontend: admin drawer (user-subscriptions-dialog.tsx) gets an optional channel picker when adding a subscription, a "Bound account" column, Bind/Change/Unbind actions (bind-channel-dialog.tsx, which warns which group the channel leaves) and "View account usage" that opens the existing ClaudeUsageDialog / CodexUsageDialog (reset stays admin-only there). Wallet card shows the bound account kind and group with "View account usage" → subscription-usage-dialog.tsx (reuses UsageWindowCard). 34 keys added to all 7 locale files (text insertion; bun run i18n:sync is a no-op afterwards).
  • model/db_time.go: getDBTimestampTx so CreateUserSubscriptionFromPlanTx reads the DB clock through the open transaction (needed for single-connection SQLite tests; same SQL otherwise).

Research

Duplicate / prior art

Docs and code

  • https://docs.newapi.ai/ : subscription plans / user groups docs describe the upgrade-group mechanism reused here.
  • https://deepwiki.com/QuantumNous/new-api : not consulted beyond the code.
  • README / repo docs: AGENTS.md, web/AGENTS.md.
  • Code paths and what they imply for this change: model/subscription.go (group snapshot and expiry), model/ability.go (UpdateAbilities keyed by group|model), middleware/auth.go + service/group.go + service/channel_select.go (group resolution: user group → using group; Auto list), controller/claude_usage.go / codex_usage.go (usage fetch with refresh), middleware/access_token_routes.go (every panel route must declare a scope).

Alternatives considered

  • Option A: pin by channel id in the relay (per-user channel override) — rejected: new selection path, bypasses abilities/groups and the UI's group model.
  • Option B: dedicated group but keep UpgradeGroup untouched and add a separate restore path — rejected: duplicates the expiry/invalidate/delete logic.
  • Why this approach: reuses the existing group transition snapshot so every existing restore path works unchanged; the channel stays private by construction (abilities only in oauth-ch<id>).

Files

Path Why
model/subscription.go, model/subscription_channel_binding.go, model/db_time.go binding columns, bind/rebind/unbind/release transactions, group ratio provisioning, bindable channel listing
service/group.go pin Auto tokens of bound users to their group
controller/subscription_binding.go, controller/subscription.go, controller/claude_usage.go, controller/codex_usage.go, controller/audit.go admin bind endpoints, create+bind, user usage endpoint, fetch helpers extracted, audit templates
router/api-router.go, middleware/access_token_routes.go routes + access-token scopes
web/src/features/subscriptions/* , web/src/features/wallet/components/subscription-plans-card.tsx, web/src/features/usage-logs/lib/format.ts admin + user UI, api/types, audit labels
web/src/i18n/locales/*.json 34 keys × 7 locales
_test.go, web/src/features/subscriptions/tests/ tests

Behavior

  • Before: subscriptions had no relation to channels; OAuth channels were shared by their group; users could not see account usage.
  • After: see Change. Tokens that follow the user group or Auto go to the bound account only; tokens pinned to another group (e.g. default) are unchanged and still use the shared pools (documented in the bind dialog).
  • Explicit non-goals / leftover work: expiry does not auto-release the channel (by design, see above); reset credits are not exposed to subscribers; multi-key channels cannot be bound; MySQL/PostgreSQL migration verified only by startup smoke (see Verification).

Verification

  • Commands and results (Windows 10, go1.26.10, Bun 1.4.0):
    • GOWORK=off go build ./... → ok; GOWORK=off go vet ./model/ ./controller/ ./service/ ./router/ → clean; gofmt -l → clean.
    • GOWORK=off go test ./model/ -run 'Binding|BoundGroup|Subscription' → ok (8 new tests: bind/rebind/unbind, plan-upgrade-group restore, invalidate/delete release, expiry keeps channel parked + rebind detaches, create+bind rollback, uniqueness, group names).
    • GOWORK=off go test ./controller/ -run 'SubscriptionSelfUsage|Claude|Codex' → ok (foreign/missing/expired/unbound/dangling subscription rejected; Claude and Codex projections drop email/org/credits; upstream 403 returns status only).
    • GOWORK=off go test ./service/ -run AutoGroups → ok (pinned Auto groups); GOWORK=off go test ./router/ -run TestAccessTokenRouteRulesCoverEveryDashboardRoute → ok.
    • Full GOWORK=off go test ./model/ ./controller/ ./service/ ./router/ ./middleware/: model ok, service ok, router ok; controller and middleware fail only with the pre-existing Windows TempDir RemoveAll cleanup: ... audit.db / oneapi-*.log: The process cannot access the file errors (no assertion failures; same on fork-main).
    • relaykit/, tokenkit/: GOWORK=off go build ./... → ok.
    • web: tsgo -b → clean; oxlint on touched files → clean (2 pre-existing errors in untouched subscriptions/constants.ts, subscriptions-provider.tsx); oxfmt --check → clean; bun run test → 208 files / 2500 tests pass (incl. 7 new); bun run build → ok; bun run i18n:sync → no diff after inserting 34 keys × 7 locales.
  • Manual steps and observed result (tailnet test host, image new-api-fork:t261105-02 built from d225925, container new-api-t05 :39683, SQLite, /api/status 200, "ready in 1133 ms", no panic in logs):
  • UI: screenshots taken in the session (admin drawer with bound column, wallet card with bound account, usage dialog error state); not attached.
  • Tests added or updated: model/subscription_channel_binding_test.go, controller/subscription_binding_test.go, service/group_auto_groups_test.go (+1 case), web/src/features/subscriptions/__tests__/channel-binding.test.ts, web/src/features/subscriptions/__tests__/subscription-usage-dialog.test.tsx.
  • Databases / providers / platforms exercised: SQLite (test container, fresh DB + the app restarted during setup); PostgreSQL 17 (postgres:17-alpine + the new image, fresh AutoMigrate: bound_channel_id bigint, bound_group/bound_channel_prev_group/bound_prev_upgrade_group varchar(64), index idx_user_subscriptions_bound_channel_id; restart → "ready", /api/status 200). Providers: none (fake tokens, upstream 401 paths only).
  • Not verified: MySQL (no cached image on the test host and docker pull fails there with the Docker Desktop credential-helper error over SSH); upgrade of a database created by the latest release (only fresh DBs); real Claude/Codex usage responses; relay traffic through the dedicated group (no real account); log-rotation and audit.db tests on Windows (pre-existing environment failures).

Risks

  • Failure modes: an administrator moving the bound channel out of oauth-ch<id> by hand ends pinning for that user (release logic then leaves the channel alone); a user whose tokens are pinned to another group bypasses the bound account (documented).
  • Billing / quota / auth impact: the dedicated group ratio is copied from the user's group at bind time (or 1); subscription quota accounting is unchanged. Auth: user usage endpoint checks ownership + active + bound; admin endpoints stay behind AdminAuth; access-token scopes wallet:read / billing:read / billing:write.
  • Follow-ups: optional auto-release on expiry; per-plan default channel pool.

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 (fork-only branch)

🤖 Generated with Claude Code

…ion (HQ-Task T261105-02)

An administrator can bind one Claude Subscription (OAuth) (type 64) or
ChatGPT Subscription (Codex) (type 57) channel to an active user
subscription, change or release the binding, or bind while creating the
subscription. Binding moves the channel into a dedicated group
`oauth-ch<channelId>` (abilities rebuilt, previous group remembered) and
switches the user to that group through the existing UpgradeGroup /
PrevUserGroup snapshot, so expiry, invalidate and delete restore the user
with the unchanged downgrade logic. Invalidate, delete and unbind also
return the channel to its previous group; an expired subscription keeps
the channel parked in its private group until an administrator rebinds
or unbinds it. One channel can be bound to one active subscription at a
time; the group ratio for the dedicated group is provisioned
automatically and the group is never added to UserUsableGroups, so only
the owner can select it. Auto tokens of a bound user resolve to the
dedicated group only.

Subscribers see the bound account's 5-hour / 7-day (Claude) or primary /
secondary (Codex) windows on the wallet subscription card through
GET /api/subscription/self/usage/:id, which checks ownership and
returns only window utilization and reset times. Reset credits stay on
the administrator channel endpoints. The admin user-subscription drawer
shows the bound account and opens the existing channel usage dialogs.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
@AdoreJc
AdoreJc merged commit 1f7d6cb into fork-main Nov 5, 2026
2 checks passed
AdoreJc added a commit that referenced this pull request Nov 14, 2026
请求路径不持锁读取、选项同步整体替换,改用 atomic.Pointer 并提供
AlternateServerAddresses / SetAlternateServerAddresses / IsAlternateServerAddress。

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
AdoreJc added a commit that referenced this pull request Nov 14, 2026
* feat(system): 多站点地址访问控制台 (HQ-Task T261113-11)

新增选项 AlternateServerAddresses,同一部署可通过多个站点地址打开控制台。
给浏览器的链接跟随用户进来的线路:OAuth redirect_uri(流程开始时记录,
回调换 token 时复用)、密码重置邮件链接、支付完成后的回跳页、/api/status
的 server_address。Origin / Referer / Host 只在已配置地址中做精确匹配,
匹配不上一律回落 ServerAddress;已配置的 HTTPS 地址同时被会话 cookie 的
origin 检查信任。

移植自 71491b3cb,并覆盖其后新增的回跳点:Stripe 支付宝/微信充值、
订阅 Stripe 订阅与一次性 Checkout、订阅 Epay 的浏览器回跳。支付平台
异步通知地址与邮件 OAuth 的 redirect URI 仍使用 ServerAddress。

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>

* test(system): 订阅 Epay 回跳测试并入 return_path_test.go,避免与 PR #21 的测试文件冲突

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>

* test(web): 站点信息表单测试夹具补 AlternateServerAddresses

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>

* refactor(system): 备用站点地址列表改为原子读写 (HQ-Review R1 #3)

请求路径不持锁读取、选项同步整体替换,改用 atomic.Pointer 并提供
AlternateServerAddresses / SetAlternateServerAddresses / IsAlternateServerAddress。

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>

---------

Co-authored-by: Claude Fable 5.2 <noreply@anthropic.com>
@AdoreJc
AdoreJc deleted the hq/T261105-02-subscription-oauth-binding 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