| 1 | import crypto from "crypto"; |
| 2 | |
| 3 | import { |
| 4 | AuthType, |
| 5 | ControlPlaneSessionInfo, |
| 6 | HubEnv, |
| 7 | isHubEnv, |
| 8 | } from "core/control-plane/AuthTypes"; |
| 9 | import { getControlPlaneEnvSync } from "core/control-plane/env"; |
| 10 | import fetch from "node-fetch"; |
| 11 | import { v4 as uuidv4 } from "uuid"; |
| 12 | import { |
| 13 | authentication, |
| 14 | AuthenticationProvider, |
| 15 | AuthenticationProviderAuthenticationSessionsChangeEvent, |
| 16 | AuthenticationSession, |
| 17 | Disposable, |
| 18 | env, |
| 19 | EventEmitter, |
| 20 | ExtensionContext, |
| 21 | ProgressLocation, |
| 22 | Uri, |
| 23 | window, |
| 24 | } from "vscode"; |
| 25 | |
| 26 | import { PromiseAdapter, promiseFromEvent } from "./promiseUtils"; |
| 27 | import { SecretStorage } from "./SecretStorage"; |
| 28 | import { UriEventHandler } from "./uriHandler"; |
| 29 | |
| 30 | const AUTH_NAME = "Continue"; |
| 31 | |
| 32 | const controlPlaneEnv = getControlPlaneEnvSync(true ? "production" : "none"); |
| 33 | |
| 34 | const SESSIONS_SECRET_KEY = `${controlPlaneEnv.AUTH_TYPE}.sessions`; |
| 35 | |
| 36 | // Function to generate a random string of specified length |
| 37 | function generateRandomString(length: number): string { |
| 38 | const possibleCharacters = |
| 39 | "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~"; |
| 40 | let randomString = ""; |
| 41 | for (let i = 0; i < length; i++) { |
| 42 | const randomIndex = Math.floor(Math.random() * possibleCharacters.length); |
| 43 | randomString += possibleCharacters[randomIndex]; |
| 44 | } |
| 45 | return randomString; |
| 46 | } |
| 47 | |
| 48 | // Function to generate a code challenge from the code verifier |
| 49 | |
| 50 | async function generateCodeChallenge(verifier: string) { |
| 51 | // Create a SHA-256 hash of the verifier |
| 52 | const hash = crypto.createHash("sha256").update(verifier).digest(); |
| 53 | |
| 54 | // Convert the hash to a base64 URL-encoded string |
| 55 | const base64String = hash |
| 56 | .toString("base64") |
| 57 | .replace(/\+/g, "-") |
| 58 | .replace(/\//g, "_") |
| 59 | .replace(/=+$/, ""); |
| 60 | |
| 61 | return base64String; |
| 62 | } |
| 63 | |
| 64 | interface ContinueAuthenticationSession extends AuthenticationSession { |
| 65 | refreshToken: string; |
| 66 | expiresInMs: number; |
| 67 | loginNeeded: boolean; |
| 68 | } |
| 69 | |
| 70 | export class WorkOsAuthProvider implements AuthenticationProvider, Disposable { |
| 71 | private _sessionChangeEmitter = |
| 72 | new EventEmitter<AuthenticationProviderAuthenticationSessionsChangeEvent>(); |
| 73 | private _disposable: Disposable; |
| 74 | private _pendingStates: string[] = []; |
| 75 | private _codeExchangePromises = new Map< |
| 76 | string, |
| 77 | { promise: Promise<string>; cancel: EventEmitter<void> } |
| 78 | >(); |
| 79 | private _refreshInterval: NodeJS.Timeout | null = null; |
| 80 | private _isRefreshing = false; |
| 81 | |
| 82 | private static EXPIRATION_TIME_MS = 1000 * 60 * 15; // 15 minutes |
| 83 | private static REFRESH_INTERVAL_MS = 1000 * 60 * 10; // 10 minutes |
| 84 | |
| 85 | private secretStorage: SecretStorage; |
| 86 | |
| 87 | constructor( |
| 88 | private readonly context: ExtensionContext, |
| 89 | private readonly _uriHandler: UriEventHandler, |
| 90 | ) { |
| 91 | this._disposable = Disposable.from( |
| 92 | authentication.registerAuthenticationProvider( |
| 93 | controlPlaneEnv.AUTH_TYPE, |
| 94 | AUTH_NAME, |
| 95 | this, |
| 96 | { supportsMultipleAccounts: false }, |
| 97 | ), |
| 98 | window.registerUriHandler(this._uriHandler), |
| 99 | ); |
| 100 | |
| 101 | this.secretStorage = new SecretStorage(context); |
| 102 | |
| 103 | // Immediately refresh any existing sessions |
| 104 | void this.refreshSessions(); |
| 105 | |
| 106 | // Set up a regular interval to refresh tokens |
| 107 | this._refreshInterval = setInterval(() => { |
| 108 | void this.refreshSessions(); |
| 109 | }, WorkOsAuthProvider.REFRESH_INTERVAL_MS); |
| 110 | } |
| 111 | |
| 112 | private decodeJwt(jwt: string): Record<string, any> | null { |
| 113 | try { |
| 114 | const decodedToken = JSON.parse( |
| 115 | Buffer.from(jwt.split(".")[1], "base64").toString(), |
| 116 | ); |
| 117 | return decodedToken; |
| 118 | } catch (e: any) { |
| 119 | console.warn(`Error decoding JWT: ${e}`); |
| 120 | return null; |
| 121 | } |
| 122 | } |
| 123 | |
| 124 | private jwtIsExpiredOrInvalid(jwt: string): boolean { |
| 125 | const decodedToken = this.decodeJwt(jwt); |
| 126 | if (!decodedToken) { |
| 127 | return true; |
| 128 | } |
| 129 | return decodedToken.exp * 1000 < Date.now(); |
| 130 | } |
| 131 | |
| 132 | private getExpirationTimeMs(jwt: string): number { |
| 133 | const decodedToken = this.decodeJwt(jwt); |
| 134 | if (!decodedToken) { |
| 135 | return WorkOsAuthProvider.EXPIRATION_TIME_MS; |
| 136 | } |
| 137 | return decodedToken.exp && decodedToken.iat |
| 138 | ? (decodedToken.exp - decodedToken.iat) * 1000 |
| 139 | : WorkOsAuthProvider.EXPIRATION_TIME_MS; |
| 140 | } |
| 141 | |
| 142 | private async storeSessions(value: ContinueAuthenticationSession[]) { |
| 143 | const data = JSON.stringify(value, null, 2); |
| 144 | await this.secretStorage.store(SESSIONS_SECRET_KEY, data); |
| 145 | } |
| 146 | |
| 147 | public async getSessions( |
| 148 | scopes?: string[], |
| 149 | ): Promise<ContinueAuthenticationSession[]> { |
| 150 | const data = await this.secretStorage.get(SESSIONS_SECRET_KEY); |
| 151 | if (!data) { |
| 152 | return []; |
| 153 | } |
| 154 | |
| 155 | try { |
| 156 | const value = JSON.parse(data) as ContinueAuthenticationSession[]; |
| 157 | return value; |
| 158 | } catch (e: any) { |
| 159 | console.warn(`Error parsing sessions.json: ${e}`); |
| 160 | return []; |
| 161 | } |
| 162 | } |
| 163 | |
| 164 | get onDidChangeSessions() { |
| 165 | return this._sessionChangeEmitter.event; |
| 166 | } |
| 167 | |
| 168 | get ideRedirectUri() { |
| 169 | // We redirect to a page that says "you can close this page", and that page finishes the redirect |
| 170 | const url = new URL(controlPlaneEnv.APP_URL); |
| 171 | url.pathname = `/auth/${env.uriScheme}-redirect`; |
| 172 | return url.toString(); |
| 173 | } |
| 174 | |
| 175 | public static useOnboardingUri: boolean = false; |
| 176 | get redirectUri() { |
| 177 | if (WorkOsAuthProvider.useOnboardingUri) { |
| 178 | const url = new URL(controlPlaneEnv.APP_URL); |
| 179 | url.pathname = `/auth/${env.uriScheme}-redirect`; |
| 180 | return url.toString(); |
| 181 | } |
| 182 | return this.ideRedirectUri; |
| 183 | } |
| 184 | |
| 185 | async refreshSessions() { |
| 186 | // Prevent concurrent refresh operations |
| 187 | if (this._isRefreshing) { |
| 188 | return; |
| 189 | } |
| 190 | |
| 191 | try { |
| 192 | this._isRefreshing = true; |
| 193 | await this._refreshSessions(); |
| 194 | } catch (e) { |
| 195 | console.error(`Error refreshing sessions: ${e}`); |
| 196 | } finally { |
| 197 | this._isRefreshing = false; |
| 198 | } |
| 199 | } |
| 200 | |
| 201 | private async _refreshSessions(): Promise<void> { |
| 202 | const sessions = await this.getSessions(); |
| 203 | if (!sessions.length) { |
| 204 | return; |
| 205 | } |
| 206 | |
| 207 | const finalSessions = []; |
| 208 | for (const session of sessions) { |
| 209 | try { |
| 210 | const newSession = await this._refreshSessionWithRetry( |
| 211 | session.refreshToken, |
| 212 | ); |
| 213 | finalSessions.push({ |
| 214 | ...session, |
| 215 | accessToken: newSession.accessToken, |
| 216 | refreshToken: newSession.refreshToken, |
| 217 | expiresInMs: newSession.expiresInMs, |
| 218 | }); |
| 219 | } catch (e: any) { |
| 220 | // If refresh fails (after retries for valid tokens), drop the session |
| 221 | console.debug(`Error refreshing session token: ${e.message}`); |
| 222 | this._sessionChangeEmitter.fire({ |
| 223 | added: [], |
| 224 | removed: [session], |
| 225 | changed: [], |
| 226 | }); |
| 227 | } |
| 228 | } |
| 229 | |
| 230 | await this.storeSessions(finalSessions); |
| 231 | this._sessionChangeEmitter.fire({ |
| 232 | added: [], |
| 233 | removed: [], |
| 234 | changed: finalSessions, |
| 235 | }); |
| 236 | } |
| 237 | |
| 238 | private async _refreshSessionWithRetry( |
| 239 | refreshToken: string, |
| 240 | attempt = 1, |
| 241 | baseDelay = 1000, |
| 242 | ): Promise<{ |
| 243 | accessToken: string; |
| 244 | refreshToken: string; |
| 245 | expiresInMs: number; |
| 246 | }> { |
| 247 | try { |
| 248 | return await this._refreshSession(refreshToken); |
| 249 | } catch (error: any) { |
| 250 | // Don't retry for auth errors |
| 251 | if ( |
| 252 | error.message?.includes("401") || |
| 253 | error.message?.includes("Invalid refresh token") || |
| 254 | error.message?.includes("Unauthorized") |
| 255 | ) { |
| 256 | throw error; |
| 257 | } |
| 258 | |
| 259 | // For network errors or transient server issues, retry with backoff |
| 260 | // Calculate exponential backoff delay with jitter |
| 261 | const delay = Math.min( |
| 262 | baseDelay * Math.pow(2, attempt - 1) * (0.5 + Math.random() * 0.5), |
| 263 | 2 * 60 * 1000, // 2 minutes |
| 264 | ); |
| 265 | |
| 266 | return new Promise((resolve, reject) => { |
| 267 | setTimeout(() => { |
| 268 | this._refreshSessionWithRetry(refreshToken, attempt + 1, baseDelay) |
| 269 | .then(resolve) |
| 270 | .catch(reject); |
| 271 | }, delay); |
| 272 | }); |
| 273 | } |
| 274 | } |
| 275 | |
| 276 | private async _refreshSession(refreshToken: string): Promise<{ |
| 277 | accessToken: string; |
| 278 | refreshToken: string; |
| 279 | expiresInMs: number; |
| 280 | }> { |
| 281 | const response = await fetch( |
| 282 | new URL("/auth/refresh", controlPlaneEnv.CONTROL_PLANE_URL), |
| 283 | { |
| 284 | method: "POST", |
| 285 | headers: { |
| 286 | "Content-Type": "application/json", |
| 287 | }, |
| 288 | body: JSON.stringify({ |
| 289 | refreshToken, |
| 290 | }), |
| 291 | }, |
| 292 | ); |
| 293 | if (!response.ok) { |
| 294 | const text = await response.text(); |
| 295 | throw new Error("Error refreshing token: " + text); |
| 296 | } |
| 297 | const data = (await response.json()) as any; |
| 298 | return { |
| 299 | accessToken: data.accessToken, |
| 300 | refreshToken: data.refreshToken, |
| 301 | expiresInMs: this.getExpirationTimeMs(data.accessToken), |
| 302 | }; |
| 303 | } |
| 304 | |
| 305 | private _formatProfileLabel( |
| 306 | firstName: string | null, |
| 307 | lastName: string | null, |
| 308 | ) { |
| 309 | return ((firstName ?? "") + " " + (lastName ?? "")).trim(); |
| 310 | } |
| 311 | |
| 312 | /** |
| 313 | * Create a new auth session |
| 314 | * @param scopes |
| 315 | * @returns |
| 316 | */ |
| 317 | public async createSession( |
| 318 | scopes: string[], |
| 319 | ): Promise<ContinueAuthenticationSession> { |
| 320 | try { |
| 321 | const codeVerifier = generateRandomString(64); |
| 322 | const codeChallenge = await generateCodeChallenge(codeVerifier); |
| 323 | |
| 324 | if (!isHubEnv(controlPlaneEnv)) { |
| 325 | throw new Error("Login is disabled"); |
| 326 | } |
| 327 | |
| 328 | const token = await this.login(codeChallenge, controlPlaneEnv, scopes); |
| 329 | if (!token) { |
| 330 | throw new Error(`Continue login failure`); |
| 331 | } |
| 332 | |
| 333 | const userInfo = (await this.getUserInfo( |
| 334 | token, |
| 335 | codeVerifier, |
| 336 | controlPlaneEnv, |
| 337 | )) as any; |
| 338 | const { user, access_token, refresh_token } = userInfo; |
| 339 | |
| 340 | const session: ContinueAuthenticationSession = { |
| 341 | id: uuidv4(), |
| 342 | accessToken: access_token, |
| 343 | refreshToken: refresh_token, |
| 344 | expiresInMs: this.getExpirationTimeMs(access_token), |
| 345 | loginNeeded: false, |
| 346 | account: { |
| 347 | label: this._formatProfileLabel(user.first_name, user.last_name), |
| 348 | id: user.email, |
| 349 | }, |
| 350 | scopes: [], |
| 351 | }; |
| 352 | |
| 353 | await this.storeSessions([session]); |
| 354 | |
| 355 | this._sessionChangeEmitter.fire({ |
| 356 | added: [session], |
| 357 | removed: [], |
| 358 | changed: [], |
| 359 | }); |
| 360 | |
| 361 | return session; |
| 362 | } catch (e) { |
| 363 | void window.showErrorMessage(`Sign in failed: ${e}`); |
| 364 | throw e; |
| 365 | } |
| 366 | } |
| 367 | |
| 368 | /** |
| 369 | * Remove an existing session |
| 370 | * @param sessionId |
| 371 | */ |
| 372 | public async removeSession(sessionId: string): Promise<void> { |
| 373 | const sessions = await this.getSessions(); |
| 374 | const sessionIdx = sessions.findIndex((s) => s.id === sessionId); |
| 375 | const session = sessions[sessionIdx]; |
| 376 | sessions.splice(sessionIdx, 1); |
| 377 | |
| 378 | await this.storeSessions(sessions); |
| 379 | |
| 380 | if (session) { |
| 381 | this._sessionChangeEmitter.fire({ |
| 382 | added: [], |
| 383 | removed: [session], |
| 384 | changed: [], |
| 385 | }); |
| 386 | } |
| 387 | } |
| 388 | |
| 389 | /** |
| 390 | * Dispose the registered services |
| 391 | */ |
| 392 | public async dispose() { |
| 393 | if (this._refreshInterval) { |
| 394 | clearInterval(this._refreshInterval); |
| 395 | this._refreshInterval = null; |
| 396 | } |
| 397 | this._disposable.dispose(); |
| 398 | } |
| 399 | |
| 400 | /** |
| 401 | * Log in to Continue |
| 402 | */ |
| 403 | private async login( |
| 404 | codeChallenge: string, |
| 405 | hubEnv: HubEnv, |
| 406 | scopes: string[] = [], |
| 407 | ) { |
| 408 | return await window.withProgress<string>( |
| 409 | { |
| 410 | location: ProgressLocation.Notification, |
| 411 | title: "Signing in to Continue...", |
| 412 | cancellable: true, |
| 413 | }, |
| 414 | async (_, token) => { |
| 415 | const stateId = uuidv4(); |
| 416 | |
| 417 | this._pendingStates.push(stateId); |
| 418 | |
| 419 | const scopeString = scopes.join(" "); |
| 420 | |
| 421 | const url = new URL("https://api.workos.com/user_management/authorize"); |
| 422 | const params = { |
| 423 | response_type: "code", |
| 424 | client_id: hubEnv.WORKOS_CLIENT_ID, |
| 425 | redirect_uri: this.redirectUri, |
| 426 | state: stateId, |
| 427 | code_challenge: codeChallenge, |
| 428 | code_challenge_method: "S256", |
| 429 | provider: "authkit", |
| 430 | screen_hint: WorkOsAuthProvider.useOnboardingUri |
| 431 | ? "sign-up" |
| 432 | : "sign-in", |
| 433 | }; |
| 434 | |
| 435 | Object.keys(params).forEach((key) => |
| 436 | url.searchParams.append(key, params[key as keyof typeof params]), |
| 437 | ); |
| 438 | |
| 439 | const oauthUrl = url; |
| 440 | if (oauthUrl) { |
| 441 | await env.openExternal(Uri.parse(oauthUrl.toString())); |
| 442 | } else { |
| 443 | return; |
| 444 | } |
| 445 | |
| 446 | let codeExchangePromise = this._codeExchangePromises.get(scopeString); |
| 447 | if (!codeExchangePromise) { |
| 448 | codeExchangePromise = promiseFromEvent( |
| 449 | this._uriHandler.event, |
| 450 | this.handleUri(scopes), |
| 451 | ); |
| 452 | this._codeExchangePromises.set(scopeString, codeExchangePromise); |
| 453 | } |
| 454 | |
| 455 | try { |
| 456 | return await Promise.race([ |
| 457 | codeExchangePromise.promise, |
| 458 | new Promise<string>( |
| 459 | (_, reject) => |
| 460 | setTimeout(() => reject("Cancelled"), 60 * 60 * 1_000), // 60min timeout |
| 461 | ), |
| 462 | promiseFromEvent<any, any>( |
| 463 | token.onCancellationRequested, |
| 464 | (_, __, reject) => { |
| 465 | reject("User Cancelled"); |
| 466 | }, |
| 467 | ).promise, |
| 468 | ]); |
| 469 | } finally { |
| 470 | this._pendingStates = this._pendingStates.filter( |
| 471 | (n) => n !== stateId, |
| 472 | ); |
| 473 | codeExchangePromise?.cancel.fire(); |
| 474 | this._codeExchangePromises.delete(scopeString); |
| 475 | } |
| 476 | }, |
| 477 | ); |
| 478 | } |
| 479 | |
| 480 | /** |
| 481 | * Handle the redirect to VS Code (after sign in from Continue) |
| 482 | * @param scopes |
| 483 | * @returns |
| 484 | */ |
| 485 | private handleUri: ( |
| 486 | scopes: readonly string[], |
| 487 | ) => PromiseAdapter<Uri, string> = |
| 488 | (scopes) => async (uri, resolve, reject) => { |
| 489 | const query = new URLSearchParams(uri.query); |
| 490 | const access_token = query.get("code"); |
| 491 | const state = query.get("state"); |
| 492 | |
| 493 | if (!access_token) { |
| 494 | reject(new Error("No token")); |
| 495 | return; |
| 496 | } |
| 497 | if (!state) { |
| 498 | reject(new Error("No state")); |
| 499 | return; |
| 500 | } |
| 501 | |
| 502 | // Check if it is a valid auth request started by the extension |
| 503 | if (!this._pendingStates.some((n) => n === state)) { |
| 504 | reject(new Error("State not found")); |
| 505 | return; |
| 506 | } |
| 507 | |
| 508 | resolve(access_token); |
| 509 | }; |
| 510 | |
| 511 | /** |
| 512 | * Get the user info from WorkOS |
| 513 | * @param token |
| 514 | * @returns |
| 515 | */ |
| 516 | private async getUserInfo( |
| 517 | token: string, |
| 518 | codeVerifier: string, |
| 519 | hubEnv: HubEnv, |
| 520 | ) { |
| 521 | const resp = await fetch( |
| 522 | "https://api.workos.com/user_management/authenticate", |
| 523 | { |
| 524 | method: "POST", |
| 525 | headers: { |
| 526 | "Content-Type": "application/json", |
| 527 | }, |
| 528 | body: JSON.stringify({ |
| 529 | client_id: hubEnv.WORKOS_CLIENT_ID, |
| 530 | code_verifier: codeVerifier, |
| 531 | grant_type: "authorization_code", |
| 532 | code: token, |
| 533 | }), |
| 534 | }, |
| 535 | ); |
| 536 | const text = await resp.text(); |
| 537 | const data = JSON.parse(text); |
| 538 | return data; |
| 539 | } |
| 540 | } |
| 541 | |
| 542 | export async function getControlPlaneSessionInfo( |
| 543 | silent: boolean, |
| 544 | useOnboarding: boolean, |
| 545 | ): Promise<ControlPlaneSessionInfo | undefined> { |
| 546 | if (!isHubEnv(controlPlaneEnv)) { |
| 547 | return { |
| 548 | AUTH_TYPE: AuthType.OnPrem, |
| 549 | }; |
| 550 | } |
| 551 | |
| 552 | try { |
| 553 | if (useOnboarding) { |
| 554 | WorkOsAuthProvider.useOnboardingUri = true; |
| 555 | } |
| 556 | |
| 557 | const session = await authentication.getSession( |
| 558 | controlPlaneEnv.AUTH_TYPE, |
| 559 | [], |
| 560 | silent ? { silent: true } : { createIfNone: true }, |
| 561 | ); |
| 562 | if (!session) { |
| 563 | return undefined; |
| 564 | } |
| 565 | return { |
| 566 | AUTH_TYPE: controlPlaneEnv.AUTH_TYPE, |
| 567 | accessToken: session.accessToken, |
| 568 | account: { |
| 569 | id: session.account.id, |
| 570 | label: session.account.label, |
| 571 | }, |
| 572 | }; |
| 573 | } finally { |
| 574 | WorkOsAuthProvider.useOnboardingUri = false; |
| 575 | } |
| 576 | } |