"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.SecurityDownloadGuard = void 0;
const fs = __importStar(require("fs"));
const path = __importStar(require("path"));
const os = __importStar(require("os"));
const ToolsetGuard_1 = require("./toolset/ToolsetGuard");
class SecurityDownloadGuard {
    blockedPatterns = [
        /(^|\/)\.git(\/|$)/i,
        /(^|\/)node_modules(\/|$)/i,
        /\.(exe|dll|bat|cmd|ps1|scr|com)$/i,
        /(^|\/)__MACOSX(\/|$)/i,
        /(^|\/)\.env/i,
    ];
    validateUrl(url) {
        const trusted = [
            'https://skills.sh/',
            'https://clawhub.ai/',
            'https://mcpmarket.com/',
            'https://mcpservers.org/',
            'https://github.com/'
        ];
        const ok = trusted.some(t => url.startsWith(t));
        return ok
            ? { ok: true, blocked: [], warnings: [] }
            : { ok: false, blocked: [url], warnings: ['untrusted_source'] };
    }
    scanFileList(paths) {
        const blocked = paths.filter(p => this.blockedPatterns.some(rx => rx.test(p)));
        const warnings = [];
        if (paths.some(p => p.endsWith('.md') === false))
            warnings.push('non_markdown_content_detected');
        return { ok: blocked.length === 0, blocked, warnings };
    }
    scanExtractedDir(rootDir) {
        const all = [];
        const walk = (dir) => {
            for (const e of fs.readdirSync(dir, { withFileTypes: true })) {
                const full = `${dir}/${e.name}`;
                if (e.isDirectory())
                    walk(full);
                else
                    all.push(full.replace(`${rootDir}/`, ''));
            }
        };
        walk(rootDir);
        return this.scanFileList(all);
    }
    /**
     * Story 9.1 — fetch a URL into a quarantine directory and run the
     * existing scan pipeline before letting the caller move into `.catalog/`.
     *
     * Returns DownloadAndScanResult. Never throws. Caller is responsible
     * for moving `downloadedTo` into its final home after inspecting the
     * result.
     *
     * v1.4 supports single-file fetch only (markdown, YAML, JSON). Archive
     * unpacking (zip / tar) is deferred to v1.5 — for v1.4, sources serve
     * one manifest per import and we just trust the response body.
     */
    async downloadAndScan(url, targetDirOpt, opts = {}) {
        (0, ToolsetGuard_1.assertToolsetAllowed)('web', 'SecurityDownloadGuard.downloadAndScan');
        const errors = [];
        const warnings = [];
        const urlCheck = this.validateUrl(url);
        if (!urlCheck.ok) {
            return { ok: false, errors: ['untrusted_url'], warnings: urlCheck.warnings };
        }
        const targetDir = targetDirOpt || fs.mkdtempSync(path.join(os.tmpdir(), 'openlife-dl-'));
        fs.mkdirSync(targetDir, { recursive: true });
        const timeoutMs = opts.timeoutMs ?? 15000;
        const maxBytes = opts.maxBytes ?? 5 * 1024 * 1024; // 5 MB cap
        let body;
        try {
            const controller = new AbortController();
            const timer = setTimeout(() => controller.abort(), timeoutMs);
            const res = await fetch(url, { signal: controller.signal });
            clearTimeout(timer);
            if (!res.ok) {
                errors.push(`fetch_status_${res.status}`);
                return { ok: false, errors, warnings };
            }
            const contentLength = Number(res.headers.get('content-length') || '0');
            if (contentLength > maxBytes) {
                errors.push(`content_too_large:${contentLength}>max:${maxBytes}`);
                return { ok: false, errors, warnings };
            }
            body = await res.arrayBuffer();
            if (body.byteLength > maxBytes) {
                errors.push(`body_too_large:${body.byteLength}`);
                return { ok: false, errors, warnings };
            }
        }
        catch (err) {
            const msg = err instanceof Error ? err.message : String(err);
            errors.push(`fetch_exception:${msg}`);
            return { ok: false, errors, warnings };
        }
        // Choose a filename from the URL path (last segment, with fallback).
        let filename = path.basename(new URL(url).pathname) || 'download.bin';
        // Reject filenames that match blocked patterns (e.g. .exe, .dll).
        const fileScan = this.scanFileList([filename]);
        if (!fileScan.ok) {
            errors.push(`filename_blocked:${fileScan.blocked.join(',')}`);
            return { ok: false, errors, warnings: [...warnings, ...fileScan.warnings] };
        }
        const outPath = path.join(targetDir, filename);
        try {
            fs.writeFileSync(outPath, Buffer.from(body));
        }
        catch (err) {
            const msg = err instanceof Error ? err.message : String(err);
            errors.push(`write_exception:${msg}`);
            return { ok: false, errors, warnings };
        }
        // Re-scan the dir for defence in depth.
        const dirScan = this.scanExtractedDir(targetDir);
        if (!dirScan.ok) {
            errors.push(`dir_scan_blocked:${dirScan.blocked.join(',')}`);
            try {
                fs.unlinkSync(outPath);
            }
            catch { /* ignore */ }
            return { ok: false, errors, warnings: [...warnings, ...dirScan.warnings] };
        }
        return {
            ok: true,
            downloadedTo: outPath,
            bytesWritten: body.byteLength,
            errors,
            warnings: [...warnings, ...urlCheck.warnings, ...dirScan.warnings],
        };
    }
}
exports.SecurityDownloadGuard = SecurityDownloadGuard;
