Skip to content

A free, open-source alternative to Burp Suite: an intercepting proxy and web app security testing suite with Repeater, Intruder, Collaborator and a built-in OWASP ZAP scanner. Linux, AGPL-3.0.

89.0 KB
Raw Blame
package opensuite.engine;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import opensuite.core.Bytes;
import opensuite.core.Debug;
import opensuite.core.HttpMessage;
import opensuite.core.HttpService;
import opensuite.core.Issue;
import opensuite.core.LogEntry;
import opensuite.core.ScanTask;
import opensuite.core.SuiteContext;
import opensuite.spider.Cdp.JsonValue;

/**
 * Drives a crawl-then-audit against the ZAP engine and maps everything it finds
 * into Open Suite's own model: crawled traffic into the site map and live passive
 * audit, and every ZAP alert into an Open Suite {@link Issue} in the issue tree.
 *
 * <p>The ZAP engine does the detecting; this class is only the bridge, nothing of
 * ZAP's data model leaks into Open Suite beyond what is translated here.
 */
public final class ZapScanner {

    /** The engine context that mirrors the suite's target scope. */
    public static final String SCOPE_CONTEXT = "Open Suite scope";
    /**
     * The engine context that holds this scan's scope. Every scan has its own,
     * so scans running side by side never draw each other's boundaries.
     */
    private final String scopeContext = SCOPE_CONTEXT + " " + Long.toHexString(System.nanoTime());

    private final SuiteContext ctx;
    private final ZapApi api;
    private final java.util.concurrent.atomic.AtomicInteger imported;

    /** Drive the shared engine; the message-history cursor is the engine's. */
    public ZapScanner(SuiteContext ctx, ZapEngine engine) {
        this(ctx, engine.api(), engine.importedMessages());
    }

    public ZapScanner(SuiteContext ctx, ZapApi api) {
        this(ctx, api, new java.util.concurrent.atomic.AtomicInteger());
    }

    private ZapScanner(SuiteContext ctx, ZapApi api, java.util.concurrent.atomic.AtomicInteger imported) {
        this.ctx = ctx;
        this.api = api;
        this.imported = imported;
    }

    private java.util.List<String> avoid = java.util.List.of();

    /** Patterns of addresses this scan must not request, on top of the scope's own excludes. */
    public void setAvoid(java.util.List<String> patterns) {
        this.avoid = patterns == null ? java.util.List.of() : java.util.List.copyOf(patterns);
    }

    private java.util.Map<String, java.util.regex.Pattern> skipWhy = java.util.Map.of();
    private LoopCheck loops;
    /** What the scan left out under its own rules, by reason. Kept in the order found. */
    private final java.util.Map<String, java.util.Set<String>> skipped = new java.util.LinkedHashMap<>();

    /**
     * The same patterns with the reason each is there, so the scan can say
     * what it left out and why. Each reason takes the patterns that carry it.
     */
    public void setSkipRules(java.util.Map<String, String> patternToReason) {
        java.util.Map<String, java.util.regex.Pattern> why = new java.util.LinkedHashMap<>();
        if (patternToReason != null) for (java.util.Map.Entry<String, String> e : patternToReason.entrySet()) {
            try { why.put(e.getKey(), java.util.regex.Pattern.compile(e.getKey())); } catch (RuntimeException ignore) { }
            reasons.put(e.getKey(), e.getValue());
        }
        skipWhy = why;
        setAvoid(patternToReason == null ? null : new java.util.ArrayList<>(patternToReason.keySet()));
    }
    private final java.util.Map<String, String> reasons = new java.util.HashMap<>();

    /** The check that confirms a crawl loop before anything is skipped for one. Null for none. */
    public void setLoopCheck(LoopCheck check) { this.loops = check; }

    /** The reason a URL is one this scan leaves out under its own rules, or null when it is not. */
    String whySkipped(String url) {
        if (url == null) return null;
        if (loops != null && loops.isLoop(url)) return SessionGuard.WHY_LOOP;
        for (java.util.Map.Entry<String, java.util.regex.Pattern> e : skipWhy.entrySet())
            if (e.getValue().matcher(url).matches()) return reasons.get(e.getKey());
        return null;
    }

    private void noteSkipped(String url) {
        String why = whySkipped(url);
        if (why != null) skipped.computeIfAbsent(why, k -> new java.util.LinkedHashSet<>()).add(url);
    }

    /**
     * Settle any crawl loop among the URLs found so far. A confirmed loop is
     * excluded from then on, and the few of its URLs already found are taken
     * out of the engine's site tree, so they are neither counted nor audited.
     */
    private void checkLoops(String site, ScanTask task) {
        if (loops == null) return;
        try {
            java.util.List<String> urls = api.urls(site);
            for (LoopCheck.Finding f : loops.examine(site, urls)) {
                if (f.loop()) {
                    api.excludeFromContext(scopeContext, f.pattern());
                    task.bar(f.pattern());
                    task.log("Crawl loop confirmed: " + f.sample() + " returns the same response as " + f.shorter()
                            + ". URLs on " + f.site() + " that repeat /" + f.name() + "/ three or more times are skipped from now on.");
                } else {
                    task.log("Not a crawl loop: " + f.sample() + " returns a different response from " + f.shorter()
                            + ". URLs that repeat /" + f.name() + "/ are kept.");
                }
                ctx.taskChanged(task);
            }
            for (String u : urls) {
                if (!loops.isLoop(u) || !dropped.add(u)) continue;
                noteSkipped(u);
                try { api.deleteSiteNode(u); } catch (Exception ignore) { /* it stays in the tree, out of scope */ }
            }
        } catch (Exception e) {
            Debug.log("crawl loop check failed: " + e);
        }
    }
    private final java.util.Set<String> dropped = new java.util.HashSet<>();

    /** How many URLs of one reason the log lists before it gives the count of the rest. */
    private static final int LISTED = 100;

    /** Say in the task's log what the crawl left out under the scan's own rules, URL by URL. */
    private void reportSkipped(ScanTask task) {
        int total = 0;
        java.util.List<String> counts = new java.util.ArrayList<>();
        for (java.util.Map.Entry<String, java.util.Set<String>> e : skipped.entrySet()) {
            total += e.getValue().size();
            counts.add(e.getValue().size() + " " + e.getKey());
        }
        if (total == 0) {
            if (!skipWhy.isEmpty() || loops != null) task.log("No URL was skipped under this scan's rules.");
            return;
        }
        task.log("Skipped " + total + " URL(s) under this scan's rules: " + String.join(", ", counts) + ". They are listed below.");
        for (java.util.Map.Entry<String, java.util.Set<String>> e : skipped.entrySet()) {
            int n = 0;
            for (String url : e.getValue()) {
                if (++n > LISTED) { task.log("Skipped (" + e.getKey() + "): " + (e.getValue().size() - LISTED) + " more"); break; }
                task.log("Skipped (" + e.getKey() + "): " + url);
            }
        }
    }

    /**
     * Say when a crawl was ended by its time limit and not by running out of
     * pages, and whether it was still finding new ones: that is a crawl cut
     * short, and what it did not reach is not audited.
     *
     * <p>Open Suite ends the crawl at the limit itself, so that this is known
     * and not guessed from how long the crawl ran. The engine cannot say: its
     * crawler is ended by a limit of N minutes only once N + 1 whole minutes
     * have gone, and one that ran out of pages in that last minute looks the
     * same afterwards as one that was stopped.
     *
     * @param stoppedAtLimit the crawl was still running at its limit and was stopped there
     */
    static String timeLimitNote(String what, int limitMin, boolean stoppedAtLimit, long sinceNewMs) {
        if (limitMin <= 0 || !stoppedAtLimit) return null;
        String limit = limitMin + (limitMin == 1 ? " minute" : " minutes");
        return sinceNewMs < 60_000
                ? what + " stopped at its time limit (" + limit + ") while still discovering new locations. Coverage is incomplete: "
                        + "use a deeper scan configuration to continue."
                : what + " stopped at its time limit (" + limit + "). No new location was discovered in its final minute.";
    }

    /** One request to audit on its own. */
    public record Item(HttpService service, HttpMessage request) {}

