(tokens: OAuthTokens)
| 1192 | |
| 1193 | // Function to store OAuth tokens in secure storage |
| 1194 | export function saveOAuthTokensIfNeeded(tokens: OAuthTokens): { |
| 1195 | success: boolean |
| 1196 | warning?: string |
| 1197 | } { |
| 1198 | if (!shouldUseClaudeAIAuth(tokens.scopes)) { |
| 1199 | logEvent('tengu_oauth_tokens_not_claude_ai', {}) |
| 1200 | return { success: true } |
| 1201 | } |
| 1202 | |
| 1203 | // Skip saving inference-only tokens (they come from env vars) |
| 1204 | if (!tokens.refreshToken || !tokens.expiresAt) { |
| 1205 | logEvent('tengu_oauth_tokens_inference_only', {}) |
| 1206 | return { success: true } |
| 1207 | } |
| 1208 | |
| 1209 | const secureStorage = getSecureStorage() |
| 1210 | const storageBackend = |
| 1211 | secureStorage.name as AnalyticsMetadata_I_VERIFIED_THIS_IS_NOT_CODE_OR_FILEPATHS |
| 1212 | |
| 1213 | try { |
| 1214 | const storageData = secureStorage.read() || {} |
| 1215 | const existingOauth = storageData.claudeAiOauth |
| 1216 | |
| 1217 | storageData.claudeAiOauth = { |
| 1218 | accessToken: tokens.accessToken, |
| 1219 | refreshToken: tokens.refreshToken, |
| 1220 | expiresAt: tokens.expiresAt, |
| 1221 | scopes: tokens.scopes, |
| 1222 | // Profile fetch in refreshOAuthToken swallows errors and returns null on |
| 1223 | // transient failures (network, 5xx, rate limit). Don't clobber a valid |
| 1224 | // stored subscription with null — fall back to the existing value. |
| 1225 | subscriptionType: |
| 1226 | tokens.subscriptionType ?? existingOauth?.subscriptionType ?? null, |
| 1227 | rateLimitTier: |
| 1228 | tokens.rateLimitTier ?? existingOauth?.rateLimitTier ?? null, |
| 1229 | } |
| 1230 | |
| 1231 | const updateStatus = secureStorage.update(storageData) |
| 1232 | |
| 1233 | if (updateStatus.success) { |
| 1234 | logEvent('tengu_oauth_tokens_saved', { storageBackend }) |
| 1235 | } else { |
| 1236 | logEvent('tengu_oauth_tokens_save_failed', { storageBackend }) |
| 1237 | } |
| 1238 | |
| 1239 | getClaudeAIOAuthTokens.cache?.clear?.() |
| 1240 | clearBetasCaches() |
| 1241 | clearToolSchemaCache() |
| 1242 | return updateStatus |
| 1243 | } catch (error) { |
| 1244 | logError(error) |
| 1245 | logEvent('tengu_oauth_tokens_save_exception', { |
| 1246 | storageBackend, |
| 1247 | error: errorMessage( |
| 1248 | error, |
| 1249 | ) as AnalyticsMetadata_I_VERIFIED_THIS_IS_NOT_CODE_OR_FILEPATHS, |
| 1250 | }) |
| 1251 | return { success: false, warning: 'Failed to save OAuth tokens' } |
no test coverage detected