Skip to content

Commit 25d961d

Browse files
authored
Merge pull request Wei-Shaw#1252 from DaydreamCoding/feat/openai-mobile-rt
feat(openai): 支持 Mobile Refresh Token 导入,自动补全 plan_type
2 parents 995bee1 + 91b1d81 commit 25d961d

9 files changed

Lines changed: 248 additions & 28 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/api/admin/accounts.ts

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -550,14 +550,18 @@ export async function getAntigravityDefaultModelMapping(): Promise<Record<string
550550
export async function refreshOpenAIToken(
551551
refreshToken: string,
552552
proxyId?: number | null,
553-
endpoint: string = '/admin/openai/refresh-token'
553+
endpoint: string = '/admin/openai/refresh-token',
554+
clientId?: string
554555
): Promise<Record<string, unknown>> {
555-
const payload: { refresh_token: string; proxy_id?: number } = {
556+
const payload: { refresh_token: string; proxy_id?: number; client_id?: string } = {
556557
refresh_token: refreshToken
557558
}
558559
if (proxyId) {
559560
payload.proxy_id = proxyId
560561
}
562+
if (clientId) {
563+
payload.client_id = clientId
564+
}
561565
const { data } = await apiClient.post<Record<string, unknown>>(endpoint, payload)
562566
return data
563567
}

frontend/src/components/account/CreateAccountModal.vue

Lines changed: 21 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -2504,13 +2504,15 @@
25042504
:allow-multiple="form.platform === 'anthropic'"
25052505
:show-cookie-option="form.platform === 'anthropic'"
25062506
:show-refresh-token-option="form.platform === 'openai' || form.platform === 'sora' || form.platform === 'antigravity'"
2507+
:show-mobile-refresh-token-option="form.platform === 'openai'"
25072508
:show-session-token-option="form.platform === 'sora'"
25082509
:show-access-token-option="form.platform === 'sora'"
25092510
:platform="form.platform"
25102511
:show-project-id="geminiOAuthType === 'code_assist'"
25112512
@generate-url="handleGenerateUrl"
25122513
@cookie-auth="handleCookieAuth"
25132514
@validate-refresh-token="handleValidateRefreshToken"
2515+
@validate-mobile-refresh-token="handleOpenAIValidateMobileRT"
25142516
@validate-session-token="handleValidateSessionToken"
25152517
@import-access-token="handleImportAccessToken"
25162518
/>
@@ -4360,11 +4362,14 @@ const handleOpenAIExchange = async (authCode: string) => {
43604362
}
43614363
43624364
// OpenAI 手动 RT 批量验证和创建
4363-
const handleOpenAIValidateRT = async (refreshTokenInput: string) => {
4365+
// OpenAI Mobile RT 使用的 client_id(与后端 openai.SoraClientID 一致)
4366+
const OPENAI_MOBILE_RT_CLIENT_ID = 'app_LlGpXReQgckcGGUo2JrYvtJK'
4367+
4368+
// OpenAI/Sora RT 批量验证和创建(共享逻辑)
4369+
const handleOpenAIBatchRT = async (refreshTokenInput: string, clientId?: string) => {
43644370
const oauthClient = activeOpenAIOAuth.value
43654371
if (!refreshTokenInput.trim()) return
43664372
4367-
// Parse multiple refresh tokens (one per line)
43684373
const refreshTokens = refreshTokenInput
43694374
.split('\n')
43704375
.map((rt) => rt.trim())
@@ -4389,7 +4394,8 @@ const handleOpenAIValidateRT = async (refreshTokenInput: string) => {
43894394
try {
43904395
const tokenInfo = await oauthClient.validateRefreshToken(
43914396
refreshTokens[i],
4392-
form.proxy_id
4397+
form.proxy_id,
4398+
clientId
43934399
)
43944400
if (!tokenInfo) {
43954401
failedCount++
@@ -4399,6 +4405,9 @@ const handleOpenAIValidateRT = async (refreshTokenInput: string) => {
43994405
}
44004406
44014407
const credentials = oauthClient.buildCredentials(tokenInfo)
4408+
if (clientId) {
4409+
credentials.client_id = clientId
4410+
}
44024411
const oauthExtra = oauthClient.buildExtraInfo(tokenInfo) as Record<string, unknown> | undefined
44034412
const extra = buildOpenAIExtra(oauthExtra)
44044413
@@ -4410,8 +4419,9 @@ const handleOpenAIValidateRT = async (refreshTokenInput: string) => {
44104419
}
44114420
}
44124421
4413-
// Generate account name with index for batch
4414-
const accountName = refreshTokens.length > 1 ? `${form.name} #${i + 1}` : form.name
4422+
// Generate account name; fallback to email if name is empty (ent schema requires NotEmpty)
4423+
const baseName = form.name || tokenInfo.email || 'OpenAI OAuth Account'
4424+
const accountName = refreshTokens.length > 1 ? `${baseName} #${i + 1}` : baseName
44154425
44164426
let openaiAccountId: string | number | undefined
44174427
@@ -4494,6 +4504,12 @@ const handleOpenAIValidateRT = async (refreshTokenInput: string) => {
44944504
}
44954505
}
44964506
4507+
// 手动输入 RT(Codex CLI client_id,默认)
4508+
const handleOpenAIValidateRT = (rt: string) => handleOpenAIBatchRT(rt)
4509+
4510+
// 手动输入 Mobile RT(SoraClientID)
4511+
const handleOpenAIValidateMobileRT = (rt: string) => handleOpenAIBatchRT(rt, OPENAI_MOBILE_RT_CLIENT_ID)
4512+
44974513
// Sora 手动 ST 批量验证和创建
44984514
const handleSoraValidateST = async (sessionTokenInput: string) => {
44994515
const oauthClient = activeOpenAIOAuth.value

frontend/src/components/account/OAuthAuthorizationFlow.vue

Lines changed: 22 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,17 @@
4848
t(getOAuthKey('refreshTokenAuth'))
4949
}}</span>
5050
</label>
51+
<label v-if="showMobileRefreshTokenOption" class="flex cursor-pointer items-center gap-2">
52+
<input
53+
v-model="inputMethod"
54+
type="radio"
55+
value="mobile_refresh_token"
56+
class="text-blue-600 focus:ring-blue-500"
57+
/>
58+
<span class="text-sm text-blue-900 dark:text-blue-200">{{
59+
t('admin.accounts.oauth.openai.mobileRefreshTokenAuth', '手动输入 Mobile RT')
60+
}}</span>
61+
</label>
5162
<label v-if="showSessionTokenOption" class="flex cursor-pointer items-center gap-2">
5263
<input
5364
v-model="inputMethod"
@@ -73,8 +84,8 @@
7384
</div>
7485
</div>
7586

76-
<!-- Refresh Token Input (OpenAI / Antigravity) -->
77-
<div v-if="inputMethod === 'refresh_token'" class="space-y-4">
87+
<!-- Refresh Token Input (OpenAI / Antigravity / Mobile RT) -->
88+
<div v-if="inputMethod === 'refresh_token' || inputMethod === 'mobile_refresh_token'" class="space-y-4">
7889
<div
7990
class="rounded-lg border border-blue-300 bg-white/80 p-4 dark:border-blue-600 dark:bg-gray-800/80"
8091
>
@@ -759,6 +770,7 @@ interface Props {
759770
methodLabel?: string
760771
showCookieOption?: boolean // Whether to show cookie auto-auth option
761772
showRefreshTokenOption?: boolean // Whether to show refresh token input option (OpenAI only)
773+
showMobileRefreshTokenOption?: boolean // Whether to show mobile refresh token option (OpenAI only)
762774
showSessionTokenOption?: boolean // Whether to show session token input option (Sora only)
763775
showAccessTokenOption?: boolean // Whether to show access token input option (Sora only)
764776
platform?: AccountPlatform // Platform type for different UI/text
@@ -776,6 +788,7 @@ const props = withDefaults(defineProps<Props>(), {
776788
methodLabel: 'Authorization Method',
777789
showCookieOption: true,
778790
showRefreshTokenOption: false,
791+
showMobileRefreshTokenOption: false,
779792
showSessionTokenOption: false,
780793
showAccessTokenOption: false,
781794
platform: 'anthropic',
@@ -787,6 +800,7 @@ const emit = defineEmits<{
787800
'exchange-code': [code: string]
788801
'cookie-auth': [sessionKey: string]
789802
'validate-refresh-token': [refreshToken: string]
803+
'validate-mobile-refresh-token': [refreshToken: string]
790804
'validate-session-token': [sessionToken: string]
791805
'import-access-token': [accessToken: string]
792806
'update:inputMethod': [method: AuthInputMethod]
@@ -834,7 +848,7 @@ const oauthState = ref('')
834848
const projectId = ref('')
835849
836850
// Computed: show method selection when either cookie or refresh token option is enabled
837-
const showMethodSelection = computed(() => props.showCookieOption || props.showRefreshTokenOption || props.showSessionTokenOption || props.showAccessTokenOption)
851+
const showMethodSelection = computed(() => props.showCookieOption || props.showRefreshTokenOption || props.showMobileRefreshTokenOption || props.showSessionTokenOption || props.showAccessTokenOption)
838852
839853
// Clipboard
840854
const { copied, copyToClipboard } = useClipboard()
@@ -945,7 +959,11 @@ const handleCookieAuth = () => {
945959
946960
const handleValidateRefreshToken = () => {
947961
if (refreshTokenInput.value.trim()) {
948-
emit('validate-refresh-token', refreshTokenInput.value.trim())
962+
if (inputMethod.value === 'mobile_refresh_token') {
963+
emit('validate-mobile-refresh-token', refreshTokenInput.value.trim())
964+
} else {
965+
emit('validate-refresh-token', refreshTokenInput.value.trim())
966+
}
949967
}
950968
}
951969

0 commit comments

Comments
 (0)