Elffuss BraidHub

kikocis/continue public

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