All files / src/cli/init wizard.ts

99.32% Statements 148/149
91.66% Branches 77/84
100% Functions 10/10
100% Lines 146/146

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        2x 2x               2x 2x         2x 2x       4x 2x   2x   4x             22x     22x   22x 22x 22x           2x 31x     31x               31x 1x 1x 1x         30x 27x   3x       1x 1x       3x 1x 1x 1x       2x       29x         29x 1x 1x 1x         28x       3x   3x               3x         3x 1x 1x 1x     2x 2x 2x 1x   1x 1x           27x     3x 2x   1x       27x 1x 1x 1x     26x     26x 26x   26x   26x 1x 1x 1x 1x 1x     25x   25x           150x           25x         25x 1x 1x 1x       24x 24x 22x         22x 1x 1x 1x     21x       207x           23x         23x 1x 1x 1x       22x                   22x     22x   22x     10x 10x   10x         10x 1x 1x 1x     9x   5x 5x 5x 3x     2x       2x 1x   1x     4x     6x 3x 3x           9x     3x 3x 3x 2x 1x   1x 1x     1x 1x         12x 12x   12x 12x         21x 7x   7x         7x         7x 1x 1x 1x     6x 5x 5x 4x   1x 1x           20x                   150x               150x    
/**
 * Interactive init wizard using @clack/prompts
 */
 
import * as p from '@clack/prompts';
import {
  WizardConfig,
  UserRole,
  McpClient,
  ROLE_DESCRIPTIONS,
  MCP_CLIENT_INFO,
  ROLE_PRESETS,
} from './types';
import { testConnection, validateGitLabUrl, getPatCreationUrl } from './connection';
import {
  generateClientConfig,
  generateClaudeDeepLink,
  generateServerConfig,
} from './config-generator';
import { openUrl } from './browser';
import { CODEX_SERVER_NAME, installCodex } from '../install/codex';
import type { InstallResult } from '../install/types';
 
function reportCodexInstall(result: InstallResult): void {
  if (result.success) {
    p.log.success('MCP server installed!');
  } else {
    p.log.error(result.error ?? 'Installation failed');
  }
  for (const note of result.notes ?? []) p.log.warn(note);
}
 
/**
 * Mask sensitive values in content for display (JSON and CLI commands)
 */
