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.1 KB
Raw Blame
package opensuite.target;

import opensuite.core.*;
import opensuite.ui.*;

import javax.swing.*;
import javax.swing.table.AbstractTableModel;
import javax.swing.tree.*;
import java.awt.*;
import java.util.ArrayList;
import java.util.List;

/** The target tool: a site map tree and the suite-wide scope editor. */
public class TargetTool implements ToolModule {

    private SuiteContext ctx;
    private SiteMap siteMap = new SiteMap();
    private JTree tree;
    private DefaultTreeModel treeModel;
    private final java.util.Map<SiteMap.Node, DefaultMutableTreeNode> treeNodes = new java.util.IdentityHashMap<>();
    private ItemsModel itemsModel;
    private JTable itemsTable;
    // One filter for the tree and the contents table, as the reference has it.
    private final opensuite.proxy.HistoryFilter itemsFilter = opensuite.proxy.HistoryFilter.siteMapDefaults();
    private JButton itemsFilterButton;
    private boolean crawlPathsView;
    private MessageEditor reqView, respView;
    private opensuite.ui.MessagePair pair;
    private JTree issuesTree;
    private DefaultTreeModel issuesTreeModel;
    private javax.swing.JEditorPane issueAdvisory;
    private JTextArea pathToIssue;
    private IssueLogModel issueLogModel;
    private MessageEditor issueReq, issueResp;
    private final opensuite.ui.Coalescer issuesRefresh =
            new opensuite.ui.Coalescer(250, this::refreshIssues);
    private SiteMap.Node selectedNode;
    private java.util.List<SiteMap.Node> selectedNodes = new java.util.ArrayList<>();

    public TargetTool() {}

    @Override public String name() { return "target"; }
    @Override public boolean alwaysTabbed() { return true; }

    @Override public void init(SuiteContext ctx) {
        this.ctx = ctx;
        ctx.addSiteMapListener(new SuiteContext.SiteMapListener() {
            @Override public void siteMapChanged(LogEntry e) {
                // Coalesce: queue the entry and sync the tree once per tick, so a
                // burst of traffic (or a crawl) costs one tree sync, not one each.
                pendingEntries.add(e);
                SwingUtilities.invokeLater(() -> { if (!syncTimer.isRunning()) syncTimer.start(); });
            }
            @Override public void siteMapSeen(LogEntry e) {
                SwingUtilities.invokeLater(() -> { if (siteMap.addLinked(e)) syncTree(); });
            }
            @Override public void siteMapReloaded(List<LogEntry> all) {
                pendingEntries.clear();
                SwingUtilities.invokeLater(() -> reloadSiteMap(all));
            }
        });
        // refreshIssues walks every issue, sorts them and rebuilds the tree.
        // Doing that once per finding is what made a scan with a thousand
        // findings stop the window answering; a coalescer makes a burst cost
        // one rebuild.
        ctx.addIssueListener(new SuiteContext.IssueListener() {
            @Override public void issueAdded(Issue i) { issuesRefresh.request(); }
            @Override public void issuesReloaded()    { issuesRefresh.request(); }
        });
        // "Show only in-scope items" depends on the scope, so a scope edit
        // re-filters the tree and the table.
        ctx.addScopeListener(() -> SwingUtilities.invokeLater(() -> {
            if (itemsFilter.inScopeOnly) applyItemsFilter();
            else if (tree != null) tree.repaint();   // in-scope and muted icons
        }));
    }

    // ---- tree filtering -----------------------------------------------------

    /**
     * Whether a site map node is shown under the current filter. A leaf shows
     * when its own exchange passes; a folder shows when anything beneath it
     * passes, or, with "hide empty folders" off, when its own URL is not
     * filtered out by scope.
     */
    private boolean nodeVisible(SiteMap.Node n) {
        if (itemsFilter.isEverything() && !itemsFilter.hideEmptyFolders) return true;
        if (n.entry != null && itemsFilter.test(n.entry)) return true;
        for (LogEntry e : n.entries()) if (itemsFilter.test(e)) return true;
        if (n.entry != null) return false;   // a requested item that is filtered out
        if (itemsFilter.hideEmptyFolders) return false;
        return !itemsFilter.inScopeOnly || n.service == null
                || ctx.scope().isInScope(n.service, n.isHost ? "/" : n.path);
    }

    /** Rebuild the whole tree under the current filter, keeping what was expanded and selected. */
    private void rebuildTree() {
        if (treeModel == null || tree == null) return;
        java.util.Set<SiteMap.Node> expanded = new java.util.HashSet<>();
        for (int i = 0; i < tree.getRowCount(); i++) {
            TreePath p = tree.getPathForRow(i);
            if (tree.isExpanded(p) && ((DefaultMutableTreeNode) p.getLastPathComponent()).getUserObject() instanceof SiteMap.Node n)
                expanded.add(n);
        }
        java.util.List<SiteMap.Node> wasSelected = new ArrayList<>(selectedNodes == null ? List.of() : selectedNodes);
        DefaultMutableTreeNode rootTn = (DefaultMutableTreeNode) treeModel.getRoot();
        rootTn.removeAllChildren();
        treeNodes.clear();
        treeNodes.put(siteMap.root(), rootTn);
        buildTree(siteMap.root(), rootTn);
        treeModel.reload();
        tree.expandPath(new TreePath(rootTn));
        for (SiteMap.Node n : expanded) {
            DefaultMutableTreeNode tn = treeNodes.get(n);
            if (tn != null) tree.expandPath(new TreePath(tn.getPath()));
        }
        java.util.List<TreePath> reselect = new ArrayList<>();
        for (SiteMap.Node n : wasSelected) {
            DefaultMutableTreeNode tn = treeNodes.get(n);
            if (tn != null) reselect.add(new TreePath(tn.getPath()));
        }
        if (!reselect.isEmpty()) tree.setSelectionPaths(reselect.toArray(new TreePath[0]));
        else if (tree.getRowCount() > 0) tree.setSelectionRow(0);
        else { selectedNodes = new ArrayList<>(); selectedNode = null; itemsModel.setEntries(List.of()); refreshIssues(); }
    }

    /** Entries recorded since the last tree sync, drained by {@link #syncTimer}. */
    private final java.util.concurrent.ConcurrentLinkedQueue<LogEntry> pendingEntries =
            new java.util.concurrent.ConcurrentLinkedQueue<>();

    /** Fires once per burst of traffic: adds every queued entry, then syncs the tree once. */
    private final javax.swing.Timer syncTimer = new javax.swing.Timer(120, e -> {
        LogEntry le;
        boolean any = false;
        while ((le = pendingEntries.poll()) != null) { siteMap.add(le); passiveCrawl(le, true); any = true; }
        if (any) syncTree();
        if (pendingEntries.isEmpty()) ((javax.swing.Timer) e.getSource()).stop();
    });

    /**
     * Rebuild the site map and its tree from a restored history in one pass:
     * every node is created up front and the model is reloaded once, instead of
     * a tree sync per entry, which made opening a large project take minutes.
     */
    private void reloadSiteMap(List<LogEntry> all) {
        siteMap.clear();
        for (LogEntry e : all) siteMap.add(e);
        for (LogEntry e : all) passiveCrawl(e, false);
        if (treeModel == null || tree == null) return;
        DefaultMutableTreeNode rootTn = (DefaultMutableTreeNode) treeModel.getRoot();
        rootTn.removeAllChildren();
        treeNodes.clear();
        treeNodes.put(siteMap.root(), rootTn);
        buildTree(siteMap.root(), rootTn);
        selectedNodes = new ArrayList<>();
        selectedNode = null;
        treeModel.reload();
        tree.expandPath(new TreePath(rootTn));
        if (tree.getRowCount() > 0) tree.setSelectionRow(0);
        refreshIssues();
    }

