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.

41.6 KB
Raw Blame
package opensuite.engine;

import java.net.URI;
import java.net.URLEncoder;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import opensuite.core.Debug;
import opensuite.spider.Cdp.JsonValue;

/**
 * Thin client for the OWASP ZAP JSON API over the loopback.
 *
 * <p>Open Suite drives ZAP purely as a headless scan engine: this talks to the
 * daemon's REST API ({@code /JSON/<component>/<view|action>/<name>/}) and parses
 * the JSON replies with the project's own {@link JsonValue} parser. Nothing of
 * ZAP's own code runs inside Open Suite; this is an HTTP conversation with a
 * separate process.
 */
public final class ZapApi {

    private final String base;     // e.g. http://127.0.0.1:8090
    private final String apiKey;   // may be null or empty (disabled key)
    private final java.net.http.HttpClient http =
            java.net.http.HttpClient.newBuilder()
                    .connectTimeout(Duration.ofSeconds(5))
                    // One connection to a call. The engine answers the calls of one
                    // connection one after another, so with them all on a single
                    // connection a slow call held up every other, the hold on a
                    // paused scan among them.
                    .version(java.net.http.HttpClient.Version.HTTP_1_1)
                    .build();

    public ZapApi(String base, String apiKey) {
        this.base = base;
        this.apiKey = apiKey;
    }

    public String base() { return base; }

    /** Call a ZAP JSON API endpoint. {@code kind} is "view" or "action". */
    public JsonValue call(String component, String kind, String name, Map<String, String> params)
            throws Exception {
        StringBuilder sb = new StringBuilder(base)
                .append("/JSON/").append(component).append('/')
                .append(kind).append('/').append(name).append("/?");
        if (apiKey != null && !apiKey.isEmpty()) {
            sb.append("apikey=").append(enc(apiKey)).append('&');
        }
        if (params != null) {
            for (Map.Entry<String, String> e : params.entrySet()) {
                sb.append(enc(e.getKey())).append('=').append(enc(e.getValue())).append('&');
            }
        }
        HttpRequest req;
        int q = sb.indexOf("?");
        if (sb.length() > 4000) {
            // Too long for a request line (a whole request passed as a parameter): post it as a form.
            req = HttpRequest.newBuilder(URI.create(sb.substring(0, q)))
                    .timeout(Duration.ofSeconds(120))
                    .header("Content-Type", "application/x-www-form-urlencoded")
                    .POST(HttpRequest.BodyPublishers.ofString(sb.substring(q + 1))).build();
        } else {
            req = HttpRequest.newBuilder(URI.create(sb.toString()))
                    .timeout(Duration.ofSeconds(120))
                    .GET().build();
        }
        HttpResponse<String> r = http.send(req, HttpResponse.BodyHandlers.ofString());
        return JsonValue.parse(r.body());
    }

    private static String enc(String s) {
        // A null parameter value must never crash a scan: URLEncoder.encode(null)
        // throws a NullPointerException, so treat null as the empty string.
        return s == null ? "" : URLEncoder.encode(s, StandardCharsets.UTF_8);
    }

    private static Map<String, String> p(String... kv) {
        Map<String, String> m = new LinkedHashMap<>();
        for (int i = 0; i + 1 < kv.length; i += 2) m.put(kv[i], kv[i + 1]);
        return m;
    }

    // ----------------------------------------------------------- convenience

    public String version() throws Exception {
        return str(call("core", "view", "version", null), "version");
    }

    public void accessUrl(String url) throws Exception {
        call("core", "action", "accessUrl", p("url", url, "followRedirects", "true"));
    }

    /** How many links deep the spider follows (0 = unlimited). */
    public void setSpiderMaxDepth(int depth) throws Exception {
        call("spider", "action", "setOptionMaxDepth", p("Integer", String.valueOf(depth)));
    }

    /** Spider time budget in minutes (0 = no limit). */
    public void setSpiderMaxDuration(int minutes) throws Exception {
        call("spider", "action", "setOptionMaxDuration", p("Integer", String.valueOf(minutes)));
    }

    /** Concurrent crawler threads (resource pool). */
    public void setSpiderThreads(int n) throws Exception {
        call("spider", "action", "setOptionThreadCount", p("Integer", String.valueOf(Math.max(1, n))));
    }

    /** Concurrent active-scan threads per host (resource pool). */
    public void setActiveThreadPerHost(int n) throws Exception {
        call("ascan", "action", "setOptionThreadPerHost", p("Integer", String.valueOf(Math.max(1, n))));
    }

    /**
     * Start the spider (crawler) inside a context, so it never leaves the scope
     * the context holds; returns the scan id. Fails with the engine's own
     * message when the URL is outside the context.
     */
    public String spiderScan(String url, int maxChildren, String contextName) throws Exception {
        Map<String, String> q = p("url", url, "maxChildren", String.valueOf(maxChildren), "recurse", "true");
        if (contextName != null) q.put("contextName", contextName);
        return str(checked(call("spider", "action", "scan", q)), "scan");
    }

