Skip to content

Commit 91b1d81

Browse files
QTomclaude
andcommitted
feat(openai): Mobile RT 补全 plan_type、精确匹配账号、刷新时自动设置隐私
1. accounts/check 补全 plan_type:当 id_token 缺少 plan_type(如 Mobile RT), 自动调用 accounts/check 端点获取订阅类型 2. orgID 精确匹配账号:从 JWT 提取 poid 匹配正确账号,避免 Go map 遍历顺序随机导致 plan_type 不稳定 3. RT 刷新时设置隐私:调用 disableOpenAITraining 关闭训练数据共享, 结果存入 extra.privacy_mode,后续跳过重复设置 Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
1 parent 1f05d9f commit 91b1d81

5 files changed

Lines changed: 174 additions & 3 deletions

File tree

backend/cmd/server/wire_gen.go

Lines changed: 1 addition & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

backend/internal/pkg/openai/oauth.go

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -270,6 +270,7 @@ type OpenAIAuthClaims struct {
270270
ChatGPTUserID string `json:"chatgpt_user_id"`
271271
ChatGPTPlanType string `json:"chatgpt_plan_type"`
272272
UserID string `json:"user_id"`
273+
POID string `json:"poid"` // organization ID in access_token JWT
273274
Organizations []OrganizationClaim `json:"organizations"`
274275
}
275276

backend/internal/service/openai_oauth_service.go

Lines changed: 35 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -29,9 +29,10 @@ type soraSessionChunk struct {
2929

3030
// OpenAIOAuthService handles OpenAI OAuth authentication flows
3131
type OpenAIOAuthService struct {
32-
sessionStore *openai.SessionStore
33-
proxyRepo ProxyRepository
34-
oauthClient OpenAIOAuthClient
32+
sessionStore *openai.SessionStore
33+
proxyRepo ProxyRepository
34+
oauthClient OpenAIOAuthClient
35+
privacyClientFactory PrivacyClientFactory // 用于调用 chatgpt.com/backend-api(ImpersonateChrome)
3536
}
3637

3738
// NewOpenAIOAuthService creates a new OpenAI OAuth service
@@ -43,6 +44,12 @@ func NewOpenAIOAuthService(proxyRepo ProxyRepository, oauthClient OpenAIOAuthCli
4344
}
4445
}
4546

47+
// SetPrivacyClientFactory 注入 ImpersonateChrome 客户端工厂,
48+
// 用于调用 chatgpt.com/backend-api 获取账号信息(plan_type 等)。
49+
func (s *OpenAIOAuthService) SetPrivacyClientFactory(factory PrivacyClientFactory) {
50+
s.privacyClientFactory = factory
51+
}
52+
4653
// OpenAIAuthURLResult contains the authorization URL and session info
4754
type OpenAIAuthURLResult struct {
4855
AuthURL string `json:"auth_url"`
@@ -131,6 +138,7 @@ type OpenAITokenInfo struct {
131138
ChatGPTUserID string `json:"chatgpt_user_id,omitempty"`
132139
OrganizationID string `json:"organization_id,omitempty"`
133140
PlanType string `json:"plan_type,omitempty"`
141+
PrivacyMode string `json:"privacy_mode,omitempty"`
134142
}
135143

136144
// ExchangeCode exchanges authorization code for tokens
@@ -251,6 +259,30 @@ func (s *OpenAIOAuthService) RefreshTokenWithClientID(ctx context.Context, refre
251259
tokenInfo.PlanType = userInfo.PlanType
252260
}
253261

262+
// id_token 中缺少 plan_type 时(如 Mobile RT),尝试通过 ChatGPT backend-api 补全
263+
if tokenInfo.PlanType == "" && tokenInfo.AccessToken != "" && s.privacyClientFactory != nil {
264+
// 从 access_token JWT 中提取 orgID(poid),用于匹配正确的账号
265+
orgID := tokenInfo.OrganizationID
266+
if orgID == "" {
267+
if atClaims, err := openai.DecodeIDToken(tokenInfo.AccessToken); err == nil && atClaims.OpenAIAuth != nil {
268+
orgID = atClaims.OpenAIAuth.POID
269+
}
270+
}
271+
if info := fetchChatGPTAccountInfo(ctx, s.privacyClientFactory, tokenInfo.AccessToken, proxyURL, orgID); info != nil {
272+
if tokenInfo.PlanType == "" && info.PlanType != "" {
273+
tokenInfo.PlanType = info.PlanType
274+
}
275+
if tokenInfo.Email == "" && info.Email != "" {
276+
tokenInfo.Email = info.Email
277+
}
278+
}
279+
}
280+
281+
// 尝试设置隐私(关闭训练数据共享),best-effort
282+
if tokenInfo.AccessToken != "" && s.privacyClientFactory != nil {
283+
tokenInfo.PrivacyMode = disableOpenAITraining(ctx, s.privacyClientFactory, tokenInfo.AccessToken, proxyURL)
284+
}
285+
254286
return tokenInfo, nil
255287
}
256288

backend/internal/service/openai_privacy_service.go

Lines changed: 133 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -69,6 +69,139 @@ func disableOpenAITraining(ctx context.Context, clientFactory PrivacyClientFacto
6969
return PrivacyModeTrainingOff
7070
}
7171