    /**
     * Audit the given requests and nothing else: each is sent through the
     * engine so that it knows the request, then attacked on its own without
     * following anything under it. With {@code active} false the requests are
     * only sent, and the engine's passive rules read the answers.
     */
    public void auditRequests(java.util.List<Item> items, boolean active, ScanConfig cfg, ScanTask task) throws Exception {
        java.util.List<String> held = new java.util.ArrayList<>();
        for (Item i : items) held.add(i.service().url());
        gateSites = held;
        try {
            if (active) {
                try {
                    int rules = 0;
                    for (JsonValue s : api.activeScanners()) if ("true".equals(ZapApi.str(s, "enabled"))) rules++;
                    task.setAuditItemsTotal(rules);
                    api.setAllAttackStrength(cfg.attackStrength());
                    api.setAllAlertThreshold(cfg.alertThreshold());
                    api.setInjectableParams(cfg.injectableMask());
                    api.setInjectableRpc(cfg.rpcMask());
                    api.setActiveDelayMs(cfg.delayMs());
                    api.setActiveMaxScanDuration(cfg.scanDurationMin());
                    applyAuditOptions(cfg);
                } catch (Exception ignore) { /* use the engine defaults */ }
            }
            Map<String, Issue.Severity> seen = new HashMap<>();
            int done = 0;
            task.setItemsTotal(100);
            for (Item item : items) {
                if (task.cancelled()) break;
                HttpMessage req = item.request().copy();
                String url = item.service().url() + req.requestTarget();
                // Findings are taken for this address only, not the whole host.
                String at = url.contains("?") ? url.substring(0, url.indexOf('?')) : url;
                // The engine wants the whole address on the request line.
                req.setRequestTarget(url);
                req.removeHeader("Accept-Encoding");
                req.updateContentLength();
                task.log((active ? "Auditing " : "Passively scanning ") + req.method() + " " + url);
                ctx.taskChanged(task);
                try {
                    api.sendRequest(Bytes.str(req.raw()));
                } catch (Exception e) {
                    task.log("The engine could not send the request: " + e.getMessage());
                    done++;
                    continue;
                }
                drain("audit", false, task);
                if (active) {
                    final String aid;
                    try {
                        aid = api.ascanScanOne(url, req.method(), req.bodyText());
                    } catch (Exception e) {
                        task.log("The engine did not audit the request: " + e.getMessage());
                        done++;
                        continue;
                    }
                    boolean paused = false;
                    RuleFeed rules = new RuleFeed(api, aid, task.rules());
                    rules.pull();   // at once: the add-on listens to the scan from its first request or from this
                    ScanGate.running(task.number, aid == null || aid.isBlank() ? null : "A" + aid);
                    while (aid != null && !aid.isBlank()) {
                        if (task.cancelled()) { stopQuietly(() -> api.ascanStop(aid)); break; }
                        if (task.state() == ScanTask.State.PAUSED) {
                            if (!paused) {
                                ScanGate.hold(api, task.number, List.of(item.service().url()));   // a pause sends nothing more
                                stopQuietly(() -> api.ascanPause(aid));
                                paused = true;
                            }
                            Thread.sleep(500);
                            continue;
                        }
                        if (paused) { stopQuietly(() -> api.ascanResume(aid)); ScanGate.release(api, task.number); paused = false; }
                        int st = api.ascanStatus(aid);
                        task.setItemsDone(Math.min(100, (done * 100 + Math.max(0, st)) / items.size()));
                        rules.pull();
                        pullAlerts(at, task, seen);
                        drain("audit", false, task);
                        ctx.taskChanged(task);
                        if (st >= 100) break;
                        Thread.sleep(1000);
                    }
                    rules.pull();
                } else {
                    // Give the passive rules a moment to read the answer.
                    for (int i = 0; i < 6 && !task.cancelled(); i++) {
                        Thread.sleep(500);
                        pullAlerts(at, task, seen);
                    }
                }
                pullAlerts(at, task, seen, true);
                drain("audit", false, task);
                done++;
                task.setItemsDone(Math.min(100, done * 100 / items.size()));
                ctx.taskChanged(task);
            }
            task.log(task.cancelled() ? "Audit stopped"
                    : (active ? "Audit" : "Passive scan") + " finished: " + seen.size() + " finding(s)");
        } finally {
            task.setState(ScanTask.State.FINISHED);
            ctx.taskChanged(task);
        }
    }

    /**
     * Hand the scan's own scope to the engine as a context, so the crawl and
     * the audit are bound to the scan's sites whatever the project's scope
     * is. Returns the context id.
     * Fails rather than falling back: a scan that cannot be bound to the
     * scope must not run unbounded.
     */
    private String applyScope(java.util.List<Seed> seeds, ScanTask task) throws Exception {
        // One scan at a time: the engine loses a context when two are drawn up at the same moment.
        synchronized (SCOPE_LOCK) { return applyScopeNow(seeds, task); }
    }

    private static final Object SCOPE_LOCK = new Object();

    private String applyScopeNow(java.util.List<Seed> seeds, ScanTask task) throws Exception {
        try { api.removeContext(scopeContext); } catch (Exception ignore) { /* none yet */ }
        String id = api.newContext(scopeContext);
        if (id == null || id.isBlank()) throw new Exception("the engine did not create the scope context");
        int inc = 0, exc = 0;
        java.util.List<String> included = new ArrayList<>(), excluded = new ArrayList<>();
        opensuite.core.Scope scope = scopeOf(seeds);
        for (opensuite.core.Scope.Rule r : scope.include()) {
            if (!r.enabled) continue;
            String re = r.urlRegex();
            if (re != null) { api.includeInContext(scopeContext, re); included.add(re); inc++; }
        }
        if (inc == 0) {
            // No usable include rule: bind the scan to the targets themselves.
            for (Seed seed : seeds) {
                for (String p : opensuite.core.Scope.sitePrefixes(seed.service())) {
                    String re = opensuite.core.Scope.Rule.prefix(p, false).urlRegex();
                    if (re != null) { api.includeInContext(scopeContext, re); included.add(re); inc++; }
                }
            }
        }
        for (opensuite.core.Scope.Rule r : scope.exclude()) {
            if (!r.enabled) continue;
            String re = r.urlRegex();
            if (re != null) { api.excludeFromContext(scopeContext, re); excluded.add(re); exc++; }
        }
        // Links that would end the scan's own session are left alone.
        for (String re : avoid) { api.excludeFromContext(scopeContext, re); excluded.add(re); exc++; }
        api.setContextInScope(scopeContext, true);
        // The task knows its own limits, so what is shown of the scan can leave out what the scan refused.
        task.setReach(included, excluded);
        task.log("Scope applied to the engine: " + inc + " include rule(s), " + exc + " exclude rule(s)"
                + (avoid.isEmpty() ? "" : ", including the pages excluded from this scan"));
        return id;
    }

    /** One seed to crawl: the target service and the full seed URL. */
    public record Seed(HttpService service, String url) {}

    /** Single-seed convenience (the Spider button), delegating to the list form. */
    public void crawlAndAudit(HttpService seed, String seedUrl, boolean thenAudit,
                              ScanConfig cfg, ScanTask crawlTask) throws Exception {
        crawlAndAudit(java.util.List.of(new Seed(seed, seedUrl)), thenAudit, cfg, crawlTask);
    }

