gemini_oauth_service.go 41 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099
  1. package service
  2. import (
  3. "context"
  4. "encoding/json"
  5. "errors"
  6. "fmt"
  7. "io"
  8. "net/http"
  9. "regexp"
  10. "strconv"
  11. "strings"
  12. "time"
  13. "github.com/Wei-Shaw/sub2api/internal/config"
  14. "github.com/Wei-Shaw/sub2api/internal/pkg/geminicli"
  15. "github.com/Wei-Shaw/sub2api/internal/pkg/httpclient"
  16. "github.com/Wei-Shaw/sub2api/internal/pkg/logger"
  17. )
  18. const (
  19. // Canonical tier IDs used by sub2api (2026-aligned).
  20. GeminiTierGoogleOneFree = "google_one_free"
  21. GeminiTierGoogleAIPro = "google_ai_pro"
  22. GeminiTierGoogleAIUltra = "google_ai_ultra"
  23. GeminiTierGCPStandard = "gcp_standard"
  24. GeminiTierGCPEnterprise = "gcp_enterprise"
  25. GeminiTierAIStudioFree = "aistudio_free"
  26. GeminiTierAIStudioPaid = "aistudio_paid"
  27. GeminiTierGoogleOneUnknown = "google_one_unknown"
  28. // Legacy/compat tier IDs that may exist in historical data or upstream responses.
  29. legacyTierAIPremium = "AI_PREMIUM"
  30. legacyTierGoogleOneStandard = "GOOGLE_ONE_STANDARD"
  31. legacyTierGoogleOneBasic = "GOOGLE_ONE_BASIC"
  32. legacyTierFree = "FREE"
  33. legacyTierGoogleOneUnknown = "GOOGLE_ONE_UNKNOWN"
  34. legacyTierGoogleOneUnlimited = "GOOGLE_ONE_UNLIMITED"
  35. )
  36. const (
  37. GB = 1024 * 1024 * 1024
  38. TB = 1024 * GB
  39. StorageTierUnlimited = 100 * TB // 100TB
  40. StorageTierAIPremium = 2 * TB // 2TB
  41. StorageTierStandard = 200 * GB // 200GB
  42. StorageTierBasic = 100 * GB // 100GB
  43. StorageTierFree = 15 * GB // 15GB
  44. )
  45. type GeminiOAuthService struct {
  46. sessionStore *geminicli.SessionStore
  47. proxyRepo ProxyRepository
  48. oauthClient GeminiOAuthClient
  49. codeAssist GeminiCliCodeAssistClient
  50. driveClient geminicli.DriveClient
  51. cfg *config.Config
  52. }
  53. type GeminiOAuthCapabilities struct {
  54. AIStudioOAuthEnabled bool `json:"ai_studio_oauth_enabled"`
  55. RequiredRedirectURIs []string `json:"required_redirect_uris"`
  56. }
  57. func NewGeminiOAuthService(
  58. proxyRepo ProxyRepository,
  59. oauthClient GeminiOAuthClient,
  60. codeAssist GeminiCliCodeAssistClient,
  61. driveClient geminicli.DriveClient,
  62. cfg *config.Config,
  63. ) *GeminiOAuthService {
  64. return &GeminiOAuthService{
  65. sessionStore: geminicli.NewSessionStore(),
  66. proxyRepo: proxyRepo,
  67. oauthClient: oauthClient,
  68. codeAssist: codeAssist,
  69. driveClient: driveClient,
  70. cfg: cfg,
  71. }
  72. }
  73. func (s *GeminiOAuthService) GetOAuthConfig() *GeminiOAuthCapabilities {
  74. // AI Studio OAuth is only enabled when the operator configures a custom OAuth client.
  75. clientID := strings.TrimSpace(s.cfg.Gemini.OAuth.ClientID)
  76. clientSecret := strings.TrimSpace(s.cfg.Gemini.OAuth.ClientSecret)
  77. enabled := clientID != "" && clientSecret != "" && clientID != geminicli.GeminiCLIOAuthClientID
  78. return &GeminiOAuthCapabilities{
  79. AIStudioOAuthEnabled: enabled,
  80. RequiredRedirectURIs: []string{geminicli.AIStudioOAuthRedirectURI},
  81. }
  82. }
  83. type GeminiAuthURLResult struct {
  84. AuthURL string `json:"auth_url"`
  85. SessionID string `json:"session_id"`
  86. State string `json:"state"`
  87. }
  88. func (s *GeminiOAuthService) GenerateAuthURL(ctx context.Context, proxyID *int64, redirectURI, projectID, oauthType, tierID string) (*GeminiAuthURLResult, error) {
  89. state, err := geminicli.GenerateState()
  90. if err != nil {
  91. return nil, fmt.Errorf("failed to generate state: %w", err)
  92. }
  93. codeVerifier, err := geminicli.GenerateCodeVerifier()
  94. if err != nil {
  95. return nil, fmt.Errorf("failed to generate code verifier: %w", err)
  96. }
  97. codeChallenge := geminicli.GenerateCodeChallenge(codeVerifier)
  98. sessionID, err := geminicli.GenerateSessionID()
  99. if err != nil {
  100. return nil, fmt.Errorf("failed to generate session ID: %w", err)
  101. }
  102. var proxyURL string
  103. if proxyID != nil {
  104. proxy, err := s.proxyRepo.GetByID(ctx, *proxyID)
  105. if err == nil && proxy != nil {
  106. proxyURL = proxy.URL()
  107. }
  108. }
  109. // OAuth client selection:
  110. // - code_assist: always use built-in Gemini CLI OAuth client (public)
  111. // - google_one: always use built-in Gemini CLI OAuth client (public)
  112. // - ai_studio: requires a user-provided OAuth client
  113. oauthCfg := geminicli.OAuthConfig{
  114. ClientID: s.cfg.Gemini.OAuth.ClientID,
  115. ClientSecret: s.cfg.Gemini.OAuth.ClientSecret,
  116. Scopes: s.cfg.Gemini.OAuth.Scopes,
  117. }
  118. if oauthType == "code_assist" || oauthType == "google_one" {
  119. // Force use of built-in Gemini CLI OAuth client
  120. oauthCfg.ClientID = ""
  121. oauthCfg.ClientSecret = ""
  122. }
  123. session := &geminicli.OAuthSession{
  124. State: state,
  125. CodeVerifier: codeVerifier,
  126. ProxyURL: proxyURL,
  127. RedirectURI: redirectURI,
  128. ProjectID: strings.TrimSpace(projectID),
  129. TierID: canonicalGeminiTierIDForOAuthType(oauthType, tierID),
  130. OAuthType: oauthType,
  131. CreatedAt: time.Now(),
  132. }
  133. s.sessionStore.Set(sessionID, session)
  134. effectiveCfg, err := geminicli.EffectiveOAuthConfig(oauthCfg, oauthType)
  135. if err != nil {
  136. return nil, err
  137. }
  138. isBuiltinClient := effectiveCfg.ClientID == geminicli.GeminiCLIOAuthClientID
  139. // AI Studio OAuth requires a user-provided OAuth client (built-in Gemini CLI client is scope-restricted).
  140. if oauthType == "ai_studio" && isBuiltinClient {
  141. return nil, fmt.Errorf("AI Studio OAuth requires a custom OAuth Client (GEMINI_OAUTH_CLIENT_ID / GEMINI_OAUTH_CLIENT_SECRET). If you don't want to configure an OAuth client, please use an AI Studio API Key account instead")
  142. }
  143. // Redirect URI strategy:
  144. // - built-in Gemini CLI OAuth client: use upstream redirect URI (codeassist.google.com/authcode)
  145. // - custom OAuth client: use localhost callback for manual copy/paste flow
  146. if isBuiltinClient {
  147. redirectURI = geminicli.GeminiCLIRedirectURI
  148. } else {
  149. redirectURI = geminicli.AIStudioOAuthRedirectURI
  150. }
  151. session.RedirectURI = redirectURI
  152. s.sessionStore.Set(sessionID, session)
  153. authURL, err := geminicli.BuildAuthorizationURL(effectiveCfg, state, codeChallenge, redirectURI, session.ProjectID, oauthType)
  154. if err != nil {
  155. return nil, err
  156. }
  157. return &GeminiAuthURLResult{
  158. AuthURL: authURL,
  159. SessionID: sessionID,
  160. State: state,
  161. }, nil
  162. }
  163. type GeminiExchangeCodeInput struct {
  164. SessionID string
  165. State string
  166. Code string
  167. ProxyID *int64
  168. OAuthType string // "code_assist" 或 "ai_studio"
  169. // TierID is a user-selected tier to be used when auto detection is unavailable or fails.
  170. // If empty, the service will fall back to the tier stored in the OAuth session (if any).
  171. TierID string
  172. }
  173. type GeminiTokenInfo struct {
  174. AccessToken string `json:"access_token"`
  175. RefreshToken string `json:"refresh_token"`
  176. ExpiresIn int64 `json:"expires_in"`
  177. ExpiresAt int64 `json:"expires_at"`
  178. TokenType string `json:"token_type"`
  179. Scope string `json:"scope,omitempty"`
  180. ProjectID string `json:"project_id,omitempty"`
  181. OAuthType string `json:"oauth_type,omitempty"` // "code_assist" 或 "ai_studio"
  182. TierID string `json:"tier_id,omitempty"` // Canonical tier id (e.g. google_one_free, gcp_standard, aistudio_free)
  183. Extra map[string]any `json:"extra,omitempty"` // Drive metadata
  184. }
  185. // validateTierID validates tier_id format and length
  186. func validateTierID(tierID string) error {
  187. if tierID == "" {
  188. return nil // Empty is allowed
  189. }
  190. if len(tierID) > 64 {
  191. return fmt.Errorf("tier_id exceeds maximum length of 64 characters")
  192. }
  193. // Allow alphanumeric, underscore, hyphen, and slash (for tier paths)
  194. if !regexp.MustCompile(`^[a-zA-Z0-9_/-]+$`).MatchString(tierID) {
  195. return fmt.Errorf("tier_id contains invalid characters")
  196. }
  197. return nil
  198. }
  199. func canonicalGeminiTierID(raw string) string {
  200. raw = strings.TrimSpace(raw)
  201. if raw == "" {
  202. return ""
  203. }
  204. lower := strings.ToLower(raw)
  205. switch lower {
  206. case GeminiTierGoogleOneFree,
  207. GeminiTierGoogleAIPro,
  208. GeminiTierGoogleAIUltra,
  209. GeminiTierGCPStandard,
  210. GeminiTierGCPEnterprise,
  211. GeminiTierAIStudioFree,
  212. GeminiTierAIStudioPaid,
  213. GeminiTierGoogleOneUnknown:
  214. return lower
  215. }
  216. upper := strings.ToUpper(raw)
  217. switch upper {
  218. // Google One legacy tiers
  219. case legacyTierAIPremium:
  220. return GeminiTierGoogleAIPro
  221. case legacyTierGoogleOneUnlimited:
  222. return GeminiTierGoogleAIUltra
  223. case legacyTierFree, legacyTierGoogleOneBasic, legacyTierGoogleOneStandard:
  224. return GeminiTierGoogleOneFree
  225. case legacyTierGoogleOneUnknown:
  226. return GeminiTierGoogleOneUnknown
  227. // Code Assist legacy tiers
  228. case "STANDARD", "PRO", "LEGACY":
  229. return GeminiTierGCPStandard
  230. case "ENTERPRISE", "ULTRA":
  231. return GeminiTierGCPEnterprise
  232. }
  233. // Some Code Assist responses use kebab-case tier identifiers.
  234. switch lower {
  235. case "standard-tier", "pro-tier":
  236. return GeminiTierGCPStandard
  237. case "ultra-tier":
  238. return GeminiTierGCPEnterprise
  239. }
  240. return ""
  241. }
  242. func canonicalGeminiTierIDForOAuthType(oauthType, tierID string) string {
  243. oauthType = strings.ToLower(strings.TrimSpace(oauthType))
  244. canonical := canonicalGeminiTierID(tierID)
  245. if canonical == "" {
  246. return ""
  247. }
  248. switch oauthType {
  249. case "google_one":
  250. switch canonical {
  251. case GeminiTierGoogleOneFree, GeminiTierGoogleAIPro, GeminiTierGoogleAIUltra:
  252. return canonical
  253. default:
  254. return ""
  255. }
  256. case "code_assist":
  257. switch canonical {
  258. case GeminiTierGCPStandard, GeminiTierGCPEnterprise:
  259. return canonical
  260. default:
  261. return ""
  262. }
  263. case "ai_studio":
  264. switch canonical {
  265. case GeminiTierAIStudioFree, GeminiTierAIStudioPaid:
  266. return canonical
  267. default:
  268. return ""
  269. }
  270. default:
  271. // Unknown oauth type: accept canonical tier.
  272. return canonical
  273. }
  274. }
  275. // extractTierIDFromAllowedTiers extracts tierID from LoadCodeAssist response
  276. // Prioritizes IsDefault tier, falls back to first non-empty tier
  277. func extractTierIDFromAllowedTiers(allowedTiers []geminicli.AllowedTier) string {
  278. tierID := "LEGACY"
  279. // First pass: look for default tier
  280. for _, tier := range allowedTiers {
  281. if tier.IsDefault && strings.TrimSpace(tier.ID) != "" {
  282. tierID = strings.TrimSpace(tier.ID)
  283. break
  284. }
  285. }
  286. // Second pass: if still LEGACY, take first non-empty tier
  287. if tierID == "LEGACY" {
  288. for _, tier := range allowedTiers {
  289. if strings.TrimSpace(tier.ID) != "" {
  290. tierID = strings.TrimSpace(tier.ID)
  291. break
  292. }
  293. }
  294. }
  295. return tierID
  296. }
  297. // inferGoogleOneTier infers Google One tier from Drive storage limit
  298. func inferGoogleOneTier(storageBytes int64) string {
  299. logger.LegacyPrintf("service.gemini_oauth", "[GeminiOAuth] inferGoogleOneTier - input: %d bytes (%.2f TB)", storageBytes, float64(storageBytes)/float64(TB))
  300. if storageBytes <= 0 {
  301. logger.LegacyPrintf("service.gemini_oauth", "[GeminiOAuth] inferGoogleOneTier - storageBytes <= 0, returning UNKNOWN")
  302. return GeminiTierGoogleOneUnknown
  303. }
  304. if storageBytes > StorageTierUnlimited {
  305. logger.LegacyPrintf("service.gemini_oauth", "[GeminiOAuth] inferGoogleOneTier - > %d bytes (100TB), returning UNLIMITED", StorageTierUnlimited)
  306. return GeminiTierGoogleAIUltra
  307. }
  308. if storageBytes >= StorageTierAIPremium {
  309. logger.LegacyPrintf("service.gemini_oauth", "[GeminiOAuth] inferGoogleOneTier - >= %d bytes (2TB), returning google_ai_pro", StorageTierAIPremium)
  310. return GeminiTierGoogleAIPro
  311. }
  312. if storageBytes >= StorageTierFree {
  313. logger.LegacyPrintf("service.gemini_oauth", "[GeminiOAuth] inferGoogleOneTier - >= %d bytes (15GB), returning FREE", StorageTierFree)
  314. return GeminiTierGoogleOneFree
  315. }
  316. logger.LegacyPrintf("service.gemini_oauth", "[GeminiOAuth] inferGoogleOneTier - < %d bytes (15GB), returning UNKNOWN", StorageTierFree)
  317. return GeminiTierGoogleOneUnknown
  318. }
  319. // FetchGoogleOneTier fetches Google One tier from Drive API.
  320. // Note: LoadCodeAssist API is NOT called for Google One accounts because:
  321. // 1. It's designed for GCP IAM (enterprise), not personal Google accounts
  322. // 2. Personal accounts will get 403/404 from cloudaicompanion.googleapis.com
  323. // 3. Google consumer (Google One) and enterprise (GCP) systems are physically isolated
  324. func (s *GeminiOAuthService) FetchGoogleOneTier(ctx context.Context, accessToken, proxyURL string) (string, *geminicli.DriveStorageInfo, error) {
  325. logger.LegacyPrintf("service.gemini_oauth", "[GeminiOAuth] Starting FetchGoogleOneTier (Google One personal account)")
  326. // Use Drive API to infer tier from storage quota (requires drive.readonly scope)
  327. logger.LegacyPrintf("service.gemini_oauth", "[GeminiOAuth] Calling Drive API for storage quota...")
  328. storageInfo, err := s.driveClient.GetStorageQuota(ctx, accessToken, proxyURL)
  329. if err != nil {
  330. // Check if it's a 403 (scope not granted)
  331. if strings.Contains(err.Error(), "status 403") {
  332. logger.LegacyPrintf("service.gemini_oauth", "[GeminiOAuth] Drive API scope not available (403): %v", err)
  333. return GeminiTierGoogleOneUnknown, nil, err
  334. }
  335. // Other errors
  336. logger.LegacyPrintf("service.gemini_oauth", "[GeminiOAuth] Failed to fetch Drive storage: %v", err)
  337. return GeminiTierGoogleOneUnknown, nil, err
  338. }
  339. logger.LegacyPrintf("service.gemini_oauth", "[GeminiOAuth] Drive API response - Limit: %d bytes (%.2f TB), Usage: %d bytes (%.2f GB)",
  340. storageInfo.Limit, float64(storageInfo.Limit)/float64(TB),
  341. storageInfo.Usage, float64(storageInfo.Usage)/float64(GB))
  342. tierID := inferGoogleOneTier(storageInfo.Limit)
  343. logger.LegacyPrintf("service.gemini_oauth", "[GeminiOAuth] Inferred tier from storage: %s", tierID)
  344. return tierID, storageInfo, nil
  345. }
  346. // RefreshAccountGoogleOneTier 刷新单个账号的 Google One Tier
  347. func (s *GeminiOAuthService) RefreshAccountGoogleOneTier(
  348. ctx context.Context,
  349. account *Account,
  350. ) (tierID string, extra map[string]any, credentials map[string]any, err error) {
  351. if account == nil {
  352. return "", nil, nil, fmt.Errorf("account is nil")
  353. }
  354. // 验证账号类型
  355. oauthType, ok := account.Credentials["oauth_type"].(string)
  356. if !ok || oauthType != "google_one" {
  357. return "", nil, nil, fmt.Errorf("not a google_one OAuth account")
  358. }
  359. // 获取 access_token
  360. accessToken, ok := account.Credentials["access_token"].(string)
  361. if !ok || accessToken == "" {
  362. return "", nil, nil, fmt.Errorf("missing access_token")
  363. }
  364. // 获取 proxy URL
  365. var proxyURL string
  366. if account.ProxyID != nil && account.Proxy != nil {
  367. proxyURL = account.Proxy.URL()
  368. }
  369. // 调用 Drive API
  370. tierID, storageInfo, err := s.FetchGoogleOneTier(ctx, accessToken, proxyURL)
  371. if err != nil {
  372. return "", nil, nil, err
  373. }
  374. // 构建 extra 数据(保留原有 extra 字段)
  375. extra = make(map[string]any)
  376. for k, v := range account.Extra {
  377. extra[k] = v
  378. }
  379. if storageInfo != nil {
  380. extra["drive_storage_limit"] = storageInfo.Limit
  381. extra["drive_storage_usage"] = storageInfo.Usage
  382. extra["drive_tier_updated_at"] = time.Now().Format(time.RFC3339)
  383. }
  384. // 构建 credentials 数据
  385. credentials = make(map[string]any)
  386. for k, v := range account.Credentials {
  387. credentials[k] = v
  388. }
  389. credentials["tier_id"] = tierID
  390. return tierID, extra, credentials, nil
  391. }
  392. func (s *GeminiOAuthService) ExchangeCode(ctx context.Context, input *GeminiExchangeCodeInput) (*GeminiTokenInfo, error) {
  393. logger.LegacyPrintf("service.gemini_oauth", "[GeminiOAuth] ========== ExchangeCode START ==========")
  394. logger.LegacyPrintf("service.gemini_oauth", "[GeminiOAuth] SessionID: %s", input.SessionID)
  395. session, ok := s.sessionStore.Get(input.SessionID)
  396. if !ok {
  397. logger.LegacyPrintf("service.gemini_oauth", "[GeminiOAuth] ERROR: Session not found or expired")
  398. return nil, fmt.Errorf("session not found or expired")
  399. }
  400. if strings.TrimSpace(input.State) == "" || input.State != session.State {
  401. logger.LegacyPrintf("service.gemini_oauth", "[GeminiOAuth] ERROR: Invalid state")
  402. return nil, fmt.Errorf("invalid state")
  403. }
  404. proxyURL := session.ProxyURL
  405. if input.ProxyID != nil {
  406. proxy, err := s.proxyRepo.GetByID(ctx, *input.ProxyID)
  407. if err == nil && proxy != nil {
  408. proxyURL = proxy.URL()
  409. }
  410. }
  411. logger.LegacyPrintf("service.gemini_oauth", "[GeminiOAuth] ProxyURL: %s", proxyURL)
  412. redirectURI := session.RedirectURI
  413. // Resolve oauth_type early (defaults to code_assist for backward compatibility).
  414. oauthType := session.OAuthType
  415. if oauthType == "" {
  416. oauthType = "code_assist"
  417. }
  418. logger.LegacyPrintf("service.gemini_oauth", "[GeminiOAuth] OAuth Type: %s", oauthType)
  419. logger.LegacyPrintf("service.gemini_oauth", "[GeminiOAuth] Project ID from session: %s", session.ProjectID)
  420. // If the session was created for AI Studio OAuth, ensure a custom OAuth client is configured.
  421. if oauthType == "ai_studio" {
  422. effectiveCfg, err := geminicli.EffectiveOAuthConfig(geminicli.OAuthConfig{
  423. ClientID: s.cfg.Gemini.OAuth.ClientID,
  424. ClientSecret: s.cfg.Gemini.OAuth.ClientSecret,
  425. Scopes: s.cfg.Gemini.OAuth.Scopes,
  426. }, "ai_studio")
  427. if err != nil {
  428. return nil, err
  429. }
  430. isBuiltinClient := effectiveCfg.ClientID == geminicli.GeminiCLIOAuthClientID
  431. if isBuiltinClient {
  432. return nil, fmt.Errorf("AI Studio OAuth requires a custom OAuth Client. Please use an AI Studio API Key account, or configure GEMINI_OAUTH_CLIENT_ID / GEMINI_OAUTH_CLIENT_SECRET and re-authorize")
  433. }
  434. }
  435. // code_assist/google_one always uses the built-in client and its fixed redirect URI.
  436. if oauthType == "code_assist" || oauthType == "google_one" {
  437. redirectURI = geminicli.GeminiCLIRedirectURI
  438. }
  439. tokenResp, err := s.oauthClient.ExchangeCode(ctx, oauthType, input.Code, session.CodeVerifier, redirectURI, proxyURL)
  440. if err != nil {
  441. logger.LegacyPrintf("service.gemini_oauth", "[GeminiOAuth] ERROR: Failed to exchange code: %v", err)
  442. return nil, fmt.Errorf("failed to exchange code: %w", err)
  443. }
  444. logger.LegacyPrintf("service.gemini_oauth", "[GeminiOAuth] Token exchange successful")
  445. logger.LegacyPrintf("service.gemini_oauth", "[GeminiOAuth] Token scope: %s", tokenResp.Scope)
  446. logger.LegacyPrintf("service.gemini_oauth", "[GeminiOAuth] Token expires_in: %d seconds", tokenResp.ExpiresIn)
  447. sessionProjectID := strings.TrimSpace(session.ProjectID)
  448. s.sessionStore.Delete(input.SessionID)
  449. // 计算过期时间:减去 5 分钟安全时间窗口(考虑网络延迟和时钟偏差)
  450. // 同时设置下界保护,防止 expires_in 过小导致过去时间(引发刷新风暴)
  451. const safetyWindow = 300 // 5 minutes
  452. const minTTL = 30 // minimum 30 seconds
  453. expiresAt := time.Now().Unix() + tokenResp.ExpiresIn - safetyWindow
  454. minExpiresAt := time.Now().Unix() + minTTL
  455. if expiresAt < minExpiresAt {
  456. expiresAt = minExpiresAt
  457. }
  458. projectID := sessionProjectID
  459. var tierID string
  460. fallbackTierID := canonicalGeminiTierIDForOAuthType(oauthType, input.TierID)
  461. if fallbackTierID == "" {
  462. fallbackTierID = canonicalGeminiTierIDForOAuthType(oauthType, session.TierID)
  463. }
  464. logger.LegacyPrintf("service.gemini_oauth", "[GeminiOAuth] ========== Account Type Detection START ==========")
  465. logger.LegacyPrintf("service.gemini_oauth", "[GeminiOAuth] OAuth Type: %s", oauthType)
  466. // 对于 code_assist 模式,project_id 是必需的,需要调用 Code Assist API
  467. // 对于 google_one 模式,使用个人 Google 账号,不需要 project_id,配额由 Google 网关自动识别
  468. // 对于 ai_studio 模式,project_id 是可选的(不影响使用 AI Studio API)
  469. switch oauthType {
  470. case "code_assist":
  471. logger.LegacyPrintf("service.gemini_oauth", "[GeminiOAuth] Processing code_assist OAuth type")
  472. if projectID == "" {
  473. logger.LegacyPrintf("service.gemini_oauth", "[GeminiOAuth] No project_id provided, attempting to fetch from LoadCodeAssist API...")
  474. var err error
  475. projectID, tierID, err = s.fetchProjectID(ctx, tokenResp.AccessToken, proxyURL)
  476. if err != nil {
  477. // 记录警告但不阻断流程,允许后续补充 project_id
  478. fmt.Printf("[GeminiOAuth] Warning: Failed to fetch project_id during token exchange: %v\n", err)
  479. logger.LegacyPrintf("service.gemini_oauth", "[GeminiOAuth] WARNING: Failed to fetch project_id: %v", err)
  480. } else {
  481. logger.LegacyPrintf("service.gemini_oauth", "[GeminiOAuth] Successfully fetched project_id: %s, tier_id: %s", projectID, tierID)
  482. }
  483. } else {
  484. logger.LegacyPrintf("service.gemini_oauth", "[GeminiOAuth] User provided project_id: %s, fetching tier_id...", projectID)
  485. // 用户手动填了 project_id,仍需调用 LoadCodeAssist 获取 tierID
  486. _, fetchedTierID, err := s.fetchProjectID(ctx, tokenResp.AccessToken, proxyURL)
  487. if err != nil {
  488. fmt.Printf("[GeminiOAuth] Warning: Failed to fetch tierID: %v\n", err)
  489. logger.LegacyPrintf("service.gemini_oauth", "[GeminiOAuth] WARNING: Failed to fetch tier_id: %v", err)
  490. } else {
  491. tierID = fetchedTierID
  492. logger.LegacyPrintf("service.gemini_oauth", "[GeminiOAuth] Successfully fetched tier_id: %s", tierID)
  493. }
  494. }
  495. if strings.TrimSpace(projectID) == "" {
  496. logger.LegacyPrintf("service.gemini_oauth", "[GeminiOAuth] ERROR: Missing project_id for Code Assist OAuth")
  497. return nil, fmt.Errorf("missing project_id for Code Assist OAuth: please fill Project ID (optional field) and regenerate the auth URL, or ensure your Google account has an ACTIVE GCP project")
  498. }
  499. // Prefer auto-detected tier; fall back to user-selected tier.
  500. tierID = canonicalGeminiTierIDForOAuthType(oauthType, tierID)
  501. if tierID == "" {
  502. if fallbackTierID != "" {
  503. tierID = fallbackTierID
  504. logger.LegacyPrintf("service.gemini_oauth", "[GeminiOAuth] Using fallback tier_id from user/session: %s", tierID)
  505. } else {
  506. tierID = GeminiTierGCPStandard
  507. logger.LegacyPrintf("service.gemini_oauth", "[GeminiOAuth] Using default tier_id: %s", tierID)
  508. }
  509. }
  510. logger.LegacyPrintf("service.gemini_oauth", "[GeminiOAuth] Final code_assist result - project_id: %s, tier_id: %s", projectID, tierID)
  511. case "google_one":
  512. logger.LegacyPrintf("service.gemini_oauth", "[GeminiOAuth] Processing google_one OAuth type")
  513. // Google One accounts use cloudaicompanion API, which requires a project_id.
  514. // For personal accounts, Google auto-assigns a project_id via the LoadCodeAssist API.
  515. if projectID == "" {
  516. logger.LegacyPrintf("service.gemini_oauth", "[GeminiOAuth] No project_id provided, attempting to fetch from LoadCodeAssist API...")
  517. var err error
  518. projectID, _, err = s.fetchProjectID(ctx, tokenResp.AccessToken, proxyURL)
  519. if err != nil {
  520. logger.LegacyPrintf("service.gemini_oauth", "[GeminiOAuth] ERROR: Failed to fetch project_id: %v", err)
  521. return nil, fmt.Errorf("google One accounts require a project_id, failed to auto-detect: %w", err)
  522. }
  523. logger.LegacyPrintf("service.gemini_oauth", "[GeminiOAuth] Successfully fetched project_id: %s", projectID)
  524. }
  525. logger.LegacyPrintf("service.gemini_oauth", "[GeminiOAuth] Attempting to fetch Google One tier from Drive API...")
  526. // Attempt to fetch Drive storage tier
  527. var storageInfo *geminicli.DriveStorageInfo
  528. var err error
  529. tierID, storageInfo, err = s.FetchGoogleOneTier(ctx, tokenResp.AccessToken, proxyURL)
  530. if err != nil {
  531. // Log warning but don't block - use fallback
  532. fmt.Printf("[GeminiOAuth] Warning: Failed to fetch Drive tier: %v\n", err)
  533. logger.LegacyPrintf("service.gemini_oauth", "[GeminiOAuth] WARNING: Failed to fetch Drive tier: %v", err)
  534. tierID = ""
  535. } else {
  536. logger.LegacyPrintf("service.gemini_oauth", "[GeminiOAuth] Successfully fetched Drive tier: %s", tierID)
  537. if storageInfo != nil {
  538. logger.LegacyPrintf("service.gemini_oauth", "[GeminiOAuth] Drive storage - Limit: %d bytes (%.2f TB), Usage: %d bytes (%.2f GB)",
  539. storageInfo.Limit, float64(storageInfo.Limit)/float64(TB),
  540. storageInfo.Usage, float64(storageInfo.Usage)/float64(GB))
  541. }
  542. }
  543. tierID = canonicalGeminiTierIDForOAuthType(oauthType, tierID)
  544. if tierID == "" || tierID == GeminiTierGoogleOneUnknown {
  545. if fallbackTierID != "" {
  546. tierID = fallbackTierID
  547. logger.LegacyPrintf("service.gemini_oauth", "[GeminiOAuth] Using fallback tier_id from user/session: %s", tierID)
  548. } else {
  549. tierID = GeminiTierGoogleOneFree
  550. logger.LegacyPrintf("service.gemini_oauth", "[GeminiOAuth] Using default tier_id: %s", tierID)
  551. }
  552. }
  553. fmt.Printf("[GeminiOAuth] Google One tierID after normalization: %s\n", tierID)
  554. // Store Drive info in extra field for caching
  555. if storageInfo != nil {
  556. tokenInfo := &GeminiTokenInfo{
  557. AccessToken: tokenResp.AccessToken,
  558. RefreshToken: tokenResp.RefreshToken,
  559. TokenType: tokenResp.TokenType,
  560. ExpiresIn: tokenResp.ExpiresIn,
  561. ExpiresAt: expiresAt,
  562. Scope: tokenResp.Scope,
  563. ProjectID: projectID,
  564. TierID: tierID,
  565. OAuthType: oauthType,
  566. Extra: map[string]any{
  567. "drive_storage_limit": storageInfo.Limit,
  568. "drive_storage_usage": storageInfo.Usage,
  569. "drive_tier_updated_at": time.Now().Format(time.RFC3339),
  570. },
  571. }
  572. logger.LegacyPrintf("service.gemini_oauth", "[GeminiOAuth] ========== ExchangeCode END (google_one with storage info) ==========")
  573. return tokenInfo, nil
  574. }
  575. case "ai_studio":
  576. // No automatic tier detection for AI Studio OAuth; rely on user selection.
  577. if fallbackTierID != "" {
  578. tierID = fallbackTierID
  579. } else {
  580. tierID = GeminiTierAIStudioFree
  581. }
  582. default:
  583. logger.LegacyPrintf("service.gemini_oauth", "[GeminiOAuth] Processing %s OAuth type (no tier detection)", oauthType)
  584. }
  585. logger.LegacyPrintf("service.gemini_oauth", "[GeminiOAuth] ========== Account Type Detection END ==========")
  586. result := &GeminiTokenInfo{
  587. AccessToken: tokenResp.AccessToken,
  588. RefreshToken: tokenResp.RefreshToken,
  589. TokenType: tokenResp.TokenType,
  590. ExpiresIn: tokenResp.ExpiresIn,
  591. ExpiresAt: expiresAt,
  592. Scope: tokenResp.Scope,
  593. ProjectID: projectID,
  594. TierID: tierID,
  595. OAuthType: oauthType,
  596. }
  597. logger.LegacyPrintf("service.gemini_oauth", "[GeminiOAuth] Final result - OAuth Type: %s, Project ID: %s, Tier ID: %s", result.OAuthType, result.ProjectID, result.TierID)
  598. logger.LegacyPrintf("service.gemini_oauth", "[GeminiOAuth] ========== ExchangeCode END ==========")
  599. return result, nil
  600. }
  601. func (s *GeminiOAuthService) RefreshToken(ctx context.Context, oauthType, refreshToken, proxyURL string) (*GeminiTokenInfo, error) {
  602. var lastErr error
  603. for attempt := 0; attempt <= 3; attempt++ {
  604. if attempt > 0 {
  605. backoff := time.Duration(1<<uint(attempt-1)) * time.Second
  606. if backoff > 30*time.Second {
  607. backoff = 30 * time.Second
  608. }
  609. time.Sleep(backoff)
  610. }
  611. tokenResp, err := s.oauthClient.RefreshToken(ctx, oauthType, refreshToken, proxyURL)
  612. if err == nil {
  613. // 计算过期时间:减去 5 分钟安全时间窗口(考虑网络延迟和时钟偏差)
  614. // 同时设置下界保护,防止 expires_in 过小导致过去时间(引发刷新风暴)
  615. const safetyWindow = 300 // 5 minutes
  616. const minTTL = 30 // minimum 30 seconds
  617. expiresAt := time.Now().Unix() + tokenResp.ExpiresIn - safetyWindow
  618. minExpiresAt := time.Now().Unix() + minTTL
  619. if expiresAt < minExpiresAt {
  620. expiresAt = minExpiresAt
  621. }
  622. return &GeminiTokenInfo{
  623. AccessToken: tokenResp.AccessToken,
  624. RefreshToken: tokenResp.RefreshToken,
  625. TokenType: tokenResp.TokenType,
  626. ExpiresIn: tokenResp.ExpiresIn,
  627. ExpiresAt: expiresAt,
  628. Scope: tokenResp.Scope,
  629. }, nil
  630. }
  631. if isNonRetryableGeminiOAuthError(err) {
  632. return nil, err
  633. }
  634. lastErr = err
  635. }
  636. return nil, fmt.Errorf("token refresh failed after retries: %w", lastErr)
  637. }
  638. func isNonRetryableGeminiOAuthError(err error) bool {
  639. msg := err.Error()
  640. nonRetryable := []string{
  641. "invalid_grant",
  642. "invalid_client",
  643. "unauthorized_client",
  644. "access_denied",
  645. }
  646. for _, needle := range nonRetryable {
  647. if strings.Contains(msg, needle) {
  648. return true
  649. }
  650. }
  651. return false
  652. }
  653. func (s *GeminiOAuthService) RefreshAccountToken(ctx context.Context, account *Account) (*GeminiTokenInfo, error) {
  654. if account.Platform != PlatformGemini || account.Type != AccountTypeOAuth {
  655. return nil, fmt.Errorf("account is not a Gemini OAuth account")
  656. }
  657. refreshToken := account.GetCredential("refresh_token")
  658. if strings.TrimSpace(refreshToken) == "" {
  659. return nil, fmt.Errorf("no refresh token available")
  660. }
  661. // Preserve oauth_type from the account (defaults to code_assist for backward compatibility).
  662. oauthType := strings.TrimSpace(account.GetCredential("oauth_type"))
  663. if oauthType == "" {
  664. oauthType = "code_assist"
  665. }
  666. var proxyURL string
  667. if account.ProxyID != nil {
  668. proxy, err := s.proxyRepo.GetByID(ctx, *account.ProxyID)
  669. if err == nil && proxy != nil {
  670. proxyURL = proxy.URL()
  671. }
  672. }
  673. tokenInfo, err := s.RefreshToken(ctx, oauthType, refreshToken, proxyURL)
  674. // Backward compatibility:
  675. // Older versions could refresh Code Assist tokens using a user-provided OAuth client when configured.
  676. // If the refresh token was originally issued to that custom client, forcing the built-in client will
  677. // fail with "unauthorized_client". In that case, retry with the custom client (ai_studio path) when available.
  678. if err != nil && oauthType == "code_assist" && strings.Contains(err.Error(), "unauthorized_client") && s.GetOAuthConfig().AIStudioOAuthEnabled {
  679. if alt, altErr := s.RefreshToken(ctx, "ai_studio", refreshToken, proxyURL); altErr == nil {
  680. tokenInfo = alt
  681. err = nil
  682. }
  683. }
  684. // Backward compatibility for google_one:
  685. // - New behavior: when a custom OAuth client is configured, google_one will use it.
  686. // - Old behavior: google_one always used the built-in Gemini CLI OAuth client.
  687. // If an existing account was authorized with the built-in client, refreshing with the custom client
  688. // will fail with "unauthorized_client". Retry with the built-in client (code_assist path forces it).
  689. if err != nil && oauthType == "google_one" && strings.Contains(err.Error(), "unauthorized_client") && s.GetOAuthConfig().AIStudioOAuthEnabled {
  690. if alt, altErr := s.RefreshToken(ctx, "code_assist", refreshToken, proxyURL); altErr == nil {
  691. tokenInfo = alt
  692. err = nil
  693. }
  694. }
  695. if err != nil {
  696. // Provide a more actionable error for common OAuth client mismatch issues.
  697. if strings.Contains(err.Error(), "unauthorized_client") {
  698. return nil, fmt.Errorf("%w (OAuth client mismatch: the refresh_token is bound to the OAuth client used during authorization; please re-authorize this account or restore the original GEMINI_OAUTH_CLIENT_ID/SECRET)", err)
  699. }
  700. return nil, err
  701. }
  702. tokenInfo.OAuthType = oauthType
  703. // Preserve account's project_id when present.
  704. existingProjectID := strings.TrimSpace(account.GetCredential("project_id"))
  705. if existingProjectID != "" {
  706. tokenInfo.ProjectID = existingProjectID
  707. }
  708. // 尝试从账号凭证获取 tierID(向后兼容)
  709. existingTierID := strings.TrimSpace(account.GetCredential("tier_id"))
  710. // For Code Assist, project_id is required. Auto-detect if missing.
  711. // For AI Studio OAuth, project_id is optional and should not block refresh.
  712. switch oauthType {
  713. case "code_assist":
  714. // 先设置默认值或保留旧值,确保 tier_id 始终有值
  715. if existingTierID != "" {
  716. tokenInfo.TierID = canonicalGeminiTierIDForOAuthType(oauthType, existingTierID)
  717. }
  718. if tokenInfo.TierID == "" {
  719. tokenInfo.TierID = GeminiTierGCPStandard
  720. }
  721. // 尝试自动探测 project_id 和 tier_id
  722. needDetect := strings.TrimSpace(tokenInfo.ProjectID) == "" || tokenInfo.TierID == ""
  723. if needDetect {
  724. projectID, tierID, err := s.fetchProjectID(ctx, tokenInfo.AccessToken, proxyURL)
  725. if err != nil {
  726. fmt.Printf("[GeminiOAuth] Warning: failed to auto-detect project/tier: %v\n", err)
  727. } else {
  728. if strings.TrimSpace(tokenInfo.ProjectID) == "" && projectID != "" {
  729. tokenInfo.ProjectID = projectID
  730. }
  731. if tierID != "" {
  732. if canonical := canonicalGeminiTierIDForOAuthType(oauthType, tierID); canonical != "" {
  733. tokenInfo.TierID = canonical
  734. }
  735. }
  736. }
  737. }
  738. if strings.TrimSpace(tokenInfo.ProjectID) == "" {
  739. return nil, fmt.Errorf("failed to auto-detect project_id: empty result")
  740. }
  741. case "google_one":
  742. canonicalExistingTier := canonicalGeminiTierIDForOAuthType(oauthType, existingTierID)
  743. // Check if tier cache is stale (> 24 hours)
  744. needsRefresh := true
  745. if account.Extra != nil {
  746. if updatedAtStr, ok := account.Extra["drive_tier_updated_at"].(string); ok {
  747. if updatedAt, err := time.Parse(time.RFC3339, updatedAtStr); err == nil {
  748. if time.Since(updatedAt) <= 24*time.Hour {
  749. needsRefresh = false
  750. // Use cached tier
  751. tokenInfo.TierID = canonicalExistingTier
  752. }
  753. }
  754. }
  755. }
  756. if tokenInfo.TierID == "" {
  757. tokenInfo.TierID = canonicalExistingTier
  758. }
  759. if needsRefresh {
  760. tierID, storageInfo, err := s.FetchGoogleOneTier(ctx, tokenInfo.AccessToken, proxyURL)
  761. if err == nil {
  762. if canonical := canonicalGeminiTierIDForOAuthType(oauthType, tierID); canonical != "" && canonical != GeminiTierGoogleOneUnknown {
  763. tokenInfo.TierID = canonical
  764. }
  765. if storageInfo != nil {
  766. tokenInfo.Extra = map[string]any{
  767. "drive_storage_limit": storageInfo.Limit,
  768. "drive_storage_usage": storageInfo.Usage,
  769. "drive_tier_updated_at": time.Now().Format(time.RFC3339),
  770. }
  771. }
  772. }
  773. }
  774. if tokenInfo.TierID == "" || tokenInfo.TierID == GeminiTierGoogleOneUnknown {
  775. if canonicalExistingTier != "" {
  776. tokenInfo.TierID = canonicalExistingTier
  777. } else {
  778. tokenInfo.TierID = GeminiTierGoogleOneFree
  779. }
  780. }
  781. }
  782. return tokenInfo, nil
  783. }
  784. func (s *GeminiOAuthService) BuildAccountCredentials(tokenInfo *GeminiTokenInfo) map[string]any {
  785. creds := map[string]any{
  786. "access_token": tokenInfo.AccessToken,
  787. "expires_at": strconv.FormatInt(tokenInfo.ExpiresAt, 10),
  788. }
  789. if tokenInfo.RefreshToken != "" {
  790. creds["refresh_token"] = tokenInfo.RefreshToken
  791. }
  792. if tokenInfo.TokenType != "" {
  793. creds["token_type"] = tokenInfo.TokenType
  794. }
  795. if tokenInfo.Scope != "" {
  796. creds["scope"] = tokenInfo.Scope
  797. }
  798. if tokenInfo.ProjectID != "" {
  799. creds["project_id"] = tokenInfo.ProjectID
  800. }
  801. if tokenInfo.TierID != "" {
  802. // Validate tier_id before storing
  803. if err := validateTierID(tokenInfo.TierID); err == nil {
  804. creds["tier_id"] = tokenInfo.TierID
  805. fmt.Printf("[GeminiOAuth] Storing tier_id: %s\n", tokenInfo.TierID)
  806. } else {
  807. fmt.Printf("[GeminiOAuth] Invalid tier_id %s: %v\n", tokenInfo.TierID, err)
  808. }
  809. // Silently skip invalid tier_id (don't block account creation)
  810. }
  811. if tokenInfo.OAuthType != "" {
  812. creds["oauth_type"] = tokenInfo.OAuthType
  813. }
  814. // Store extra metadata (Drive info) if present
  815. if len(tokenInfo.Extra) > 0 {
  816. for k, v := range tokenInfo.Extra {
  817. creds[k] = v
  818. }
  819. }
  820. return creds
  821. }
  822. func (s *GeminiOAuthService) Stop() {
  823. s.sessionStore.Stop()
  824. }
  825. func (s *GeminiOAuthService) fetchProjectID(ctx context.Context, accessToken, proxyURL string) (string, string, error) {
  826. if s.codeAssist == nil {
  827. return "", "", errors.New("code assist client not configured")
  828. }
  829. loadResp, loadErr := s.codeAssist.LoadCodeAssist(ctx, accessToken, proxyURL, nil)
  830. // Extract tierID from response (works whether CloudAICompanionProject is set or not)
  831. tierID := "LEGACY"
  832. if loadResp != nil {
  833. // First try to get tier from currentTier/paidTier fields
  834. if tier := loadResp.GetTier(); tier != "" {
  835. tierID = tier
  836. } else {
  837. // Fallback to extracting from allowedTiers
  838. tierID = extractTierIDFromAllowedTiers(loadResp.AllowedTiers)
  839. }
  840. }
  841. // If LoadCodeAssist returned a project, use it
  842. if loadErr == nil && loadResp != nil && strings.TrimSpace(loadResp.CloudAICompanionProject) != "" {
  843. return strings.TrimSpace(loadResp.CloudAICompanionProject), tierID, nil
  844. }
  845. // 关键逻辑:对齐 Gemini CLI 对“已注册用户”的处理方式。
  846. // 当 LoadCodeAssist 返回了 currentTier / paidTier(表示账号已注册)但没有返回 cloudaicompanionProject 时:
  847. // - 不要再调用 onboardUser(通常不会再分配 project_id,且可能触发 INVALID_ARGUMENT)
  848. // - 先尝试从 Cloud Resource Manager 获取可用项目;仍失败则提示用户手动填写 project_id
  849. if loadResp != nil {
  850. registeredTierID := strings.TrimSpace(loadResp.GetTier())
  851. if registeredTierID != "" {
  852. // 已注册但未返回 cloudaicompanionProject,这在 Google One 用户中较常见:需要用户自行提供 project_id。
  853. logger.LegacyPrintf("service.gemini_oauth", "[GeminiOAuth] User has tier (%s) but no cloudaicompanionProject, trying Cloud Resource Manager...", registeredTierID)
  854. // Try to get project from Cloud Resource Manager
  855. fallback, fbErr := fetchProjectIDFromResourceManager(ctx, accessToken, proxyURL)
  856. if fbErr == nil && strings.TrimSpace(fallback) != "" {
  857. logger.LegacyPrintf("service.gemini_oauth", "[GeminiOAuth] Found project from Cloud Resource Manager: %s", fallback)
  858. return strings.TrimSpace(fallback), tierID, nil
  859. }
  860. // No project found - user must provide project_id manually
  861. logger.LegacyPrintf("service.gemini_oauth", "[GeminiOAuth] No project found from Cloud Resource Manager, user must provide project_id manually")
  862. return "", tierID, fmt.Errorf("user is registered (tier: %s) but no project_id available. Please provide Project ID manually in the authorization form, or create a project at https://console.cloud.google.com", registeredTierID)
  863. }
  864. }
  865. // 未检测到 currentTier/paidTier,视为新用户,继续调用 onboardUser
  866. logger.LegacyPrintf("service.gemini_oauth", "[GeminiOAuth] No currentTier/paidTier found, proceeding with onboardUser (tierID: %s)", tierID)
  867. req := &geminicli.OnboardUserRequest{
  868. TierID: tierID,
  869. Metadata: geminicli.LoadCodeAssistMetadata{
  870. IDEType: "ANTIGRAVITY",
  871. Platform: "PLATFORM_UNSPECIFIED",
  872. PluginType: "GEMINI",
  873. },
  874. }
  875. maxAttempts := 5
  876. for attempt := 1; attempt <= maxAttempts; attempt++ {
  877. resp, err := s.codeAssist.OnboardUser(ctx, accessToken, proxyURL, req)
  878. if err != nil {
  879. // If Code Assist onboarding fails (e.g. INVALID_ARGUMENT), fallback to Cloud Resource Manager projects.
  880. fallback, fbErr := fetchProjectIDFromResourceManager(ctx, accessToken, proxyURL)
  881. if fbErr == nil && strings.TrimSpace(fallback) != "" {
  882. return strings.TrimSpace(fallback), tierID, nil
  883. }
  884. return "", tierID, err
  885. }
  886. if resp.Done {
  887. if resp.Response != nil && resp.Response.CloudAICompanionProject != nil {
  888. switch v := resp.Response.CloudAICompanionProject.(type) {
  889. case string:
  890. return strings.TrimSpace(v), tierID, nil
  891. case map[string]any:
  892. if id, ok := v["id"].(string); ok {
  893. return strings.TrimSpace(id), tierID, nil
  894. }
  895. }
  896. }
  897. fallback, fbErr := fetchProjectIDFromResourceManager(ctx, accessToken, proxyURL)
  898. if fbErr == nil && strings.TrimSpace(fallback) != "" {
  899. return strings.TrimSpace(fallback), tierID, nil
  900. }
  901. return "", tierID, errors.New("onboardUser completed but no project_id returned")
  902. }
  903. time.Sleep(2 * time.Second)
  904. }
  905. fallback, fbErr := fetchProjectIDFromResourceManager(ctx, accessToken, proxyURL)
  906. if fbErr == nil && strings.TrimSpace(fallback) != "" {
  907. return strings.TrimSpace(fallback), tierID, nil
  908. }
  909. if loadErr != nil {
  910. return "", tierID, fmt.Errorf("loadCodeAssist failed (%v) and onboardUser timeout after %d attempts", loadErr, maxAttempts)
  911. }
  912. return "", tierID, fmt.Errorf("onboardUser timeout after %d attempts", maxAttempts)
  913. }
  914. type googleCloudProject struct {
  915. ProjectID string `json:"projectId"`
  916. DisplayName string `json:"name"`
  917. LifecycleState string `json:"lifecycleState"`
  918. }
  919. type googleCloudProjectsResponse struct {
  920. Projects []googleCloudProject `json:"projects"`
  921. }
  922. func fetchProjectIDFromResourceManager(ctx context.Context, accessToken, proxyURL string) (string, error) {
  923. req, err := http.NewRequestWithContext(ctx, http.MethodGet, "https://cloudresourcemanager.googleapis.com/v1/projects", nil)
  924. if err != nil {
  925. return "", fmt.Errorf("failed to create resource manager request: %w", err)
  926. }
  927. req.Header.Set("Authorization", "Bearer "+accessToken)
  928. req.Header.Set("User-Agent", geminicli.GeminiCLIUserAgent)
  929. client, err := httpclient.GetClient(httpclient.Options{
  930. ProxyURL: strings.TrimSpace(proxyURL),
  931. Timeout: 30 * time.Second,
  932. ValidateResolvedIP: true,
  933. })
  934. if err != nil {
  935. return "", fmt.Errorf("create http client failed: %w", err)
  936. }
  937. resp, err := client.Do(req)
  938. if err != nil {
  939. return "", fmt.Errorf("resource manager request failed: %w", err)
  940. }
  941. defer func() { _ = resp.Body.Close() }()
  942. bodyBytes, err := io.ReadAll(resp.Body)
  943. if err != nil {
  944. return "", fmt.Errorf("failed to read resource manager response: %w", err)
  945. }
  946. if resp.StatusCode != http.StatusOK {
  947. return "", fmt.Errorf("resource manager HTTP %d: %s", resp.StatusCode, string(bodyBytes))
  948. }
  949. var projectsResp googleCloudProjectsResponse
  950. if err := json.Unmarshal(bodyBytes, &projectsResp); err != nil {
  951. return "", fmt.Errorf("failed to parse resource manager response: %w", err)
  952. }
  953. active := make([]googleCloudProject, 0, len(projectsResp.Projects))
  954. for _, p := range projectsResp.Projects {
  955. if p.LifecycleState == "ACTIVE" && strings.TrimSpace(p.ProjectID) != "" {
  956. active = append(active, p)
  957. }
  958. }
  959. if len(active) == 0 {
  960. return "", errors.New("no ACTIVE projects found from resource manager")
  961. }
  962. // Prefer likely companion projects first.
  963. for _, p := range active {
  964. id := strings.ToLower(strings.TrimSpace(p.ProjectID))
  965. name := strings.ToLower(strings.TrimSpace(p.DisplayName))
  966. if strings.Contains(id, "cloud-ai-companion") || strings.Contains(name, "cloud ai companion") || strings.Contains(name, "code assist") {
  967. return strings.TrimSpace(p.ProjectID), nil
  968. }
  969. }
  970. // Then prefer "default".
  971. for _, p := range active {
  972. id := strings.ToLower(strings.TrimSpace(p.ProjectID))
  973. name := strings.ToLower(strings.TrimSpace(p.DisplayName))
  974. if strings.Contains(id, "default") || strings.Contains(name, "default") {
  975. return strings.TrimSpace(p.ProjectID), nil
  976. }
  977. }
  978. return strings.TrimSpace(active[0].ProjectID), nil
  979. }