    /**
     * The engine answers an action it refused with an error object instead of
     * the result; turn that into an exception carrying its message, so a
     * refusal cannot pass as an empty result.
     */
    static JsonValue checked(JsonValue v) throws Exception {
        String code = str(v, "code");
        if (code != null && !code.isEmpty()) {
            String msg = str(v, "message");
            String detail = str(v, "detail");
            throw new Exception((msg == null || msg.isEmpty() ? code : msg)
                    + (detail == null || detail.isEmpty() ? "" : " (" + detail + ")"));
        }
        return v;
    }

    // ------------------------------------------------------------ contexts

    /** Create a context; returns its id. */
    public String newContext(String name) throws Exception {
        return str(checked(call("context", "action", "newContext", p("contextName", name))), "contextId");
    }

    /** Remove a context; a context that does not exist is not an error. */
    public void removeContext(String name) throws Exception {
        call("context", "action", "removeContext", p("contextName", name));
    }

    /** A whole-URL regex the context includes. */
    public void includeInContext(String name, String regex) throws Exception {
        checked(call("context", "action", "includeInContext", p("contextName", name, "regex", regex)));
    }

    /** A whole-URL regex the context excludes, even when an include covers it. */
    public void excludeFromContext(String name, String regex) throws Exception {
        checked(call("context", "action", "excludeFromContext", p("contextName", name, "regex", regex)));
    }

    /** Whether the context counts as the engine's scope. */
    public void setContextInScope(String name, boolean inScope) throws Exception {
        checked(call("context", "action", "setContextInScope",
                p("contextName", name, "booleanInScope", String.valueOf(inScope))));
    }

    public int spiderStatus(String id) throws Exception {
        return intOf(call("spider", "view", "status", p("scanId", id)), "status");
    }

    /** Stop the spider scan so the engine releases it and stops crawling. */
    public void spiderStop(String id) throws Exception {
        call("spider", "action", "stop", p("scanId", id));
    }

    public void spiderPause(String id) throws Exception {
        call("spider", "action", "pause", p("scanId", id));
    }

    public void spiderResume(String id) throws Exception {
        call("spider", "action", "resume", p("scanId", id));
    }

    public List<JsonValue> spiderResults(String id) throws Exception {
        return arr(call("spider", "view", "results", p("scanId", id)), "results");
    }

    /**
     * Start the active scan (audit) of the subtree under url, limited to the
     * context when one is given, so nothing outside it is ever attacked;
     * returns the scan id. Fails with the engine's own message when there is
     * nothing under the URL or it lies outside the context.
     */
    public String ascanScan(String url, String contextId) throws Exception {
        Map<String, String> q = p("url", url, "recurse", "true",
                "inScopeOnly", String.valueOf(contextId != null));
        if (contextId != null) q.put("contextId", contextId);
        return str(checked(call("ascan", "action", "scan", q)), "scan");
    }

    /**
     * Start the active scan of one request the engine has already seen, and
     * nothing under it; returns the scan id. The method and body pick out the
     * exact request when the URL has been seen with more than one.
     */
    public String ascanScanOne(String url, String method, String postData) throws Exception {
        Map<String, String> q = p("url", url, "recurse", "false", "inScopeOnly", "false");
        if (method != null && !method.isEmpty()) q.put("method", method);
        if (postData != null && !postData.isEmpty()) q.put("postData", postData);
        return str(checked(call("ascan", "action", "scan", q)), "scan");
    }

    /**
     * Have the engine send a request itself, so that it knows the request and
     * passively scans the response. The request line must carry the full URL.
     */
    public void sendRequest(String rawRequest) throws Exception {
        checked(call("core", "action", "sendRequest", p("request", rawRequest, "followRedirects", "false")));
    }

    // ------------------------------------------------- scanner-only headers

    /** The engine's request initiators that are scanning: active scan, spider and AJAX spider. */
    public static final String SCAN_INITIATORS = "2,3,10";

    /**
     * Set a header on every scanning request the engine sends to URLs matching
     * the pattern, replacing the header when the request already has one.
     * Requests the engine relays for the proxy are not touched.
     */
    public void addScanHeader(String ruleName, String urlRegex, String header, String value) throws Exception {
        checked(call("replacer", "action", "addRule", p(
                "description", ruleName, "enabled", "true", "matchType", "REQ_HEADER",
                "matchRegex", "false", "matchString", header, "replacement", value,
                "initiators", SCAN_INITIATORS, "url", urlRegex)));
    }

    public void removeScanHeader(String ruleName) throws Exception {
        call("replacer", "action", "removeRule", p("description", ruleName));
    }

