Elffuss BraidHub

kikocis/continue public

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