Skip to content

Commit a638b21

Browse files
committed
fix(api): fix stale token binding and remove raw GitHub token fallback
Re-read copilotToken after refresh since the local binding captured the pre-refresh value. Stop falling back to the raw GitHub token when Copilot exchange fails - the raw token doesn't work with the Copilot API and just produces confusing 401 errors downstream.
1 parent 812724d commit a638b21

1 file changed

Lines changed: 12 additions & 12 deletions

File tree

Sources/APIFramework/CopilotTokenStore.swift

Lines changed: 12 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -120,26 +120,29 @@ public class CopilotTokenStore: ObservableObject {
120120
public func getCopilotToken() async throws -> String {
121121
// If we have a Copilot token, use it (with refresh if needed)
122122
if let token = copilotToken {
123-
// Check if expired
124123
if token.isExpired() {
125124
logger.info("Copilot token expired, refreshing...")
126125
try await refreshCopilotToken()
127126
}
128-
return token.token
127+
// Re-read copilotToken after potential refresh (local binding may be stale)
128+
if let current = copilotToken {
129+
return current.token
130+
}
129131
}
130132

131133
// Have a GitHub token but no Copilot token - try exchange
132-
if let githubToken = githubToken {
134+
if githubToken != nil {
133135
logger.info("No Copilot token, attempting exchange...")
134136
do {
135137
try await refreshCopilotToken()
136138
if let token = copilotToken {
137139
return token.token
138140
}
139141
} catch {
140-
logger.warning("Copilot token exchange failed: \(error.localizedDescription), using GitHub token directly")
142+
logger.warning("Copilot token exchange failed: \(error.localizedDescription)")
141143
}
142-
return githubToken
144+
// Don't fall back to raw GitHub token - it won't work with Copilot API
145+
throw TokenStoreError.noToken
143146
}
144147

145148
// No token at all
@@ -189,19 +192,16 @@ public class CopilotTokenStore: ObservableObject {
189192
do {
190193
try await refreshCopilotToken()
191194
if let token = copilotToken {
192-
logger.info("Token recovery succeeded")
195+
logger.info("Token recovery succeeded - new Copilot token obtained")
193196
return token.token
194197
}
195198
} catch {
196199
logger.warning("Token recovery failed: \(error.localizedDescription)")
197200
}
198201

199-
// If Copilot refresh failed, try returning the raw GitHub token
200-
if let githubToken = githubToken {
201-
logger.info("Falling back to GitHub token after Copilot refresh failure")
202-
return githubToken
203-
}
204-
202+
// Don't fall back to raw GitHub token - it causes 401 loops
203+
// The raw GitHub token can't authenticate against the Copilot API
204+
logger.error("Token recovery failed - no valid Copilot token available")
205205
return nil
206206
}
207207

0 commit comments

Comments
 (0)