    /** The names of every header rule in the engine. */
    public List<String> scanHeaderRules() throws Exception {
        List<String> out = new java.util.ArrayList<>();
        JsonValue r = call("replacer", "view", "rules", null);
        JsonValue rules = r == null ? null : r.get("rules");
        // An engine without the add-on answers with an error and no list.
        if (rules == null) throw new Exception("this scan engine does not support adding headers to its requests");
        if (rules != null && rules.isArray()) for (JsonValue v : rules.asArray()) out.add(str(v, "description"));
        return out;
    }

    // ------------------------------------------------- logging in with a browser

    /** One exchange the engine has recorded. */
    public record Recorded(String type, String requestHeader, String requestBody, String responseHeader, String responseBody) {}

    /** The kind the engine gives to what its login browser sends, as against a crawl's or a scan's requests. */
    public static final String LOGIN_TRAFFIC = "11";

    /** Whether this engine has the add-on that logs in with a browser. */
    public boolean canBrowserLogin() throws Exception {
        JsonValue r = call("authentication", "view", "getSupportedAuthenticationMethods", null);
        for (JsonValue v : arr(r, "supportedMethods")) if ("browserBasedAuthentication".equals(v.asString())) return true;
        return false;
    }

    /** Have the context's users log in by filling in the login page in a browser without a window. */
    public void setBrowserLogin(String contextId, String loginUrl) throws Exception {
        checked(call("authentication", "action", "setAuthenticationMethod", p("contextId", contextId,
                "authMethodName", "browserBasedAuthentication",
                "authMethodConfigParams", "loginPageUrl=" + enc(loginUrl) + "&browserId=chrome-headless&loginPageWait=5")));
    }

    /** Add a user with a username and a password to the context; returns the user's id. */
    public String newUser(String contextId, String username, String password) throws Exception {
        String id = str(checked(call("users", "action", "newUser", p("contextId", contextId, "name", username))), "userId");
        checked(call("users", "action", "setAuthenticationCredentials", p("contextId", contextId, "userId", id,
                "authCredentialsConfigParams", "username=" + enc(username) + "&password=" + enc(password))));
        checked(call("users", "action", "setUserEnabled", p("contextId", contextId, "userId", id, "enabled", "true")));
        return id;
    }

    /** Log the user in now. The engine answers the same whether or not the application accepted the login. */
    public void authenticateAsUser(String contextId, String userId) throws Exception {
        checked(call("users", "action", "authenticateAsUser", p("contextId", contextId, "userId", userId)));
    }

    /** When the user's login last ran to its end, in milliseconds, or 0 when it never has. */
    public long lastLogin(String contextId, String userId) throws Exception {
        String v = str(call("users", "view", "getAuthenticationState", p("contextId", contextId, "userId", userId)),
                "lastSuccessfulAuthTimeInMs");
        try { return Long.parseLong(v); } catch (RuntimeException e) { return 0; }
    }

    /** How many exchanges with the site the engine has recorded. */
    public int messageCount(String baseurl) throws Exception {
        return intOf(call("core", "view", "numberOfMessages", p("baseurl", baseurl)), "numberOfMessages");
    }

    /** The exchanges with the site the engine recorded after the first {@code skip} of them, oldest first. */
    public List<Recorded> messagesAfter(String baseurl, int skip, int count) throws Exception {
        List<Recorded> out = new java.util.ArrayList<>();
        JsonValue r = call("core", "view", "messages", p("baseurl", baseurl,
                "start", String.valueOf(skip + 1), "count", String.valueOf(count)));
        JsonValue ms = r == null ? null : r.get("messages");
        if (ms != null && ms.isArray()) for (JsonValue m : ms.asArray())
            out.add(new Recorded(str(m, "type"), str(m, "requestHeader"), str(m, "requestBody"), str(m, "responseHeader"), str(m, "responseBody")));
        return out;
    }

    /** Switch passive checks off by their ids. */
    public void disablePassiveChecks(String ids) throws Exception {
        call("pscan", "action", "disableScanners", p("ids", ids));
    }

    /** Whether the two crawlers pass over links and buttons that log out, by the engine's own reckoning of what those are. */
    public void setLogoutAvoidance(boolean on) throws Exception {
        call("spider", "action", "setOptionLogoutAvoidance", p("Boolean", String.valueOf(on)));
        call("ajaxSpider", "action", "setOptionLogoutAvoidance", p("Boolean", String.valueOf(on)));
    }

    /** Ask the address for its GraphQL schema and request what it describes; false when it is not such an endpoint. */
    public boolean importGraphql(String endpoint) {
        try { checked(call("graphql", "action", "importUrl", p("endurl", endpoint))); return true; }
        catch (Exception e) { return false; }
    }

    /** Fetch the address through the engine, so it is recorded with the site, and give the body of a 200 answer ("" for any other). */
    public String fetchBody(String url) throws Exception {
        List<JsonValue> got = arr(call("core", "action", "accessUrl", p("url", url, "followRedirects", "true")), "accessUrl");
        if (got.isEmpty()) return "";
        JsonValue last = got.get(got.size() - 1);
        String head = str(last, "responseHeader");
        String body = str(last, "responseBody");
        return head != null && head.matches("(?s)HTTP/\\S+ 200\\b.*") && body != null ? body : "";
    }

