All files / src/cli/docker docker-utils.ts

99.6% Statements 249/250
93.05% Branches 134/144
100% Functions 36/36
99.58% Lines 239/240

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 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705        3x 3x 3x 3x 3x 3x                       3x 3x     8x         3x 70x           3x 3x 3x           3x 3x 3x           3x 3x 3x               11x           3x   11x 1x     1x     10x 10x 10x                               10x 4x     6x 6x   6x 1x     5x     5x 5x 5x 1x 4x 1x 3x 1x 2x 1x 1x 1x         5x 5x 1x     5x         5x                       3x 3x   3x               3x 2x       3x   3x         3x               22x 14x 9x     2x 1x   1x   7x     3x               6x 2x   1x   4x                 2x           3x 22x 21x 20x           20x 20x                                   20x   12x       12x 5x           7x             12x     20x           5x               5x           20x 4x                                   4x 4x         20x 1x 2x       20x           3x 14x       14x 14x       14x 2x           14x 1x       14x           3x 12x 12x   12x 6x     6x 6x 6x   5x                       1x             3x 9x   9x 3x     9x 9x 9x 9x       3x   3x             12x 12x 3x   12x 12x 7x 9x                         7x   12x           3x 5x   5x 2x     5x 5x 5x           3x 13x     13x 13x 1x           12x 12x 1x           11x   11x 11x   11x           10x 8x         2x           1x                   3x 5x           3x 2x           3x 2x           3x 2x 2x 1x     1x           3x 4x 4x   4x 1x   3x   3x   3x 2x     3x   3x                 3x 1x           3x 3x     3x 3x 1x   2x     3x           3x 2x 2x   2x 1x     1x 1x           3x 5x           5x     5x       5x 1x 4x 3x     5x             3x 14x   14x 3x     14x   14x 5x     14x   10x     14x   2x     14x   2x     14x 11x 11x 11x     9x 9x   11x               3x       9x             3x 13x 13x 13x 9x 9x 9x   5x 4x 4x   13x 21x   13x    
/**
 * Docker utilities for gitlab-mcp container management
 */
 
import { spawnSync, spawn, ChildProcess } from 'child_process';
import { randomBytes } from 'crypto';
import { chmodSync, existsSync, readFileSync, writeFileSync, mkdirSync } from 'fs';
import { join } from 'path';
import YAML from 'yaml';
import {
  DockerConfig,
  DockerComposeFile,
  DockerStatusResult,
  DockerCommandResult,
  ContainerInfo,
  ContainerStatus,
  GitLabInstance,
  InstancesYaml,
  DEFAULT_DOCKER_CONFIG,
  getConfigDir,
} from './types';
import { getContainerRuntime } from './container-runtime';
import { expandPath } from '../utils/path-utils.js';
 
// Re-export expandPath for backwards compatibility with existing imports
export { expandPath } from '../utils/path-utils.js';
 
/**
 * Get expanded config directory path
 */
export function getExpandedConfigDir(): string {
  return expandPath(getConfigDir());
}
 
/**
 * Check if a container runtime (Docker/Podman) is installed
 */
export function isDockerInstalled(): boolean {
  const runtime = getContainerRuntime();
  return runtime.runtimeVersion !== undefined;
}
 
/**
 * Check if the container runtime daemon is running
 */
export function isDockerRunning(): boolean {
  const runtime = getContainerRuntime();
  return runtime.runtimeAvailable;
}
 
/**
 * Check if a compose tool is available for the detected runtime
 */
export function isComposeInstalled(): boolean {
  const runtime = getContainerRuntime();
  return runtime.composeCmd !== null;
}
 
/**
 * Validate container name format to prevent command injection
 */
function isValidContainerName(name: string): boolean {
  // Docker container names can only contain [a-zA-Z0-9][a-zA-Z0-9_.-]
  return /^[a-zA-Z0-9][a-zA-Z0-9_.-]*$/.test(name);
}
 
/**
 * Get container info
 */
