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.

63.2 KB
Raw Blame
package opensuite.dashboard;

import opensuite.engine.ScanConfig;
import opensuite.engine.ScanConfigStore;
import opensuite.ui.Glyphs;
import opensuite.ui.OptionsPage;
import opensuite.ui.Theme;
import opensuite.ui.Ui;

import javax.swing.*;
import javax.swing.table.AbstractTableModel;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreeSelectionModel;
import java.awt.*;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * The scan configuration step shared by the New scan wizard and the live task
 * dialog: a preset chooser (Lightweight / Fast / Balanced / Deep / Custom) with
 * Save and Load, and, for Custom, a tree of configuration pages: crawl
 * optimization, limits, login functions, error handling and project overrides
 * under "Crawl configuration"; audit behaviour, scan checks, JavaScript
 * analysis and insertion points under "Audit configuration". The controls that
 * drive the engine map onto {@link ScanConfig}; the rest are kept with the
 * configuration so a saved one reloads exactly as it was.
 */
public final class ScanConfigPanel extends JPanel {

    /** Which trees to show. */
    public enum Mode { CRAWL_AND_AUDIT, CRAWL, AUDIT, PASSIVE_CRAWL }

    public record Preset(String name, String description) {}
    public static final List<Preset> PRESETS = List.of(
            new Preset("Lightweight", "Gain fast feedback on a site's security. Will complete within 15 minutes."),
            new Preset("Fast", "Greater coverage while keeping scan times low. Generally completes within one hour."),
            new Preset("Balanced", "Provides a balance between coverage and speed. Generally completes within a few hours."),
            new Preset("Deep", "Achieve comprehensive coverage. Scanning time depends on the target site's size and complexity."),
            new Preset("Custom", "Configure the default scan settings to meet your needs."));

    private final Mode mode;
    private final JComboBox<Preset> preset = new JComboBox<>(PRESETS.toArray(new Preset[0]));
    private final JPanel custom = new JPanel(new BorderLayout(8, 0));
    private final CardLayout pageCards = new CardLayout();
    private final JPanel pages = new JPanel(pageCards);
    private final Map<String, JComponent> pageByName = new LinkedHashMap<>();

    // ---- Crawl behaviour
    private final JTextField maxDepth = num("4", 126);
    private final JComboBox<String> crawlStrategy = Ui.combo(new String[]{"Fastest", "Faster", "Normal", "More complete", "Most complete"});
    private final JTextArea strategyNote = opensuite.ui.Sections.fill(opensuite.ui.Sections.text(""));
    private final JTextField maxCrawlMin = num("150", 74);
    private final JTextField maxLocations = num("1500", 74);
    private final JTextField maxRequests = num("", 74);
    private final JTextField crawlConnectSecs = num("", 86);
    private final JTextField crawlRequestSecs = num("", 86);
    private final JTextField crawlTimeouts = num("15", 62);
    private final JTextField crawlTimeoutPct = num("", 62);
    private final JTextField crawlAuthFailures = num("2", 62);
    private final JTextField crawlRetries = num("1", 82);
    // Advanced crawl settings, behind the button.
    private final JComboBox<String> crawlSpeed = Ui.combo(new String[]{"Fast", "Normal", "Slow"});
    private final JSpinner ajaxDepth = spin(10, 0, 100, 1);
    private final JSpinner ajaxStates = spin(0, 0, 10000, 10);
    // ---- Login behaviour
    private final JCheckBox authenticatedOnly = Ui.check("Only perform an authenticated crawl using the provided credentials", false);
    private final JCheckBox selfRegister = Ui.check("Try to self-register a user", true);
    private final JCheckBox triggerFailures = Ui.check("Use invalid usernames to trigger login failures", true);
    // ---- API crawling
    private final JCheckBox apiDefinitions = Ui.check("Parse API definitions", true);
    private final JCheckBox apiWsdl = Ui.check("Parse SOAP WSDL definitions", true);
    private final JCheckBox apiGraphql = Ui.check("Perform GraphQL introspection", true);
    private final JCheckBox apiGraphqlCommon = Ui.check("Test common GraphQL endpoints", false);
    // ---- Browser behaviour
    private final JComboBox<String> browserUse = Ui.combo(new String[]{"Use if my hardware appears to support it", "Always", "Never"});
    private final JCheckBox customAgent = Ui.check("Customize User-Agent header", false);
    private final JTextField userAgent = num("", 358);
    private final JCheckBox fetchOutOfScope = Ui.check("Fetch required resources and data from out-of-scope hosts", true);
    private final JTextField resourceTimeout = num("10", 280);
    // ---- Discovery logic
    private final JCheckBox submitForms = Ui.check("Submit forms", true);
    private final JCheckBox requestRobots = Ui.check("Request robots.txt", true);
    private final JCheckBox requestSitemap = Ui.check("Request site map", true);
    private final JTextField sitemapItems = num("1000", 134);
    private final JCheckBox hiddenLinks = Ui.check("Follow hidden links in comments and JavaScript", true);
    private final JTextField hiddenLinkCount = num("1000", 134);
    private final JCheckBox clickAll = Ui.check("Click all clickable elements", true);
    private final JCheckBox clickPointer = Ui.check("Click all pointer clickable elements", false);
    private final JComboBox<String> fragments = Ui.combo(new String[]{"Unsure", "Yes", "No"});
    // ---- Audit behaviour
    private final JComboBox<String> auditSpeed = Ui.combo(new String[]{"Fast", "Normal", "Thorough"});
    private final JComboBox<String> auditAccuracy = Ui.combo(new String[]{"Minimize false negatives", "Normal", "Minimize false positives"});
    private final JCheckBox skipIneffective = Ui.check("Skip checks unlikely to be effective", true);
    private final JCheckBox maintainSession = Ui.check("Automatically maintain session (doesn't apply to audit-only scans)", true);
    private final JCheckBox followRedirects = Ui.check("Follow redirections when necessary", true);
    private final JCheckBox parallelPhases = Ui.check("Allow crawl and audit phases to run in parallel", true);
    private final JTextField maxScanMin = num("", 86);
    private final JCheckBox consolidatePassive = Ui.check("Consolidate frequently occurring passive issues", true);
    private final JTextField connectTimeout = num("", 86);
    private final JTextField requestTimeout = num("", 86);
    private final JTextField failChecks = num("2", 62);
    private final JTextField failPoints = num("2", 62);
    private final JTextField failItems = num("60", 62);
    private final JTextField failPct = num("", 62);
    private final JTextField followUpPasses = num("1", 62);
    // ---- JavaScript analysis
    private final JCheckBox jsDynamic = Ui.check("Use dynamic analysis techniques", true);
    private final JCheckBox jsStatic = Ui.check("Use static analysis techniques", false);
    private final JCheckBox jsMissing = Ui.check("Make requests for missing site resources", true);
    private final JCheckBox jsOutOfScope = Ui.check("Fetch previously undiscovered resources and data from out-of-scope hosts", true);
    private final JTextField jsDynamicSecs = num("30", 110);
    private final JTextField jsStaticSecs = num("30", 110);
    // ---- Insertion points
    private static final String[] POINT_TYPES = {"URL parameter values", "Body parameter values", "Cookie parameter values",
            "Parameter name", "HTTP headers", "Entire body (for relevant content types)", "URL path filename", "URL path folders"};
    private final JCheckBox ipQuery = Ui.check(POINT_TYPES[0], true);
    private final JCheckBox ipBody = Ui.check(POINT_TYPES[1], true);
    private final JCheckBox ipCookie = Ui.check(POINT_TYPES[2], true);
    private final JCheckBox ipName = Ui.check(POINT_TYPES[3], true);
    private final JCheckBox ipHeaders = Ui.check(POINT_TYPES[4], true);
    private final JCheckBox ipEntireBody = Ui.check(POINT_TYPES[5], true);
    private final JCheckBox ipFilename = Ui.check(POINT_TYPES[6], true);
    private final JCheckBox ipFolders = Ui.check(POINT_TYPES[7], true);
    private final JCheckBox[] frequent = new JCheckBox[POINT_TYPES.length];
    /** The structured body formats the entire-body insertion point covers; a loaded configuration can narrow them. */
    private int rpcFormats = ScanConfig.RPC_MULTIPART | ScanConfig.RPC_XML | ScanConfig.RPC_JSON | ScanConfig.RPC_GWT | ScanConfig.RPC_ODATA;
    private final JCheckBox nested = Ui.check("Use nested insertion points", true);
    private final JCheckBox arrayPoints = Ui.check("Create insertion points for all array elements", false);
    private final JTextField maxPoints = num("30", 74);
    private final JCheckBox[] relocate = {
            Ui.check("URL to body", false), Ui.check("URL to cookie", false), Ui.check("Body to URL", false),
            Ui.check("Body to cookie", false), Ui.check("Cookie to URL", false), Ui.check("Cookie to body", false)};
    private final SkipTable skipInjection = new SkipTable(defaultSkipInjection());
    private final SkipTable skipAll = new SkipTable(defaultSkipAll());
    // ---- Scan checks
    private final ChecksTable checks = new ChecksTable();
    // ---- Live passive crawl
    private final JCheckBox pcLinks = Ui.check("Links", true);
    private final JCheckBox pcForms = Ui.check("Form submissions", false);
    private final JCheckBox pcEverything = Ui.check("Everything", false);
    private final JCheckBox pcItself = Ui.check("The item itself", true);
    private final JCheckBox pcSameDomain = Ui.check("Items on the same domain", true);
    private final JCheckBox pcInScope = Ui.check("URLs in scope with", true);
    private final JRadioButton pcSuiteScope = Ui.radio("Suite scope", true);
    private final JRadioButton pcCustomScope = Ui.radio("Custom scope", false);