    /**
     * Crawl every seed, then (when {@code thenAudit}) audit what was found, all
     * as one job: one crawl task and one audit task. The seeds are processed one
     * at a time on this single thread, so the configured thread count applies
     * once to the engine rather than being multiplied across targets.
     *
     * @param crawlTask a LIVE_ACTIVE task to report crawl progress on
     */
    public void crawlAndAudit(java.util.List<Seed> seeds, boolean thenAudit,
                              ScanConfig cfg, ScanTask crawlTask) throws Exception {
        java.util.List<String> at = new java.util.ArrayList<>();
        for (Seed s : seeds) at.add(s.service().url());
        gateSites = at;
        // ---- crawl each seed into the one task ---------------------------
        try {
            api.setSpiderMaxDepth(cfg.crawlDepth());
            api.setSpiderMaxDuration(cfg.crawlDurationMin());
            api.setSpiderProcessForms(cfg.submitForms());
            ScanConfig.Options o = cfg.more();
            // A site map with a limit is read here, not by the engine, which takes all of one.
            api.setSpiderSources(o.robots(), o.sitemap() && o.sitemapMax() <= 0, o.hiddenLinks());
            api.setUserAgent(o.userAgent());
            api.setTimeoutSecs(timeoutFor(o.crawlTimeoutSecs()));
        } catch (Exception ignore) { /* use the engine defaults */ }

        // Everything the engine does in this job stays inside the suite scope.
        final String contextId = applyScope(seeds, crawlTask);
        ctx.taskChanged(crawlTask);

        // Every site is in the task from the start, each with its own progress.
        final opensuite.core.SiteProgress sites = crawlTask.sites();
        for (Seed seed : seeds) sites.add(seed.service().url(), seed.url());
        final boolean several = seeds.size() > 1;
        // The thread setting is the scan's, not each site's: sites crawled together share it.
        if (several && crawlThreads > 0) {
            try { api.setSpiderThreads(Math.max(1, crawlThreads / seeds.size())); } catch (Exception ignore) { /* the setting as it was */ }
        }

        // ---- crawl every site together ------------------------------------
        // The engine's crawler takes several sites at once, so each is found in the
        // first moments of the scan. What it finds is audited one site at a time.
        java.util.List<Crawl> crawls = new ArrayList<>();
        java.util.List<Seed> ready = new ArrayList<>();   // seeds whose crawl is over, in the order they got there
        for (Seed seed : seeds) {
            if (crawlTask.cancelled()) break;
            String site = seed.service().url();
            Crawl c = new Crawl(seed);
            crawls.add(c);
            sites.set(site, opensuite.core.SiteProgress.Status.CRAWLING, "");
            if (!several) {
                // A scan of one site that cannot start has nothing else to do: the failure is the scan's.
                api.accessUrl(seed.url());
                readSitemap(site, cfg.more(), crawlTask);
                // 0 = no per-node child limit: crawl every in-scope link within the
                // depth budget, instead of stopping after 20 links per page.
                c.sid = api.spiderScan(seed.url(), 0, scopeContext);
                c.began = c.lastNew = System.currentTimeMillis();
                if (c.sid == null || c.sid.isBlank()) { c.sid = null; c.error = "The engine did not start the crawl"; }
                continue;
            }
            crawlTask.log("Crawling " + seed.url());
            // Each site is started on a thread of its own: the first fetch of one that is slow
            // or does not answer takes its time, and the others are not kept waiting for it.
            Thread starter = new Thread(() -> {
                try {
                    api.accessUrl(seed.url());
                    if (crawlTask.cancelled()) { c.error = "Stopped"; return; }
                    readSitemap(site, cfg.more(), crawlTask);
                    String sid = api.spiderScan(seed.url(), 0, scopeContext);
                    if (sid == null || sid.isBlank()) { c.error = "The engine did not start the crawl"; return; }
                    c.began = c.lastNew = System.currentTimeMillis();
                    c.sid = sid;
                } catch (Exception e) {
                    c.error = String.valueOf(e.getMessage());
                }
            }, "crawl-start");
            starter.setDaemon(true);
            starter.start();
        }
        ctx.taskChanged(crawlTask);
        // One crawl can be held by itself. Several are held by their sites.
        ScanGate.running(crawlTask.number, crawls.size() == 1 && crawls.get(0).sid != null ? "S" + crawls.get(0).sid : null);
        long crawlLimit = cfg.crawlDurationMin() > 0 ? cfg.crawlDurationMin() * 60_000L : Long.MAX_VALUE;
        boolean zapPaused = false;
        int lastLoc = -1;
        while (true) {
            // A crawl still being started is neither running nor over. One that could not be started has failed.
            java.util.List<Crawl> active = new ArrayList<>();
            boolean starting = false;
            for (Crawl c : crawls) {
                if (c.over) continue;
                if (c.sid != null) { active.add(c); continue; }
                if (c.error == null) { starting = true; continue; }
                c.over = true;
                String site = c.seed.service().url();
                if (!crawlTask.cancelled()) {
                    crawlTask.log("The engine did not crawl " + c.seed.url() + ": " + c.error);
                    sites.set(site, opensuite.core.SiteProgress.Status.FAILED, c.error);
                }
            }
            if (active.isEmpty() && !starting) break;
            if (active.isEmpty()) {
                if (crawlTask.cancelled()) break;
                ctx.taskChanged(crawlTask);
                Thread.sleep(500);
                continue;
            }
            // Stop the moment the task is deleted, so nothing keeps crawling.
            if (crawlTask.cancelled()) { for (Crawl c : active) { final String id = c.sid; stopQuietly(() -> api.spiderStop(id)); } break; }
            // Honour a paused task by pausing the engine's crawls too.
            if (crawlTask.state() == ScanTask.State.PAUSED) {
                if (!zapPaused) {
                    java.util.List<String> held = new ArrayList<>();
                    for (Crawl c : active) held.add(c.seed.service().url());
                    ScanGate.hold(api, crawlTask.number, held);   // a pause sends nothing more
                    for (Crawl c : active) { final String id = c.sid; stopQuietly(() -> api.spiderPause(id)); }
                    zapPaused = true;
                }
                Thread.sleep(500);
                continue;
            }
            if (zapPaused) {
                for (Crawl c : active) { final String id = c.sid; stopQuietly(() -> api.spiderResume(id)); }
                ScanGate.release(api, crawlTask.number);
                zapPaused = false;
            }
            long now = System.currentTimeMillis();
            for (Crawl c : active) {
                final String id = c.sid;
                String site = c.seed.service().url();
                opensuite.core.SiteProgress.Site mine = sites.get(site);
                if (mine != null && mine.skipAsked()) {
                    stopQuietly(() -> api.spiderStop(id));
                    c.over = true;
                    continue;
                }
                int st = api.spiderStatus(id);
                int own = locations(site);
                if (own >= 0) {
                    sites.locations(site, own);
                    if (own > c.lastLoc) { c.lastNew = now; c.lastLoc = own; }
                }
                checkLoops(site, crawlTask);
                boolean atLimit = false;
                if (st < 100 && now - c.began >= crawlLimit) {
                    // Still crawling at its time limit: it is stopped here, at the limit as stated.
                    stopQuietly(() -> api.spiderStop(id));
                    atLimit = true;
                }
                // The limits of a custom configuration: how many locations, and how many requests.
                String capped = null;
                if (st < 100 && !atLimit) {
                    capped = crawlCap(cfg.more(), own, cfg.more().maxRequests() > 0 ? requestsTo(site) : 0);
                    if (capped != null) stopQuietly(() -> api.spiderStop(id));
                }
                if (st >= 100 || atLimit || capped != null) {
                    c.over = true;
                    String cut = capped != null ? capped : timeLimitNote("Crawl", cfg.crawlDurationMin(), atLimit, now - c.lastNew);
                    if (cut != null) crawlTask.log(several ? label(c.seed) + ": " + cut : cut);
                    try { for (String u : api.spiderOutOfScope(id)) noteSkipped(u); } catch (Exception ignore) { /* the list is then shorter */ }
                    readWsdls(site, crawlTask);
                    if (cfg.more().graphqlCommon()) tryGraphql(site, crawlTask);
                    if (several && c.lastLoc <= 0) {
                        // Nothing came back from it at all: there is nothing to crawl further or to audit.
                        crawlTask.log("No page could be fetched from " + label(c.seed) + ": it is left out of the rest of the scan");
                        sites.set(site, opensuite.core.SiteProgress.Status.FAILED, "No page could be fetched from the site");
                    } else {
                        ready.add(c.seed);
                        if (several) sites.set(site, opensuite.core.SiteProgress.Status.QUEUED,
                                cfg.ajaxSpider() ? "Crawled. Queued for its browser crawl, which the engine runs one site at a time" : "Crawled. Queued for its audit");
                    }
                }
            }
            drain("crawl", true, crawlTask);
            int loc = totalLocations(seeds);
            if (loc >= 0 && loc != lastLoc) {
                crawlTask.setDiscoveredLocations(loc);
                crawlTask.log("Discovered " + loc + " location(s)");
                lastLoc = loc;
            }
            ctx.taskChanged(crawlTask);
            // A crawl with a limit on locations or requests is looked at more often, to stop nearer the limit.
            Thread.sleep(cfg.more().maxLocations() > 0 || cfg.more().maxRequests() > 0 ? 200 : 1000);
        }
        ScanGate.running(crawlTask.number, null);
        drain("crawl", true, crawlTask);

        // ---- then the browser crawl, one site at a time, and the audits together ----
        // The engine runs one browser crawl at a time, so the sites take that in
        // turn, in the order their crawls ended. A site's audit starts the moment
        // its own crawling is over and runs beside the others': the scan does not
        // wait for one site to be audited before it starts on the next.
        final ScanTask auditTask = crawlTask;
        final Audits audits = new Audits(seeds.size(), several, cfg, contextId, auditTask);
        try {
            for (int turn = 0; turn < ready.size(); turn++) {
                Seed seed = ready.get(turn);
                String site = seed.service().url();
                boolean lastCrawl = turn == ready.size() - 1;
                if (crawlTask.cancelled()) break;
                if (skipped(sites, site, crawlTask)) { audits.passed(); continue; }

                // AJAX crawl (headless Chromium) for JavaScript-rendered routes.
                if (cfg.ajaxSpider()) {
                    sites.set(site, opensuite.core.SiteProgress.Status.CRAWLING, "Browser crawl");
                    ctx.taskChanged(crawlTask);
                    runAjaxCrawl(seed.url(), contextId, cfg, crawlTask, sites.get(site), audits);
                }
                drain("crawl", true, crawlTask);
                checkLoops(site, crawlTask);
                sites.locations(site, locations(site));
                int kept = totalLocations(seeds);
                if (kept >= 0) crawlTask.setDiscoveredLocations(kept);
                if (crawlTask.cancelled()) break;
                if (skipped(sites, site, crawlTask)) { audits.passed(); continue; }
                opensuite.core.SiteProgress.Site mine = sites.get(site);
                if (several) crawlTask.log("Crawl finished: " + label(seed) + ", "
                        + (mine == null ? 0 : mine.locations()) + " location(s)");
                if (lastCrawl) {
                    reportSkipped(crawlTask);
                    // With several sites each has said so itself, and the task's requests by now include audits.
                    if (!several) crawlTask.log("Crawl finished: " + crawlTask.requests() + " request(s)");
                }
                sites.set(site, thenAudit ? opensuite.core.SiteProgress.Status.CRAWLED : opensuite.core.SiteProgress.Status.FINISHED, "");
                ctx.taskChanged(crawlTask);
                if (!thenAudit) { audits.passed(); continue; }
                audits.add(seed);
                audits.poll();
            }
            // Every crawl is over: the audits still running are seen through.
            while (audits.busy()) {
                if (!audits.poll()) break;
                Thread.sleep(auditTask.state() == ScanTask.State.PAUSED ? 500 : 2000);
            }
            if (ready.isEmpty() && !crawlTask.cancelled()) {
                // No site could be crawled: the reasons are in the log, one a site.
                crawlTask.log("Crawl finished: " + crawlTask.requests() + " request(s)");
            }
            if (crawlTask.cancelled()) {
                audits.stopAll();
                crawlTask.log(audits.setUp ? "Audit stopped" : "Crawl stopped");
            } else if (thenAudit && audits.setUp) {
                // The findings as the task lists them, not every alert the engine raised for them.
                String src = "Scan " + auditTask.number;
                int finds = 0;
                for (Issue is : ctx.issues()) if (is.foundBy(src)) finds++;
                auditTask.log("Audit finished: " + finds + " finding(s)");
            }
        } finally {
            audits.stopAll();
            sites.stopRest();
            auditTask.setState(ScanTask.State.FINISHED);
            ctx.taskChanged(auditTask);
        }
    }

    /** The most sites audited at the same moment. Others wait for one to end. */
    static final int AUDITS_AT_ONCE = 6;

    /** One site's audit as the engine runs it. */
    private static final class Audit {
        final Seed seed;
        final String aid;
        final RuleFeed rules;
        boolean paused, over;
        int status;
        Audit(Seed seed, String aid, RuleFeed rules) { this.seed = seed; this.aid = aid; this.rules = rules; }
    }

    /**
     * The audits of one scan, run side by side. A site is added when its crawl
     * is over; {@link #poll} is called every second or two for as long as any
     * is running, from the loop that is crawling other sites or from the one
     * that waits for the audits to end.
     */
    private final class Audits {
        private final int total;
        private final boolean several;
        private final ScanConfig cfg;
        private final String contextId;
        private final ScanTask task;
        private final opensuite.core.SiteProgress sites;
        private final java.util.List<Audit> running = new ArrayList<>();
        private final java.util.ArrayDeque<Seed> waiting = new java.util.ArrayDeque<>();
        private final Map<String, Issue.Severity> seen = new HashMap<>();
        boolean setUp;
        private int done;            // sites with nothing more to audit: audited, skipped, failed, or never to be
        private boolean held;
        // Throttled proof-of-life for the event log. The active-scan
        // percentage can sit at 0 for a while as the engine builds its
        // attack queue, so - like the crawl's "Discovered N locations" - the
        // audit reports what it has done so far whenever the numbers move, at
        // most about once every 15s, so a flat bar never reads as hung.
        private long lastProgressLog;
        private int lastLoggedReq = -1, lastLoggedFind = -1;

        Audits(int total, boolean several, ScanConfig cfg, String contextId, ScanTask task) {
            this.total = Math.max(1, total);
            this.several = several;
            this.cfg = cfg;
            this.contextId = contextId;
            this.task = task;
            this.sites = task.sites();
        }

        boolean busy() { return !running.isEmpty() || !waiting.isEmpty(); }

        /** A site that will not be audited: it still counts towards the whole. */
        void passed() { done++; }

        /** Queue a site's audit. It starts at the next poll if fewer than the most allowed are running. */
        void add(Seed seed) {
            waiting.add(seed);
            if (running.size() >= AUDITS_AT_ONCE)
                sites.set(seed.service().url(), opensuite.core.SiteProgress.Status.QUEUED, "Crawled. Queued for its audit: " + AUDITS_AT_ONCE + " sites are audited at once");
        }

