Elffuss BraidHub

kikocis/continue public

04e94bf72239 · 15.4 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 await this._refreshSessions();
187 } catch (e) {
188 console.error(`Error refreshing sessions: ${e}`);
189 }
190 }
191
192 private async _refreshSessions(): Promise<void> {
193 const sessions = await this.getSessions();
194 if (!sessions.length) {
195 return;
196 }
197
198 const finalSessions = [];
199 for (const session of sessions) {
200 try {
201 // For expired tokens, don't use retries - if refresh fails, we drop the session
202 const refreshMethod = this.jwtIsExpiredOrInvalid(session.accessToken)
203 ? this._refreshSession.bind(this) // Direct refresh for expired tokens
204 : this._refreshSessionWithRetry.bind(this); // Retry for valid tokens
205
206 const newSession = await refreshMethod(session.refreshToken);
207 finalSessions.push({
208 ...session,
209 accessToken: newSession.accessToken,
210 refreshToken: newSession.refreshToken,
211 expiresInMs: newSession.expiresInMs,
212 });
213 } catch (e: any) {
214 // If refresh fails (after retries for valid tokens), drop the session
215 console.debug(`Error refreshing session token: ${e.message}`);
216 this._sessionChangeEmitter.fire({
217 added: [],
218 removed: [session],
219 changed: [],
220 });
221 }
222 }
223
224 await this.storeSessions(finalSessions);
225 this._sessionChangeEmitter.fire({
226 added: [],
227 removed: [],
228 changed: finalSessions,
229 });
230 }
231
232 private async _refreshSessionWithRetry(
233 refreshToken: string,
234 attempt = 1,
235 maxAttempts = 3,
236 baseDelay = 1000,
237 ): Promise<{
238 accessToken: string;
239 refreshToken: string;
240 expiresInMs: number;
241 }> {
242 try {
243 return await this._refreshSession(refreshToken);
244 } catch (error: any) {
245 // Don't retry for auth errors (401 Unauthorized) or if we've reached max attempts
246 if (
247 error.message?.includes("401") ||
248 error.message?.includes("Invalid refresh token") ||
249 error.message?.includes("Unauthorized") ||
250 attempt >= maxAttempts
251 ) {
252 throw error;
253 }
254
255 // For network errors or transient server issues, retry with backoff
256 // Calculate exponential backoff delay with jitter
257 const delay =
258 baseDelay * Math.pow(2, attempt - 1) * (0.5 + Math.random() * 0.5);
259
260 // Schedule retry after delay
261 return new Promise((resolve, reject) => {
262 setTimeout(() => {
263 this._refreshSessionWithRetry(
264 refreshToken,
265 attempt + 1,
266 maxAttempts,
267 baseDelay,
268 )
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 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
542export 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}