feat: Cline Auth Provider (#6131)

* Add ClineAuthProvider and integrate with AuthService

- Add new ClineAuthProvider class for Cline-specific authentication
- Update AuthService to support both Firebase and Cline auth providers
- Switch default provider from Firebase to Cline
- Add dynamic auth URL fetching for Cline provider
- Update type definitions to support multiple provider types

* Add API auth URL configuration and update Cline auth flow

- Add apiAuthUrl to environment configs for all environments
- Update ClineAuthProvider to use new token exchange API endpoint
- Add shared Cline API utilities and types
- Refactor auth service to handle access tokens with expiration
- Update mock auth service and test fixtures for new auth flow

* add changeset

* wip

* refactor authentication service and improve token handling

- Add null check for auth token in ClineAccountService
- Update authorization header format to use 'workos:' prefix
- Replace hardcoded API endpoints with CLINE_API_ENDPOINT constants
- Refactor ClineAuthInfo interface to use accessToken terminology
- Remove Firebase auth provider dependency
- Simplify auth callback handling and token storage
- Improve error handling for missing authentication tokens

* refactor(auth): standardize workos token prefix handling

Centralize workos: prefix application in AuthService.getAuthToken() method instead of duplicating across multiple API call sites. This ensures consistent authentication token formatting and simplifies maintenance by having a single source of truth for token prefixing.

* Remove unused code

* update mock responses

* Set Firebase Auth Provider as default

* Update src/shared/cline/api.ts

Co-authored-by: Tomás Barreiro <52393857+BarreiroT@users.noreply.github.com>

* remove docs

* refactor(auth): replace type union with IAuthProvider interface

- Replace AvailableAuthProvider type union with IAuthProvider interface for better extensibility
- Add ServiceConfig type for provider configuration
- Remove hardcoded providerName field in favor of provider.name property
- Update method signatures to use IAuthProvider interface
- Improve error messages and code comments for clarity
- Add TODO for mock auth provider implementation

---------

Co-authored-by: Tomás Barreiro <52393857+BarreiroT@users.noreply.github.com>
This commit is contained in:
BeeandTomás Barreiro authored and GitHub committed 2025-09-23 08:23:22 -07:00
1 parent 08365b3e0b
commit 10cbbb2c6b
15 files changed
+635 -177

No files matched your search

+5
View File
@@ -0,0 +1,5 @@
---
"claude-dev": patch
---
Support new Cline endpoint auth flow
+1 -1
View File
@@ -4,7 +4,7 @@ export enum Environment {
local = "local",
}
interface EnvironmentConfig {
export interface EnvironmentConfig {
appBaseUrl: string
apiBaseUrl: string
mcpBaseUrl: string
+1 -2
View File
@@ -200,14 +200,13 @@ export class ClineHandler implements ApiHandler {
async getApiStreamUsage(): Promise<ApiStreamUsageChunk | undefined> {
if (this.lastGenerationId) {
try {
// TODO: replace this with firebase auth
// TODO: use global API Host
const clineAccountAuthToken = await this._authService.getAuthToken()
if (!clineAccountAuthToken) {
throw new Error(CLINE_ACCOUNT_AUTH_ERROR_MESSAGE)
}
const response = await axios.get(`${this.clineAccountService.baseUrl}/generation?id=${this.lastGenerationId}`, {
headers: {
// Align with backend auth expectations
Authorization: `Bearer ${clineAccountAuthToken}`,
},
timeout: 15_000, // this request hangs sometimes
+8 -5
View File
@@ -8,6 +8,7 @@ import type {
} from "@shared/ClineAccount"
import axios, { AxiosRequestConfig, AxiosResponse } from "axios"
import { clineEnvConfig } from "@/config"
import { CLINE_API_ENDPOINT } from "@/shared/cline/api"
import { AuthService } from "../auth/AuthService"
export class ClineAccountService {
@@ -46,10 +47,12 @@ export class ClineAccountService {
* @throws Error if the API key is not found or the request fails
*/
private async authenticatedRequest<T>(endpoint: string, config: AxiosRequestConfig = {}): Promise<T> {
const url = `${this._baseUrl}${endpoint}`
const url = new URL(endpoint, this._baseUrl).toString() // Validate URL
// IMPORTANT: Prefixed with 'workos:' so backend can route verification to WorkOS provider
const clineAccountAuthToken = await this._authService.getAuthToken()
if (!clineAccountAuthToken) {
throw new Error("No Cline account auth token found")
}
const requestConfig: AxiosRequestConfig = {
...config,
headers: {
@@ -145,7 +148,7 @@ export class ClineAccountService {
*/
async fetchMe(): Promise<UserResponse | undefined> {
try {
const data = await this.authenticatedRequest<UserResponse>(`/api/v1/users/me`)
const data = await this.authenticatedRequest<UserResponse>(CLINE_API_ENDPOINT.USER_INFO)
return data
} catch (error) {
console.error("Failed to fetch user data (RPC):", error)
@@ -223,7 +226,7 @@ export class ClineAccountService {
// Call API to switch account
try {
// make XHR request to switch account
const _response = await this.authenticatedRequest<string>(`/api/v1/users/active-account`, {
const _response = await this.authenticatedRequest<string>(CLINE_API_ENDPOINT.ACTIVE_ACCOUNT, {
method: "PUT",
headers: {
"Content-Type": "application/json",
+101 -93
View File
@@ -7,23 +7,29 @@ import { HostProvider } from "@/hosts/host-provider"
import { telemetryService } from "@/services/telemetry"
import { openExternal } from "@/utils/env"
import { featureFlagsService } from "../feature-flags"
import { ClineAuthProvider } from "./providers/ClineAuthProvider"
import { FirebaseAuthProvider } from "./providers/FirebaseAuthProvider"
const DefaultClineAccountURI = `${clineEnvConfig.appBaseUrl}/auth`
let authProviders: any[] = []
import { IAuthProvider } from "./providers/IAuthProvider"
export type ServiceConfig = {
URI?: string
[key: string]: any
}
const availableAuthProviders = {
firebase: FirebaseAuthProvider,
// Add other providers here as needed
}
export interface ClineAuthInfo {
/**
* accessToken
*/
idToken: string
/**
* Short-lived refresh token
*/
refreshToken?: string
/**
* Access token expiration time
* When expired, the access token needs to be refreshed using the refresh token.
*/
expiresAt?: number
userInfo: ClineAccountUserInfo
}
@@ -37,6 +43,10 @@ export interface ClineAccountUserInfo {
* Cline app base URL, used for webview UI and other client-side operations
*/
appBaseUrl?: string
/**
* WorkOS IDP ID if user logged in via SSO
*/
subject?: string
}
export interface ClineAccountOrganization {
@@ -47,15 +57,13 @@ export interface ClineAccountOrganization {
roles: string[]
}
// TODO: Add logic to handle multiple webviews getting auth updates.
export class AuthService {
protected static instance: AuthService | null = null
protected _config: ServiceConfig
protected _authenticated: boolean = false
protected _clineAuthInfo: ClineAuthInfo | null = null
protected _provider: { provider: FirebaseAuthProvider } | null = null
protected _activeAuthStatusUpdateSubscriptions = new Set<[Controller, StreamingResponseHandler<AuthState>]>()
protected _provider: IAuthProvider | null = null
protected _activeAuthStatusUpdateHandlers = new Set<StreamingResponseHandler<AuthState>>()
protected _handlerToController = new Map<StreamingResponseHandler<AuthState>, Controller>()
protected _controller: Controller
/**
@@ -63,36 +71,8 @@ export class AuthService {
* @param controller - Optional reference to the Controller instance.
*/
protected constructor(controller: Controller) {
const providerName = "firebase"
this._config = { URI: DefaultClineAccountURI }
// Fetch AuthProviders
// TODO: Deliver this config from the backend securely
// ex. https://app.cline.bot/api/v1/auth/providers
const authProvidersConfigs = [
{
name: "firebase",
config: clineEnvConfig.firebase,
},
]
// Merge authProviders with availableAuthProviders
authProviders = authProvidersConfigs.map((provider) => {
const providerName = provider.name
const ProviderClass = availableAuthProviders[providerName as keyof typeof availableAuthProviders]
if (!ProviderClass) {
throw new Error(`Auth provider "${providerName}" is not available`)
}
return {
name: providerName,
config: provider.config,
provider: new ProviderClass(provider.config),
}
})
this._setProvider(authProviders.find((authProvider) => authProvider.name === providerName).name)
// Default to firebase for now
this._setProvider("firebase")
this._controller = controller
}
@@ -126,7 +106,7 @@ export class AuthService {
this._controller = controller
}
get authProvider(): any {
get authProvider(): IAuthProvider | null {
return this._provider
}
@@ -134,29 +114,52 @@ export class AuthService {
this._setProvider(providerName)
}
/**
* Returns the current authentication token with the appropriate prefix.
* Refreshing it if necessary.
*/
async getAuthToken(): Promise<string | null> {
if (!this._clineAuthInfo) {
return null
}
const idToken = this._clineAuthInfo.idToken
const shouldRefreshIdToken = await this._provider?.provider.shouldRefreshIdToken(idToken)
if (shouldRefreshIdToken) {
// Retrieves the stored id token and refreshes it, then updates this._clineAuthInfo
await this.restoreRefreshTokenAndRetrieveAuthInfo()
if (!this._clineAuthInfo) {
try {
const clineAccountAuthToken = this._clineAuthInfo?.idToken
if (!this._clineAuthInfo || !clineAccountAuthToken) {
// Not authenticated
return null
}
// Check if token has expired
if (await this._provider?.shouldRefreshIdToken(clineAccountAuthToken, this._clineAuthInfo.expiresAt)) {
console.log("Provider indicates token needs refresh")
const updatedAuthInfo = await this._provider?.retrieveClineAuthInfo(this._controller)
if (updatedAuthInfo) {
this._clineAuthInfo = updatedAuthInfo
this._authenticated = true
} else {
this._clineAuthInfo = null
this._authenticated = false
}
await this.sendAuthStatusUpdate()
}
// IMPORTANT: Prefix with 'workos:' so backend can route verification to WorkOS provider
const prefix = this._provider?.name === "cline" ? "workos:" : ""
return clineAccountAuthToken ? `${prefix}${clineAccountAuthToken}` : null
} catch (error) {
console.error("Error getting auth token:", error)
return null
}
return this._clineAuthInfo.idToken
}
protected _setProvider(providerName: string): void {
const providerConfig = authProviders.find((provider) => provider.name === providerName)
if (!providerConfig) {
throw new Error(`Auth provider "${providerName}" not found`)
// Only ClineAuthProvider is supported going forward
// Keeping the providerName param for forward compatibility/telemetrye
switch (providerName) {
case "cline":
this._provider = new ClineAuthProvider(clineEnvConfig)
break
case "firebase":
default:
this._provider = new FirebaseAuthProvider(clineEnvConfig)
break
}
this._provider = providerConfig
}
getInfo(): AuthState {
@@ -187,17 +190,14 @@ export class AuthService {
return String.create({ value: "Already authenticated" })
}
if (!this._config.URI) {
throw new Error("Authentication URI is not configured")
if (!this._provider) {
return String.create({ value: "Authentication provider is not configured" })
}
const callbackHost = await HostProvider.get().getCallbackUrl()
const callbackUrl = `${callbackHost}/auth`
// Use URL object for more graceful query construction
const authUrl = new URL(this._config.URI)
authUrl.searchParams.set("callback_url", callbackUrl)
const authUrl = await this._provider.getAuthRequest(callbackUrl)
const authUrlString = authUrl.toString()
await openExternal(authUrlString)
@@ -219,14 +219,14 @@ export class AuthService {
}
}
async handleAuthCallback(token: string, provider: string): Promise<void> {
async handleAuthCallback(authorizationCode: string, provider: string): Promise<void> {
if (!this._provider) {
throw new Error("Auth provider is not set")
}
try {
this._clineAuthInfo = await this._provider.provider.signIn(this._controller, token, provider)
this._authenticated = true
this._clineAuthInfo = await this._provider.signIn(this._controller, authorizationCode, provider)
this._authenticated = this._clineAuthInfo?.idToken !== undefined
await this.sendAuthStatusUpdate()
} catch (error) {
@@ -244,16 +244,16 @@ export class AuthService {
}
/**
* Restores the authentication token from the extension's storage.
* Restores the authentication data from the extension's storage.
* This is typically called when the extension is activated.
*/
async restoreRefreshTokenAndRetrieveAuthInfo(): Promise<void> {
if (!this._provider || !this._provider.provider) {
if (!this._provider) {
throw new Error("Auth provider is not set")
}
try {
this._clineAuthInfo = await this._provider.provider.retrieveClineAuthInfo(this._controller)
this._clineAuthInfo = await this._provider.retrieveClineAuthInfo(this._controller)
if (this._clineAuthInfo) {
this._authenticated = true
await this.sendAuthStatusUpdate()
@@ -286,10 +286,12 @@ export class AuthService {
console.log("Subscribing to authStatusUpdate")
// Add this subscription to the active subscriptions
this._activeAuthStatusUpdateSubscriptions.add([controller, responseStream])
this._activeAuthStatusUpdateHandlers.add(responseStream)
this._handlerToController.set(responseStream, controller)
// Register cleanup when the connection is closed
const cleanup = () => {
this._activeAuthStatusUpdateSubscriptions.delete([controller, responseStream])
this._activeAuthStatusUpdateHandlers.delete(responseStream)
this._handlerToController.delete(responseStream)
}
// Register the cleanup function with the request registry if we have a requestId
if (requestId) {
@@ -302,7 +304,8 @@ export class AuthService {
} catch (error) {
console.error("Error sending initial auth status:", error)
// Remove the subscription if there was an error
this._activeAuthStatusUpdateSubscriptions.delete([controller, responseStream])
this._activeAuthStatusUpdateHandlers.delete(responseStream)
this._handlerToController.delete(responseStream)
}
}
@@ -310,35 +313,40 @@ export class AuthService {
* Send an authStatusUpdate event to all active subscribers
*/
async sendAuthStatusUpdate(): Promise<void> {
// Send the event to all active subscribers
const promises = Array.from(this._activeAuthStatusUpdateSubscriptions).map(async ([controller, responseStream]) => {
try {
const authInfo: AuthState = this.getInfo()
// Compute once per broadcast
const authInfo: AuthState = this.getInfo()
const uniqueControllers = new Set<Controller>()
// Send the event to all active subscribers
const streamSends = Array.from(this._activeAuthStatusUpdateHandlers).map(async (responseStream) => {
const controller = this._handlerToController.get(responseStream)
if (controller) {
uniqueControllers.add(controller)
}
try {
await responseStream(
authInfo,
false, // Not the last message
)
// Identify the user in telemetry if available
// Fetch the feature flags for the user
if (this._clineAuthInfo?.userInfo?.id) {
telemetryService.identifyAccount(this._clineAuthInfo.userInfo)
featureFlagsService.reset()
await featureFlagsService.poll()
}
// Update the state in the webview
if (controller) {
await controller.postStateToWebview()
}
} catch (error) {
console.error("Error sending authStatusUpdate event:", error)
// Remove the subscription if there was an error
this._activeAuthStatusUpdateSubscriptions.delete([controller, responseStream])
this._activeAuthStatusUpdateHandlers.delete(responseStream)
this._handlerToController.delete(responseStream)
}
})
await Promise.all(promises)
await Promise.all(streamSends)
// Identify the user in telemetry if available
// Fetch the feature flags for the user
if (this._clineAuthInfo?.userInfo?.id) {
telemetryService.identifyAccount(this._clineAuthInfo.userInfo)
featureFlagsService.reset()
await featureFlagsService.poll()
}
// Update state in webviews once per unique controller
await Promise.all(Array.from(uniqueControllers).map((c) => c.postStateToWebview()))
}
}
+33 -25
View File
@@ -2,9 +2,10 @@ import { String } from "@shared/proto/cline/common"
import { clineEnvConfig } from "@/config"
import { Controller } from "@/core/controller"
import { WebviewProvider } from "@/core/webview"
import type { UserResponse } from "@/shared/ClineAccount"
import { CLINE_API_ENDPOINT } from "@/shared/cline/api"
import { AuthService } from "./AuthService"
// TODO: Consider adding a mock auth provider implementing IAuthProvider for more realistic testing
export class AuthServiceMock extends AuthService {
protected constructor(controller: Controller) {
super(controller)
@@ -13,8 +14,9 @@ export class AuthServiceMock extends AuthService {
throw new Error("AuthServiceMock should only be used in local environment for testing purposes.")
}
this._config = { URI: clineEnvConfig.apiBaseUrl }
this._setProvider("firebase")
// Support both auth providers, default to firebase for compatibility
const authProvider = process.env.E2E_TEST_AUTH_PROVIDER || "firebase"
this._setProvider(authProvider)
this._controller = controller
}
@@ -53,16 +55,20 @@ export class AuthServiceMock extends AuthService {
}
try {
// Fetch user data from mock server
const meUri = new URL("/api/v1/users/me", clineEnvConfig.apiBaseUrl)
// Use token exchange endpoint like ClineAuthProvider
const tokenExchangeUri = new URL(CLINE_API_ENDPOINT.TOKEN_EXCHANGE, clineEnvConfig.apiBaseUrl)
const tokenType = "personal"
const testToken = `test-${tokenType}-token`
const response = await fetch(meUri, {
method: "GET",
const testCode = `test-${tokenType}-token`
const response = await fetch(tokenExchangeUri, {
method: "POST",
headers: {
Authorization: `Bearer ${testToken}`,
"Content-Type": "application/json",
},
body: JSON.stringify({
code: testCode,
grantType: "authorization_code",
}),
})
if (!response.ok) {
@@ -75,30 +81,32 @@ export class AuthServiceMock extends AuthService {
throw new Error("Invalid response from mock server")
}
const userData = responseData.data as UserResponse
const authData = responseData.data
// Convert UserResponse to ClineAuthInfo format
// Convert to ClineAuthInfo format matching ClineAuthProvider
this._clineAuthInfo = {
idToken: testToken,
idToken: authData.accessToken,
refreshToken: authData.refreshToken,
expiresAt: new Date(authData.expiresAt).getTime() / 1000,
userInfo: {
id: userData.id,
email: userData.email,
displayName: userData.displayName,
createdAt: userData.createdAt,
organizations: userData.organizations.map((org) => ({
active: org.active,
memberId: org.memberId,
name: org.name,
organizationId: org.organizationId,
roles: org.roles,
})),
id: authData.userInfo.clineUserId || authData.userInfo.subject,
email: authData.userInfo.email,
displayName: authData.userInfo.name,
createdAt: new Date().toISOString(),
organizations: authData.organizations,
appBaseUrl: clineEnvConfig.appBaseUrl,
subject: authData.userInfo.subject,
},
}
console.log(`Successfully authenticated with mock server as ${userData.displayName} (${userData.email})`)
console.log(`Successfully authenticated with mock server as ${authData.userInfo.name} (${authData.userInfo.email})`)
const visibleWebview = WebviewProvider.getVisibleInstance()
await visibleWebview?.controller.handleAuthCallback(testToken, "mock")
// Use appropriate provider name for callback
const providerName = this._provider?.name || "mock"
// Simulate handling the auth callback as if from a real provider
await visibleWebview?.controller.handleAuthCallback(authData.accessToken, providerName)
} catch (error) {
console.error("Error signing in with mock server:", error)
this._authenticated = false
@@ -0,0 +1,313 @@
import { clineEnvConfig, EnvironmentConfig } from "@/config"
import { Controller } from "@/core/controller"
import { HostProvider } from "@/hosts/host-provider"
import { Logger } from "@/services/logging/Logger"
import { CLINE_API_ENDPOINT } from "@/shared/cline/api"
import type { ClineAuthInfo } from "../AuthService"
import { IAuthProvider } from "./IAuthProvider"
interface ClineAuthApiUser {
subject: string | null
email: string
name: string
clineUserId: string | null
accounts: string[] | null
}
// Unified API response data shape for token exchange/refresh
interface ClineAuthResponseData {
/**
* Auth token to be used for authenticated requests
*/
accessToken: string
/**
* Refresh token to be used for refreshing the access token
*/
refreshToken?: string
/**
* Token type
* E.g. "Bearer"
*/
tokenType: string
/**
* Access token expiration time in ISO 8601 format
* E.g. "2025-09-17T04:32:24.842636548Z"
*/
expiresAt: string
/**
* User information associated with the token
*/
userInfo: ClineAuthApiUser
}
export interface ClineAuthApiTokenExchangeResponse {
success: boolean
data: ClineAuthResponseData
}
export interface ClineAuthApiTokenRefreshResponse {
success: boolean
data: ClineAuthResponseData
}
export class ClineAuthProvider implements IAuthProvider {
readonly name = "cline"
private _config
constructor(config: EnvironmentConfig) {
this._config = config
}
get config(): any {
return this._config
}
set config(value: any) {
this._config = value
}
/**
* Checks if the access token needs to be refreshed (expired or about to expire).
* Since the new flow doesn't support refresh tokens, this will return true if token is expired.
* @param _refreshToken - The existing refresh token to check.
* @returns {Promise<boolean>} True if the token is expired or about to expire.
*/
async shouldRefreshIdToken(_refreshToken: string, expiresAt?: number): Promise<boolean> {
try {
// expiresAt is in seconds
const expirationTime = expiresAt || 0
const currentTime = Date.now() / 1000
const next5Min = currentTime + 5 * 60
// Check if token is expired or will expire in the next 5 minutes
return expirationTime < next5Min // Access token is expired or about to expire
} catch (error) {
Logger.error("Error checking token expiration:", error)
return true // If we can't decode the token, assume it needs refresh
}
}
/**
* Retrieves Cline auth info using the stored access token.
* @param controller - The controller instance to access stored secrets.
* @returns {Promise<ClineAuthInfo | null>} A promise that resolves with the auth info or null.
*/
async retrieveClineAuthInfo(controller: Controller): Promise<ClineAuthInfo | null> {
try {
// Get the stored auth data from secure storage
const storedAuthDataString = controller.stateManager.getSecretKey("clineAccountId")
if (!storedAuthDataString) {
Logger.debug("No stored authentication data found")
return null
}
// Parse the stored auth data
let storedAuthData: ClineAuthInfo
try {
storedAuthData = JSON.parse(storedAuthDataString)
} catch (e) {
console.error("Failed to parse stored auth data:", e)
controller.stateManager.setSecret("clineAccountId", undefined)
return null
}
if (!storedAuthData.refreshToken || !storedAuthData?.idToken) {
console.error("No valid token found in stored authentication data")
controller.stateManager.setSecret("clineAccountId", undefined)
return null
}
if (await this.shouldRefreshIdToken(storedAuthData.refreshToken, storedAuthData.expiresAt)) {
// Try to refresh the token using the refresh token
const authInfo = await this.refreshToken(storedAuthData.refreshToken)
return authInfo || null
}
// Is the token valid?
if (storedAuthData.idToken && storedAuthData.refreshToken && storedAuthData.userInfo.id) {
return storedAuthData
}
// Verify the token structure
const tokenParts = storedAuthData.idToken.split(".")
if (tokenParts.length !== 3) {
throw new Error("Invalid token format")
}
// Decode the token to verify it's a valid JWT
const payload = JSON.parse(Buffer.from(tokenParts[1], "base64").toString("utf-8"))
if (payload.external_id) {
storedAuthData.userInfo.id = payload.external_id
}
console.log("Successfully retrieved and validated stored auth token")
return storedAuthData
} catch (error) {
console.error("Error retrieving stored authentication credential:", error)
return null
}
}
/**
* Refreshes an access token using a refresh token.
* @param refreshToken - The refresh token.
* @returns {Promise<ClineAuthInfo>} The new access token and user info.
*/
async refreshToken(refreshToken: string): Promise<ClineAuthInfo> {
try {
// Get the callback URL that was used during the initial auth request
const endpoint = new URL(CLINE_API_ENDPOINT.REFRESH_TOKEN, this._config.apiBaseUrl)
const response = await fetch(endpoint.toString(), {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
refreshToken, // short_lived_auth_code
grantType: "refresh_token", // must be "authorization_code"
}),
})
if (!response.ok) {
if (response.status === 400) {
const errorData = await response.json().catch(() => ({}))
const errorMessage = errorData?.error || "Invalid or expired authorization code"
throw new Error(errorMessage)
}
throw new Error(`HTTP error! status: ${response.status}`)
}
const data: ClineAuthApiTokenExchangeResponse = await response.json()
if (!data.success || !data.data.refreshToken || !data.data.accessToken) {
throw new Error("Failed to exchange authorization code for access token")
}
return {
idToken: data.data.accessToken,
// data.data.expiresAt example: "2025-09-17T03:43:57Z"; store in seconds
expiresAt: new Date(data.data.expiresAt).getTime() / 1000,
refreshToken: data.data.refreshToken || refreshToken,
userInfo: {
createdAt: new Date().toISOString(),
email: data.data.userInfo.email || "",
id: data.data.userInfo.clineUserId || "",
displayName: data.data.userInfo.name || "",
organizations: [],
appBaseUrl: this._config.appBaseUrl,
subject: data.data.userInfo.subject || "",
},
}
} catch (error: any) {
throw error
}
}
async getAuthRequest(callbackUrl: string): Promise<string> {
const authUrl = new URL(CLINE_API_ENDPOINT.AUTH, clineEnvConfig.apiBaseUrl)
authUrl.searchParams.set("client_type", "extension")
authUrl.searchParams.set("callback_url", callbackUrl)
// Ensure the redirect_uri is properly encoded and included
authUrl.searchParams.set("redirect_uri", callbackUrl)
// The server will respond with a 302 redirect to the OAuth provider
// We need to follow the redirect and get the final URL
let response: Response
try {
// Set redirect: 'manual' to handle the redirect manually
response = await fetch(authUrl.toString(), {
method: "GET",
redirect: "manual",
credentials: "include", // Important for cookies if needed
headers: {
Accept: "application/json",
"Content-Type": "application/json",
},
})
// If we get a redirect status (3xx), get the Location header
if (response.status >= 300 && response.status < 400) {
const redirectUrl = response.headers.get("Location")
if (!redirectUrl) {
throw new Error("No redirect URL found in the response")
}
return redirectUrl
}
// If we didn't get a redirect, try to parse the response as JSON
const responseData = await response.json()
if (responseData.redirect_url) {
return responseData.redirect_url
}
throw new Error("Unexpected response from auth server")
} catch (error) {
console.error("Error during authentication request:", error)
throw new Error(`Authentication failed: ${error instanceof Error ? error.message : "Unknown error"}`)
}
}
async signIn(controller: Controller, authorizationCode: string, provider: string): Promise<ClineAuthInfo | null> {
try {
// Get the callback URL that was used during the initial auth request
const callbackHost = await HostProvider.get().getCallbackUrl()
const callbackUrl = `${callbackHost}/auth`
// Exchange the authorization code for tokens
const tokenUrl = new URL(CLINE_API_ENDPOINT.TOKEN_EXCHANGE, clineEnvConfig.apiBaseUrl)
const response = await fetch(tokenUrl.toString(), {
method: "POST",
headers: {
"Content-Type": "application/json",
Accept: "application/json",
},
body: JSON.stringify({
grant_type: "authorization_code",
code: authorizationCode,
client_type: "extension",
redirect_uri: callbackUrl,
provider: provider,
}),
})
if (!response.ok) {
const errorData = await response.json().catch(() => ({}))
throw new Error(errorData.error_description || "Failed to exchange authorization code for tokens")
}
const responseJSON = await response.json()
console.log("Token data received:", responseJSON)
const responseType: ClineAuthApiTokenExchangeResponse = responseJSON
const tokenData = responseType.data
if (!tokenData.accessToken || !tokenData.refreshToken || !tokenData.userInfo) {
throw new Error("Invalid token response from server")
}
// Store the tokens and user info
const clineAuthInfo = {
idToken: tokenData.accessToken,
refreshToken: tokenData.refreshToken,
userInfo: {
id: tokenData.userInfo.clineUserId || "",
email: tokenData.userInfo.email || "",
displayName: tokenData.userInfo.name || "",
createdAt: new Date().toISOString(),
organizations: [],
},
expiresAt: new Date(tokenData.expiresAt).getTime() / 1000, // "2025-09-17T04:32:24.842636548Z"
}
controller.stateManager.setSecret("clineAccountId", JSON.stringify(clineAuthInfo))
return clineAuthInfo
} catch (error) {
console.error("Error handling auth callback:", error)
throw error
}
}
}
@@ -2,15 +2,19 @@ import axios from "axios"
import { initializeApp } from "firebase/app"
import { GithubAuthProvider, GoogleAuthProvider, getAuth, type OAuthCredential, signInWithCredential, User } from "firebase/auth"
import { jwtDecode } from "jwt-decode"
import { clineEnvConfig } from "@/config"
import { clineEnvConfig, EnvironmentConfig } from "@/config"
import { Controller } from "@/core/controller"
import { ErrorService } from "@/services/error"
import type { ClineAccountUserInfo, ClineAuthInfo } from "../AuthService"
import { IAuthProvider } from "./IAuthProvider"
export class FirebaseAuthProvider {
private _config: any
export class FirebaseAuthProvider implements IAuthProvider {
readonly name = "firebase"
readonly callbackEndpoint = "/auth"
constructor(config: any) {
private _config: EnvironmentConfig
constructor(config: EnvironmentConfig) {
this._config = config || {}
}
@@ -22,7 +26,7 @@ export class FirebaseAuthProvider {
this._config = value
}
async shouldRefreshIdToken(existingIdToken: string): Promise<boolean> {
async shouldRefreshIdToken(existingIdToken: string, _expiresAt?: number): Promise<boolean> {
const decodedToken = jwtDecode(existingIdToken)
const exp = decodedToken.exp || 0 // 1752297633
const expirationTime = exp * 1000
@@ -48,23 +52,11 @@ export class FirebaseAuthProvider {
}
try {
// Exchange refresh token for new access token using Firebase's secure token endpoint
// https://stackoverflow.com/questions/38233687/how-to-use-the-firebase-refreshtoken-to-reauthenticate/57119131#57119131
const firebaseApiKey = this._config.apiKey
const googleAccessTokenResponse = await axios.post(
`https://securetoken.googleapis.com/v1/token?key=${firebaseApiKey}`,
`grant_type=refresh_token&refresh_token=${encodeURIComponent(userRefreshToken)}`,
{
headers: {
"Content-Type": "application/x-www-form-urlencoded",
},
},
)
const { idToken } = await this.refreshToken(userRefreshToken)
// console.log("googleAccessTokenResponse", googleAccessTokenResponse)
// This returns an object with access_token, expires_in (3600), id_token (can be used as bearer token to authenticate requests, we'll use this in the future instead of firebase but need to be aware of how we use firebase sdk for e.g. user info like the profile image), project_id, refresh_token, token_type (always Bearer), and user_id
const idToken = googleAccessTokenResponse.data.id_token
// const idTokenExpirationDate = new Date(Date.now() + googleAccessTokenResponse.data.expires_in * 1000)
if (!idToken) {
throw new Error("No ID token received from refresh token exchange")
}
// Now retrieve the user info from the backend (this was an easy solution to keep providing user profile details like name and email, but we should move to using the fetchMe() function instead)
// Fetch user info from Cline API
@@ -79,26 +71,39 @@ export class FirebaseAuthProvider {
const userInfo: ClineAccountUserInfo = userResponse.data.data
return { idToken, userInfo }
// let userObject = JSON.parse(credentialJSON)
// let user = User.
// userObject = User.constructor._fromJSON(auth, user2);
// const credentialData: AuthCredential = OAuthCredential.fromJSON(credentialJSON) as AuthCredential
// const userCredential = await this._signInWithCredential(context, credentialData)
// return userCredential.user
} catch (error) {
console.error("Firebase restore token error", error)
ErrorService.get().logMessage("Firebase restore token error", "error")
ErrorService.get().logException(error)
throw error
}
}
/**
* Signs in the user using Firebase authentication with a custom token.
* @returns {Promise<User>} A promise that resolves with the authenticated user.
* @throws {Error} Throws an error if the sign-in fails.
*/
async refreshToken(userRefreshToken: string): Promise<Partial<ClineAuthInfo>> {
// Exchange refresh token for new access token using Firebase's secure token endpoint
// https://stackoverflow.com/questions/38233687/how-to-use-the-firebase-refreshtoken-to-reauthenticate/57119131#57119131
const firebaseApiKey = this._config.firebase.apiKey
const googleAccessTokenResponse = await axios.post(
`https://securetoken.googleapis.com/v1/token?key=${firebaseApiKey}`,
`grant_type=refresh_token&refresh_token=${encodeURIComponent(userRefreshToken)}`,
{
headers: {
"Content-Type": "application/x-www-form-urlencoded",
},
},
)
// This returns an object with access_token, expires_in (3600), id_token (can be used as bearer token to authenticate requests, we'll use this in the future instead of firebase but need to be aware of how we use firebase sdk for e.g. user info like the profile image), project_id, refresh_token, token_type (always Bearer), and user_id
// Store user data
return { idToken: googleAccessTokenResponse.data.id_token }
}
getAuthRequest(callbackUrl: string): Promise<string> {
// Use URL object for more graceful query construction
const authUrl = new URL(`${clineEnvConfig.appBaseUrl}/auth`)
authUrl.searchParams.set("callback_url", callbackUrl)
return Promise.resolve(authUrl.toString())
}
async signIn(controller: Controller, token: string, provider: string): Promise<ClineAuthInfo | null> {
try {
let credential: OAuthCredential
@@ -113,7 +118,7 @@ export class FirebaseAuthProvider {
throw new Error(`Unsupported provider: ${provider}`)
}
// we've received the short-lived tokens from google/github, now we need to sign in to firebase with them
const firebaseConfig = Object.assign({}, this._config)
const firebaseConfig = Object.assign({}, this._config.firebase)
const app = initializeApp(firebaseConfig)
const auth = getAuth(app)
// this signs the user into firebase sdk internally
@@ -0,0 +1,13 @@
import { EnvironmentConfig } from "@/config"
import { Controller } from "@/core/controller"
import { ClineAuthInfo } from "../AuthService"
export interface IAuthProvider {
readonly name: string
config: EnvironmentConfig
shouldRefreshIdToken(token: string, expiresAt?: number): Promise<boolean>
retrieveClineAuthInfo(controller: Controller): Promise<ClineAuthInfo | null>
refreshToken(refreshToken: string): Promise<Partial<ClineAuthInfo>>
getAuthRequest(callbackUrl: string): Promise<string>
signIn(controller: Controller, authorizationCode: string, provider: string): Promise<ClineAuthInfo | null>
}
+21 -1
View File
@@ -2,6 +2,8 @@ import { expect } from "chai"
import { afterEach, beforeEach, describe, it } from "mocha"
import * as sinon from "sinon"
import { WebviewProvider } from "@/core/webview"
import { ErrorService } from "../error"
import { Logger } from "../logging/Logger"
import { SharedUriHandler } from "./SharedUriHandler"
describe("SharedUriHandler", () => {
@@ -9,9 +11,27 @@ describe("SharedUriHandler", () => {
let handleOpenRouterCallbackStub: sinon.SinonStub
let handleAuthCallbackStub: sinon.SinonStub
beforeEach(() => {
beforeEach(async () => {
sandbox = sinon.createSandbox()
// Mock Logger methods to avoid HostProvider dependency
sandbox.stub(Logger, "info").returns()
sandbox.stub(Logger, "error").returns()
// Mock ErrorService to avoid telemetry dependency
const mockErrorService = {
logMessage: sandbox.stub(),
logException: sandbox.stub(),
toClineError: sandbox.stub(),
isEnabled: sandbox.stub().returns(false),
getSettings: sandbox.stub().returns({ enabled: false, hostEnabled: false }),
getProvider: sandbox.stub(),
dispose: sandbox.stub().resolves(),
}
sandbox.stub(ErrorService, "initialize").resolves(mockErrorService as any)
sandbox.stub(ErrorService, "get").returns(mockErrorService as any)
await ErrorService.initialize()
handleOpenRouterCallbackStub = sandbox.stub().resolves()
handleAuthCallbackStub = sandbox.stub().resolves()
const mockWebviewProvider = {
+15 -11
View File
@@ -1,4 +1,5 @@
import { WebviewProvider } from "@/core/webview"
import { Logger } from "../logging/Logger"
/**
* Shared URI handler that processes both VSCode URI events and HTTP server callbacks
@@ -18,16 +19,19 @@ export class SharedUriHandler {
const queryString = parsedUrl.search.slice(1) // Remove leading '?'
const query = new URLSearchParams(queryString.replace(/\+/g, "%2B"))
console.log("SharedUriHandler: Processing URI:", {
path: path,
query: query,
scheme: parsedUrl.protocol,
})
Logger.info(
"SharedUriHandler: Processing URI:" +
JSON.stringify({
path: path,
query: query,
scheme: parsedUrl.protocol,
}),
)
const visibleWebview = WebviewProvider.getVisibleInstance()
if (!visibleWebview) {
console.warn("SharedUriHandler: No visible webview found")
Logger.warn("SharedUriHandler: No visible webview found")
return false
}
@@ -44,15 +48,15 @@ export class SharedUriHandler {
}
case "/auth": {
const provider = query.get("provider")
const token = query.get("idToken")
console.log("SharedUriHandler: Auth callback received:", { path: path, provider: provider })
Logger.info(`SharedUriHandler - Auth callback received for ${provider} - ${path}`)
const token = query.get("refreshToken") || query.get("idToken") || query.get("code")
if (token) {
await visibleWebview.controller.handleAuthCallback(token, provider)
return true
}
console.warn("SharedUriHandler: Missing idToken parameter for auth callback")
Logger.warn("SharedUriHandler: Missing idToken parameter for auth callback")
return false
}
case "/auth/oca": {
@@ -69,11 +73,11 @@ export class SharedUriHandler {
return false
}
default:
console.warn(`SharedUriHandler: Unknown path: ${path}`)
Logger.warn(`SharedUriHandler: Unknown path: ${path}`)
return false
}
} catch (error) {
console.error("SharedUriHandler: Error processing URI:", error)
Logger.error("SharedUriHandler: Error processing URI:", error)
return false
}
}
+15
View File
@@ -0,0 +1,15 @@
enum CLINE_API_AUTH_ENDPOINTS {
AUTH = "/api/v1/auth/authorize",
REFRESH_TOKEN = "/api/v1/auth/refresh",
}
enum CLINE_API_ENDPOINT_V1 {
TOKEN_EXCHANGE = "/api/v1/auth/token",
USER_INFO = "/api/v1/users/me",
ACTIVE_ACCOUNT = "/api/v1/users/active-account",
}
export const CLINE_API_ENDPOINT = {
...CLINE_API_AUTH_ENDPOINTS,
...CLINE_API_ENDPOINT_V1,
}
+1 -1
View File
@@ -9,7 +9,7 @@ export const E2E_REGISTERED_MOCK_ENDPOINTS = {
"/users/{userId}/usages",
"/users/{userId}/payments",
],
POST: ["/chat/completions"],
POST: ["/chat/completions", "/auth/token"],
PUT: ["/users/active-account"],
},
"/.test": {
+1 -1
View File
@@ -117,7 +117,7 @@ export class ClineDataMock {
public getUserByToken(token?: string): UserResponse {
// Use default personal token if none provided
const actualToken = token || ClineDataMock.getDefaultToken("personal") || "test-personal-token"
const currentUser = this._getUserByToken(actualToken)
const currentUser = this._getUserByToken(actualToken.replace("_access", "")) // Remove _access suffix if present
this.setCurrentUser(currentUser)
return currentUser
}
+66 -1
View File
@@ -157,7 +157,7 @@ export class ClineApiServerMock {
// Authentication middleware
const authHeader = req.headers.authorization
const isAuthRequired = !path.startsWith("/.test/") && path !== "/health"
const isAuthRequired = !path.startsWith("/.test/") && path !== "/health" && path !== "/api/v1/auth/token"
if (isAuthRequired && (!authHeader || !authHeader.startsWith("Bearer "))) {
return sendApiError("Unauthorized", 401)
@@ -296,6 +296,71 @@ export class ClineApiServerMock {
return sendApiResponse("Account switched successfully")
}
// Auth token exchange endpoint
if (endpoint === "/auth/token" && method === "POST") {
const body = await readBody()
const parsed = JSON.parse(body)
const { code, grantType } = parsed
if (grantType !== "authorization_code" || !code) {
return sendApiError("Invalid request", 400)
}
const user = controller.API_USER.getUserByToken(code)
if (!user) {
return sendApiError("Invalid or expired authorization code", 400)
}
// Return format matching ClineAuthProvider expectations
return sendApiResponse({
accessToken: code + "_access",
refreshToken: code + "_refresh",
tokenType: "Bearer",
expiresAt: new Date(Date.now() + 3600 * 1000).toISOString(), // 1 hour from now
userInfo: {
subject: user.id,
email: user.email,
name: user.displayName,
clineUserId: user.id,
accounts: null,
organizations: user.organizations,
},
})
}
// Auth refresh token endpoint
if (endpoint === "/auth/refresh" && method === "POST") {
const body = await readBody()
const parsed = JSON.parse(body)
const { refreshToken, grantType } = parsed
if (grantType !== "refresh_token" || !refreshToken) {
return sendApiError("Invalid request", 400)
}
// Extract original token from refresh token
const originalToken = refreshToken.replace("_refresh", "")
const user = controller.API_USER.getUserByToken(originalToken)
if (!user) {
return sendApiError("Invalid or expired refresh token", 400)
}
// Return format matching ClineAuthProvider expectations
return sendApiResponse({
accessToken: originalToken + "_access_refreshed",
refreshToken: refreshToken, // Keep same refresh token
tokenType: "Bearer",
expiresAt: new Date(Date.now() + 3600 * 1000).toISOString(), // 1 hour from now
userInfo: {
subject: user.id,
email: user.email,
name: user.displayName,
clineUserId: user.id,
accounts: null,
},
})
}
// Chat completions endpoint
if (endpoint === "/chat/completions" && method === "POST") {
if (!controller.userHasOrganization && controller.userBalance <= 0) {