All files / src config.ts

36.06% Statements 145/402
61.11% Branches 22/36
48.27% Functions 14/29
36.06% Lines 145/402

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 6201x 1x 1x 1x 1x           1x 1x 1x 1x       1x   1x   1x 6x 6x 6x 6x 1x 1x 1x 1x 1x 6x 1x 1x 4x 4x 6x 2x 2x 2x 2x 2x             1x                                                                                                         1x 1x 1x 1x         1x 1x 1x 1x 1x 1x               1x   1x 3x 3x   1x 1x 1x 1x       1x 1x 1x 1x 1x 1x 1x     1x           1x                                                                           1x 18x 18x     18x 18x 18x 18x 18x         1x                               1x                             1x               1x                     1x                                       1x 9x 9x 9x 9x 9x 9x         1x                   1x                                   1x                                                                           1x                                       1x                                                                               1x                                     1x                                                                                                                       1x                                                       1x 5x   5x     5x   5x 5x 5x 5x         1x 1x           1x 1x 1x 1x 1x 1x 1x 1x       1x     1x 5x 5x         1x 3x           3x 3x 3x 3x 3x 3x 3x   3x 3x 3x 3x 3x       3x         1x 1x           1x 1x 1x 1x 1x 1x 1x   1x 1x 1x 1x 1x       1x 1x   1x   1x 3x 3x  
import * as crypto from "node:crypto";
import * as net from "node:net";
import * as path from "node:path";
import * as vscode from "vscode";
import {
    AuthConfig,
    IConfigService,
    M2MMode,
    M2MType,
} from "@dataflint/mcp-server";
import { CopilotConfigClient, mergeScopes } from "@dataflint/mcp-server";
import { getFileConfigHandler } from "./code-editor-mcp-configurator";
import { Logger } from "./logger";
import { extractSubFromSecret } from "./extract-user-info";
 
export type Environment = "staging" | "prod" | "local";
 
export const REMOTE_MCP_URL = "https://mcp.dataflint.io/mcp";
 
const VSCODE_MCP_INSTALL_MIN_VERSION = [1, 101];
 
export function remoteMcpInstallUri(
    uriScheme: string,
    editorVersion: string
): string | undefined {
    if (uriScheme === "cursor") {
        const config = Buffer.from(
            JSON.stringify({ url: REMOTE_MCP_URL })
        ).toString("base64");
        return `cursor://anysphere.cursor-deeplink/mcp/install?name=dataflint&config=${encodeURIComponent(config)}`;
    }
    if (uriScheme !== "vscode" && uriScheme !== "vscode-insiders") {
        return undefined;
    }
    const [major, minor] = editorVersion.split(".").map(Number);
    const [minMajor, minMinor] = VSCODE_MCP_INSTALL_MIN_VERSION;
    if (major < minMajor || (major === minMajor && minor < minMinor)) {
        return undefined;
    }
    const server = { name: "dataflint", type: "http", url: REMOTE_MCP_URL };
    return `${uriScheme}:mcp/install?${encodeURIComponent(JSON.stringify(server))}`;
}
 
/**
 * Build the DataFlint API base URL for a given tenant and environment.
 * Pure function so probe routing can resolve URLs for tenants other than
 * the currently-configured one.
 */
export function serverUrlForDomain(
    customerDomain: string | null,
    environment: Environment
): string {
    if (customerDomain) {
        return `https://api.${customerDomain}.dataflint.io`;
    }
    switch (environment) {
        case "staging":
            return "https://api.staging.dataflint.io";
        case "local":
            return "http://localhost:8000";
        case "prod":
        default:
            return "https://api.dataflint.io";
    }
}
 
// Cursor MCP server config format
export interface McpServerConfig {
    command?: string;
    args?: string[];
    env?: { [key: string]: string };
    url?: string;
    disabled?: boolean;
    autoApprove?: string[];
    timeout?: number;
    runId?: string;
}
 