    /** Read the WSDL at the address and request each operation it describes; they join the site's addresses. */
    public void importWsdl(String url) throws Exception {
        call("soap", "action", "importUrl", p("url", url));
    }

    /** Where the crawler looks for addresses besides the links of a page: robots.txt, sitemap.xml and comments. */
    public void setSpiderSources(boolean robots, boolean sitemap, boolean comments) throws Exception {
        call("spider", "action", "setOptionParseRobotsTxt", p("Boolean", String.valueOf(robots)));
        call("spider", "action", "setOptionParseSitemapXml", p("Boolean", String.valueOf(sitemap)));
        call("spider", "action", "setOptionParseComments", p("Boolean", String.valueOf(comments)));
    }

    /** Whether the browser crawl clicks every element, or only the usual ones (links, buttons, inputs). */
    public void setAjaxClickAll(boolean all) throws Exception {
        call("ajaxSpider", "action", "setOptionClickDefaultElems", p("Boolean", String.valueOf(!all)));
    }

    private String ownAgent;      // the engine's User-Agent before a scan first changed it
    private String browserAgent;  // the User-Agent argument its browsers were last given

    /** The User-Agent of the engine's requests and of its browsers; empty puts back the engine's own. */
    public synchronized void setUserAgent(String agent) throws Exception {
        if (ownAgent == null) ownAgent = str(call("network", "view", "getDefaultUserAgent", null), "getDefaultUserAgent");
        boolean custom = agent != null && !agent.isBlank();
        call("network", "action", "setDefaultUserAgent", p("userAgent", custom ? agent.strip() : ownAgent == null ? "" : ownAgent));
        String arg = custom ? "--user-agent=" + agent.strip() : null;
        if (java.util.Objects.equals(arg, browserAgent)) return;
        if (browserAgent != null) setBrowserArgument(browserAgent, false);
        if (arg != null) setBrowserArgument(arg, true);
        browserAgent = arg;
    }

    private int ownTimeout = -1;  // the engine's timeout before a scan first changed it

    /** How long the engine waits on a connection, in seconds: 0 is for ever, and below 0 puts back the engine's own. */
    public synchronized void setTimeoutSecs(int seconds) throws Exception {
        if (ownTimeout < 0) ownTimeout = Math.max(0, intOf(call("network", "view", "getConnectionTimeout", null), "getConnectionTimeout"));
        call("network", "action", "setConnectionTimeout", p("timeout", String.valueOf(seconds < 0 ? ownTimeout : seconds)));
    }

    private List<String[]> ownSkips;   // the engine's list of parameters left alone, before a scan first changed it

    /** The parameters the audit sends no payload to; null puts back the engine's own list. */
    public synchronized void setSkippedParams(List<ScanConfig.Skip> skips) throws Exception {
        List<JsonValue> now = arr(call("ascan", "view", "excludedParams", null), "excludedParams");
        if (ownSkips == null) {
            ownSkips = new java.util.ArrayList<>();
            for (JsonValue e : now) ownSkips.add(new String[]{str(e, "parameter"), str(e.get("type"), "id"), str(e, "url")});
        }
        for (int i = now.size() - 1; i >= 0; i--) call("ascan", "action", "removeExcludedParam", p("idx", String.valueOf(i)));
        if (skips == null) {
            for (String[] e : ownSkips) call("ascan", "action", "addExcludedParam", p("name", e[0], "type", e[1], "url", e[2] == null ? "*" : e[2]));
            return;
        }
        java.util.Set<String> seen = new java.util.HashSet<>();
        for (ScanConfig.Skip s : skips) {
            if (s.expression() == null || s.expression().isBlank() || !seen.add(s.typeId() + " " + s.regex())) continue;
            call("ascan", "action", "addExcludedParam", p("name", s.regex(), "type", String.valueOf(s.typeId()), "url", "*"));
        }
    }

    /** Whether the crawler keeps cookies it is sent; off while a session's own cookies are forced. */
    public void setSpiderAcceptCookies(boolean on) throws Exception {
        call("spider", "action", "setOptionAcceptCookies", p("Boolean", String.valueOf(on)));
    }

    public int ascanStatus(String id) throws Exception {
        return intOf(call("ascan", "view", "status", p("scanId", id)), "status");
    }

    /** Stop the active scan so the engine stops attacking and releases it. */
    public void ascanStop(String id) throws Exception {
        call("ascan", "action", "stop", p("scanId", id));
    }

    public void ascanPause(String id) throws Exception {
        call("ascan", "action", "pause", p("scanId", id));
    }

    public void ascanResume(String id) throws Exception {
        call("ascan", "action", "resume", p("scanId", id));
    }