export function getContainerInfo(containerName: string = 'gitlab-mcp'): ContainerInfo | undefined {
  // Validate container name to prevent command injection
  if (!isValidContainerName(containerName)) {
    console.error(
      `Invalid container name: "${containerName}". Name must match [a-zA-Z0-9][a-zA-Z0-9_.-]*`,
    );
    return undefined;
  }
 
  try {
    const runtime = getContainerRuntime();
    const result = spawnSync(
      runtime.runtimeCmd,
      [
        'ps',
        '-a',
        '--filter',
        `name=${containerName}`,
        '--format',
        '{{.ID}}|{{.Names}}|{{.Image}}|{{.Status}}|{{.Ports}}|{{.CreatedAt}}',
      ],
      {
        stdio: 'pipe',
        encoding: 'utf8',
      },
    );
 
    if (result.status !== 0 || !result.stdout.trim()) {
      return undefined;
    }
 
    const line = result.stdout.trim().split('\n')[0];
    const parts = line.split('|');
 
    if (parts.length < 6) {
      return undefined;
    }
 
    const [id, name, image, statusStr, ports, created] = parts;
 
    // Parse status
    let status: ContainerStatus = 'exited';
    const statusLower = statusStr.toLowerCase();
    if (statusLower.includes('up')) {
      status = 'running';
    } else if (statusLower.includes('paused')) {
      status = 'paused';
    } else if (statusLower.includes('restarting')) {
      status = 'restarting';
    } else if (statusLower.includes('created')) {
      status = 'created';
    } else Eif (statusLower.includes('dead')) {
      status = 'dead';
    }
 
    // Extract uptime from status string
    let uptime: string | undefined;
    const uptimeMatch = statusStr.match(/Up\s+(.+?)(?:\s*\(|$)/i);
    if (uptimeMatch) {
      uptime = uptimeMatch[1].trim();
    }
 
    return {
      id,
      name,
      image,
      status,
      ports: ports ? ports.split(',').map((p) => p.trim()) : [],
      created,
      uptime,
    };
  } catch {
    return undefined;
  }
}
 
/**
 * Get Docker status
 */
export function getDockerStatus(containerName: string = 'gitlab-mcp'): DockerStatusResult {
  const runtime = getContainerRuntime();
 
  const result: DockerStatusResult = {
    dockerInstalled: runtime.runtimeVersion !== undefined,
    dockerRunning: runtime.runtimeAvailable,
    composeInstalled: runtime.composeCmd !== null,
    instances: [],
    runtime,
  };
 
  if (result.dockerRunning) {
    result.container = getContainerInfo(containerName);
  }
 
  // Load instances from config
  result.instances = loadInstances();
 
  return result;
}
 
/** Connection string of the database bundled by the compose-bundle deployment */
const BUNDLED_POSTGRESQL_URL =
  'postgresql://gitlab_mcp:${POSTGRES_PASSWORD}@postgres:5432/gitlab_mcp';
 
/**
 * PostgreSQL URL the deployment stores OAuth sessions in, as written into the compose
 * file; undefined when sessions live in a file on the data volume. An external URL
 * carries its password, so it stays in .env and the compose file references it.
 */
function sessionDatabaseUrl(config: DockerConfig): string | undefined {
  if (!config.oauthEnabled) return undefined;
  if (config.deploymentType === 'compose-bundle') return BUNDLED_POSTGRESQL_URL;
  if (config.deploymentType === 'external-db') {
    // The compose file references the URL written to .env; without one Compose would
    // substitute an empty string and the migrations could not start.
    if (!config.databaseUrl) {
      throw new Error('An external-db deployment with OAuth needs the PostgreSQL connection URL');
    }
    return '${OAUTH_STORAGE_POSTGRESQL_URL}';
  }
  return undefined;
}
 
const CORE_IMAGE_REPOSITORY = 'ghcr.io/structured-world/gitlab-mcp';
 
/**
 * Image of a deployment that keeps sessions in PostgreSQL. Only the db image carries that
 * backend, so the released core image is replaced by the db image of the same tag; any
 * other image is taken as a db build already.
 */
function databaseImage(image: string): string {
  if (image !== CORE_IMAGE_REPOSITORY && !image.startsWith(`${CORE_IMAGE_REPOSITORY}:`)) {
    if (!image.startsWith(`${CORE_IMAGE_REPOSITORY}@`)) return image;
    // A digest names one build of the core image; its db image has another digest.
    throw new Error('Pin the gitlab-mcp-db image by tag or digest for a PostgreSQL deployment');
  }
  return image.replace(CORE_IMAGE_REPOSITORY, `${CORE_IMAGE_REPOSITORY}-db`);
}
 
/**
 * A URL as a literal .env value: Compose interpolates unquoted values (a "$" in a password
 * would be replaced) but keeps single-quoted ones as written. A single quote inside the
 * URL is percent-encoded, which PostgreSQL decodes back to the same connection string.
 */
function envLiteralUrl(url: string): string {
  return `'${url.replaceAll("'", '%27')}'`;
}
 
/**
 * Generate docker-compose.yml content
 */
export function generateDockerCompose(config: DockerConfig): string {
  const databaseUrl = sessionDatabaseUrl(config);
  const image = databaseUrl ? databaseImage(config.image) : config.image;
  const environment = [
    'TRANSPORT=sse',
    'HOST=0.0.0.0',
    'PORT=3333',
    `OAUTH_ENABLED=${config.oauthEnabled}`,
  ];
  const volumes = ['gitlab-mcp-data:/data'];
  const compose: DockerComposeFile = {
    version: '3.8',
    services: {
      'gitlab-mcp': {
        image,
        container_name: config.containerName,
        ports: [`\${PORT:-${config.port}}:3333`],
        environment,
        volumes,
        restart: 'unless-stopped',
      },
    },
    volumes: {
      'gitlab-mcp-data': {},
    },
  };
 
  // Add OAuth-specific configuration
  if (config.oauthEnabled) {
    // Reference secret via env var — actual value stored in .env file
    environment.push(
      'OAUTH_SESSION_SECRET=${OAUTH_SESSION_SECRET}',
      'OAUTH_ISSUER=${OAUTH_ISSUER}',
    );
    if (databaseUrl) {
      environment.push(
        'OAUTH_STORAGE_TYPE=postgresql',
        `OAUTH_STORAGE_POSTGRESQL_URL=${databaseUrl}`,
      );
    } else {
      // Sessions survive restarts on the data volume
      environment.push(
        'OAUTH_STORAGE_TYPE=file',
        'OAUTH_STORAGE_FILE_PATH=/data/oauth-sessions.json',
      );
    }
    // The instance list (GITLAB_INSTANCES, rewritten whenever instances change) and the
    // instance secrets it names (kept in .env) reach the server at every start.
    compose.services['gitlab-mcp'].env_file = ['.env', INSTANCES_ENV_FILE];
  }
 
  if (databaseUrl) {
    // One-shot schema migration from the db image; the server starts only after it
    // succeeds. It waits for the database to accept connections itself and baselines a
    // database created before migrations shipped. The bundled database is only started
    // first: podman-compose 1.6.0 on Podman 4.9.3 hangs on `service_healthy`
    // (https://github.com/containers/podman-compose/issues/1541).
    compose.services.migrate = {
      image,
      restart: 'no',
      working_dir: '/app/node_modules/@structured-world/gitlab-mcp-db',
      entrypoint: ['node', 'dist/src/migrate.js'],
      environment: [`OAUTH_STORAGE_POSTGRESQL_URL=${databaseUrl}`],
      ...(config.deploymentType === 'compose-bundle' && { depends_on: ['postgres'] }),
    };
    compose.services['gitlab-mcp'].depends_on = {
      migrate: { condition: 'service_completed_successfully' },
    };
  }
 
  // Add compose-bundle postgres service (only when OAuth needs a database)
  if (config.deploymentType === 'compose-bundle' && config.oauthEnabled) {
    compose.services.postgres = {
      image: 'postgres:16-alpine',
      container_name: `${config.containerName}-db`,
      ports: [],
      environment: [
        'POSTGRES_USER=gitlab_mcp',
        'POSTGRES_PASSWORD=${POSTGRES_PASSWORD}',
        'POSTGRES_DB=gitlab_mcp',
      ],
      volumes: ['postgres-data:/var/lib/postgresql/data'],
      restart: 'unless-stopped',
      healthcheck: {
        test: ['CMD-SHELL', 'pg_isready -U gitlab_mcp'],
        interval: '5s',
        timeout: '5s',
        retries: 5,
      },
    };
    Eif (compose.volumes) {
      compose.volumes['postgres-data'] = {};
    }
  }
 
  // Add tool configuration environment variables
  if (config.environment) {
    for (const [key, value] of Object.entries(config.environment)) {
      environment.push(`${key}=${value}`);
    }
  }
 
  return YAML.stringify(compose);
}
 
/**
 * Generate instances.yml content
 */
export function generateInstancesYaml(instances: GitLabInstance[]): string {
  const yaml: InstancesYaml = {
    instances: {},
  };
 
  for (const instance of instances) {
    yaml.instances[instance.host] = {
      name: instance.name,
    };
 
    if (instance.oauth) {
      yaml.instances[instance.host].oauth = {
        client_id: instance.oauth.clientId,
        client_secret_env: instance.oauth.clientSecretEnv,
      };
    }
 
    if (instance.defaultPreset) {
      yaml.instances[instance.host].default_preset = instance.defaultPreset;
    }
  }
 
  return YAML.stringify(yaml);
}
 
/**
 * Load instances from config file
 */
export function loadInstances(): GitLabInstance[] {
  const configDir = getExpandedConfigDir();
  const instancesPath = join(configDir, 'instances.yml');
 
  if (!existsSync(instancesPath)) {
    return [];
  }
 
  try {
    const content = readFileSync(instancesPath, 'utf8');
    const yaml = YAML.parse(content) as InstancesYaml;
 
    return Object.entries(yaml.instances).map(([host, config]) => ({
      host,
      name: config.name,
      oauth: config.oauth
        ? {
            clientId: config.oauth.client_id,
            clientSecretEnv: config.oauth.client_secret_env,
          }
        : undefined,
      defaultPreset: config.default_preset,
    }));
  } catch {
    return [];
  }
}
 
/**
 * Save instances to config file
 */
export function saveInstances(instances: GitLabInstance[]): void {
  const configDir = getExpandedConfigDir();
 
  if (!existsSync(configDir)) {
    mkdirSync(configDir, { recursive: true });
  }
 
  const instancesPath = join(configDir, 'instances.yml');
  const content = generateInstancesYaml(instances);
  writeFileSync(instancesPath, content, 'utf8');
  saveServerInstances(instances);
}
 
/** Env file holding the server's instance list, next to the compose file. */
const INSTANCES_ENV_FILE = 'instances.env';
/** JSON escape of a single quote: a backslash followed by u0027. */
const JSON_QUOTE_ESCAPE = `${String.fromCodePoint(92)}u0027`;
 
/**
 * Write the instances as the server reads them: GITLAB_INSTANCES with the configuration
 * object the server validates. Secrets stay in .env; each instance names its variable.
 */
function saveServerInstances(instances: GitLabInstance[]): void {
  const configDir = getExpandedConfigDir();
  if (!existsSync(configDir)) {
    mkdirSync(configDir, { recursive: true });
  }
  let value = '';
  if (instances.length > 0) {
    const config = {
      instances: instances.map((instance) => ({
        url: instance.host.includes('://') ? instance.host : `https://${instance.host}`,
        label: instance.name,
        ...(instance.oauth && {
          oauth: {
            clientId: instance.oauth.clientId,
            clientSecretEnv: instance.oauth.clientSecretEnv,
          },
        }),
      })),
    };
    // Single-quoted env values are literal and cannot contain a single quote; JSON spells
    // it as the escape backslash-u0027 instead.
    value = `'${JSON.stringify(config).replaceAll("'", JSON_QUOTE_ESCAPE)}'`;
  }
  writeFileSync(join(configDir, INSTANCES_ENV_FILE), `GITLAB_INSTANCES=${value}\n`, 'utf8');
}
 
/**
 * Save docker-compose.yml to config directory
 */
export function saveDockerCompose(config: DockerConfig): void {
  const configDir = getExpandedConfigDir();
 
  if (!existsSync(configDir)) {
    mkdirSync(configDir, { recursive: true });
  }
 
  const composePath = join(configDir, 'docker-compose.yml');
  const content = generateDockerCompose(config);
  writeFileSync(composePath, content, 'utf8');
}
 
/**
 * Run docker compose command
 */
export function runComposeCommand(args: string[], configDir?: string): DockerCommandResult {
  const cwd = configDir ?? getExpandedConfigDir();
 
  // Check if docker-compose.yml exists
  const composePath = join(cwd, 'docker-compose.yml');
  if (!existsSync(composePath)) {
    return {
      success: false,
      error: `docker-compose.yml not found in ${cwd}. Run 'gitlab-mcp docker init' first.`,
    };
  }
 
  const runtime = getContainerRuntime();
  if (!runtime.composeCmd) {
    return {
      success: false,
      error: 'No compose tool available. Install docker-compose or podman-compose.',
    };
  }
 
  try {
    // Use the detected compose command
    const [composeExe, ...composePrefix] = runtime.composeCmd;
    const fullArgs = [...composePrefix, ...args];
 
    const result = spawnSync(composeExe, fullArgs, {
      cwd,
      stdio: 'pipe',
      encoding: 'utf8',
    });
 
    if (result.status === 0) {
      return {
        success: true,
        output: result.stdout,
      };
    } else {
      return {
        success: false,
        error: result.stderr || result.stdout || 'Unknown error',
      };
    }
  } catch (error) {
    return {
      success: false,
      error: error instanceof Error ? error.message : String(error),
    };
  }
}
 
/**
 * Start container
 */
export function startContainer(): DockerCommandResult {
  return runComposeCommand(['up', '-d']);
}
 
/**
 * Stop container
 */
export function stopContainer(): DockerCommandResult {
  return runComposeCommand(['down']);
}
 
/**
 * Restart container
 */
export function restartContainer(): DockerCommandResult {
  return runComposeCommand(['restart']);
}
 
/**
 * Pull latest image and restart
 */
export function upgradeContainer(): DockerCommandResult {
  const pullResult = runComposeCommand(['pull']);
  if (!pullResult.success) {
    return pullResult;
  }
 
  return runComposeCommand(['up', '-d']);
}
 
/**
 * Get container logs (returns process for streaming)
 */
export function tailLogs(follow: boolean = true, lines: number = 100): ChildProcess {
  const configDir = getExpandedConfigDir();
  const runtime = getContainerRuntime();
 
  if (!runtime.composeCmd) {
    throw new Error('No compose tool available. Install Docker Compose or podman-compose.');
  }
  const [composeExe, ...composePrefix] = runtime.composeCmd;
 
  const args = [...composePrefix, 'logs'];
 
  if (follow) {
    args.push('-f');
  }
 
  args.push('--tail', String(lines));
 
  return spawn(composeExe, args, {
    cwd: configDir,
    stdio: 'inherit',
  });
}
 
/**
 * Get container logs (non-streaming)
 */
export function getLogs(lines: number = 100): DockerCommandResult {
  return runComposeCommand(['logs', '--tail', String(lines)]);
}
 
/**
 * Add a GitLab instance to configuration
 */
export function addInstance(instance: GitLabInstance): void {
  const instances = loadInstances();
 
  // Check if already exists
  const existingIndex = instances.findIndex((i) => i.host === instance.host);
  if (existingIndex >= 0) {
    instances[existingIndex] = instance;
  } else {
    instances.push(instance);
  }
 
  saveInstances(instances);
}
 
/**
 * Remove a GitLab instance from configuration
 */
export function removeInstance(host: string): boolean {
  const instances = loadInstances();
  const filteredInstances = instances.filter((i) => i.host !== host);
 
  if (filteredInstances.length === instances.length) {
    return false; // Instance not found
  }
 
  saveInstances(filteredInstances);
  return true;
}
 
/**
 * Initialize Docker configuration
 */
export function initDockerConfig(config: Partial<DockerConfig> = {}): DockerConfig {
  const fullConfig: DockerConfig = {
    ...DEFAULT_DOCKER_CONFIG,
    ...config,
  };
 
  // Save docker-compose.yml
  saveDockerCompose(fullConfig);
 
  // Write .env file with secrets (restricted permissions)
  saveEnvFile(fullConfig);
 
  // Save instances if provided; an OAuth deployment's compose file names the server's
  // instance list, so it exists from the start
  if (fullConfig.instances.length > 0) {
    saveInstances(fullConfig.instances);
  } else if (fullConfig.oauthEnabled) {
    saveServerInstances([]);
  }
 
  return fullConfig;
}
 
/**
 * Write .env file with secrets for docker-compose environment variable references.
 * File is created with 0600 permissions to limit exposure.
 */
export function saveEnvFile(config: DockerConfig): void {
  const configDir = getExpandedConfigDir();
 
  if (!existsSync(configDir)) {
    mkdirSync(configDir, { recursive: true });
  }
 
  const managed = new Map<string, string>();
 
  if (config.oauthSessionSecret) {
    managed.set('OAUTH_SESSION_SECRET', config.oauthSessionSecret);
  }
 
  if (config.oauthEnabled) {
    // The public URL chosen during setup; without one, local access on the published port.
    managed.set('OAUTH_ISSUER', config.oauthIssuer ?? `http://localhost:${config.port}`);
  }
 
  if (config.deploymentType === 'compose-bundle' && config.oauthEnabled) {
    // Generate a strong random postgres password for the bundled database
    managed.set('POSTGRES_PASSWORD', randomBytes(24).toString('base64url'));
  }
 
  if (config.deploymentType === 'external-db' && config.oauthEnabled && config.databaseUrl) {
    // The compose file references it; the URL carries the database password
    managed.set('OAUTH_STORAGE_POSTGRESQL_URL', envLiteralUrl(config.databaseUrl));
  }
 
  if (managed.size > 0) {
    const envPath = join(configDir, '.env');
    let existing = '';
    if (existsSync(envPath)) {
      // The mode applies only when the file is created: an existing .env is restricted
      // first, so its secrets never land in a file other accounts on the host can read.
      chmodSync(envPath, 0o600);
      existing = readFileSync(envPath, 'utf8');
    }
    writeFileSync(envPath, mergeEnvFile(existing, managed), { encoding: 'utf8', mode: 0o600 });
  }
}
 
/**
 * Generated secrets keep the value already written: a new session secret would end every
 * session, a new database password would not match the database initialized with the old.
 */
const GENERATED_ENV_KEYS = new Set(['OAUTH_SESSION_SECRET', 'POSTGRES_PASSWORD']);
 
/** Variable a `.env` line assigns, if any. */
function envLineKey(line: string): string | undefined {
  return /^\s*(?:export\s+)?([A-Za-z_]\w*)\s*=/.exec(line)?.[1];
}
 
/**
 * `.env` content with the `managed` entries set. Everything else (secrets named by instances,
 * OAuth application credentials added by hand, comments) is kept in place.
 */
export function mergeEnvFile(existing: string, managed: ReadonlyMap<string, string>): string {
  const written = new Set<string>();
  const lines = existing === '' ? [] : existing.replace(/\n$/, '').split('\n');
  const merged = lines.flatMap((line) => {
    const key = envLineKey(line);
    const value = key === undefined ? undefined : managed.get(key);
    if (key === undefined || value === undefined) return [line];
    // A repeated assignment of a managed key would override the value written here.
    if (written.has(key)) return [];
    written.add(key);
    return [GENERATED_ENV_KEYS.has(key) ? line : `${key}=${value}`];
  });
  for (const [key, value] of managed) {
    if (!written.has(key)) merged.push(`${key}=${value}`);
  }
  return merged.join('\n') + '\n';
}