Elffuss BraidHub

kikocis/continue public

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