    // ------------------------------------------------- AJAX spider (JavaScript)

    /**
     * Tell the engine where the browser and its driver are. The engine is also
     * told when it starts, but a browser fetched after that is known only here.
     */
    public void setBrowserPaths(String chrome, String driver) throws Exception {
        if (chrome != null) call("selenium", "action", "setOptionChromeBinaryPath", p("String", chrome));
        if (driver != null) call("selenium", "action", "setOptionChromeDriverPath", p("String", driver));
    }

    /** Pick the browser the AJAX spider drives, e.g. "chrome-headless". */
    public void setAjaxBrowser(String browserId) throws Exception {
        call("ajaxSpider", "action", "setOptionBrowserId", p("String", browserId));
    }

    /**
     * Let the engine's browser start without its sandbox, or put the sandbox
     * back. Some Linux systems refuse the sandbox, and the browser then does not
     * start at all.
     */
    public void setBrowserSandboxOff(boolean off) throws Exception {
        Map<String, String> q = p("browser", "chrome", "argument", "--no-sandbox");
        if (off) {
            q.put("enabled", "true");
            call("selenium", "action", "addBrowserArgument", q);
        } else {
            call("selenium", "action", "removeBrowserArgument", q);
        }
    }

    /** The names of form fields the engine takes for anti-forgery tokens and refreshes before each test. */
    public List<String> formTokenNames() throws Exception {
        List<String> out = new java.util.ArrayList<>();
        JsonValue v = call("acsrf", "view", "optionTokensNames", p()).get("optionTokensNames");
        if (v != null && v.isArray()) for (JsonValue n : v.asArray()) out.add(n.asString());
        return out;
    }

    public void addFormToken(String name) throws Exception {
        call("acsrf", "action", "addOptionToken", p("String", name));
    }

    public void removeFormToken(String name) throws Exception {
        call("acsrf", "action", "removeOptionToken", p("String", name));
    }

    /** Set one of the engine's global variables, which its add-ons can read. */
    public void setGlobalVar(String key, String value) throws Exception {
        call("script", "action", "setGlobalVar", p("varKey", key, "varValue", value));
    }

    public void clearGlobalVar(String key) throws Exception {
        call("script", "action", "clearGlobalVar", p("varKey", key));
    }

    private volatile int gateVersion = -1;

    /**
     * The version of Open Suite's own add-on in this engine, or 0 when it is
     * not there. Version 2 applies a scan's session itself, sparing a header
     * or cookie that a check has changed, and holds one scan without holding
     * the others of the same site. Version 3 names the alerts raised since a
     * given one, so they need not all be listed again each time. Version 4
     * tells which rules an audit has started on which addresses. Version 5
     * lists the requests recorded since a given one, passing over any the
     * engine cannot read back.
     */
    public int gateVersion() {
        int v = gateVersion;
        if (v >= 0) return v;
        v = 0;
        try {
            for (JsonValue a : arr(call("autoupdate", "view", "installedAddons", null), "installedAddons")) {
                if (!"opensuitegate".equalsIgnoreCase(str(a, "id"))) continue;
                String ver = str(a, "version");
                v = ver == null ? 1 : Integer.parseInt(ver.replaceAll("[^0-9].*$", ""));
            }
        } catch (Exception e) {
            return 0;   // asked again next time: the engine may only be busy
        }
        gateVersion = v;
        return v;
    }

    /** Add or take away an argument the engine starts its browsers with. */
    public void setBrowserArgument(String argument, boolean on) throws Exception {
        Map<String, String> q = p("browser", "chrome", "argument", argument);
        if (on) {
            q.put("enabled", "true");
            call("selenium", "action", "addBrowserArgument", q);
        } else {
            call("selenium", "action", "removeBrowserArgument", q);
        }
    }

    /** Bound the AJAX spider's concurrent headless-browser pool. */
    public void setAjaxBrowsers(int n) throws Exception {
        call("ajaxSpider", "action", "setOptionNumberOfBrowsers", p("Integer", String.valueOf(n)));
    }

    /**
     * Start the AJAX spider over the URL, kept inside the context when one is
     * given; it executes JavaScript as it crawls.
     */
    public void ajaxSpiderScan(String url, String contextName) throws Exception {
        Map<String, String> q = p("url", url, "inScope", "false");
        if (contextName != null) q.put("contextName", contextName);
        checked(call("ajaxSpider", "action", "scan", q));
    }

    /** "running" while the AJAX spider is working, "stopped" once it is done. */
    public String ajaxSpiderStatus() throws Exception {
        return str(call("ajaxSpider", "view", "status", null), "status");
    }

    /** How many results (URLs) the AJAX spider has found so far. */
    public int ajaxSpiderResults() throws Exception {
        return intOf(call("ajaxSpider", "view", "numberOfResults", null), "numberOfResults");
    }

