MCPcopy Create free account
hub / github.com/freecodexyz/free-code / saveOAuthTokensIfNeeded

Function saveOAuthTokensIfNeeded

src/utils/auth.ts:1195–1254  ·  view source on GitHub ↗
(tokens: OAuthTokens)

Source from the content-addressed store, hash-verified

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

Callers 3

OAuthFlowStepFunction · 0.85
installOAuthTokensFunction · 0.85

Calls 9

shouldUseClaudeAIAuthFunction · 0.85
logEventFunction · 0.85
getSecureStorageFunction · 0.85
clearBetasCachesFunction · 0.85
clearToolSchemaCacheFunction · 0.85
logErrorFunction · 0.70
errorMessageFunction · 0.70
readMethod · 0.45
clearMethod · 0.45

Tested by

no test coverage detected