    /**
     * The live passive crawl: add the same-site links in an HTML response to
     * the site map as items that have not been requested. Nothing is sent.
     * {@code report} is false when replaying a restored history, which should
     * rebuild the map without logging every link a second time.
     */
    /** True when everything at or under a node was seen and not requested. */
    private boolean onlySeen(SiteMap.Node n) {
        List<LogEntry> all = n.entries();
        if (all.isEmpty()) return false;
        for (LogEntry e : all) if (!siteMap.isLinked(e)) return false;
        return true;
    }

    /** List a link to another site in the map, under that site, as an item that was seen and never requested. */
    private void linkElsewhere(String link) {
        opensuite.core.HttpService other = opensuite.core.HttpService.parse(link);
        if (other == null) return;
        String path = LinkFinder.pathOn(other.url(), link);
        if (path == null) path = "/";
        int hash = path.indexOf('#');
        if (hash >= 0) path = path.substring(0, hash);
        if (path.isEmpty()) path = "/";
        String hostHeader = other.host() + (other.defaultPort() ? "" : ":" + other.port());
        siteMap.addLinked(new LogEntry("link", other, new opensuite.core.HttpMessage(
                ("GET " + path + " HTTP/1.1\r\nHost: " + hostHeader + "\r\n\r\n")
                        .getBytes(java.nio.charset.StandardCharsets.ISO_8859_1))));
    }

    private void passiveCrawl(LogEntry e, boolean report) {
        if (!PassiveCrawl.enabled() || e.service() == null) return;
        try {
            opensuite.core.HttpMessage resp = e.response();
            if (resp == null) return;
            report &= !secondary;
            if (report) PassiveCrawl.responseProcessed(e);
            String mime = e.mimeType();
            if (mime == null || !mime.toLowerCase(java.util.Locale.ROOT).contains("html")) return;
            byte[] body = resp.body();
            if (body == null || body.length == 0 || body.length > LinkFinder.MAX_CHARS) return;
            String html = new String(body, java.nio.charset.StandardCharsets.ISO_8859_1);
            String origin = e.service().url();
            String hostHeader = e.service().host() + (e.service().defaultPort() ? "" : ":" + e.service().port());
            for (String link : LinkFinder.links(e.url(), html)) {
                String path = LinkFinder.pathOn(origin, link);
                if (path == null) {
                    // A link to another site. It is not followed, but it is listed under its own host, as
                    // seen and not requested: what an application points at or depends on is part of the map.
                    linkElsewhere(link);
                    continue;
                }
                LogEntry item = new LogEntry("link", e.service(), new opensuite.core.HttpMessage(
                        ("GET " + path + " HTTP/1.1\r\nHost: " + hostHeader + "\r\n\r\n")
                                .getBytes(java.nio.charset.StandardCharsets.ISO_8859_1)));
                if (siteMap.addLinked(item) && report) PassiveCrawl.linkAdded(link, e.url(), e.service().host(), path);
            }
        } catch (RuntimeException ignored) {
            // A response that will not parse adds no links; the exchange itself is already in the map.
        }
    }

    private void buildTree(SiteMap.Node sm, DefaultMutableTreeNode tn) {
        // Crawl paths view drops the folder hierarchy: under each host every
        // requested item hangs directly off the host, labelled by its full
        // path, so the paths that were actually reached read as one list.
        if (crawlPathsView && sm.isHost) {
            java.util.List<SiteMap.Node> leaves = new ArrayList<>();
            collectRequested(sm, leaves);
            for (SiteMap.Node leaf : leaves) {
                if (!nodeVisible(leaf)) continue;
                DefaultMutableTreeNode c = new DefaultMutableTreeNode(leaf);
                treeNodes.put(leaf, c);
                tn.add(c);
            }
            return;
        }
        for (SiteMap.Node child : sm.children.values()) {
            if (!nodeVisible(child)) continue;
            DefaultMutableTreeNode c = new DefaultMutableTreeNode(child);
            treeNodes.put(child, c);
            tn.add(c);
            buildTree(child, c);
        }
    }

    /** Every node at or below {@code n} that stands for a request that was made. */
    private void collectRequested(SiteMap.Node n, java.util.List<SiteMap.Node> out) {
        for (SiteMap.Node c : n.children.values()) {
            if (c.entry != null && !siteMap.isLinked(c.entry)) out.add(c);
            collectRequested(c, out);
        }
    }

    /** The "URL view" / "Crawl paths view" switch above the filter bar. */
    private JComponent buildViewSwitch() {
        return Ui.segmented(i -> { crawlPathsView = i == 1; rebuildTree(); },
                "URL view", "Crawl paths view");
    }

    /**
     * The "Path to issue" tab: the chain of requests that led to the finding,
     * or a plain note for a passively detected one, which has no chain.
     */
    private JComponent buildPathToIssue() {
        pathToIssue = Ui.note("");
        pathToIssue.setBorder(Ui.pad(10, 12, 10, 12));
        return Ui.scroll(pathToIssue);
    }

    /** The "Log" tab: when the issue was recorded, by what, and against what path. */
    private JComponent buildIssueLog() {
        issueLogModel = new IssueLogModel();
        JTable t = new JTable(issueLogModel);
        Ui.styleTable(t);
        Ui.distributeWidths(t, 150, 90, 160, 300);
        return Ui.scroll(t);
    }

    /** One row per recorded step for the selected issue. */
    private static final class IssueLogModel extends AbstractTableModel {
        private final String[] cols = {"Time", "Source", "Action", "Path"};
        private final java.text.DateFormat fmt = new java.text.SimpleDateFormat("HH:mm:ss d MMM yyyy");
        private java.util.List<Object[]> rows = new ArrayList<>();

        void show(Issue i) {
            rows = new ArrayList<>();
            if (i != null) {
                rows.add(new Object[]{fmt.format(new java.util.Date(i.time())), i.source(), "Issue recorded", i.path()});
                if (i.request() != null) rows.add(new Object[]{fmt.format(new java.util.Date(i.time())), i.source(), "Request sent", i.request().startLine()});
            }
            fireTableDataChanged();
        }

        @Override public int getRowCount() { return rows.size(); }
        @Override public int getColumnCount() { return cols.length; }
        @Override public String getColumnName(int c) { return cols[c]; }
        @Override public Object getValueAt(int r, int c) { return rows.get(r)[c]; }
    }

    @Override public Tab[] tabs() {
        return new Tab[]{
                new Tab("Site map", buildSiteMap()),
                new Tab("Scope", buildScope()),
                new Tab("Issues", new IssueDefinitionsPanel(ctx::issues)),
        };
    }