// VS Code MCP server config format (requires type field)
export interface VsCodeMcpServerConfig {
    type: "http" | "stdio";
    url?: string;
    command?: string;
    args?: string[];
    env?: { [key: string]: string };
    runId?: string;
}
 
// Cursor format uses "mcpServers" key
export interface CursorMcpConfig {
    mcpServers: { [key: string]: McpServerConfig };
}
 
// VS Code format uses "servers" key
export interface VsCodeMcpConfig {
    servers: { [key: string]: VsCodeMcpServerConfig };
}
 
// Legacy type alias for backwards compatibility
export type McpConfig = CursorMcpConfig;
 
export class DataFlintCopilotConfig implements IConfigService {
    private static readonly CONFIG_PREFIX = "dataflint-copilot";
    private context?: vscode.ExtensionContext;
    private bootstrappedAuth?: {
        customerDomain: string | null;
        auth: AuthConfig;
    };
 
    constructor(context?: vscode.ExtensionContext) {
        this.context = context;
        try {
            this.initializeDefaults();
            Logger.tryGetInstance()?.info("DataFlintCopilotConfig initialized");
        } catch (error) {
            // Config initialization errors are critical - log and rethrow
            console.error(
                "Failed to initialize DataFlintCopilotConfig:",
                error
            );
            throw error;
        }
    }
 
    attach(ctx: vscode.ExtensionContext): void {
        this.context = ctx;
    }
 
    private initializeDefaults(): void {
        const config = vscode.workspace.getConfiguration(
            DataFlintCopilotConfig.CONFIG_PREFIX
        );
 
        // Set default values if not already configured
 
        if (!config.has("environment")) {
            config.update(
                "environment",
                "prod",
                vscode.ConfigurationTarget.Global
            );
        }
 
        // Note: adminCompanyDomain is read dynamically from configuration and doesn't need initialization
    }
 
    /**
     * Validate configuration and return any issues found
     * Returns empty array if configuration is valid
     */
    validateConfig(): string[] {
        const issues: string[] = [];
 
        // Validate environment
        const environment = this.getEnvironment();
        if (!["staging", "prod", "local"].includes(environment)) {
            issues.push(
                `Invalid environment "${environment}". Expected: staging, prod, or local.`
            );
        }
 
        // Validate customer domain format if set
        const customerDomain = this.getCustomerDomain();
        if (customerDomain) {
            // Basic domain format validation
            const domainPattern = /^[a-zA-Z0-9]([a-zA-Z0-9-]*[a-zA-Z0-9])?$/;
            if (!domainPattern.test(customerDomain)) {
                issues.push(
                    `Customer domain "${customerDomain}" appears invalid. Expected format: "your-company" (no spaces or special characters).`
                );
            }
        }
 
        // Validate server URL is reachable format
        const serverUrl = this.getServerUrl();
        try {
            new URL(serverUrl);
        } catch {
            issues.push(`Server URL "${serverUrl}" is not a valid URL.`);
        }
 
        return issues;
    }
 
    /**
     * Get the environment from configuration
     * Priority: 1) DATAFLINT_ENVIRONMENT env var, 2) VS Code settings, 3) default "prod"
     */
    getEnvironment(): Environment {
        const envVar = process.env.DATAFLINT_ENVIRONMENT as Environment;
        if (envVar && ["staging", "prod", "local"].includes(envVar)) {
            return envVar;
        }
        const config = vscode.workspace.getConfiguration(
            DataFlintCopilotConfig.CONFIG_PREFIX
        );
        return config.get<Environment>("environment") || "prod";
    }
 
    /**
     * Get the admin company domain from configuration
     */
    getAdminCompanyDomain(): string {
        const config = vscode.workspace.getConfiguration(
            DataFlintCopilotConfig.CONFIG_PREFIX
        );
        return config.get<string>("adminCompanyDomain") || "none";
    }
 
    // =========================================================================
    // PRIVACY SETTINGS
    // =========================================================================
 