function maskSensitiveContent(content: string): string {
  let masked = content;
  // Mask GITLAB_TOKEN value in JSON: "GITLAB_TOKEN": "value"
  // Pattern handles escaped quotes: (?:\\.|[^"\\])* matches escaped chars or non-quote/backslash
  masked = masked.replace(/("GITLAB_TOKEN"\s*:\s*")((?:\\.|[^"\\])*)(")/g, '$1****$3');
  // Mask GITLAB_TOKEN in CLI commands: --env GITLAB_TOKEN="value" or GITLAB_TOKEN=value
  masked = masked.replace(/(GITLAB_TOKEN=")((?:\\.|[^"\\])*)(")/g, '$1****$3');
  masked = masked.replace(/(GITLAB_TOKEN=)([^\s"]+)/g, '$1****');
  return masked;
}
 
/**
 * Run the interactive init wizard
 */
export async function runWizard(): Promise<void> {
  p.intro('GitLab MCP Setup Wizard');
 
  // Step 1: Select GitLab instance type
  const instanceType = await p.select({
    message: 'Which GitLab instance do you want to connect to?',
    options: [
      { value: 'saas' as const, label: 'GitLab.com (SaaS)' },
      { value: 'self-hosted' as const, label: 'Self-hosted GitLab' },
    ],
  });
 
  if (p.isCancel(instanceType)) {
    p.cancel('Setup cancelled');
    process.exit(0);
    return;
  }
 
  // Step 2: Get instance URL
  let instanceUrl: string;
  if (instanceType === 'saas') {
    instanceUrl = 'https://gitlab.com';
  } else {
    const urlInput = await p.text({
      message: 'Enter your GitLab instance URL:',
      placeholder: 'https://gitlab.example.com',
      validate: (value) => {
        const result = validateGitLabUrl(value ?? '');
        return result.valid ? undefined : result.error;
      },
    });
 
    if (p.isCancel(urlInput)) {
      p.cancel('Setup cancelled');
      process.exit(0);
      return; // Unreachable, but helps TypeScript and test mocks
    }
 
    // Normalize URL: strip trailing slash and /api/v4 suffix if present
    instanceUrl = urlInput.replace(/\/+$/, '').replace(/\/api\/v4$/i, '');
  }
 
  // Step 3: Check if user has a token
  const hasToken = await p.confirm({
    message: 'Do you already have a GitLab Personal Access Token (PAT)?',
    initialValue: false,
  });
 
  if (p.isCancel(hasToken)) {
    p.cancel('Setup cancelled');
    process.exit(0);
    return;
  }
 
  let token: string;
 
  if (!hasToken) {
    // Offer to open browser for PAT creation
    // Note: We use full API scopes here since readOnly mode isn't determined yet.
    // Users who want minimal scopes can adjust them manually in GitLab.
    const patUrl = getPatCreationUrl(instanceUrl);
 
    p.note(
      `You need a Personal Access Token with these scopes:\n` +
        `  - api (full API access)\n` +
        `  - read_user (read user info)\n\n` +
        `Token URL: ${patUrl}`,
      'Create a Personal Access Token',
    );
 
    const openBrowser = await p.confirm({
      message: 'Open browser to create token?',
      initialValue: true,
    });
 
    if (p.isCancel(openBrowser)) {
      p.cancel('Setup cancelled');
      process.exit(0);
      return;
    }
 
    Eif (openBrowser) {
      const opened = await openUrl(patUrl);
      if (opened) {
        p.log.info('Browser opened. Create your token and copy it.');
      } else {
        p.log.warn('Could not open browser automatically');
        p.note(patUrl, 'Open this URL manually:');
      }
    }
  }
 
  // Step 4: Enter token
  const tokenInput = await p.password({
    message: 'Enter your Personal Access Token:',
    validate: (value) => {
      if (!value || value.length < 10) {
        return 'Token is too short';
      }
      return undefined;
    },
  });
 
  if (p.isCancel(tokenInput)) {
    p.cancel('Setup cancelled');
    process.exit(0);
    return;
  }
 
  token = tokenInput;
 
  // Step 5: Test connection
  const spinner = p.spinner();
  spinner.start('Testing connection...');
 
  const connectionResult = await testConnection(instanceUrl, token);
 
  if (!connectionResult.success) {
    spinner.stop('Connection failed');
    p.log.error(`Connection error: ${connectionResult.error ?? 'Unknown error'}`);
    p.cancel('Please check your URL and token');
    process.exit(1);
    return;
  }
 
  spinner.stop('Connection successful!');
 
  p.log.success(
    `Connected as ${connectionResult.username ?? 'unknown user'}` +
      (connectionResult.gitlabVersion ? ` (GitLab ${connectionResult.gitlabVersion})` : ''),
  );
 
  // Step 6: Select role
  const roleOptions = (Object.keys(ROLE_DESCRIPTIONS) as UserRole[]).map((r) => ({
    value: r,
    label: formatRoleLabel(r),
    hint: ROLE_DESCRIPTIONS[r],
  }));
 
  const role = await p.select({
    message: 'What is your primary role?',
    options: roleOptions,
  });
 
  if (p.isCancel(role)) {
    p.cancel('Setup cancelled');
    process.exit(0);
    return;
  }
 
  // Step 7: Confirm read-only if applicable
  let readOnly = role === 'readonly';
  if (!readOnly) {
    const confirmReadWrite = await p.confirm({
      message: 'Enable write operations (create issues, merge MRs, etc.)?',
      initialValue: true,
    });
 
    if (p.isCancel(confirmReadWrite)) {
      p.cancel('Setup cancelled');
      process.exit(0);
      return;
    }
 
    readOnly = !confirmReadWrite;
  }
 
  // Step 8: Select MCP client
  const clientOptions = (Object.keys(MCP_CLIENT_INFO) as McpClient[]).map((c) => ({
    value: c,
    label: MCP_CLIENT_INFO[c].name,
    hint: MCP_CLIENT_INFO[c].configPath ? MCP_CLIENT_INFO[c].configPath : undefined,
  }));
 
  const client = await p.select({
    message: 'Which MCP client are you using?',
    options: clientOptions,
  });
 
  if (p.isCancel(client)) {
    p.cancel('Setup cancelled');
    process.exit(0);
    return;
  }
 
  // Build configuration
  const wizardConfig: WizardConfig = {
    instanceUrl,
    token,
    role,
    client,
    readOnly,
    presetName: ROLE_PRESETS[role],
  };
 
  // Generate configuration
  const generatedConfig = generateClientConfig(wizardConfig);
 
  // Display results
  p.log.step('Configuration generated');
 
  if (generatedConfig.type === 'cli' && generatedConfig.cliCommand) {
    // Claude Code - offer CLI installation
    // Mask token in displayed command for security (actual command uses real token)
    p.note(maskSensitiveContent(generatedConfig.cliCommand), 'Run this command to install:');
    p.log.info('If copying this command, replace **** with your actual token.');
 
    const runNow = await p.confirm({
      message: 'Run this command now?',
      initialValue: true,
    });
 
    if (p.isCancel(runNow)) {
      p.cancel('Setup cancelled');
      process.exit(0);
      return;
    }
 
    if (runNow && client === 'codex') {
      // The installer drives the Codex CLI with backup, read-back and rollback.
      const serverConfig = generateServerConfig(wizardConfig);
      const result = installCodex(serverConfig, false);
      if (!result.wasAlreadyConfigured) {
        reportCodexInstall(result);
      } else {
        // The wizard has no --force flag, so it asks before replacing an existing entry.
        const replace = await p.confirm({
          message: `Codex already has a ${CODEX_SERVER_NAME} entry. Replace it?`,
          initialValue: false,
        });
        if (p.isCancel(replace) || !replace) {
          p.log.info(`Kept the existing Codex ${CODEX_SERVER_NAME} entry.`);
        } else {
          reportCodexInstall(installCodex(serverConfig, true));
        }
      }
    } else if (runNow) {
      // Execute claude mcp add command using spawnSync with argument array
      // to prevent command injection vulnerabilities
      const { spawnSync } = await import('child_process');
      const serverConfig = generateServerConfig(wizardConfig);
      const args = [
        'mcp',
        'add',
        'gitlab',
        serverConfig.command,
        ...serverConfig.args,
        ...Object.entries(serverConfig.env).flatMap(([key, value]) => ['--env', `${key}=${value}`]),
      ];
 
      try {
        spinner.start('Installing MCP server...');
        const result = spawnSync('claude', args, { stdio: 'inherit' });
        if (result.status === 0) {
          spinner.stop('MCP server installed!');
        } else {
          spinner.stop('Installation failed');
          p.log.error('Failed to run command. You can run it manually.');
        }
      } catch {
        spinner.stop('Installation failed');
        p.log.error('Failed to run command. You can run it manually.');
      }
    }
  } else {
    // JSON configuration - mask PAT in terminal output for security
    p.note(maskSensitiveContent(generatedConfig.content), 'Add to your MCP configuration:');
    p.log.warn('Note: Replace **** with your actual token in the config file');
 
    Eif (generatedConfig.configPath) {
      p.log.info(`Config file: ${generatedConfig.configPath}`);
    }
  }
 
  // Offer Claude Deep Link for Claude Desktop
  if (client === 'claude-desktop') {
    const deepLink = generateClaudeDeepLink(wizardConfig);
 
    p.log.warn(
      'Security: the deep link encodes your GitLab token. ' +
        'It may be recorded in OS/app logs. Treat it like a password.',
    );
 
    const useDeepLink = await p.confirm({
      message: 'Open Claude Desktop with deep link?',
      initialValue: true,
    });
 
    if (p.isCancel(useDeepLink)) {
      p.cancel('Setup cancelled');
      process.exit(0);
      return;
    }
 
    if (useDeepLink) {
      const opened = await openUrl(deepLink);
      if (opened) {
        p.log.success('Claude Desktop should open with the configuration');
      } else {
        p.log.warn('Could not open Claude Desktop automatically');
        p.note(deepLink, 'Copy this sensitive link (treat like a password):');
      }
    }
  }
 
  // Summary
  p.outro(
    `Setup complete! Preset: ${wizardConfig.presetName ?? 'default'}` +
      (readOnly ? ' (read-only)' : ''),
  );
}
 
/**
 * Format role label for display
 */
function formatRoleLabel(role: UserRole): string {
  const labels: Record<UserRole, string> = {
    developer: 'Developer',
    'senior-developer': 'Senior Developer',
    'tech-lead': 'Tech Lead / Admin',
    devops: 'DevOps Engineer',
    reviewer: 'Code Reviewer',
    readonly: 'Read-Only Access',
  };
  return labels[role];
}