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