72+
// ChatGPTAccountInfo 从 chatgpt.com/backend-api/accounts/check 获取的账号信息
73+
type ChatGPTAccountInfo struct {
74+
PlanType string
75+
Email string
76+
}
77+
78+
const chatGPTAccountsCheckURL = "https://chatgpt.com/backend-api/accounts/check/v4-2023-04-27"
79+
80+
// fetchChatGPTAccountInfo calls ChatGPT backend-api to get account info (plan_type, etc.).
81+
// Used as fallback when id_token doesn't contain these fields (e.g., Mobile RT).
82+
// orgID is used to match the correct account when multiple accounts exist (e.g., personal + team).
83+
// Returns nil on any failure (best-effort, non-blocking).
84+
func fetchChatGPTAccountInfo(ctx context.Context, clientFactory PrivacyClientFactory, accessToken, proxyURL, orgID string) *ChatGPTAccountInfo {
85+
if accessToken == "" || clientFactory == nil {
86+
return nil
87+
}
88+
89+
ctx, cancel := context.WithTimeout(ctx, 15*time.Second)
90+
defer cancel()
91+
92+
client, err := clientFactory(proxyURL)
93+
if err != nil {
94+
slog.Debug("chatgpt_account_check_client_error", "error", err.Error())
95+
return nil
96+
}
97+
98+
var result map[string]any
99+
resp, err := client.R().
100+
SetContext(ctx).
101+
SetHeader("Authorization", "Bearer "+accessToken).
102+
SetHeader("Origin", "https://chatgpt.com").
103+
SetHeader("Referer", "https://chatgpt.com/").
104+
SetHeader("Accept", "application/json").
105+
SetSuccessResult(&result).
106+
Get(chatGPTAccountsCheckURL)
107+
108+
if err != nil {
109+
slog.Debug("chatgpt_account_check_request_error", "error", err.Error())
110+
return nil
111+
}
112+
113+
if !resp.IsSuccessState() {
114+
slog.Debug("chatgpt_account_check_failed", "status", resp.StatusCode, "body", truncate(resp.String(), 200))
115+
return nil
116+
}
117+
118+
info := &ChatGPTAccountInfo{}
119+
120+
accounts, ok := result["accounts"].(map[string]any)
121+
if !ok {
122+
slog.Debug("chatgpt_account_check_no_accounts", "body", truncate(resp.String(), 300))
123+
return nil
124+
}
125+
126+
// 优先匹配 orgID 对应的账号(access_token JWT 中的 poid)
127+
if orgID != "" {
128+
if matched := extractPlanFromAccount(accounts, orgID); matched != "" {
129+
info.PlanType = matched
130+
}
131+
}
132+
133+
// 未匹配到时,遍历所有账号:优先 is_default,次选非 free
134+
if info.PlanType == "" {
135+
var defaultPlan, paidPlan, anyPlan string
136+
for _, acctRaw := range accounts {
137+
acct, ok := acctRaw.(map[string]any)
138+
if !ok {
139+
continue
140+
}
141+
planType := extractPlanType(acct)
142+
if planType == "" {
143+
continue
144+
}
145+
if anyPlan == "" {
146+
anyPlan = planType
147+
}
148+
if account, ok := acct["account"].(map[string]any); ok {
149+
if isDefault, _ := account["is_default"].(bool); isDefault {
150+
defaultPlan = planType
151+
}
152+
}
153+
if !strings.EqualFold(planType, "free") && paidPlan == "" {
154+
paidPlan = planType
155+
}
156+
}
157+
// 优先级:default > 非 free > 任意
158+
switch {
159+
case defaultPlan != "":
160+
info.PlanType = defaultPlan
161+
case paidPlan != "":
162+
info.PlanType = paidPlan
163+
default:
164+
info.PlanType = anyPlan
165+
}
166+
}
167+
168+
if info.PlanType == "" {
169+
slog.Debug("chatgpt_account_check_no_plan_type", "body", truncate(resp.String(), 300))
170+
return nil
171+
}
172+
173+
slog.Info("chatgpt_account_check_success", "plan_type", info.PlanType, "org_id", orgID)
174+
return info
175+
}
176+
177+
// extractPlanFromAccount 从 accounts map 中按 key(account_id)精确匹配并提取 plan_type
178+
func extractPlanFromAccount(accounts map[string]any, accountKey string) string {
179+
acctRaw, ok := accounts[accountKey]
180+
if !ok {
181+
return ""
182+
}
183+
acct, ok := acctRaw.(map[string]any)
184+
if !ok {
185+
return ""
186+
}
187+
return extractPlanType(acct)
188+
}
189+
190+
// extractPlanType 从单个 account 对象中提取 plan_type
191+
func extractPlanType(acct map[string]any) string {
192+
if account, ok := acct["account"].(map[string]any); ok {
193+
if planType, ok := account["plan_type"].(string); ok && planType != "" {
194+
return planType
195+
}
196+
}
197+
if entitlement, ok := acct["entitlement"].(map[string]any); ok {
198+
if subPlan, ok := entitlement["subscription_plan"].(string); ok && subPlan != "" {
199+
return subPlan
200+
}
201+
}
202+
return ""
203+
}
204+
72205
func truncate(s string, n int) string {
73206
if len(s) <= n {
74207
return s

frontend/src/composables/useOpenAIOAuth.ts

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ export interface OpenAITokenInfo {
1414
email?: string
1515
name?: string
1616
plan_type?: string
17+
privacy_mode?: string
1718
// OpenAI specific IDs (extracted from ID Token)
1819
chatgpt_account_id?: string
1920
chatgpt_user_id?: string
@@ -231,6 +232,9 @@ export function useOpenAIOAuth(options?: UseOpenAIOAuthOptions) {
231232
if (tokenInfo.name) {
232233
extra.name = tokenInfo.name
233234
}
235+
if (tokenInfo.privacy_mode) {
236+
extra.privacy_mode = tokenInfo.privacy_mode
237+
}
234238
return Object.keys(extra).length > 0 ? extra : undefined
235239
}
236240

0 commit comments

Comments
 (0)