Elffuss BraidHub

kikocis/continue public

f96bfd141fb6 · 14.3 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
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 = `/auth/${env.uriScheme}-redirect`;
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 screen_hint: WorkOsAuthProvider.useOnboardingUri
397 ? "sign-up"
398 : "sign-in",
399 };
400
401 Object.keys(params).forEach((key) =>
402 url.searchParams.append(key, params[key as keyof typeof params]),
403 );
404
405 const oauthUrl = url;
406 if (oauthUrl) {
407 await env.openExternal(Uri.parse(oauthUrl.toString()));
408 } else {
409 return;
410 }
411
412 let codeExchangePromise = this._codeExchangePromises.get(scopeString);
413 if (!codeExchangePromise) {
414 codeExchangePromise = promiseFromEvent(
415 this._uriHandler.event,
416 this.handleUri(scopes),
417 );
418 this._codeExchangePromises.set(scopeString, codeExchangePromise);
419 }
420
421 try {
422 return await Promise.race([
423 codeExchangePromise.promise,
424 new Promise<string>(
425 (_, reject) =>
426 setTimeout(() => reject("Cancelled"), 60 * 60 * 1_000), // 60min timeout
427 ),
428 promiseFromEvent<any, any>(
429 token.onCancellationRequested,
430 (_, __, reject) => {
431 reject("User Cancelled");
432 },
433 ).promise,
434 ]);
435 } finally {
436 this._pendingStates = this._pendingStates.filter(
437 (n) => n !== stateId,
438 );
439 codeExchangePromise?.cancel.fire();
440 this._codeExchangePromises.delete(scopeString);
441 }
442 },
443 );
444 }
445
446 /**
447 * Handle the redirect to VS Code (after sign in from Continue)
448 * @param scopes
449 * @returns
450 */
451 private handleUri: (
452 scopes: readonly string[],
453 ) => PromiseAdapter<Uri, string> =
454 (scopes) => async (uri, resolve, reject) => {
455 const query = new URLSearchParams(uri.query);
456 const access_token = query.get("code");
457 const state = query.get("state");
458
459 if (!access_token) {
460 reject(new Error("No token"));
461 return;
462 }
463 if (!state) {
464 reject(new Error("No state"));
465 return;
466 }
467
468 // Check if it is a valid auth request started by the extension
469 if (!this._pendingStates.some((n) => n === state)) {
470 reject(new Error("State not found"));
471 return;
472 }
473
474 resolve(access_token);
475 };
476
477 /**
478 * Get the user info from WorkOS
479 * @param token
480 * @returns
481 */
482 private async getUserInfo(
483 token: string,
484 codeVerifier: string,
485 hubEnv: HubEnv,
486 ) {
487 const resp = await fetch(
488 "https://api.workos.com/user_management/authenticate",
489 {
490 method: "POST",
491 headers: {
492 "Content-Type": "application/json",
493 },
494 body: JSON.stringify({
495 client_id: hubEnv.WORKOS_CLIENT_ID,
496 code_verifier: codeVerifier,
497 grant_type: "authorization_code",
498 code: token,
499 }),
500 },
501 );
502 const text = await resp.text();
503 const data = JSON.parse(text);
504 return data;
505 }
506}
507
508export async function getControlPlaneSessionInfo(
509 silent: boolean,
510 useOnboarding: boolean,
511): Promise<ControlPlaneSessionInfo | undefined> {
512 if (!isHubEnv(controlPlaneEnv)) {
513 return {
514 AUTH_TYPE: AuthType.OnPrem,
515 };
516 }
517
518 try {
519 if (useOnboarding) {
520 WorkOsAuthProvider.useOnboardingUri = true;
521 }
522
523 const session = await authentication.getSession(
524 controlPlaneEnv.AUTH_TYPE,
525 [],
526 silent ? { silent: true } : { createIfNone: true },
527 );
528 if (!session) {
529 return undefined;
530 }
531 return {
532 AUTH_TYPE: controlPlaneEnv.AUTH_TYPE,
533 accessToken: session.accessToken,
534 account: {
535 id: session.account.id,
536 label: session.account.label,
537 },
538 };
539 } finally {
540 WorkOsAuthProvider.useOnboardingUri = false;
541 }
542}