    public ScanConfigPanel(Mode mode) {
        super(new BorderLayout(0, 10));
        this.mode = mode;
        setOpaque(false);

        // Header row: Save / Load on the right, preset combo beneath the note.
        JButton save = Ui.button("Save", "Save this configuration to the library");
        JButton load = Ui.button("Load", "Load a configuration from the library");
        save.setIcon(Glyphs.save(15, Theme.ICON));
        load.setIcon(Glyphs.download(15, Theme.ICON));
        save.setIconTextGap(8);
        load.setIconTextGap(8);
        save.addActionListener(e -> save());
        load.addActionListener(e -> load());
        JPanel actions = new JPanel(new FlowLayout(FlowLayout.RIGHT, 6, 0));
        actions.setOpaque(false);
        actions.add(save); actions.add(load);

        preset.setFont(Ui.PLAIN);
        preset.setRenderer(new PresetRenderer());
        preset.setMaximumRowCount(PRESETS.size());   // every choice shows at once, with no scroll bar
        preset.setPreferredSize(new Dimension(Ui.em(300), 28 + 2 * Ui.fontGrowth()));   // one line closed; it takes the page's width
        // All five show at once, so the list has no scroll bar to draw.
        preset.addPopupMenuListener(new javax.swing.event.PopupMenuListener() {
            @Override public void popupMenuWillBecomeVisible(javax.swing.event.PopupMenuEvent e) {
                if (preset.getAccessibleContext().getAccessibleChild(0) instanceof javax.swing.plaf.basic.ComboPopup popup
                        && SwingUtilities.getAncestorOfClass(JScrollPane.class, popup.getList()) instanceof JScrollPane scroll) {
                    scroll.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_NEVER);
                }
            }
            @Override public void popupMenuWillBecomeInvisible(javax.swing.event.PopupMenuEvent e) { }
            @Override public void popupMenuCanceled(javax.swing.event.PopupMenuEvent e) { }
        });
        preset.addActionListener(e -> onPreset());

        JPanel top = new JPanel(new BorderLayout(0, 6));
        top.setOpaque(false);
        JPanel head = new JPanel(new BorderLayout());
        head.setOpaque(false);
        head.add(Ui.note(mode == Mode.PASSIVE_CRAWL
                ? "Select how the live passive crawl adds items to the site map."
                : "Select the type of scan configuration you want to run, or load an existing configuration. You can adjust the configuration as needed."), BorderLayout.CENTER);
        head.add(actions, BorderLayout.EAST);
        top.add(head, BorderLayout.NORTH);
        JPanel presetRow = new JPanel(new BorderLayout());
        presetRow.setOpaque(false);
        presetRow.setBorder(Ui.pad(8, 0, 0, 0));
        presetRow.add(preset, BorderLayout.CENTER);
        if (mode != Mode.PASSIVE_CRAWL) top.add(presetRow, BorderLayout.CENTER);
        add(top, BorderLayout.NORTH);

        // The tree + pages.
        DefaultMutableTreeNode root = new DefaultMutableTreeNode("config");
        if (mode == Mode.PASSIVE_CRAWL) {
            DefaultMutableTreeNode pc = node(root, "Live passive crawl configuration");
            leaf(pc, "Live passive crawl", passiveCrawlPage());
        } else {
            if (mode != Mode.AUDIT) {
                DefaultMutableTreeNode crawl = node(root, "Crawl configuration");
                leaf(crawl, "Crawl behaviour", crawlBehaviourPage());
                leaf(crawl, "Login behaviour", loginBehaviourPage());
                leaf(crawl, "API crawling", apiCrawlingPage());
                leaf(crawl, "Browser behaviour", browserBehaviourPage());
                leaf(crawl, "Discovery logic", discoveryLogicPage());
            }
            if (mode != Mode.CRAWL) {
                DefaultMutableTreeNode audit = node(root, "Audit configuration");
                leaf(audit, "Audit behaviour", auditBehaviourPage());
                leaf(audit, "Scan checks", checks);
                leaf(audit, "JavaScript analysis", javascriptPage());
                leaf(audit, "Insertion points strategy", insertionPointsPage());
            }
        }
        // The page list: plain names, no icons, the chosen one on a rounded band.
        opensuite.ui.RowTree tree = new opensuite.ui.RowTree(new DefaultTreeModel(root));
        tree.setRootVisible(false);
        tree.setShowsRootHandles(true);
        tree.setRowHeight(28);
        tree.setBand(2, 2);
        tree.setBorder(Ui.pad(2, 6, 2, 2));
        javax.swing.tree.DefaultTreeCellRenderer names = new javax.swing.tree.DefaultTreeCellRenderer();
        names.setLeafIcon(null); names.setOpenIcon(null); names.setClosedIcon(null);
        tree.setCellRenderer(names);
        tree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
        for (int i = 0; i < tree.getRowCount(); i++) tree.expandRow(i);
        tree.addTreeSelectionListener(e -> {
            Object o = tree.getLastSelectedPathComponent();
            if (o instanceof DefaultMutableTreeNode n && pageByName.containsKey(String.valueOf(n.getUserObject())))
                pageCards.show(pages, String.valueOf(n.getUserObject()));
        });
        JScrollPane ts = new JScrollPane(tree);
        ts.setBorder(BorderFactory.createMatteBorder(0, 0, 0, 1, Ui.GRID));
        ts.getViewport().setBackground(Theme.BG);
        ts.setPreferredSize(new Dimension(mode == Mode.PASSIVE_CRAWL ? 250 : 300, 10));
        pages.setOpaque(false);
        // One box holds the list and the page, with a line between them.
        custom.setLayout(new BorderLayout());
        custom.setOpaque(false);
        custom.setBorder(BorderFactory.createLineBorder(Ui.GRID));
        custom.add(ts, BorderLayout.WEST);
        custom.add(pages, BorderLayout.CENTER);
        add(custom, BorderLayout.CENTER);
        // What the scan engine cannot do yet stays on the page, greyed, so the page keeps its shape.
        notYet(crawlStrategy, crawlSpeed, crawlTimeouts, crawlTimeoutPct, crawlAuthFailures, crawlRetries,
                authenticatedOnly, selfRegister, triggerFailures,
                apiDefinitions, apiWsdl, apiGraphql,
                fetchOutOfScope, resourceTimeout, hiddenLinkCount, clickPointer, fragments,
                skipIneffective, maintainSession, followRedirects, parallelPhases, consolidatePassive,
                failChecks, failPoints, failItems, failPct, followUpPasses,
                jsStatic, jsMissing, jsOutOfScope, jsDynamicSecs, jsStaticSecs,
                ipName, nested, arrayPoints, maxPoints);
        notYet(relocate);
        notYet(frequent);
        // Select the first leaf.
        for (int i = 0; i < tree.getRowCount(); i++) {
            Object o = tree.getPathForRow(i).getLastPathComponent();
            if (o instanceof DefaultMutableTreeNode n && n.isLeaf()) { tree.setSelectionRow(i); break; }
        }