    /** Stop the AJAX spider early (e.g. when a time budget is reached). */
    public void ajaxSpiderStop() throws Exception {
        call("ajaxSpider", "action", "stop", null);
    }

    public int numberOfAlerts(String baseurl) throws Exception {
        return intOf(call("core", "view", "numberOfAlerts", p("baseurl", baseurl)), "numberOfAlerts");
    }

    /**
     * The number of unique locations (endpoints) under {@code baseurl} that ZAP
     * has discovered, counted at node granularity: a path plus its set of
     * parameter names, with parameter *values* collapsed. So {@code /p?id=2} and
     * {@code /p?id=3} count once, while {@code /p?d=1} counts separately. This
     * reads ZAP's site tree, so it combines the traditional and AJAX spiders
     * with no double counting.
     */
    /** Every URL the engine has in its site tree under this site. */
    public List<String> urls(String baseurl) throws Exception {
        List<String> out = new java.util.ArrayList<>();
        for (JsonValue u : arr(call("core", "view", "urls", p("baseurl", baseurl)), "urls")) {
            String url = u.asString();
            if (url != null) out.add(url);
        }
        return out;
    }

    /** Take a URL out of the engine's site tree, so it is neither counted nor audited. */
    public void deleteSiteNode(String url) throws Exception {
        call("core", "action", "deleteSiteNode", p("url", url));
    }

    /** The URLs a crawl found and did not request because they were outside what it may request. */
    public List<String> spiderOutOfScope(String scanId) throws Exception {
        List<String> out = new java.util.ArrayList<>();
        JsonValue r = call("spider", "view", "fullResults", p("scanId", scanId));
        for (JsonValue part : arr(r, "fullResults")) {
            if (part == null || !part.isObject()) continue;
            for (JsonValue u : arr(part, "urlsOutOfScope")) {
                String url = u.isObject() ? str(u, "url") : u.asString();
                if (url != null) out.add(url);
            }
        }
        return out;
    }

    public int uniqueLocations(String baseurl) throws Exception {
        java.util.Set<String> nodes = new java.util.HashSet<>();
        for (JsonValue u : arr(call("core", "view", "urls", p("baseurl", baseurl)), "urls")) {
            String url = u.asString();
            if (url != null) nodes.add(nodeKey(url));
        }
        return nodes.size();
    }

    /** host + path + the sorted set of query-parameter names (values dropped). */
    static String nodeKey(String url) {
        try {
            java.net.URI u = java.net.URI.create(url);
            StringBuilder b = new StringBuilder();
            if (u.getHost() != null) b.append(u.getHost());
            b.append(u.getRawPath() == null ? "/" : u.getRawPath());
            String q = u.getRawQuery();
            if (q != null && !q.isEmpty()) {
                java.util.TreeSet<String> names = new java.util.TreeSet<>();
                for (String pair : q.split("&")) {
                    if (pair.isEmpty()) continue;
                    int eq = pair.indexOf('=');
                    names.add(eq >= 0 ? pair.substring(0, eq) : pair);
                }
                b.append('?').append(String.join("&", names));
            }
            return b.toString();
        } catch (Exception e) {
            return url;   // unparseable: treat the raw URL as its own node
        }
    }

    public List<JsonValue> alerts(String baseurl, int start, int count) throws Exception {
        return arr(call("core", "view", "alerts",
                p("baseurl", baseurl, "start", String.valueOf(start), "count", String.valueOf(count))), "alerts");
    }

    public List<JsonValue> messages(String baseurl, int start, int count) throws Exception {
        return arr(call("core", "view", "messages",
                p("baseurl", baseurl, "start", String.valueOf(start), "count", String.valueOf(count))), "messages");
    }

    /** The alerts raised after a given one: their numbers, the last number looked at, and the highest there is. */
    public record NewAlerts(List<Integer> ids, int last, int top) {}

    /**
     * Ask Open Suite's add-on which alerts are newer than the one numbered
     * {@code after}, on URLs beginning with {@code baseurl} where one is given.
     * Needs version {@link AlertFeed#NEEDS_GATE} of the add-on.
     */
    public NewAlerts alertIdsAfter(int after, String baseurl) throws Exception {
        JsonValue v = call("opensuitegate", "view", "alertIds",
                p("after", String.valueOf(after), "baseurl", baseurl == null ? "" : baseurl));
        String last = str(v, "last"), top = str(v, "top"), ids = str(v, "ids");
        if (last == null || top == null) throw new java.io.IOException("the engine did not list its new alerts");
        List<Integer> out = new java.util.ArrayList<>();
        if (ids != null) for (String id : ids.split(",")) if (!id.isBlank()) out.add(Integer.parseInt(id.trim()));
        return new NewAlerts(out, Integer.parseInt(last.trim()), Integer.parseInt(top.trim()));
    }

    /** One answer of the add-on about an audit's rules: see {@link RuleFeed#take}. */
    public record RuleSteps(String rules, String steps, String names, String addresses, int next, boolean more) {}