        private void setUp() {
            if (setUp) return;
            setUp = true;
            // One job is one task, as in the reference: the card that said it was
            // crawling now says it is auditing and carries the issue counts.
            task.setType(ScanTask.Type.AUDIT);
            try {
                int rules = 0;
                for (JsonValue s : api.activeScanners())
                    if ("true".equals(ZapApi.str(s, "enabled"))) rules++;
                task.setAuditItemsTotal(rules);
            } catch (Exception ignore) { /* leave at 0 if ZAP cannot report it */ }
            // Apply the tier's audit settings once before starting. One scan at a time: two scans
            // writing the engine's rule settings at the same moment lose some of each other's writes.
            try { synchronized (AUDIT_SETUP_LOCK) {
                api.setAllAttackStrength(cfg.attackStrength());
                api.setAllAlertThreshold(cfg.alertThreshold());
                api.setInjectableParams(cfg.injectableMask());
                api.setInjectableRpc(cfg.rpcMask());
                api.setActiveDelayMs(cfg.delayMs());
                api.setActiveMaxScanDuration(cfg.scanDurationMin());
                applyAuditOptions(cfg);
                // The thread setting is the scan's: sites audited together share it.
                if (several && crawlThreads > 0)
                    api.setActiveThreadPerHost(Math.max(2, crawlThreads / Math.min(total, AUDITS_AT_ONCE)));
            } } catch (Exception ignore) { /* use the engine defaults */ }
            task.log("Auditing with the ZAP active rules (" + cfg.name()
                    + ": strength " + cfg.attackStrength() + ", threshold " + cfg.alertThreshold() + ")...");
            ctx.taskChanged(task);
        }

        private void start(Seed seed) {
            String site = seed.service().url();
            if (skipped(sites, site, task)) { done++; return; }
            setUp();
            // The audit is bound to the scope context: only what the crawl
            // found inside it is attacked. Nothing crawled for this seed, or
            // a seed the scope no longer covers, is skipped with a note
            // rather than driving the loop with an id the engine rejected.
            String aid;
            try {
                aid = api.ascanScan(seed.url(), contextId);
            } catch (Exception e) {
                task.log("Nothing to audit for " + label(seed) + ": " + e.getMessage());
                sites.set(site, opensuite.core.SiteProgress.Status.FINISHED, "Nothing to audit");
                done++;
                return;
            }
            if (aid == null || aid.isBlank()) {
                task.log("Nothing to audit for " + label(seed)
                        + (task.discoveredLocations() <= 0 ? " (no crawlable content found)" : ""));
                sites.set(site, opensuite.core.SiteProgress.Status.FINISHED, "Nothing to audit");
                done++;
                return;
            }
            sites.set(site, opensuite.core.SiteProgress.Status.AUDITING, "");
            if (several) task.log("Auditing " + label(seed));
            Audit a = new Audit(seed, aid, new RuleFeed(api, aid, task.rules()));
            a.rules.pull();   // at once: the add-on listens to the scan from its first request or from this
            running.add(a);
            mark();
        }

        /** One audit can be held by itself. Several are held by their sites. */
        private void mark() {
            ScanGate.running(task.number, running.size() == 1 ? "A" + running.get(0).aid : null);
        }

        /** Stop whatever is still running: the task was deleted, or the scan is ending. */
        void stopAll() {
            for (Audit a : running) { final String id = a.aid; stopQuietly(() -> api.ascanStop(id)); }
            running.clear();
            waiting.clear();
            if (held) { ScanGate.release(api, task.number); held = false; }
            ScanGate.running(task.number, null);
        }

        /**
         * Look at every running audit once: follow a pause or a skip, take its
         * new findings and requests, and close it when it is done. Starts the
         * audits that were waiting for room. False when the task was deleted.
         */
        boolean poll() throws Exception {
            if (task.cancelled()) { stopAll(); return false; }
            if (task.state() == ScanTask.State.PAUSED) {
                if (!held && !running.isEmpty()) {
                    java.util.List<String> at = new ArrayList<>();
                    for (Audit a : running) at.add(a.seed.service().url());
                    ScanGate.hold(api, task.number, at);   // a pause sends nothing more
                    for (Audit a : running) { final String id = a.aid; stopQuietly(() -> api.ascanPause(id)); }
                    held = true;
                }
                return true;
            }
            if (held) {
                for (Audit a : running) { final String id = a.aid; stopQuietly(() -> api.ascanResume(id)); }
                ScanGate.release(api, task.number);
                held = false;
            }
            while (!waiting.isEmpty() && running.size() < AUDITS_AT_ONCE) start(waiting.poll());
            if (running.isEmpty()) { progress(); return true; }

            for (Audit a : new ArrayList<>(running)) {
                final String id = a.aid;
                String site = a.seed.service().url();
                opensuite.core.SiteProgress.Site own = sites.get(site);
                boolean left = own != null && own.skipAsked();
                if (left) stopQuietly(() -> api.ascanStop(id));
                else a.status = api.ascanStatus(id);
                a.rules.pull();
                pullAlerts(site, task, seen, left || a.status >= 100);
                if (!left && a.status < 100) continue;
                running.remove(a);
                done++;
                if (left) {
                    task.log("Skipped the rest of " + label(a.seed) + ", as asked");
                    sites.set(site, opensuite.core.SiteProgress.Status.SKIPPED, "Skipped during its audit");
                } else {
                    sites.set(site, opensuite.core.SiteProgress.Status.FINISHED, "");
                    if (several) task.log("Audit finished: " + label(a.seed));
                }
                mark();
            }
            drain("audit", false, task);
            progress();
            long nowMs = System.currentTimeMillis();
            int req = task.requests();
            // De-duplicated findings this task raised, not the raw alert count.
            String asrc = "Scan " + task.number;
            int finds = 0;
            for (Issue is : ctx.issues()) if (is.foundBy(asrc)) finds++;
            if (!running.isEmpty() && nowMs - lastProgressLog >= 15000 && (req != lastLoggedReq || finds != lastLoggedFind)) {
                String what = running.size() == 1 ? label(running.get(0).seed) : running.size() + " sites";
                task.log("Auditing " + what + ": " + req + " request(s), " + finds + " finding(s) so far");
                lastProgressLog = nowMs;
                lastLoggedReq = req;
                lastLoggedFind = finds;
            }
            ctx.taskChanged(task);
            return true;
        }

        /** The whole scan's progress: the sites done, and how far those being audited have got. */
        private void progress() {
            if (!setUp) return;
            long sum = (long) done * 100;
            for (Audit a : running) sum += Math.max(0, Math.min(100, a.status));
            task.setItemsTotal(100);
            task.setItemsDone((int) Math.min(100, sum / total));
        }
    }

    /** A site as a line of the log names it: its host, with its port when that is not the usual one. */
    /** The audit's own timeout, User-Agent and list of parameters to leave alone. */
    private void applyAuditOptions(ScanConfig cfg) throws Exception {
        ScanConfig.Options o = cfg.more();
        api.setUserAgent(o.userAgent());
        api.setTimeoutSecs(timeoutFor(o.auditTimeoutSecs()));
        api.setSkippedParams(o.skips());
    }

    /**
     * Whether the address asks a service for its WSDL the usual way: {@code ?wsdl} or {@code ?singleWsdl}.
     * The engine's crawler knows a WSDL only by an address ending in {@code .wsdl}, and reads those itself.
     */
    public static boolean asksForWsdl(String url) {
        int q = url == null ? -1 : url.indexOf('?');
        if (q < 0) return false;
        String query = url.substring(q + 1);
        int hash = query.indexOf('#');
        if (hash >= 0) query = query.substring(0, hash);
        for (String part : query.split("&")) {
            String name = part.contains("=") ? part.substring(0, part.indexOf('=')) : part;
            if (name.equalsIgnoreCase("wsdl") || name.equalsIgnoreCase("singleWsdl")) return part.indexOf('=') < 0 || part.endsWith("=");
        }
        return false;
    }

    /** Where a GraphQL endpoint usually is. */
    static final String[] GRAPHQL_PATHS = {"/graphql", "/api/graphql", "/v1/graphql", "/v2/graphql", "/api/v1/graphql",
            "/graphql/v1", "/graphiql", "/query", "/api/query", "/graphql.php", "/graphql/console", "/gql", "/api/gql"};

    /** After a site's crawl: the usual GraphQL addresses are asked for a schema, whether or not a page links to them. */
    private void tryGraphql(String site, ScanTask task) {
        String base = site.endsWith("/") ? site.substring(0, site.length() - 1) : site;
        for (String path : GRAPHQL_PATHS) {
            if (task.cancelled()) return;
            if (api.importGraphql(base + path)) task.log("Found a GraphQL endpoint at " + base + path + " and requested what its schema describes");
        }
    }

    /** The addresses a site map lists, in its order: the {@code loc} of each entry. */
    public static java.util.List<String> sitemapLocations(String xml) {
        java.util.List<String> out = new ArrayList<>();
        if (xml == null) return out;
        java.util.regex.Matcher m = java.util.regex.Pattern.compile("(?is)<loc>\\s*(?:<!\\[CDATA\\[)?\\s*(.*?)\\s*(?:\\]\\]>)?\\s*</loc>").matcher(xml);
        while (m.find()) {
            String u = m.group(1).replace("&amp;", "&").replace("&apos;", "'").replace("&quot;", "\"").replace("&lt;", "<").replace("&gt;", ">");
            if (!u.isBlank()) out.add(u);
        }
        return out;
    }

