Elffuss BraidHub

kikocis/continue public

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