Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
94 changes: 64 additions & 30 deletions packages/core/src/auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,39 +33,73 @@ export async function refreshClaudeOAuthToken(input: {
refreshToken: string
fetchImpl?: typeof fetch
now?: () => number
maxRetries?: number
baseDelayMs?: number
}): Promise<ClaudeOAuthRefreshResult> {
const fetchImpl = input.fetchImpl ?? fetch
const response = await fetchImpl(TOKEN_URL, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Accept: 'application/json',
},
body: JSON.stringify({
grant_type: 'refresh_token',
refresh_token: input.refreshToken,
client_id: CLIENT_ID,
}),
})

if (!response.ok) {
const body = await response.text().catch(() => '')
throw new ClaudeOAuthRefreshError(response.status, body)
}

const json = (await response.json()) as {
access_token: string
refresh_token?: string
expires_in: number
}
const refreshedAt = input.now?.() ?? Date.now()

return {
access: json.access_token,
refresh: json.refresh_token ?? input.refreshToken,
expires: refreshedAt + json.expires_in * 1000,
expiresIn: json.expires_in,
const maxRetries = input.maxRetries ?? 2
const baseDelayMs = input.baseDelayMs ?? 500

for (let attempt = 0; attempt <= maxRetries; attempt++) {
try {
if (attempt > 0) {
const delay = baseDelayMs * 2 ** (attempt - 1)
await new Promise((resolve) => setTimeout(resolve, delay))
}

const response = await fetchImpl(TOKEN_URL, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Accept: 'application/json',
},
body: JSON.stringify({
grant_type: 'refresh_token',
refresh_token: input.refreshToken,
client_id: CLIENT_ID,
}),
})

if (!response.ok) {
if (response.status >= 500 && attempt < maxRetries) {
await response.body?.cancel()
continue
}
const body = await response.text().catch(() => '')
throw new ClaudeOAuthRefreshError(response.status, body)
}

const json = (await response.json()) as {
access_token: string
refresh_token?: string
expires_in: number
}
const refreshedAt = input.now?.() ?? Date.now()

return {
access: json.access_token,
refresh: json.refresh_token ?? input.refreshToken,
expires: refreshedAt + json.expires_in * 1000,
expiresIn: json.expires_in,
}
} catch (error) {
if (error instanceof ClaudeOAuthRefreshError) throw error
const isNetworkError =
error instanceof Error &&
(error.message.includes('fetch failed') ||
('code' in error &&
((error as Error & { code: string }).code === 'ECONNRESET' ||
(error as Error & { code: string }).code === 'ECONNREFUSED' ||
(error as Error & { code: string }).code === 'ETIMEDOUT' ||
(error as Error & { code: string }).code ===
'UND_ERR_CONNECT_TIMEOUT')))
if (attempt < maxRetries && isNetworkError) {
continue
}
throw error
}
}
throw new Error('Token refresh exhausted all retries')
}

export type AuthorizationResult = {
Expand Down