    /**
     * Before a site's crawl, when the configuration limits what is taken from a site map: the map is
     * fetched here, a map of maps is followed one level, and the first addresses of the site, up to the
     * limit, are requested. The crawl that follows starts from them as well as from the scan's address.
     */
    private void readSitemap(String site, ScanConfig.Options o, ScanTask task) {
        if (!o.sitemap() || o.sitemapMax() <= 0) return;
        String base = site.endsWith("/") ? site.substring(0, site.length() - 1) : site;
        try {
            String xml = api.fetchBody(base + "/sitemap.xml");
            java.util.List<String> listed = sitemapLocations(xml);
            if (xml.toLowerCase(java.util.Locale.ROOT).contains("<sitemapindex")) {
                java.util.List<String> maps = listed;
                listed = new ArrayList<>();
                for (int i = 0; i < maps.size() && i < 10 && listed.size() < o.sitemapMax(); i++) {
                    if (task.cancelled()) return;
                    if (!maps.get(i).startsWith(base + "/")) continue;
                    listed.addAll(sitemapLocations(api.fetchBody(maps.get(i))));
                    try { api.deleteSiteNode(maps.get(i)); } catch (Exception ignore) { /* as above */ }
                }
            }
            // The crawl starts from everything recorded for the site, and would read all of a map it found there.
            try { api.deleteSiteNode(base + "/sitemap.xml"); } catch (Exception ignore) { /* not recorded: nothing to take out */ }
            java.util.Set<String> taken = new java.util.LinkedHashSet<>();
            for (String u : listed) {
                if (taken.size() >= o.sitemapMax()) break;
                if (u.startsWith(base + "/") || u.equals(base)) taken.add(u);
            }
            for (String u : taken) {
                if (task.cancelled()) return;
                try { api.accessUrl(u); } catch (Exception ignore) { /* one address that does not answer */ }
            }
            if (!listed.isEmpty())
                task.log("Site map of " + base + ": requested " + taken.size() + " of the " + listed.size() + " addresses it lists (limit " + o.sitemapMax() + ")");
        } catch (Exception e) {
            task.log("The site map of " + base + " could not be read: " + e.getMessage());
        }
    }

    /** After a site's crawl: each WSDL it found by such an address is read, and its operations requested. */
    private void readWsdls(String site, ScanTask task) {
        java.util.List<String> found;
        try { found = api.urls(site); } catch (Exception e) { return; }
        int read = 0;
        for (String u : found) {
            if (!asksForWsdl(u) || task.cancelled() || read >= 20) continue;
            try {
                api.importWsdl(u);
                read++;
                task.log("Read the service description at " + u + " and requested its operations");
            } catch (Exception e) {
                task.log("The service description at " + u + " could not be read: " + e.getMessage());
            }
        }
    }

    /** A scan's timeout in seconds: its own when it sets one (0 is none), else the one in Settings > Network > Connections > Timeouts. */
    private static int timeoutFor(int own) {
        return own >= 0 ? own : globalTimeoutSecs(opensuite.core.HttpClient.defaultConnectTimeoutMs, opensuite.core.HttpClient.defaultReadTimeoutMs);
    }

    /** The engine has one timeout where the settings have two: the longer is taken, and 0 when either is without limit. */
    public static int globalTimeoutSecs(int connectMs, int readMs) {
        if (connectMs == Integer.MAX_VALUE || readMs == Integer.MAX_VALUE) return 0;
        return Math.max(1, (int) Math.ceil(Math.max(connectMs, readMs) / 1000.0));
    }

    /** What to say when a crawl has reached a limit of its configuration, or null while it is inside them. */
    public static String crawlCap(ScanConfig.Options o, int locations, int requests) {
        if (o.maxLocations() > 0 && locations >= o.maxLocations())
            return "Crawl stopped at its limit of " + o.maxLocations() + " unique locations";
        if (o.maxRequests() > 0 && requests >= o.maxRequests())
            return "Crawl stopped at its limit of " + o.maxRequests() + " requests";
        return null;
    }

    private int requestsTo(String site) {
        try { return api.messageCount(site); } catch (Exception e) { return 0; }
    }

    private static String label(Seed seed) {
        String url = seed.service().url();
        int i = url.indexOf("://");
        return i < 0 ? url : url.substring(i + 3);
    }

    /** One site's crawl as the engine runs it. */
    private static final class Crawl {
        final Seed seed;
        volatile String sid;        // the engine's number for it, once it has started
        volatile String error;      // why it could not be started, if it could not
        volatile long began = System.currentTimeMillis();
        volatile long lastNew = began;
        int lastLoc = -1;
        boolean over;
        Crawl(Seed seed) { this.seed = seed; }
    }

    /** Whether the user asked for this site to be left out; if so it is marked and said, once. */
    private boolean skipped(opensuite.core.SiteProgress sites, String site, ScanTask task) {
        opensuite.core.SiteProgress.Site s = sites.get(site);
        if (s == null || !s.skipAsked()) return false;
        if (s.status() != opensuite.core.SiteProgress.Status.SKIPPED) sites.set(site, opensuite.core.SiteProgress.Status.SKIPPED, "Skipped, as asked");
        if (saidSkipped.add(site)) {
            task.log("Skipped " + s.host() + ", as asked");
            ctx.taskChanged(task);
        }
        return true;
    }

    private final java.util.Set<String> saidSkipped = new java.util.HashSet<>();
    private int crawlThreads;
    /** The scan's thread setting, which sites crawled together share between them. */
    public void setCrawlThreads(int n) { crawlThreads = n; }

    private opensuite.core.Scope scanScope;
    /**
     * The scan's own scope: its sites, with what the wizard's detailed scope
     * adds or takes away. It binds the engine and decides which requests are
     * the scan's. The project's scope plays no part: that is the user's.
     */
    public void setScanScope(opensuite.core.Scope scope) { scanScope = scope; }

    /** The scope this scan runs in: the one it was given, or else its sites and no more. */
    private opensuite.core.Scope scopeOf(java.util.List<Seed> seeds) {
        if (scanScope == null) {
            scanScope = new opensuite.core.Scope();
            for (Seed seed : seeds) scanScope.includeSite(seed.service());
        }
        return scanScope;
    }

    /** Short label for a job that may cover several targets. */
    private static String targetLabel(java.util.List<Seed> seeds) {
        if (seeds.isEmpty()) return "targets";
        String first = seeds.get(0).service().host();
        return seeds.size() == 1 ? first : first + " +" + (seeds.size() - 1) + " more";
    }

    /** Unique discovered locations across every seed host, or -1 if none known. */
    private int totalLocations(java.util.List<Seed> seeds) {
        int total = 0; boolean any = false;
        for (Seed seed : seeds) {
            int n = locations(seed.service().url());
            if (n >= 0) { total += n; any = true; }
        }
        return any ? total : -1;
    }

    /** Count issues this task has reported, across every target. */
    static final String NO_BROWSER = "JavaScript-rendered pages were not crawled: the browser sandbox is not available on"
            + " this system. To crawl them, enable \"Allow Open Suite's browser to run without a"
            + " sandbox\" under Settings > Tools > Browser.";
    private boolean warnedNoBrowser;

    /** The browser crawl could not run: said on the task, in its log and in the event log. */
    private void browserCrawlFailed(ScanTask crawlTask, String why) {
        String full = "The browser crawl did not run, so pages built by JavaScript were not crawled: " + why;
        crawlTask.setCaution("browser crawl did not run", full);
        crawlTask.log(full);
        ctx.alert("scanner", "Scan " + crawlTask.number + ": " + full);
        ctx.taskChanged(crawlTask);
    }

    /** A browser crawl with no time limit ends when it has found nothing new for this long. */
    static final long AJAX_IDLE_MS = 10 * 60_000L;

