/**
 * install/home-stub.mjs — per-task stubbed HOME builder (C54 R3 hardening).
 *
 * The detached install child runs with HOME=.aperant/tasks/<id>/install/home/
 * instead of the user's real HOME. This prevents credentials (~/.npmrc
 * auth tokens, ~/.cargo/credentials.toml, ~/.composer/auth.json, etc.)
 * from leaking into postinstall scripts.
 *
 * This module materializes the stubbed HOME by writing skeleton config
 * files that ONLY reference allowlisted registries. Any ecosystem that
 * reads a config from HOME gets the safe defaults; anything looking for
 * tokens finds nothing.
 *
 * Stubbed configs (all with always-auth=false / equivalents):
 *   - .npmrc               → registry=https://registry.npmjs.org/
 *                            always-auth=false
 *   - .cargo/config.toml   → [registries.crates-io] protocol = 'sparse'
 *   - .bundle/config       → BUNDLE_DISABLE_SHARED_GEMS: 'true'
 *   - pip.conf             → index-url = https://pypi.org/simple/
 *
 * Idempotent: if the homeDir already exists with the expected structure
 * we leave it alone. That's important because worktree-install is called
 * re-entrantly on retry.
 */
import { existsSync, mkdirSync, writeFileSync } from 'node:fs';
import { join, resolve } from 'node:path';
/**
 * Build (or refresh) the per-task stubbed HOME. Returns the absolute path.
 *
 * @param {{
 *   taskId: string,
 *   projectDir: string,
 *   allowlist?: string[] | null,
 * }} opts
 * @returns {{ homeDir: string, created: boolean }}
 */
export function buildStubbedHome({ taskId, projectDir }) {
    if (!taskId || !/^[a-zA-Z0-9_-]+$/.test(taskId)) {
        throw new Error(`buildStubbedHome: invalid taskId: ${taskId}`);
    }
    const homeDir = resolve(projectDir, '.aperant', 'tasks', taskId, 'install', 'home');
    const alreadyExists = existsSync(homeDir);
    mkdirSync(homeDir, { recursive: true });
    // 1. .npmrc — used by pnpm/npm/yarn-classic/bun for registry config.
    // `always-auth=false` explicitly disables token inheritance.
    writeFileSync(join(homeDir, '.npmrc'), [
        'registry=https://registry.npmjs.org/',
        'always-auth=false',
        // Prevent install scripts from prompting; non-interactive by default.
        'progress=false',
        '',
    ].join('\n'));
    // 2. .cargo/config.toml — sparse protocol (no credentials file read).
    const cargoDir = join(homeDir, '.cargo');
    mkdirSync(cargoDir, { recursive: true });
    writeFileSync(join(cargoDir, 'config.toml'), [
        '[registries.crates-io]',
        "protocol = 'sparse'",
        '',
        '[net]',
        '# Retry registry requests rather than silently stalling.',
        'retry = 2',
        '',
    ].join('\n'));
    // 3. .bundle/config — disable shared gems; non-interactive.
    const bundleDir = join(homeDir, '.bundle');
    mkdirSync(bundleDir, { recursive: true });
    writeFileSync(join(bundleDir, 'config'), ['---', "BUNDLE_DISABLE_SHARED_GEMS: 'true'", "BUNDLE_FROZEN: 'false'", ''].join('\n'));
    // 4. pip.conf — redirect to PyPI only.
    const pipDir = join(homeDir, '.config', 'pip');
    mkdirSync(pipDir, { recursive: true });
    writeFileSync(join(pipDir, 'pip.conf'), [
        '[global]',
        'index-url = https://pypi.org/simple/',
        'disable-pip-version-check = true',
        '',
    ].join('\n'));
    // Also write the Windows-style pip.ini for cross-platform fallbacks.
    writeFileSync(join(homeDir, 'pip.ini'), [
        '[global]',
        'index-url = https://pypi.org/simple/',
        'disable-pip-version-check = true',
        '',
    ].join('\n'));
    // 5. .gemrc — gem install should never prompt.
    writeFileSync(join(homeDir, '.gemrc'), ['---', 'gem: --no-document', 'install: --no-document', 'update: --no-document', ''].join('\n'));
    // 6. .composer/auth.json (empty) — prevents composer from picking up
    // auth creds from the user's real ~/.composer/.
    const composerDir = join(homeDir, '.composer');
    mkdirSync(composerDir, { recursive: true });
    writeFileSync(join(composerDir, 'auth.json'), '{}\n');
    return { homeDir, created: !alreadyExists };
}
//# sourceMappingURL=home-stub.mjs.map