Elffuss BraidHub

kikocis/continue public

9d5865e0e05b · 19.4 KiBRawPermalink
1import * as fs from "fs";
2import * as path from "path";
3
4import chalk from "chalk";
5// Polyfill fetch for Node < 18
6import nodeFetch from "node-fetch";
7import open from "open";
8
9import { getApiClient } from "../config.js";
10import { env } from "../env.js";
11if (!globalThis.fetch) {
12 globalThis.fetch = nodeFetch as unknown as typeof globalThis.fetch;
13}
14
15// Config file path
16const AUTH_CONFIG_PATH = path.join(env.continueHome, "auth.json");
17
18// Represents an authenticated user's configuration
19export interface AuthenticatedConfig {
20 userId: string;
21 userEmail: string;
22 accessToken: string;
23 refreshToken: string;
24 expiresAt: number;
25 organizationId: string | null; // null means personal organization
26 configUri?: string; // Optional config URI (file:// or slug://owner/slug)
27 modelName?: string; // Name of the selected model
28}
29
30// Represents configuration when using environment variable auth
31export interface EnvironmentAuthConfig {
32 /**
33 * This userId?: undefined; field a trick to help TypeScript differentiate between
34 * AuthenticatedConfig and EnvironmentAuthConfig. Otherwise AuthenticatedConfig is
35 * a possible subtype of EnvironmentAuthConfig and TypeScript gets confused where
36 * type guards are involved.
37 */
38 userId?: undefined;
39 accessToken: string;
40 organizationId: string | null; // Can be set via --org flag in headless mode
41 configUri?: string; // Optional config URI (file:// or slug://owner/slug)
42 modelName?: string; // Name of the selected model
43}
44
45// Union type representing the possible authentication states
46export type AuthConfig = AuthenticatedConfig | EnvironmentAuthConfig | null;
47
48/**
49 * Type guard to check if config is authenticated via file-based auth
50 */
51export function isAuthenticatedConfig(
52 config: AuthConfig,
53): config is AuthenticatedConfig {
54 return config !== null && "userId" in config;
55}
56
57/**
58 * Type guard to check if config is authenticated via environment variable
59 */
60export function isEnvironmentAuthConfig(
61 config: AuthConfig,
62): config is EnvironmentAuthConfig {
63 return config !== null && !("userId" in config);
64}
65
66/**
67 * Gets the access token from any auth config type
68 */
69export function getAccessToken(config: AuthConfig): string | null {
70 if (config === null) return null;
71 return config.accessToken;
72}
73
74/**
75 * Gets the organization ID from any auth config type
76 */
77export function getOrganizationId(config: AuthConfig): string | null {
78 if (config === null) return null;
79 return config.organizationId;
80}
81
82/**
83 * Gets the config URI from any auth config type
84 */
85export function getConfigUri(config: AuthConfig): string | null {
86 if (config === null) return null;
87 return config.configUri || null;
88}
89
90/**
91 * Gets the model name from any auth config type
92 */
93export function getModelName(config: AuthConfig): string | null {
94 if (config === null) return null;
95 return config.modelName || null;
96}
97
98// URI utility functions have been moved to ./uriUtils.ts
99import { pathToUri, slugToUri, uriToPath, uriToSlug } from "./uriUtils.js";
100import {
101 autoSelectOrganization,
102 createUpdatedAuthConfig,
103 handleCliOrgForAuthenticatedConfig,
104 handleCliOrgForEnvironmentAuth,
105} from "./workos.helpers.js";
106
107/**
108 * Legacy functions for backward compatibility
109 */
110export function getAssistantSlug(config: AuthConfig): string | null {
111 const uri = getConfigUri(config);
112 return uri ? uriToSlug(uri) : null;
113}
114
115export function getLocalConfigPath(config: AuthConfig): string | null {
116 const uri = getConfigUri(config);
117 return uri ? uriToPath(uri) : null;
118}
119
120/**
121 * Loads the authentication configuration from disk
122 */
123export function loadAuthConfig(): AuthConfig {
124 // If CONTINUE_API_KEY environment variable exists, use that instead
125 if (process.env.CONTINUE_API_KEY) {
126 return {
127 accessToken: process.env.CONTINUE_API_KEY,
128 organizationId: null,
129 };
130 }
131
132 try {
133 if (fs.existsSync(AUTH_CONFIG_PATH)) {
134 const data = JSON.parse(fs.readFileSync(AUTH_CONFIG_PATH, "utf8"));
135
136 // Validate that we have all required fields for authenticated config
137 if (
138 data.userId &&
139 data.userEmail &&
140 data.accessToken &&
141 data.refreshToken &&
142 data.expiresAt
143 ) {
144 return {
145 userId: data.userId,
146 userEmail: data.userEmail,
147 accessToken: data.accessToken,
148 refreshToken: data.refreshToken,
149 expiresAt: data.expiresAt,
150 organizationId: data.organizationId || null,
151 configUri: data.configUri,
152 modelName: data.modelName,
153 };
154 } else {
155 console.warn("Invalid auth config found, ignoring.");
156 return null;
157 }
158 }
159 } catch (error) {
160 console.error(`Error loading auth config: ${error}`);
161 }
162
163 return null;
164}
165
166/**
167 * Saves the authentication configuration to disk
168 */
169export function saveAuthConfig(config: AuthenticatedConfig): void {
170 // If using CONTINUE_API_KEY environment variable, don't save anything
171 if (process.env.CONTINUE_API_KEY) {
172 return;
173 }
174
175 try {
176 // Make sure the directory exists
177 const dir = path.dirname(AUTH_CONFIG_PATH);
178 if (!fs.existsSync(dir)) {
179 fs.mkdirSync(dir, { recursive: true });
180 }
181
182 fs.writeFileSync(AUTH_CONFIG_PATH, JSON.stringify(config, null, 2));
183 } catch (error) {
184 console.error(`Error saving auth config: ${error}`);
185 }
186}
187
188/**
189 * Updates the config URI in the authentication configuration
190 */
191export function updateConfigUri(configUri: string | null): void {
192 // If using CONTINUE_API_KEY environment variable, don't save anything
193 if (process.env.CONTINUE_API_KEY) {
194 return;
195 }
196
197 const config = loadAuthConfig();
198 if (config && isAuthenticatedConfig(config)) {
199 const updatedConfig: AuthenticatedConfig = {
200 ...config,
201 configUri: configUri || undefined,
202 };
203 saveAuthConfig(updatedConfig);
204 }
205}
206
207/**
208 * Updates the model name in the authentication configuration
209 */
210export function updateModelName(modelName: string | null): void {
211 // If using CONTINUE_API_KEY environment variable, don't save anything
212 if (process.env.CONTINUE_API_KEY) {
213 return;
214 }
215
216 const config = loadAuthConfig();
217 if (config && isAuthenticatedConfig(config)) {
218 const updatedConfig: AuthenticatedConfig = {
219 ...config,
220 modelName: modelName || undefined,
221 };
222 saveAuthConfig(updatedConfig);
223 }
224}
225
226/**
227 * Legacy functions for backward compatibility
228 */
229export function updateAssistantSlug(assistantSlug: string | null): void {
230 updateConfigUri(assistantSlug ? slugToUri(assistantSlug) : null);
231}
232
233export function updateLocalConfigPath(localConfigPath: string | null): void {
234 updateConfigUri(localConfigPath ? pathToUri(localConfigPath) : null);
235}
236
237/**
238 * Checks if the user is authenticated and the token is valid
239 */
240export function isAuthenticated(): boolean {
241 const config = loadAuthConfig();
242
243 if (config === null) {
244 return false;
245 }
246
247 // Environment auth is always valid
248 if (isEnvironmentAuthConfig(config)) {
249 return true;
250 }
251
252 /**
253 * THIS CODE DOESN'T WORK.
254 * .catch() will never return in a non-async function.
255 * It's a hallucination.
256 **/
257 if (Date.now() > config.expiresAt) {
258 // Try refreshing the token
259 refreshToken(config.refreshToken).catch(() => {
260 // If refresh fails, we're not authenticated
261 return false;
262 });
263 }
264
265 return true;
266}
267
268/**
269 * Device authorization response from WorkOS
270 */
271interface DeviceAuthorizationResponse {
272 device_code: string;
273 user_code: string;
274 verification_uri: string;
275 verification_uri_complete: string;
276 expires_in: number;
277 interval: number;
278}
279
280/**
281 * Request device authorization from WorkOS
282 */
283async function requestDeviceAuthorization(): Promise<DeviceAuthorizationResponse> {
284 try {
285 const params = new URLSearchParams({
286 client_id: env.workOsClientId,
287 screen_hint: "sign-up",
288 });
289
290 // Use WorkOS User Management device authorization endpoint
291 const response = await fetch(
292 "https://api.workos.com/user_management/authorize/device",
293 {
294 method: "POST",
295 headers: {
296 "Content-Type": "application/x-www-form-urlencoded",
297 },
298 body: params,
299 },
300 );
301
302 if (!response.ok) {
303 throw new Error(`HTTP ${response.status}: ${response.statusText}`);
304 }
305
306 return await response.json();
307 } catch (error: any) {
308 console.error(
309 chalk.red("Device authorization error:"),
310 error.message || error,
311 );
312 throw error;
313 }
314}
315
316/**
317 * Poll for device authorization completion
318 */
319async function pollForDeviceToken(
320 deviceCode: string,
321 interval: number,
322 expiresIn: number,
323): Promise<AuthenticatedConfig> {
324 const startTime = Date.now();
325 const expirationTime = startTime + expiresIn * 1000;
326 let currentInterval = interval;
327
328 while (Date.now() < expirationTime) {
329 try {
330 const params = new URLSearchParams({
331 grant_type: "urn:ietf:params:oauth:grant-type:device_code",
332 device_code: deviceCode,
333 client_id: env.workOsClientId,
334 });
335
336 const headers: Record<string, string> = {
337 "Content-Type": "application/x-www-form-urlencoded",
338 };
339
340 // Poll WorkOS User Management token endpoint
341 const response = await fetch(
342 "https://api.workos.com/user_management/authenticate",
343 {
344 method: "POST",
345 headers,
346 body: params,
347 },
348 );
349
350 if (response.ok) {
351 const data = await response.json();
352 const { access_token, refresh_token, user } = data;
353
354 // Calculate token expiration (assuming 1 hour validity)
355 const tokenExpiresAt = Date.now() + 60 * 60 * 1000;
356
357 const authConfig: AuthenticatedConfig = {
358 userId: user.id,
359 userEmail: user.email,
360 accessToken: access_token,
361 refreshToken: refresh_token,
362 expiresAt: tokenExpiresAt,
363 organizationId: null,
364 };
365
366 // Save the config
367 saveAuthConfig(authConfig);
368
369 return authConfig;
370 } else {
371 // Handle HTTP error responses
372 const errorData = await response.json().catch(() => ({}));
373 const errorCode = errorData.error;
374
375 // Log response details for debugging
376 if (response.status === 401) {
377 throw new Error(
378 "Oops! We had trouble authenticating. Please try again and reach out if the error persists.",
379 );
380 }
381
382 if (errorCode === "authorization_pending") {
383 // Continue polling
384 await new Promise((resolve) =>
385 setTimeout(resolve, currentInterval * 1000),
386 );
387 continue;
388 } else if (errorCode === "slow_down") {
389 // Increase polling interval
390 currentInterval += 5;
391 await new Promise((resolve) =>
392 setTimeout(resolve, currentInterval * 1000),
393 );
394 continue;
395 } else if (errorCode === "access_denied") {
396 throw new Error("User denied access");
397 } else if (errorCode === "expired_token") {
398 throw new Error("Device code has expired");
399 } else {
400 throw new Error(`HTTP ${response.status}: ${response.statusText}`);
401 }
402 }
403 } catch (error: any) {
404 console.error(chalk.red("Token polling error:"), error.message || error);
405 throw error;
406 }
407 }
408
409 throw new Error("Device authorization timeout");
410}
411
412/**
413 * Refreshes the access token using a refresh token
414 */
415async function refreshToken(
416 refreshToken: string,
417): Promise<AuthenticatedConfig> {
418 try {
419 // Load existing config to preserve organizationId and other fields
420 const existingConfig = loadAuthConfig();
421
422 const response = await fetch(new URL("auth/refresh", env.apiBase), {
423 method: "POST",
424 headers: {
425 "Content-Type": "application/json",
426 },
427 body: JSON.stringify({
428 refreshToken,
429 }),
430 });
431
432 if (!response.ok) {
433 throw new Error(`HTTP ${response.status}: ${response.statusText}`);
434 }
435
436 const data = await response.json();
437 const { accessToken, refreshToken: newRefreshToken, user } = data;
438
439 // Calculate token expiration (assuming 1 hour validity)
440 const tokenExpiresAt = Date.now() + 60 * 60 * 1000;
441
442 const authConfig: AuthenticatedConfig = {
443 userId: user.id,
444 userEmail: user.email,
445 accessToken,
446 refreshToken: newRefreshToken,
447 expiresAt: tokenExpiresAt,
448 // Preserve existing organizationId if it exists, otherwise set to null
449 organizationId: isAuthenticatedConfig(existingConfig)
450 ? existingConfig.organizationId
451 : null,
452 // Preserve existing configUri if it exists
453 configUri: isAuthenticatedConfig(existingConfig)
454 ? existingConfig.configUri
455 : undefined,
456 // Preserve existing modelName if it exists
457 modelName: isAuthenticatedConfig(existingConfig)
458 ? existingConfig.modelName
459 : undefined,
460 };
461
462 // Save the config
463 saveAuthConfig(authConfig);
464
465 return authConfig;
466 } catch (error: any) {
467 console.error(chalk.red("Token refresh error:"), error.message || error);
468 throw error;
469 }
470}
471
472/**
473 * Authenticates using the WorkOS device flow
474 */
475export async function login(): Promise<AuthConfig> {
476 // If CONTINUE_API_KEY environment variable exists, use that instead
477 if (process.env.CONTINUE_API_KEY) {
478 console.info(
479 chalk.green("Using CONTINUE_API_KEY from environment variables"),
480 );
481 return {
482 accessToken: process.env.CONTINUE_API_KEY,
483 organizationId: null,
484 };
485 }
486
487 console.info(chalk.white("\nSigning in with Continue..."));
488
489 // Request device authorization
490 const deviceAuth = await requestDeviceAuthorization();
491
492 console.info(
493 chalk.white(
494 `Your authentication code: ${chalk.bold(deviceAuth.user_code)}`,
495 ),
496 );
497 console.info(
498 chalk.dim(
499 `If the browser doesn't automatically open, use this link: ${deviceAuth.verification_uri_complete}`,
500 ),
501 );
502
503 // Try to open the complete verification URL in browser
504 try {
505 await open(deviceAuth.verification_uri_complete);
506 } catch {
507 console.info(chalk.yellow("Unable to open browser automatically"));
508 }
509
510 console.info(chalk.dim("\nWaiting for confirmation..."));
511
512 // Poll for token
513 const authConfig = await pollForDeviceToken(
514 deviceAuth.device_code,
515 deviceAuth.interval,
516 deviceAuth.expires_in,
517 );
518
519 console.info(chalk.white("✅ Success!"));
520
521 return authConfig;
522}
523
524/**
525 * Ensures the user has selected an organization, automatically selecting the first one if available
526 */
527export async function ensureOrganization(
528 authConfig: AuthConfig,
529 isHeadless: boolean = false,
530 cliOrganizationSlug?: string,
531): Promise<AuthConfig> {
532 // Handle CLI organization slug if provided (undefined means no --org flag or --org personal)
533 if (cliOrganizationSlug) {
534 // For environment auth configs
535 if (isEnvironmentAuthConfig(authConfig)) {
536 return handleCliOrgForEnvironmentAuth(
537 authConfig,
538 cliOrganizationSlug,
539 isHeadless,
540 );
541 }
542 } else if (isEnvironmentAuthConfig(authConfig)) {
543 // No CLI organization slug (or "personal" was specified)
544 // If using API key auth, attempt to resolve its organization scope once
545 const resolved = await resolveOrgScopeForApiKey(authConfig);
546 return resolved;
547 }
548
549 // If not authenticated, return as-is
550 if (!isAuthenticatedConfig(authConfig)) {
551 return authConfig;
552 }
553
554 // TypeScript now knows authConfig is AuthenticatedConfig
555 const authenticatedConfig: AuthenticatedConfig = authConfig;
556
557 // If a CLI organization slug is provided, try to use it (for authenticated configs)
558 if (cliOrganizationSlug) {
559 return handleCliOrgForAuthenticatedConfig(
560 authenticatedConfig,
561 cliOrganizationSlug,
562 isHeadless,
563 );
564 }
565
566 // If already have organization ID (including null for personal), return as-is
567 if (authenticatedConfig.organizationId !== undefined) {
568 return authenticatedConfig;
569 }
570
571 // In headless mode, default to personal organization if none saved
572 if (isHeadless) {
573 const updatedConfig = createUpdatedAuthConfig(authenticatedConfig, null);
574 saveAuthConfig(updatedConfig);
575 return updatedConfig;
576 }
577
578 // Need to select organization
579 return autoSelectOrganization(authenticatedConfig);
580}
581
582/**
583 * Attempts to resolve the organization scope for API key auth (environment-based auth).
584 * Calls a lightweight backend endpoint to determine if the API key is an org-scoped key.
585 * If successful, returns a new EnvironmentAuthConfig with organizationId set; otherwise returns the original config.
586 */
587async function resolveOrgScopeForApiKey(
588 envConfig: EnvironmentAuthConfig,
589): Promise<EnvironmentAuthConfig> {
590 // If already set (including explicit null), return as-is
591 if (envConfig.organizationId !== null) {
592 return envConfig;
593 }
594
595 const accessToken = envConfig.accessToken;
596 if (!accessToken) return envConfig;
597
598 try {
599 // Prefer a dedicated endpoint for scope discovery. This should return JSON like:
600 // { organizationId: string | null } (aka orgScopeId)
601 const url = new URL("auth/scope", env.apiBase);
602 const resp = await fetch(url, {
603 method: "GET",
604 headers: {
605 Authorization: `Bearer ${accessToken}`,
606 "Content-Type": "application/json",
607 },
608 });
609
610 if (!resp.ok) {
611 // Gracefully ignore if the endpoint isn't available yet (e.g., 404) or other non-2xx errors
612 return envConfig;
613 }
614
615 const data: any = await resp.json().catch(() => ({}));
616 const orgId =
617 data?.organizationId ??
618 data?.orgScopeId ??
619 data?.organization?.id ??
620 null;
621
622 if (orgId && typeof orgId === "string") {
623 return {
624 ...envConfig,
625 organizationId: orgId,
626 };
627 }
628 } catch {
629 // Network or parsing issues: leave config unchanged
630 }
631
632 return envConfig;
633}
634
635/**
636 * Gets the list of available organizations for the user
637 */
638export async function listUserOrganizations(): Promise<
639 { id: string; name: string; slug: string }[] | null
640> {
641 const authConfig = loadAuthConfig();
642
643 // If using CONTINUE_API_KEY environment variable, organization switching is not supported
644 if (isEnvironmentAuthConfig(authConfig)) {
645 return null;
646 }
647
648 if (!isAuthenticatedConfig(authConfig)) {
649 return null;
650 }
651
652 const apiClient = getApiClient(authConfig.accessToken);
653
654 try {
655 const resp = await apiClient.listOrganizations();
656 // Map the organizations to include slug field
657 return (
658 resp.organizations?.map((org) => ({
659 id: org.id,
660 name: org.name,
661 slug: org.slug,
662 })) || []
663 );
664 } catch {
665 return null;
666 }
667}
668
669/**
670 * Checks if the user has multiple organizations available
671 */
672export async function hasMultipleOrganizations(): Promise<boolean> {
673 const organizations = await listUserOrganizations();
674 // Has multiple organizations if there's at least one organization (plus personal)
675 return organizations !== null && organizations.length > 0;
676}
677
678/**
679 * Logs the user out by clearing saved credentials
680 */
681export function logout(): void {
682 const onboardingFlagPath = path.join(
683 env.continueHome,
684 ".onboarding_complete",
685 );
686
687 // Remove onboarding completion flag so user will go through onboarding again
688 if (fs.existsSync(onboardingFlagPath)) {
689 fs.unlinkSync(onboardingFlagPath);
690 }
691
692 if (process.env.CONTINUE_API_KEY) {
693 console.info(
694 chalk.yellow(
695 "Using CONTINUE_API_KEY from environment variables, nothing to log out",
696 ),
697 );
698 return;
699 }
700
701 if (fs.existsSync(AUTH_CONFIG_PATH)) {
702 fs.unlinkSync(AUTH_CONFIG_PATH);
703 console.info(chalk.green("Successfully logged out"));
704 } else {
705 console.info(chalk.yellow("No active session found"));
706 }
707}