    /**
     * Run ZAP's AJAX spider (a real headless Chromium) over the seed, so that
     * JavaScript-rendered links and routes are discovered and fed to the audit.
     * Bounded by a time budget; absence of the add-on or a browser is not fatal.
     */
    private void runAjaxCrawl(String seedUrl, String contextId, ScanConfig cfg, ScanTask crawlTask, opensuite.core.SiteProgress.Site own, Audits audits) {
        // The engine's browser follows the same sandbox setting as Open Suite's
        // own. Where the system refuses the sandbox and the setting is off, the
        // browser cannot start: say so, rather than crawl nothing in silence.
        boolean noSandbox = ctx.settings().getBool(opensuite.proxy.BrowserFlags.NO_SANDBOX, false);
        try { api.setBrowserSandboxOff(noSandbox); } catch (Exception ignore) { }
        // The browser is part of the scan. Without it the scan is not the scan
        // that was asked for, and the task says so where it cannot be missed.
        String chrome = opensuite.proxy.EmbeddedBrowser.findBinary(), driver = opensuite.proxy.EmbeddedBrowser.findDriver();
        if (chrome == null || driver == null) {
            browserCrawlFailed(crawlTask, "Open Suite's browser is not installed.");
            return;
        }
        try { api.setBrowserPaths(chrome, driver); } catch (Exception ignore) { /* the engine was told when it started */ }
        if (!noSandbox && !opensuite.proxy.EmbeddedBrowser.sandboxWorks()) {
            crawlTask.setCaution("browser crawl did not run", NO_BROWSER);
            crawlTask.log(NO_BROWSER);
            if (!warnedNoBrowser) {
                warnedNoBrowser = true;
                ctx.alert("scanner", "Scan " + crawlTask.number + ": " + NO_BROWSER);
            }
            ctx.taskChanged(crawlTask);
            return;
        }
        // The engine has one crawl browser: a second scan waits its turn rather than
        // be refused, or have its crawl stopped when the first scan's ends.
        boolean waited = false;
        try {
            while (!AJAX_TURN.tryLock(1, java.util.concurrent.TimeUnit.SECONDS)) {
                if (crawlTask.cancelled()) return;
                if (!waited) {
                    waited = true;
                    crawlTask.log("Waiting for another scan's browser crawl to finish");
                    ctx.taskChanged(crawlTask);
                }
            }
        } catch (InterruptedException ie) {
            Thread.currentThread().interrupt();
            return;
        }
        try {
            api.setAjaxBrowser("chrome-headless");
            api.setAjaxBrowsers(2);   // bound the headless-browser pool
            try {
                // The engine's own limit is set a minute later than the scan's: Open
                // Suite ends the crawl at the limit itself, and so knows that it did.
                api.setAjaxMaxDuration(cfg.ajaxMaxDurationMin() > 0 ? cfg.ajaxMaxDurationMin() + 1 : 0);
                api.setAjaxMaxCrawlDepth(cfg.ajaxMaxDepth());
                api.setAjaxMaxCrawlStates(cfg.ajaxMaxStates());
                api.setAjaxClickAll(cfg.more().clickAll());
                api.setUserAgent(cfg.more().userAgent());
            } catch (Exception ignore) { /* use the engine defaults */ }
            // A crawl that was just stopped (a deleted scan, a time limit) is still
            // closing its browsers, and the engine refuses another until it has.
            awaitAjaxIdle();
            crawlTask.log("Starting AJAX crawl (headless Chromium, executes JavaScript)...");
            ctx.taskChanged(crawlTask);
            // Bound to the scope context like the traditional crawl.
            api.ajaxSpiderScan(seedUrl, contextId == null ? null : scopeContext);
            ScanGate.running(crawlTask.number, "J");

            // The time limit is kept here. With no
            // time limit the crawl ends when the browser has nothing left to try, or
            // when it has gone a good while without finding anything new: a
            // single-page application can be clicked through for ever.
            boolean limited = cfg.ajaxMaxDurationMin() > 0, atLimit = false;
            long began = System.currentTimeMillis(), lastNew = began;
            long deadline = limited ? began + cfg.ajaxMaxDurationMin() * 60_000L : Long.MAX_VALUE;
            int lastLoc = -1;
            String baseurl = HttpService.parse(seedUrl).url();
            while ("running".equalsIgnoreCase(api.ajaxSpiderStatus())) {
                // A deleted task stops the AJAX spider (the finally block below), and so does a site the user skips.
                if (crawlTask.cancelled()) break;
                if (own != null && own.skipAsked()) break;
                // Other sites' audits go on while this one is crawled.
                if (audits != null && !audits.poll()) break;
                drain("crawl", true, crawlTask);
                checkLoops(baseurl, crawlTask);
                int loc = locations(baseurl);
                if (loc >= 0 && loc != lastLoc) {
                    // The task's figure is every site's; this site's is its own.
                    crawlTask.sites().locations(baseurl, loc);
                    int every = 0;
                    for (opensuite.core.SiteProgress.Site each : crawlTask.sites().all()) every += each.locations();
                    crawlTask.setDiscoveredLocations(Math.max(loc, every));
                    crawlTask.log("Discovered " + Math.max(loc, every) + " location(s)");
                    if (loc > lastLoc) lastNew = System.currentTimeMillis();
                    lastLoc = loc;
                }
                ctx.taskChanged(crawlTask);
                long now = System.currentTimeMillis();
                if (now >= deadline) {
                    try { api.ajaxSpiderStop(); } catch (Exception ignore) { }
                    atLimit = true;
                    break;
                }
                if (!limited && now - lastNew > AJAX_IDLE_MS) {
                    crawlTask.log("AJAX crawl stopped: no new location was discovered in the last " + (AJAX_IDLE_MS / 60_000) + " minutes");
                    try { api.ajaxSpiderStop(); } catch (Exception ignore) { }
                    break;
                }
                Thread.sleep(1500);
            }
            if (!crawlTask.cancelled()) {
                long now = System.currentTimeMillis();
                String cut = timeLimitNote("AJAX crawl", cfg.ajaxMaxDurationMin(), atLimit, now - lastNew);
                if (cut != null) crawlTask.log(cut);
            }
            drain("crawl", true, crawlTask);
            crawlTask.log("AJAX crawl finished");
        } catch (Exception e) {
            // Add-on missing, no browser/driver, or the engine refused: carry on
            // with whatever the traditional spider found.
            browserCrawlFailed(crawlTask, String.valueOf(e.getMessage()));
        } finally {
            // Always stop the AJAX spider so ZAP releases its headless browsers,
            // even if the crawl was interrupted or threw.
            try { api.ajaxSpiderStop(); } catch (Exception ignore) { }
            // The turn is given up only once the engine has let go of the crawl:
            // the scan waiting for it would be refused, and told its crawl did not run.
            awaitAjaxIdle();
            ScanGate.running(crawlTask.number, null);
            AJAX_TURN.unlock();
        }
        ctx.taskChanged(crawlTask);
    }

    /** How long a stopped browser crawl is given to close its browsers. */
    static final long AJAX_STOP_MS = 60_000;

    /** Wait, within a limit, until the engine reports no browser crawl running. */
    private void awaitAjaxIdle() {
        long until = System.currentTimeMillis() + AJAX_STOP_MS;
        try {
            while (System.currentTimeMillis() < until && "running".equalsIgnoreCase(api.ajaxSpiderStatus())) Thread.sleep(250);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        } catch (Exception e) {
            // the engine is not answering: nothing to wait for
        }
    }

    /** A ZAP control call (stop/pause/resume) whose failure must never abort the
     *  scan loop: the engine may have already finished the scan being stopped. */
    private interface ZapCall { void run() throws Exception; }
    private static void stopQuietly(ZapCall c) {
        try { c.run(); } catch (Exception ignore) { }
    }

    /** Unique discovered locations under baseurl, or the last value on error. */
    private int locations(String baseurl) {
        try { return api.uniqueLocations(baseurl); } catch (Exception e) { return -1; }
    }

    /**
     * Fetch the engine's alerts for the target and add any this audit has not
     * seen to the issue list, then recount the task's badges from what it has
     * seen. The badges count every alert the audit found, whether or not the
     * shared issue list already held the same finding: the live passive audit
     * usually raises the header and disclosure findings first, and an audit
     * that found them too still found them.
     */
    private final Map<String, AlertFeed> feeds = new HashMap<>();   // one for each site this scan reads alerts of

    private void pullAlerts(String baseurl, ScanTask task, Map<String, Issue.Severity> seen) throws Exception {
        pullAlerts(baseurl, task, seen, false);
    }

    /**
     * @param all read every alert waiting, however many: for the last look, when the
     *            audit is over. While it runs one part is read at a time, so that a
     *            long backlog does not keep the scan from seeing a pause or a stop.
     */
    private void pullAlerts(String baseurl, ScanTask task, Map<String, Issue.Severity> seen, boolean all) throws Exception {
        String source = "Scan " + task.number;
        // One evidence cache for this listing: findings on the same message
        // share its request/response pair instead of copying it per alert.
        java.util.Map<String, Evidence> evidence = new java.util.HashMap<>();
        // Only the alerts raised since the last look are read: see AlertFeed.
        AlertFeed feed = feeds.computeIfAbsent(baseurl == null ? "" : baseurl, b -> new AlertFeed(api, b));
        do {
            for (JsonValue a : feed.next()) {
                String id = ZapApi.str(a, "id");
                if (id == null || seen.containsKey(id)) continue;
                Issue is = mapAlert(api, a, evidence);
                if (is == null) continue;
                seen.put(id, is.severity());
                is.setSource(source);
                // addIssue de-duplicates and records this task as a finder, so the
                // live passive poller getting to a finding first no longer hides it
                // from the audit's own view, and a re-run audit shows it too.
                ctx.addIssue(is);
            }
        } while (all && feed.more() && !task.cancelled());
        // The card counts are this task's de-duplicated findings by severity, not
        // the raw alert count: a site-wide finding seen on many URLs is one issue,
        // so counting raw alerts over-stated the total many times over.
        int h = 0, m = 0, l = 0, i = 0;
        for (Issue is : ctx.issues()) {
            if (!is.foundBy(source)) continue;
            switch (is.severity()) {
                case HIGH -> h++;
                case MEDIUM -> m++;
                case LOW -> l++;
                case INFORMATION -> i++;
            }
        }
        task.setCounts(h, m, l, i);
    }

    // ------------------------------------------------- alert -> Issue mapping

    /**
     * Translate one ZAP alert JSON object into an Open Suite {@link Issue}. When
     * {@code api} is non-null the alert's HTTP message is fetched and attached.
     */
    public static Issue mapAlert(ZapApi api, JsonValue a) {
        return mapAlert(api, a, new java.util.HashMap<String, Evidence>());
    }

    /**
     * As {@link #mapAlert(ZapApi, JsonValue)}, with the evidence cache of one
     * listing of alerts. One response commonly triggers several passive
     * alerts; with a shared cache those findings hold one request/response
     * pair instead of a copy each, which the project file then writes once
     * and a restored project holds once. The cache must not outlive its
     * listing: message ids belong to one engine process, and a restarted
     * engine reuses them for different messages.
     */
    public static Issue mapAlert(ZapApi api, JsonValue a, java.util.Map<String, Evidence> evidence) {
        return mapAlert(a, evidence, api == null ? null : api::message);
    }

    /** The engine's message records, so the mapping can be driven without an engine. */
    interface MessageSource { JsonValue message(String id) throws Exception; }

    static Issue mapAlert(JsonValue a, java.util.Map<String, Evidence> evidence, MessageSource messages) {
        String name = ZapApi.str(a, "name");
        if (name == null || name.isEmpty()) name = ZapApi.str(a, "alert");
        if (name == null || name.isEmpty()) return null;

        String url = ZapApi.str(a, "url");
        HttpService svc = (url != null) ? HttpService.parse(url) : null;
        if (svc == null) return null;

        Issue.Builder b = Issue.builder(name)
                .severity(severity(ZapApi.str(a, "risk")))
                .confidence(confidence(ZapApi.str(a, "confidence")))
                .service(svc)
                .path(pathOf(url))
                .param(nz(ZapApi.str(a, "param")))
                .detail(detail(a))
                .background(nz(ZapApi.str(a, "other")))
                .remediation(nz(ZapApi.str(a, "solution")))
                .references(nz(ZapApi.str(a, "reference")))
                .evidence(nz(ZapApi.str(a, "evidence")))
                .cwe(toInt(ZapApi.str(a, "cweid")))
                .wasc(toInt(ZapApi.str(a, "wascid")))
                .moduleId(toInt(ZapApi.str(a, "pluginId")))
                // An active-scan finding carries the payload the engine injected
                // ("attack"); it is a real injection point, so keep one per path
                // and parameter, each with its own proof. A passive finding has no
                // such payload: it is a site-wide condition (a missing header, a
                // cookie flag, a disclosed value), so keep one per host and gather
                // the affected paths into it, the way the reference tools group a
                // repeated finding rather than listing it once per URL.
                .dedupe(nz(ZapApi.str(a, "attack")).isEmpty() ? Issue.Dedupe.SITE : Issue.Dedupe.PARAM);

        JsonValue tags = a.get("tags");
        if (tags != null && tags.isObject() && !tags.keys().isEmpty()) {
            b.tags(new ArrayList<>(tags.keys()));
        }

        if (messages != null) {
            String mid = ZapApi.str(a, "messageId");
            if (mid != null && !mid.isEmpty()) {
                try { attachMessage(b, mid, evidence, messages); } catch (Exception ignore) { }
            }
        }
        Issue made = b.build();
        made.setAttack(nz(ZapApi.str(a, "attack")));
        return made;
    }