        preset.setSelectedIndex(mode == Mode.PASSIVE_CRAWL ? 4 : 2);   // Balanced, or Custom for passive crawl
        onPreset();
    }

    private DefaultMutableTreeNode node(DefaultMutableTreeNode parent, String name) {
        DefaultMutableTreeNode n = new DefaultMutableTreeNode(name);
        parent.add(n);
        return n;
    }

    private void leaf(DefaultMutableTreeNode parent, String name, JComponent page) {
        parent.add(new DefaultMutableTreeNode(name));
        pageByName.put(name, page);
        pages.add(page, name);
    }

    private static JSpinner spin(int v, int min, int max, int step) {
        JSpinner s = new JSpinner(new SpinnerNumberModel(v, min, max, step));
        s.setFont(Ui.PLAIN);
        s.setPreferredSize(new Dimension(80, s.getPreferredSize().height));
        return s;
    }

    /** A plain box for a number, as the reference has them: no arrows, and empty where a limit is not set. */
    private static JTextField num(String value, int width) {
        JTextField f = Ui.field(value);
        f.setColumns(0);
        f.setPreferredSize(new Dimension(width + 4 * Ui.fontGrowth(), Ui.tall(24)));
        return f;
    }

    /** The whole number in a box, or {@code blank} when it is empty or is not one. */
    static int intOf(JTextField f, int blank) {
        try { return Math.max(0, Integer.parseInt(f.getText().strip())); }
        catch (NumberFormatException e) { return blank; }
    }

    private static void put(JTextField f, int value, boolean zeroIsBlank) {
        f.setText(value == 0 && zeroIsBlank ? "" : String.valueOf(value));
    }

    static final String NOT_YET = "Not available yet";

    /** Grey out controls the engine has nothing behind, and say so when the pointer rests on one. */
    private static void notYet(JComponent... controls) {
        for (JComponent c : controls) {
            if (c == null) continue;
            c.setEnabled(false);
            c.setToolTipText(NOT_YET);
            // A box or a list has to look as dead as it is.
            if (c instanceof javax.swing.text.JTextComponent t) { t.setDisabledTextColor(Theme.DISABLED_TEXT); t.setBackground(Theme.SURFACE); }
        }
    }

    private static JPanel row(Component... c) { return Ui.row(c); }

    private static JTextArea para(String s) { return opensuite.ui.Sections.text(s); }

    /** Words that follow a box, in the case they are written: Ui.label would start them with a capital. */
    private static JLabel plain(String s) {
        JLabel l = new JLabel(s);
        l.setFont(Ui.PLAIN);
        l.setForeground(Theme.TEXT);
        return l;
    }

    // ---- pages ----

    private static final Map<String, String> STRATEGY_NOTES = Map.of(
            "Fastest", "This strategy is the quickest. It suits applications whose pages are reached by plain links and hold no state.",
            "Faster", "This strategy favours speed over coverage, and suits simple applications.",
            "Normal", "This strategy represents a trade-off between coverage and speed that is appropriate for typical applications.",
            "More complete", "This strategy favours coverage over speed, and suits applications with more state or more complex navigation.",
            "Most complete", "This strategy gives the fullest coverage and takes the longest. It suits applications where the same address can show different content.");

    private JComponent crawlBehaviourPage() {
        OptionsPage p = new OptionsPage();
        crawlStrategy.setSelectedItem("Normal");
        crawlSpeed.setSelectedItem("Normal");
        Ui.sized(crawlStrategy, 126);
        Runnable note = () -> strategyNote.setText(STRATEGY_NOTES.getOrDefault(String.valueOf(crawlStrategy.getSelectedItem()), ""));
        crawlStrategy.addActionListener(e -> note.run());
        note.run();
        JButton advanced = Ui.button("View advanced settings", "Crawl speed and the limits of the browser's exploring");
        advanced.addActionListener(e -> JOptionPane.showMessageDialog(this,
                Ui.form("Crawl speed:", Ui.natural(crawlSpeed), "Maximum click depth:", Ui.natural(ajaxDepth), "Maximum page states explored (0 for no limit):", Ui.natural(ajaxStates)),
                "Advanced crawl settings", JOptionPane.PLAIN_MESSAGE));
        JLabel depthLabel = Ui.label("Maximum crawl depth:"), strategyLabel = Ui.label("Crawl strategy:");
        strategyLabel.setPreferredSize(depthLabel.getPreferredSize());
        p.section("Crawl strategy",
                Ui.note("Choose a strategy and crawl depth to balance crawl coverage and speed based on your application's structure."),
                row(depthLabel, maxDepth, plain("steps from start URL")),
                row(strategyLabel, crawlStrategy),
                strategyNote,
                Box.createVerticalStrut(4),
                row(advanced),
                para("We recommend that you only change the advanced settings when an application needs it."));
        p.section("Crawl limits",
                Ui.note("Control how long Open Suite crawls your site and how much content it explores. Unique content is found early, so limits help reduce scan time and overhead."),
                para("To disable a limit, leave it blank."),
                Box.createVerticalStrut(3),
                OptionsPage.fieldRow("Maximum crawl time:", maxCrawlMin, "minutes"),
                OptionsPage.fieldRow("Maximum unique locations discovered:", maxLocations, ""),
                OptionsPage.fieldRow("Maximum request count:", maxRequests, ""),
                para("These settings only impact the crawl phase. For crawl and audit scans, you can also set an overall scan time. The scan stops when this limit is reached, even if crawling or auditing is in progress. Configure this under Audit behaviour > Total scan time."));
        p.section("Crawl network timeouts",
                Ui.note("Set time limits for network tasks during the crawl. These override your global timeouts under Settings > Network > Connections > Timeouts."),
                para("To turn off a timeout, set it to 0. To use your global settings, leave blank."),
                Box.createVerticalStrut(3),
                OptionsPage.fieldRow("Maximum wait to establish a connection:", crawlConnectSecs, "seconds"),
                OptionsPage.fieldRow("Maximum wait to complete the request after connecting:", crawlRequestSecs, "seconds"));
        p.section("Handling repeated timeouts during crawl",
                Ui.note("Control how Open Suite responds to repeated request timeouts during the crawl."),
                para("Pause the crawl if:"),
                Box.createVerticalStrut(3),
                OptionsPage.indent(row(crawlTimeouts, plain("consecutive requests time out")), 5),
                OptionsPage.indent(row(crawlTimeoutPct, plain("% of all requests time out")), 5),
                OptionsPage.indent(row(crawlAuthFailures, plain("consecutive authentication failures")), 5),
                Box.createVerticalStrut(4),
                row(Ui.label("After the crawl, do"), crawlRetries, plain("follow-up passes to retry requests that timed out.")));
        return p;
    }

    private JComponent loginBehaviourPage() {
        OptionsPage p = new OptionsPage();
        p.section("Authenticated crawl only",
                Ui.note("Choose whether Open Suite only runs an authenticated crawl, using credentials that you set in the Application login tab. If no credentials are set, Open Suite runs an unauthenticated crawl instead."),
                para("If you set credentials but don't enable this setting, Open Suite crawls the site both logged out and logged in. In some cases, this means the authenticated crawl may not find much extra content."),
                Box.createVerticalStrut(3),
                authenticatedOnly);
        p.section("Testing login functions",
                Ui.note("Choose how Open Suite tests login functionality during the unauthenticated crawl phase."),
                para("These settings are ignored if you use a recorded login sequence or enable Authenticated crawl only."),
                Box.createVerticalStrut(3),
                selfRegister, triggerFailures);
        return p;
    }

    private JComponent apiCrawlingPage() {
        OptionsPage p = new OptionsPage();
        p.section("API crawling",
                Ui.note("Configure how Open Suite detects and explores APIs when crawling your site."),
                apiDefinitions, apiWsdl, apiGraphql, OptionsPage.indent(apiGraphqlCommon, 21));
        return p;
    }

    private JComponent browserBehaviourPage() {
        OptionsPage p = new OptionsPage();
        Ui.sized(browserUse, 280);
        userAgent.setEnabled(false);
        JLabel agentLabel = Ui.label("User-Agent:"), timeoutLabel = Ui.label("Read timeout for site resources:");
        agentLabel.setPreferredSize(new Dimension(timeoutLabel.getPreferredSize().width + 22, agentLabel.getPreferredSize().height));
        timeoutLabel.setPreferredSize(agentLabel.getPreferredSize());
        agentLabel.setEnabled(false);
        customAgent.addItemListener(e -> { userAgent.setEnabled(customAgent.isSelected()); agentLabel.setEnabled(customAgent.isSelected()); });
        p.section("Browser behaviour",
                Ui.note("Configure how Open Suite loads and interacts with websites when crawling your site."),
                row(Ui.label("Use the browser for Crawl and Audit"), browserUse),
                Box.createVerticalStrut(4),
                customAgent,
                OptionsPage.indent(row(agentLabel, userAgent), 21),
                fetchOutOfScope,
                OptionsPage.indent(row(timeoutLabel, resourceTimeout, plain("milliseconds")), 21));
        return p;
    }

    private JComponent discoveryLogicPage() {
        OptionsPage p = new OptionsPage();
        Ui.sized(fragments, 134);
        JLabel a = Ui.label("Maximum items to request from site map:"), b = Ui.label("Maximum hidden links to follow:"),
                c = Ui.label("Application uses fragments for routing");
        b.setPreferredSize(a.getPreferredSize());
        c.setPreferredSize(new Dimension(a.getPreferredSize().width + 21, c.getPreferredSize().height));
        requestSitemap.addItemListener(e -> sitemapItems.setEnabled(requestSitemap.isSelected()));
        p.section("Discovery logic",
                Ui.note("Configure how Open Suite discovers and interacts with different types of content when crawling your site."),
                submitForms, requestRobots, requestSitemap,
                OptionsPage.indent(row(a, sitemapItems), 21),
                hiddenLinks,
                OptionsPage.indent(row(b, hiddenLinkCount), 21),
                clickAll, clickPointer,
                row(c, fragments));
        return p;
    }

    private JComponent auditBehaviourPage() {
        OptionsPage p = new OptionsPage();
        auditSpeed.setSelectedItem("Normal");
        auditAccuracy.setSelectedItem("Normal");
        Ui.sized(auditSpeed, 180); Ui.sized(auditAccuracy, 180);
        JLabel speed = Ui.label("Audit speed:"), accuracy = Ui.label("Audit accuracy:");
        speed.setPreferredSize(accuracy.getPreferredSize());
        p.section("Audit strategy",
                Ui.note("These settings enable you to control audit coverage and speed based on your application's structure."),
                para("Control how many requests Open Suite sends and how deeply it checks for vulnerabilities."),
                Box.createVerticalStrut(3),
                row(speed, auditSpeed),
                para("Control how many times Open Suite retries tests to confirm issues. Minimizing false negatives means fewer retries; minimizing false positives means more retries."),
                Box.createVerticalStrut(3),
                row(accuracy, auditAccuracy),
                Box.createVerticalStrut(4),
                skipIneffective, maintainSession, followRedirects, parallelPhases);
        p.section("Total scan time",
                Ui.note("Limit the total run time for a scan. When the time limit is reached, the scan stops immediately, even if the crawl or audit isn't finished."),
                para("This doesn't apply to audit-only scans."),
                Box.createVerticalStrut(3),
                OptionsPage.fieldRow("Maximum scan time:", maxScanMin, "minutes"));
        p.section("Issue noise reduction",
                Ui.note("Reduce noise by grouping repeated passive issues in the scan results."),
                consolidatePassive);
        p.section("Audit network timeouts",
                Ui.note("Set time limits for network tasks during the audit. These override your global timeout settings under Settings > Network > Connections > Timeouts."),
                para("To turn off a timeout, set it to 0. To use your global settings, leave blank."),
                Box.createVerticalStrut(3),
                OptionsPage.fieldRow("Maximum time to establish a connection:", connectTimeout, "seconds"),
                OptionsPage.fieldRow("Maximum time to complete the request after connecting:", requestTimeout, "seconds"));
        p.section("Handling repeated timeouts during audit",
                Ui.note("Control how Open Suite responds to repeated timeouts during the audit."),
                row(Ui.label("If"), failChecks, plain("consecutive audit checks fail, skip remaining checks in the current insertion point")),
                row(Ui.label("If"), failPoints, plain("consecutive insertion points fail, skip remaining insertion points, and flag audit item as failed")),
                para("Pause the audit if:"),
                Box.createVerticalStrut(3),
                OptionsPage.indent(row(failItems, plain("consecutive audit items fail")), 13),
                OptionsPage.indent(row(failPct, plain("% of audit items fail")), 13),
                Box.createVerticalStrut(4),
                row(Ui.label("On completion of each audit phase, do"), followUpPasses, plain("follow-up passes to retry failed operations")));
        return p;
    }

    private JComponent javascriptPage() {
        OptionsPage p = new OptionsPage();
        JLabel a = Ui.label("Maximum dynamic analysis time per item:"), b = Ui.label("Maximum static analysis time per item:");
        b.setPreferredSize(a.getPreferredSize());
        p.section("JavaScript analysis",
                Ui.note("Configure how Open Suite detects DOM-based vulnerabilities in JavaScript."),
                jsDynamic, jsStatic, jsMissing, OptionsPage.indent(jsOutOfScope, 21),
                Box.createVerticalStrut(4),
                row(a, jsDynamicSecs, plain("seconds")),
                row(b, jsStaticSecs, plain("seconds")));
        return p;
    }

    private JComponent insertionPointsPage() {
        OptionsPage p = new OptionsPage();
        for (int i = 0; i < frequent.length; i++) frequent[i] = Ui.check(POINT_TYPES[i], true);
        p.section("Set insertion point types",
                Ui.note("Select which parts of the request Open Suite inserts payloads into:"),
                ipQuery, ipBody, ipCookie, ipName, ipHeaders, ipEntireBody, ipFilename, ipFolders);
        p.section("Ignore specific insertion points",
                Ui.note("Skip server-side injection tests for these parameters:"),
                opensuite.ui.Sections.fill(skipInjection),
                Box.createVerticalStrut(6),
                para("Skip all tests for these parameters:"),
                Box.createVerticalStrut(3),
                opensuite.ui.Sections.fill(skipAll));
        List<Component> often = new ArrayList<>();
        often.add(Ui.note("If the same insertion point appears often with no change in results, Open Suite runs a lighter audit to speed up scanning."));
        often.add(para("Select the insertion point types this applies to:"));
        often.addAll(List.of(frequent));
        p.section("Handling frequent insertion points", often.toArray(new Component[0]));
        p.section("Nested insertion points",
                Ui.note("Choose whether Open Suite places payloads into insertion points within nested data structures, such as JSON within URL parameters."),
                nested);
        p.section("Array insertion points",
                Ui.note("Choose whether Open Suite places payloads into every element of an array, or just a single value. Includes JSON arrays, and repeated or array-notation URL, body, and multipart parameters."),
                arrayPoints);
        p.section("Insertion point limits",
                Ui.note("Limit how many insertion points are used in each base request. This helps speed up auditing when scanning requests with many parameters."),
                OptionsPage.fieldRow("Maximum insertion points per base request:", maxPoints, ""));
        // Two columns: where a payload starts, then each place it can be moved to.
        JPanel grid = new JPanel(new GridLayout(3, 2, 12, opensuite.ui.Sections.ROW_GAP));
        grid.setOpaque(false);
        for (JCheckBox b : relocate) grid.add(b);
        p.section("Payload relocation rules",
                Ui.note("Insert payloads for one insertion point type into other insertion point types. This may help evade some filters, but creates many more requests."),
                para("Select new payload destinations:"),
                Box.createVerticalStrut(3),
                row(grid));
        return p;
    }

    private JComponent passiveCrawlPage() {
        OptionsPage p = new OptionsPage();
        ButtonGroup g = new ButtonGroup();
        g.add(pcSuiteScope); g.add(pcCustomScope);
        p.section("Types of item to add", pcLinks, pcForms);
        p.section("URLs to add", pcEverything, pcItself, pcSameDomain,
                row(pcInScope, pcSuiteScope, pcCustomScope));
        return p;
    }

    // ---- presets ----

    private void onPreset() {
        Preset p = (Preset) preset.getSelectedItem();
        boolean isCustom = p == null || "Custom".equals(p.name());
        custom.setVisible((isCustom && !(p == null && mustChoose)) || mode == Mode.PASSIVE_CRAWL);
        if (!isCustom && p != null) apply(ScanConfig.preset(p.name()));
        // Custom starts from the default settings, not from whichever preset was shown before it.
        if (isCustom && p != null && !wasCustom) apply(customDefaults());
        wasCustom = isCustom && p != null;
        revalidate();
        repaint();
    }

    private boolean mustChoose;
    private boolean wasCustom;

    /** The settings Custom opens with: four steps deep, 150 minutes of crawling, normal speed and accuracy. */
    static ScanConfig customDefaults() {
        ScanConfig b = ScanConfig.preset("Balanced");
        return new ScanConfig("Custom", 4, 150, true, true, 0, 10, 0, "MEDIUM", "MEDIUM", b.injectableMask(), b.rpcMask(), 0, 0,
                new ScanConfig.Options(true, true, true, true, "", -1, -1, 1500, 0, null, false, 1000));
    }

    /**
     * Start with no configuration selected: the list says to select one, and
     * {@link #chosen()} is false until the user has. A scan is not started on
     * a configuration nobody picked.
     */
    public void requireChoice() {
        mustChoose = true;
        preset.setSelectedIndex(-1);
        onPreset();
    }

    /** Whether a configuration is selected. Always true where one is selected to begin with. */
    public boolean chosen() { return preset.getSelectedItem() != null; }

    public String presetName() {
        Preset p = (Preset) preset.getSelectedItem();
        return p == null ? "Custom" : p.name();
    }

    /** Put a configuration's values into the controls. */
    public void apply(ScanConfig c) {
        put(maxDepth, c.crawlDepth(), false);
        put(maxCrawlMin, c.crawlDurationMin(), true);
        submitForms.setSelected(c.submitForms());
        browserUse.setSelectedIndex(c.ajaxSpider() ? 0 : 2);
        jsDynamic.setSelected(c.ajaxSpider());
        put(jsDynamicSecs, Math.max(1, c.ajaxMaxDurationMin() == 0 ? 30 : c.ajaxMaxDurationMin() * 60), false);
        ajaxDepth.setValue(c.ajaxMaxDepth());
        ajaxStates.setValue(c.ajaxMaxStates());
        auditSpeed.setSelectedItem(switch (c.attackStrength()) { case "LOW" -> "Fast"; case "HIGH", "INSANE" -> "Thorough"; default -> "Normal"; });
        auditAccuracy.setSelectedItem(switch (c.alertThreshold()) { case "LOW" -> "Minimize false negatives"; case "HIGH" -> "Minimize false positives"; default -> "Normal"; });
        int inj = c.injectableMask();
        ipQuery.setSelected((inj & ScanConfig.INJECT_QUERY) != 0);
        ipBody.setSelected((inj & ScanConfig.INJECT_BODY) != 0);
        ipFilename.setSelected((inj & ScanConfig.INJECT_PATH) != 0);
        ipFolders.setSelected((inj & ScanConfig.INJECT_PATH) != 0);
        ipHeaders.setSelected((inj & ScanConfig.INJECT_HEADERS) != 0);
        ipCookie.setSelected((inj & ScanConfig.INJECT_COOKIE) != 0);
        // The structured body formats are kept as the configuration gave them; the tick box covers them all.
        rpcFormats = c.rpcMask();
        ipEntireBody.setSelected(rpcFormats != 0);
        put(maxScanMin, c.scanDurationMin(), true);
        ScanConfig.Options o = c.more();
        requestRobots.setSelected(o.robots());
        requestSitemap.setSelected(o.sitemap());
        hiddenLinks.setSelected(o.hiddenLinks());
        clickAll.setSelected(o.clickAll());
        customAgent.setSelected(!o.userAgent().isEmpty());
        userAgent.setText(o.userAgent());
        // The engine has one timeout: it stands in the second box, the wait for the whole request.
        crawlConnectSecs.setText("");
        crawlRequestSecs.setText(o.crawlTimeoutSecs() < 0 ? "" : String.valueOf(o.crawlTimeoutSecs()));
        connectTimeout.setText("");
        requestTimeout.setText(o.auditTimeoutSecs() < 0 ? "" : String.valueOf(o.auditTimeoutSecs()));
        put(maxLocations, o.maxLocations(), true);
        put(maxRequests, o.maxRequests(), true);
        apiGraphqlCommon.setSelected(o.graphqlCommon());
        put(sitemapItems, o.sitemapMax(), true);
        if (o.skips() != null) {
            List<SkipRule> some = new ArrayList<>(), all = new ArrayList<>();
            for (ScanConfig.Skip s : o.skips())
                (s.allTests() ? all : some).add(new SkipRule(true, s.parameter(), "Name", s.matchType(), s.expression()));
            skipInjection.setRules(some);
            skipAll.setRules(all);
        }
    }

    /** One timeout from two boxes: the longer of what is filled in, or -1 when both are empty. */
    static int timeoutOf(JTextField connect, JTextField request) {
        return Math.max(intOf(connect, -1), intOf(request, -1));
    }

    private ScanConfig.Options options() {
        List<ScanConfig.Skip> skips = new ArrayList<>();
        for (SkipRule r : skipInjection.rules()) if (r.enabled()) skips.add(new ScanConfig.Skip(r.parameter(), r.matchType(), r.expression(), false));
        for (SkipRule r : skipAll.rules()) if (r.enabled()) skips.add(new ScanConfig.Skip(r.parameter(), r.matchType(), r.expression(), true));
        return new ScanConfig.Options(
                requestRobots.isSelected(), requestSitemap.isSelected(), hiddenLinks.isSelected(), clickAll.isSelected(),
                customAgent.isSelected() ? userAgent.getText().strip() : "",
                timeoutOf(crawlConnectSecs, crawlRequestSecs), timeoutOf(connectTimeout, requestTimeout),
                intOf(maxLocations, 0), intOf(maxRequests, 0), skips,
                apiGraphqlCommon.isSelected(), intOf(sitemapItems, 0));
    }

    /** The engine configuration the controls describe. */
    public ScanConfig config() {
        String name = presetName();
        int inj = 0;
        if (ipQuery.isSelected()) inj |= ScanConfig.INJECT_QUERY;
        if (ipBody.isSelected()) inj |= ScanConfig.INJECT_BODY;
        if (ipFilename.isSelected() || ipFolders.isSelected()) inj |= ScanConfig.INJECT_PATH;
        if (ipHeaders.isSelected()) inj |= ScanConfig.INJECT_HEADERS;
        if (ipCookie.isSelected()) inj |= ScanConfig.INJECT_COOKIE;
        int all = ScanConfig.RPC_MULTIPART | ScanConfig.RPC_XML | ScanConfig.RPC_JSON | ScanConfig.RPC_GWT | ScanConfig.RPC_ODATA;
        int rpc = !ipEntireBody.isSelected() ? 0 : rpcFormats != 0 ? rpcFormats : all;
        String strength = switch (String.valueOf(auditSpeed.getSelectedItem())) { case "Fast" -> "LOW"; case "Thorough" -> "HIGH"; default -> "MEDIUM"; };
        String threshold = switch (String.valueOf(auditAccuracy.getSelectedItem())) { case "Minimize false negatives" -> "LOW"; case "Minimize false positives" -> "HIGH"; default -> "MEDIUM"; };
        boolean dyn = !"Never".equals(browserUse.getSelectedItem()) && jsDynamic.isSelected();
        return new ScanConfig(name,
                intOf(maxDepth, 0), intOf(maxCrawlMin, 0), submitForms.isSelected(),
                dyn, intOf(jsDynamicSecs, 30) / 60, (Integer) ajaxDepth.getValue(), (Integer) ajaxStates.getValue(),
                strength, threshold, inj, rpc, 0, intOf(maxScanMin, 0), options());
    }

    /** Live passive crawl choices, for the task description. */
    public String passiveCrawlSummary() {
        List<String> add = new ArrayList<>();
        if (pcLinks.isSelected()) add.add("links");
        if (pcForms.isSelected()) add.add("form submissions");
        List<String> urls = new ArrayList<>();
        if (pcEverything.isSelected()) urls.add("everything");
        if (pcItself.isSelected()) urls.add("the item itself");
        if (pcSameDomain.isSelected()) urls.add("same domain");
        if (pcInScope.isSelected()) urls.add(pcSuiteScope.isSelected() ? "URLs in suite scope" : "URLs in custom scope");
        return "Add " + String.join(", ", add) + ". " + String.join(", ", urls) + ".";
    }

    private void save() {
        String suggested = "Custom".equals(presetName()) ? "" : presetName() + " (copy)";
        String name = JOptionPane.showInputDialog(this, "Name for this configuration:", suggested);
        if (name == null || name.isBlank()) return;
        name = name.strip();
        if (ScanConfigStore.exists(name) && JOptionPane.showConfirmDialog(this, "\"" + name + "\" already exists. Replace it?",
                "Save configuration", JOptionPane.YES_NO_OPTION) != JOptionPane.YES_OPTION) return;
        try { ScanConfigStore.save(name, config()); }
        catch (java.io.IOException e) { JOptionPane.showMessageDialog(this, "Could not save the configuration: " + e.getMessage(), "Save configuration", JOptionPane.ERROR_MESSAGE); }
    }

    private void load() {
        List<String> names = ScanConfigStore.names();
        if (names.isEmpty()) {
            JOptionPane.showMessageDialog(this, "No saved configurations. Configure a scan and click Save to add it to the library.",
                    "Load configuration", JOptionPane.INFORMATION_MESSAGE);
            return;
        }
        Object pick = JOptionPane.showInputDialog(this, "Saved configuration:", "Load configuration",
                JOptionPane.PLAIN_MESSAGE, null, names.toArray(), names.get(0));
        if (pick == null) return;
        try {
            preset.setSelectedIndex(4);
            apply(ScanConfigStore.load(pick.toString()));
        } catch (java.io.IOException e) {
            JOptionPane.showMessageDialog(this, "Could not load the configuration: " + e.getMessage(), "Load configuration", JOptionPane.ERROR_MESSAGE);
        }
    }

    /**
     * A configuration to choose. In the open list each is its own icon, its
     * name in bold and a line saying what it is for, with a rule under it;
     * the closed box shows the name alone on one line.
     */
    private static final class PresetRenderer extends JPanel implements ListCellRenderer<Preset> {
        private final JLabel title = Ui.bold("");
        private final JLabel desc = Ui.label("");
        private final JLabel icon = new JLabel();
        private final JLabel closed = Ui.label("");
        private final JPanel open = new JPanel(new BorderLayout(12, 0));
        PresetRenderer() {
            super(new BorderLayout());
            JPanel text = new JPanel(new GridLayout(2, 1, 0, 6));
            text.setOpaque(false);
            text.add(title); text.add(desc);
            icon.setVerticalAlignment(SwingConstants.TOP);
            icon.setBorder(Ui.pad(1, 0, 0, 0));
            open.setOpaque(false);
            open.add(icon, BorderLayout.WEST);
            open.add(text, BorderLayout.CENTER);
            setOpaque(true);
        }
        private static Icon iconOf(String name, int size) {
            return switch (name) {
                case "Lightweight" -> Glyphs.lightweight(size, Theme.TEXT);
                case "Fast" -> Glyphs.fast(size, Theme.TEXT);
                case "Balanced" -> Glyphs.balanced(size, Theme.TEXT);
                case "Deep" -> Glyphs.deep(size, Theme.TEXT);
                default -> Glyphs.sliders(size, Theme.TEXT);
            };
        }
        @Override public Component getListCellRendererComponent(JList<? extends Preset> list, Preset v, int i, boolean sel, boolean focus) {
            removeAll();
            if (i < 0) {
                // The closed box.
                closed.setText(v == null ? "Select a scan configuration" : v.name());
                closed.setIcon(v == null ? null : iconOf(v.name(), 15));
                closed.setIconTextGap(8);
                closed.setForeground(Theme.TEXT);
                setBorder(Ui.pad(0, 2, 0, 2));
                setBackground(Theme.CARD);
                add(closed, BorderLayout.CENTER);
                return this;
            }
            title.setText(v.name());
            desc.setText(v.description());
            title.setForeground(Theme.TEXT);
            desc.setForeground(Theme.TEXT);
            icon.setIcon(iconOf(v.name(), 18));
            boolean last = i == list.getModel().getSize() - 1;
            setBorder(BorderFactory.createCompoundBorder(
                    BorderFactory.createMatteBorder(0, 0, last ? 0 : 1, 0, Ui.GRID), Ui.pad(16, 14, 16, 14)));
            setBackground(sel ? Theme.CONTROL_TINT : Theme.CARD);
            add(open, BorderLayout.CENTER);
            return this;
        }
    }

    // ---- the "skip these parameters" tables ----

    record SkipRule(boolean enabled, String parameter, String item, String matchType, String expression) {}

    private static List<SkipRule> defaultSkipInjection() {
        List<SkipRule> l = new ArrayList<>();
        l.add(new SkipRule(true, "Cookie", "Name", "Matches regex", "aspsessionid.*"));
        l.add(new SkipRule(true, "Cookie", "Name", "Is", "asp.net_sessionid"));
        for (String n : new String[]{"__eventtarget", "__eventargument", "__viewstate", "__eventvalidation"})
            l.add(new SkipRule(true, "Body parameter", "Name", "Is", n));
        for (String n : new String[]{"jsessionid", "cfid", "cftoken", "phpsessid", "sessionid"})
            l.add(new SkipRule(true, "Any parameter", "Name", "Is", n));
        return l;
    }

    private static List<SkipRule> defaultSkipAll() {
        List<SkipRule> l = new ArrayList<>();
        for (String n : new String[]{"version", "encoding", "standalone", "xmlns.*", "xml:lang", "lang"})
            l.add(new SkipRule(true, "XML attribute", "Name", n.endsWith("*") ? "Matches regex" : "Is", n));
        for (String n : new String[]{"_ga", "_gid", "_gat", "_ga_.*", "_gac_.*", "aws.*"})
            l.add(new SkipRule(true, "Cookie", "Name", n.endsWith("*") ? "Matches regex" : "Is", n));
        return l;
    }

    private static final class SkipTable extends JPanel {
        final List<SkipRule> rules;
        private final AbstractTableModel model = new AbstractTableModel() {
            private final String[] cols = {"Enabled", "Parameter", "Item", "Match type", "Expression"};
            @Override public int getRowCount() { return rules.size(); }
            @Override public int getColumnCount() { return cols.length; }
            @Override public String getColumnName(int c) { return cols[c]; }
            @Override public Class<?> getColumnClass(int c) { return c == 0 ? Boolean.class : String.class; }
            @Override public boolean isCellEditable(int r, int c) { return c == 0; }
            @Override public Object getValueAt(int r, int c) {
                SkipRule x = rules.get(r);
                return switch (c) { case 0 -> x.enabled(); case 1 -> x.parameter(); case 2 -> x.item(); case 3 -> x.matchType(); default -> x.expression(); };
            }
            @Override public void setValueAt(Object v, int r, int c) {
                if (c == 0) { SkipRule x = rules.get(r); rules.set(r, new SkipRule(Boolean.TRUE.equals(v), x.parameter(), x.item(), x.matchType(), x.expression())); }
            }
        };
        List<SkipRule> rules() { return List.copyOf(rules); }
        void setRules(List<SkipRule> to) { rules.clear(); rules.addAll(to); model.fireTableDataChanged(); }
        SkipTable(List<SkipRule> initial) {
            super(new BorderLayout(8, 0));
            setOpaque(false);
            rules = new ArrayList<>(initial);
            JTable t = new JTable(model);
            Ui.styleTable(t);
            Ui.distributeWidths(t, 110, 130, 110, 140, 240);
            JButton add = Ui.button("Add"), edit = Ui.button("Edit"), remove = Ui.button("Remove");
            add.addActionListener(e -> { SkipRule r = dialog(null); if (r != null) { rules.add(r); model.fireTableDataChanged(); } });
            edit.addActionListener(e -> { int i = t.getSelectedRow(); if (i >= 0) { SkipRule r = dialog(rules.get(i)); if (r != null) { rules.set(i, r); model.fireTableDataChanged(); } } });
            remove.addActionListener(e -> { int i = t.getSelectedRow(); if (i >= 0) { rules.remove(i); model.fireTableDataChanged(); } });
            add(Ui.buttonColumn(add, edit, remove), BorderLayout.WEST);
            JScrollPane sp = Ui.scroll(t);
            sp.setPreferredSize(new Dimension(560, 26 + 6 * t.getRowHeight()));   // the heading and six rows, as the reference shows
            add(sp, BorderLayout.CENTER);
        }
        private SkipRule dialog(SkipRule editing) {
            JComboBox<String> param = Ui.combo(new String[]{"Any parameter", "URL parameter", "Body parameter", "Cookie", "HTTP header", "XML attribute", "JSON parameter"});
            JComboBox<String> item = Ui.combo(new String[]{"Name"});
            JComboBox<String> match = Ui.combo(new String[]{"Is", "Matches regex"});
            JTextField expr = Ui.field(editing == null ? "" : editing.expression());
            if (editing != null) { param.setSelectedItem(editing.parameter()); item.setSelectedItem(editing.item()); match.setSelectedItem(editing.matchType()); }
            JPanel form = Ui.form("Parameter:", param, "Item:", item, "Match type:", match, "Expression:", expr);
            form.setBorder(Ui.pad(10, 10, 10, 10));
            int ok = JOptionPane.showConfirmDialog(this, form, (editing == null ? "Add" : "Edit") + " parameter rule", JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE);
            if (ok != JOptionPane.OK_OPTION || expr.getText().isBlank()) return null;
            return new SkipRule(editing == null || editing.enabled(), String.valueOf(param.getSelectedItem()), String.valueOf(item.getSelectedItem()),
                    String.valueOf(match.getSelectedItem()), expr.getText().strip());
        }
    }

    // ---- Scan checks: Built-in / Custom / Extension ----

    record Check(String id, String name, String type, boolean javascript, String severity, String methods, boolean enabled) {}

    private static final class ChecksTable extends JPanel {
        private final List<Check> all = new ArrayList<>();
        private final List<Check> shown = new ArrayList<>();
        private final java.util.Set<String> typeFilter = new java.util.HashSet<>(List.of("Passive", "Light", "Medium", "Intrusive", "JavaScript"));
        private String query = "";
        private boolean loaded;
        private final JLabel status = Ui.label("");
        private final AbstractTableModel model = new AbstractTableModel() {
            private final String[] cols = {"", "Name", "Type", "JavaScript", "Typical severity", "Type index", "Detection methods"};
            @Override public int getRowCount() { return shown.size(); }
            @Override public int getColumnCount() { return cols.length; }
            @Override public String getColumnName(int c) { return cols[c]; }
            @Override public Class<?> getColumnClass(int c) { return c == 0 ? Boolean.class : String.class; }
            @Override public boolean isCellEditable(int r, int c) { return c == 0; }
            @Override public Object getValueAt(int r, int c) {
                Check x = shown.get(r);
                return switch (c) { case 0 -> x.enabled(); case 1 -> x.name(); case 2 -> x.type(); case 3 -> x.javascript();
                    case 4 -> x.severity(); case 5 -> x.id(); default -> x.methods(); };
            }
            @Override public void setValueAt(Object v, int r, int c) {
                if (c != 0) return;
                Check x = shown.get(r);
                Check y = new Check(x.id(), x.name(), x.type(), x.javascript(), x.severity(), x.methods(), Boolean.TRUE.equals(v));
                shown.set(r, y);
                int i = all.indexOf(x); if (i >= 0) all.set(i, y);
            }
        };
        private final JTable table = new JTable(model);

        ChecksTable() {
            super(new BorderLayout());
            setOpaque(false);
            JTabbedPane tabs = new JTabbedPane();
            tabs.setFont(Ui.PLAIN);
            tabs.addTab("Built-in", builtIn());
            tabs.addTab("Custom", customTab());
            tabs.addTab("Extension", extensionTab());
            add(tabs, BorderLayout.CENTER);
            // The help mark stands in the gutter beside the tabs, as it does beside a section's title.
            JLabel help = new JLabel(Glyphs.help());
            help.setVerticalAlignment(SwingConstants.TOP);
            help.setBorder(Ui.pad(10, 10, 0, 6));
            add(help, BorderLayout.WEST);
            setBorder(Ui.pad(2, 0, 6, 8));
            addHierarchyListener(e -> { if (isShowing() && !loaded) { loaded = true; load(); } });
        }

        private JComponent builtIn() {
            JPanel p = new JPanel(new BorderLayout(0, 6));
            p.setOpaque(false);
            p.setBorder(Ui.pad(8, 4, 4, 4));
            JPanel chips = new JPanel(new FlowLayout(FlowLayout.LEFT, 4, 0));
            chips.setOpaque(false);
            chips.add(new JLabel(Glyphs.funnel(14, Theme.MUTED)));
            chips.add(Ui.label("Filter"));
            for (String t : new String[]{"Passive", "Light", "Medium", "Intrusive", "JavaScript"}) {
                JToggleButton b = new JToggleButton(t, true) {
                    // A grey pill when its type is shown, an outline when it is filtered out.
                    @Override protected void paintComponent(Graphics g) {
                        Graphics2D g2 = (Graphics2D) g.create();
                        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
                        g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
                        int h = getHeight(), w = getWidth();
                        if (isSelected()) { g2.setColor(Theme.SURFACE); g2.fillRoundRect(0, 0, w, h, h, h); }
                        else { g2.setColor(Theme.BORDER); g2.drawRoundRect(0, 0, w - 1, h - 1, h, h); }
                        g2.setFont(getFont());
                        g2.setColor(isSelected() ? Theme.TEXT : Theme.MUTED);
                        FontMetrics fm = g2.getFontMetrics();
                        g2.drawString(getText(), (w - fm.stringWidth(getText())) / 2, (h - fm.getHeight()) / 2 + fm.getAscent());
                        g2.dispose();
                    }
                };
                b.setFont(Ui.BOLD); b.setFocusable(false);
                b.setContentAreaFilled(false); b.setBorderPainted(false); b.setOpaque(false);
                b.setPreferredSize(new Dimension(b.getFontMetrics(Ui.BOLD).stringWidth(t) + 18, Ui.tall(22)));
                b.addActionListener(e -> { if (b.isSelected()) typeFilter.add(t); else typeFilter.remove(t); refilter(); });
                chips.add(b);
            }
            JTextField search = Ui.field("");
            search.putClientProperty("JTextField.placeholderText", "Search");
            search.getDocument().addDocumentListener(new javax.swing.event.DocumentListener() {
                public void insertUpdate(javax.swing.event.DocumentEvent e) { query = search.getText(); refilter(); }
                public void removeUpdate(javax.swing.event.DocumentEvent e) { query = search.getText(); refilter(); }
                public void changedUpdate(javax.swing.event.DocumentEvent e) { query = search.getText(); refilter(); }
            });
            JPanel right = new JPanel(new FlowLayout(FlowLayout.RIGHT, 4, 0));
            right.setOpaque(false);
            right.add(search);
            right.add(Glyphs.button(Glyphs.help(), "The scanner's built-in checks, from the engine's policy", null));
            right.add(Glyphs.menuButton("More", () -> {
                JPopupMenu m = new JPopupMenu();
                JMenuItem on = new JMenuItem("Enable all shown"), off = new JMenuItem("Disable all shown");
                on.setFont(Ui.PLAIN); off.setFont(Ui.PLAIN);
                on.addActionListener(e -> setAll(true)); off.addActionListener(e -> setAll(false));
                m.add(on); m.add(off);
                return m;
            }));
            JPanel bar = new JPanel(new BorderLayout());
            bar.setOpaque(false);
            bar.add(chips, BorderLayout.WEST);
            bar.add(right, BorderLayout.EAST);
            JPanel north = new JPanel(new BorderLayout(0, 8));
            north.setOpaque(false);
            north.add(Ui.label("These are scan checks that are included with the scanner."), BorderLayout.NORTH);
            north.add(bar, BorderLayout.CENTER);
            p.add(north, BorderLayout.NORTH);
            Ui.styleTable(table);
            table.getColumnModel().getColumn(3).setCellRenderer(new Ui.TickRenderer());
            table.getColumnModel().getColumn(0).setMaxWidth(32);
            Ui.distributeWidths(table, 32, 260, 80, 80, 110, 80, 160);
            p.add(Ui.scroll(table), BorderLayout.CENTER);
            status.setForeground(Theme.MUTED);
            p.add(status, BorderLayout.SOUTH);
            return p;
        }

        private void setAll(boolean on) {
            for (int i = 0; i < shown.size(); i++) model.setValueAt(on, i, 0);
            model.fireTableDataChanged();
        }

        private JComponent customTab() {
            JPanel col = new JPanel();
            col.setLayout(new BoxLayout(col, BoxLayout.Y_AXIS));
            col.setOpaque(false);
            JLabel icon = new JLabel(Glyphs.bolt(48, Ui.ACCENT));
            JLabel h = Ui.heading("Extend the scanner with custom scan checks");
            JTextArea t = Ui.note("A custom check runs against every audit item. Custom checks are stored in the Script library under Extensions.");
            Ui.sizeNote(t, 420);
            JButton learn = Ui.button("Learn more");
            learn.addActionListener(e -> opensuite.ui.Unbuilt.openProject(this));
            JButton go = Ui.primaryButton("Go to custom scan checks", "Open Extensions > Custom scan checks");
            go.addActionListener(e -> {
                java.awt.Window w = SwingUtilities.getWindowAncestor(this);
                for (java.awt.Frame f : java.awt.Frame.getFrames()) if (f instanceof opensuite.ui.SuiteFrame sf) { sf.selectTool("extensions"); break; }
                if (w instanceof JDialog d) d.toBack();
            });
            for (JComponent c : new JComponent[]{icon, h, t, Ui.row(learn, go)}) { c.setAlignmentX(Component.CENTER_ALIGNMENT); col.add(c); col.add(Box.createVerticalStrut(10)); }
            JPanel wrap = new JPanel(new GridBagLayout());
            wrap.setOpaque(false);
            wrap.add(col, new GridBagConstraints());
            return wrap;
        }

        private JComponent extensionTab() {
            JPanel p = new JPanel(new BorderLayout(0, 6));
            p.setOpaque(false);
            p.setBorder(Ui.pad(8, 4, 4, 4));
            JCheckBox enabled = Ui.check("Enabled", true);
            p.add(Ui.row(enabled, Ui.note("Run checks provided by loaded extensions.")), BorderLayout.NORTH);
            javax.swing.table.DefaultTableModel m = new javax.swing.table.DefaultTableModel(new Object[]{"Check", "Extension", "Type", "Check runs"}, 0) {
                @Override public boolean isCellEditable(int r, int c) { return false; }
            };
            JTable t = new JTable(m);
            Ui.styleTable(t);
            p.add(Ui.scroll(t), BorderLayout.CENTER);
            return p;
        }

        private void refilter() {
            shown.clear();
            String q = query.strip().toLowerCase();
            for (Check c : all) {
                if (!typeFilter.contains(c.type()) && !(c.javascript() && typeFilter.contains("JavaScript"))) continue;
                if (!q.isEmpty() && !c.name().toLowerCase().contains(q)) continue;
                shown.add(c);
            }
            model.fireTableDataChanged();
        }

        /** Read the engine's policy off the EDT; the engine starts on first use. */
        private void load() {
            status.setText("Loading the scanner's checks from the engine...");
            new Thread(() -> {
                List<Check> out = new ArrayList<>();
                String note;
                try {
                    opensuite.engine.ZapEngine ze = opensuite.engine.ZapEngine.shared();
                    if (ze == null || !ze.available()) {
                        note = "Scan engine not installed: run ./fetch-zap.sh to list its checks.";
                    } else {
                        ze.start();
                        for (var s : ze.api().passiveScanners())
                            out.add(new Check(opensuite.engine.ZapApi.str(s, "id"), opensuite.engine.ZapApi.str(s, "name"), "Passive", false,
                                    "", "Passive", "true".equalsIgnoreCase(opensuite.engine.ZapApi.str(s, "enabled"))));
                        for (var s : ze.api().activeScanners()) {
                            String strength = opensuite.engine.ZapApi.str(s, "attackStrength");
                            String type = switch (strength == null ? "" : strength.toUpperCase()) { case "LOW" -> "Light"; case "HIGH", "INSANE" -> "Intrusive"; default -> "Medium"; };
                            out.add(new Check(opensuite.engine.ZapApi.str(s, "id"), opensuite.engine.ZapApi.str(s, "name"), type, false,
                                    "", "Active", "true".equalsIgnoreCase(opensuite.engine.ZapApi.str(s, "enabled"))));
                        }
                        note = out.size() + " checks from the engine's policy. Enable or disable them under Scanner.";
                    }
                } catch (Exception e) {
                    note = "Could not read the engine's checks: " + e.getMessage();
                }
                final String fnote = note;
                SwingUtilities.invokeLater(() -> { all.clear(); all.addAll(out); refilter(); status.setText(fnote); });
            }, "scan-checks-load").start();
        }
    }
}