    /**
     * Ask Open Suite's add-on how the rules of an audit stand and which it has
     * started on which addresses since step {@code after}; the caller says how
     * many rule names and addresses it already holds. Needs version
     * {@link RuleFeed#NEEDS_GATE} of the add-on.
     */
    public RuleSteps ruleSteps(String scanId, int after, int names, int addresses) throws Exception {
        JsonValue v = call("opensuitegate", "view", "ruleSteps", p("scanId", scanId, "after", String.valueOf(after),
                "names", String.valueOf(names), "addresses", String.valueOf(addresses)));
        String next = str(v, "next");
        if (next == null) throw new java.io.IOException("the engine did not report its rules");
        return new RuleSteps(str(v, "rules"), str(v, "steps"), str(v, "names"), str(v, "addresses"),
                Integer.parseInt(next.trim()), "1".equals(str(v, "more")));
    }

    /** One alert by its number, or null where there is none. */
    public JsonValue alert(int id) throws Exception {
        JsonValue v = call("core", "view", "alert", p("id", String.valueOf(id)));
        return v == null ? null : v.get("alert");
    }

    public JsonValue message(String id) throws Exception {
        JsonValue v = call("core", "view", "message", p("id", id));
        return v == null ? null : v.get("message");
    }

    /** Total messages ZAP has recorded this session (all tools). */
    /** Requests recorded since a given one: the requests, the number of the last record looked at, how many were unreadable, and whether more wait. */
    public record History(List<JsonValue> messages, int next, int skipped, boolean more) {}

    /** The version of the add-on that lists the engine's requests from a given one on, passing over any it cannot read. */
    public static final int HISTORY_NEEDS_GATE = 5;

    /**
     * Ask Open Suite's add-on for the requests recorded after the one numbered
     * {@code after}. Needs version {@link #HISTORY_NEEDS_GATE} of the add-on.
     */
    public History messagesAfter(int after, int count) throws Exception {
        List<JsonValue> all = arr(call("opensuitegate", "view", "messages",
                p("after", String.valueOf(after), "count", String.valueOf(count))), "messages");
        List<JsonValue> messages = new java.util.ArrayList<>();
        int next = after, skipped = 0;
        boolean more = false;
        for (JsonValue m : all) {
            String n = str(m, "next");
            if (n == null || n.isEmpty() || str(m, "requestHeader") != null && !str(m, "requestHeader").isEmpty()) { messages.add(m); continue; }
            try { next = Integer.parseInt(n.trim()); } catch (NumberFormatException e) { /* stays where it was */ }
            try { skipped = Integer.parseInt(String.valueOf(str(m, "skipped")).trim()); } catch (NumberFormatException e) { /* none said */ }
            more = "1".equals(str(m, "more"));
        }
        return new History(messages, next, skipped, more);
    }

    public int numberOfMessages() throws Exception {
        return intOf(call("core", "view", "numberOfMessages", null), "numberOfMessages");
    }

    /** A slice of ZAP's complete message history, for streaming into the logger. */
    public List<JsonValue> messages(int start, int count) throws Exception {
        return arr(call("core", "view", "messages",
                p("start", String.valueOf(start), "count", String.valueOf(count))), "messages");
    }

    public void shutdown() throws Exception {
        call("core", "action", "shutdown", null);
    }

    // ------------------------------------------------- passive scan-rule config

    /** Every passive rule ZAP has: id, name, enabled, alertThreshold, quality. */
    public List<JsonValue> passiveScanners() throws Exception {
        return arr(call("pscan", "view", "scanners", null), "scanners");
    }

    public void setPassiveEnabled(String id, boolean enabled) throws Exception {
        call("pscan", "action", enabled ? "enableScanners" : "disableScanners", p("ids", id));
    }

    public void setAllPassiveEnabled(boolean enabled) throws Exception {
        call("pscan", "action", enabled ? "enableAllScanners" : "disableAllScanners", null);
    }

    /** threshold is one of OFF, DEFAULT, LOW, MEDIUM, HIGH. */
    public void setPassiveThreshold(String id, String threshold) throws Exception {
        call("pscan", "action", "setScannerAlertThreshold", p("id", id, "alertThreshold", threshold));
    }

    // -------------------------------------------------- active scan-rule config

    /** Every active rule ZAP has: id, name, enabled, attackStrength, alertThreshold. */
    public List<JsonValue> activeScanners() throws Exception {
        return arr(call("ascan", "view", "scanners", null), "scanners");
    }

    public void setActiveEnabled(String id, boolean enabled) throws Exception {
        call("ascan", "action", enabled ? "enableScanners" : "disableScanners", p("ids", id));
    }

    /** strength is one of LOW, MEDIUM, HIGH, INSANE, DEFAULT. */
    public void setActiveStrength(String id, String strength) throws Exception {
        call("ascan", "action", "setScannerAttackStrength", p("id", id, "attackStrength", strength));
    }