    private static String detail(JsonValue a) {
        StringBuilder sb = new StringBuilder(nz(ZapApi.str(a, "description")));
        String attack = ZapApi.str(a, "attack");
        if (attack != null && !attack.isEmpty()) {
            sb.append("\n\nAttack: ").append(attack);
        }
        return sb.toString();
    }

    /** The request/response pair one engine message contributes as issue evidence. */
    static final class Evidence {
        final HttpMessage request;    // null when the engine holds no request
        final HttpMessage response;   // null when it holds no response
        Evidence(HttpMessage request, HttpMessage response) {
            this.request = request;
            this.response = response;
        }
    }

    private static void attachMessage(Issue.Builder b, String messageId,
            java.util.Map<String, Evidence> evidence, MessageSource messages) throws Exception {
        Evidence e = evidence.get(messageId);
        if (e == null) {
            JsonValue m = messages.message(messageId);
            if (m == null) return;   // nothing attached and nothing cached: a later alert retries
            e = buildEvidence(m);
            evidence.put(messageId, e);
        }
        if (e.request != null) b.request(e.request);
        if (e.response != null) b.response(e.response);
    }

    private static Evidence buildEvidence(JsonValue m) {
        return new Evidence(requestOf(m), responseOf(m));
    }

    /** An engine record's request as our message model, or null when it holds none. */
    private static HttpMessage requestOf(JsonValue m) {
        String h = ZapApi.str(m, "requestHeader");
        if (h == null || h.isEmpty()) return null;
        return new HttpMessage(Bytes.bytes(norm(toOriginForm(h)) + nz(ZapApi.str(m, "requestBody"))));
    }

    /** An engine record's response as our message model, or null when it holds none. */
    private static HttpMessage responseOf(JsonValue m) {
        String h = ZapApi.str(m, "responseHeader");
        if (h == null || h.isEmpty()) return null;
        return new HttpMessage(Bytes.bytes(norm(h) + nz(ZapApi.str(m, "responseBody"))));
    }

    // ------------------------------------------- live traffic record (logger)

    /**
     * Stream every new message the engine has recorded into our store, so the
     * logger holds a complete live record of everything the engine ran. Each
     * record is tagged by what the engine says made it: its crawlers' pages
     * become {@code crawl} entries and populate the site map; its scanner's
     * probes become {@code audit} entries and do not, to keep the site map to
     * real endpoints rather than every attack variant. Traffic the engine only
     * relayed for the proxy is left out, because the proxy has already recorded
     * it. The read position is shared across scans, so nothing is imported
     * twice. Batched so a flood of attack traffic cannot pull thousands of
     * messages in one call.
     *
     * @param phase the tool to count the batch against when a record carries
     *              no type, and the one whose entries count as this task's requests
     */
    private volatile java.util.List<String> gateSites = java.util.List.of();
    private int waitingOn;

    /**
     * Say so when this scan is stopped by another scan's hold on the same
     * site, and again when it is let go. Without this it would only sit at
     * "Crawling" or "Auditing" and send nothing, with no word of why.
     */
    private void noteWaiting(ScanTask task) {
        Integer other = ScanGate.heldByOther(task.number, gateSites);
        int now = other == null ? 0 : other;
        if (now == waitingOn) return;
        waitingOn = now;
        if (now != 0) {
            task.setWaiting("Waiting for scan " + now);
            task.log("Waiting: scan " + now + " on the same site is paused or checking its session, which blocks all scan requests "
                    + "to the site. This scan continues when scan " + now + " is resumed or removed.");
        } else {
            task.setWaiting("");
            task.log("Scan requests to the site are no longer blocked: resuming");
        }
        ctx.taskChanged(task);
    }

    private void drain(String phase, boolean toSiteMap, ScanTask task) {
        noteWaiting(task);
        try {
            if (api.gateVersion() >= ZapApi.HISTORY_NEEDS_GATE) { drainAfter(phase, task); return; }
            int total = api.numberOfMessages();
            int added = 0;
            while (imported.get() < total) {
                int from = imported.get();
                int want = Math.min(total - from, 500);
                java.util.List<JsonValue> batch = api.messages(from, want);
                if (batch.isEmpty()) break;
                for (JsonValue m : batch) {
                    String tool = toolFor(ZapApi.str(m, "type"), phase);
                    if (tool == null) continue;
                    if (importMessage(m, tool, "crawl".equals(tool)) && tool.equals(phase)) added++;
                }
                imported.addAndGet(batch.size());
            }
            if (added > 0 && task != null) task.addRequests(added);
        } catch (Exception e) {
            // The scan itself already finished; this only imports the engine's
            // history into the Logger, so a failure degrades the log, not the
            // scan. Trace it so the history is not quietly incomplete.
            Debug.log("engine history import failed: " + e);
        }
    }

    private int unreadable;

    /**
     * The same import by way of Open Suite's add-on, which gives the requests
     * recorded since the last one taken and passes over any the engine cannot
     * read back. The cursor is then the number of the last record looked at,
     * not a count of records.
     */
    private void drainAfter(String phase, ScanTask task) throws Exception {
        int added = 0;
        while (true) {
            int from = imported.get();
            ZapApi.History h = api.messagesAfter(from, 500);
            for (JsonValue m : h.messages()) {
                String tool = toolFor(ZapApi.str(m, "type"), phase);
                if (tool == null) continue;
                if (importMessage(m, tool, "crawl".equals(tool)) && tool.equals(phase)) added++;
            }
            if (h.skipped() > 0) {
                unreadable += h.skipped();
                Debug.log("engine history: " + h.skipped() + " request(s) could not be read back and are not in the Logger (" + unreadable + " so far)");
            }
            if (h.next() <= from) break;
            imported.set(h.next());
            if (!h.more()) break;
        }
        if (added > 0 && task != null) task.addRequests(added);
    }

    /**
     * Which tool a record of the engine's history belongs to, from the record
     * type the engine stamps on it, or null for one that is not the engine's
     * own work. Proxied traffic is the proxy's, recorded there already.
     */
    static String toolFor(String type, String phase) {
        if (type == null || type.isEmpty()) return phase;
        return switch (type) {
            case "0" -> phase;                                               // the engine's own untyped fetches
            case "2", "9", "10", "15", "18", "19", "24", "25" -> "crawl";   // spiders, and the seed fetch
            case "3", "14" -> opensuite.core.ProjectOptions.AUDIT_TOOL;       // active scanner
            default -> null;                                                 // proxied, hidden, internal
        };
    }

    private boolean importMessage(JsonValue m, String tool, boolean toSiteMap) {
        String reqH = ZapApi.str(m, "requestHeader");
        if (reqH == null || reqH.isEmpty()) return false;
        String target = requestTargetUrl(reqH);
        HttpService s = (target != null) ? HttpService.parse(target) : null;
        if (s == null) return false;
        HttpMessage req = requestOf(m);
        if (scanScope != null) {
            // Nothing outside a scan's scope is attributed to it. The JavaScript crawl drives a real
            // browser, though, which loads each page's outside resources and calls the services its
            // scripts call: those are part of what the application talks to, and are kept for the
            // site map as things seen. The browser's own background requests are not.
            if (!scanScope.isInScope(s, req.path())) { seenElsewhere(m, s, req); return false; }
        } else if (!ctx.scope().isEmpty() && !ctx.scope().isInScope(s, req.path())) {
            // An audit of chosen requests has no scope of its own: the project's, where one is set.
            return false;
        }
        LogEntry e = new LogEntry(tool, s, req);
        HttpMessage res = responseOf(m);
        if (res != null) e.setResponse(res);
        ctx.store().add(e);
        if (toSiteMap) ctx.siteMapChanged(e);
        return true;
    }

    /** The sites outside the scan that a page of the scan was seen to call, and so may call others in turn. */
    private final java.util.Set<String> calledSites = java.util.concurrent.ConcurrentHashMap.newKeySet();

    /**
     * True when a request to a site outside the scan was made on behalf of a
     * page of the scan: its Referer or Origin names one of the scan's sites,
     * or a site already known to be called by one (a script from one outside
     * site that loads from another). A request with neither is the browser's
     * own, such as an update check, and is nothing the application did.
     */
    static boolean calledByScan(String referer, String origin, java.util.function.Predicate<String> ofScan, java.util.Set<String> called) {
        for (String from : new String[] {referer, origin}) {
            if (from == null || from.isBlank()) continue;
            HttpService f = HttpService.parse(from.trim());
            if (f == null) continue;
            if (ofScan.test(f.url()) || called.contains(f.url())) return true;
        }
        return false;
    }

    /** True for the answer the engine gives in a site's place when the crawl's browser asks for something outside the scan. */
    static boolean refusedByEngine(HttpMessage res) {
        if (res.statusCode() != 403) return false;
        String body = res.bodyText();
        return body != null && body.contains("Out of AJAX Spider scope");
    }

    /** The kinds of content that say nothing a tester reads and only swell a project: kept as a line, without the body. */
    private static final java.util.regex.Pattern BULK = java.util.regex.Pattern.compile("(?i)^(image|font|video|audio)/.*");

    /**
     * Keep, for the site map, a request the crawl's browser made to a site
     * outside the scan. It is listed as seen, under its own host, and is never
     * tested: the audit is bound to the scan's scope.
     */
    private static final Object AUDIT_SETUP_LOCK = new Object();
    private static final java.util.concurrent.locks.ReentrantLock AJAX_TURN = new java.util.concurrent.locks.ReentrantLock(true);