    /**
     * Check if anonymized code snippets should be shared to improve highlight accuracy.
     * When enabled, code is automatically obfuscated (variables→v1, strings→"str_1", etc.)
     * Disabled by default - only file:line references are sent.
     */
    getSendSourceCode(): boolean {
        const config = vscode.workspace.getConfiguration(
            DataFlintCopilotConfig.CONFIG_PREFIX
        );
        return config.get<boolean>("privacy.sendSourceCode", false);
    }
 
    // =========================================================================
    // M2M (MACHINE-TO-MACHINE) AUTHENTICATION
    // =========================================================================
 
    /**
     * Get M2M authentication mode.
     * VS Code extension always uses interactive OAuth - returns "none".
     */
    getM2MMode(): M2MMode {
        return { type: M2MType.NONE };
    }
 
    /**
     * Get tenant ID for M2M mode.
     * VS Code extension uses interactive OAuth - not applicable.
     */
    getTenantId(): string | undefined {
        return undefined;
    }
 
    // =========================================================================
    // LOGGING SETTINGS
    // =========================================================================
 
    /**
     * Get the logging level from configuration.
     */
    getLoggingLevel(): "debug" | "info" | "warn" | "error" {
        const config = vscode.workspace.getConfiguration(
            DataFlintCopilotConfig.CONFIG_PREFIX
        );
        const level = config.get<string>("logging.level", "info");
 
        if (["debug", "info", "warn", "error"].includes(level)) {
            return level as "debug" | "info" | "warn" | "error";
        }
        return "info";
    }
 
    // =========================================================================
    // CUSTOMER DOMAIN
    // =========================================================================
 
    /**
     * Get the customer domain from configuration
     * Returns null for local environment (no customer domain needed)
     */
    getCustomerDomain(): string | null {
        if (this.getEnvironment() === "local") return null;
        const config = vscode.workspace.getConfiguration(
            DataFlintCopilotConfig.CONFIG_PREFIX
        );
        return config.get<string>("customerDomain") || null;
    }
 
    /**
     * Get the server URL based on environment
     */
    getServerUrl(): string {
        return serverUrlForDomain(
            this.getCustomerDomain(),
            this.getEnvironment()
        );
    }
 
    /**
     * Get Auth0 configuration based on environment or customer domain
     */
    getAuthConfig(): AuthConfig {
        const customerDomain = this.getCustomerDomain();
        if (
            !this.bootstrappedAuth ||
            this.bootstrappedAuth.customerDomain !== customerDomain
        ) {
            throw new Error(
                "Auth not bootstrapped — call bootstrapAuth() before getAuthConfig()."
            );
        }
        return this.bootstrappedAuth.auth;
    }
 
    /**
     * Fetch /copilot/config and cache the resolved auth config.
     * Idempotent: skipped when the cached result still matches the current
     * customerDomain unless `force: true` is passed (used on persona change).
     */
    async bootstrapAuth(opts?: { force?: boolean }): Promise<AuthConfig> {
        const customerDomain = this.getCustomerDomain();
        if (
            !opts?.force &&
            this.bootstrappedAuth &&
            this.bootstrappedAuth.customerDomain === customerDomain
        ) {
            return this.bootstrappedAuth.auth;
        }
        // Probe-eligible tenants (Cloud and Self) share a single Auth0
        // app. Always bootstrap from the Cloud /copilot/config so the
        // sign-in audience is Cloud — that token works against both
        // backends (Self accepts Cloud audience server-side). BYOC
        // tenants keep their own /copilot/config.
        const isProbeEligible =
            customerDomain === null || customerDomain === "self";
        const fetchUrl = isProbeEligible
            ? serverUrlForDomain(null, this.getEnvironment())
            : this.getServerUrl();
        const client = new CopilotConfigClient({
            getServerUrl: () => fetchUrl,
        });
        const config = await client.getConfig();
        this.bootstrappedAuth = {
            customerDomain,
            auth: {
                domain: config.auth.url,
                clientId: config.auth.client_id,
                audience: config.auth.audience,
                scope: mergeScopes(config.auth.scopes),
            },
        };
        return this.bootstrappedAuth.auth;
    }
 
