Elffuss BraidHub

kikocis/continue public

3389e73db7c2 · 15.2 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 void this.refreshSessions();
104
105 // Set up a regular interval to refresh tokens
106 this._refreshInterval = setInterval(() => {
107 void 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 const newSession = await this._refreshSessionWithRetry(
202 session.refreshToken,
203 );
204 finalSessions.push({
205 ...session,
206 accessToken: newSession.accessToken,
207 refreshToken: newSession.refreshToken,
208 expiresInMs: newSession.expiresInMs,
209 });
210 } catch (e: any) {
211 // If refresh fails (after retries for valid tokens), drop the session
212 console.debug(`Error refreshing session token: ${e.message}`);
213 this._sessionChangeEmitter.fire({
214 added: [],
215 removed: [session],
216 changed: [],
217 });
218 }
219 }
220
221 await this.storeSessions(finalSessions);
222 this._sessionChangeEmitter.fire({
223 added: [],
224 removed: [],
225 changed: finalSessions,
226 });
227 }
228
229 private async _refreshSessionWithRetry(
230 refreshToken: string,
231 attempt = 1,
232 maxAttempts = 3,
233 baseDelay = 1000,
234 ): Promise<{
235 accessToken: string;
236 refreshToken: string;
237 expiresInMs: number;
238 }> {
239 try {
240 return await this._refreshSession(refreshToken);
241 } catch (error: any) {
242 // Don't retry for auth errors (401 Unauthorized) or if we've reached max attempts
243 if (
244 error.message?.includes("401") ||
245 error.message?.includes("Invalid refresh token") ||
246 error.message?.includes("Unauthorized") ||
247 attempt >= maxAttempts
248 ) {
249 throw error;
250 }
251
252 // For network errors or transient server issues, retry with backoff
253 // Calculate exponential backoff delay with jitter
254 const delay =
255 baseDelay * Math.pow(2, attempt - 1) * (0.5 + Math.random() * 0.5);
256
257 // Schedule retry after delay
258 return new Promise((resolve, reject) => {
259 setTimeout(() => {
260 this._refreshSessionWithRetry(
261 refreshToken,
262 attempt + 1,
263 maxAttempts,
264 baseDelay,
265 )
266 .then(resolve)
267 .catch(reject);
268 }, delay);
269 });
270 }
271 }
272
273 private async _refreshSession(refreshToken: string): Promise<{
274 accessToken: string;
275 refreshToken: string;
276 expiresInMs: number;
277 }> {
278 const response = await fetch(
279 new URL("/auth/refresh", controlPlaneEnv.CONTROL_PLANE_URL),
280 {
281 method: "POST",
282 headers: {
283 "Content-Type": "application/json",
284 },
285 body: JSON.stringify({
286 refreshToken,
287 }),
288 },
289 );
290 if (!response.ok) {
291 const text = await response.text();
292 throw new Error("Error refreshing token: " + text);
293 }
294 const data = (await response.json()) as any;
295 return {
296 accessToken: data.accessToken,
297 refreshToken: data.refreshToken,
298 expiresInMs: this.getExpirationTimeMs(data.accessToken),
299 };
300 }
301
302 private _formatProfileLabel(
303 firstName: string | null,
304 lastName: string | null,
305 ) {
306 return ((firstName ?? "") + " " + (lastName ?? "")).trim();
307 }
308
309 /**
310 * Create a new auth session
311 * @param scopes
312 * @returns
313 */
314 public async createSession(
315 scopes: string[],
316 ): Promise<ContinueAuthenticationSession> {
317 try {
318 const codeVerifier = generateRandomString(64);
319 const codeChallenge = await generateCodeChallenge(codeVerifier);
320
321 if (!isHubEnv(controlPlaneEnv)) {
322 throw new Error("Login is disabled");
323 }
324
325 const token = await this.login(codeChallenge, controlPlaneEnv, scopes);
326 if (!token) {
327 throw new Error(`Continue login failure`);
328 }
329
330 const userInfo = (await this.getUserInfo(
331 token,
332 codeVerifier,
333 controlPlaneEnv,
334 )) as any;
335 const { user, access_token, refresh_token } = userInfo;
336
337 const session: ContinueAuthenticationSession = {
338 id: uuidv4(),
339 accessToken: access_token,
340 refreshToken: refresh_token,
341 expiresInMs: this.getExpirationTimeMs(access_token),
342 loginNeeded: false,
343 account: {
344 label: this._formatProfileLabel(user.first_name, user.last_name),
345 id: user.email,
346 },
347 scopes: [],
348 };
349
350 await this.storeSessions([session]);
351
352 this._sessionChangeEmitter.fire({
353 added: [session],
354 removed: [],
355 changed: [],
356 });
357
358 return session;
359 } catch (e) {
360 window.showErrorMessage(`Sign in failed: ${e}`);
361 throw e;
362 }
363 }
364
365 /**
366 * Remove an existing session
367 * @param sessionId
368 */
369 public async removeSession(sessionId: string): Promise<void> {
370 const sessions = await this.getSessions();
371 const sessionIdx = sessions.findIndex((s) => s.id === sessionId);
372 const session = sessions[sessionIdx];
373 sessions.splice(sessionIdx, 1);
374
375 await this.storeSessions(sessions);
376
377 if (session) {
378 this._sessionChangeEmitter.fire({
379 added: [],
380 removed: [session],
381 changed: [],
382 });
383 }
384 }
385
386 /**
387 * Dispose the registered services
388 */
389 public async dispose() {
390 if (this._refreshInterval) {
391 clearInterval(this._refreshInterval);
392 this._refreshInterval = null;
393 }
394 this._disposable.dispose();
395 }
396
397 /**
398 * Log in to Continue
399 */
400 private async login(
401 codeChallenge: string,
402 hubEnv: HubEnv,
403 scopes: string[] = [],
404 ) {
405 return await window.withProgress<string>(
406 {
407 location: ProgressLocation.Notification,
408 title: "Signing in to Continue...",
409 cancellable: true,
410 },
411 async (_, token) => {
412 const stateId = uuidv4();
413
414 this._pendingStates.push(stateId);
415
416 const scopeString = scopes.join(" ");
417
418 const url = new URL("https://api.workos.com/user_management/authorize");
419 const params = {
420 response_type: "code",
421 client_id: hubEnv.WORKOS_CLIENT_ID,
422 redirect_uri: this.redirectUri,
423 state: stateId,
424 code_challenge: codeChallenge,
425 code_challenge_method: "S256",
426 provider: "authkit",
427 screen_hint: WorkOsAuthProvider.useOnboardingUri
428 ? "sign-up"
429 : "sign-in",
430 };
431
432 Object.keys(params).forEach((key) =>
433 url.searchParams.append(key, params[key as keyof typeof params]),
434 );
435
436 const oauthUrl = url;
437 if (oauthUrl) {
438 await env.openExternal(Uri.parse(oauthUrl.toString()));
439 } else {
440 return;
441 }
442
443 let codeExchangePromise = this._codeExchangePromises.get(scopeString);
444 if (!codeExchangePromise) {
445 codeExchangePromise = promiseFromEvent(
446 this._uriHandler.event,
447 this.handleUri(scopes),
448 );
449 this._codeExchangePromises.set(scopeString, codeExchangePromise);
450 }
451
452 try {
453 return await Promise.race([
454 codeExchangePromise.promise,
455 new Promise<string>(
456 (_, reject) =>
457 setTimeout(() => reject("Cancelled"), 60 * 60 * 1_000), // 60min timeout
458 ),
459 promiseFromEvent<any, any>(
460 token.onCancellationRequested,
461 (_, __, reject) => {
462 reject("User Cancelled");
463 },
464 ).promise,
465 ]);
466 } finally {
467 this._pendingStates = this._pendingStates.filter(
468 (n) => n !== stateId,
469 );
470 codeExchangePromise?.cancel.fire();
471 this._codeExchangePromises.delete(scopeString);
472 }
473 },
474 );
475 }
476
477 /**
478 * Handle the redirect to VS Code (after sign in from Continue)
479 * @param scopes
480 * @returns
481 */
482 private handleUri: (
483 scopes: readonly string[],
484 ) => PromiseAdapter<Uri, string> =
485 (scopes) => async (uri, resolve, reject) => {
486 const query = new URLSearchParams(uri.query);
487 const access_token = query.get("code");
488 const state = query.get("state");
489
490 if (!access_token) {
491 reject(new Error("No token"));
492 return;
493 }
494 if (!state) {
495 reject(new Error("No state"));
496 return;
497 }
498
499 // Check if it is a valid auth request started by the extension
500 if (!this._pendingStates.some((n) => n === state)) {
501 reject(new Error("State not found"));
502 return;
503 }
504
505 resolve(access_token);
506 };
507
508 /**
509 * Get the user info from WorkOS
510 * @param token
511 * @returns
512 */
513 private async getUserInfo(
514 token: string,
515 codeVerifier: string,
516 hubEnv: HubEnv,
517 ) {
518 const resp = await fetch(
519 "https://api.workos.com/user_management/authenticate",
520 {
521 method: "POST",
522 headers: {
523 "Content-Type": "application/json",
524 },
525 body: JSON.stringify({
526 client_id: hubEnv.WORKOS_CLIENT_ID,
527 code_verifier: codeVerifier,
528 grant_type: "authorization_code",
529 code: token,
530 }),
531 },
532 );
533 const text = await resp.text();
534 const data = JSON.parse(text);
535 return data;
536 }
537}
538
539export async function getControlPlaneSessionInfo(
540 silent: boolean,
541 useOnboarding: boolean,
542): Promise<ControlPlaneSessionInfo | undefined> {
543 if (!isHubEnv(controlPlaneEnv)) {
544 return {
545 AUTH_TYPE: AuthType.OnPrem,
546 };
547 }
548
549 try {
550 if (useOnboarding) {
551 WorkOsAuthProvider.useOnboardingUri = true;
552 }
553
554 const session = await authentication.getSession(
555 controlPlaneEnv.AUTH_TYPE,
556 [],
557 silent ? { silent: true } : { createIfNone: true },
558 );
559 if (!session) {
560 return undefined;
561 }
562 return {
563 AUTH_TYPE: controlPlaneEnv.AUTH_TYPE,
564 accessToken: session.accessToken,
565 account: {
566 id: session.account.id,
567 label: session.account.label,
568 },
569 };
570 } finally {
571 WorkOsAuthProvider.useOnboardingUri = false;
572 }
573}