    private void seenElsewhere(JsonValue m, HttpService s, HttpMessage req) {
        try {
            if (!"crawl".equals(toolFor(ZapApi.str(m, "type"), "crawl"))) return;
            final opensuite.core.Scope scope = scanScope;
            if (!calledByScan(req.header("Referer"), req.header("Origin"), site -> {
                    HttpService f = HttpService.parse(site);
                    return f != null && scope.isInScope(f, "/");
                }, calledSites)) return;
            calledSites.add(s.url());
            LogEntry e = new LogEntry("crawl", s, req);
            HttpMessage res = responseOf(m);
            // The engine keeps the crawl's browser inside the scan: a call to another site is answered by
            // the engine itself with a refusal and never leaves this machine. That answer is not the
            // site's, so the call is listed as seen and not requested.
            if (res == null || refusedByEngine(res)) {
                ctx.siteMapSeen(e);
                // What the page itself asked for (a script, a style, data from an API) is fetched once,
                // as the page would have fetched it. A link the crawl followed out of the scan is not.
                if (isResourceCall(req) && calledByScan(req.header("Referer"), req.header("Origin"), site -> {
                        HttpService f = HttpService.parse(site);
                        return f != null && scope.isInScope(f, "/");
                    }, java.util.Set.of())) fetchOnce(s, req, e);   // asked for by a page of the scan itself, not by an outside page
                return;
            }
            if (res != null) {
                String type = res.header("Content-Type");
                if (type == null || !BULK.matcher(type.trim()).matches()) e.setResponse(res);
            }
            ctx.store().add(e);
            ctx.siteMapChanged(e);
        } catch (RuntimeException ignored) {
            // A record that will not parse is not worth losing the import for.
        }
    }

    /**
     * True for a request a page makes on its own account: a script, a style,
     * an image, or data it calls for. False for a navigation, which is the
     * browser going to another page: the browser marks those, and asks for
     * a document.
     */
    static boolean isResourceCall(HttpMessage req) {
        if (req == null) return false;
        String mode = req.header("Sec-Fetch-Mode"), dest = req.header("Sec-Fetch-Dest");
        if (mode != null && mode.trim().equalsIgnoreCase("navigate")) return false;
        if (dest != null && (dest.trim().equalsIgnoreCase("document") || dest.trim().toLowerCase(java.util.Locale.ROOT).contains("frame"))) return false;
        if (req.header("Upgrade-Insecure-Requests") != null) return false;
        String accept = req.header("Accept");
        if (accept != null && accept.trim().toLowerCase(java.util.Locale.ROOT).startsWith("text/html")) return false;
        String method = req.method();
        // Only what reads: a page's call that changes something on another party's server is not repeated.
        return "GET".equalsIgnoreCase(method) || "HEAD".equalsIgnoreCase(method) || "OPTIONS".equalsIgnoreCase(method);
    }

    private final java.util.Set<String> fetchedElsewhere = java.util.concurrent.ConcurrentHashMap.newKeySet();
    private static final int FETCH_ELSEWHERE_CAP = 300;

    /** Fetch one outside resource a page asked for, once in this scan, and list it as requested. */
    private void fetchOnce(HttpService s, HttpMessage req, LogEntry seen) {
        if (fetchedElsewhere.size() >= FETCH_ELSEWHERE_CAP) return;
        if (!fetchedElsewhere.add(req.method() + " " + s.url() + seen.pathAndQuery())) return;
        Thread t = new Thread(() -> {
            try {
                opensuite.core.HttpClient.Options opt = new opensuite.core.HttpClient.Options();
                opensuite.core.HttpClient.Result r = new opensuite.core.HttpClient().send(s, req.copy(), opt);
                if (r == null || r.response == null) return;
                LogEntry e = new LogEntry("crawl", s, req);
                String type = r.response.header("Content-Type");
                if (type == null || !BULK.matcher(type.trim()).matches()) e.setResponse(r.response);
                ctx.store().add(e);
                ctx.siteMapChanged(e);
            } catch (RuntimeException ignored) {
                // The other site did not answer: it stays listed as seen.
            }
        }, "opensuite-fetch-elsewhere");
        t.setDaemon(true);
        t.start();
    }

    /**
     * Rewrite a request header's start line from ZAP's absolute (proxy) form,
     * {@code POST http://host/path?q HTTP/1.1}, to the origin form the rest of the
     * tool uses, {@code POST /path?q HTTP/1.1}. Without this, "copy URL" and other
     * path logic would see an already-absolute target and double the host.
     */
    private static String toOriginForm(String requestHeader) {
        int nl = requestHeader.indexOf('\n');
        if (nl < 0) return requestHeader;
        String rawStart = requestHeader.substring(0, nl);     // may end with '\r'
        String rest = requestHeader.substring(nl + 1);
        boolean cr = rawStart.endsWith("\r");
        String start = cr ? rawStart.substring(0, rawStart.length() - 1) : rawStart;
        String[] parts = start.split(" ", 3);                 // METHOD TARGET VERSION
        if (parts.length == 3
                && (parts[1].startsWith("http://") || parts[1].startsWith("https://"))) {
            try {
                java.net.URI u = java.net.URI.create(parts[1]);
                String pq = (u.getRawPath() == null || u.getRawPath().isEmpty() ? "/" : u.getRawPath())
                        + (u.getRawQuery() != null ? "?" + u.getRawQuery() : "");
                start = parts[0] + " " + pq + " " + parts[2];
            } catch (Exception ignore) { /* leave as-is */ }
        }
        return start + (cr ? "\r" : "") + "\n" + rest;
    }

    /** The absolute URL from a request header's start line (ZAP uses proxy form). */
    private static String requestTargetUrl(String requestHeader) {
        int nl = requestHeader.indexOf('\n');
        String start = (nl < 0) ? requestHeader : requestHeader.substring(0, nl);
        String[] parts = start.trim().split("\\s+");
        if (parts.length < 2) return null;
        String target = parts[1];
        return target.startsWith("http://") || target.startsWith("https://") ? target : null;
    }

    // --------------------------------------------------------------- helpers

    private static Issue.Severity severity(String risk) {
        if (risk == null) return Issue.Severity.INFORMATION;
        return switch (risk.trim().toLowerCase()) {
            case "high" -> Issue.Severity.HIGH;
            case "medium" -> Issue.Severity.MEDIUM;
            case "low" -> Issue.Severity.LOW;
            default -> Issue.Severity.INFORMATION;     // "Informational"
        };
    }

    private static Issue.Confidence confidence(String c) {
        if (c == null) return Issue.Confidence.TENTATIVE;
        return switch (c.trim().toLowerCase()) {
            case "high", "confirmed", "user confirmed" -> Issue.Confidence.CERTAIN;
            case "medium" -> Issue.Confidence.FIRM;
            default -> Issue.Confidence.TENTATIVE;     // "Low", "False Positive"
        };
    }

    private static String pathOf(String url) {
        try {
            java.net.URI u = java.net.URI.create(url);
            String p = u.getRawPath();
            if (p == null || p.isEmpty()) p = "/";
            if (u.getRawQuery() != null) p += "?" + u.getRawQuery();
            return p;
        } catch (Exception e) {
            return "/";
        }
    }

    private static int toInt(String s) {
        try { return Integer.parseInt(s.trim()); } catch (Exception e) { return -1; }
    }

    private static String nz(String s) { return (s == null) ? "" : s; }

    /** Normalise a header block to end in a single blank line before the body. */
    private static String norm(String header) {
        return header.replaceAll("\\r?\\n+$", "") + "\r\n\r\n";
    }

    // ----------------------------------------------------------- diagnostics

    /**
     * Standalone check: attach to a running ZAP daemon and print how its alerts
     * for a base URL map into Open Suite issues. Not part of the app; run with
     *   java -cp build opensuite.engine.ZapScanner http://127.0.0.1:8090 "" http://host/
     */
    public static void main(String[] args) throws Exception {
        String base = args.length > 0 ? args[0] : "http://127.0.0.1:8090";
        String key = args.length > 1 ? args[1] : "";
        String baseurl = args.length > 2 ? args[2] : "http://testaspnet.vulnweb.com/";
        ZapApi api = new ZapApi(base, key);
        System.out.println("engine version: " + api.version());
        List<JsonValue> alerts = api.alerts(baseurl, 0, 100000);
        System.out.println("raw alerts: " + alerts.size());
        java.util.Map<String, int[]> bySev = new java.util.TreeMap<>();
        java.util.Map<String, Evidence> evidence = new java.util.HashMap<>();
        Issue sample = null;
        int mapped = 0;
        for (JsonValue a : alerts) {
            Issue is = mapAlert(api, a, evidence);
            if (is == null) continue;
            mapped++;
            bySev.computeIfAbsent(is.severity().label(), k -> new int[1])[0]++;
            if (sample == null && is.severity() == Issue.Severity.HIGH) sample = is;
        }
        System.out.println("mapped issues: " + mapped);
        bySev.forEach((s, c) -> System.out.println("  " + s + ": " + c[0]));
        if (sample == null && mapped > 0) {
            // fall back to any issue for the sample
            for (JsonValue a : alerts) { Issue is = mapAlert(api, a); if (is != null) { sample = is; break; } }
        }
        if (sample != null) {
            System.out.println("\nsample mapped issue:");
            System.out.println("  title      : " + sample.title());
            System.out.println("  severity   : " + sample.severity().label() + "  confidence: " + sample.confidence().label());
            System.out.println("  host/path  : " + sample.host() + sample.path());
            System.out.println("  param      : " + sample.param());
            System.out.println("  cwe/wasc   : " + sample.cwe() + " / " + sample.wasc() + "  module: " + sample.moduleId());
            System.out.println("  evidence   : " + trunc(sample.evidence(), 80));
            System.out.println("  request?   : " + (sample.request() != null));
            System.out.println("  response?  : " + (sample.response() != null));
            System.out.println("  detail     : " + trunc(sample.detail(), 120));
        }
    }

    private static String trunc(String s, int n) {
        if (s == null) return "";
        s = s.replaceAll("\\s+", " ");
        return s.length() > n ? s.substring(0, n) + "..." : s;
    }
}