    /** threshold is one of OFF, DEFAULT, LOW, MEDIUM, HIGH. */
    public void setActiveThreshold(String id, String threshold) throws Exception {
        call("ascan", "action", "setScannerAlertThreshold", p("id", id, "alertThreshold", threshold));
    }

    /**
     * Set the attack strength (LOW, MEDIUM, HIGH, INSANE) on every active rule, so
     * the whole default scan policy probes at the one intensity. Applied rule by
     * rule because ZAP has no single global strength control; a rule ZAP refuses
     * is skipped rather than failing the whole call.
     */
    public void setAllAttackStrength(String strength) throws Exception {
        for (JsonValue s : activeScanners()) {
            String id = str(s, "id");
            if (id != null) try { setActiveStrength(id, strength); }
            catch (Exception e) { Debug.log("strength for active rule " + id + ": " + e); }
        }
        // Read back: a rule the engine left at another level is set once more.
        for (JsonValue s : activeScanners()) {
            String id = str(s, "id"), now = str(s, "attackStrength");
            if (id != null && now != null && !now.equalsIgnoreCase(strength) && !"DEFAULT".equalsIgnoreCase(now))
                try { setActiveStrength(id, strength); } catch (Exception e) { Debug.log("strength for active rule " + id + ": " + e); }
        }
    }

    /** Set the alert threshold (OFF, LOW, MEDIUM, HIGH) on every active rule. */
    public void setAllAlertThreshold(String threshold) throws Exception {
        for (JsonValue s : activeScanners()) {
            String id = str(s, "id");
            if (id != null) try { setActiveThreshold(id, threshold); }
            catch (Exception e) { Debug.log("threshold for active rule " + id + ": " + e); }
        }
    }

    // ----------------------------------------------- active scan engine options

    /**
     * Which request locations the active scan injects payloads into, as a bitmask
     * of query string, POST body, URL path, headers and cookies (see
     * {@link ScanConfig}). More locations means broader coverage and more requests.
     */
    public void setInjectableParams(int mask) throws Exception {
        call("ascan", "action", "setOptionTargetParamsInjectable", p("Integer", String.valueOf(mask)));
    }

    /**
     * Which request-body content types the active scan tests (JSON, XML, multipart
     * and so on), as a bitmask (see {@link ScanConfig}). A type only applies when a
     * request actually carries it.
     */
    public void setInjectableRpc(int mask) throws Exception {
        call("ascan", "action", "setOptionTargetParamsEnabledRPC", p("Integer", String.valueOf(mask)));
    }

    /** Throttle between active-scan requests in milliseconds (0 = fastest). */
    public void setActiveDelayMs(int ms) throws Exception {
        call("ascan", "action", "setOptionDelayInMs", p("Integer", String.valueOf(Math.max(0, ms))));
    }

    /** Active-scan time backstop in minutes (0 = no limit). */
    public void setActiveMaxScanDuration(int minutes) throws Exception {
        call("ascan", "action", "setOptionMaxScanDurationInMins", p("Integer", String.valueOf(Math.max(0, minutes))));
    }

    /** Whether the crawler fills and submits forms to reach more of the site. */
    public void setSpiderProcessForms(boolean on) throws Exception {
        call("spider", "action", "setOptionPostForm", p("Boolean", String.valueOf(on)));
        call("spider", "action", "setOptionProcessForm", p("Boolean", String.valueOf(on)));
    }

    // ------------------------------------------------- AJAX spider budget options

    /** AJAX crawl time budget in minutes (0 = no limit). */
    public void setAjaxMaxDuration(int minutes) throws Exception {
        call("ajaxSpider", "action", "setOptionMaxDuration", p("Integer", String.valueOf(Math.max(0, minutes))));
    }

    /** AJAX crawl click-depth from the seed (0 = unlimited). */
    public void setAjaxMaxCrawlDepth(int depth) throws Exception {
        call("ajaxSpider", "action", "setOptionMaxCrawlDepth", p("Integer", String.valueOf(Math.max(0, depth))));
    }

    /** How many distinct UI states the AJAX crawl explores (0 = unlimited). */
    public void setAjaxMaxCrawlStates(int states) throws Exception {
        call("ajaxSpider", "action", "setOptionMaxCrawlStates", p("Integer", String.valueOf(Math.max(0, states))));
    }

    // ----------------------------------------------------------- json helpers

    public static String str(JsonValue o, String k) {
        JsonValue v = (o == null) ? null : o.get(k);
        return v == null ? null : v.asString();
    }

    public static int intOf(JsonValue o, String k) {
        try { return Integer.parseInt(str(o, k)); } catch (Exception e) { return -1; }
    }

    static List<JsonValue> arr(JsonValue o, String k) {
        JsonValue v = (o == null) ? null : o.get(k);
        return (v == null || !v.isArray()) ? List.of() : v.asArray();
    }
}