Elffuss BraidHub

kikocis/continue public

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