    private JComponent buildSiteMap() {
        DefaultMutableTreeNode rootTn = new DefaultMutableTreeNode(siteMap.root());
        treeNodes.clear();
        treeNodes.put(siteMap.root(), rootTn);
        treeModel = new DefaultTreeModel(rootTn);
        tree = new opensuite.ui.RowTree(treeModel);
        tree.setRootVisible(false);
        tree.setShowsRootHandles(true);
        ((opensuite.ui.RowTree) tree).setConnectors(true);
        // Hosts carry a padlock (closed for https, open and red for http) and
        // are labelled by host and port, the scheme being what the padlock
        // says; folders and requests get flat icons. Out-of-scope nodes are
        // muted when a scope is set, so the target stands out.
        tree.setCellRenderer(new DefaultTreeCellRenderer() {
            @Override public Component getTreeCellRendererComponent(JTree t, Object value,
                    boolean sel, boolean exp, boolean leaf, int row, boolean focus) {
                super.getTreeCellRendererComponent(t, value, sel, exp, leaf, row, focus);
                if (value instanceof DefaultMutableTreeNode tn && tn.getUserObject() instanceof SiteMap.Node n) {
                    boolean muted = !ctx.scope().isEmpty() && n.service != null
                            && !ctx.scope().isInScope(n.service, n.isHost ? "/" : n.path);
                    if (n.isHost && n.service != null) {
                        setText(n.service.host() + (n.service.defaultPort() ? "" : ":" + n.service.port()));
                        setIcon(SiteIcons.host(n.service.secure(), muted));
                    } else {
                        if (crawlPathsView) setText(n.label.startsWith("?") ? n.path + n.label : n.path);
                        // A cog for a request that takes parameters, a folder for a path with pages under it.
                        boolean takes = false, under = false;
                        for (SiteMap.Node child : n.children.values()) { if (child.label.startsWith("?")) takes = true; else under = true; }
                        try { if (n.entry != null && n.entry.hasParameters()) takes = true; } catch (RuntimeException ignore) { }
                        setIcon(crawlPathsView ? SiteIcons.page(muted) : under ? SiteIcons.folder(muted)
                                : takes ? SiteIcons.parameters(muted) : SiteIcons.page(muted));
                    }
                    // An item that was only seen, or a host or folder with nothing under it that was requested.
                    boolean unrequested = n.entry != null ? siteMap.isLinked(n.entry) : onlySeen(n);
                    if (!sel) setForeground(muted || unrequested ? Theme.MUTED : Theme.TEXT);
                }
                return this;
            }
        });

        itemsModel = new ItemsModel();
        itemsTable = new JTable(itemsModel) {
            // An item known only from a link reads in grey until it is requested.
            @Override public Component prepareRenderer(javax.swing.table.TableCellRenderer r, int row, int col) {
                Component c = super.prepareRenderer(r, row, col);
                if (!isRowSelected(row)) {
                    LogEntry e = itemsModel.at(convertRowIndexToModel(row));
                    c.setForeground(siteMap.isLinked(e) ? Theme.MUTED : getForeground());
                }
                return c;
            }
        };
        Ui.styleTable(itemsTable);
        // host, method, URL, params, status code, length, MIME type, title, notes, time requested
        Ui.exactWidths(itemsTable, 186, 73, 186, 73, 121, 73, 111, 186, 186, 113);
        Ui.centerCells(itemsTable);
        itemsTable.getColumnModel().getColumn(3).setCellRenderer(new Ui.TickRenderer());

        reqView = new MessageEditor(ctx, MessageEditor.REQUEST, false);
        respView = new MessageEditor(ctx, MessageEditor.RESPONSE, false);

        tree.addTreeSelectionListener(e -> showTreeSelection());
        itemsTable.getSelectionModel().addListSelectionListener(e -> showItem());
        installTreeMenu();
        // The Contents table is a history table, so it carries the same right-click
        // menu (send to the tools, engagement tools, add to scope, copy URL, save).
        new opensuite.proxy.HistoryContextMenu(ctx, itemsTable, itemsModel::at, null).install();

        itemsFilter.scope = ctx.scope();
        JScrollPane contentsTable = Ui.scroll(itemsTable);
        contentsTable.setBorder(BorderFactory.createMatteBorder(1, 0, 0, 0, Theme.BORDER));
        // "Contents", with a search of the rows and the table's layout menu, as the reference heads the table.
        JTextField contentsSearch = Ui.searchField(22);
        contentsSearch.getDocument().addDocumentListener(new javax.swing.event.DocumentListener() {
            private void go() {
                String term = contentsSearch.getText().strip();
                javax.swing.table.TableRowSorter<javax.swing.table.TableModel> sorter;
                if (itemsTable.getRowSorter() instanceof javax.swing.table.TableRowSorter<?> have) {
                    @SuppressWarnings("unchecked") javax.swing.table.TableRowSorter<javax.swing.table.TableModel> s = (javax.swing.table.TableRowSorter<javax.swing.table.TableModel>) have;
                    sorter = s;
                } else {
                    sorter = new opensuite.ui.NumberSorter<>(itemsTable.getModel());
                    itemsTable.setRowSorter(sorter);
                }
                sorter.setRowFilter(term.isEmpty() ? null : RowFilter.regexFilter("(?i)" + java.util.regex.Pattern.quote(term)));
            }
            @Override public void insertUpdate(javax.swing.event.DocumentEvent e) { go(); }
            @Override public void removeUpdate(javax.swing.event.DocumentEvent e) { go(); }
            @Override public void changedUpdate(javax.swing.event.DocumentEvent e) { go(); }
        });
        JButton contentsMenu = opensuite.ui.Glyphs.menuButton("Table layout", () -> opensuite.ui.TableLayoutMenu.build(itemsTable));
        JPanel contentsTools = new JPanel(new FlowLayout(FlowLayout.RIGHT, 6, 0));
        contentsTools.setOpaque(false);
        contentsTools.add(contentsSearch); contentsTools.add(contentsMenu);
        JPanel contentsHead = new JPanel(new BorderLayout());
        contentsHead.setOpaque(false);
        contentsHead.setBorder(Ui.pad(5, 10, 5, 6));
        contentsHead.add(Ui.bold("Contents"), BorderLayout.WEST);
        contentsHead.add(contentsTools, BorderLayout.EAST);
        JPanel contents = new JPanel(new BorderLayout());
        contents.setOpaque(false);
        contents.add(contentsHead, BorderLayout.NORTH);
        contents.add(contentsTable, BorderLayout.CENTER);

        opensuite.ui.MessagePair detail = new opensuite.ui.MessagePair(reqView, respView);
        this.pair = detail;
        JSplitPane center = new JSplitPane(JSplitPane.VERTICAL_SPLIT, contents, detail);
        center.setDividerSize(1);
        Ui.balance(center, 0.273);

        JComponent issuesPanel = buildIssuesPanel();

        final JSplitPane rightmost = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, center, issuesPanel);
        rightmost.setDividerSize(1);
        Ui.balance(rightmost, 0.7);
        JScrollPane treeScroll = new JScrollPane(tree);
        treeScroll.setBorder(null);
        treeScroll.getViewport().setBackground(Theme.BG);
        treeScroll.getVerticalScrollBar().setUnitIncrement(16);
        JSplitPane split = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, treeScroll, rightmost);
        split.setDividerSize(1);
        split.setDividerLocation(291 + 23 * Ui.fontGrowth());   // 337 at 13px, as measured

        // A row of the contents table offers what its item offers in the tree.
        itemsTable.addMouseListener(new java.awt.event.MouseAdapter() {
            @Override public void mousePressed(java.awt.event.MouseEvent e) { pop(e); }
            @Override public void mouseReleased(java.awt.event.MouseEvent e) { pop(e); }
            private void pop(java.awt.event.MouseEvent e) {
                if (!e.isPopupTrigger()) return;
                int row = itemsTable.rowAtPoint(e.getPoint());
                if (row < 0) return;
                if (!itemsTable.isRowSelected(row)) itemsTable.setRowSelectionInterval(row, row);
                LogEntry le = itemsModel.at(itemsTable.convertRowIndexToModel(row));
                SiteMap.Node node = le == null ? null : nodeOf(siteMap.root(), le);
                if (node != null) buildNodeMenu(node).show(itemsTable, e.getX(), e.getY());
            }
        });

        // The contents table's heading carries its layout menu, and with it the
        // choice of showing the issues pane beside the contents or not.
        itemsTable.getTableHeader().addMouseListener(new java.awt.event.MouseAdapter() {
            @Override public void mousePressed(java.awt.event.MouseEvent e) { pop(e); }
            @Override public void mouseReleased(java.awt.event.MouseEvent e) { pop(e); }
            private void pop(java.awt.event.MouseEvent e) {
                if (!e.isPopupTrigger()) return;
                JPopupMenu m = opensuite.ui.TableLayoutMenu.build(itemsTable);
                JCheckBoxMenuItem show = new JCheckBoxMenuItem("Show issues pane", rightmost.getRightComponent() != null);
                show.setFont(Ui.PLAIN);
                show.addActionListener(a -> {
                    if (show.isSelected()) { rightmost.setRightComponent(issuesPanel); rightmost.setDividerSize(1); Ui.balance(rightmost, 0.7); }
                    else { rightmost.setRightComponent(null); rightmost.setDividerSize(0); }
                });
                m.addSeparator();
                m.add(show);
                m.show(e.getComponent(), e.getX(), e.getY());
            }
        });

        // The filter bar spans the tree and the contents, as in the reference,
        // because one filter drives both; above it the view switch, and above
        // that the out-of-scope logging notice when the proxy has stopped
        // recording other sites.
        JPanel top = new JPanel(new BorderLayout());
        top.add(new OutOfScopeBanner(ctx), BorderLayout.NORTH);
        JPanel viewRow = new JPanel(new BorderLayout());
        viewRow.setBorder(Ui.pad(4, 4, 0, 4));
        viewRow.add(buildViewSwitch(), BorderLayout.WEST);
        JPanel stacked = new JPanel(new BorderLayout());
        stacked.add(viewRow, BorderLayout.NORTH);
        stacked.add(buildItemsFilterBar(), BorderLayout.CENTER);
        top.add(stacked, BorderLayout.CENTER);
        JPanel page = new JPanel(new BorderLayout());
        page.add(top, BorderLayout.NORTH);
        page.add(split, BorderLayout.CENTER);
        applyItemsFilter();
        return page;
    }

    private JComponent buildIssuesPanel() {
        DefaultMutableTreeNode iroot = new DefaultMutableTreeNode("Issues");
        issuesTreeModel = new DefaultTreeModel(iroot);
        issuesTree = new JTree(issuesTreeModel);
        issuesTree.setRootVisible(false);
        issuesTree.setShowsRootHandles(true);
        issuesTree.setFont(Ui.PLAIN);
        issuesTree.setRowHeight(18);
        // The same issue badge the lists use, so one finding looks the same
        // whether it is read from the tree or from a table.
        issuesTree.setCellRenderer(new DefaultTreeCellRenderer() {
            @Override public Component getTreeCellRendererComponent(JTree t, Object value,
                    boolean sel, boolean exp, boolean leaf, int row, boolean focus) {
                super.getTreeCellRendererComponent(t, value, sel, exp, leaf, row, focus);
                Issue.Severity sev = null;
                Issue.Confidence conf = Issue.Confidence.CERTAIN;
                if (value instanceof DefaultMutableTreeNode n) {
                    Object o = n.getUserObject();
                    if (o instanceof IssueType it) sev = it.severity();
                    else if (o instanceof Issue i) { sev = i.falsePositive() ? Issue.Severity.INFORMATION : i.severity(); conf = i.confidence(); }
                }
                setIcon(sev == null ? null : Ui.issueBadge(sev, conf));
                return this;
            }
        });

        issueAdvisory = new javax.swing.JEditorPane();
        issueAdvisory.setEditable(false);
        issueAdvisory.setEditorKit(Theme.htmlKit());
        issueReq = new MessageEditor(ctx, MessageEditor.REQUEST, false);
        issueResp = new MessageEditor(ctx, MessageEditor.RESPONSE, false);

        issuesTree.addTreeSelectionListener(e -> showIssue());
        opensuite.ui.Advisory.clickable(issueAdvisory);
        issuesTree.addMouseListener(new java.awt.event.MouseAdapter() {
            @Override public void mousePressed(java.awt.event.MouseEvent e) { pop(e); }
            @Override public void mouseReleased(java.awt.event.MouseEvent e) { pop(e); }
            private void pop(java.awt.event.MouseEvent e) {
                if (!e.isPopupTrigger()) return;
                TreePath at = issuesTree.getPathForLocation(e.getX(), e.getY());
                if (at == null) return;
                if (!issuesTree.isPathSelected(at)) issuesTree.setSelectionPath(at);
                java.util.List<Issue> chosen = new ArrayList<>();
                TreePath[] sel = issuesTree.getSelectionPaths();
                if (sel != null) for (TreePath p : sel) collectIssues((DefaultMutableTreeNode) p.getLastPathComponent(), chosen);
                opensuite.ui.IssueMenu.show(issuesTree, e.getX(), e.getY(), ctx, chosen);
            }
        });

        JLabel header = Ui.bold(" Issues");
        header.setBorder(Ui.pad(3, 2, 3, 2));
        JPanel top = new JPanel(new BorderLayout());
        top.add(header, BorderLayout.NORTH);
        top.add(Ui.scroll(issuesTree), BorderLayout.CENTER);

        // One tabbed detail pane: Advisory, Request, Response, Path to issue, Log.
        JTabbedPane detailTabs = new JTabbedPane();
        detailTabs.setFont(Ui.PLAIN);
        detailTabs.addTab("Advisory", Ui.scroll(issueAdvisory));
        detailTabs.addTab("Request", issueReq);
        detailTabs.addTab("Response", issueResp);
        detailTabs.addTab("Path to issue", buildPathToIssue());
        detailTabs.addTab("Log", buildIssueLog());

        JSplitPane panel = new JSplitPane(JSplitPane.VERTICAL_SPLIT, top, detailTabs);
        panel.setDividerSize(1);
        Ui.balance(panel, 0.4);
        return panel;
    }

    /**
     * Issues for the selected node's host/path, grouped by type into a tree.
     * Each type expands to its distinct locations (path + parameter); the same
     * location never appears twice, matching how the site map dedups.
     */
    private void refreshIssues() {
        if (issuesTreeModel == null) return;
        // type -> (locationKey -> issue), insertion-ordered and deduped by location.
        java.util.Map<String, java.util.LinkedHashMap<String, Issue>> grouped = new java.util.LinkedHashMap<>();
        // Which issues to show: everything when the root (a node with no service)
        // is selected or nothing is selected, otherwise the union of issues under
        // all the selected host/path nodes. Selecting all sites shows all issues.
        boolean showAll = selectedNodes == null || selectedNodes.isEmpty();
        if (!showAll) {
            for (SiteMap.Node n : selectedNodes) {
                if (n.service == null) { showAll = true; break; }
            }
        }
        java.util.List<Issue> list = new java.util.ArrayList<>();
        if (showAll) {
            list.addAll(ctx.issues());
        } else {
            for (Issue i : ctx.issues()) {
                for (SiteMap.Node n : selectedNodes) {
                    if (n.service == null) continue;
                    if (!i.host().equalsIgnoreCase(n.service.host())) continue;
                    String prefix = n.isHost ? "" : n.path;
                    if (!prefix.isEmpty() && !i.path().startsWith(prefix)) continue;
                    list.add(i);
                    break;
                }
            }
        }
        list.sort(java.util.Comparator.comparingInt(Issue::rank));
        for (Issue i : list) {
            String locKey = i.host() + "\u0000" + i.path() + "\u0000"
                    + (i.param() == null ? "" : i.param());
            grouped.computeIfAbsent(i.title(), k -> new java.util.LinkedHashMap<>())
                   .putIfAbsent(locKey, i);
        }
        DefaultMutableTreeNode root = (DefaultMutableTreeNode) issuesTreeModel.getRoot();
        root.removeAllChildren();
        for (var typeEntry : grouped.entrySet()) {
            java.util.Collection<Issue> locs = typeEntry.getValue().values();
            // The group's colour is its most severe location; because the list is
            // rank-sorted the first location is the most severe.
            Issue.Severity sev = locs.isEmpty() || locs.iterator().next().falsePositive()
                    ? Issue.Severity.INFORMATION : locs.iterator().next().severity();
            DefaultMutableTreeNode typeNode = new DefaultMutableTreeNode(
                    new IssueType(typeEntry.getKey(), locs.size(), sev));
            for (Issue i : locs) typeNode.add(new DefaultMutableTreeNode(i));
            root.add(typeNode);
        }
        // Remember what was selected so a newly arriving issue does not drag the
        // advisory away from whatever is being read.
        String previouslySelected = selectionKey(issuesTree.getSelectionPath());

        issuesTreeModel.reload();

        if (root.getChildCount() > 0) {
            TreePath restore = findByKey(root, previouslySelected);
            if (restore != null) {
                issuesTree.setSelectionPath(restore);
                issuesTree.scrollPathToVisible(restore);
            } else {
                // Select the first issue type so the advisory populates, but leave
                // it closed. The type node already shows everything the advisory
                // needs, so expanding it only to select a child is noise; the
                // locations are there when the tester wants them.
                DefaultMutableTreeNode type0 = (DefaultMutableTreeNode) root.getChildAt(0);
                issuesTree.setSelectionPath(new TreePath(type0.getPath()));
            }
        } else {
            issueAdvisory.setText("");
            issueReq.setMessage(null, new HttpMessage(new byte[0]));
            issueResp.setMessage(null, new HttpMessage(new byte[0]));
            if (pathToIssue != null) pathToIssue.setText("");
            if (issueLogModel != null) issueLogModel.show(null);
        }
    }

    /** Issue-type grouping node: title, a count of distinct locations, severity. */
    private record IssueType(String title, int count, Issue.Severity severity) {
        @Override public String toString() { return title + "  [" + count + "]"; }
    }

    /**
     * The issue a selected node should display.
     *
     * <p>Selecting a leaf shows that location. Selecting the type node shows its
     * first location rather than nothing, so clicking a finding's title is
     * enough to read it. Expanding to pick a specific location stays available
     * but is no longer required to see anything.
     */
    private static Issue issueFor(DefaultMutableTreeNode node) {
        if (node == null) return null;
        if (node.getUserObject() instanceof Issue i) return i;
        if (node.getUserObject() instanceof IssueType && node.getChildCount() > 0) {
            DefaultMutableTreeNode first = (DefaultMutableTreeNode) node.getChildAt(0);
            if (first.getUserObject() instanceof Issue i) return i;
        }
        return null;
    }

    /**
     * A stable identifier for a selected node, used to hold the selection
     * steady while the tree is rebuilt.
     */
    private static String selectionKey(TreePath path) {
        if (path == null) return null;
        Object last = path.getLastPathComponent();
        if (!(last instanceof DefaultMutableTreeNode tn)) return null;
        Object o = tn.getUserObject();
        if (o instanceof Issue i) return "issue\0" + i.dedupeKey();
        if (o instanceof IssueType t) return "type\0" + t.title();
        return null;
    }

    /** Find the rebuilt node matching a remembered selection, or null. */
    private static TreePath findByKey(DefaultMutableTreeNode root, String key) {
        if (key == null) return null;
        for (int t = 0; t < root.getChildCount(); t++) {
            DefaultMutableTreeNode typeNode = (DefaultMutableTreeNode) root.getChildAt(t);
            if (key.equals(selectionKey(new TreePath(typeNode.getPath())))) {
                return new TreePath(typeNode.getPath());
            }
            for (int c = 0; c < typeNode.getChildCount(); c++) {
                DefaultMutableTreeNode leaf = (DefaultMutableTreeNode) typeNode.getChildAt(c);
                if (key.equals(selectionKey(new TreePath(leaf.getPath())))) {
                    return new TreePath(leaf.getPath());
                }
            }
        }
        return null;
    }

    /** The findings a node of the issues tree stands for: itself, or every one under its type. */
    private static void collectIssues(DefaultMutableTreeNode tn, java.util.List<Issue> out) {
        if (tn.getUserObject() instanceof Issue i) { if (!out.contains(i)) out.add(i); return; }
        for (int c = 0; c < tn.getChildCount(); c++) collectIssues((DefaultMutableTreeNode) tn.getChildAt(c), out);
    }

    private void showIssue() {
        TreePath path = issuesTree.getSelectionPath();
        if (path == null) return;
        DefaultMutableTreeNode tn = (DefaultMutableTreeNode) path.getLastPathComponent();
        Issue i = issueFor(tn);
        if (i == null) return;
        issueAdvisory.setText(opensuite.ui.Advisory.render(i));
        issueAdvisory.setCaretPosition(0);
        issueReq.setMessage(i.service(),
                i.request() == null ? new HttpMessage(new byte[0]) : i.request().copy());
        issueResp.setMessage(i.service(),
                i.response() == null ? new HttpMessage(new byte[0]) : i.response().copy(), i.request());
        // Auto-highlight the evidence (the matched text) in the request and
        // response, so the relevant part is obvious.
        opensuite.ui.IssueMenu.markEvidence(i, issueReq, issueResp);
        if (pathToIssue != null) {
            pathToIssue.setText(i.request() == null
                    ? "No path available\n\nThis is a passively detected issue. No modified requests were "
                      + "sent to detect it, so there is no request chain to display."
                    : "The issue was detected in this request:\n\n" + i.request().startLine()
                      + "\n\nHost: " + (i.service() == null ? i.host() : i.service().url())
                      + (i.param() == null ? "" : "\nParameter: " + i.param()));
            pathToIssue.setCaretPosition(0);
        }
        if (issueLogModel != null) issueLogModel.show(i);
    }




    private JComponent buildScope() {
        // One section set 20px in from the page: help and gear in the gutter,
        // the heading, one sentence, then the editor.
        JButton gear = opensuite.ui.Glyphs.button(opensuite.ui.Glyphs.gear(21, Theme.TEXT), "Scope settings", null);
        gear.setBorder(null);
        gear.addActionListener(e -> {
            JPopupMenu m = new JPopupMenu();
            JMenuItem clear = new JMenuItem("Restore defaults");
            clear.setFont(Ui.PLAIN);
            clear.addActionListener(a -> { ctx.scope().include().clear(); ctx.scope().exclude().clear(); ctx.scopeChanged(); });
            m.add(clear);
            m.show(gear, 0, gear.getHeight());
        });
        JPanel section = opensuite.ui.Sections.section("Target scope",
                "Use these settings to define exactly what hosts and URLs constitute the target for your current "
              + "work. This configuration affects the behaviour of tools throughout the suite.",
                gear, null, new ScopeEditor(ctx, ctx.scope()));
        section.setBorder(Ui.pad(28, 20, 20, 20));
        return opensuite.ui.Sections.page(section);
    }

    /** Insert only newly-discovered nodes, preserving expansion and selection. */
    private void syncTree() {
        if (treeModel == null || tree == null) return;
        sync(siteMap.root());
        // With an invisible root, its children (hosts) only show once the root
        // path is expanded; expand it whenever new hosts appear.
        javax.swing.tree.TreeNode rootTn = (javax.swing.tree.TreeNode) treeModel.getRoot();
        tree.expandPath(new TreePath(rootTn));
        // Auto-select the first host so the panes populate when the tab is first viewed.
        if (tree.getSelectionPath() == null && tree.getRowCount() > 0) {
            tree.setSelectionRow(0);
        }
        refreshSelectedItems();
    }

    private void sync(SiteMap.Node sm) {
        DefaultMutableTreeNode tn = treeNodes.get(sm);
        if (tn == null) return;
        for (SiteMap.Node child : sm.children.values()) {
            DefaultMutableTreeNode childTn = treeNodes.get(child);
            boolean visible = nodeVisible(child);
            if (childTn == null) {
                if (!visible) continue;
                childTn = new DefaultMutableTreeNode(child);
                treeNodes.put(child, childTn);
                treeModel.insertNodeInto(childTn, tn, tn.getChildCount());
            } else if (!visible) {
                // A new exchange can take a node out of view (a folder that is
                // now all not-found items, say); a later one can bring it back.
                treeModel.removeNodeFromParent(childTn);
                removeTreeNodes(child);
                continue;
            }
            sync(child);
        }
    }

    private void removeTreeNodes(SiteMap.Node n) {
        treeNodes.remove(n);
        for (SiteMap.Node c : n.children.values()) removeTreeNodes(c);
    }

    /**
     * The site map filter bar: a clickable summary that opens the full filter
     * and full-text search, plus a quick URL search, matching the proxy history.
     */
    private JComponent buildItemsFilterBar() {
        itemsFilterButton = Ui.filterButton();
        itemsFilterButton.setText("Site map filter: " + itemsFilter.summary());
        itemsFilterButton.addActionListener(e -> {
            java.awt.Window owner = SwingUtilities.getWindowAncestor(itemsTable);
            new opensuite.proxy.FilterDialog(owner, "Site map filter",
                    itemsFilter, true, TargetTool.this::applyItemsFilter).setVisible(true);
        });
        JButton help = Ui.helpButton("Site map",
                "The site map records every host, folder and request observed by the suite.\n"
                + "The filter above determines which items are shown in the tree and the contents table.");
        help.setIcon(opensuite.ui.Glyphs.help(21, Theme.TEXT));
        help.setBorder(null);
        help.setVerticalAlignment(SwingConstants.TOP);
        JPanel bar = new JPanel(new BorderLayout(10, 0));
        bar.setOpaque(false);
        itemsFilterButton.setPreferredSize(new Dimension(itemsFilterButton.getPreferredSize().width, Ui.tall(22)));
        bar.add(itemsFilterButton, BorderLayout.CENTER);
        bar.add(help, BorderLayout.EAST);
        // 10px under the bar, then the hairline that closes the page's head.
        bar.setBorder(BorderFactory.createCompoundBorder(
                BorderFactory.createMatteBorder(0, 0, 1, 0, Theme.BORDER), Ui.pad(5, 10, 10, 12)));
        return bar;
    }

    private void applyItemsFilter() {
        if (itemsModel == null) return;
        itemsModel.setFilter(itemsFilter::test);
        if (itemsFilterButton != null) itemsFilterButton.setText("Site map filter: " + itemsFilter.summary());
        rebuildTree();
    }

    /** The filter travels with the project. */
    @Override public java.io.Serializable saveState() { return itemsFilter.copy(); }

    @Override public void restoreState(java.io.Serializable state) {
        if (!(state instanceof opensuite.proxy.HistoryFilter f)) return;
        f.scope = ctx.scope();
        itemsFilter.copyFrom(f);
        SwingUtilities.invokeLater(this::applyItemsFilter);
    }

    /** Refresh the items table for the selected node without stealing selection. */
    private void refreshSelectedItems() {
        if (tree == null || itemsModel == null) return;
        if (selectedNodes == null || selectedNodes.isEmpty()) return;
        int sel = itemsTable.getSelectedRow();
        itemsModel.setEntries(unionEntries(selectedNodes));
        if (sel >= 0 && sel < itemsModel.getRowCount()) {
            itemsTable.setRowSelectionInterval(sel, sel);
        }
    }

    private void showTreeSelection() {
        TreePath[] paths = tree.getSelectionPaths();
        selectedNodes = new java.util.ArrayList<>();
        if (paths != null) {
            for (TreePath p : paths) {
                DefaultMutableTreeNode tn = (DefaultMutableTreeNode) p.getLastPathComponent();
                if (tn.getUserObject() instanceof SiteMap.Node node) selectedNodes.add(node);
            }
        }
        selectedNode = selectedNodes.isEmpty() ? null : selectedNodes.get(selectedNodes.size() - 1);
        itemsModel.setEntries(unionEntries(selectedNodes));
        if (itemsModel.getRowCount() > 0) itemsTable.setRowSelectionInterval(0, 0);
        refreshIssues();
    }

    /** Deduplicated union of the request entries under all the given nodes. */
    private java.util.List<LogEntry> unionEntries(java.util.List<SiteMap.Node> nodes) {
        java.util.LinkedHashMap<String, LogEntry> union = new java.util.LinkedHashMap<>();
        for (SiteMap.Node n : nodes) {
            for (LogEntry e : n.entries()) {
                if (e.service() == null || e.request() == null) continue;
                String k = e.service().url() + "|" + e.request().method() + " " + e.pathAndQuery();
                union.putIfAbsent(k, e);
            }
        }
        return new java.util.ArrayList<>(union.values());
    }

    private void showItem() {
        int row = itemsTable.getSelectedRow();
        pair.show(row < 0 ? null : itemsModel.at(row));
    }

    private void installTreeMenu() {
        tree.addMouseListener(new java.awt.event.MouseAdapter() {
            @Override public void mousePressed(java.awt.event.MouseEvent e)  { maybe(e); }
            @Override public void mouseReleased(java.awt.event.MouseEvent e) { maybe(e); }
            private void maybe(java.awt.event.MouseEvent e) {
                if (!e.isPopupTrigger()) return;
                TreePath p = tree.getPathForLocation(e.getX(), e.getY());
                if (p == null) return;
                // A right-click inside a selection of several keeps it: the menu then acts on all of them.
                if (!tree.isPathSelected(p)) tree.setSelectionPath(p);
                DefaultMutableTreeNode tn = (DefaultMutableTreeNode) p.getLastPathComponent();
                SiteMap.Node node = (SiteMap.Node) tn.getUserObject();
                java.util.List<SiteMap.Node> chosen = new ArrayList<>();
                TreePath[] sel = tree.getSelectionPaths();
                if (sel != null) for (TreePath sp : sel) {
                    Object o = ((DefaultMutableTreeNode) sp.getLastPathComponent()).getUserObject();
                    if (o instanceof SiteMap.Node n && n.service != null) chosen.add(n);
                }
                (chosen.size() > 1 ? buildManyMenu(chosen) : buildNodeMenu(node)).show(tree, e.getX(), e.getY());
            }
        });
    }

    /** The menu for several hosts, folders or items chosen together: each action covers all of them. */
    private JPopupMenu buildManyMenu(java.util.List<SiteMap.Node> nodes) {
        JPopupMenu menu = new JPopupMenu();
        JMenuItem t = new JMenuItem(nodes.size() + " items selected");
        t.setEnabled(false);
        menu.add(t);
        menu.addSeparator();
        addItem(menu, "Add to scope", () -> {
            for (SiteMap.Node n : nodes) ctx.scope().includeUrl(n.service, n.path, n.isHost);
            ctx.scopeChanged();
        });
        addItem(menu, "Remove from scope", () -> {
            for (SiteMap.Node n : nodes) ctx.scope().removeUrl(n.service, n.path, n.isHost);
            ctx.scopeChanged();
        });
        menu.addSeparator();
        java.util.function.Predicate<Issue> under = i -> {
            for (SiteMap.Node n : nodes) {
                if (!i.host().equalsIgnoreCase(n.service.host())) continue;
                if (n.isHost || i.path().startsWith(n.path)) return true;
            }
            return false;
        };
        addItem(menu, "Report issues", () -> {
            java.util.List<Issue> found = new java.util.ArrayList<>();
            for (Issue i : ctx.issues()) if (under.test(i)) found.add(i);
            opensuite.report.Export.reportDialog(ctx.frame(), found, "opensuite-report");
        });
        addItem(menu, "Delete issues", () -> ctx.removeIssuesWhere(under));
        menu.addSeparator();
        final java.util.List<LogEntry> ents = new java.util.ArrayList<>(), requested = new java.util.ArrayList<>();
        for (SiteMap.Node n : nodes) for (LogEntry e : n.entries()) if (!ents.contains(e)) {
            ents.add(e);
            if (!siteMap.isLinked(e) && e.request() != null) requested.add(e);
        }
        if (ctx.canScan()) {
            addItem(menu, "Passively scan selected items", () -> sendToScanner(requested, "passive")).setEnabled(!requested.isEmpty());
            addItem(menu, "Actively scan selected items", () -> sendToScanner(requested, null)).setEnabled(!requested.isEmpty());
            menu.addSeparator();
        }
        addItem(menu, "Delete selected items", () -> {
            boolean any = false;
            for (SiteMap.Node n : nodes) {
                java.util.List<LogEntry> gone = n.entries();
                if (n.entry != null) gone.add(n.entry);
                if (siteMap.remove(n)) { any = true; forget(gone); }
            }
            if (any) rebuildTree();
        });
        addItem(menu, "Copy URLs in selected items", () -> {
            StringBuilder sb = new StringBuilder();
            for (LogEntry e : ents) sb.append(e.url()).append('\n');
            opensuite.ui.MessageActions.clip(sb.toString().trim());
        });
        addItem(menu, "Save selected items", () -> opensuite.report.Export.saveItemsDialog(ctx.frame(), requested)).setEnabled(!requested.isEmpty());
        return menu;
    }

    private JPopupMenu buildNodeMenu(SiteMap.Node node) {
        JPopupMenu menu = new JPopupMenu();
        // The heading is the address in bold behind the host's padlock, as in the reference.
        String address = node.isHost ? node.service.url() + "/"
                : node.entry != null && node.children.isEmpty() ? node.entry.url() : node.path;
        JLabel t = new JLabel(Ui.truncate(address, 60));
        t.setFont(Ui.BOLD);
        t.setForeground(Theme.TAB_TEXT_ON);
        if (node.service != null) t.setIcon(SiteIcons.host(node.service.secure(), false));
        t.setIconTextGap(Ui.em(8));
        t.setBorder(Ui.pad(5, 10, 5, 14));
        menu.add(t);
        menu.addSeparator();
        // One item that reads as the opposite of the node's state, as in the
        // reference: a node already in scope offers to leave it.
        boolean inScope = node.service != null
                && ctx.scope().isInScope(node.service, node.isHost ? "/" : node.path);
        if (inScope) {
            addItem(menu, "Remove from scope", () -> {
                ctx.scope().removeUrl(node.service, node.path, node.isHost);
                ctx.scopeChanged();
            });
        } else {
            addItem(menu, "Add to scope", () -> {
                ctx.scope().includeUrl(node.service, node.path, node.isHost);
                ctx.scopeChanged();
            });
        }
        menu.addSeparator();
        final String word = node.isHost ? "host" : "branch";
        final String url = node.service == null ? null
                : node.isHost ? node.service.url() : node.service.url() + node.path;
        // What was really requested at or under this node: only that is ever sent to a scan.
        final java.util.List<LogEntry> ents = node.entries();
        final java.util.List<LogEntry> requested = new java.util.ArrayList<>();
        for (LogEntry e : ents) if (!siteMap.isLinked(e) && e.request() != null) requested.add(e);
        final LogEntry le = node.entry;
        final boolean single = le != null && node.children.isEmpty();

        addItem(menu, "Expand branch", () -> expandBranch(node));
        addItem(menu, "Expand requested items", () -> expandRequested(node));
        menu.addSeparator();

        if (node.service != null) {
            final String host = node.service.host();
            addItem(menu, "Report issues", () -> {
                java.util.List<Issue> hostIssues = new java.util.ArrayList<>();
                for (Issue i : ctx.issues()) if (i.host().equalsIgnoreCase(host)) hostIssues.add(i);
                opensuite.report.Export.reportDialog(ctx.frame(), hostIssues, "opensuite-report-" + host);
            });
            addItem(menu, "Delete issues", () -> ctx.removeIssuesWhere(i -> i.host().equalsIgnoreCase(host)));
            menu.addSeparator();
        }

        // Scan opens the scan window on this address; the two beneath it work on what is already in the map.
        if (url != null && ctx.canScan()) {
            addItem(menu, "Scan", () -> ctx.openScan(url));
            JMenuItem passive = addItem(menu, single ? "Passively scan this item" : "Passively scan this " + word,
                    () -> sendToScanner(requested, "passive"));
            JMenuItem active = addItem(menu, single ? "Actively scan this item" : "Actively scan this " + word,
                    () -> sendToScanner(requested, null));
            passive.setEnabled(!requested.isEmpty());
            active.setEnabled(!requested.isEmpty());
            menu.addSeparator();
        }

        if (single) {
            // One request: the send-to tools, as the reference lists them for an item.
            for (String tool : ctx.sinkNames()) {
                if (opensuite.ui.Engagement.isEngagement(tool) || "scanner".equals(tool)) continue;
                final String to = tool; final LogEntry e = le;
                addItem(menu, "Send to " + Ui.sentence(to), () -> ctx.sendTo(to, e.service(),
                        e.request() == null ? null : e.request().copy(),
                        e.response() == null ? null : e.response().copy(), null));
            }
            if (le.response() != null) {
                addItem(menu, "Show response in browser", () -> opensuite.ui.MessageActions.openResponseInBrowser(
                        ctx.frame(), ctx, le.service(), le.request(), le.response()));
            }
            if (le.request() != null) {
                addItem(menu, "Request in browser",
                        () -> opensuite.ui.MessageActions.openRequestInBrowser(ctx.frame(), le.service(), le.request()));
            }
            addItem(menu, "Record an issue", () -> opensuite.ui.ManualIssue.record(ctx.frame(), ctx,
                    le.service(), le.request(), le.response()));
        }
        LogEntry rep = le != null ? le : ents.isEmpty() ? null : ents.get(0);
        addEngagementSubmenu(menu, rep, single);
        menu.addSeparator();

        addItem(menu, "Delete " + (single ? "item" : word), () -> deleteNode(node));
        if (single) {
            addItem(menu, "Copy URL", () -> opensuite.ui.MessageActions.clip(le.url()));
            if (le.request() != null) {
                addItem(menu, "Copy as curl command (bash)",
                        () -> opensuite.ui.MessageActions.clip(opensuite.ui.MessageActions.curl(le.service(), le.request())));
            }
            JMenuItem links = addItem(menu, "Copy links",
                    () -> opensuite.ui.MessageActions.clip(opensuite.ui.MessageActions.linksIn(le.response(), le.url())));
            links.setEnabled(le.response() != null);
            addItem(menu, "Save item", () -> opensuite.report.Export.saveItemsDialog(ctx.frame(), java.util.List.of(le)));
        } else {
            JMenuItem urls = addItem(menu, "Copy URLs in this " + word, () -> {
                StringBuilder sb = new StringBuilder();
                for (LogEntry e : ents) sb.append(e.url()).append('\n');
                opensuite.ui.MessageActions.clip(sb.toString().trim());
            });
            JMenuItem links = addItem(menu, "Copy links in this " + word, () -> {
                java.util.LinkedHashSet<String> found = new java.util.LinkedHashSet<>();
                for (LogEntry e : ents) if (e.response() != null) {
                    String t2 = opensuite.ui.MessageActions.linksIn(e.response(), e.url());
                    if (!t2.isEmpty()) java.util.Collections.addAll(found, t2.split("\n"));
                }
                opensuite.ui.MessageActions.clip(String.join("\n", found));
            });
            JMenuItem save = addItem(menu, "Save items", () -> opensuite.report.Export.saveItemsDialog(ctx.frame(), requested));
            urls.setEnabled(!ents.isEmpty());
            links.setEnabled(!requested.isEmpty());
            save.setEnabled(!requested.isEmpty());
        }
        menu.addSeparator();

        addItem(menu, "Compare site maps", () -> CompareSiteMaps.open(ctx, siteMap));
        menu.addSeparator();

        // View: how the request and response below the table are laid out.
        JMenu view = new JMenu("View");
        view.setFont(Ui.PLAIN);
        String[] modes = {"Left/right split", "Top/bottom split", "Tabs"};
        for (int i = 0; i < modes.length; i++) {
            final int mode = i;
            JMenuItem mi = new JMenuItem(modes[i]);
            mi.setFont(Ui.PLAIN);
            mi.addActionListener(e -> { if (pair != null) pair.setMode(mode); });
            view.add(mi);
        }
        menu.add(view);
        addItem(menu, "Show new site map window", this::newWindow);
        menu.addSeparator();
        addItem(menu, "Site map documentation", () -> opensuite.ui.AboutDialog.open(opensuite.ui.Unbuilt.PROJECT_URL + "#readme"));
        return menu;
    }

    /** The deepest node that stands for exactly this item. */
    private static SiteMap.Node nodeOf(SiteMap.Node from, LogEntry le) {
        for (SiteMap.Node c : from.children.values()) {
            SiteMap.Node deeper = nodeOf(c, le);
            if (deeper != null) return deeper;
            if (c.entry == le) return c;
        }
        return null;
    }

    /** Hand what was requested under a node to the scanner as one task: looked at only ({@code "passive"}) or audited. */
    private void sendToScanner(java.util.List<LogEntry> requested, String how) {
        for (LogEntry e : requested) ctx.sendTo("scanner", e.service(), e.request().copy(), null, how);
    }

    /** Take a host, branch or item out of the site map. The proxy history keeps its record. */
    private void deleteNode(SiteMap.Node node) {
        java.util.List<LogEntry> gone = node.entries();
        if (node.entry != null) gone.add(node.entry);
        if (!siteMap.remove(node)) return;
        forget(gone);
        rebuildTree();
    }

    /** Mark deleted items so they stay out of the map when the project is opened again. */
    private void forget(java.util.List<LogEntry> gone) {
        for (LogEntry e : gone) {
            if (e.offSiteMap()) continue;
            e.setOffSiteMap(true);
            if (!"link".equals(e.tool())) ctx.store().updated(e);
        }
    }

    /** Open the branch only as far as there is something that was requested. */
    private void expandRequested(SiteMap.Node node) {
        DefaultMutableTreeNode tn = treeNodes.get(node);
        if (tn != null) expandRequested(new TreePath(tn.getPath()));
    }

    private boolean expandRequested(TreePath path) {
        DefaultMutableTreeNode tn = (DefaultMutableTreeNode) path.getLastPathComponent();
        SiteMap.Node n = (SiteMap.Node) tn.getUserObject();
        boolean any = n.entry != null && !siteMap.isLinked(n.entry);
        boolean under = false;
        for (int i = 0; i < tn.getChildCount(); i++) under |= expandRequested(path.pathByAddingChild(tn.getChildAt(i)));
        if (under) tree.expandPath(path);
        return any || under;
    }

    /** A second site map in its own window, kept up to date like the first and filtered on its own. */
    private void newWindow() {
        TargetTool other = new TargetTool();
        other.secondary = true;
        other.init(ctx);
        JFrame f = new JFrame("Site map");
        f.setIconImages(opensuite.ui.AppIcon.images());
        f.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
        f.getContentPane().add(other.buildSiteMap());
        other.reloadSiteMap(ctx.store().all());
        f.setSize(1100, 700);
        f.setLocationRelativeTo(ctx.frame());
        f.setVisible(true);
    }

    /** True for a site map shown in its own window: it mirrors the first and reports nothing of its own. */
    private boolean secondary;

    /** Expand the whole subtree under the node the context menu was raised on. */
    private void expandBranch(SiteMap.Node node) {
        javax.swing.tree.TreePath sel = tree.getSelectionPath();
        if (sel != null) expandAll(sel);
    }

    private void expandAll(javax.swing.tree.TreePath path) {
        javax.swing.tree.TreeNode n = (javax.swing.tree.TreeNode) path.getLastPathComponent();
        for (int i = 0; i < n.getChildCount(); i++) {
            expandAll(path.pathByAddingChild(n.getChildAt(i)));
        }
        tree.expandPath(path);
    }

    /**
     * The engagement-tools submenu. {@code includeRequestTools} false drops the
     * tools that need a single specific request (a CSRF PoC), leaving the ones
     * that work from a path (content discovery), for a host or folder node.
     */
    private void addEngagementSubmenu(JPopupMenu menu, LogEntry le, boolean includeRequestTools) {
        if (le == null || le.request() == null) return;
        java.util.List<String> eng = new java.util.ArrayList<>();
        for (String tool : ctx.sinkNames()) {
            if (!opensuite.ui.Engagement.isEngagement(tool)) continue;
            if (!includeRequestTools && opensuite.ui.Engagement.needsRequest(tool)) continue;
            eng.add(tool);
        }
        if (eng.isEmpty()) return;
        JMenu sub = new JMenu("Engagement tools");
        sub.setFont(Ui.PLAIN);
        for (String tool : eng) {
            final String to = tool; final LogEntry e = le;
            JMenuItem mi = new JMenuItem(opensuite.ui.Engagement.label(to));
            mi.setFont(Ui.PLAIN);
            mi.addActionListener(ev -> ctx.sendTo(to, e.service(),
                    e.request() == null ? null : e.request().copy(),
                    e.response() == null ? null : e.response().copy(), null));
            sub.add(mi);
        }
        menu.add(sub);
    }

    private JMenuItem addItem(JPopupMenu menu, String label, Runnable r) {
        JMenuItem mi = new JMenuItem(Ui.sentence(label));
        mi.setFont(Ui.PLAIN);
        mi.addActionListener(e -> r.run());
        menu.add(mi);
        return mi;
    }

    private static class ItemsModel extends AbstractTableModel {
        private final String[] cols = {"Host", "Method", "URL", "Params", "Status code", "Length", "MIME type", "Title",
                "Notes", "Time requested"};
        private final java.text.SimpleDateFormat stamp = new java.text.SimpleDateFormat("HH:mm:ss d MMM yyyy");
        private List<LogEntry> all = new ArrayList<>();
        private List<LogEntry> entries = new ArrayList<>();
        private java.util.function.Predicate<LogEntry> filter = e -> true;

        void setEntries(List<LogEntry> e) { this.all = new ArrayList<>(e); reapply(); }

        void setFilter(java.util.function.Predicate<LogEntry> f) {
            this.filter = f == null ? e -> true : f;
            reapply();
        }

        private void reapply() {
            entries = new ArrayList<>();
            for (LogEntry e : all) if (filter.test(e)) entries.add(e);
            fireTableDataChanged();
        }

        LogEntry at(int r) { return (r >= 0 && r < entries.size()) ? entries.get(r) : null; }

        @Override public int getRowCount() { return entries.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 == 3 ? Boolean.class : String.class; }

        @Override public Object getValueAt(int r, int c) {
            LogEntry e = entries.get(r);
            return switch (c) {
                case 0 -> e.service().url();
                case 1 -> e.request() == null || "link".equals(e.tool()) ? "" : e.request().method();
                case 2 -> e.pathAndQuery();
                case 3 -> e.request() != null && e.request().hasParameters();
                case 4 -> e.status() == 0 ? "" : String.valueOf(e.status());
                case 5 -> e.responseLen() == 0 ? "" : String.valueOf(e.responseLen());
                case 6 -> e.mimeType();
                case 7 -> e.title();
                case 8 -> e.notes() == null ? "" : e.notes();
                default -> e.time() == null || "link".equals(e.tool()) ? "" : stamp.format(e.time());
            };
        }
    }
}