    /**
     * Check if a port is available
     */
    private async isPortAvailable(port: number): Promise<boolean> {
        return new Promise((resolve) => {
            const server = net.createServer();
 
            server.listen(port, () => {
                server.once("close", () => {
                    resolve(true);
                });
                server.close();
            });
 
            server.on("error", () => {
                resolve(false);
            });
        });
    }
 
    /**
     * Determine MCP port based on workspace path hash
     */
    private async determineWorkspacePort(): Promise<number> {
        const logger = Logger.getInstance();
        const workspaceFolder = vscode.workspace.workspaceFolders?.[0];
 
        let hashSource: string;
        if (workspaceFolder) {
            hashSource = workspaceFolder.uri.fsPath;
            logger.debug(`Determining port for workspace: ${hashSource}`);
        } else {
            hashSource =
                "no-workspace-" +
                (process.env.HOME || process.env.USERPROFILE || "default");
            logger.info(
                "No workspace folder — using home directory for port hash"
            );
        }
 
        // Hash the source path and get a number between 0-999
        const hash = crypto
            .createHash("sha256")
            .update(hashSource)
            .digest("hex");
        const hashNumber = parseInt(hash.substring(0, 8), 16) % 1000;
        let port = 21220 + hashNumber;
 
        logger.debug(`Initial port calculation: ${port} (hash: ${hashNumber})`);
 
        // Find an available port starting from the calculated one
        while (!(await this.isPortAvailable(port))) {
            logger.debug(`Port ${port} is not available, trying ${port + 1}`);
            port++;
        }
 
        logger.info(
            `Selected available port: ${port} for source: ${path.basename(hashSource)}`
        );
        return port;
    }
 
    /** Get a workspace-specific globalState key for MCP port persistence. */
    private getMcpPortStateKey(): string {
        const workspacePath =
            vscode.workspace.workspaceFolders?.[0]?.uri.fsPath;
        if (!workspacePath) {
            return "dataflint-copilot.mcpPort.no-workspace";
        }
        const hash = crypto
            .createHash("sha256")
            .update(workspacePath)
            .digest("hex")
            .substring(0, 12);
        return `dataflint-copilot.mcpPort.${hash}`;
    }
 
    /**
     * Get MCP port from globalState or workspace config.
     * Checks globalState first (persists across file cleanup by API registrars),
     * then falls back to file-based config.
     */
    async getWorkspaceMcpPort(): Promise<number | undefined> {
        const logger = Logger.getInstance();
 
        // Check globalState first (set by configureWorkspaceMcpPort)
        const stateKey = this.getMcpPortStateKey();
        const savedPort = this.context?.globalState.get<number>(stateKey);
        if (savedPort !== undefined) {
            if (await this.isPortAvailable(savedPort)) {
                logger.info(
                    `Using existing port from globalState: ${savedPort}`
                );
                return savedPort;
            } else {
                logger.warn(
                    `Saved port ${savedPort} is no longer available, checking file-based config`
                );
                // Fall through to file-based config instead of returning undefined
            }
        }
 
        // Fall back to file-based config
        try {
            const handler = getFileConfigHandler();
            const config = handler.read();
            const dataflintServer = config.servers["dataflint-copilot"];
 
            if (dataflintServer?.url) {
                const match = dataflintServer.url.match(/:(\d+)/);
                if (match) {
                    const port = parseInt(match[1], 10);
                    if (await this.isPortAvailable(port)) {
                        logger.info(
                            `Using existing port from workspace config: ${port}`
                        );
                        // Persist to globalState so auto-start survives file cleanup
                        await this.context?.globalState.update(stateKey, port);
                        return port;
                    } else {
                        logger.warn(
                            `Configured port ${port} is no longer available`
                        );
                        return undefined;
                    }
                }
            }
 
            logger.info(
                "No MCP configuration found - MCP server not configured"
            );
            return undefined;
        } catch (error) {
            logger.error("Failed to get workspace MCP port:", error);
            return undefined;
        }
    }
 
