Elffuss BraidHub

kikocis/continue public

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