    /**
     * Configure and determine MCP port for workspace (used during login).
     * Persists the port in globalState so it survives file-based config cleanup.
     */
    async configureWorkspaceMcpPort(): Promise<number> {
        const logger = Logger.getInstance();
 
        try {
            // Determine new port
            const port = await this.determineWorkspacePort();
            logger.info(`Determined new port: ${port}`);
 
            // Persist in globalState for auto-start after file cleanup
            await this.context?.globalState.update(
                this.getMcpPortStateKey(),
                port
            );
 
            return port;
        } catch (error) {
            logger.error("Failed to configure workspace MCP port:", error);
            // Fallback to default port with warning
            logger.warn(
                `Falling back to default port 11223. This may cause conflicts if multiple instances are running.`
            );
            return 11223;
        }
    }
 
    /**
     * Get the authentication storage key based on customer domain or environment
     */
    private getAuthStorageKey(): string {
        const customerDomain = this.getCustomerDomain();
 
        if (customerDomain) {
            // Use customer domain for the storage key if defined
            return `dataflint-auth-result-${customerDomain}`;
        } else {
            // Fall back to environment-based key
            const environment = this.getEnvironment();
            return `dataflint-auth-result-${environment}`;
        }
    }
 
    /**
     * Get authentication result from persistent storage
     */
    async getAuthSecret(): Promise<string | undefined> {
        if (!this.context) {
            throw new Error(
                "Extension context is required for auth secret operations"
            );
        }
 
        const logger = Logger.getInstance();
        try {
            const secret = await this.context.secrets.get(
                this.getAuthStorageKey()
            );
            this.syncTelemetryUser(secret);
            return secret;
        } catch (error) {
            logger.error("Failed to load authentication result", error);
            return undefined;
        }
    }
 
    /** Sentry identifies users by opaque JWT `sub` for distinct counts only. */
    private syncTelemetryUser(authSecret: string | undefined): void {
        Logger.getInstance().identify(extractSubFromSecret(authSecret));
    }
 
    /**
     * Set authentication result in persistent storage
     */
    async setAuthSecret(authResult: string): Promise<void> {
        if (!this.context) {
            throw new Error(
                "Extension context is required for auth secret operations"
            );
        }
 
        const logger = Logger.getInstance();
        try {
            const authKey = this.getAuthStorageKey();
            await this.context.secrets.store(authKey, authResult);
            this.syncTelemetryUser(authResult);
            const customerDomain = this.getCustomerDomain();
            const storageContext = customerDomain
                ? `customer domain: ${customerDomain}`
                : `environment: ${this.getEnvironment()}`;
            logger.debug(
                `Authentication result saved to persistent storage for ${storageContext}`
            );
        } catch (error) {
            logger.error("Failed to save authentication result", error);
            throw error;
        }
    }
 
    /**
     * Delete authentication result from persistent storage
     */
    async deleteAuthSecret(): Promise<void> {
        if (!this.context) {
            throw new Error(
                "Extension context is required for auth secret operations"
            );
        }
 
        const logger = Logger.getInstance();
        try {
            const authKey = this.getAuthStorageKey();
            await this.context.secrets.delete(authKey);
            this.syncTelemetryUser(undefined);
            const customerDomain = this.getCustomerDomain();
            const storageContext = customerDomain
                ? `customer domain: ${customerDomain}`
                : `environment: ${this.getEnvironment()}`;
            logger.info(
                `Authentication result cleared from persistent storage for ${storageContext}`
            );
        } catch (error) {
            logger.error("Failed to clear authentication result", error);
            throw error;
        }
    }
}
 
export const config: DataFlintCopilotConfig = new DataFlintCopilotConfig();
 
export function initConfig(ctx: vscode.ExtensionContext) {
    config.attach(ctx);
}